Split re-identification: pick subaccount when re-ordering on a split table
When a diner confirms an order on a table that's already split, the cart now asks
which subaccount they belong to instead of blindly creating a parallel one.
- New GET /split/subaccounts?table — lists active subaccounts (id + full name).
- New GET /split/mine?id — returns a subaccount's items so the client can rebuild
its cart.
- OrderPanel (normal cart) on a split table shows '¿Quién eres?' with a tappable
button per active subaccount + 'Soy nuevo':
* pick existing → load that subaccount's items, merge the new items, and sync;
reconcileItems keeps the existing batches and turns the new items into a fresh
batch (independent timer). Existing items' timers are not reset.
* 'Soy nuevo' → name input → creates a new subaccount seeded with the cart.
- Continuity: once a diner has a split session, the normal cart FAB is replaced by
'Mi cuenta' (existing behavior), so the selector never reappears for that session
— no localStorage, just in-memory session state.
i18n es/en (whoAreYou, imNew) at parity. Build passes.
Verified criterion 7: table 5 with Ana+Beto → a third order lists [Ana][Beto]
[Soy nuevo]; tapping Ana adds the order to Ana as a NEW batch (2 distinct batchIds,
the new batch starts now, Ana's prior item keeps its ~30-min-old start).
This commit is contained in:
1 parent
8004d51f7b
commit
8fc95c3cab
5 files changed
+193
-16
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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 })),
|
||||
});
|
||||
}
|
||||
@@ -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<string, CartLine>();
|
||||
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 (
|
||||
<div className="mx-auto min-h-screen max-w-2xl px-4 pb-48">
|
||||
{/* 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({
|
||||
<p className="rounded-2xl bg-amber-50/70 px-3 py-2 text-xs text-amber-800">
|
||||
{t('splitDetected', { table: Number(table) })}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => onJoinSplit(Number(table))}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white"
|
||||
>
|
||||
{t('joinSplit', { table: Number(table) })}
|
||||
</button>
|
||||
<p className="text-sm font-medium">{t('whoAreYou')}</p>
|
||||
{subaccounts.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => onPickSubaccount(s.id, s.name, Number(table))}
|
||||
className="glass-soft rounded-2xl px-4 py-3 text-left text-sm font-medium"
|
||||
>
|
||||
{s.name || `${t('table')} ${table}`}
|
||||
</button>
|
||||
))}
|
||||
{pickNew ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder={t('yourName')}
|
||||
className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={() => newName.trim() && onCreateSubaccount(newName.trim(), Number(table))}
|
||||
disabled={!newName.trim()}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('createSplit')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setPickNew(true)}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white"
|
||||
>
|
||||
{t('imNew')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
|
||||
Reference in new issue
Block a user