Commit Graph
40 Commits
Author SHA1 Message Date
Jorem Juárez 4bec78597b Consultant: recolor the user question bubble to navy
The asked-question bubble used the red accent, which clashed with the sage-green
assistant bubble. Use navy #1e3a5f (brand blue, already used elsewhere) for a
harmonious chat look; the red accent stays on the CTAs (Add / send).
2026-06-29 13:30:36 -06:00
Jorem Juárez b0be66990f Cart: unify font size of bottom controls
The table-number input was text-lg and the dark action buttons (Confirm order,
split-subaccount buttons) had no size class (text-base), clashing with the text-sm
general-note field. Set all to text-sm so the bottom of the cart reads consistently.
2026-06-29 12:55:08 -06:00
Jorem Juárez cbb4a9e8ef Split panel: match font size of the two action buttons
'Actualizar mi subcuenta' had no text-size class (fell back to text-base) while
'Agregar platillos' was text-sm, so they looked inconsistent and the longer label
overflowed. Both are now text-sm font-medium.
2026-06-29 12:52:09 -06:00
Jorem Juárez 02a0163d60 Show dish thumbnail in split-bill subaccount line items
Same fix as the regular cart: the split-bill subaccount rows showed only name +
price + quantity. Render the dish photo as a thumbnail (MediaThumb, with the
plate-icon fallback).
2026-06-29 12:33:49 -06:00
Jorem Juárez 7933e35fc3 Show dish thumbnail in cart line items
The cart ('Tu pedido') line showed only name + price + quantity, no image. Render
the dish photo as a thumbnail (MediaThumb, with the plate-icon fallback when media
is missing or fails to load).
2026-06-29 12:29:30 -06:00
Jorem Juárez 9fd28d6059 Rename consultant CTA to 'mesero virtual' and use a neutral example prompt
- Button label: 'Preguntar a Claude' -> 'Preguntar al mesero virtual' (es) /
  'Ask the virtual waiter' (en).
- Consultant placeholder example: the diabetic example can be counterproductive for
  some restaurants -> neutral '¿Qué me recomiendas para hoy?' / 'What do you
  recommend today?'. es/en parity kept.
2026-06-29 11:49:11 -06:00
Collina SystemsandClaude Opus 4.8 cf6090d588 Restyle AI consultant ("Virtual waiter") to match new mockup
- Rename the consultant title to "Mesero virtual" / "Virtual waiter"
  (uppercased in the UI via CSS).
- Answer intro now shown in a sage-green card; recommendation dish names use
  the palette text color.
