Add collaborative split-bill by table
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.
This commit is contained in:
1 parent
6cda59387c
commit
1dfdecb262
21 files changed
+1150
-222
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
@@ -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?
|
||||
|
||||
|
||||
@@ -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) ?? {},
|
||||
|
||||
@@ -19,6 +19,7 @@ async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
|
||||
// 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<string, string[]>) ?? {},
|
||||
bannerImage: restaurant.bannerImage,
|
||||
profileImage: restaurant.profileImage,
|
||||
@@ -44,6 +45,7 @@ async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
|
||||
// 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;
|
||||
|
||||
@@ -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<string, string[]>) ?? {};
|
||||
snapshot.restaurant.bannerImage = restaurant.bannerImage;
|
||||
snapshot.restaurant.profileImage = restaurant.profileImage;
|
||||
|
||||
@@ -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<string, unknown>)
|
||||
.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) {
|
||||
|
||||
@@ -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<string, unknown>)
|
||||
.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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
|
||||
const [tab, setTab] = useState<Tab>('catalog');
|
||||
const [sections, setSections] = useState<EditorSection[]>(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}
|
||||
/>
|
||||
)}
|
||||
|
||||
+491
-184
@@ -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<WaiterCall[]>([]);
|
||||
const [retention, setRetention] = useState(24);
|
||||
const [now, setNow] = useState(() => 0);
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
const [modified, setModified] = useState<Set<string>>(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<Set<string>>(new Set());
|
||||
|
||||
const menuOptions = useMemo<MenuOption[]>(
|
||||
() =>
|
||||
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<MenuOption[]>(
|
||||
() =>
|
||||
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<number, Order[]>();
|
||||
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 (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="glass flex items-center justify-between rounded-3xl p-4">
|
||||
<span className="text-sm font-medium">{t('enableOrders')}</span>
|
||||
<button
|
||||
onClick={toggleOrders}
|
||||
className={`relative h-7 w-12 rounded-full transition ${ordersEnabled ? 'bg-green-500' : 'bg-gray-300'}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${ordersEnabled ? 'left-6' : 'left-1'}`}
|
||||
/>
|
||||
</button>
|
||||
<Toggle on={ordersEnabled} onClick={toggleOrders} />
|
||||
</div>
|
||||
|
||||
{ordersEnabled && (
|
||||
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t('orderRetention')}</div>
|
||||
<div className="text-xs text-[var(--text)]/55">{t('orderRetentionHint')}</div>
|
||||
<>
|
||||
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t('enableSplit')}</div>
|
||||
<div className="text-xs text-[var(--text)]/55">{t('enableSplitHint')}</div>
|
||||
</div>
|
||||
<Toggle on={splitEnabled} onClick={toggleSplit} />
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={720}
|
||||
value={retention}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
<span className="text-xs text-[var(--text)]/55">{t('hours')}</span>
|
||||
|
||||
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t('orderRetention')}</div>
|
||||
<div className="text-xs text-[var(--text)]/55">{t('orderRetentionHint')}</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={720}
|
||||
value={retention}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
<span className="text-xs text-[var(--text)]/55">{t('hours')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!ordersEnabled && (
|
||||
@@ -183,14 +250,30 @@ export default function OrdersTab({
|
||||
|
||||
{ordersEnabled && (
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
{orders.map((o) => (
|
||||
{splitTables.map(([table, subs]) => (
|
||||
<SplitTableCard
|
||||
key={`split-${table}`}
|
||||
table={table}
|
||||
subaccounts={subs}
|
||||
now={now}
|
||||
modified={modified}
|
||||
menuOptions={menuOptions}
|
||||
onSaveItems={saveItems}
|
||||
onTogglePaid={togglePaid}
|
||||
onCompleteTable={(ids) => ids.forEach(completeOrder)}
|
||||
onAck={clearModified}
|
||||
/>
|
||||
))}
|
||||
{normalOrders.map((o) => (
|
||||
<OrderCard
|
||||
key={o.id}
|
||||
order={o}
|
||||
elapsed={elapsed(o.createdAt)}
|
||||
now={now}
|
||||
modified={modified.has(o.id)}
|
||||
menuOptions={menuOptions}
|
||||
slug={slug}
|
||||
onComplete={() => complete(o)}
|
||||
onSaveItems={saveItems}
|
||||
onComplete={() => completeOrder(o.id)}
|
||||
onAck={() => clearModified(o.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -199,37 +282,70 @@ export default function OrdersTab({
|
||||
);
|
||||
}
|
||||
|
||||
function OrderCard({
|
||||
order,
|
||||
elapsed,
|
||||
function Toggle({ on, onClick }: { on: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={`relative h-7 w-12 shrink-0 rounded-full transition ${on ? 'bg-green-500' : 'bg-gray-300'}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${on ? 'left-6' : 'left-1'}`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Read-only items list with intermediate "+Xm" badges.
|
||||
function ItemsView({ items, createdAt, now }: { items: OrderItem[]; createdAt: string; now: number }) {
|
||||
const t = useTranslations('editor');
|
||||
return (
|
||||
<ul className="space-y-1.5 text-sm">
|
||||
{items.map((it, idx) => {
|
||||
const age = itemAge(it.addedAt, createdAt, now);
|
||||
return (
|
||||
<li key={idx}>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="min-w-0">{it.name}</span>
|
||||
<span className="flex shrink-0 items-center gap-2">
|
||||
{age && (
|
||||
<span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-medium text-blue-700">
|
||||
{age === 'now' ? t('addedNow') : t('addedAgo', { time: age })}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[var(--text)]/60">×{it.qty}</span>
|
||||
</span>
|
||||
</div>
|
||||
{it.note && <div className="text-xs text-[var(--accent)]">↳ {it.note}</div>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
// 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> | void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const tc = useTranslations('common');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [items, setItems] = useState<OrderItem[]>(order.items);
|
||||
const [note, setNote] = useState(order.note ?? '');
|
||||
const [items, setItems] = useState<OrderItem[]>(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 (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{items.map((it, idx) => (
|
||||
<div key={idx} className="glass-soft flex flex-col gap-1.5 rounded-2xl px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 text-sm">{it.name}</span>
|
||||
<button
|
||||
onClick={() =>
|
||||
setItems((p) => p.map((x, i) => (i === idx ? { ...x, qty: x.qty - 1 } : x)).filter((x) => x.qty > 0))
|
||||
}
|
||||
className="px-2 text-lg"
|
||||
aria-label="−"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span className="w-5 text-center">{it.qty}</span>
|
||||
<button
|
||||
onClick={() => setItems((p) => p.map((x, i) => (i === idx ? { ...x, qty: x.qty + 1 } : x)))}
|
||||
className="px-2 text-lg"
|
||||
aria-label="+"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
value={it.note ?? ''}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
function setItemNote(i: number, v: string) {
|
||||
setItems((prev) => prev.map((it, idx) => (idx === i ? { ...it, note: v } : it)));
|
||||
}
|
||||
<div className="relative">
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => 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 && (
|
||||
<div className="glass absolute z-10 mt-1 flex max-h-52 w-full flex-col overflow-y-auto rounded-2xl p-1">
|
||||
{matches.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
onClick={() => addDish(m)}
|
||||
className="flex items-center justify-between gap-2 rounded-xl px-3 py-2 text-left text-sm hover:bg-white/50"
|
||||
>
|
||||
<span className="min-w-0 truncate">{m.name}</span>
|
||||
<span className="shrink-0 text-[var(--text)]/60">${m.price.toFixed(2)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
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 && (
|
||||
<textarea
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
rows={2}
|
||||
placeholder={t('generalNote')}
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between px-1 text-sm font-semibold">
|
||||
<span>{t('total')}</span>
|
||||
<span>${subtotalOf(items).toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button onClick={onCancel} className="glass-pill flex-1 rounded-2xl py-2 text-sm">
|
||||
{tc('cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (items.length === 0 || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(items, note);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}}
|
||||
disabled={saving || items.length === 0}
|
||||
className="flex-1 rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{tc('save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderCard({
|
||||
order,
|
||||
now,
|
||||
modified,
|
||||
menuOptions,
|
||||
onSaveItems,
|
||||
onComplete,
|
||||
onAck,
|
||||
}: {
|
||||
order: Order;
|
||||
now: number;
|
||||
modified: boolean;
|
||||
menuOptions: MenuOption[];
|
||||
onSaveItems: (id: string, items: OrderItem[], note: string) => Promise<void> | void;
|
||||
onComplete: () => void;
|
||||
onAck: () => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const e = elapsed(order.createdAt, now);
|
||||
|
||||
return (
|
||||
<div className="animate-spawn glass relative rounded-3xl p-4">
|
||||
<div
|
||||
onClick={modified ? onAck : undefined}
|
||||
className={`animate-spawn glass relative rounded-3xl p-4 ${
|
||||
modified ? 'ring-2 ring-blue-400 animate-pulse-dot' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
onClick={onComplete}
|
||||
className="absolute right-3 top-3 text-lg text-[var(--text)]/40"
|
||||
@@ -275,33 +491,30 @@ function OrderCard({
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
<div className="flex items-center justify-between pr-6">
|
||||
<span className="display text-lg font-semibold">{t('table')} {order.tableNumber}</span>
|
||||
<div className="flex items-center justify-between gap-2 pr-6">
|
||||
<span className="display text-lg font-semibold">
|
||||
{t('table')} {order.tableNumber}
|
||||
</span>
|
||||
<span
|
||||
className="rounded-full px-2 py-0.5 font-mono text-sm font-semibold text-white"
|
||||
style={{ background: elapsed.color }}
|
||||
style={{ background: e.color }}
|
||||
>
|
||||
{elapsed.label}
|
||||
{e.label}
|
||||
</span>
|
||||
</div>
|
||||
{modified && (
|
||||
<span className="mt-1 inline-block rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700">
|
||||
{t('modified')}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!editing ? (
|
||||
<>
|
||||
<ul className="mt-2 space-y-1.5 text-sm">
|
||||
{order.items.map((it, idx) => (
|
||||
<li key={idx}>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="min-w-0">{it.name}</span>
|
||||
<span className="shrink-0 text-[var(--text)]/60">×{it.qty}</span>
|
||||
</div>
|
||||
{it.note && <div className="text-xs text-[var(--accent)]">↳ {it.note}</div>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="mt-2">
|
||||
<ItemsView items={order.items} createdAt={order.createdAt} now={now} />
|
||||
</div>
|
||||
{order.note && (
|
||||
<p className="mt-2 rounded-xl bg-amber-50/70 px-3 py-1.5 text-xs text-amber-800">
|
||||
📝 {order.note}
|
||||
</p>
|
||||
<p className="mt-2 rounded-xl bg-amber-50/70 px-3 py-1.5 text-xs text-amber-800">📝 {order.note}</p>
|
||||
)}
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button
|
||||
@@ -319,81 +532,175 @@ function OrderCard({
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{items.map((it, idx) => (
|
||||
<div key={idx} className="glass-soft flex flex-col gap-1.5 rounded-2xl px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 text-sm">{it.name}</span>
|
||||
<button onClick={() => setQty(idx, -1)} className="px-2 text-lg" aria-label="−">−</button>
|
||||
<span className="w-5 text-center">{it.qty}</span>
|
||||
<button onClick={() => setQty(idx, 1)} className="px-2 text-lg" aria-label="+">+</button>
|
||||
</div>
|
||||
<input
|
||||
value={it.note ?? ''}
|
||||
onChange={(e) => setItemNote(idx, e.target.value)}
|
||||
placeholder={t('itemNote')}
|
||||
className="rounded-xl bg-white/40 px-3 py-1.5 text-xs outline-none"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<ItemsEditPanel
|
||||
initialItems={order.items}
|
||||
initialNote={order.note ?? ''}
|
||||
menuOptions={menuOptions}
|
||||
showNote
|
||||
onCancel={() => setEditing(false)}
|
||||
onSave={async (items, note) => {
|
||||
await onSaveItems(order.id, items, note);
|
||||
setEditing(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SplitTableCard({
|
||||
table,
|
||||
subaccounts,
|
||||
now,
|
||||
modified,
|
||||
menuOptions,
|
||||
onSaveItems,
|
||||
onTogglePaid,
|
||||
onCompleteTable,
|
||||
onAck,
|
||||
}: {
|
||||
table: number;
|
||||
subaccounts: Order[];
|
||||
now: number;
|
||||
modified: Set<string>;
|
||||
menuOptions: MenuOption[];
|
||||
onSaveItems: (id: string, items: OrderItem[], note: string) => Promise<void> | void;
|
||||
onTogglePaid: (id: string, paid: boolean) => void;
|
||||
onCompleteTable: (ids: string[]) => void;
|
||||
onAck: (id: string) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
// Main timer = earliest subaccount creation (when the table started).
|
||||
const startedAt = subaccounts.reduce(
|
||||
(min, o) => (new Date(o.createdAt) < new Date(min) ? o.createdAt : min),
|
||||
subaccounts[0].createdAt,
|
||||
);
|
||||
const e = elapsed(startedAt, now);
|
||||
const tableTotal = subaccounts.reduce((s, o) => s + subtotalOf(o.items), 0);
|
||||
const allPaid = subaccounts.every((o) => o.paid);
|
||||
|
||||
return (
|
||||
<div className="animate-spawn glass relative flex flex-col gap-2 rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="display text-lg font-semibold">
|
||||
{t('table')} {table} · {t('split')}
|
||||
</span>
|
||||
<span
|
||||
className="rounded-full px-2 py-0.5 font-mono text-sm font-semibold text-white"
|
||||
style={{ background: e.color }}
|
||||
>
|
||||
{e.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{subaccounts.map((sub) => (
|
||||
<SubaccountCard
|
||||
key={sub.id}
|
||||
sub={sub}
|
||||
now={now}
|
||||
modified={modified.has(sub.id)}
|
||||
menuOptions={menuOptions}
|
||||
onSaveItems={onSaveItems}
|
||||
onTogglePaid={onTogglePaid}
|
||||
onAck={() => onAck(sub.id)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Searchable add-dish */}
|
||||
<div className="relative">
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => 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 && (
|
||||
<div className="glass absolute z-10 mt-1 flex max-h-52 w-full flex-col overflow-y-auto rounded-2xl p-1">
|
||||
{matches.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
onClick={() => addDish(m)}
|
||||
className="flex items-center justify-between gap-2 rounded-xl px-3 py-2 text-left text-sm hover:bg-white/50"
|
||||
>
|
||||
<span className="min-w-0 truncate">{m.name}</span>
|
||||
<span className="shrink-0 text-[var(--text)]/60">${m.price.toFixed(2)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between border-t border-white/40 pt-2 text-sm font-semibold">
|
||||
<span>{t('tableTotal')}</span>
|
||||
<span>${tableTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onCompleteTable(subaccounts.map((s) => s.id))}
|
||||
className={`rounded-2xl py-2 text-sm font-medium text-white ${allPaid ? 'bg-green-600' : 'bg-[var(--accent)]'}`}
|
||||
>
|
||||
{t('completeTable')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
<textarea
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
rows={2}
|
||||
placeholder={t('generalNote')}
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
function SubaccountCard({
|
||||
sub,
|
||||
now,
|
||||
modified,
|
||||
menuOptions,
|
||||
onSaveItems,
|
||||
onTogglePaid,
|
||||
onAck,
|
||||
}: {
|
||||
sub: Order;
|
||||
now: number;
|
||||
modified: boolean;
|
||||
menuOptions: MenuOption[];
|
||||
onSaveItems: (id: string, items: OrderItem[], note: string) => Promise<void> | void;
|
||||
onTogglePaid: (id: string, paid: boolean) => void;
|
||||
onAck: () => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const sub$ = subtotalOf(sub.items);
|
||||
|
||||
<div className="flex items-center justify-between px-1 text-sm font-semibold">
|
||||
<span>{t('total')}</span>
|
||||
<span>${total.toFixed(2)}</span>
|
||||
</div>
|
||||
return (
|
||||
<div
|
||||
onClick={modified ? onAck : undefined}
|
||||
className={`glass-soft rounded-2xl p-3 ${modified ? 'ring-2 ring-blue-400' : ''} ${sub.paid ? 'opacity-70' : ''}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
{sub.subaccountName || t('tableSubaccount')}
|
||||
{modified && (
|
||||
<span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700">
|
||||
{t('modified')}
|
||||
</span>
|
||||
)}
|
||||
{sub.paid && (
|
||||
<span className="rounded-full bg-green-100 px-2 py-0.5 text-[10px] font-semibold text-green-700">
|
||||
{t('paid')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="shrink-0 text-sm font-semibold">${sub$.toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!editing ? (
|
||||
<>
|
||||
{sub.items.length > 0 ? (
|
||||
<div className="mt-1.5">
|
||||
<ItemsView items={sub.items} createdAt={sub.createdAt} now={now} />
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-1 text-xs text-[var(--text)]/50">{t('subaccountEmpty')}</p>
|
||||
)}
|
||||
<div className="mt-2 flex gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditing(false);
|
||||
setItems(order.items);
|
||||
setNote(order.note ?? '');
|
||||
}}
|
||||
className="glass-pill flex-1 rounded-2xl py-2 text-sm"
|
||||
onClick={() => setEditing(true)}
|
||||
className="glass-pill flex-1 rounded-xl py-1.5 text-xs font-medium"
|
||||
>
|
||||
{tc('cancel')}
|
||||
{t('edit')}
|
||||
</button>
|
||||
<button
|
||||
onClick={save}
|
||||
disabled={saving || items.length === 0}
|
||||
className="flex-1 rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
onClick={() => onTogglePaid(sub.id, !sub.paid)}
|
||||
className={`flex-1 rounded-xl py-1.5 text-xs font-medium ${
|
||||
sub.paid ? 'bg-gray-200 text-gray-600' : 'bg-green-600 text-white'
|
||||
}`}
|
||||
>
|
||||
{t('save')}
|
||||
{sub.paid ? t('markUnpaid') : t('markPaid')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<ItemsEditPanel
|
||||
initialItems={sub.items}
|
||||
initialNote=""
|
||||
menuOptions={menuOptions}
|
||||
showNote={false}
|
||||
onCancel={() => setEditing(false)}
|
||||
onSave={async (items) => {
|
||||
await onSaveItems(sub.id, items, sub.note ?? '');
|
||||
setEditing(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -43,6 +43,7 @@ export type EditorData = {
|
||||
slug: string;
|
||||
name: string;
|
||||
ordersEnabled: boolean;
|
||||
splitEnabled: boolean;
|
||||
showMacros: boolean;
|
||||
defaultLocale: Locale;
|
||||
palette: Palette;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { MenuSnapshot, SnapshotProduct } from '@/lib/types';
|
||||
@@ -12,6 +12,7 @@ import MacroLegend from './MacroLegend';
|
||||
import Gallery from './Gallery';
|
||||
import AiConsultant from './AiConsultant';
|
||||
import SuggestionCarousel from './SuggestionCarousel';
|
||||
import SplitPanel, { type SplitSession } from './SplitPanel';
|
||||
|
||||
type ViewMode = 'cards' | 'list';
|
||||
|
||||
@@ -50,6 +51,9 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
const [cart, setCart] = useState<CartLine[]>([]);
|
||||
const [orderOpen, setOrderOpen] = useState(false);
|
||||
const [waiterOpen, setWaiterOpen] = useState(false);
|
||||
const [splitOpen, setSplitOpen] = useState(false);
|
||||
const [splitSession, setSplitSession] = useState<SplitSession | null>(null);
|
||||
const [splitPrefillTable, setSplitPrefillTable] = useState<number | null>(null);
|
||||
const [toast, setToast] = useState<string | null>(null);
|
||||
// View preference is intentionally not persisted — always starts on cards.
|
||||
const [view, setView] = useState<ViewMode>('cards');
|
||||
@@ -74,6 +78,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
const pairings = menu.restaurant.pairings ?? {};
|
||||
|
||||
const ordersEnabled = menu.restaurant.ordersEnabled;
|
||||
const splitEnabled = ordersEnabled && !!menu.restaurant.splitEnabled;
|
||||
// Macros hierarchy: global flag AND the section's own flag. The legend appears
|
||||
// only if at least one visible section actually shows macros.
|
||||
const globalMacros = menu.restaurant.showMacros;
|
||||
@@ -243,18 +248,48 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
>
|
||||
✨ {t('askAi')}
|
||||
</button>
|
||||
{ordersEnabled && (
|
||||
{/* In a split session the cart IS the diner's subaccount → show one
|
||||
'Mi cuenta' button (split). Otherwise show the normal cart, plus a
|
||||
separate Split button when split is enabled. */}
|
||||
{splitSession ? (
|
||||
<button
|
||||
onClick={() => setOrderOpen(true)}
|
||||
onClick={() => setSplitOpen(true)}
|
||||
className="relative flex items-center gap-2 rounded-full bg-[var(--accent)] px-5 py-3 text-sm font-semibold text-white shadow-lg"
|
||||
>
|
||||
🛒 {t('cart')}
|
||||
🧾 {t('myAccount')}
|
||||
{cartCount > 0 && (
|
||||
<span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-white px-1 text-xs font-bold text-[var(--accent)] shadow">
|
||||
{cartCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
{ordersEnabled && (
|
||||
<button
|
||||
onClick={() => setOrderOpen(true)}
|
||||
className="relative flex items-center gap-2 rounded-full bg-[var(--accent)] px-5 py-3 text-sm font-semibold text-white shadow-lg"
|
||||
>
|
||||
🛒 {t('cart')}
|
||||
{cartCount > 0 && (
|
||||
<span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-white px-1 text-xs font-bold text-[var(--accent)] shadow">
|
||||
{cartCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{splitEnabled && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSplitPrefillTable(null);
|
||||
setSplitOpen(true);
|
||||
}}
|
||||
className="glass rounded-full px-5 py-3 text-sm font-semibold shadow-lg"
|
||||
>
|
||||
🧾 {t('split')}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* 'More' (waiter / back to top) — distinct ⋯ icon, not a '+', to avoid
|
||||
confusion with the add-to-cart '+' inside each dish. */}
|
||||
@@ -294,6 +329,13 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
setCart={setCart}
|
||||
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);
|
||||
}}
|
||||
onClose={() => setOrderOpen(false)}
|
||||
onSent={() => {
|
||||
setCart([]);
|
||||
@@ -302,6 +344,18 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{splitOpen && (
|
||||
<SplitPanel
|
||||
slug={slug}
|
||||
cart={cart}
|
||||
setCart={setCart}
|
||||
session={splitSession}
|
||||
setSession={setSplitSession}
|
||||
prefillTable={splitPrefillTable}
|
||||
onClose={() => setSplitOpen(false)}
|
||||
onToast={showToast}
|
||||
/>
|
||||
)}
|
||||
{waiterOpen && (
|
||||
<WaiterPanel
|
||||
slug={slug}
|
||||
@@ -343,6 +397,8 @@ function OrderPanel({
|
||||
setCart,
|
||||
suggestions,
|
||||
onAdd,
|
||||
splitEnabled,
|
||||
onJoinSplit,
|
||||
onClose,
|
||||
onSent,
|
||||
}: {
|
||||
@@ -351,6 +407,8 @@ function OrderPanel({
|
||||
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
|
||||
suggestions: SnapshotProduct[];
|
||||
onAdd: (p: SnapshotProduct) => void;
|
||||
splitEnabled: boolean;
|
||||
onJoinSplit: (table: number) => void;
|
||||
onClose: () => void;
|
||||
onSent: () => void;
|
||||
}) {
|
||||
@@ -359,6 +417,23 @@ function OrderPanel({
|
||||
const [table, setTable] = useState('');
|
||||
const [generalNote, setGeneralNote] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
const [tableInSplit, setTableInSplit] = useState(false);
|
||||
|
||||
// Detect if the entered table is already a split bill → offer to join instead.
|
||||
useEffect(() => {
|
||||
if (!splitEnabled || !table) {
|
||||
setTableInSplit(false);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
fetch(`/api/${slug}/table-status?table=${Number(table)}`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => !cancelled && setTableInSplit(d.mode === 'split'))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [slug, table, splitEnabled]);
|
||||
|
||||
function setQty(id: string, delta: number) {
|
||||
setCart((prev) =>
|
||||
@@ -447,13 +522,28 @@ function OrderPanel({
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
<TableInput value={table} onChange={setTable} />
|
||||
<button
|
||||
onClick={send}
|
||||
disabled={!table || cart.length === 0 || sending}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('confirmOrder')}
|
||||
</button>
|
||||
|
||||
{tableInSplit && table ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<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>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={send}
|
||||
disabled={!table || cart.length === 0 || sending}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('confirmOrder')}
|
||||
</button>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { SnapshotProduct } from '@/lib/types';
|
||||
import { pickText } from '@/lib/text';
|
||||
|
||||
export type SplitSession = { id: string; name: string; table: number };
|
||||
type CartLine = { product: SnapshotProduct; qty: number; note?: string };
|
||||
|
||||
// Diner-facing split-bill panel: join/convert flow + own subaccount view.
|
||||
// Reuses the shared cart state as the subaccount draft; sync pushes it server-side.
|
||||
export default function SplitPanel({
|
||||
slug,
|
||||
cart,
|
||||
setCart,
|
||||
session,
|
||||
setSession,
|
||||
prefillTable,
|
||||
onClose,
|
||||
onToast,
|
||||
}: {
|
||||
slug: string;
|
||||
cart: CartLine[];
|
||||
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
|
||||
session: SplitSession | null;
|
||||
setSession: (s: SplitSession | null) => void;
|
||||
prefillTable?: number | null;
|
||||
onClose: () => void;
|
||||
onToast: (msg: string) => void;
|
||||
}) {
|
||||
const t = useTranslations('menu');
|
||||
const locale = useLocale() as Locale;
|
||||
const [name, setName] = useState('');
|
||||
const [table, setTable] = useState(prefillTable ? String(prefillTable) : '');
|
||||
const [mode, setMode] = useState<'none' | 'normal' | 'split'>('none');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [tableTotal, setTableTotal] = useState(0);
|
||||
|
||||
const yourSubtotal = cart.reduce((s, l) => s + l.product.price * l.qty, 0);
|
||||
|
||||
function itemsPayload() {
|
||||
return cart.map((l) => ({
|
||||
productId: l.product.id,
|
||||
name: pickText(l.product.name, locale),
|
||||
qty: l.qty,
|
||||
note: l.note,
|
||||
price: l.product.price,
|
||||
}));
|
||||
}
|
||||
|
||||
// Probe the table's current mode while typing (to show join vs create wording).
|
||||
useEffect(() => {
|
||||
if (session || !table) {
|
||||
setMode('none');
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
fetch(`/api/${slug}/table-status?table=${Number(table)}`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => !cancelled && setMode(d.mode))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [slug, table, session]);
|
||||
|
||||
async function refreshTotal(tbl: number) {
|
||||
const d = await fetch(`/api/${slug}/split/summary?table=${tbl}`).then((r) => r.json());
|
||||
setTableTotal(d.tableTotal ?? 0);
|
||||
}
|
||||
|
||||
async function join() {
|
||||
const tbl = Number(table);
|
||||
if (!name.trim() || !tbl || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/api/${slug}/split/join`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tableNumber: tbl, name: name.trim() }),
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const newSession = { id: data.id, name: data.name, table: tbl };
|
||||
setSession(newSession);
|
||||
// Carry any items already in the cart into the new subaccount.
|
||||
if (cart.length > 0) {
|
||||
await fetch(`/api/${slug}/split/sync`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: data.id, items: itemsPayload() }),
|
||||
});
|
||||
}
|
||||
await refreshTotal(tbl);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function sync() {
|
||||
if (!session || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/api/${slug}/split/sync`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: session.id, items: itemsPayload() }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const d = await res.json();
|
||||
setTableTotal(d.tableTotal ?? 0);
|
||||
onToast(t('subaccountUpdated'));
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (session) refreshTotal(session.table);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
function setQty(id: string, delta: number) {
|
||||
setCart((prev) =>
|
||||
prev.map((l) => (l.product.id === id ? { ...l, qty: l.qty + delta } : l)).filter((l) => l.qty > 0),
|
||||
);
|
||||
}
|
||||
function setNote(id: string, note: string) {
|
||||
setCart((prev) => prev.map((l) => (l.product.id === id ? { ...l, note } : l)));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="safe-modal fixed inset-0 z-50 flex items-end justify-center bg-black/40 px-3 backdrop-blur-sm sm:items-center">
|
||||
<div className="glass flex max-h-[88vh] w-full max-w-md flex-col gap-3 overflow-y-auto rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-lg font-semibold">{t('split')}</h3>
|
||||
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!session ? (
|
||||
<>
|
||||
{mode === 'split' && table && (
|
||||
<p className="rounded-2xl bg-amber-50/70 px-3 py-2 text-sm text-amber-800">
|
||||
{t('splitDetected', { table: Number(table) })}
|
||||
</p>
|
||||
)}
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('yourName')}
|
||||
className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
inputMode="numeric"
|
||||
value={table}
|
||||
onChange={(e) => setTable(e.target.value)}
|
||||
placeholder={t('tableNumber')}
|
||||
className="glass-soft rounded-2xl px-4 py-3 text-center text-lg outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={join}
|
||||
disabled={!name.trim() || !table || busy}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{mode === 'split' && table ? t('joinSplit', { table: Number(table) }) : t('createSplit')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm text-[var(--text)]/70">
|
||||
{t('yourSubaccount')}: <strong>{session.name}</strong> · {t('table')} {session.table}
|
||||
</div>
|
||||
|
||||
<div className="flex max-h-[40vh] flex-col gap-2 overflow-y-auto">
|
||||
{cart.length === 0 && (
|
||||
<p className="text-sm text-[var(--text)]/60">{t('splitItemsEmpty')}</p>
|
||||
)}
|
||||
{cart.map((l) => (
|
||||
<div key={l.product.id} className="glass-soft flex flex-col gap-2 rounded-2xl px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 text-sm font-medium">
|
||||
{pickText(l.product.name, locale)}
|
||||
</span>
|
||||
<span className="shrink-0 text-sm text-[var(--text)]/60">
|
||||
${(l.product.price * l.qty).toFixed(2)}
|
||||
</span>
|
||||
<button onClick={() => setQty(l.product.id, -1)} className="px-2 text-lg" aria-label="−">
|
||||
−
|
||||
</button>
|
||||
<span className="w-5 text-center">{l.qty}</span>
|
||||
<button onClick={() => setQty(l.product.id, 1)} className="px-2 text-lg" aria-label="+">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
value={l.note ?? ''}
|
||||
onChange={(e) => setNote(l.product.id, e.target.value)}
|
||||
placeholder={t('itemNotePlaceholder')}
|
||||
className="rounded-xl bg-white/40 px-3 py-1.5 text-xs outline-none"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between px-1 text-sm">
|
||||
<span className="font-medium">{t('yourSubtotal')}</span>
|
||||
<span className="font-semibold">${yourSubtotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-1 text-sm">
|
||||
<span className="text-[var(--text)]/70">{t('tableTotal')}</span>
|
||||
<span className="font-semibold text-[var(--accent)]">${tableTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button onClick={onClose} className="glass-pill flex-1 rounded-2xl py-3 text-sm">
|
||||
{t('addDishes')}
|
||||
</button>
|
||||
<button
|
||||
onClick={sync}
|
||||
disabled={busy}
|
||||
className="flex-1 rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('updateSubaccount')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { OrderItem } from './types';
|
||||
|
||||
// Sanitize public/admin order item input into a safe OrderItem list.
|
||||
export function sanitizeItems(raw: unknown): OrderItem[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.map((r) => r as Record<string, unknown>)
|
||||
.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,
|
||||
}));
|
||||
}
|
||||
|
||||
function key(it: OrderItem): string {
|
||||
return `${it.productId}|${it.qty}|${it.note ?? ''}`;
|
||||
}
|
||||
|
||||
// Stamp items added in a later modification with addedAt, so the dashboard can
|
||||
// show "added X ago" for intermediate items without touching the order's main
|
||||
// timer. Items identical to a previous one keep their original addedAt (or stay
|
||||
// unstamped if they were part of the initial order).
|
||||
export function stampNewItems(
|
||||
prev: OrderItem[],
|
||||
next: OrderItem[],
|
||||
nowIso: string,
|
||||
): OrderItem[] {
|
||||
// Match previous items by content; consume matches so duplicates are handled.
|
||||
const prevByKey = new Map<string, OrderItem[]>();
|
||||
for (const p of prev) {
|
||||
const k = key(p);
|
||||
(prevByKey.get(k) ?? prevByKey.set(k, []).get(k)!).push(p);
|
||||
}
|
||||
return next.map((it) => {
|
||||
const bucket = prevByKey.get(key(it));
|
||||
const match = bucket && bucket.length ? bucket.shift() : undefined;
|
||||
if (match) return { ...it, addedAt: match.addedAt };
|
||||
return { ...it, addedAt: nowIso };
|
||||
});
|
||||
}
|
||||
|
||||
export function subtotal(items: OrderItem[]): number {
|
||||
return items.reduce((s, it) => s + (it.price ?? 0) * it.qty, 0);
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export type MenuSnapshot = {
|
||||
slug: string;
|
||||
palette: Palette;
|
||||
ordersEnabled: boolean;
|
||||
splitEnabled?: boolean;
|
||||
defaultLocale: Locale;
|
||||
showMacros: boolean;
|
||||
pairings?: Record<string, string[]>;
|
||||
@@ -71,4 +72,5 @@ export type OrderItem = {
|
||||
qty: number;
|
||||
note?: string;
|
||||
price?: number;
|
||||
addedAt?: string; // ISO time when added in a later modification (intermediate items)
|
||||
};
|
||||
Reference in new issue
Block a user