Add public cart feeding the existing orders/SSE system

Builds on the existing Order model + SSE dashboard (no parallel system).

Model: extend Order.items JSON to {productId,name,qty,note?,price?} and add
Order.note (general note) — migration 0005.

Public menu (only when orders are enabled):
- Add button on every dish in BOTH card and list views
- Dedicated floating cart FAB with an item-count badge
- Cart sheet: per-line qty +/- (0 removes), per-item note, per-line subtotal +
  total, a general order note, and required table number; confirm posts to the
  existing POST /order, shows a confirmation toast and clears the cart
- Cart lives in client state only (no localStorage)

Admin Orders tab:
- Shows per-item notes and the general note
- Edit mode: adjust quantities, edit per-item and general notes, and ADD dishes
  via a searchable dropdown over the restaurant's menu; saves through an extended
  PATCH /orders/[id] that updates items/note and broadcasts a new 'order-edit' SSE
  event so the dashboard updates live. Table number and timer (createdAt) preserved

order POST and PATCH sanitize/clamp incoming items (public + admin input).
i18n: cart/notes/total/confirm/search labels in es/en at parity. Glassmorphism,
mobile-first and safe areas preserved.

Endpoints/models: no new routes — POST /api/[slug]/order and PATCH
/api/[slug]/orders/[id] extended; Order model extended (items shape + note column,
migration 0005); new SSE event type 'order-edit'.

Verified: build passes; 5 migrations apply; order create persists qty/notes/price;
admin edit adds dishes + notes keeping table/timer; unauth edit 401.
This commit is contained in:
Jorem Juárez committed 2026-06-15 16:15:45 -06:00
1 parent 1d9498b6d5
commit 79cee9ebde
11 files changed
+422 -116

No files matched your search