- Replace hardcoded navy (#1e3a5f) with var(--accent) across the consultant
  (asked bubble, recommendation "Add" button, send arrow) and the
  SuggestionCarousel "Add" button — all red under the current palette.
- More opaque modal surface for readability over the dimmed menu; dish
  thumbnails preserved in recommendations.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 20:05:37 -06:00
Jorem Juárez bae032aa75 Consultant: clear input on send and show the asked question above the answer
The question stayed in the input after sending. Now it clears automatically and the
submitted question appears as a chat bubble above the response, so the panel reads
like a normal prompt/chat (your message on top, the assistant's answer below).
2026-06-26 18:38:11 -06:00
Jorem Juárez 8cf6ca8cb5 Show dish thumbnails in AI consultant recommendations
The consultant cards (both direct recommendations and the 'Para acompañar'
complements) showed only name + reason. Each card already resolves the real
product for its Add button, so render its photo as a thumbnail (MediaThumb, which
falls back to the plate icon when media is missing or fails to load).
2026-06-26 18:33:59 -06:00
Jorem Juárez 595769ced0 Remove the Palette tab from the editor
The per-restaurant palette was retired in the redesign (menu colors are fixed), so
the Palette editor tab no longer affected anything. Removed the tab and its
PaletteTab component; the editor now has 4 tabs (Catalog, Brand, Orders, QR). The
Restaurant.palette value is kept because the QR tab still uses it for its color
templates.
2026-06-26 11:24:15 -06:00
Collina SystemsandClaude Opus 4.8 ffa8766540 Match popup panels exactly to mockups (3-color action system)
The button-triggered panels followed a coarse "primary = red" rule; the mockups
actually use: black for confirm actions, navy #1e3a5f for suggestions/AI recs,
khaki #e2db8d for "Translate", grey-blue #c8cbd8 for delete, red only for total
text and add-to-order/FAB/CTA.

- OrderPanel: Confirm/order/split-create buttons -> black #111; Total -> red;
  cart item qty stepper -> white pill (matches mockup).
- SuggestionCarousel: "Add" -> navy #1e3a5f; price -> black.
- AiConsultant: recommendation name + "Add" + send arrow -> navy #1e3a5f.
- SplitPanel: join/create + order buttons -> black #111.
- ProductEditor: Save -> black #111; Delete -> grey-blue #c8cbd8;
  "Translate with AI" -> khaki #e2db8d.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 18:02:21 -06:00
Collina SystemsandClaude Opus 4.8 bcec7ee8dc Hardcode fixed brand palette (retire per-restaurant palette)
Colors are now fixed from the design mockups instead of the per-restaurant
palette: white background, red #dc2626 accent. paletteToCssVars() ignores the
stored palette and always emits the fixed tokens (covers both the public and
editor pages), and globals.css :root matches. The palette editor section will
be removed separately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:22:42 -06:00
Collina SystemsandClaude Opus 4.8 58a71d0bef Apply full frontend redesign (Montserrat, red accent, glass + dock UI)
Fonts switched to Montserrat (UI) + Merriweather (landing wordmark). Macro
protein standard color updated to #dc2626; primary actions hardcoded red.
New globals.css primitives: ai-smoke gradient buttons, seg-btn, sticky
cat-bar, editor dock-*, macro shimmer, delivery-timer pulses, liquid-btn,
aurora, editable-num.

- Public: landing (video bg + red CTA), PublicMenu (segmented toggle +
  "Preguntar a Claude" + sticky category bar w/ scroll-spy + Order/Waiter/
  Split FABs), DishCard flip, MacrosBack shimmer, BrandHeader, SplitPanel,
  AiConsultant.
- Editor: bottom dock navigation, EditorLogin video background, BrandTab,
  CatalogTab (+SectionTitleEditor), VersionHistory, OrdersTab, ProductEditor.
- Admin: AdminLogin, AdminPanel.
- Add landing/editor background videos under public/videos.
- ES/EN i18n keys added; FRONTEND.md updated; design mockups included.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:03:06 -06:00
Jorem Juárez ceac688fa8 Add cost dashboard to the master panel (tokens + storage, USD/MXN)
Superadmin view in /admin showing operating cost with per-restaurant breakdown.

Models (migration 0012):
- TokenUsage(restaurantId?, model, feature, inputTokens, outputTokens, createdAt)
- ModelPrice(model, inputPricePerMTok, outputPricePerMTok, updatedAt) — seeded
  Haiku 4.5 1/5, Sonnet 4.6 3/15, Opus 4.8 5/25 (USD per million)
- PriceUpdateLog(model, old/new input+output, source, createdAt)
- ExchangeRate(date, rate) — daily USD→MXN cache
- AppConfig(key,value) — seeded costPerGb=0

B1 Instrumentation: recordUsage() (fire-and-forget) logs every Anthropic call with
its model/feature/restaurant and the response usage tokens — wired into the
consultor (ai-consult), translation, and menu import. restaurantId null = Collina
operational.

B2 Price update: 'Update prices from Anthropic' button → fetches the public pricing
page, Haiku extracts prices FROM THE PAGE TEXT ONLY (omits any not found), updates
ModelPrice and writes a PriceUpdateLog (old→new). If the fetch is blocked, the UI
offers a manual paste box processed the same way. These calls log as
feature 'precios-update', restaurantId null.

B3 Exchange: getUsdMxn() caches once/day via Frankfurter (no key); on failure falls
back to the last stored rate, then a constant — never /bin/zsh; shows the rate's date.

B4 Storage: measures GB per restaurant from /data/uploads/{slug}; configurable
costPerGb (editable) projects a storage cost.

B5 Dashboard (CostsDashboard): month total in USD + MXN, per-restaurant token cost
(USD/MXN) + GB + projected storage cost, average per active restaurant, a separate
'Operativo Collina' line for restaurantId-null calls, and context (exchange rate +
date, last price update). i18n es/en at parity.

Verified (build passes; migration 0012 applies; seeds present): a usage row records
model/tokens/restaurant; dashboard shows USD + MXN with the day's rate (Frankfurter
live 17.21, cached); token cost math correct (/bin/zsh.04 for 20k/4k Haiku); storage GB +
projected cost with cost/GB=0.10; operational calls isolated; price endpoint guarded
(401) and graceful without key (502); PriceUpdateLog records old→new.
2026-06-18 07:27:46 -06:00
Jorem Juárez c82c0f2108 Show full dish description on public cards (no truncation)
The card description was clamped to 2 lines with an ellipsis. Removed the
line-clamp so it shows in full and the card grows to fit (the flip front face is
in normal flow, so it already drives card height; the back is the absolute
overlay). Added whitespace-pre-line to honor line breaks.

Grid uses items-start so cards of different heights render at their natural height
(rows align to the tallest) instead of being stretched with awkward gaps. List
view already shows the full description on expand — unchanged.
2026-06-16 12:50:07 -06:00
Jorem Juárez 14e2f73db9 Carousel: random sample (reshuffles per open), dedup vs consultant, broken-image fallback
1) getRecommendations is now a RANDOM sample of the whole active menu, lightly
   refined by complement rules (a +0.25 nudge toward wanted categories that can't
   beat a strong random draw — variety dominates, all sections surface). New
   opts.seed re-randomizes per open; opts.excludeIds filters extra ids. Signature
   and the CoOccurrence Phase-2 seam are unchanged. Never returns empty unless the
   whole menu is excluded.
