diff --git a/messages/en.json b/messages/en.json index bf4dece..ee38520 100644 --- a/messages/en.json +++ b/messages/en.json @@ -36,6 +36,8 @@ "createSplit": "Create split bill", "joinSplit": "Join table {table}'s bill", "splitDetected": "Table {table} already has a split bill", + "whoAreYou": "Who are you?", + "imNew": "I'm new", "yourSubaccount": "Your subaccount", "yourSubtotal": "What you owe", "tableTotal": "Table total", diff --git a/messages/es.json b/messages/es.json index aed9f62..a9948ee 100644 --- a/messages/es.json +++ b/messages/es.json @@ -36,6 +36,8 @@ "createSplit": "Crear cuenta dividida", "joinSplit": "Unirme a la cuenta de la mesa {table}", "splitDetected": "La mesa {table} ya tiene una cuenta dividida", + "whoAreYou": "¿Quién eres?", + "imNew": "Soy nuevo", "yourSubaccount": "Tu subcuenta", "yourSubtotal": "Lo que debes tú", "tableTotal": "Total de la mesa", diff --git a/src/app/api/[slug]/split/mine/route.ts b/src/app/api/[slug]/split/mine/route.ts new file mode 100644 index 0000000..04adc04 --- /dev/null +++ b/src/app/api/[slug]/split/mine/route.ts @@ -0,0 +1,35 @@ +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: fetch a diner's OWN subaccount (by the id their session holds) so the +// client can rebuild its cart — used when a returning diner picks their existing +// subaccount, so a subsequent sync sends the full, correct item list. +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 id = new URL(req.url).searchParams.get('id') ?? ''; + const order = await prisma.order.findFirst({ + where: { id, restaurantId: restaurant.id, status: 'active' }, + }); + if (!order) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + + const items = (order.items as OrderItem[]).map((it) => ({ + productId: it.productId, + qty: it.qty, + note: it.note, + })); + return NextResponse.json({ + id: order.id, + name: order.subaccountName, + tableNumber: order.tableNumber, + items, + }); +} diff --git a/src/app/api/[slug]/split/subaccounts/route.ts b/src/app/api/[slug]/split/subaccounts/route.ts new file mode 100644 index 0000000..0bdaefc --- /dev/null +++ b/src/app/api/[slug]/split/subaccounts/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; + +export const dynamic = 'force-dynamic'; + +// Public: list the active subaccounts of a table so a returning diner can pick +// which one they belong to (full names; no privacy requirement here). +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({ subaccounts: [] }); + + const orders = await prisma.order.findMany({ + where: { restaurantId: restaurant.id, tableNumber: table, status: 'active' }, + orderBy: { createdAt: 'asc' }, + select: { id: true, subaccountName: true }, + }); + return NextResponse.json({ + subaccounts: orders.map((o) => ({ id: o.id, name: o.subaccountName })), + }); +} diff --git a/src/components/public/PublicMenu.tsx b/src/components/public/PublicMenu.tsx index c13d208..16ed39e 100644 --- a/src/components/public/PublicMenu.tsx +++ b/src/components/public/PublicMenu.tsx @@ -123,6 +123,76 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s const resolveDish = (dishName: string) => nameIndex.get(normName(dishName)); + function cartPayload(lines: CartLine[]) { + return lines.map((l) => ({ + productId: l.product.id, + name: pickText(l.product.name, locale), + qty: l.qty, + note: l.note, + price: l.product.price, + })); + } + function mergeLines(a: CartLine[], b: CartLine[]): CartLine[] { + const map = new Map(); + for (const l of [...a, ...b]) { + const k = `${l.product.id}|${l.note ?? ''}`; + const ex = map.get(k); + if (ex) ex.qty += l.qty; + else map.set(k, { ...l }); + } + return [...map.values()]; + } + + // #9 — returning diner picks an existing subaccount: load it, merge the new + // items, and sync (reconcile turns the new items into a fresh batch). + async function joinExistingSubaccount(saId: string, saName: string | null, table: number) { + try { + const mine = await fetch(`/api/${slug}/split/mine?id=${saId}`).then((r) => r.json()); + const existing: CartLine[] = (mine.items ?? []) + .map((i: { productId: string; qty: number; note?: string }) => { + const product = productIndex.get(i.productId); + return product ? { product, qty: i.qty, note: i.note } : null; + }) + .filter(Boolean) as CartLine[]; + const merged = mergeLines(existing, cart); + setCart(merged); + await fetch(`/api/${slug}/split/sync`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id: saId, items: cartPayload(merged) }), + }); + setSplitSession({ id: saId, name: saName || `${t('table')} ${table}`, table }); + setOrderOpen(false); + showToast(t('subaccountUpdated')); + } catch { + showToast('⚠️'); + } + } + + // #9 — "Soy nuevo": create a subaccount and seed it with the current cart. + async function createNewSubaccount(name: string, table: number) { + try { + const res = await fetch(`/api/${slug}/split/join`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ tableNumber: table, name }), + }).then((r) => r.json()); + if (!res?.id) return; + if (cart.length > 0) { + await fetch(`/api/${slug}/split/sync`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id: res.id, items: cartPayload(cart) }), + }); + } + setSplitSession({ id: res.id, name: res.name, table }); + setOrderOpen(false); + showToast(t('subaccountUpdated')); + } catch { + showToast('⚠️'); + } + } + return (
{/* Brand header (banner + logo + name + social icons) */} @@ -330,12 +400,8 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s suggestions={cartSuggestions} onAdd={addToCart} splitEnabled={splitEnabled} - onJoinSplit={(tbl) => { - // Normal-cart diner discovered the table is in split → switch to split. - setOrderOpen(false); - setSplitPrefillTable(tbl); - setSplitOpen(true); - }} + onPickSubaccount={joinExistingSubaccount} + onCreateSubaccount={createNewSubaccount} onClose={() => setOrderOpen(false)} onSent={() => { setCart([]); @@ -398,7 +464,8 @@ function OrderPanel({ suggestions, onAdd, splitEnabled, - onJoinSplit, + onPickSubaccount, + onCreateSubaccount, onClose, onSent, }: { @@ -408,7 +475,8 @@ function OrderPanel({ suggestions: SnapshotProduct[]; onAdd: (p: SnapshotProduct) => void; splitEnabled: boolean; - onJoinSplit: (table: number) => void; + onPickSubaccount: (id: string, name: string | null, table: number) => void; + onCreateSubaccount: (name: string, table: number) => void; onClose: () => void; onSent: () => void; }) { @@ -418,17 +486,32 @@ function OrderPanel({ const [generalNote, setGeneralNote] = useState(''); const [sending, setSending] = useState(false); const [tableInSplit, setTableInSplit] = useState(false); + const [subaccounts, setSubaccounts] = useState<{ id: string; name: string | null }[]>([]); + const [pickNew, setPickNew] = useState(false); + const [newName, setNewName] = useState(''); - // Detect if the entered table is already a split bill → offer to join instead. + // Detect if the entered table is already a split bill, and load its subaccounts + // so a returning diner can pick which one they belong to before confirming. useEffect(() => { if (!splitEnabled || !table) { setTableInSplit(false); + setSubaccounts([]); return; } let cancelled = false; fetch(`/api/${slug}/table-status?table=${Number(table)}`) .then((r) => r.json()) - .then((d) => !cancelled && setTableInSplit(d.mode === 'split')) + .then((d) => { + if (cancelled) return; + const isSplit = d.mode === 'split'; + setTableInSplit(isSplit); + if (isSplit) { + fetch(`/api/${slug}/split/subaccounts?table=${Number(table)}`) + .then((r) => r.json()) + .then((s) => !cancelled && setSubaccounts(s.subaccounts ?? [])) + .catch(() => {}); + } + }) .catch(() => {}); return () => { cancelled = true; @@ -528,12 +611,41 @@ function OrderPanel({

{t('splitDetected', { table: Number(table) })}

- +

{t('whoAreYou')}

+ {subaccounts.map((s) => ( + + ))} + {pickNew ? ( +
+ setNewName(e.target.value)} + placeholder={t('yourName')} + className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none" + /> + +
+ ) : ( + + )}
) : (