Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions netlify/database/migrations/0003_drop_prize_award_source.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
DROP INDEX IF EXISTS prize_awards_passport_completion_per_kid_idx;

ALTER TABLE prize_awards
DROP COLUMN IF EXISTS source;
52 changes: 28 additions & 24 deletions server/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import type {
PassportActivity,
Prize,
PrizeAward,
PrizeAwardSource,
PrizeKind,
StoreData,
UserRole,
Expand Down Expand Up @@ -74,6 +73,7 @@ const kidGenders = new Set(['boy', 'girl', 'preferNotToSay']);
const prizeKinds = new Set<PrizeKind>(['final', 'normal', 'valuable']);
const staffRoles = new Set<UserRole>(['desk', 'lead', 'wheel']);
const supportedLocales = new Set(['en', 'es']);
const normalPrizeKinds = new Set<PrizeKind>(['normal', 'valuable']);

export function normalizeApiPath(pathname: string) {
if (pathname.startsWith('/.netlify/functions/api/')) {
Expand Down Expand Up @@ -362,8 +362,13 @@ function getPassportWheelShotSummary(snapshot: StoreData, kidId: string) {
Math.max(passportActivities.length - 1, 0),
);
const earnedShots = Math.floor(spinEligibleActivities / 4);
const finalPrizeIds = new Set(
snapshot.prizes
.filter((prize) => prize.kind === 'final')
.map((prize) => prize.id),
);
const usedShots = snapshot.prizeAwards.filter(
(award) => award.kidId === kidId && award.source === 'wheel',
(award) => award.kidId === kidId && !finalPrizeIds.has(award.prizeId),
).length;

return {
Expand Down Expand Up @@ -544,14 +549,11 @@ function normalizeBackupPrizes(value: unknown): Prize[] {
function normalizeBackupPrizeAwards(value: unknown): PrizeAward[] {
return asArray(value, 'prizesWon').map((entry, index) => {
const award = asObject(entry, `prizesWon.${index}`);
const source = normalizeAwardSource(award.source);

return {
awardedAt: asString(award.awardedAt, `prizesWon.${index}.awardedAt`),
id: asString(award.id, `prizesWon.${index}.id`),
kidId: asString(award.kidId, `prizesWon.${index}.kidId`),
prizeId: asString(award.prizeId, `prizesWon.${index}.prizeId`),
...(source ? { source } : {}),
};
});
}
Expand Down Expand Up @@ -861,7 +863,7 @@ async function handleWheelPrizes(
const stock = url.searchParams.get('stock')?.trim();

if (!stock) {
if (typeof body.title !== 'string' || !body.title.trim()) {
if (typeof body.title !== 'string') {
throw new HttpError(400, 'title is required when stock is omitted');
}

Expand Down Expand Up @@ -892,8 +894,15 @@ async function handleWheelPrizes(

const title = body.title === undefined ? prize.title : String(body.title).trim();

if (!title) {
throw new HttpError(400, 'title cannot be empty');
if (!title && prize.given === 0) {
return jsonResponse(
request,
200,
await savePrize({
prizeId: stock,
type: 'deleteIfUnawarded',
}),
);
}

try {
Expand All @@ -917,18 +926,6 @@ async function handleWheelPrizes(
throw error;
}
}
function normalizeAwardSource(value: unknown) {
if (value === undefined || value === null || value === '') {
return undefined;
}

if (value !== 'passportCompletion' && value !== 'wheel') {
throw new HttpError(400, 'source must be passportCompletion or wheel');
}

return value as PrizeAwardSource;
}

async function handlePrizesKid(
request: ApiRequest,
url: URL,
Expand All @@ -951,7 +948,6 @@ async function handlePrizesKid(

await requireMagicLink(request, url, ['wheel']);

const body = parseJsonBody(request.body);
const stock = url.searchParams.get('stock')?.trim();

if (!stock) {
Expand All @@ -960,15 +956,23 @@ async function handlePrizesKid(

const snapshot = await readSnapshot();
const kidId = normalizeKidId(url.searchParams.get('kid'), snapshot);
const source = normalizeAwardSource(body.source);
const prize = snapshot.prizes.find((entry) => entry.id === stock);
const awardKind = prize?.kind === 'final' ? 'passport-complete' : 'wheel';

if (prize && normalPrizeKinds.has(prize.kind)) {
const shotSummary = getPassportWheelShotSummary(snapshot, kidId);

if (shotSummary.availableShots <= 0) {
throw new HttpError(409, `Kid has no wheel shots available: ${kidId}`);
}
}

try {
const response = await awardPrize({
awardId: `${kidId}-${source === 'passportCompletion' ? 'passport-complete' : 'wheel'}-${randomUUID()}`,
awardId: `${kidId}-${awardKind}-${randomUUID()}`,
awardedAt: new Date().toISOString(),
kidId,
prizeId: stock,
...(source ? { source } : {}),
});

return jsonResponse(request, 200, response);
Expand Down
31 changes: 31 additions & 0 deletions server/db-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,33 @@ function splitSqlStatements(sqlText: string) {
.filter(Boolean);
}

function isLegacyPrizeAwardSourceIndex(statement: string) {
return statement.includes('prize_awards_passport_completion_per_kid_idx') &&
statement.includes('WHERE source');
}

async function hasPrizeAwardSourceColumn(sql: SqlClient) {
const rows = (await sql`
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name = 'prize_awards'
AND column_name = 'source'
) AS has_source
`) as Array<{ has_source: boolean }>;

return rows[0]?.has_source === true;
}

async function shouldApplySchemaStatement(sql: SqlClient, statement: string) {
if (!isLegacyPrizeAwardSourceIndex(statement)) {
return true;
}

return hasPrizeAwardSourceColumn(sql);
}

export async function applyDbSchema(sql: SqlClient = createSqlClient()) {
const migrationFiles = (await readdir(migrationsDir))
.filter((fileName) => fileName.endsWith('.sql'))
Expand All @@ -61,6 +88,10 @@ export async function applyDbSchema(sql: SqlClient = createSqlClient()) {
const sqlText = await readFile(path.join(migrationsDir, migrationFile), 'utf8');

for (const statement of splitSqlStatements(sqlText)) {
if (!(await shouldApplySchemaStatement(sql, statement))) {
continue;
}

await sql.query(statement);
}
}
Expand Down
40 changes: 25 additions & 15 deletions server/db-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,11 @@ function mapPrize(row: Row): Prize {
}

function mapPrizeAward(row: Row): PrizeAward {
const source = asOptionalString(row.source, 'prize_awards.source');

return {
awardedAt: asString(row.awarded_at, 'prize_awards.awarded_at'),
id: asString(row.id, 'prize_awards.id'),
kidId: asString(row.kid_id, 'prize_awards.kid_id'),
prizeId: asString(row.prize_id, 'prize_awards.prize_id'),
...(source ? { source: source as PrizeAward['source'] } : {}),
};
}

Expand Down Expand Up @@ -292,12 +289,11 @@ function prizeAwardQueries(tx: TransactionSql, prizeAwards: PrizeAward[]) {
tx`DELETE FROM prize_awards`,
...prizeAwards.map(
(award) => tx`
INSERT INTO prize_awards (id, kid_id, prize_id, source, awarded_at)
INSERT INTO prize_awards (id, kid_id, prize_id, awarded_at)
VALUES (
${award.id},
${award.kidId},
${award.prizeId},
${award.source ?? null},
${award.awardedAt}::timestamptz
)
ON CONFLICT DO NOTHING
Expand Down Expand Up @@ -352,10 +348,10 @@ export function createDbStore(sql: SqlClient = createSqlClient()): StoreAdapter
FROM prizes p
LEFT JOIN prize_awards a ON a.prize_id = p.id
GROUP BY p.id, p.title, p.kind, p.initial_units
ORDER BY p.id
ORDER BY p.created_at, p.id
`,
sql`
SELECT id, kid_id, prize_id, source, awarded_at::text AS awarded_at
SELECT id, kid_id, prize_id, awarded_at::text AS awarded_at
FROM prize_awards
ORDER BY awarded_at, id
`,
Expand Down Expand Up @@ -491,6 +487,21 @@ export function createDbStore(sql: SqlClient = createSqlClient()): StoreAdapter
throw new Error('Unable to allocate a fresh prize id');
}

if (command.type === 'deleteIfUnawarded') {
await sql`
DELETE FROM prizes
WHERE id = ${command.prizeId}
AND NOT EXISTS (
SELECT 1
FROM prize_awards
WHERE prize_awards.prize_id = prizes.id
)
`;

const snapshot = await readSnapshot();
return prizeResponse(snapshot);
}

const rows = (await sql`
UPDATE prizes
SET title = COALESCE(${command.title ?? null}, title),
Expand Down Expand Up @@ -519,28 +530,27 @@ export function createDbStore(sql: SqlClient = createSqlClient()): StoreAdapter
}

async function awardPrize(command: AwardPrizeCommand) {
const source = command.source ?? null;
const rows = (await sql`
WITH locked_prize AS (
SELECT id, initial_units
SELECT id, kind, initial_units
FROM prizes
WHERE id = ${command.prizeId}
FOR UPDATE
),
existing_passport_completion AS (
SELECT 1
FROM prize_awards
WHERE ${source} = 'passportCompletion'
AND kid_id = ${command.kidId}
AND source = 'passportCompletion'
FROM locked_prize, prize_awards existing_award
JOIN prizes awarded_prize ON awarded_prize.id = existing_award.prize_id
WHERE locked_prize.kind = 'final'
AND existing_award.kid_id = ${command.kidId}
AND awarded_prize.kind = 'final'
),
inserted AS (
INSERT INTO prize_awards (id, kid_id, prize_id, source, awarded_at)
INSERT INTO prize_awards (id, kid_id, prize_id, awarded_at)
SELECT
${command.awardId},
${command.kidId},
locked_prize.id,
${source},
${command.awardedAt}::timestamptz
FROM locked_prize
WHERE NOT EXISTS (SELECT 1 FROM existing_passport_completion)
Expand Down
5 changes: 4 additions & 1 deletion server/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export type SavePrizeCommand =
prizeKind?: Prize['kind'];
title?: string;
type: 'update';
}
| {
prizeId: string;
type: 'deleteIfUnawarded';
};

export type PrizeMutationResult = {
Expand All @@ -41,7 +45,6 @@ export type AwardPrizeCommand = {
awardedAt: string;
kidId: string;
prizeId: string;
source?: PrizeAward['source'];
};

export type WritableStoreData = Pick<
Expand Down
3 changes: 0 additions & 3 deletions server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,11 @@ export type Prize = {
title: string;
};

export type PrizeAwardSource = 'passportCompletion' | 'wheel';

export type PrizeAward = {
awardedAt: string;
id: string;
kidId: string;
prizeId: string;
source?: PrizeAwardSource;
};

export type UserRole = 'desk' | 'lead' | 'wheel';
Expand Down
Loading
Loading