2) PublicMenu passes a buildSuggestions(seed, excludeIds) callback instead of a
   memoized list. OrderPanel and AiConsultant each seed on mount (Date.now()), so
   reopening reshuffles. The consultant excludes the dishes it already showed above
   (answer.recommendations resolved to ids) → no more carousel/answer duplicates
   (fixes the Combo Aguacate dup).
3) MediaThumb adds onError on <img>/<video> → a 404/broken file falls back to the
   🍽️ icon, same as missing media.

Verified: build passes; reopening yields a different sample (same seed stable);
sample spans all sections; consultant picks + cart items excluded; never empty.
2026-06-15 21:36:37 -06:00
Jorem Juárez 2bd7da0839 Remove macro color-code legend from the public menu
The 'Código de color de macros' collapsible bar took prominent space for secondary
info that's already self-explanatory on each card's back (full text labels like
'Proteína 19g' next to their color). Removed it from the toggle row in both views;
the row is justify-end so the cards/list view toggle reflows cleanly with no gap.
Dropped the now-unused MacroLegend component and the anyMacros computation. The
macro text labels on the card backs are unchanged.

Build passes.
2026-06-15 21:13:10 -06:00
Jorem Juárez da2c0113e0 Tweak landing subtitle copy
'Menús digitales que tus comensales reconocen en cualquier restaurante.' ->
'Menús digitales que entienden a tus comensales.'
2026-06-15 20:48:14 -06:00
Jorem Juárez 0d924e36ef Replace AI pairings with a deterministic local recommendation engine
The cart/consultant suggestion carousel no longer depends on Claude-generated
pairings. It now computes suggestions locally and instantly from the menu
structure + cart — always available, zero API calls, zero cost, no failure point.

