|
| 1 | +import { and, count, eq, inArray, isNull } from 'drizzle-orm'; |
| 2 | +import * as schema from '../db/schema'; |
| 3 | +import type { DbInstance } from '../db'; |
| 4 | + |
| 5 | +/** YYYYMMDD integer bucket in the restaurant timezone. */ |
| 6 | +export function currentOrderDay(now = new Date(), timeZone = 'UTC'): number { |
| 7 | + const parts = new Intl.DateTimeFormat('en-US', { |
| 8 | + timeZone, |
| 9 | + year: 'numeric', |
| 10 | + month: '2-digit', |
| 11 | + day: '2-digit', |
| 12 | + }).formatToParts(now); |
| 13 | + const value = (type: string) => Number(parts.find((part) => part.type === type)!.value); |
| 14 | + return value('year') * 10000 + value('month') * 100 + value('day'); |
| 15 | +} |
| 16 | + |
| 17 | +/** Intents expire 30 minutes after creation (#19). */ |
| 18 | +export const INTENT_TTL_MS = 30 * 60_000; |
| 19 | + |
| 20 | +const MAX_NUMBERING_RETRIES = 3; |
| 21 | + |
| 22 | +export type CreateOrderResult = |
| 23 | + | { ok: true; orderId: string; dailyNumber: number } |
| 24 | + | { error: 'stale_items'; staleEntryIds: string[] } |
| 25 | + | { error: 'invalid_table_session' } |
| 26 | + | { error: 'check_open' }; |
| 27 | + |
| 28 | +/** Shared order creation path for diner, staff, and admin submits. */ |
| 29 | +export async function createOrder( |
| 30 | + db: DbInstance, |
| 31 | + idempotencyKey: string, |
| 32 | + rawLines: { entryId: string; quantity: number }[], |
| 33 | + tableSessionId?: string | null, |
| 34 | + actor: 'diner' | 'staff' | 'admin' = tableSessionId ? 'staff' : 'diner', |
| 35 | + actorName?: string | null, |
| 36 | + orderTimeZone = 'UTC', |
| 37 | +): Promise<CreateOrderResult> { |
| 38 | + const existing = await findByIdempotencyKey(db, idempotencyKey); |
| 39 | + if (existing) return existing; |
| 40 | + |
| 41 | + if (tableSessionId != null) { |
| 42 | + const [session] = await db |
| 43 | + .select({ id: schema.tableSessions.id }) |
| 44 | + .from(schema.tableSessions) |
| 45 | + .where(and(eq(schema.tableSessions.id, tableSessionId), isNull(schema.tableSessions.closedAt))) |
| 46 | + .limit(1); |
| 47 | + if (!session) return { error: 'invalid_table_session' }; |
| 48 | + |
| 49 | + const [openCheck] = await db |
| 50 | + .select({ id: schema.checks.id }) |
| 51 | + .from(schema.checks) |
| 52 | + .where(and(eq(schema.checks.tableSessionId, tableSessionId), eq(schema.checks.status, 'open'))) |
| 53 | + .limit(1); |
| 54 | + if (openCheck) return { error: 'check_open' }; |
| 55 | + } |
| 56 | + |
| 57 | + const quantities = new Map<string, number>(); |
| 58 | + for (const line of rawLines) { |
| 59 | + quantities.set(line.entryId, (quantities.get(line.entryId) ?? 0) + line.quantity); |
| 60 | + } |
| 61 | + const entryIds = [...quantities.keys()]; |
| 62 | + |
| 63 | + const entries = await db |
| 64 | + .select({ |
| 65 | + id: schema.menuEntries.id, |
| 66 | + name: schema.menuEntries.name, |
| 67 | + price: schema.menuEntries.price, |
| 68 | + hidden: schema.menuEntries.hidden, |
| 69 | + outOfStock: schema.menuEntries.outOfStock, |
| 70 | + }) |
| 71 | + .from(schema.menuEntries) |
| 72 | + .where(inArray(schema.menuEntries.id, entryIds)); |
| 73 | + const entryById = new Map(entries.map((e) => [e.id, e])); |
| 74 | + const staleEntryIds = entryIds.filter((id) => { |
| 75 | + const entry = entryById.get(id); |
| 76 | + return !entry || entry.hidden || entry.outOfStock; |
| 77 | + }); |
| 78 | + if (staleEntryIds.length > 0) return { error: 'stale_items', staleEntryIds }; |
| 79 | + |
| 80 | + const destinationRows = await db |
| 81 | + .select({ |
| 82 | + entryId: schema.entryDestinations.entryId, |
| 83 | + destinationId: schema.orderDestinations.id, |
| 84 | + destinationName: schema.orderDestinations.name, |
| 85 | + }) |
| 86 | + .from(schema.entryDestinations) |
| 87 | + .innerJoin(schema.orderDestinations, eq(schema.entryDestinations.destinationId, schema.orderDestinations.id)) |
| 88 | + .where(inArray(schema.entryDestinations.entryId, entryIds)); |
| 89 | + const destinationsByEntry = new Map<string, { destinationId: string; destinationName: string }[]>(); |
| 90 | + for (const row of destinationRows) { |
| 91 | + const list = destinationsByEntry.get(row.entryId) ?? []; |
| 92 | + list.push({ destinationId: row.destinationId, destinationName: row.destinationName }); |
| 93 | + destinationsByEntry.set(row.entryId, list); |
| 94 | + } |
| 95 | + |
| 96 | + const orderId = crypto.randomUUID(); |
| 97 | + const orderDay = currentOrderDay(new Date(), orderTimeZone); |
| 98 | + const itemValues = entryIds.map((entryId) => { |
| 99 | + const entry = entryById.get(entryId)!; |
| 100 | + return { |
| 101 | + id: crypto.randomUUID(), |
| 102 | + orderId, |
| 103 | + entryId, |
| 104 | + name: entry.name, |
| 105 | + price: entry.price, |
| 106 | + quantity: quantities.get(entryId)!, |
| 107 | + }; |
| 108 | + }); |
| 109 | + const itemDestinationValues = itemValues.flatMap((item) => |
| 110 | + (destinationsByEntry.get(item.entryId) ?? []).map((dest) => ({ |
| 111 | + id: crypto.randomUUID(), |
| 112 | + orderItemId: item.id, |
| 113 | + destinationId: dest.destinationId, |
| 114 | + destinationName: dest.destinationName, |
| 115 | + })), |
| 116 | + ); |
| 117 | + |
| 118 | + for (let attempt = 0; attempt < MAX_NUMBERING_RETRIES; attempt++) { |
| 119 | + const [{ value: existingCount }] = await db |
| 120 | + .select({ value: count() }) |
| 121 | + .from(schema.orders) |
| 122 | + .where(eq(schema.orders.orderDay, orderDay)); |
| 123 | + const dailyNumber = existingCount + 1; |
| 124 | + |
| 125 | + try { |
| 126 | + await db.batch([ |
| 127 | + db.insert(schema.orders).values({ |
| 128 | + id: orderId, |
| 129 | + orderDay, |
| 130 | + dailyNumber, |
| 131 | + idempotencyKey, |
| 132 | + tableSessionId: tableSessionId ?? null, |
| 133 | + }), |
| 134 | + db.insert(schema.orderItems).values(itemValues), |
| 135 | + ...(itemDestinationValues.length > 0 ? [db.insert(schema.orderItemDestinations).values(itemDestinationValues)] : []), |
| 136 | + db.insert(schema.orderEvents).values({ |
| 137 | + id: crypto.randomUUID(), |
| 138 | + orderId, |
| 139 | + status: 'submitted', |
| 140 | + actor, |
| 141 | + actorName: actorName ?? null, |
| 142 | + }), |
| 143 | + ]); |
| 144 | + return { ok: true, orderId, dailyNumber }; |
| 145 | + } catch (error) { |
| 146 | + const won = await findByIdempotencyKey(db, idempotencyKey); |
| 147 | + if (won) return won; |
| 148 | + if (attempt === MAX_NUMBERING_RETRIES - 1) throw error; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + throw new Error('Could not assign order number'); |
| 153 | +} |
| 154 | + |
| 155 | +async function findByIdempotencyKey(db: DbInstance, idempotencyKey: string) { |
| 156 | + const [row] = await db |
| 157 | + .select({ id: schema.orders.id, dailyNumber: schema.orders.dailyNumber }) |
| 158 | + .from(schema.orders) |
| 159 | + .where(eq(schema.orders.idempotencyKey, idempotencyKey)) |
| 160 | + .limit(1); |
| 161 | + if (!row) return null; |
| 162 | + return { ok: true as const, orderId: row.id, dailyNumber: row.dailyNumber }; |
| 163 | +} |
0 commit comments