From 1dfdecb262b87141d4f73f7a4bd1b4f1d52bc28e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Mon, 15 Jun 2026 18:43:57 -0600 Subject: [PATCH] Add collaborative split-bill by table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Built on the existing Order/SSE system (no parallel system). Model choice: each Order is one subaccount; a table account is the set of active orders sharing a tableNumber with split=true. This reuses table grouping, the SSE events, GET /orders, retention pruning, and the dashboard with minimal change. Model (migration 0010): Order.split/subaccountName/paid, Restaurant.splitEnabled, OrderItem.addedAt (for intermediate-item timing). Endpoints (public): GET table-status (none/normal/split), POST split/join (creates/joins; converts a normal table to split non-destructively — existing orders flagged split=true as an unnamed 'table' subaccount, items kept; name collisions get a numeric suffix), POST split/sync (diner updates own subaccount), GET split/summary (table total + count, NO per-subaccount item detail). Editor PATCH /orders/[id] gains a paid toggle; settings gains splitEnabled. Public UI: Split FAB (only when splitEnabled && orders on), join/convert modal, diner subaccount view (own items + own subtotal + table total only), and detection in the normal cart that offers to join when the table is already split. Admin (OrdersTab): split tables grouped and broken down by subaccount (name, items, subtotal, paid badge/toggle) + table total + complete-table; live via SSE. Block 7 — modification notice + dual timer: order-edit highlights the card as 'Modificada' (ring + badge, dismiss on click; self-edits suppressed); the main table timer keeps running from createdAt (never reset on edit) and drives the green→amber→red color, while intermediate items show 'added X ago' from addedAt. i18n es/en at parity. Glassmorphism, mobile-first, safe areas preserved. Verified end-to-end (migration 0010 applies; build passes; all i18n present): 1 split button hidden when splitEnabled off (🧾 count 0→1); 2 join+sync creates Ana subaccount w/ 2 items; 3 table-status reports split for table 5; 4 Beto joins → 2 subaccounts, summary exposes total+count only (no item detail); 5 dashboard breakdown Ana $200 / Beto $50 / total $250, mark paid persists + SSE order-edit fires; 6 normal table 3 converts to split keeping its items (becomes '(table)' subaccount + new named one); 7 adding an item 10 min later keeps createdAt (main timer ~10m) and stamps the new item's addedAt recent. --- messages/en.json | 27 + messages/es.json | 27 + .../0010_split_accounts/migration.sql | 7 + prisma/schema.prisma | 8 +- src/app/[slug]/editor/page.tsx | 1 + src/app/[slug]/page.tsx | 2 + src/app/api/[slug]/menu/route.ts | 1 + src/app/api/[slug]/order/route.ts | 15 +- src/app/api/[slug]/orders/[id]/route.ts | 29 +- src/app/api/[slug]/settings/route.ts | 2 + src/app/api/[slug]/split/join/route.ts | 78 ++ src/app/api/[slug]/split/summary/route.ts | 26 + src/app/api/[slug]/split/sync/route.ts | 45 ++ src/app/api/[slug]/table-status/route.ts | 26 + src/components/editor/Editor.tsx | 3 + src/components/editor/OrdersTab.tsx | 675 +++++++++++++----- src/components/editor/types.ts | 1 + src/components/public/PublicMenu.tsx | 112 ++- src/components/public/SplitPanel.tsx | 238 ++++++ src/lib/orders.ts | 47 ++ src/lib/types.ts | 2 + 21 files changed, 1150 insertions(+), 222 deletions(-) create mode 100644 prisma/migrations/0010_split_accounts/migration.sql create mode 100644 src/app/api/[slug]/split/join/route.ts create mode 100644 src/app/api/[slug]/split/summary/route.ts create mode 100644 src/app/api/[slug]/split/sync/route.ts create mode 100644 src/app/api/[slug]/table-status/route.ts create mode 100644 src/components/public/SplitPanel.tsx create mode 100644 src/lib/orders.ts diff --git a/messages/en.json b/messages/en.json index 7e85d27..e523084 100644 --- a/messages/en.json +++ b/messages/en.json @@ -20,6 +20,7 @@ "callWaiter": "Call the waiter", "viewFull": "View full menu", "tableNumber": "Table number", + "table": "Table", "send": "Send", "addToOrder": "Add", "cart": "Cart", @@ -29,6 +30,19 @@ "total": "Total", "confirmOrder": "Confirm order", "suggestions": "You might also like", + "split": "Split bill", + "myAccount": "My account", + "yourName": "Your name", + "createSplit": "Create split bill", + "joinSplit": "Join table {table}'s bill", + "splitDetected": "Table {table} already has a split bill", + "yourSubaccount": "Your subaccount", + "yourSubtotal": "What you owe", + "tableTotal": "Table total", + "updateSubaccount": "Update my subaccount", + "addDishes": "Add dishes", + "subaccountUpdated": "Your subaccount was updated", + "splitItemsEmpty": "Add dishes to your subaccount.", "yourOrder": "Your order", "empty": "No dishes in this section yet.", "waiterCalled": "The waiter is on the way", @@ -90,6 +104,19 @@ "uploadMedia": "Upload photo or video", "ordersDisabled": "Order taking is disabled", "enableOrders": "Enable order taking", + "enableSplit": "Enable split bill", + "enableSplitHint": "Diners build a shared per-table account with a subaccount each.", + "split": "Split", + "tableTotal": "Table total", + "completeTable": "Complete table", + "tableSubaccount": "Table", + "subaccountEmpty": "No dishes yet.", + "paid": "Paid", + "markPaid": "Mark paid", + "markUnpaid": "Mark unpaid", + "modified": "Modified", + "addedNow": "just now", + "addedAgo": "added {time} ago", "orderRetention": "Keep completed orders for", "orderRetentionHint": "Older completed orders are removed automatically.", "hours": "hours", diff --git a/messages/es.json b/messages/es.json index ddd5488..a05d028 100644 --- a/messages/es.json +++ b/messages/es.json @@ -20,6 +20,7 @@ "callWaiter": "Llamar al mesero", "viewFull": "Ver el menú completo", "tableNumber": "Número de mesa", + "table": "Mesa", "send": "Enviar", "addToOrder": "Agregar", "cart": "Carrito", @@ -29,6 +30,19 @@ "total": "Total", "confirmOrder": "Confirmar orden", "suggestions": "También te puede gustar", + "split": "Cuenta dividida", + "myAccount": "Mi cuenta", + "yourName": "Tu nombre", + "createSplit": "Crear cuenta dividida", + "joinSplit": "Unirme a la cuenta de la mesa {table}", + "splitDetected": "La mesa {table} ya tiene una cuenta dividida", + "yourSubaccount": "Tu subcuenta", + "yourSubtotal": "Lo que debes tú", + "tableTotal": "Total de la mesa", + "updateSubaccount": "Actualizar mi subcuenta", + "addDishes": "Agregar platillos", + "subaccountUpdated": "Tu subcuenta se actualizó", + "splitItemsEmpty": "Agrega platillos a tu subcuenta.", "yourOrder": "Tu pedido", "empty": "Aún no hay platillos en esta sección.", "waiterCalled": "El mesero va en camino", @@ -90,6 +104,19 @@ "uploadMedia": "Subir foto o video", "ordersDisabled": "La toma de órdenes está desactivada", "enableOrders": "Habilitar toma de órdenes", + "enableSplit": "Habilitar cuenta dividida", + "enableSplitHint": "Los comensales arman una cuenta compartida por mesa, con subcuenta por persona.", + "split": "Dividida", + "tableTotal": "Total de la mesa", + "completeTable": "Completar mesa", + "tableSubaccount": "Mesa", + "subaccountEmpty": "Aún sin platillos.", + "paid": "Pagado", + "markPaid": "Marcar pagado", + "markUnpaid": "Marcar no pagado", + "modified": "Modificada", + "addedNow": "recién", + "addedAgo": "agregado hace {time}", "orderRetention": "Conservar órdenes completadas", "orderRetentionHint": "Las órdenes completadas más viejas se eliminan automáticamente.", "hours": "horas", diff --git a/prisma/migrations/0010_split_accounts/migration.sql b/prisma/migrations/0010_split_accounts/migration.sql new file mode 100644 index 0000000..72cf054 --- /dev/null +++ b/prisma/migrations/0010_split_accounts/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE "Restaurant" ADD COLUMN "splitEnabled" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "Order" ADD COLUMN "split" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "Order" ADD COLUMN "subaccountName" TEXT; +ALTER TABLE "Order" ADD COLUMN "paid" BOOLEAN NOT NULL DEFAULT false; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 1ba3c51..18615df 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -20,6 +20,7 @@ model Restaurant { palette Json @default("{}") qrConfig Json @default("{}") // artistic QR styling (qr-code-styling config) ordersEnabled Boolean @default(false) + splitEnabled Boolean @default(false) // enables collaborative split-by-table accounts orderRetentionHours Int @default(24) // completed orders older than this are pruned on read showMacros Boolean @default(false) // when false, the public menu hides all macro layers pairings Json @default("{}") // precomputed cart suggestions { productId: [productId] } @@ -98,9 +99,14 @@ model Order { id String @id @default(cuid()) restaurantId String tableNumber Int - items Json // [{ productId, name, qty, note?, price? }] + items Json // [{ productId, name, qty, note?, price?, addedAt? }] note String? // general note for the whole order status String @default("active") // active | completed + // Split: each Order is one subaccount of a table. A table is "in split" when + // any active order for that tableNumber has split=true. Reuses table grouping. + split Boolean @default(false) + subaccountName String? // diner name for the subaccount (null = unnamed/"table") + paid Boolean @default(false) // restaurant marks a subaccount as paid createdAt DateTime @default(now()) completedAt DateTime? diff --git a/src/app/[slug]/editor/page.tsx b/src/app/[slug]/editor/page.tsx index 7b43570..f7a8ffe 100644 --- a/src/app/[slug]/editor/page.tsx +++ b/src/app/[slug]/editor/page.tsx @@ -37,6 +37,7 @@ export default async function EditorPage({ slug: restaurant.slug, name: restaurant.name, ordersEnabled: restaurant.ordersEnabled, + splitEnabled: restaurant.splitEnabled, showMacros: restaurant.showMacros, defaultLocale: restaurant.defaultLocale as 'es' | 'en', palette: (restaurant.palette as Palette) ?? {}, diff --git a/src/app/[slug]/page.tsx b/src/app/[slug]/page.tsx index 6863512..d6eb329 100644 --- a/src/app/[slug]/page.tsx +++ b/src/app/[slug]/page.tsx @@ -19,6 +19,7 @@ async function getPublishedMenu(slug: string): Promise { // Brand + pairings come from the live restaurant (not the snapshot) so they // update without republishing. const brand = { + splitEnabled: restaurant.splitEnabled, pairings: (restaurant.pairings as Record) ?? {}, bannerImage: restaurant.bannerImage, profileImage: restaurant.profileImage, @@ -44,6 +45,7 @@ async function getPublishedMenu(slug: string): Promise { // showMacros (global + per-section) and brand/pairings are read live (not from the // snapshot) so toggling/editing takes effect immediately without republishing. snapshot.restaurant.showMacros = restaurant.showMacros; + snapshot.restaurant.splitEnabled = brand.splitEnabled; snapshot.restaurant.pairings = brand.pairings; snapshot.restaurant.bannerImage = brand.bannerImage; snapshot.restaurant.profileImage = brand.profileImage; diff --git a/src/app/api/[slug]/menu/route.ts b/src/app/api/[slug]/menu/route.ts index 9e5ec7d..794a3d6 100644 --- a/src/app/api/[slug]/menu/route.ts +++ b/src/app/api/[slug]/menu/route.ts @@ -24,6 +24,7 @@ export async function GET(_req: Request, { params }: { params: { slug: string } // Read showMacros (global + per-section), pairings and brand live so changes // apply without republishing. snapshot.restaurant.showMacros = restaurant.showMacros; + snapshot.restaurant.splitEnabled = restaurant.splitEnabled; snapshot.restaurant.pairings = (restaurant.pairings as Record) ?? {}; snapshot.restaurant.bannerImage = restaurant.bannerImage; snapshot.restaurant.profileImage = restaurant.profileImage; diff --git a/src/app/api/[slug]/order/route.ts b/src/app/api/[slug]/order/route.ts index a11e03c..f1f0c97 100644 --- a/src/app/api/[slug]/order/route.ts +++ b/src/app/api/[slug]/order/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { publish } from '@/lib/orders-bus'; -import type { OrderItem } from '@/lib/types'; +import { sanitizeItems } from '@/lib/orders'; export async function POST(req: Request, { params }: { params: { slug: string } }) { const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } }); @@ -14,18 +14,7 @@ export async function POST(req: Request, { params }: { params: { slug: string } const body = await req.json().catch(() => null); const tableNumber = Number(body?.tableNumber); - const rawItems: unknown[] = Array.isArray(body?.items) ? body.items : []; - // Sanitize the incoming items (public input). - const items: OrderItem[] = rawItems - .map((r) => r as Record) - .filter((r) => typeof r.productId === 'string' && typeof r.name === 'string') - .map((r) => ({ - productId: r.productId as string, - name: r.name as string, - qty: Math.max(1, Math.min(99, Math.round(Number(r.qty) || 1))), - note: typeof r.note === 'string' && r.note.trim() ? r.note.trim().slice(0, 200) : undefined, - price: Number.isFinite(Number(r.price)) ? Number(r.price) : undefined, - })); + const items = sanitizeItems(body?.items); const note = typeof body?.note === 'string' && body.note.trim() ? body.note.trim().slice(0, 500) : null; if (!tableNumber || items.length === 0) { diff --git a/src/app/api/[slug]/orders/[id]/route.ts b/src/app/api/[slug]/orders/[id]/route.ts index 0f9388a..3bce5ad 100644 --- a/src/app/api/[slug]/orders/[id]/route.ts +++ b/src/app/api/[slug]/orders/[id]/route.ts @@ -2,10 +2,12 @@ import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { requireEditor } from '@/lib/guard'; import { publish } from '@/lib/orders-bus'; +import { sanitizeItems, stampNewItems } from '@/lib/orders'; import type { OrderItem } from '@/lib/types'; -// Complete an order, or edit it (admin: add/edit items and notes). The table -// number and createdAt (and therefore the timer) are never touched. +// Complete an order, mark a subaccount paid, or edit it (admin: add/edit items +// and notes). The table number and createdAt (and so the main timer) are never +// touched; items added in an edit are stamped addedAt for the "added X ago" badge. export async function PATCH( req: Request, { params }: { params: { slug: string; id: string } }, @@ -30,21 +32,22 @@ export async function PATCH( return NextResponse.json({ ok: true }); } + // Mark a subaccount paid/unpaid. + if (typeof body?.paid === 'boolean') { + const updated = await prisma.order.update({ + where: { id: order.id }, + data: { paid: body.paid }, + }); + publish(params.slug, { type: 'order-edit', data: updated }); + return NextResponse.json({ ok: true, order: updated }); + } + // Edit (items and/or general note) — keeps status active, table and timer intact. const data: { items?: object; note?: string | null } = {}; if (Array.isArray(body?.items)) { - const items: OrderItem[] = (body.items as unknown[]) - .map((r) => r as Record) - .filter((r) => typeof r.productId === 'string' && typeof r.name === 'string') - .map((r) => ({ - productId: r.productId as string, - name: r.name as string, - qty: Math.max(1, Math.min(99, Math.round(Number(r.qty) || 1))), - note: typeof r.note === 'string' && r.note.trim() ? r.note.trim().slice(0, 200) : undefined, - price: Number.isFinite(Number(r.price)) ? Number(r.price) : undefined, - })); + const items = sanitizeItems(body.items); if (items.length === 0) return NextResponse.json({ error: 'invalid' }, { status: 400 }); - data.items = items as unknown as object; + data.items = stampNewItems(order.items as OrderItem[], items, new Date().toISOString()) as unknown as object; } if (typeof body?.note === 'string') data.note = body.note.trim().slice(0, 500) || null; else if (body?.note === null) data.note = null; diff --git a/src/app/api/[slug]/settings/route.ts b/src/app/api/[slug]/settings/route.ts index a507536..1f6e2bc 100644 --- a/src/app/api/[slug]/settings/route.ts +++ b/src/app/api/[slug]/settings/route.ts @@ -25,6 +25,7 @@ export async function PATCH(req: Request, { params }: { params: { slug: string } const body = await req.json().catch(() => null); const data: { ordersEnabled?: boolean; + splitEnabled?: boolean; defaultLocale?: string; showMacros?: boolean; orderRetentionHours?: number; @@ -34,6 +35,7 @@ export async function PATCH(req: Request, { params }: { params: { slug: string } } = {}; if (typeof body?.ordersEnabled === 'boolean') data.ordersEnabled = body.ordersEnabled; + if (typeof body?.splitEnabled === 'boolean') data.splitEnabled = body.splitEnabled; if (typeof body?.showMacros === 'boolean') data.showMacros = body.showMacros; if (body?.defaultLocale === 'es' || body?.defaultLocale === 'en') { data.defaultLocale = body.defaultLocale; diff --git a/src/app/api/[slug]/split/join/route.ts b/src/app/api/[slug]/split/join/route.ts new file mode 100644 index 0000000..dd4c0de --- /dev/null +++ b/src/app/api/[slug]/split/join/route.ts @@ -0,0 +1,78 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; +import { publish } from '@/lib/orders-bus'; +import { subtotal } from '@/lib/orders'; +import type { OrderItem } from '@/lib/types'; + +export const dynamic = 'force-dynamic'; + +function norm(s: string): string { + return s.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '').replace(/\s+/g, ' ').trim(); +} + +// Public: create or join a split subaccount for a table. +// - New table → creates the table's first subaccount. +// - Table already in split → adds another subaccount. +// - Table in NORMAL mode → converts non-destructively: existing active orders are +// flagged split=true (kept as an unnamed "table" subaccount), then the new +// named subaccount is added. +// Name collisions on the same table get a numeric suffix. +export async function POST(req: Request, { params }: { params: { slug: string } }) { + const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } }); + if (!restaurant || !restaurant.active) { + return NextResponse.json({ error: 'not_found' }, { status: 404 }); + } + if (!restaurant.ordersEnabled || !restaurant.splitEnabled) { + return NextResponse.json({ error: 'split_disabled' }, { status: 403 }); + } + + const body = await req.json().catch(() => null); + const tableNumber = Number(body?.tableNumber); + let name = String(body?.name ?? '').trim().slice(0, 40); + if (!tableNumber || !name) return NextResponse.json({ error: 'invalid' }, { status: 400 }); + + const active = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber, status: 'active' }, + }); + + // Convert a normal table to split (non-destructive: keep items, flag split). + const toConvert = active.filter((o) => !o.split); + for (const o of toConvert) { + const updated = await prisma.order.update({ + where: { id: o.id }, + data: { split: true }, + }); + publish(params.slug, { type: 'order-edit', data: updated }); + } + + // Resolve name collisions within the table. + const taken = new Set( + active.map((o) => norm(o.subaccountName ?? '')).filter(Boolean), + ); + if (taken.has(norm(name))) { + let n = 2; + while (taken.has(norm(`${name} (${n})`))) n++; + name = `${name} (${n})`; + } + + const created = await prisma.order.create({ + data: { + restaurantId: restaurant.id, + tableNumber, + items: [] as unknown as object, + status: 'active', + split: true, + subaccountName: name, + }, + }); + publish(params.slug, { type: 'order', data: created }); + + // Table total across all active subaccounts (incl. the converted ones). + const all = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber, status: 'active' }, + select: { items: true }, + }); + const tableTotal = all.reduce((s, o) => s + subtotal(o.items as OrderItem[]), 0); + + return NextResponse.json({ id: created.id, name, tableTotal }); +} diff --git a/src/app/api/[slug]/split/summary/route.ts b/src/app/api/[slug]/split/summary/route.ts new file mode 100644 index 0000000..14334c1 --- /dev/null +++ b/src/app/api/[slug]/split/summary/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; +import { subtotal } from '@/lib/orders'; +import type { OrderItem } from '@/lib/types'; + +export const dynamic = 'force-dynamic'; + +// Public: aggregate table total + subaccount count for the diner's view. +// Deliberately returns NO per-subaccount item detail (diners only see the total). +export async function GET(req: Request, { params }: { params: { slug: string } }) { + const restaurant = await prisma.restaurant.findUnique({ + where: { slug: params.slug }, + select: { id: true }, + }); + if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + + const table = Number(new URL(req.url).searchParams.get('table')); + if (!table) return NextResponse.json({ tableTotal: 0, subaccounts: 0 }); + + const all = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber: table, status: 'active' }, + select: { items: true, subaccountName: true }, + }); + const tableTotal = all.reduce((s, o) => s + subtotal(o.items as OrderItem[]), 0); + return NextResponse.json({ tableTotal, subaccounts: all.length }); +} diff --git a/src/app/api/[slug]/split/sync/route.ts b/src/app/api/[slug]/split/sync/route.ts new file mode 100644 index 0000000..11802f8 --- /dev/null +++ b/src/app/api/[slug]/split/sync/route.ts @@ -0,0 +1,45 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; +import { publish } from '@/lib/orders-bus'; +import { sanitizeItems, stampNewItems, subtotal } from '@/lib/orders'; +import type { OrderItem } from '@/lib/types'; + +export const dynamic = 'force-dynamic'; + +// Public: a diner updates the items of THEIR own subaccount (identified by id, +// which the client holds for the session). New/changed items get stamped addedAt +// so later additions show as intermediate on the dashboard. Publishes order-edit. +export async function POST(req: Request, { params }: { params: { slug: string } }) { + const restaurant = await prisma.restaurant.findUnique({ + where: { slug: params.slug }, + select: { id: true, ordersEnabled: true, splitEnabled: true }, + }); + if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + if (!restaurant.ordersEnabled || !restaurant.splitEnabled) { + return NextResponse.json({ error: 'split_disabled' }, { status: 403 }); + } + + const body = await req.json().catch(() => null); + const id = String(body?.id ?? ''); + const order = await prisma.order.findFirst({ + where: { id, restaurantId: restaurant.id, status: 'active', split: true }, + }); + if (!order) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + + const items = sanitizeItems(body?.items); + const stamped = stampNewItems(order.items as OrderItem[], items, new Date().toISOString()); + + const updated = await prisma.order.update({ + where: { id: order.id }, + data: { items: stamped as unknown as object }, + }); + publish(params.slug, { type: 'order-edit', data: updated }); + + const all = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber: order.tableNumber, status: 'active' }, + select: { items: true }, + }); + const tableTotal = all.reduce((s, o) => s + subtotal(o.items as OrderItem[]), 0); + + return NextResponse.json({ ok: true, subtotal: subtotal(stamped), tableTotal }); +} diff --git a/src/app/api/[slug]/table-status/route.ts b/src/app/api/[slug]/table-status/route.ts new file mode 100644 index 0000000..039ebe0 --- /dev/null +++ b/src/app/api/[slug]/table-status/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; + +export const dynamic = 'force-dynamic'; + +// Public: report a table's current mode so the diner flow can branch. +// none → no active orders +// normal → active order(s) but not in split +// split → at least one active split subaccount exists +export async function GET(req: Request, { params }: { params: { slug: string } }) { + const restaurant = await prisma.restaurant.findUnique({ + where: { slug: params.slug }, + select: { id: true, splitEnabled: true, ordersEnabled: true }, + }); + if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + + const table = Number(new URL(req.url).searchParams.get('table')); + if (!table) return NextResponse.json({ mode: 'none' }); + + const active = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber: table, status: 'active' }, + select: { split: true }, + }); + const mode = active.length === 0 ? 'none' : active.some((o) => o.split) ? 'split' : 'normal'; + return NextResponse.json({ mode, splitEnabled: restaurant.splitEnabled }); +} diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx index a90a07d..6ca48a1 100644 --- a/src/components/editor/Editor.tsx +++ b/src/components/editor/Editor.tsx @@ -18,6 +18,7 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s const [tab, setTab] = useState('catalog'); const [sections, setSections] = useState(data.sections); const [ordersEnabled, setOrdersEnabled] = useState(data.ordersEnabled); + const [splitEnabled, setSplitEnabled] = useState(data.splitEnabled); const [showMacros, setShowMacros] = useState(data.showMacros); const [publishOpen, setPublishOpen] = useState(false); const [publishedName, setPublishedName] = useState(data.publishedVersionName); @@ -68,6 +69,8 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s slug={data.slug} ordersEnabled={ordersEnabled} setOrdersEnabled={setOrdersEnabled} + splitEnabled={splitEnabled} + setSplitEnabled={setSplitEnabled} sections={sections} /> )} diff --git a/src/components/editor/OrdersTab.tsx b/src/components/editor/OrdersTab.tsx index df26fb3..e936415 100644 --- a/src/components/editor/OrdersTab.tsx +++ b/src/components/editor/OrdersTab.tsx @@ -15,20 +15,51 @@ type Order = { note?: string | null; createdAt: string; status: string; + split?: boolean; + subaccountName?: string | null; + paid?: boolean; }; type WaiterCall = { tableNumber: number; at: string }; type MenuOption = { id: string; name: string; price: number }; +function subtotalOf(items: OrderItem[]): number { + return items.reduce((s, it) => s + (it.price ?? 0) * it.qty, 0); +} + +// Main (table) timer — never reset on edit; drives the green→amber→red color. +function elapsed(createdAt: string, now: number): { label: string; color: string } { + const secs = Math.max(0, Math.floor((now - new Date(createdAt).getTime()) / 1000)); + const m = Math.floor(secs / 60); + const s = secs % 60; + return { + label: `${m}:${s.toString().padStart(2, '0')}`, + color: secs < 300 ? '#15803d' : secs < 600 ? '#b45309' : '#dc2626', + }; +} + +// Per-item "added X ago" — only for items added meaningfully after the order +// started (intermediate items), so initial items aren't flagged. +function itemAge(addedAt: string | undefined, createdAt: string, now: number): string | null { + if (!addedAt) return null; + if (new Date(addedAt).getTime() - new Date(createdAt).getTime() < 60_000) return null; + const mins = Math.max(0, Math.round((now - new Date(addedAt).getTime()) / 60000)); + return mins <= 0 ? 'now' : `${mins}m`; +} + export default function OrdersTab({ slug, ordersEnabled, setOrdersEnabled, + splitEnabled, + setSplitEnabled, sections, }: { slug: string; ordersEnabled: boolean; setOrdersEnabled: (v: boolean) => void; + splitEnabled: boolean; + setSplitEnabled: (v: boolean) => void; sections: EditorSection[]; }) { const t = useTranslations('editor'); @@ -37,10 +68,19 @@ export default function OrdersTab({ const [waiterCalls, setWaiterCalls] = useState([]); const [retention, setRetention] = useState(24); const [now, setNow] = useState(() => 0); - const esRef = useRef(null); + const [modified, setModified] = useState>(new Set()); + // Ids the admin just mutated locally — suppress the resulting order-edit from + // flagging "modified" (only diner/other edits should highlight). + const selfEdits = useRef>(new Set()); + + const menuOptions = useMemo( + () => + sections.flatMap((s) => + s.products.map((p) => ({ id: p.id, name: pickText(p.name, locale), price: p.price })), + ), + [sections, locale], + ); - // Load active orders from the DB on mount so a reload doesn't lose them - // (the SSE stream only carries live events). Also pulls the retention setting. useEffect(() => { if (!ordersEnabled) return; let cancelled = false; @@ -56,20 +96,6 @@ export default function OrdersTab({ }; }, [slug, ordersEnabled]); - async function saveRetention(hours: number) { - setRetention(hours); - await api(slug, '/settings', { method: 'PATCH', json: { orderRetentionHours: hours } }); - } - - // Flat list of dishes for the "add dish" search. - const menuOptions = useMemo( - () => - sections.flatMap((s) => - s.products.map((p) => ({ id: p.id, name: pickText(p.name, locale), price: p.price })), - ), - [sections, locale], - ); - useEffect(() => { setNow(Date.now()); const id = setInterval(() => setNow(Date.now()), 1000); @@ -79,8 +105,6 @@ export default function OrdersTab({ useEffect(() => { if (!ordersEnabled) return; const es = new EventSource(`/api/${slug}/orders/stream`); - esRef.current = es; - es.addEventListener('snapshot', (e) => setOrders(JSON.parse((e as MessageEvent).data))); es.addEventListener('order', (e) => { const order: Order = JSON.parse((e as MessageEvent).data); @@ -90,72 +114,115 @@ export default function OrdersTab({ const { id, status } = JSON.parse((e as MessageEvent).data); setOrders((prev) => (status === 'active' ? prev : prev.filter((o) => o.id !== id))); }); - // Live edit: replace the order in place (keeps timer/table). es.addEventListener('order-edit', (e) => { const order: Order = JSON.parse((e as MessageEvent).data); - setOrders((prev) => prev.map((o) => (o.id === order.id ? order : o))); + setOrders((prev) => { + const existed = prev.some((o) => o.id === order.id); + const next = existed ? prev.map((o) => (o.id === order.id ? order : o)) : [...prev, order]; + return next; + }); + // Highlight as modified unless this client made the change. + if (selfEdits.current.has(order.id)) { + selfEdits.current.delete(order.id); + } else { + setModified((prev) => new Set(prev).add(order.id)); + } }); es.addEventListener('waiter', (e) => { const call: WaiterCall = JSON.parse((e as MessageEvent).data); setWaiterCalls((prev) => [call, ...prev].slice(0, 8)); }); - return () => es.close(); }, [slug, ordersEnabled]); + function clearModified(id: string) { + setModified((prev) => { + if (!prev.has(id)) return prev; + const n = new Set(prev); + n.delete(id); + return n; + }); + } + async function toggleOrders() { const next = !ordersEnabled; setOrdersEnabled(next); await api(slug, '/settings', { method: 'PATCH', json: { ordersEnabled: next } }); } - - async function complete(o: Order) { - setOrders((prev) => prev.filter((x) => x.id !== o.id)); - await api(slug, `/orders/${o.id}`, { method: 'PATCH', json: { status: 'completed' } }); + async function toggleSplit() { + const next = !splitEnabled; + setSplitEnabled(next); + await api(slug, '/settings', { method: 'PATCH', json: { splitEnabled: next } }); + } + async function saveRetention(hours: number) { + setRetention(hours); + await api(slug, '/settings', { method: 'PATCH', json: { orderRetentionHours: hours } }); } - function elapsed(createdAt: string): { label: string; color: string } { - const secs = Math.max(0, Math.floor((now - new Date(createdAt).getTime()) / 1000)); - const m = Math.floor(secs / 60); - const s = secs % 60; - const label = `${m}:${s.toString().padStart(2, '0')}`; - const color = secs < 300 ? '#15803d' : secs < 600 ? '#b45309' : '#dc2626'; - return { label, color }; + // Mutations (owned here so we can mark self-edits and update local state). + async function completeOrder(id: string) { + selfEdits.current.add(id); + setOrders((prev) => prev.filter((x) => x.id !== id)); + clearModified(id); + await api(slug, `/orders/${id}`, { method: 'PATCH', json: { status: 'completed' } }); } + async function saveItems(id: string, items: OrderItem[], note: string) { + selfEdits.current.add(id); + await api(slug, `/orders/${id}`, { method: 'PATCH', json: { items, note } }); + clearModified(id); + } + async function togglePaid(id: string, paid: boolean) { + selfEdits.current.add(id); + setOrders((prev) => prev.map((o) => (o.id === id ? { ...o, paid } : o))); + await api(slug, `/orders/${id}`, { method: 'PATCH', json: { paid } }); + } + + const splitTables = useMemo(() => { + const map = new Map(); + for (const o of orders) { + if (!o.split) continue; + (map.get(o.tableNumber) ?? map.set(o.tableNumber, []).get(o.tableNumber)!).push(o); + } + return Array.from(map.entries()).sort((a, b) => a[0] - b[0]); + }, [orders]); + const normalOrders = useMemo(() => orders.filter((o) => !o.split), [orders]); return (
{t('enableOrders')} - +
{ordersEnabled && ( -
-
-
{t('orderRetention')}
-
{t('orderRetentionHint')}
+ <> +
+
+
{t('enableSplit')}
+
{t('enableSplitHint')}
+
+
-
- setRetention(Math.max(1, Math.min(720, Number(e.target.value) || 1)))} - onBlur={() => saveRetention(retention)} - className="glass-soft w-16 rounded-xl px-2 py-1.5 text-center text-sm outline-none" - /> - {t('hours')} + +
+
+
{t('orderRetention')}
+
{t('orderRetentionHint')}
+
+
+ setRetention(Math.max(1, Math.min(720, Number(e.target.value) || 1)))} + onBlur={() => saveRetention(retention)} + className="glass-soft w-16 rounded-xl px-2 py-1.5 text-center text-sm outline-none" + /> + {t('hours')} +
-
+ )} {!ordersEnabled && ( @@ -183,14 +250,30 @@ export default function OrdersTab({ {ordersEnabled && (
- {orders.map((o) => ( + {splitTables.map(([table, subs]) => ( + ids.forEach(completeOrder)} + onAck={clearModified} + /> + ))} + {normalOrders.map((o) => ( complete(o)} + onSaveItems={saveItems} + onComplete={() => completeOrder(o.id)} + onAck={() => clearModified(o.id)} /> ))}
@@ -199,37 +282,70 @@ export default function OrdersTab({ ); } -function OrderCard({ - order, - elapsed, +function Toggle({ on, onClick }: { on: boolean; onClick: () => void }) { + return ( + + ); +} + +// Read-only items list with intermediate "+Xm" badges. +function ItemsView({ items, createdAt, now }: { items: OrderItem[]; createdAt: string; now: number }) { + const t = useTranslations('editor'); + return ( +
    + {items.map((it, idx) => { + const age = itemAge(it.addedAt, createdAt, now); + return ( +
  • +
    + {it.name} + + {age && ( + + {age === 'now' ? t('addedNow') : t('addedAgo', { time: age })} + + )} + ×{it.qty} + +
    + {it.note &&
    ↳ {it.note}
    } +
  • + ); + })} +
+ ); +} + +// Shared edit form (qty / notes / searchable add-dish). Calls onSave(items, note). +function ItemsEditPanel({ + initialItems, + initialNote, menuOptions, - slug, - onComplete, + showNote, + onSave, + onCancel, }: { - order: Order; - elapsed: { label: string; color: string }; + initialItems: OrderItem[]; + initialNote: string; menuOptions: MenuOption[]; - slug: string; - onComplete: () => void; + showNote: boolean; + onSave: (items: OrderItem[], note: string) => Promise | void; + onCancel: () => void; }) { const t = useTranslations('editor'); const tc = useTranslations('common'); - const [editing, setEditing] = useState(false); - const [items, setItems] = useState(order.items); - const [note, setNote] = useState(order.note ?? ''); + const [items, setItems] = useState(initialItems); + const [note, setNote] = useState(initialNote); const [search, setSearch] = useState(''); const [saving, setSaving] = useState(false); - // Keep local edit copy in sync when a live edit/replace arrives. - useEffect(() => { - if (!editing) { - setItems(order.items); - setNote(order.note ?? ''); - } - }, [order, editing]); - - const total = items.reduce((s, it) => s + (it.price ?? 0) * it.qty, 0); - const matches = useMemo(() => { const q = search.trim().toLowerCase(); if (!q) return []; @@ -245,29 +361,129 @@ function OrderCard({ setSearch(''); } - function setQty(i: number, delta: number) { - setItems((prev) => - prev.map((it, idx) => (idx === i ? { ...it, qty: it.qty + delta } : it)).filter((it) => it.qty > 0), - ); - } + return ( +
+ {items.map((it, idx) => ( +
+
+ {it.name} + + {it.qty} + +
+ setItems((p) => p.map((x, i) => (i === idx ? { ...x, note: e.target.value } : x)))} + placeholder={t('itemNote')} + className="rounded-xl bg-white/40 px-3 py-1.5 text-xs outline-none" + /> +
+ ))} - function setItemNote(i: number, v: string) { - setItems((prev) => prev.map((it, idx) => (idx === i ? { ...it, note: v } : it))); - } +
+ setSearch(e.target.value)} + placeholder={t('searchDish')} + className="glass-soft w-full rounded-2xl px-3 py-2 text-sm outline-none" + /> + {matches.length > 0 && ( +
+ {matches.map((m) => ( + + ))} +
+ )} +
- async function save() { - if (items.length === 0 || saving) return; - setSaving(true); - try { - await api(slug, `/orders/${order.id}`, { method: 'PATCH', json: { items, note } }); - setEditing(false); - } finally { - setSaving(false); - } - } + {showNote && ( +