- New lib/recommendations.ts: getRecommendations(menu, cartItemIds, opts) — a pure
  function. Section-complement rules (main+no drink -> drinks; food+no dessert ->
  desserts; drink-only -> food/snacks) classified by flexible keywords (es/en,
  whole-word match so 'te'/tea doesn't match 'fuertes'), then featured fill
  (unrepresented sections first, then price desc). Excludes cart items + inactive;
  empty cart -> featured so the carousel is never empty.
- Phase-2 seam: opts.coOccurrence?(cartIds) => Map<productId, score> lets a future
  market-basket signal blend in WITHOUT changing the carousel — it still only calls
  getRecommendations(menu, cart). Documented where it plugs in.
- PublicMenu computes cartSuggestions via getRecommendations (was the pairings map);
  carousel shows whenever there's >=1 suggestion and orders are enabled, in both the
  cart sheet and the consultant. SuggestionCarousel reused unchanged.
- Removed the Claude generation: publish no longer calls generatePairings and the
  'Generar sugerencias' checkbox is gone; deleted lib/pairings.ts. Restaurant.pairings
  column kept (unused, no migration churn).

i18n parity kept. Glassmorphism/mobile-first/safe-areas untouched. Cart, consultant,
SSE, split all intact.

Verified (build passes, no Anthropic import in the carousel/publish path):
1 fresh publish (nothing generated) -> carousel shows; 2 main+no drink -> drinks
surface first; 3 cart items never suggested; 4 empty cart -> featured; 5 zero
Anthropic calls in the carousel flow; 6 carousel in both cart and consultant.
2026-06-15 20:47:20 -06:00
Jorem Juárez b30430a1ea Premium minimalist landing page (brand + single CTA)
Replaces the generic card at / with a single-screen, centered brand moment:

- Brand animation: 'SmartMenu' rises in as the protagonist (bold sans, Smart in
  ink + Menu in terracotta), then a delicate Fraunces-italic 'by Collina'
  signature fades in surrounded by soft twinkling SVG sparkles (Magic-UI style),
  over a slow radial brand glow. Pure CSS keyframes + inline SVG — no animation
  libs, no extra deps; stays light (first thing a prospect loads).
- Single sales CTA 'Solicita una demo' → /demo placeholder (flow designed later).
- Easter egg: the admin panel has no visible button; tapping the 'by Collina'
  signature navigates to /admin (discreet <a aria-label=Collina href=/admin>).
- Accessible: prefers-reduced-motion shows the final state (no sequence, sparkles
  static). Responsive mobile→desktop. Uses the existing warm Collina palette.

Verified: build passes; / returns 200 with the wordmark, sparkles, demo CTA, and
the Collina→/admin link; reduced-motion CSS present in the bundle.
2026-06-15 20:36:00 -06:00
Jorem Juárez 8fc95c3cab Split re-identification: pick subaccount when re-ordering on a split table
When a diner confirms an order on a table that's already split, the cart now asks
which subaccount they belong to instead of blindly creating a parallel one.

- New GET /split/subaccounts?table — lists active subaccounts (id + full name).
- New GET /split/mine?id — returns a subaccount's items so the client can rebuild
  its cart.
- OrderPanel (normal cart) on a split table shows '¿Quién eres?' with a tappable
  button per active subaccount + 'Soy nuevo':
  * pick existing → load that subaccount's items, merge the new items, and sync;
    reconcileItems keeps the existing batches and turns the new items into a fresh
    batch (independent timer). Existing items' timers are not reset.
  * 'Soy nuevo' → name input → creates a new subaccount seeded with the cart.
- Continuity: once a diner has a split session, the normal cart FAB is replaced by
  'Mi cuenta' (existing behavior), so the selector never reappears for that session
  — no localStorage, just in-memory session state.

i18n es/en (whoAreYou, imNew) at parity. Build passes.

Verified criterion 7: table 5 with Ana+Beto → a third order lists [Ana][Beto]
[Soy nuevo]; tapping Ana adds the order to Ana as a NEW batch (2 distinct batchIds,
the new batch starts now, Ana's prior item keeps its ~30-min-old start).
2026-06-15 20:01:14 -06:00
Jorem Juárez 8004d51f7b Unify tables/orders/split: table accounts, batches, per-item delivery timers
Unifies the model: a table is ALWAYS one account; every active Order on a table
number is a subaccount (named or not) — no more 'normal vs split table'.

Total convergence (fixes the bug): the dashboard groups ALL active orders by
tableNumber into one card; two normal orders on the same table now share one table
card with two subaccounts. (POST /order already converges split too.)

Batches: items sent together share a batchId + batchAt; later additions form a new
batch. reconcileItems() carries id/batch/delivered for matched lines and opens one
new batch for new lines. (OrderItem is embedded JSON, so its new fields — id,
batchId, batchAt, delivered, deliveredAt — need no migration.)

Per-item timer + delivery: each item runs from its batch start; 'Entregado' freezes
that item's timer (deliveredAt) while siblings keep running. Color thresholds are
per-restaurant (timerGreenMax/timerYellowMax, migration 0011) and editable in the
Orders tab; each item colors green/yellow/red by its own minutes.

Independent states: delivered (per item, kitchen) vs paid (per subaccount, billing).
Admin can rename a subaccount inline (PATCH subaccountName). All live via SSE;
retention unchanged.

i18n es/en at parity. Glassmorphism/mobile-first/safe areas preserved. Cart,
maridajes and consultant untouched.

New: Restaurant.timerGreenMax/timerYellowMax (migration 0011); OrderItem JSON gains
id/batchId/batchAt/delivered/deliveredAt (no migration); PATCH orders/[id] gains
deliverItemId+delivered and subaccountName; settings + GET /orders carry thresholds.

Verified (build passes, all i18n present, migration 0011 applies):
1 two normal orders table 7 -> one card, two subaccounts;
2 lote A (30m ago) red + lote B (now) green, two batches;
3 deliver A1 -> frozen w/ deliveredAt, A2 keeps running;
4 thresholds 5/15 persist and return via GET /orders;
5 paid toggles independent of delivered (and vice versa);
6 rename '(table)' -> 'Juan' persists + SSE order-edit carries it.
2026-06-15 19:42:44 -06:00
Jorem Juárez ac08731aaf Fix split convergence: normal order on a split table must not coexist
A diner ordering 'normally' on a table that was already in split created a parallel
non-split Order, so the dashboard showed two cards for the same table (e.g. 'Mesa 11
· Dividida' + a separate 'Mesa 11'). That violates convergence.

- order POST: if the table already has an active split order, the new order is
  created with split=true (joins as an unnamed '(table)' subaccount) instead of a
  parallel normal order.
- OrdersTab: a table is treated as split if ANY of its active orders is split, and
  every active order on that table renders under the single split card — so legacy/
  race stray orders never get their own card.

Verified: split table 11 + a normal order on 11 → the normal order becomes split=t,
zero non-split active orders remain, table-status stays 'split'. Build passes.
2026-06-15 19:11:44 -06:00
Jorem Juárez 1dfdecb262 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.
2026-06-15 18:43:57 -06:00
Jorem Juárez 6cda59387c Public menu UX fixes: brand header, FABs, consultant add/carousel, modal safe-area
B1 brand header: shorter banner (h-36), avatar centered over the banner's lower
edge (z-10, no clipping/layout push), and a compact name-only header when neither
banner nor logo is set (no giant gray gradient block). Banner stays edge-to-edge
behind the island when an image exists.

B2 FABs: reorganized into an ordered bottom-right vertical stack that never
overlaps each other or covers dish names/prices; the global 'more' button is now a
distinct ⋯ (was a '+', which clashed with the per-dish add '+'). Container
padding-bottom raised (pb-48) so the last dish is never hidden behind the FABs.

B3 consultant add-to-cart: each recommendation (direct and complement) resolves to
a real product by name and shows an 'Agregar' button that adds to the shared cart
(badge updates) — only when orders are enabled.

B4 consultant carousel: reuses SuggestionCarousel at the bottom of the consultant,
contextual to the cart, only when orders are on and pairings exist.

B5 safe-area: new .safe-modal padding (top+bottom env insets) on the consultant and
cart sheets so content clears the island and gesture bar; layout unchanged.

Suggestion computation + name resolution lifted into PublicMenu and shared by the
cart and consultant (no duplicated logic). No new i18n keys. Build passes; public
page renders in both header modes with no runtime errors.
2026-06-15 18:01:07 -06:00
Jorem Juárez 244adaee30 Orders persistence/expiration, cart pairings, and brand header
BLOCK 1 — Orders persistence + expiration:
- New GET /api/[slug]/orders loads active orders from PostgreSQL on mount, so the
  dashboard survives reloads (SSE only carries live events); it also prunes
  completed orders older than the retention window on read (no cron)
- Restaurant.orderRetentionHours (default 24, migration 0007) + editor control in
  the Orders tab; settings PATCH accepts it

BLOCK 2 — Smart cart pairings (precomputed, zero tokens at runtime):
- Restaurant.pairings JSON (migration 0008) stores { productId: [productId] }
- Optional 'Generate smart suggestions' checkbox in the publish modal; on publish,
  one cheap Haiku call analyzes the snapshot and stores validated complements
  (lib/pairings.ts, reuses parseLenientJson). AI failure never breaks publishing
- pairings read live and exposed via the public menu; cart shows an auto-rotating,
  swipeable SuggestionCarousel of complements for what's in the cart (excluding
  items already added), each with Add — only when orders are on and pairings exist

BLOCK 3 — Brand header:
- Restaurant.bannerImage, profileImage, socialLinks (migration 0009)
- New editor Brand tab: upload banner + circular logo (reuses /upload), social
  links with common-platform suggestions and basic URL validation; saved via settings
- Public BrandHeader: full-bleed banner (edge-to-edge behind the island, safe-area
  aware), circular logo avatar, name, and clickable social icons (lucide-react).
  Graceful fallbacks (palette gradient banner, initial avatar) — no broken images.
  Images are language-independent

All read live (no republish needed). i18n es/en at parity; glassmorphism,
mobile-first and safe areas preserved. Adds lucide-react.

Verified: build passes; 9 migrations apply; orders persist + prune on read;
publish survives missing API key; pairings + brand exposed via /menu.
2026-06-15 17:25:35 -06:00
Jorem Juárez 57a9b191bd Fix section macros toggle not persisting (stale value in setState updater)
The per-section macros toggle read 'next' inside the setSections updater callback,
which React runs during the render phase — after the synchronous PATCH had already
fired. So 'next' stayed at its initial 'true', and turning a section OFF sent
showMacros:true to the server: the DB never became false while the editor UI
flipped, so the public kept showing that section's macros even though it looked off.

Fix: compute 'next' from the current sections state before calling setSections, and
PATCH that value. The public hierarchy (global AND section) and applyLiveSectionMacros
were already correct.

Verified: build passes; global ON + a section toggled OFF now persists showMacros=f
in the DB and /menu returns that section showMacros:false, so its dishes hide macros.
2026-06-15 17:04:50 -06:00
Jorem Juárez e4e8c50438 Relocate macros toggle and add per-section macros control
- Move the global 'Show macros' toggle from the Palette tab to the Catalog tab,
  next to 'Cargar menú', where catalog assembly lives
- Section.showMacros boolean (default true) + migration 0006; existing sections
  default to showing (so turning the global on shows all by default)
- Per-section toggle in the editor, visible only when the global toggle is on
- Hierarchy: global wins. A dish shows macros only if Restaurant.showMacros AND
  its Section.showMacros are both true. Applies to card flip, list tap-image, the
  gallery, and the color-code legend (legend shows only if some visible section does)
- Turning the global off only HIDES — macro data is never deleted; the disclaimer
  is reassuring ('Macros will stop showing to the public, but they are not deleted')
- Live read: global + per-section showMacros are overlaid onto the published
  snapshot at read time (new applyLiveSectionMacros helper) so toggles take effect
  instantly without republishing; old snapshots default section macros on
- sections PATCH accepts showMacros; settings PATCH still handles the global
- i18n: sectionMacros + soft disclaimer (es/en parity); hint reworded

Verified: build passes; 6 migrations apply; section toggle persists; /menu reflects
the global+section hierarchy live; macro data preserved in DB and API when toggled off.
2026-06-15 16:26:27 -06:00
Jorem Juárez 79cee9ebde 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.
2026-06-15 16:15:45 -06:00
Jorem Juárez 1d9498b6d5 Make AI consultant distinguish direct vs complement recommendations
The consultant could surface an unrelated dish as if it directly answered the
request. Now each recommendation is classified and presented accordingly.

- Prompt: model classifies each recommendation as type 'direct' (answers what was
  asked) or 'complement' (pairs with it). Direct first and primary; complements
  are optional and never used to pad to a count. Reasons must be anchored to a real
  dish attribute or the dish isn't recommended. If nothing matches directly, the
  intro says so gracefully instead of inventing a false direct match.
- Route: parse/validate the type (defaults to 'direct' if missing), keep existing
  existence validation, order direct-first then complements, cap at 3.
- UI: AiConsultant renders direct cards first, then a 'Para acompañar' / 'To pair
  with' header before complements (glassmorphism preserved).
- i18n: ai.pairWith in es/en (parity); the type field itself is internal, not translated.

Keeps prompt caching and the compact menu context. Verified: build passes; parser
orders direct-first, drops non-existent dishes, defaults missing type to direct.
2026-06-15 15:15:35 -06:00
Jorem Juárez c001550e4f Optimize and harden the AI consultant
A) Token optimization:
- Prompt caching: the stable block (system instructions + full menu) is now a
  single cached system text block with cache_control:ephemeral and goes first;
  the variable diner question stays in messages, after the cache breakpoint, so
  the cached prefix is byte-identical between queries of the same restaurant/locale
- Compact context: only name, price, short description (<=120 chars), diet tags
  and allergens; macros are omitted (rarely change a recommendation). Inactive
  dishes still skipped

B) Hardening:
- Validate existence: each recommended dish must match a real active menu name
  (accent/case/space-insensitive, both locales); non-existent dishes are dropped