+11 -1
View File
@@ -21,7 +21,13 @@
"viewFull": "View full menu",
"tableNumber": "Table number",
"send": "Send",
"addToOrder": "Add to order",
"addToOrder": "Add",
"cart": "Cart",
"cartEmpty": "Your cart is empty.",
"itemNotePlaceholder": "Note (e.g. no onion)",
"generalNotePlaceholder": "General order note (optional)",
"total": "Total",
"confirmOrder": "Confirm order",
"yourOrder": "Your order",
"empty": "No dishes in this section yet.",
"waiterCalled": "The waiter is on the way",
@@ -83,6 +89,10 @@
"ordersDisabled": "Order taking is disabled",
"enableOrders": "Enable order taking",
"completeOrder": "Complete order",
"itemNote": "Dish note",
"generalNote": "General note",
"searchDish": "Search a dish to add…",
"total": "Total",
"table": "Table",
"downloadQr": "Download QR",
"publicLink": "Public link",
+11 -1
View File
@@ -21,7 +21,13 @@
"viewFull": "Ver el menú completo",
"tableNumber": "Número de mesa",
"send": "Enviar",
"addToOrder": "Agregar al pedido",
"addToOrder": "Agregar",
"cart": "Carrito",
"cartEmpty": "Tu carrito está vacío.",
"itemNotePlaceholder": "Nota (ej. sin cebolla)",
"generalNotePlaceholder": "Nota general de la orden (opcional)",
"total": "Total",
"confirmOrder": "Confirmar orden",
"yourOrder": "Tu pedido",
"empty": "Aún no hay platillos en esta sección.",
"waiterCalled": "El mesero va en camino",
@@ -83,6 +89,10 @@
"ordersDisabled": "La toma de órdenes está desactivada",
"enableOrders": "Habilitar toma de órdenes",
"completeOrder": "Completar orden",
"itemNote": "Nota del platillo",
"generalNote": "Nota general",
"searchDish": "Buscar platillo para agregar…",
"total": "Total",
"table": "Mesa",
"downloadQr": "Descargar QR",
"publicLink": "Link público",
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Order" ADD COLUMN "note" TEXT;
+2 -1
View File
@@ -92,7 +92,8 @@ model Order {
id String @id @default(cuid())
restaurantId String
tableNumber Int
items Json // [{ productId, name, qty }]
items Json // [{ productId, name, qty, note?, price? }]
note String? // general note for the whole order
status String @default("active") // active | completed
createdAt DateTime @default(now())
completedAt DateTime?
+15 -1
View File
@@ -14,7 +14,20 @@ export async function POST(req: Request, { params }: { params: { slug: string }
const body = await req.json().catch(() => null);
const tableNumber = Number(body?.tableNumber);
const items: OrderItem[] = Array.isArray(body?.items) ? body.items : [];
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 note =
typeof body?.note === 'string' && body.note.trim() ? body.note.trim().slice(0, 500) : null;
if (!tableNumber || items.length === 0) {
return NextResponse.json({ error: 'invalid' }, { status: 400 });
}
@@ -24,6 +37,7 @@ export async function POST(req: Request, { params }: { params: { slug: string }
restaurantId: restaurant.id,
tableNumber,
items: items as unknown as object,
note,
status: 'active',
},
});
+44 -9
View File
@@ -2,8 +2,10 @@ import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { requireEditor } from '@/lib/guard';
import { publish } from '@/lib/orders-bus';
import type { OrderItem } from '@/lib/types';
// Complete (or otherwise update) an order.
// Complete an order, or edit it (admin: add/edit items and notes). The table
// number and createdAt (and therefore the timer) are never touched.
export async function PATCH(
req: Request,
{ params }: { params: { slug: string; id: string } },
@@ -11,17 +13,50 @@ export async function PATCH(
const guard = await requireEditor(params.slug);
if ('error' in guard) return guard.error;
const body = await req.json().catch(() => ({}));
const status = body?.status === 'completed' ? 'completed' : 'active';
const result = await prisma.order.updateMany({
const order = await prisma.order.findFirst({
where: { id: params.id, restaurantId: guard.restaurant.id },
data: { status, completedAt: status === 'completed' ? new Date() : null },
});
if (result.count === 0) return NextResponse.json({ error: 'not_found' }, { status: 404 });
if (!order) return NextResponse.json({ error: 'not_found' }, { status: 404 });
publish(params.slug, { type: 'order-update', data: { id: params.id, status } });
return NextResponse.json({ ok: true });
const body = await req.json().catch(() => ({}));
// Completion
if (body?.status === 'completed') {
await prisma.order.update({
where: { id: order.id },
data: { status: 'completed', completedAt: new Date() },
});
publish(params.slug, { type: 'order-update', data: { id: order.id, status: 'completed' } });
return NextResponse.json({ ok: true });
}
// 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,
}));
if (items.length === 0) return NextResponse.json({ error: 'invalid' }, { status: 400 });
data.items = items 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;
if (Object.keys(data).length === 0) {
return NextResponse.json({ error: 'invalid' }, { status: 400 });
}
const updated = await prisma.order.update({ where: { id: order.id }, data });
// Publish the full updated order so the dashboard reflects the edit live.
publish(params.slug, { type: 'order-edit', data: updated });
return NextResponse.json({ ok: true, order: updated });
}
export async function DELETE(
+1
View File
@@ -61,6 +61,7 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
slug={data.slug}
ordersEnabled={ordersEnabled}
setOrdersEnabled={setOrdersEnabled}
sections={sections}
/>
)}
{tab === 'qr' && (
+238 -58
View File
@@ -1,36 +1,52 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import type { Locale } from '@/i18n/config';
import type { OrderItem } from '@/lib/types';
import { pickText } from '@/lib/text';
import type { EditorSection } from './types';
import { api } from './api';
type Order = {
id: string;
tableNumber: number;
items: OrderItem[];
note?: string | null;
createdAt: string;
status: string;
};
type WaiterCall = { tableNumber: number; at: string };
type MenuOption = { id: string; name: string; price: number };
export default function OrdersTab({
slug,
ordersEnabled,
setOrdersEnabled,
sections,
}: {
slug: string;
ordersEnabled: boolean;
setOrdersEnabled: (v: boolean) => void;
sections: EditorSection[];
}) {
const t = useTranslations('editor');
const locale = useLocale() as Locale;
const [orders, setOrders] = useState<Order[]>([]);
const [waiterCalls, setWaiterCalls] = useState<WaiterCall[]>([]);
const [now, setNow] = useState(() => 0);
const esRef = useRef<EventSource | null>(null);
// Tick every second to drive timers (avoids Date in render init).
// 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);
@@ -42,18 +58,19 @@ export default function OrdersTab({
const es = new EventSource(`/api/${slug}/orders/stream`);
esRef.current = es;
es.addEventListener('snapshot', (e) => {
setOrders(JSON.parse((e as MessageEvent).data));
});
es.addEventListener('snapshot', (e) => setOrders(JSON.parse((e as MessageEvent).data)));
es.addEventListener('order', (e) => {
const order: Order = JSON.parse((e as MessageEvent).data);
setOrders((prev) => [...prev, order]);
setOrders((prev) => (prev.some((o) => o.id === order.id) ? prev : [...prev, order]));
});
es.addEventListener('order-update', (e) => {
const { id, status } = JSON.parse((e as MessageEvent).data);
setOrders((prev) =>
status === 'active' ? prev : prev.filter((o) => o.id !== id),
);
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)));
});
es.addEventListener('waiter', (e) => {
const call: WaiterCall = JSON.parse((e as MessageEvent).data);
@@ -79,7 +96,6 @@ export default function OrdersTab({
const m = Math.floor(secs / 60);
const s = secs % 60;
const label = `${m}:${s.toString().padStart(2, '0')}`;
// green → amber → red as time grows.
const color = secs < 300 ? '#15803d' : secs < 600 ? '#b45309' : '#dc2626';
return { label, color };
}
@@ -90,14 +106,10 @@ export default function OrdersTab({
<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'
}`}
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'
}`}
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${ordersEnabled ? 'left-6' : 'left-1'}`}
/>
</button>
</div>
@@ -113,10 +125,7 @@ export default function OrdersTab({
key={i}
className="animate-spawn flex items-center gap-2 rounded-2xl bg-amber-100/80 px-4 py-2 text-sm text-amber-800"
>
🔔{' '}
<strong>
{t('table')} {c.tableNumber}
</strong>
🔔 <strong>{t('table')} {c.tableNumber}</strong>
<button
onClick={() => setWaiterCalls((prev) => prev.filter((_, idx) => idx !== i))}
className="ml-auto"
@@ -130,45 +139,216 @@ export default function OrdersTab({
{ordersEnabled && (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{orders.map((o) => {
const e = elapsed(o.createdAt);
return (
<div key={o.id} className="animate-spawn glass relative rounded-3xl p-4">
<button
onClick={() => complete(o)}
className="absolute right-3 top-3 text-lg text-[var(--text)]/40"
aria-label={t('completeOrder')}
>
✕
</button>
<div className="flex items-center justify-between pr-6">
<span className="display text-lg font-semibold">
{t('table')} {o.tableNumber}
</span>
<span
className="rounded-full px-2 py-0.5 font-mono text-sm font-semibold text-white"
style={{ background: e.color }}
{orders.map((o) => (
<OrderCard
key={o.id}
order={o}
elapsed={elapsed(o.createdAt)}
menuOptions={menuOptions}
slug={slug}
onComplete={() => complete(o)}
/>
))}
</div>
)}
</div>
);
}
function OrderCard({
order,
elapsed,
menuOptions,
slug,
onComplete,
}: {
order: Order;
elapsed: { label: string; color: string };
menuOptions: MenuOption[];
slug: string;
onComplete: () => 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 [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 [];
return menuOptions.filter((m) => m.name.toLowerCase().includes(q)).slice(0, 8);
}, [search, menuOptions]);
function addDish(m: MenuOption) {
setItems((prev) => {
const ex = prev.find((it) => it.productId === m.id);
if (ex) return prev.map((it) => (it.productId === m.id ? { ...it, qty: it.qty + 1 } : it));
return [...prev, { productId: m.id, name: m.name, qty: 1, price: m.price, note: '' }];
});
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),
);
}
function setItemNote(i: number, v: string) {
setItems((prev) => prev.map((it, idx) => (idx === i ? { ...it, note: v } : it)));
}
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);
}
}
return (
<div className="animate-spawn glass relative rounded-3xl p-4">
<button
onClick={onComplete}
className="absolute right-3 top-3 text-lg text-[var(--text)]/40"
aria-label={t('completeOrder')}
>
✕
</button>
<div className="flex items-center justify-between 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 }}
>
{elapsed.label}
</span>
</div>
{!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>
{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>
)}
<div className="mt-3 flex gap-2">
<button
onClick={() => setEditing(true)}
className="glass-pill flex-1 rounded-2xl py-2 text-sm font-medium"
>
{t('edit')}
</button>
<button
onClick={onComplete}
className="flex-1 rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white"
>
{t('completeOrder')}
</button>
</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>
))}
{/* 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"
>
{e.label}
</span>
</div>
<ul className="mt-2 space-y-1 text-sm">
{o.items.map((it, idx) => (
<li key={idx} className="flex justify-between">
<span>{it.name}</span>
<span className="text-[var(--text)]/60">×{it.qty}</span>
</li>
))}
</ul>
<button
onClick={() => complete(o)}
className="mt-3 w-full rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white"
>
{t('completeOrder')}
</button>
<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>
<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>${total.toFixed(2)}</span>
</div>
<div className="flex gap-2">
<button
onClick={() => {
setEditing(false);
setItems(order.items);
setNote(order.note ?? '');
}}
className="glass-pill flex-1 rounded-2xl py-2 text-sm"
>
{tc('cancel')}
</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"
>
{t('save')}
</button>
</div>
</div>
)}
</div>
+26 -20
View File
@@ -34,17 +34,32 @@ export default function ListRow({
return (
<div className="glass-soft overflow-hidden rounded-2xl">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className="flex w-full items-center gap-3 px-4 py-3 text-left"
>
<span className="display min-w-0 flex-1 font-medium">{name}</span>
<span className="shrink-0 font-semibold text-[var(--accent)]">${product.price.toFixed(2)}</span>
<span className={`shrink-0 text-[var(--text)]/40 transition-transform ${open ? 'rotate-180' : ''}`}>
⌄
</span>
</button>
<div className="flex items-center gap-2 px-4 py-3">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className="flex min-w-0 flex-1 items-center gap-3 text-left"
>
<span className="display min-w-0 flex-1 font-medium">{name}</span>
<span className="shrink-0 font-semibold text-[var(--accent)]">
${product.price.toFixed(2)}
</span>
<span
className={`shrink-0 text-[var(--text)]/40 transition-transform ${open ? 'rotate-180' : ''}`}
>
⌄
</span>
</button>
{ordersEnabled && onAdd && (
<button
onClick={() => onAdd(product)}
aria-label={t('addToOrder')}
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--accent)] text-lg text-white"
>
+
</button>
)}
</div>
{/* allergen tags visible at a glance in the collapsed row */}
{product.allergens.length > 0 && (
@@ -85,15 +100,6 @@ export default function ListRow({
)}
{showMacros && macrosOpen && <MacrosBack macros={product.macros} />}
{ordersEnabled && onAdd && (
<button
onClick={() => onAdd(product)}
className="rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white"
>
{t('addToOrder')}
</button>
)}
</div>
)}
</div>
+65 -24
View File
@@ -14,7 +14,7 @@ import AiConsultant from './AiConsultant';
type ViewMode = 'cards' | 'list';
type CartLine = { product: SnapshotProduct; qty: number };
type CartLine = { product: SnapshotProduct; qty: number; note?: string };
export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: string }) {
const locale = useLocale() as Locale;
@@ -160,17 +160,6 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
<div className="safe-bottom-fab fixed left-1/2 z-30 flex -translate-x-1/2 flex-col items-center gap-3">
{actionsOpen && (
<div className="animate-spawn flex flex-col items-stretch gap-2">
{ordersEnabled && (
<button
onClick={() => {
setOrderOpen(true);
setActionsOpen(false);
}}
className="glass rounded-full px-5 py-3 text-sm font-medium"
>
{t('placeOrder')} {cartCount > 0 && `(${cartCount})`}
</button>
)}
<button
onClick={() => {
setWaiterOpen(true);
@@ -198,6 +187,20 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
>
✨ {t('askAi')}
</button>
{ordersEnabled && (
<button
onClick={() => setOrderOpen(true)}
className="relative flex h-12 items-center gap-2 rounded-full bg-[var(--accent)] px-5 text-sm font-semibold text-white shadow-lg"
aria-label={t('cart')}
>
🛒 {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>
)}
<button
onClick={() => setActionsOpen((o) => !o)}
className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--accent)] text-2xl text-white shadow-lg transition"
@@ -277,6 +280,7 @@ function OrderPanel({
const locale = useLocale() as Locale;
const t = useTranslations('menu');
const [table, setTable] = useState('');
const [generalNote, setGeneralNote] = useState('');
const [sending, setSending] = useState(false);
function setQty(id: string, delta: number) {
@@ -287,6 +291,12 @@ function OrderPanel({
);
}
function setNote(id: string, note: string) {
setCart((prev) => prev.map((l) => (l.product.id === id ? { ...l, note } : l)));
}
const total = cart.reduce((sum, l) => sum + l.product.price * l.qty, 0);
async function send() {
if (!table || cart.length === 0 || sending) return;
setSending(true);
@@ -296,10 +306,13 @@ function OrderPanel({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tableNumber: Number(table),
note: generalNote,
items: cart.map((l) => ({
productId: l.product.id,
name: pickText(l.product.name, locale),
qty: l.qty,
note: l.note,
price: l.product.price,
})),
}),
});
@@ -311,28 +324,56 @@ function OrderPanel({
return (
<Sheet title={t('yourOrder')} onClose={onClose}>
<div className="flex flex-col gap-2">
{cart.length === 0 && <p className="text-sm text-[var(--text)]/60">—</p>}
<div className="flex max-h-[45vh] flex-col gap-2 overflow-y-auto">
{cart.length === 0 && <p className="text-sm text-[var(--text)]/60">{t('cartEmpty')}</p>}
{cart.map((l) => (
<div key={l.product.id} className="glass-soft flex items-center gap-2 rounded-2xl px-3 py-2">
<span className="flex-1 text-sm">{pickText(l.product.name, locale)}</span>
<button onClick={() => setQty(l.product.id, -1)} className="px-2 text-lg">
−
</button>
<span className="w-5 text-center">{l.qty}</span>
<button onClick={() => setQty(l.product.id, 1)} className="px-2 text-lg">
+
</button>
<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>
{cart.length > 0 && (
<div className="flex items-center justify-between px-1 text-sm font-semibold">
<span>{t('total')}</span>
<span>${total.toFixed(2)}</span>
</div>
)}
<textarea
value={generalNote}
onChange={(e) => setGeneralNote(e.target.value)}
rows={2}
placeholder={t('generalNotePlaceholder')}
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('send')}
{t('confirmOrder')}
</button>
</Sheet>
);
+7 -1
View File
@@ -60,4 +60,10 @@ export type SnapshotProduct = {
translationStatus: TranslationStatus;
};
export type OrderItem = { productId: string; name: string; qty: number };
export type OrderItem = {
productId: string;
name: string;
qty: number;
note?: string;
price?: number;
};