- Fewer than 3 valid is fine — return what's valid, never pad with non-fitting dishes
- Robust parsing: reuse the import's tolerant parser (extractJson +
  repairTruncatedJson, now shared in lib/json.ts) so truncated/prose replies don't 502
- max_tokens 700 -> 900 and system prompt asks for one-sentence reasons

Refactor: repairTruncatedJson + parseLenientJson moved into lib/json.ts and shared
by import.ts and ai-consult. No behavior change to import.

Verified: build passes; existence filter drops fake dishes, recovers truncated+prose
replies, and returns <3 without padding.
2026-06-15 15:08:56 -06:00
Jorem Juárez 084a191061 Add per-restaurant macros toggle and public list view
Feature 1 — showMacros toggle:
- Restaurant.showMacros boolean (default false) so existing menus (e.g. NOCNEX)
  never publish with empty macros (migration 0004; default applies to existing rows)
- Editor toggle in the Palette tab, saved via the existing /settings endpoint
- Read live (not from the snapshot) in the public page and /menu API so it takes
  effect immediately without republishing; old snapshots default off
- When off, the public menu hides every macro layer: card flip + 'tap to see
  macros', the gallery macros, and the macro color-code legend

Feature 2 — public list view:
- Card/list toggle in the public menu; preference is NOT persisted (always starts
  on cards)
- New ListRow: compact traditional rows (name + price + allergen tags); tap the
  name to expand image + description (accordion); tap the image to reveal macros
  (only when showMacros is on)

i18n: viewCards/viewList (menu) and showMacros/showMacrosHint (editor) in es/en at parity.
Glassmorphism, mobile-first and safe areas preserved. Existing features untouched
(versioning, import, consultant, QR, i18n).

Verified: build passes; 4 migrations apply in order; existing rows default false;
toggling via /settings updates /menu live without republish.
2026-06-15 14:32:44 -06:00
Jorem Juárez d71ede3d00 Edge-to-edge mobile layout with safe-area insets
The public menu (and editor) left a non-matching rectangular gap around the
iPhone notch / dynamic island. Make the glassmorphism background go edge-to-edge
while keeping interactive content clear of the unsafe regions.

- viewport-fit=cover so the layout uses the full screen incl. behind the island
- Safe-area utility classes (globals.css) built on env(safe-area-inset-*); they
  resolve to 0 on devices without insets, preserving previous spacing
- Public menu: header padding-top, sticky section tabs offset, and floating
  action buttons (Ask AI / +) respect top/bottom insets
- Editor: header padding-top and bottom tab bar respect top/bottom insets

Verified: build passes; all safe-area classes survive Tailwind purge; rendered
meta tag emits viewport-fit=cover.
2026-06-15 13:46:27 -06:00
Jorem Juárez 9fad1d43aa Harden menu import: tolerate truncated JSON + reject oversized files
Bug 1 (malformed/truncated JSON crashed the route with SyntaxError):
- Raise extraction max_tokens 4000 -> 8000 and ask the model for compact, complete JSON
- Parse tolerantly: extractJson() for fences/prose, plus a repair pass that closes
  open strings/brackets and drops a trailing partial entry for token-truncated output
- Wrap JSON.parse; on failure return a friendly code (parse_failed, or output_truncated
  when stop_reason was max_tokens) instead of a raw 500

Bug 2 (40MB PDF -> Anthropic 413):
- Validate visual file size BEFORE calling the API (max 4.5MB raw; base64 inflates ~33%)
- Return 413 {error:file_too_large, maxMb} so the UI shows 'max X MB, compress or use text/link'

i18n: file_too_large (with {mb}), parse_failed, output_truncated (es/en); ImportModal
interpolates the size limit.

Verified: build passes; repair recovers mid-string/mid-property/fenced/prose JSON;
oversized upload returns 413 with the limit; text path fails gracefully (no crash).
2026-06-14 02:14:40 -06:00
Jorem Juárez 9a40a988e0 Add artistic QR (templates + customization) with qr-code-styling
Editor QR tab now generates a styled, scannable QR with live preview and clean
PNG/SVG export (no frame or text — the owner lays it out).

- Restaurant.qrConfig JSON persists the styling (migration 0003)
- qr-code-styling (MIT) runs client-side in QrTab: preview + WYSIWYG PNG (2048px)
  and vector SVG export, avoiding native canvas deps in the alpine image
- Controls: dots color/gradient, background (incl. transparent), corners color,
  dot & corner shapes, optional center logo (uploaded via /upload, capped at 20%)
- Scannability: error correction forced to 'H' whenever there's a logo or color;
  WCAG contrast check warns on low contrast; persistent 'verify before printing' notice
- Templates inherit the menu palette but every value is independently editable
- QR always targets {APP_BASE_URL}/{slug}
- PATCH /api/[slug]/qr saves config; GET stays as a config-aware server fallback
- i18n (es/en) for the qr namespace; glassmorphism, mobile-first

Verified: build passes; migration 0003 applies; PATCH persists qrConfig; GET
honors saved colors/ECC (png + colored svg); auth guard returns 401.
2026-06-14 02:00:45 -06:00
Jorem Juárez d6ffbbd60b Fix missing i18n keys in editor (save/edit/delete)
ProductEditor and CatalogTab use t('save'/'edit'/'delete') from the editor
namespace, but those keys only existed in the common namespace, so the UI showed
raw keys (editor.save, editor.delete). Add them to messages/es.json and en.json.

Audited every useTranslations call across src/ against both catalogs: no other
unresolved keys, and es/en are at full key parity.
2026-06-13 20:47:00 -06:00
Jorem Juárez 112e95dc28 Add AI smart menu import (Cargar menú)
Import a menu from PDF, photo, Excel/CSV, web link, or pasted text and turn it
into draft sections + products with Claude.

- Product.aiEstimated JSON flags AI-inferred macros/allergens (migration 0002)
- POST /api/[slug]/import: resolves the source (vision via Sonnet for PDF/photo,
  Haiku for text/CSV/XLSX/web), extracts structured JSON for review only
- POST /api/[slug]/import/apply: writes to the draft in add or replace mode,
  preserving aiEstimated flags; replace wipes the draft first
- Editor: 'Cargar menú' button + glass ImportModal (method -> review -> add/replace),
  'Estimado por IA — verifica' badges, verification disclaimer; ProductEditor shows
  the badge and clears the flag when the value is edited
- Reuses anthropic.ts, upload/guard, shared extractJson (moved to lib/json.ts)
- i18n labels (es/en); adds xlsx dependency for spreadsheet parsing

Verified: build passes; migration applies; apply add/replace persist correctly
with aiEstimated; extract validation + auth guard behave as expected.
2026-06-13 20:43:06 -06:00
Jorem Juárez 24a412f793 Fix Prisma migrate deploy in standalone production image
The entrypoint invoked the node_modules/.bin/prisma symlink, so Node resolved the
CLI's bundled .wasm files relative to .bin/ and crashed with ENOENT on
prisma_schema_build_bg.wasm. Call the real CLI entry (node_modules/prisma/build/
index.js) instead so the wasm resolves under prisma/build/. Also add the
linux-musl-openssl-3.0.x binaryTarget so the runtime engine matches the alpine
runner regardless of build host arch.

Verified end-to-end in a built alpine image: migrate deploy applies, and the
Prisma client reads/writes against Postgres at runtime.
2026-06-13 20:13:21 -06:00
Jorem Juárez fc12ff5f02 Add public/ directory so Dockerfile COPY succeeds
Next.js standalone build copies /app/public; the folder was empty and untracked,
breaking the Docker build. Keep it in the repo via .gitkeep.
2026-06-13 19:59:25 -06:00
Jorem Juárez 5fb9c7a145 Initial build: Menú inteligente platform
Multi-tenant digital menu platform (Collina Systems): public QR menu with
glassmorphism + 3D macro flip cards, mobile-first editor with draft/publish
versioning (5-version history + restore), AI consultant & translation (Claude
Haiku), realtime orders via SSE, configurable palette, QR generation, superadmin
panel, and Docker/Coolify infra.
2026-06-13 19:33:00 -06:00