@fayz-ai/plugin-tables 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,15 @@
1
1
  import { TablesContextProvider } from './chunk-XHRPH676.js';
2
- import React from 'react';
2
+ import React3 from 'react';
3
3
  import { createStore } from 'zustand/vanilla';
4
4
  import { PluginSettingsPanel, dedup } from '@fayz-ai/admin';
5
5
  import { toast } from 'sonner';
6
- import { registerComponent, getSupabaseClientOptional } from '@fayz-ai/core';
6
+ import { cancelReplayResults, fixedDiscountShares, legacyKindOfChannel, openingServiceCharge, registerComponent, resolveDataProvider, getSupabaseClientOptional, getActiveTenantId, getActiveUnitId } from '@fayz-ai/core';
7
7
  import { createFayzClient } from '@fayz-ai/sdk';
8
+ import { settle } from '@fayz-ai/core/orders';
9
+ import { Search, ChevronDown, ChevronRight, Utensils } from 'lucide-react';
10
+ import '@fayz-ai/core/interaction';
11
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
12
+ import { Skeleton, Input, Checkbox, Badge } from '@fayz-ai/ui';
8
13
 
9
14
  // src/data/mock.ts
10
15
  var uid = 0;
@@ -698,7 +703,8 @@ function createTablesStore(provider) {
698
703
  try {
699
704
  await provider.cancelLines(order.id, input);
700
705
  await get().refreshAfterWrite();
701
- toast.success(input.lineIds.length === 1 ? "Item cancelado" : `${input.lineIds.length} itens cancelados`);
706
+ const n = input.lines.length;
707
+ toast.success(n === 1 ? "Item cancelado" : `${n} itens cancelados`);
702
708
  } catch (err) {
703
709
  toast.error("N\xE3o foi poss\xEDvel cancelar", { description: err?.message });
704
710
  }
@@ -1362,6 +1368,8 @@ var GUESTS = "plg_tables_order_guests";
1362
1368
  var ITEM_GUESTS = "plg_tables_item_guests";
1363
1369
  var CANCEL_REASONS = "plg_tables_cancel_reasons";
1364
1370
  var SERVICE_PRESETS = "plg_tables_service_charge_presets";
1371
+ var DISCOUNT_GRANTS = "plg_financial_discount_grants";
1372
+ var DISCOUNT_REASONS = "plg_financial_discount_reasons";
1365
1373
  var SERVICE_EXEMPTIONS = "plg_tables_service_charge_exemptions";
1366
1374
  var COVER_CHARGES = "plg_tables_cover_charges";
1367
1375
  var COVER_ZONES = "plg_tables_cover_charge_zones";
@@ -1369,6 +1377,16 @@ var COVER_SCHEDULES = "plg_tables_cover_charge_schedules";
1369
1377
  var SPINE_CATEGORIES = "categories";
1370
1378
  var TRANSFERS = "plg_tables_order_transfers";
1371
1379
  var GUESTS_VIEW = "v_comanda_guests";
1380
+ var FISCAL_DOCS = "plg_fiscalbr_documents";
1381
+ var AUTHORIZERS = "v_comanda_authorizers";
1382
+ var SERVICE_AUDIT = "plg_tables_service_charge_audit";
1383
+ var AREA_STAFF = "plg_tables_service_area_staff";
1384
+ var ORDER_PAYMENTS = "plg_tables_order_payments";
1385
+ var ORDER_COVERS = "plg_tables_order_cover_charges";
1386
+ var COURTESY = "plg_tables_courtesy_events";
1387
+ var AREAS = "plg_tables_service_areas";
1388
+ var AREA_TABLES = "plg_tables_service_area_tables";
1389
+ var WAITLIST = "plg_tables_waitlist";
1372
1390
  var BALANCES = "v_invoice_balances";
1373
1391
  var SECTIONS = "plg_menu_sections";
1374
1392
  var PLACEMENTS = "plg_menu_placements";
@@ -1407,6 +1425,15 @@ function createCoreTablesProvider(options) {
1407
1425
  function shortRef(orderId) {
1408
1426
  return orderId ? `#${String(orderId).slice(0, 8)}` : void 0;
1409
1427
  }
1428
+ function assertTocou(linhas, oQue) {
1429
+ if (!Array.isArray(linhas) || linhas.length === 0) {
1430
+ throw new Error(`Nenhuma linha foi atualizada ao gravar ${oQue}. Verifique as permiss\xF5es.`);
1431
+ }
1432
+ }
1433
+ function politicaDe(r) {
1434
+ const p = r?.[COVER_CHARGES];
1435
+ return Array.isArray(p) ? p[0] : p;
1436
+ }
1410
1437
  function num(value) {
1411
1438
  return Number(value) || 0;
1412
1439
  }
@@ -1457,8 +1484,13 @@ function createCoreTablesProvider(options) {
1457
1484
  total: num(r.total),
1458
1485
  notes: typeof meta.kitchenNotes === "string" ? meta.kitchenNotes : void 0,
1459
1486
  guestId: r.guest_id ?? void 0,
1487
+ createdAt: r.created_at ?? void 0,
1460
1488
  cancelledAt: r.cancelled_at ?? void 0,
1461
- cancelReason: r.cancel_reason ?? void 0
1489
+ cancelReason: r.cancel_reason ?? void 0,
1490
+ // O MESMO critério do banco: `comanda_item_is_service_exempt` reconhece
1491
+ // o couvert por este campo do metadata, e não pelo produto — a linha do
1492
+ // couvert não tem produto nenhum.
1493
+ ...meta.cover_charge_id ? { isCoverCharge: true } : {}
1462
1494
  };
1463
1495
  }
1464
1496
  function rowToGuest(r) {
@@ -1471,7 +1503,24 @@ function createCoreTablesProvider(options) {
1471
1503
  subtotal: num(r.subtotal),
1472
1504
  serviceCharge: num(r.service_charge),
1473
1505
  cancelledTotal: num(r.cancelled_total),
1474
- itemCount: Number(r.item_count) || 0
1506
+ itemCount: Number(r.item_count) || 0,
1507
+ phone: r.phone ?? void 0,
1508
+ personId: r.person_id ?? void 0,
1509
+ paidTotal: num(r.paid_total),
1510
+ settled: r.settlement_status === "settled",
1511
+ // Só quem fechou tem conta congelada. `settled_total` ausente quer dizer
1512
+ // que o fechamento nunca aconteceu — e sem ele os outros quatro números
1513
+ // não descrevem pagamento nenhum.
1514
+ settledBill: r.settled_total == null ? void 0 : {
1515
+ items: num(r.settled_items_total),
1516
+ shared: num(r.settled_shared_total),
1517
+ cover: num(r.settled_cover_total),
1518
+ service: num(r.settled_service_total),
1519
+ discount: num(r.settled_discount_total),
1520
+ total: num(r.settled_total),
1521
+ paid: num(r.paid_total),
1522
+ at: r.settled_at ?? void 0
1523
+ }
1475
1524
  };
1476
1525
  }
1477
1526
  async function recalc(orderId) {
@@ -1488,9 +1537,30 @@ function createCoreTablesProvider(options) {
1488
1537
  status: r.status ?? "available",
1489
1538
  zone: r.zone_id ?? "",
1490
1539
  zoneName: r.zone_name ?? void 0,
1540
+ unitId: r.unit_id ?? null,
1491
1541
  shape: r.shape ?? "square",
1492
1542
  gridCol: Number(r.grid_col) || 0,
1493
1543
  gridRow: Number(r.grid_row) || 0,
1544
+ // ── O LUGAR REAL, em metros ─────────────────────────────────────────
1545
+ // `gridCol/gridRow` é a maquete: a mesa fica na célula que o cadastro
1546
+ // deu. Isto é onde ela ESTÁ no salão. Duzentas das duzentas e oito mesas
1547
+ // do Pertinho já tinham coordenada; ela nunca chegou à tela porque a
1548
+ // `v_tables` parava antes — o motor pronto e a porta faltando, de novo.
1549
+ // `null` (e não zero) é o que distingue "ainda não desenhada" de "está
1550
+ // na origem".
1551
+ posX: r.pos_x != null ? num(r.pos_x) : null,
1552
+ posY: r.pos_y != null ? num(r.pos_y) : null,
1553
+ rotation: r.rotation != null ? num(r.rotation) : null,
1554
+ widthM: r.width_m != null ? num(r.width_m) : null,
1555
+ heightM: r.height_m != null ? num(r.height_m) : null,
1556
+ diameterM: r.diameter_m != null ? num(r.diameter_m) : null,
1557
+ // O ambiente como FORMA — a origem a que `posX`/`posY` se referem.
1558
+ zoneShape: r.zone_shape ?? null,
1559
+ zonePosX: r.zone_pos_x != null ? num(r.zone_pos_x) : null,
1560
+ zonePosY: r.zone_pos_y != null ? num(r.zone_pos_y) : null,
1561
+ zoneWidthM: r.zone_width_m != null ? num(r.zone_width_m) : null,
1562
+ zoneHeightM: r.zone_height_m != null ? num(r.zone_height_m) : null,
1563
+ zonePolygon: r.zone_polygon ?? null,
1494
1564
  isActive: r.is_active !== false,
1495
1565
  // The session IS the comanda, so the two ids are deliberately the same:
1496
1566
  // closing one closes the other, and there is no third row to disagree.
@@ -1503,18 +1573,98 @@ function createCoreTablesProvider(options) {
1503
1573
  currentGuests: r.current_guests ?? void 0,
1504
1574
  currentElapsedMinutes: r.current_order_id ? elapsed : void 0,
1505
1575
  currentTotal: r.current_order_id ? Number(r.current_total) || 0 : void 0,
1576
+ // `null` quando a comanda existe e não tem item — e isso é um FATO, não
1577
+ // ignorância: a mesa conta «parada» desde a abertura.
1578
+ // A abertura CRUA, sem passar por minutos. Ver `currentOpenedAt`.
1579
+ currentOpenedAt: r.current_order_id ? r.seated_at ?? null : void 0,
1580
+ currentLastItemAt: r.current_order_id ? r.last_item_at ?? null : void 0,
1581
+ currentBillRequestedAt: r.current_order_id ? r.bill_requested_at ?? null : void 0,
1506
1582
  tenantId: r.tenant_id,
1507
1583
  createdAt: r.created_at,
1508
1584
  updatedAt: r.updated_at
1509
1585
  };
1510
1586
  }
1587
+ async function carregarComanda(row, order) {
1588
+ const [
1589
+ { data: lines, error: linesError },
1590
+ { data: people },
1591
+ { data: guestRows, error: guestsError },
1592
+ { data: balance }
1593
+ ] = await Promise.all([
1594
+ // `cancelled_at` e `cancel_reason` entram no select: a linha cancelada
1595
+ // CONTINUA na comanda, riscada. Filtrá-la aqui esconderia justamente o
1596
+ // que o gerente abre a comanda para ver.
1597
+ db().from(LINES).select("id, product_id, name, quantity, unit_price, discount, total, sort_order, metadata, cancelled_at, cancel_reason, created_at").eq("order_id", order.id).order("sort_order"),
1598
+ order.assignee_id || order.party_id ? db().from("people").select("id, name").in("id", [order.assignee_id, order.party_id].filter(Boolean)) : Promise.resolve({ data: [] }),
1599
+ db().from(GUESTS_VIEW).select("*").eq("order_id", order.id).order("seat_no"),
1600
+ db().from(BALANCES).select("paid, balance").eq("invoice_id", order.id).maybeSingle()
1601
+ ]);
1602
+ if (linesError) throw new Error(linesError.message);
1603
+ const idsDasLinhas = (lines ?? []).map((l) => l.id);
1604
+ const { data: itemGuests } = idsDasLinhas.length > 0 ? await db().from(ITEM_GUESTS).select("item_id, guest_id").in("item_id", idsDasLinhas) : { data: [] };
1605
+ const nameById = new Map((people ?? []).map((p) => [p.id, p.name]));
1606
+ const guestOfItem = new Map(
1607
+ (itemGuests ?? []).map((r) => [r.item_id, r.guest_id])
1608
+ );
1609
+ return {
1610
+ id: order.id,
1611
+ reference: order.reference_number ?? shortRef(order.id),
1612
+ status: order.status,
1613
+ guests: row.guests ?? 0,
1614
+ seatedAt: row.seated_at,
1615
+ notes: order.notes ?? void 0,
1616
+ waiterId: order.assignee_id ?? void 0,
1617
+ waiterName: order.assignee_id ? nameById.get(order.assignee_id) : void 0,
1618
+ partyName: order.party_id ? nameById.get(order.party_id) : void 0,
1619
+ lines: (lines ?? []).map((l) => rowToLine({ ...l, guest_id: guestOfItem.get(l.id) ?? null })),
1620
+ participants: (guestRows ?? []).map(rowToGuest),
1621
+ // NÃO DEU PARA LER QUEM JÁ QUITOU.
1622
+ //
1623
+ // A vista dos participantes ficava dentro do `Promise.all` com o erro
1624
+ // DESCARTADO — só o das linhas era conferido. Falhando (RLS, rede, a
1625
+ // vista ausente), a comanda era montada **sem participante nenhum**,
1626
+ // sem uma palavra, e a folha de taxa passava a oferecer todo mundo.
1627
+ //
1628
+ // A regra do V1 é dura e é sobre dinheiro: a taxa incide POR
1629
+ // PARTICIPANTE, e sem a lista de quitados a folha mostra como
1630
+ // disponível quem já fechou a conta. Ele avisa
1631
+ // («Não foi possível conferir os participantes quitados…») e TRAVA o
1632
+ // salvar. Para travar, a tela precisa saber — e é isto que atravessa.
1633
+ guestsUnavailable: guestsError ? true : void 0,
1634
+ serviceChargePercent: row.service_charge_percent == null ? void 0 : num(row.service_charge_percent),
1635
+ subtotal: num(order.subtotal),
1636
+ discount: num(order.discount),
1637
+ tax: num(order.tax),
1638
+ total: num(order.total),
1639
+ // Sem fatura levantada ainda, nada foi pago e tudo é devido. É a
1640
+ // resposta certa e não um buraco: a comanda aberta é, por definição,
1641
+ // dinheiro a receber.
1642
+ paid: num(balance?.paid),
1643
+ due: balance ? num(balance.balance) : num(order.total),
1644
+ currency: order.currency ?? "BRL"
1645
+ };
1646
+ }
1511
1647
  async function loadTables(query) {
1512
1648
  let q = db().from(VIEW).select("*").order("number");
1649
+ if (query?.activeOnly) q = q.neq("is_active", false);
1513
1650
  if (query?.zone) q = q.eq("zone_id", query.zone);
1514
1651
  if (query?.search) q = q.ilike("name", `%${query.search}%`);
1515
1652
  const { data, error } = await q;
1516
1653
  if (error) throw new Error(error.message);
1517
1654
  let tables = (data ?? []).map(rowToTable2);
1655
+ try {
1656
+ const abertas = await openSeatings();
1657
+ const porMesa = /* @__PURE__ */ new Map();
1658
+ for (const r of abertas) {
1659
+ if (!r.table_id) continue;
1660
+ porMesa.set(r.table_id, (porMesa.get(r.table_id) ?? 0) + 1);
1661
+ }
1662
+ tables = tables.map((t) => {
1663
+ const n = porMesa.get(t.id) ?? 0;
1664
+ return n > 0 ? { ...t, openOrdersCount: n } : t;
1665
+ });
1666
+ } catch {
1667
+ }
1518
1668
  if (query?.status) {
1519
1669
  const wanted = Array.isArray(query.status) ? query.status : [query.status];
1520
1670
  tables = tables.filter((t) => wanted.includes(t.status));
@@ -1533,6 +1683,11 @@ function createCoreTablesProvider(options) {
1533
1683
  if (error) throw new Error(error.message);
1534
1684
  return data ?? [];
1535
1685
  }
1686
+ function nomeDeCliente(nome) {
1687
+ const limpo = nome?.trim();
1688
+ if (!limpo) return null;
1689
+ return /^consumidor n[ãa]o identificado$/i.test(limpo) ? null : limpo;
1690
+ }
1536
1691
  function rowToSession(r, tableName) {
1537
1692
  const order = Array.isArray(r.orders) ? r.orders[0] : r.orders;
1538
1693
  const closed = order && ["completed", "cancelled"].includes(order.status);
@@ -1583,32 +1738,42 @@ function createCoreTablesProvider(options) {
1583
1738
  if (data.gridCol !== void 0) patch.grid_col = data.gridCol;
1584
1739
  if (data.gridRow !== void 0) patch.grid_row = data.gridRow;
1585
1740
  if (data.isActive !== void 0) patch.is_active = data.isActive;
1741
+ if (data.posX !== void 0) patch.pos_x = data.posX;
1742
+ if (data.posY !== void 0) patch.pos_y = data.posY;
1743
+ if (data.rotation !== void 0) patch.rotation = data.rotation;
1744
+ if (data.widthM !== void 0) patch.width_m = data.widthM;
1745
+ if (data.heightM !== void 0) patch.height_m = data.heightM;
1746
+ if (data.diameterM !== void 0) patch.diameter_m = data.diameterM;
1586
1747
  if (data.status !== void 0 && data.status !== "occupied") patch.status = data.status;
1587
1748
  if (Object.keys(patch).length) {
1588
- const { error } = await db().from(TABLES).update(patch).eq("id", id);
1749
+ const { data: mudadas, error } = await db().from(TABLES).update(patch).eq("id", id).select("id");
1589
1750
  if (error) throw new Error(error.message);
1751
+ assertTocou(mudadas, "a altera\xE7\xE3o da mesa");
1590
1752
  }
1591
1753
  return tableById(id);
1592
1754
  },
1593
1755
  async deleteTable(id) {
1594
1756
  requireWrites();
1595
- const { error } = await db().from(TABLES).delete().eq("id", id);
1757
+ const { data: apagadas, error } = await db().from(TABLES).delete().eq("id", id).select("id");
1596
1758
  if (error) throw new Error(error.message);
1759
+ assertTocou(apagadas, "a remo\xE7\xE3o da mesa");
1597
1760
  },
1598
1761
  async updateTableStatus(input) {
1599
1762
  requireWrites();
1600
1763
  if (input.status === "occupied") {
1601
1764
  throw new Error('Uma mesa fica ocupada ao abrir a comanda \u2014 use "sentar" em vez de marcar o estado.');
1602
1765
  }
1603
- const { error } = await db().from(TABLES).update({ status: input.status }).eq("id", input.tableId);
1766
+ const { data: mudadas, error } = await db().from(TABLES).update({ status: input.status }).eq("id", input.tableId).select("id");
1604
1767
  if (error) throw new Error(error.message);
1768
+ assertTocou(mudadas, "a mudan\xE7a de estado da mesa");
1605
1769
  return tableById(input.tableId);
1606
1770
  },
1607
1771
  async updateTablePositions(positions) {
1608
1772
  requireWrites();
1609
1773
  for (const p of positions) {
1610
- const { error } = await db().from(TABLES).update({ grid_col: p.gridCol, grid_row: p.gridRow }).eq("id", p.id);
1774
+ const { data: mudadas, error } = await db().from(TABLES).update({ grid_col: p.gridCol, grid_row: p.gridRow }).eq("id", p.id).select("id");
1611
1775
  if (error) throw new Error(error.message);
1776
+ assertTocou(mudadas, "a nova posi\xE7\xE3o da mesa");
1612
1777
  }
1613
1778
  },
1614
1779
  async seatGuests(input) {
@@ -1629,11 +1794,25 @@ function createCoreTablesProvider(options) {
1629
1794
  currency: "BRL"
1630
1795
  }).select("id, status, notes, assignee_id").single();
1631
1796
  if (error) throw new Error(error.message);
1797
+ const [{ data: politica }, { data: taxasCadastradas }] = await Promise.all([
1798
+ db().from(SETTINGS).select("service_charge_percent").eq("tenant_id", tenantId).maybeSingle(),
1799
+ db().from(SERVICE_PRESETS).select("percent, is_active, is_default, position").eq("tenant_id", tenantId)
1800
+ ]);
1801
+ const taxaVigente = openingServiceCharge(
1802
+ (taxasCadastradas ?? []).map((r) => ({
1803
+ percent: num(r.percent),
1804
+ isActive: r.is_active !== false,
1805
+ isDefault: r.is_default === true,
1806
+ position: Number(r.position) || 0
1807
+ })),
1808
+ politica?.service_charge_percent
1809
+ );
1632
1810
  const { data: ext, error: extError } = await db().from(ORDER_EXT).insert({
1633
1811
  order_id: order.id,
1634
1812
  tenant_id: tenantId,
1635
1813
  table_id: input.tableId,
1636
- guests: input.guests
1814
+ guests: input.guests,
1815
+ service_charge_percent: taxaVigente
1637
1816
  }).select("order_id, table_id, guests, seated_at, tenant_id").single();
1638
1817
  if (extError) {
1639
1818
  await db().from("orders").delete().eq("id", order.id);
@@ -1641,6 +1820,23 @@ function createCoreTablesProvider(options) {
1641
1820
  }
1642
1821
  return rowToSession({ ...ext, orders: order }, table.name);
1643
1822
  },
1823
+ async reopenComanda(orderId) {
1824
+ requireWrites();
1825
+ const { data, error } = await db().from("orders").update({ status: "confirmed" }).eq("id", orderId).select("id, status");
1826
+ if (error) throw new Error(error.message);
1827
+ const ok = (data ?? []).some((r) => r.status === "confirmed");
1828
+ if (!ok) throw new Error("O servidor n\xE3o confirmou a reabertura.");
1829
+ const { data: faturas } = await db().from("plg_financial_invoices").select("id").eq("order_id", orderId).is("cancelled_at", null);
1830
+ for (const f of faturas ?? []) {
1831
+ const { count } = await db().from("plg_financial_movements").select("id", { count: "exact", head: true }).eq("financial_invoice_id", f.id).eq("movement_kind", "payment");
1832
+ if ((count ?? 0) > 0) continue;
1833
+ await db().rpc("financial_cancel_invoice", {
1834
+ p_invoice_id: f.id,
1835
+ p_reason: "Comanda reaberta",
1836
+ p_idempotency_key: `reopen:${orderId}:${f.id}`
1837
+ });
1838
+ }
1839
+ },
1644
1840
  async closeSession(sessionId) {
1645
1841
  requireWrites();
1646
1842
  const { data: order, error } = await db().from("orders").update({ status: "completed" }).eq("id", sessionId).select("id, status, notes, assignee_id").single();
@@ -1648,6 +1844,53 @@ function createCoreTablesProvider(options) {
1648
1844
  const { data: ext } = await db().from(ORDER_EXT).select("order_id, table_id, guests, seated_at, tenant_id").eq("order_id", sessionId).maybeSingle();
1649
1845
  return rowToSession({ ...ext ?? { order_id: sessionId }, orders: order });
1650
1846
  },
1847
+ /**
1848
+ * Fechar RECEBENDO — o que faltava para o dinheiro do PDV existir.
1849
+ *
1850
+ * `closeSession` acima escreve `status = 'completed'` e mais nada. A mesa
1851
+ * se libera, o operador vê «Fechar conta» dar certo, e nenhum centavo
1852
+ * entra no razão: em 29-09, de 6 comandas fechadas no Pertinho, 1 tinha
1853
+ * pagamento. A tela até PERGUNTA a forma, a conta e as parcelas — e
1854
+ * `closeBill` descartava as três, que é pior que não perguntar, porque
1855
+ * quem responde acredita que ficou registrado.
1856
+ *
1857
+ * `settle` de `@fayz-ai/core/orders` é a sequência que o PDV, o totem e
1858
+ * qualquer coisa que venda executam igual: completa o pedido, o gatilho
1859
+ * `orders_raise_receivable_on_close` levanta a fatura na mesma transação,
1860
+ * e `financial_receive_payment` baixa a parcela com chave de idempotência
1861
+ * — o mesmo botão apertado duas vezes não cobra duas vezes.
1862
+ *
1863
+ * A fatura VOLTA mesmo quando o pagamento não baixa. O recebível é real
1864
+ * dos dois jeitos, e a mesa já fechou; esconder isso deixaria a casa com
1865
+ * uma conta que ninguém sabe que existe.
1866
+ */
1867
+ async settleSession(sessionId, payment) {
1868
+ const tenantId = tenant();
1869
+ try {
1870
+ const { invoice, paid, warning, replayed } = await settle(
1871
+ { db: db(), tenantId, source: "pos:salao" },
1872
+ sessionId,
1873
+ {
1874
+ method: payment.method,
1875
+ amountCents: payment.amountCents,
1876
+ accountId: payment.accountId,
1877
+ cardBrand: payment.cardBrand,
1878
+ cardInstallments: payment.cardInstallments,
1879
+ // Dinheiro sem caixa aberto: o `core` abre um com abertura ZERO.
1880
+ //
1881
+ // Mas só para quem TEM o privilégio — é a regra do
1882
+ // `useSettlementGate` do V1, onde a permissão geral quita sem
1883
+ // caixa e o caixinha exige o próprio. Mandando `true` para todos,
1884
+ // a recepção abria um caixa fantasma sem perceber.
1885
+ openCashSession: payment.mayOpenCashSession === true
1886
+ }
1887
+ );
1888
+ return { invoiceNumber: invoice?.number ?? null, paid, warning, replayed };
1889
+ } catch (e) {
1890
+ const msg = e instanceof Error ? e.message : String(e);
1891
+ return { invoiceNumber: null, paid: false, warning: `A comanda fechou, mas o pagamento n\xE3o foi registrado: ${msg}` };
1892
+ }
1893
+ },
1651
1894
  async getActiveSessions() {
1652
1895
  const [rows, tables] = await Promise.all([openSeatings(), loadTables()]);
1653
1896
  const names = new Map(tables.map((t) => [t.id, t.name]));
@@ -1671,7 +1914,16 @@ function createCoreTablesProvider(options) {
1671
1914
  sortOrder: z.sort_order ?? 0,
1672
1915
  isActive: z.is_active !== false,
1673
1916
  tenantId: z.tenant_id,
1674
- createdAt: z.created_at
1917
+ createdAt: z.created_at,
1918
+ // A FORMA do ambiente. `null` quando ninguém desenhou — e é essa
1919
+ // ausência que faz a planta cair para a maquete em vez de abrir num
1920
+ // salão em branco.
1921
+ shape: z.shape ?? null,
1922
+ posX: z.pos_x != null ? num(z.pos_x) : null,
1923
+ posY: z.pos_y != null ? num(z.pos_y) : null,
1924
+ widthM: z.width_m != null ? num(z.width_m) : null,
1925
+ heightM: z.height_m != null ? num(z.height_m) : null,
1926
+ polygon: z.polygon ?? null
1675
1927
  }));
1676
1928
  },
1677
1929
  async createZone(data) {
@@ -1700,6 +1952,12 @@ function createCoreTablesProvider(options) {
1700
1952
  if (data.color !== void 0) patch.color = data.color;
1701
1953
  if (data.sortOrder !== void 0) patch.sort_order = data.sortOrder;
1702
1954
  if (data.isActive !== void 0) patch.is_active = data.isActive;
1955
+ if (data.shape !== void 0) patch.shape = data.shape;
1956
+ if (data.posX !== void 0) patch.pos_x = data.posX;
1957
+ if (data.posY !== void 0) patch.pos_y = data.posY;
1958
+ if (data.widthM !== void 0) patch.width_m = data.widthM;
1959
+ if (data.heightM !== void 0) patch.height_m = data.heightM;
1960
+ if (data.polygon !== void 0) patch.polygon = data.polygon;
1703
1961
  const { data: row, error } = await db().from(ZONES).update(patch).eq("id", id).select("*").single();
1704
1962
  if (error) throw new Error(error.message);
1705
1963
  return {
@@ -1714,61 +1972,32 @@ function createCoreTablesProvider(options) {
1714
1972
  },
1715
1973
  async deleteZone(id) {
1716
1974
  requireWrites();
1717
- const { error } = await db().from(ZONES).delete().eq("id", id);
1975
+ const { data: apagados, error } = await db().from(ZONES).delete().eq("id", id).select("id");
1718
1976
  if (error) throw new Error(error.message);
1977
+ assertTocou(apagados, "a remo\xE7\xE3o do ambiente");
1719
1978
  },
1720
1979
  // -- The comanda ---------------------------------------------------------
1980
+ /**
1981
+ * A comanda de um CANAL, pelo id do pedido.
1982
+ *
1983
+ * `getTableOrder` parte de `ORDER_EXT.table_id`, e a comanda de balcão tem
1984
+ * `table_id` nulo — por isso ela não tinha leitor. O efeito era uma conta
1985
+ * aberta no banco que o PDV não conseguia mostrar depois de um recarregamento:
1986
+ * o dinheiro existia e ninguém alcançava para fechar.
1987
+ */
1988
+ async getOrderById(orderId) {
1989
+ const { data, error } = await db().from(ORDER_EXT).select("order_id, guests, seated_at, service_charge_percent, orders!inner(id, reference_number, status, notes, assignee_id, party_id, subtotal, discount, tax, total, currency)").eq("order_id", orderId).not("orders.status", "in", '("completed","cancelled")').limit(1);
1990
+ if (error) throw new Error(error.message);
1991
+ const row = (data ?? [])[0];
1992
+ if (!row) return null;
1993
+ return carregarComanda(row, Array.isArray(row.orders) ? row.orders[0] : row.orders);
1994
+ },
1721
1995
  async getTableOrder(tableId) {
1722
1996
  const { data, error } = await db().from(ORDER_EXT).select("order_id, guests, seated_at, service_charge_percent, orders!inner(id, reference_number, status, notes, assignee_id, party_id, subtotal, discount, tax, total, currency)").eq("table_id", tableId).not("orders.status", "in", '("completed","cancelled")').order("seated_at", { ascending: false }).limit(1);
1723
1997
  if (error) throw new Error(error.message);
1724
1998
  const row = (data ?? [])[0];
1725
1999
  if (!row) return null;
1726
- const order = Array.isArray(row.orders) ? row.orders[0] : row.orders;
1727
- const [
1728
- { data: lines, error: linesError },
1729
- { data: people },
1730
- { data: guestRows },
1731
- { data: itemGuests },
1732
- { data: balance }
1733
- ] = await Promise.all([
1734
- // `cancelled_at` e `cancel_reason` entram no select: a linha cancelada
1735
- // CONTINUA na comanda, riscada. Filtrá-la aqui esconderia justamente o
1736
- // que o gerente abre a comanda para ver.
1737
- db().from(LINES).select("id, product_id, name, quantity, unit_price, discount, total, sort_order, metadata, cancelled_at, cancel_reason").eq("order_id", order.id).order("sort_order"),
1738
- order.assignee_id || order.party_id ? db().from("people").select("id, name").in("id", [order.assignee_id, order.party_id].filter(Boolean)) : Promise.resolve({ data: [] }),
1739
- db().from(GUESTS_VIEW).select("*").eq("order_id", order.id).order("seat_no"),
1740
- db().from(ITEM_GUESTS).select("item_id, guest_id"),
1741
- db().from(BALANCES).select("paid, balance").eq("invoice_id", order.id).maybeSingle()
1742
- ]);
1743
- if (linesError) throw new Error(linesError.message);
1744
- const nameById = new Map((people ?? []).map((p) => [p.id, p.name]));
1745
- const guestOfItem = new Map(
1746
- (itemGuests ?? []).map((r) => [r.item_id, r.guest_id])
1747
- );
1748
- return {
1749
- id: order.id,
1750
- reference: order.reference_number ?? shortRef(order.id),
1751
- status: order.status,
1752
- guests: row.guests ?? 0,
1753
- seatedAt: row.seated_at,
1754
- notes: order.notes ?? void 0,
1755
- waiterId: order.assignee_id ?? void 0,
1756
- waiterName: order.assignee_id ? nameById.get(order.assignee_id) : void 0,
1757
- partyName: order.party_id ? nameById.get(order.party_id) : void 0,
1758
- lines: (lines ?? []).map((l) => rowToLine({ ...l, guest_id: guestOfItem.get(l.id) ?? null })),
1759
- participants: (guestRows ?? []).map(rowToGuest),
1760
- serviceChargePercent: row.service_charge_percent == null ? void 0 : num(row.service_charge_percent),
1761
- subtotal: num(order.subtotal),
1762
- discount: num(order.discount),
1763
- tax: num(order.tax),
1764
- total: num(order.total),
1765
- // Sem fatura levantada ainda, nada foi pago e tudo é devido. É a
1766
- // resposta certa e não um buraco: a comanda aberta é, por definição,
1767
- // dinheiro a receber.
1768
- paid: num(balance?.paid),
1769
- due: balance ? num(balance.balance) : num(order.total),
1770
- currency: order.currency ?? "BRL"
1771
- };
2000
+ return carregarComanda(row, Array.isArray(row.orders) ? row.orders[0] : row.orders);
1772
2001
  },
1773
2002
  async getMenuCategories() {
1774
2003
  const sections = await db().from(SECTIONS).select("id, name, sort_order").eq("is_active", true).order("sort_order");
@@ -1823,8 +2052,16 @@ function createCoreTablesProvider(options) {
1823
2052
  imageUrl: r.image_url ?? void 0
1824
2053
  }));
1825
2054
  },
2055
+ /** Devolve o ID DA LINHA no banco: a tela cria a sua com um id local e
2056
+ * precisa trocá-lo, senão cancelar essa linha manda `line-1` para uma
2057
+ * coluna uuid. */
1826
2058
  async addOrderLine(orderId, input) {
1827
2059
  const tenantId = tenant();
2060
+ if (input.idempotencyKey) {
2061
+ const { data: jaEntrou } = await db().from(LINES).select("id, metadata").eq("order_id", orderId);
2062
+ const igual = (jaEntrou ?? []).find((r) => (r.metadata ?? {}).line_key === input.idempotencyKey);
2063
+ if (igual) return igual.id;
2064
+ }
1828
2065
  const { count } = await db().from(LINES).select("id", { count: "exact", head: true }).eq("order_id", orderId);
1829
2066
  const { data, error } = await db().from(LINES).insert({
1830
2067
  tenant_id: tenantId,
@@ -1836,7 +2073,10 @@ function createCoreTablesProvider(options) {
1836
2073
  discount: 0,
1837
2074
  total: input.unitPrice * input.quantity,
1838
2075
  sort_order: count ?? 0,
1839
- metadata: input.notes ? { kitchenNotes: input.notes } : {}
2076
+ metadata: {
2077
+ ...input.notes ? { kitchenNotes: input.notes } : {},
2078
+ ...input.idempotencyKey ? { line_key: input.idempotencyKey } : {}
2079
+ }
1840
2080
  }).select("id").single();
1841
2081
  if (error) throw new Error(error.message);
1842
2082
  if (input.guestId && data?.id) {
@@ -1848,6 +2088,7 @@ function createCoreTablesProvider(options) {
1848
2088
  if (linkError) throw new Error(linkError.message);
1849
2089
  }
1850
2090
  await recalc(orderId);
2091
+ return data?.id;
1851
2092
  },
1852
2093
  async setOrderLineQuantity(lineId, quantity) {
1853
2094
  requireWrites();
@@ -1858,11 +2099,12 @@ function createCoreTablesProvider(options) {
1858
2099
  const { error: delError } = await db().from(LINES).delete().eq("id", lineId);
1859
2100
  if (delError) throw new Error(delError.message);
1860
2101
  } else {
1861
- const { error: upError } = await db().from(LINES).update({
2102
+ const { data: ajustadas, error: upError } = await db().from(LINES).update({
1862
2103
  quantity,
1863
2104
  total: num(line.unit_price) * quantity - num(line.discount)
1864
- }).eq("id", lineId);
2105
+ }).eq("id", lineId).select("id");
1865
2106
  if (upError) throw new Error(upError.message);
2107
+ assertTocou(ajustadas, "a nova quantidade do item");
1866
2108
  }
1867
2109
  await recalc(line.order_id);
1868
2110
  },
@@ -1898,8 +2140,758 @@ function createCoreTablesProvider(options) {
1898
2140
  const { error } = await db().from(SETTINGS).upsert(row, { onConflict: "tenant_id" });
1899
2141
  if (error) throw new Error(error.message);
1900
2142
  },
2143
+ /**
2144
+ * As comandas fechadas HOJE.
2145
+ *
2146
+ * "Hoje" é o dia OPERACIONAL, não o calendário: a casa vira o dia às 06:00,
2147
+ * e quem fecha a conta às 02:00 de domingo fechou no sábado. Cortar à
2148
+ * meia-noite esvaziaria a lista bem no pico da madrugada, que é justamente
2149
+ * quando o caixa mais a consulta.
2150
+ */
2151
+ async getClosedComandas(channel) {
2152
+ const { data: corte } = await db().rpc("comanda_next_day_cutoff");
2153
+ const inicio = corte ? new Date(new Date(corte).getTime() - 24 * 36e5).toISOString() : new Date(Date.now() - 24 * 36e5).toISOString();
2154
+ let q = db().from("orders").select(`id, total, completed_at, updated_at, channel, kind,
2155
+ ${ORDER_EXT}(table_id, ${TABLES}(number, name)), people:party_id(name)`).eq("status", "completed").gte("updated_at", inicio).order("updated_at", { ascending: false }).limit(60);
2156
+ if (channel) q = q.eq("channel", channel);
2157
+ const { data, error } = await q;
2158
+ if (error) throw new Error(error.message);
2159
+ const ids = (data ?? []).map((r) => r.id);
2160
+ const pagamentos = /* @__PURE__ */ new Map();
2161
+ const notas = /* @__PURE__ */ new Map();
2162
+ const consolidadas = /* @__PURE__ */ new Set();
2163
+ const cortesias = /* @__PURE__ */ new Set();
2164
+ let cortesiasOk = true;
2165
+ let selosOk = true;
2166
+ if (ids.length > 0) {
2167
+ try {
2168
+ const { data: cs, error: error2 } = await db().from(COURTESY).select("order_id").in("order_id", ids);
2169
+ if (error2) throw new Error("cortesia");
2170
+ for (const c of cs ?? []) cortesias.add(c.order_id);
2171
+ } catch {
2172
+ cortesiasOk = false;
2173
+ }
2174
+ }
2175
+ if (ids.length > 0) {
2176
+ try {
2177
+ const [pgs, elos, direto] = await Promise.all([
2178
+ db().from("plg_tables_order_payments").select("order_id").in("order_id", ids),
2179
+ db().from("plg_fiscalbr_document_orders").select(`order_id, ${FISCAL_DOCS}!inner(status)`).in("order_id", ids),
2180
+ db().from(FISCAL_DOCS).select("order_id").in("order_id", ids).eq("status", "authorized")
2181
+ ]);
2182
+ if (pgs.error || elos.error || direto.error) throw new Error("selo");
2183
+ for (const p of pgs.data ?? []) {
2184
+ pagamentos.set(p.order_id, (pagamentos.get(p.order_id) ?? 0) + 1);
2185
+ }
2186
+ for (const e of elos.data ?? []) {
2187
+ const doc = Array.isArray(e[FISCAL_DOCS]) ? e[FISCAL_DOCS][0] : e[FISCAL_DOCS];
2188
+ if (doc?.status !== "authorized") continue;
2189
+ notas.set(e.order_id, (notas.get(e.order_id) ?? 0) + 1);
2190
+ }
2191
+ for (const d of direto.data ?? []) {
2192
+ if (d.order_id) consolidadas.add(d.order_id);
2193
+ }
2194
+ } catch {
2195
+ selosOk = false;
2196
+ }
2197
+ }
2198
+ return (data ?? []).map((r) => {
2199
+ const mesa = r[ORDER_EXT]?.[TABLES] ?? r[ORDER_EXT]?.[0]?.[TABLES];
2200
+ const ext = Array.isArray(r[ORDER_EXT]) ? r[ORDER_EXT][0] : r[ORDER_EXT];
2201
+ return {
2202
+ id: r.id,
2203
+ // A mesa por ID decide o CANAL da conta fechada. Ver `comandaChannel`:
2204
+ // 3.766 contas históricas do Pertinho vieram com `channel` nulo e
2205
+ // mesa preenchida, e sem este campo elas apareciam no «Histórico do
2206
+ // balcão» — sessenta contas de mesa num canal sem uma única linha.
2207
+ tableId: ext?.table_id ?? null,
2208
+ // ENCERRADA COMO CORTESIA — e por isso não reabre. Ver `reopen.ts`.
2209
+ //
2210
+ // Quando a leitura da cortesia falhou, TODA conta é tratada como
2211
+ // cortesia: «não sei» faz o botão sumir, em vez de oferecê-lo sobre
2212
+ // uma conta perdoada. Esconder custa um chamado; oferecer errado
2213
+ // custa uma conta cobrada duas vezes.
2214
+ courtesy: cortesiasOk ? cortesias.has(r.id) : true,
2215
+ // O mesmo cuidado para o DINHEIRO: reabrir uma conta paga é
2216
+ // estorno, não reabertura, e a leitura dos pagamentos vem da mesma
2217
+ // busca tolerante do selo. Falhando ela, `undefined` diz «não sei»
2218
+ // e o botão some — ver `reopenBlock`.
2219
+ hasPayment: selosOk ? (pagamentos.get(r.id) ?? 0) > 0 : void 0,
2220
+ // Sem número de comanda: ele NÃO é coluna de `orders` nem da
2221
+ // extensão — pedi-lo derrubava a consulta inteira com `column
2222
+ // orders.reference does not exist`, e com ela a lista de contas
2223
+ // fechadas. A linha se identifica pela mesa e pela hora, que é o que
2224
+ // o caixa usa para achar a conta que alguém está reclamando.
2225
+ reference: void 0,
2226
+ tableLabel: mesa?.number != null ? `Mesa ${mesa.number}` : null,
2227
+ // O placeholder do cadastro NÃO é nome.
2228
+ //
2229
+ // `party_id` aponta para uma ficha genérica em toda comanda que
2230
+ // ninguém identificou — no Pertinho, "Consumidor não identificado"
2231
+ // nas dezoito abertas. Escrevê-lo na linha gasta o espaço do nome
2232
+ // para dizer que não há nome, e a régua do porte é clara: vocabulário
2233
+ // do banco não chega cru à tela. Vazio custa menos que errado.
2234
+ customerName: nomeDeCliente(r.people?.name),
2235
+ total: num(r.total),
2236
+ closedAt: r.completed_at ?? r.updated_at ?? null,
2237
+ channel: r.channel ?? null,
2238
+ // A espécie viaja junto: sem ela, toda conta que a migração trouxe
2239
+ // (canal nulo) caía no balcão.
2240
+ kind: r.kind ?? null,
2241
+ ...selosOk ? {
2242
+ expectedDocuments: pagamentos.get(r.id) ?? 0,
2243
+ issuedDocuments: notas.get(r.id) ?? 0,
2244
+ hasConsolidatedDocument: consolidadas.has(r.id)
2245
+ } : {}
2246
+ };
2247
+ });
2248
+ },
2249
+ /**
2250
+ * O que já entrou nesta comanda, e de quem.
2251
+ *
2252
+ * O valor vem do RAZÃO pelo `movement_id` — a faceta de salão não guarda
2253
+ * dinheiro. E só o que está liquidado conta: um pagamento pendente na
2254
+ * maquininha ainda não é dinheiro, e mostrá-lo como "pago" faria o caixa
2255
+ * liberar a mesa contra uma promessa.
2256
+ */
2257
+ async getOrderPayments(orderId) {
2258
+ const { data, error } = await db().from(ORDER_PAYMENTS).select("id, guest_id, paid_by_name, metadata, plg_financial_movements(amount, status, payment_method_id)").eq("order_id", orderId);
2259
+ if (error) throw new Error(error.message);
2260
+ const rows = data ?? [];
2261
+ const metodoIds = [...new Set(rows.map((r) => r.plg_financial_movements?.payment_method_id).filter(Boolean))];
2262
+ const metodoById = metodoIds.length > 0 ? new Map(((await db().from("plg_financial_payment_methods").select("id, name").in("id", metodoIds)).data ?? []).map((m) => [m.id, m.name])) : /* @__PURE__ */ new Map();
2263
+ const nomeDoGuest = new Map(
2264
+ ((await db().from(GUESTS_VIEW).select("id, guest_name").eq("order_id", orderId)).data ?? []).map((g) => [g.id, g.guest_name])
2265
+ );
2266
+ return rows.map((r) => {
2267
+ const mov = r.plg_financial_movements;
2268
+ return {
2269
+ id: r.id,
2270
+ guestId: r.guest_id ?? null,
2271
+ amount: num(mov?.amount),
2272
+ paidByName: r.paid_by_name ?? null,
2273
+ status: mov?.status ?? null,
2274
+ guestName: r.guest_id ? nomeDoGuest.get(r.guest_id) ?? null : null,
2275
+ methodName: mov ? metodoById.get(mov.payment_method_id) ?? r.metadata?.v1?.card_brand ?? null : void 0
2276
+ };
2277
+ });
2278
+ },
2279
+ async getOrderCoverCharges(orderId) {
2280
+ const { data, error } = await db().from(ORDER_COVERS).select("id, charge_name, unit_amount, guest_count, total_amount, discount_amount, guest_quantities, cover_charge_id, " + COVER_CHARGES + "(qty_identified, qty_unidentified)").eq("order_id", orderId);
2281
+ if (error) throw new Error(error.message);
2282
+ return (data ?? []).map((r) => ({
2283
+ id: r.id,
2284
+ name: r.charge_name ?? "Couvert",
2285
+ unitAmount: num(r.unit_amount),
2286
+ guestCount: Number(r.guest_count) || 0,
2287
+ total: num(r.total_amount),
2288
+ discount: num(r.discount_amount),
2289
+ guestQuantities: Array.isArray(r.guest_quantities) ? r.guest_quantities.map((g) => ({ guestId: g.guest_id, qty: Number(g.qty) || 0 })) : void 0,
2290
+ // `?? 1` é o default do V1 (`charge.qty_per_identified ?? 1`).
2291
+ qtyIdentified: Number(politicaDe(r)?.qty_identified ?? 1),
2292
+ qtyUnidentified: Number(politicaDe(r)?.qty_unidentified ?? 1)
2293
+ }));
2294
+ },
2295
+ /**
2296
+ * QUANTOS COUVERTS cada participante levou.
2297
+ *
2298
+ * O V1 tem um diálogo para isto (`CoverChargeEditDialog`): lista os
2299
+ * participantes, um campo de quantidade em cada um, e o total embaixo.
2300
+ * Existe porque couvert **não é um por cabeça**: uma pessoa pede dois, a
2301
+ * criança não paga, quem chegou no fim da noite também não.
2302
+ *
2303
+ * O V2 tinha a coluna (`guest_quantities`, migration 019), o tipo
2304
+ * (`OrderCoverCharge.guestQuantities`) e a leitura — e **nenhum escritor**.
2305
+ * A coluna nasceu em 019 e nunca recebeu uma linha: o couvert era sempre
2306
+ * `unit_amount × número de pessoas`, sem correção possível a não ser
2307
+ * cancelar a linha inteira.
2308
+ *
2309
+ * O total é recalculado AQUI, e não pela `comanda_apply_cover_charges`: a
2310
+ * RPC reparte por cabeça, que é justamente a conta que este gesto está
2311
+ * corrigindo. Chamá-la depois desfaria o ajuste.
2312
+ */
2313
+ async setCoverChargeQuantities(coverChargeId, quantities) {
2314
+ requireWrites();
2315
+ const limpas = quantities.map((q) => ({ guest_id: q.guestId, qty: Math.max(0, Math.floor(Number(q.qty) || 0)) }));
2316
+ const total = limpas.reduce((s, q) => s + q.qty, 0);
2317
+ const { data: linha } = await db().from(ORDER_COVERS).select("order_id, unit_amount").eq("id", coverChargeId).maybeSingle();
2318
+ const unitario = num(linha?.unit_amount);
2319
+ const { data: tocou, error } = await db().from(ORDER_COVERS).update({
2320
+ guest_quantities: limpas,
2321
+ guest_count: total,
2322
+ total_amount: Math.round(unitario * total * 100) / 100
2323
+ }).eq("id", coverChargeId).select("id");
2324
+ if (error) throw new Error(error.message);
2325
+ assertTocou(tocou, "a quantidade de couvert por participante");
2326
+ const orderId = linha?.order_id;
2327
+ if (orderId) await recalc(orderId);
2328
+ },
2329
+ /**
2330
+ * "A casa paga."
2331
+ *
2332
+ * Duas escritas, nesta ordem: o REGISTRO primeiro, a comanda depois. Se a
2333
+ * ordem se inverter e a segunda falhar, fica uma comanda fechada sem
2334
+ * nenhuma explicação de para onde foi o dinheiro — que é exatamente o furo
2335
+ * de caixa sem dono que este registro existe para impedir.
2336
+ */
2337
+ async closeAsCourtesy(input) {
2338
+ requireWrites();
2339
+ const tenantId = tenant();
2340
+ const { error } = await db().from(COURTESY).insert({
2341
+ tenant_id: tenantId,
2342
+ order_id: input.orderId,
2343
+ amount: input.amount,
2344
+ reason: input.reason,
2345
+ authorized_by_name: input.authorizedByName ?? null,
2346
+ operation_key: input.operationKey
2347
+ });
2348
+ if (error && !String(error.message).includes("duplicate key")) {
2349
+ throw new Error(error.message);
2350
+ }
2351
+ const { data: fechada, error: closeError } = await db().from("orders").update({ status: "completed" }).eq("id", input.orderId).select("id, status");
2352
+ if (closeError) throw new Error(closeError.message);
2353
+ const ok = (fechada ?? []).some((r) => r.status === "completed");
2354
+ if (!ok) throw new Error("O servidor n\xE3o confirmou o encerramento por cortesia.");
2355
+ const { data: faturas } = await db().from("plg_financial_invoices").select("id").eq("order_id", input.orderId).is("cancelled_at", null);
2356
+ for (const f of faturas ?? []) {
2357
+ await db().rpc("financial_cancel_invoice", {
2358
+ p_invoice_id: f.id,
2359
+ p_reason: `Cortesia: ${input.reason}`,
2360
+ p_idempotency_key: `courtesy:${input.operationKey}:${f.id}`
2361
+ });
2362
+ }
2363
+ },
2364
+ // -- Escala do salão ------------------------------------------------------
2365
+ /**
2366
+ * Quem atende o quê AGORA.
2367
+ *
2368
+ * O corte é `ends_at is null or ends_at > now()` — permanente ou ainda
2369
+ * válido — feito NO BANCO. Trazer a escala inteira e filtrar na tela
2370
+ * funcionaria hoje, com poucas linhas, e pararia de funcionar exatamente
2371
+ * quando a casa passar a usar isto todo dia.
2372
+ */
2373
+ /**
2374
+ * As praças da unidade, com as mesas de cada uma.
2375
+ *
2376
+ * Duas leituras e não um join: o vínculo praça × mesa é N:N e vive em
2377
+ * `plg_tables_service_area_tables`. Pedi-lo embutido faria o PostgREST
2378
+ * devolver a praça repetida uma vez por mesa — cem linhas para cinco
2379
+ * praças, e a cor pintada cem vezes.
2380
+ */
2381
+ async createServiceArea(input) {
2382
+ const tenantId = tenant();
2383
+ const { data, error } = await db().from(AREAS).insert({
2384
+ tenant_id: tenantId,
2385
+ name: input.name,
2386
+ color: input.color ?? null,
2387
+ shape: input.shape,
2388
+ sort_order: input.sortOrder ?? 0,
2389
+ pos_x: input.posX ?? null,
2390
+ pos_y: input.posY ?? null,
2391
+ width_m: input.widthM ?? null,
2392
+ height_m: input.heightM ?? null,
2393
+ polygon: input.polygon ?? null
2394
+ }).select("id").single();
2395
+ if (error) throw new Error(error.message);
2396
+ const ids = input.tableIds ?? [];
2397
+ if (ids.length > 0) {
2398
+ const { error: vinculo } = await db().from(AREA_TABLES).insert(
2399
+ ids.map((table_id) => ({
2400
+ tenant_id: tenantId,
2401
+ area_id: data.id,
2402
+ table_id,
2403
+ source: "auto"
2404
+ }))
2405
+ );
2406
+ if (vinculo) throw new Error(vinculo.message);
2407
+ }
2408
+ return data.id;
2409
+ },
2410
+ async updateServiceArea(id, patch) {
2411
+ const tenantId = tenant();
2412
+ const campos = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
2413
+ if (patch.name !== void 0) campos.name = patch.name;
2414
+ if (patch.color !== void 0) campos.color = patch.color;
2415
+ if (patch.posX !== void 0) campos.pos_x = patch.posX;
2416
+ if (patch.posY !== void 0) campos.pos_y = patch.posY;
2417
+ if (patch.widthM !== void 0) campos.width_m = patch.widthM;
2418
+ if (patch.heightM !== void 0) campos.height_m = patch.heightM;
2419
+ if (patch.polygon !== void 0) campos.polygon = patch.polygon;
2420
+ const { data: mudadas, error } = await db().from(AREAS).update(campos).eq("id", id).select("id");
2421
+ if (error) throw new Error(error.message);
2422
+ assertTocou(mudadas, "a altera\xE7\xE3o da pra\xE7a");
2423
+ if (patch.tableIds === void 0) return;
2424
+ const { error: limpeza } = await db().from(AREA_TABLES).delete().eq("area_id", id).eq("source", "auto");
2425
+ if (limpeza) throw new Error(limpeza.message);
2426
+ const { data: manuais } = await db().from(AREA_TABLES).select("table_id").eq("area_id", id);
2427
+ const jaTem = new Set((manuais ?? []).map((m) => m.table_id));
2428
+ const novos = patch.tableIds.filter((t) => !jaTem.has(t));
2429
+ if (novos.length > 0) {
2430
+ const { error: vinculo } = await db().from(AREA_TABLES).insert(
2431
+ novos.map((table_id) => ({
2432
+ tenant_id: tenantId,
2433
+ area_id: id,
2434
+ table_id,
2435
+ source: "auto"
2436
+ }))
2437
+ );
2438
+ if (vinculo) throw new Error(vinculo.message);
2439
+ }
2440
+ },
2441
+ async setTableInServiceArea(areaId, tableId, how) {
2442
+ const tenantId = tenant();
2443
+ if (how === "reset") {
2444
+ const { error: error2 } = await db().from(AREA_TABLES).delete().eq("area_id", areaId).eq("table_id", tableId);
2445
+ if (error2) throw new Error(error2.message);
2446
+ const { error: recria } = await db().from(AREA_TABLES).insert({
2447
+ tenant_id: tenantId,
2448
+ area_id: areaId,
2449
+ table_id: tableId,
2450
+ source: "auto"
2451
+ });
2452
+ if (recria) throw new Error(recria.message);
2453
+ return;
2454
+ }
2455
+ const { error } = await db().from(AREA_TABLES).upsert({
2456
+ tenant_id: tenantId,
2457
+ area_id: areaId,
2458
+ table_id: tableId,
2459
+ source: "manual",
2460
+ is_excluded: how === "exclude",
2461
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
2462
+ }, { onConflict: "area_id,table_id" });
2463
+ if (error) throw new Error(error.message);
2464
+ },
2465
+ async deleteServiceArea(id) {
2466
+ const { data: apagadas, error } = await db().from(AREAS).delete().eq("id", id).select("id");
2467
+ if (error) throw new Error(error.message);
2468
+ assertTocou(apagadas, "a remo\xE7\xE3o da pra\xE7a");
2469
+ },
2470
+ async updateZoneOutline(id, patch) {
2471
+ requireWrites();
2472
+ const campos = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
2473
+ if (patch.name !== void 0) campos.name = patch.name;
2474
+ if (patch.color !== void 0) campos.color = patch.color;
2475
+ if (patch.shape !== void 0) campos.shape = patch.shape;
2476
+ if (patch.widthM !== void 0) campos.width_m = patch.widthM;
2477
+ if (patch.heightM !== void 0) campos.height_m = patch.heightM;
2478
+ if (patch.polygon !== void 0) campos.polygon = patch.polygon;
2479
+ const { data: mudadas, error } = await db().from(ZONES).update(campos).eq("id", id).select("id");
2480
+ if (error) throw new Error(error.message);
2481
+ assertTocou(mudadas, "a altera\xE7\xE3o do ambiente");
2482
+ },
2483
+ async applyArrangement(plan) {
2484
+ for (const a of plan.areas) {
2485
+ const campos = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
2486
+ if (a.widthM !== void 0) campos.width_m = a.widthM;
2487
+ if (a.heightM !== void 0) campos.height_m = a.heightM;
2488
+ if (a.posX !== void 0) campos.pos_x = a.posX;
2489
+ if (a.posY !== void 0) campos.pos_y = a.posY;
2490
+ const { data: mudadas, error } = await db().from(ZONES).update(campos).eq("id", a.id).select("id");
2491
+ if (error) throw new Error(error.message);
2492
+ assertTocou(mudadas, "a nova posi\xE7\xE3o do ambiente");
2493
+ }
2494
+ const porDestino = /* @__PURE__ */ new Map();
2495
+ for (const t of plan.tables) {
2496
+ const chave = t.areaId ?? "";
2497
+ const lista = porDestino.get(chave) ?? [];
2498
+ lista.push({ id: t.id, posX: t.posX, posY: t.posY });
2499
+ porDestino.set(chave, lista);
2500
+ }
2501
+ for (const [areaId, lista] of porDestino) {
2502
+ for (const t of lista) {
2503
+ const campos = {
2504
+ zone_id: areaId || null,
2505
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
2506
+ };
2507
+ campos.pos_x = areaId ? t.posX ?? null : null;
2508
+ campos.pos_y = areaId ? t.posY ?? null : null;
2509
+ const { data: mudadas, error } = await db().from(TABLES).update(campos).eq("id", t.id).select("id");
2510
+ if (error) throw new Error(error.message);
2511
+ assertTocou(mudadas, "a nova posi\xE7\xE3o da mesa");
2512
+ }
2513
+ }
2514
+ },
2515
+ async listOpenChannelOrders(channel) {
2516
+ const especie = legacyKindOfChannel(channel);
2517
+ let q = db().from("orders").select(`id, channel, kind, status, total, created_at, unit_id, reference_number,
2518
+ ${ORDER_EXT}!inner ( table_id, unit_id, seated_at, delivery_source )`).eq("tenant_id", tenant()).not("status", "in", '("completed","cancelled")');
2519
+ q = especie ? q.or(`channel.eq.${channel},and(channel.is.null,kind.eq.${especie})`) : q.eq("channel", channel);
2520
+ const { data, error } = await q;
2521
+ if (error) throw new Error(error.message);
2522
+ return (data ?? []).map((r) => {
2523
+ const ext = Array.isArray(r[ORDER_EXT]) ? r[ORDER_EXT][0] : r[ORDER_EXT];
2524
+ return {
2525
+ id: r.id,
2526
+ // O NÚMERO da comanda: é o que o V1 escreve no cartão do delivery
2527
+ // (`#{order.number}`) e na ficha do dock («Balcão #1234»).
2528
+ reference: r.reference_number ?? null,
2529
+ // De ONDE veio: o cartão do V1 mostra isto logo abaixo do número.
2530
+ source: ext?.delivery_source ?? null,
2531
+ channel: r.channel ?? channel,
2532
+ tableId: ext?.table_id ?? null,
2533
+ // A unidade da COMANDA e a do ext podem divergir em linha antiga; a
2534
+ // do ext é a que o V1 grava ao abrir, então ela ganha.
2535
+ unitId: ext?.unit_id ?? r.unit_id ?? null,
2536
+ status: r.status ?? "new",
2537
+ // Reais → centavos. A regra da retirada compara com ZERO e um
2538
+ // arredondamento de float faria `0.004` deixar de ser conta vazia.
2539
+ totalCents: Math.round(Number(r.total ?? 0) * 100),
2540
+ openedAt: ext?.seated_at ?? r.created_at ?? ""
2541
+ };
2542
+ });
2543
+ },
2544
+ async openChannelOrder(input) {
2545
+ requireWrites();
2546
+ const tenantId = tenant();
2547
+ const reference = await nextReference();
2548
+ const { data: order, error } = await db().from("orders").insert({
2549
+ tenant_id: tenantId,
2550
+ // A ESPÉCIE continua a da casa: é o que o quadro de pedidos e o KDS
2551
+ // leem. O que distingue o canal é `channel`.
2552
+ kind: SEATING_KIND,
2553
+ status: "new",
2554
+ channel: input.channel,
2555
+ unit_id: input.unitId,
2556
+ ...reference ? { reference_number: reference } : {},
2557
+ subtotal: 0,
2558
+ total: 0,
2559
+ currency: "BRL"
2560
+ }).select("id").single();
2561
+ if (error) throw new Error(error.message);
2562
+ const { error: extError } = await db().from(ORDER_EXT).insert({
2563
+ order_id: order.id,
2564
+ tenant_id: tenantId,
2565
+ // Sem mesa, e é o ponto: é por isto que `seatGuests` não servia.
2566
+ table_id: null,
2567
+ unit_id: input.unitId,
2568
+ // Taxa ZERO, regra do V1: quem pega a sacola no balcão não foi servido
2569
+ // à mesa. Explícito e não omitido — a coluna é nulável, e null aqui
2570
+ // deixaria a tela repetir a política da casa.
2571
+ service_charge_percent: 0,
2572
+ service_charge_amount: 0,
2573
+ ...input.customerName ? { customer_name: input.customerName } : {}
2574
+ });
2575
+ if (extError) {
2576
+ await db().from("orders").delete().eq("id", order.id);
2577
+ throw new Error(extError.message);
2578
+ }
2579
+ return { orderId: order.id };
2580
+ },
2581
+ async getServiceAreas() {
2582
+ const [{ data: areas, error }, { data: vinculos }] = await Promise.all([
2583
+ db().from(AREAS).select("*").eq("is_active", true).order("sort_order"),
2584
+ // `area_id`, não `service_area_id`. E `is_excluded` fica de fora: o
2585
+ // vínculo existe para registrar que aquela mesa foi TIRADA da praça à
2586
+ // mão — contá-lo pintaria a praça sobre mesa que alguém já removeu.
2587
+ db().from(AREA_TABLES).select("area_id, table_id, is_excluded")
2588
+ ]);
2589
+ if (error) throw new Error(error.message);
2590
+ const porArea = /* @__PURE__ */ new Map();
2591
+ const foraPorArea = /* @__PURE__ */ new Map();
2592
+ for (const v of vinculos ?? []) {
2593
+ const alvo = v.is_excluded ? foraPorArea : porArea;
2594
+ const lista = alvo.get(v.area_id) ?? [];
2595
+ lista.push(v.table_id);
2596
+ alvo.set(v.area_id, lista);
2597
+ }
2598
+ return (areas ?? []).map((a) => ({
2599
+ id: a.id,
2600
+ name: a.name,
2601
+ color: a.color ?? null,
2602
+ sortOrder: a.sort_order ?? 0,
2603
+ isActive: a.is_active !== false,
2604
+ shape: a.shape ?? null,
2605
+ posX: a.pos_x != null ? num(a.pos_x) : null,
2606
+ posY: a.pos_y != null ? num(a.pos_y) : null,
2607
+ widthM: a.width_m != null ? num(a.width_m) : null,
2608
+ heightM: a.height_m != null ? num(a.height_m) : null,
2609
+ polygon: a.polygon ?? null,
2610
+ tableIds: porArea.get(a.id) ?? [],
2611
+ excludedTableIds: foraPorArea.get(a.id) ?? []
2612
+ }));
2613
+ },
2614
+ /**
2615
+ * As formas de pagamento que o PDV pode oferecer, HOJE, nesta casa.
2616
+ *
2617
+ * A regra é a do V1: método cadastrado ganha; tipo sem método vira opção
2618
+ * VIRTUAL — mas **só se houver ao menos uma conta compatível**. Oferecer
2619
+ * "Pix" a quem não tem conta bancária é oferecer um caminho que o
2620
+ * `financial_receive_payment` vai recusar com "an account is required".
2621
+ *
2622
+ * O casamento é pelo `kind` da conta, não pelo `account_type`: o cadastro
2623
+ * do Pertinho escreve `caixa_fisico` e o catálogo fala `cash_physical`, e
2624
+ * é `plg_financial_account_kind_of` que traduz os dois no gatilho. Comparar
2625
+ * `account_type` direto dá zero em todos os sete tipos.
2626
+ */
2627
+ async getPaymentOptions() {
2628
+ const [{ data: tipos, error }, { data: metodos }, { data: contas }] = await Promise.all([
2629
+ db().from("plg_financial_payment_method_types").select("*").eq("is_active", true),
2630
+ db().from("plg_financial_payment_methods").select("*").eq("is_active", true),
2631
+ db().from("plg_financial_accounts").select("kind").eq("is_active", true)
2632
+ ]);
2633
+ if (error) throw new Error(error.message);
2634
+ const porKind = /* @__PURE__ */ new Map();
2635
+ for (const a of contas ?? []) {
2636
+ porKind.set(a.kind, (porKind.get(a.kind) ?? 0) + 1);
2637
+ }
2638
+ const cabem = (permitidos) => permitidos.reduce((n, k) => n + (porKind.get(k) ?? 0), 0);
2639
+ const out = [];
2640
+ const comMetodo = /* @__PURE__ */ new Set();
2641
+ for (const m of metodos ?? []) {
2642
+ const t = (tipos ?? []).find((x) => x.id === m.payment_method_type_id);
2643
+ if (!t) continue;
2644
+ const permitidos = t.allowed_account_types ?? [];
2645
+ const n = cabem(permitidos);
2646
+ if (n === 0) continue;
2647
+ comMetodo.add(t.id);
2648
+ out.push({
2649
+ key: `m-${m.id}`,
2650
+ methodId: m.id,
2651
+ typeId: t.id,
2652
+ label: m.name ?? t.name,
2653
+ transactionType: t.transaction_type,
2654
+ typeName: t.name ?? null,
2655
+ allowedAccountKinds: permitidos,
2656
+ accountCount: n,
2657
+ minInstallments: Number(m.min_installments) || 1,
2658
+ maxInstallments: Number(m.max_installments) || 1
2659
+ });
2660
+ }
2661
+ for (const t of tipos ?? []) {
2662
+ if (comMetodo.has(t.id)) continue;
2663
+ const permitidos = t.allowed_account_types ?? [];
2664
+ const n = cabem(permitidos);
2665
+ if (n === 0) continue;
2666
+ const cartao = t.transaction_type === "credit_card";
2667
+ out.push({
2668
+ key: `t-${t.id}`,
2669
+ methodId: null,
2670
+ typeId: t.id,
2671
+ label: t.name,
2672
+ transactionType: t.transaction_type,
2673
+ typeName: t.name ?? null,
2674
+ allowedAccountKinds: permitidos,
2675
+ accountCount: n,
2676
+ minInstallments: 1,
2677
+ // Só o CRÉDITO parcela. Débito é sempre à vista — e no V1 a regra
2678
+ // segue o tipo da CONTA, não o nome do método, porque o nome é livre
2679
+ // e mente ("Cielo - Link de Pagamento A vista" é conta de débito).
2680
+ maxInstallments: cartao ? 12 : 1
2681
+ });
2682
+ }
2683
+ return out;
2684
+ },
2685
+ /**
2686
+ * As contas que podem receber dinheiro nesta casa.
2687
+ *
2688
+ * `kind` e não `account_type`: o cadastro escreve `caixa_fisico` e o
2689
+ * catálogo de formas fala `cash_physical`. Quem traduz é
2690
+ * `plg_financial_account_kind_of`, num gatilho, e é a coluna derivada que
2691
+ * `financial_receive_payment` valida. Comparar `account_type` direto dá
2692
+ * zero em todos os tipos — e o PDV ficaria sem forma nenhuma.
2693
+ */
2694
+ async getReceivingAccounts() {
2695
+ const { data, error } = await db().from("plg_financial_accounts").select("id, name, kind, unit_id").eq("is_active", true).order("name");
2696
+ if (error) throw new Error(error.message);
2697
+ return (data ?? []).map((a) => ({
2698
+ id: a.id,
2699
+ name: a.name,
2700
+ kind: a.kind,
2701
+ unitId: a.unit_id ?? null
2702
+ }));
2703
+ },
2704
+ async getServiceAreaStaff() {
2705
+ const agora = (/* @__PURE__ */ new Date()).toISOString();
2706
+ const { data, error } = await db().from(AREA_STAFF).select(`id, area_id, table_id, person_id, role, starts_at, ends_at,
2707
+ ${AREAS}(name, color), ${TABLES}(number, name), people(name)`).lte("starts_at", agora).or(`ends_at.is.null,ends_at.gt.${agora}`);
2708
+ if (error) throw new Error(error.message);
2709
+ return (data ?? []).map((r) => ({
2710
+ id: r.id,
2711
+ areaId: r.area_id ?? null,
2712
+ areaName: r[AREAS]?.name ?? null,
2713
+ areaColor: r[AREAS]?.color ?? null,
2714
+ tableId: r.table_id ?? null,
2715
+ tableNumber: r[TABLES]?.number == null ? null : String(r[TABLES].number),
2716
+ tableName: r[TABLES]?.name ?? null,
2717
+ personId: r.person_id,
2718
+ personName: r.people?.name ?? null,
2719
+ role: r.role ?? null,
2720
+ startsAt: r.starts_at,
2721
+ endsAt: r.ends_at ?? null
2722
+ }));
2723
+ },
2724
+ async assignServiceAreaStaff(input) {
2725
+ requireWrites();
2726
+ const tenantId = tenant();
2727
+ if (!input.areaId && !input.tableId) {
2728
+ throw new Error("Escolha uma pra\xE7a ou uma mesa para escalar.");
2729
+ }
2730
+ let endsAt = null;
2731
+ if (input.untilEndOfDay) {
2732
+ const { data, error: error2 } = await db().rpc("comanda_next_day_cutoff");
2733
+ if (error2) throw new Error(error2.message);
2734
+ endsAt = data;
2735
+ }
2736
+ const { error } = await db().from(AREA_STAFF).insert({
2737
+ tenant_id: tenantId,
2738
+ area_id: input.areaId ?? null,
2739
+ table_id: input.tableId ?? null,
2740
+ person_id: input.personId,
2741
+ role: input.role,
2742
+ validity: input.untilEndOfDay ? "end_of_day" : "permanent",
2743
+ starts_at: (/* @__PURE__ */ new Date()).toISOString(),
2744
+ ends_at: endsAt
2745
+ });
2746
+ if (error) throw new Error(error.message);
2747
+ },
2748
+ async unassignServiceAreaStaff(id) {
2749
+ requireWrites();
2750
+ const { error } = await db().from(AREA_STAFF).delete().eq("id", id);
2751
+ if (error) throw new Error(error.message);
2752
+ },
2753
+ // -- Fila de espera -------------------------------------------------------
2754
+ /**
2755
+ * Só quem ainda disputa mesa.
2756
+ *
2757
+ * `seated`, `no_show` e `cancelled` ficam de fora: eles são histórico, e
2758
+ * no painel do anfitrião a lista cresceria a noite inteira empurrando para
2759
+ * baixo justamente o próximo da fila.
2760
+ */
2761
+ async getWaitlist() {
2762
+ const { data, error } = await db().from(WAITLIST).select("id, guest_name, guest_phone, party_size, size_bucket, zone_id, note, status, joined_at, called_at, call_expires_at, call_count, person_id").in("status", ["waiting", "called"]).order("joined_at", { ascending: true }).limit(200);
2763
+ if (error) throw new Error(error.message);
2764
+ return (data ?? []).map((r) => ({
2765
+ id: r.id,
2766
+ name: r.guest_name,
2767
+ phone: r.guest_phone,
2768
+ party: r.party_size,
2769
+ sizeBucket: r.size_bucket ?? null,
2770
+ zoneId: r.zone_id ?? null,
2771
+ note: r.note ?? null,
2772
+ status: r.status,
2773
+ joinedAt: r.joined_at,
2774
+ calledAt: r.called_at ?? null,
2775
+ callExpiresAt: r.call_expires_at ?? null,
2776
+ callCount: r.call_count ?? 0,
2777
+ personId: r.person_id ?? null
2778
+ }));
2779
+ },
2780
+ /**
2781
+ * `tenant_id`, `unit_id` e `size_bucket` NÃO vão daqui: quem os resolve é o
2782
+ * BEFORE INSERT. O balcão manda o que sabe — quem, que telefone, quantas
2783
+ * pessoas — e não conhece a grade de mesas da casa, que é o que decide o
2784
+ * bucket.
2785
+ */
2786
+ async addWaitlistEntry(input) {
2787
+ requireWrites();
2788
+ const { error } = await db().from(WAITLIST).insert({
2789
+ tenant_id: tenant(),
2790
+ guest_name: input.name.trim(),
2791
+ guest_phone: input.phone.trim(),
2792
+ party_size: input.party,
2793
+ zone_id: input.zoneId ?? null,
2794
+ note: input.note?.trim() || null,
2795
+ person_id: input.personId ?? null
2796
+ });
2797
+ if (error) throw new Error(error.message);
2798
+ },
2799
+ /**
2800
+ * As três transições passam por RPC, nunca por UPDATE solto: o prazo de
2801
+ * tolerância, a contagem de chamados e o log vivem num lugar só. Três telas
2802
+ * escrevendo o mesmo UPDATE é como as três divergem.
2803
+ */
2804
+ async callWaitlistEntry(id) {
2805
+ requireWrites();
2806
+ const { error } = await db().rpc("waitlist_call", { p_entry_id: id });
2807
+ if (error) throw new Error(error.message);
2808
+ },
2809
+ async seatWaitlistEntry(id, tableId, orderId) {
2810
+ requireWrites();
2811
+ const { error } = await db().rpc("waitlist_seat", {
2812
+ p_entry_id: id,
2813
+ p_table_id: tableId ?? null,
2814
+ p_order_id: orderId ?? null
2815
+ });
2816
+ if (error) throw new Error(error.message);
2817
+ },
2818
+ async closeWaitlistEntry(id, status, reason) {
2819
+ requireWrites();
2820
+ const { error } = await db().rpc("waitlist_close", {
2821
+ p_entry_id: id,
2822
+ p_status: status,
2823
+ p_reason: reason ?? null
2824
+ });
2825
+ if (error) throw new Error(error.message);
2826
+ },
2827
+ /**
2828
+ * Este telefone já é de alguém?
2829
+ *
2830
+ * Só LÊ. A fila nunca cria pessoa — quem passou na porta uma vez não vira
2831
+ * cadastro sem querer, e uma base cheia de "João" sem documento não se
2832
+ * desfaz depois.
2833
+ *
2834
+ * A busca vai em `phone_digits`, não em `phone`: o cadastro guarda o número
2835
+ * formatado («(11) 99999-0000») e o balcão digita só dígitos, então o
2836
+ * `ilike` sobre o campo formatado do V1 não casa nunca. O corte nos 8
2837
+ * últimos dígitos é o que torna «11999990000» e «(11) 99999-0000» a mesma
2838
+ * pessoa mesmo quando um dos dois foi salvo sem DDD.
2839
+ */
2840
+ async findPersonByPhone(digits) {
2841
+ if (digits.length < 10) return null;
2842
+ const { data, error } = await db().from("people").select("id, name").ilike("phone_digits", `%${digits.slice(-8)}`).limit(1);
2843
+ if (error) return null;
2844
+ const p = (data ?? [])[0];
2845
+ return p ? { id: p.id, name: p.name } : null;
2846
+ },
2847
+ async getDayCutoff() {
2848
+ const s = await this.getSettings?.();
2849
+ return s?.operationalDayStart ?? "06:00";
2850
+ },
2851
+ // -- Autorização ----------------------------------------------------------
2852
+ /**
2853
+ * Quem pode autorizar, lido da VIEW — nunca da tabela.
2854
+ *
2855
+ * A tabela tem a coluna do hash e um `revoke select` por cima dela: um
2856
+ * `select *` ali devolve erro de permissão, que é exatamente o objetivo.
2857
+ * A view existe para que a tela nunca precise chegar perto do segredo.
2858
+ */
2859
+ async getAuthorizers(action) {
2860
+ const { data, error } = await db().from(AUTHORIZERS).select("id, label, has_pin, allows_discount, allows_service_charge, allows_cancel, allows_courtesy, max_discount_percent");
2861
+ if (error) throw new Error(error.message);
2862
+ const linhas = (data ?? []).map((r) => ({
2863
+ id: r.id,
2864
+ name: r.label ?? "Autorizador",
2865
+ hasPin: !!r.has_pin,
2866
+ allowsDiscount: !!r.allows_discount,
2867
+ allowsServiceCharge: !!r.allows_service_charge,
2868
+ allowsCancel: !!r.allows_cancel,
2869
+ allowsCourtesy: !!r.allows_courtesy,
2870
+ maxDiscountPercent: r.max_discount_percent == null ? void 0 : num(r.max_discount_percent)
2871
+ }));
2872
+ const comPin = linhas.filter((a) => a.hasPin);
2873
+ if (!action) return comPin;
2874
+ return comPin.filter((a) => action === "discount" ? a.allowsDiscount : action === "service_charge" ? a.allowsServiceCharge : action === "cancel" ? a.allowsCancel : a.allowsCourtesy);
2875
+ },
2876
+ async verifyAuthorizerPin(authorizerId, pin, action) {
2877
+ const { data, error } = await db().rpc("comanda_verify_authorizer_pin", {
2878
+ p_authorizer_id: authorizerId,
2879
+ p_pin: pin,
2880
+ p_action: action ?? null
2881
+ });
2882
+ if (error) throw new Error(error.message);
2883
+ return data ?? null;
2884
+ },
2885
+ async authorizerByPin(pin, action) {
2886
+ const { data, error } = await db().rpc("comanda_authorizer_by_pin", {
2887
+ p_pin: pin,
2888
+ p_action: action ?? null
2889
+ });
2890
+ if (error) throw new Error(error.message);
2891
+ return data ?? null;
2892
+ },
1901
2893
  // -- Participantes --------------------------------------------------------
1902
- async addGuest(orderId, label) {
2894
+ async addGuest(orderId, label, identity) {
1903
2895
  const tenantId = tenant();
1904
2896
  const { data: taken } = await db().from(GUESTS).select("seat_no").eq("order_id", orderId).order("seat_no");
1905
2897
  const used = new Set((taken ?? []).map((r) => Number(r.seat_no)));
@@ -1909,59 +2901,153 @@ function createCoreTablesProvider(options) {
1909
2901
  tenant_id: tenantId,
1910
2902
  order_id: orderId,
1911
2903
  seat_no: seat,
1912
- label: label ?? null
1913
- }).select("id, seat_no, label").single();
2904
+ label: identity?.label ?? label ?? null,
2905
+ phone: identity?.phone ?? null,
2906
+ person_id: identity?.personId ?? null
2907
+ }).select("id, seat_no, label, phone, person_id").single();
1914
2908
  if (error) throw new Error(error.message);
1915
2909
  return {
1916
2910
  id: data.id,
1917
2911
  seatNo: Number(data.seat_no),
1918
2912
  label: data.label ?? void 0,
2913
+ phone: data.phone ?? void 0,
2914
+ personId: data.person_id ?? void 0,
1919
2915
  serviceChargePercent: 0,
1920
2916
  subtotal: 0,
1921
2917
  serviceCharge: 0,
1922
2918
  cancelledTotal: 0,
1923
- itemCount: 0
2919
+ itemCount: 0,
2920
+ paidTotal: 0,
2921
+ settled: false
1924
2922
  };
1925
2923
  },
2924
+ /**
2925
+ * Dar nome a uma cadeira.
2926
+ *
2927
+ * Só grava o que veio: identificar pelo telefone não pode apagar um nome
2928
+ * que já estava lá, e a tela manda um campo de cada vez conforme o
2929
+ * operador descobre quem é quem.
2930
+ */
2931
+ async identifyGuest(guestId, identity) {
2932
+ requireWrites();
2933
+ const patch = {};
2934
+ if (identity.label !== void 0) patch.label = identity.label || null;
2935
+ if (identity.phone !== void 0) patch.phone = identity.phone || null;
2936
+ if (identity.personId !== void 0) patch.person_id = identity.personId || null;
2937
+ if (Object.keys(patch).length === 0) return;
2938
+ const { data: mudados, error } = await db().from(GUESTS).update(patch).eq("id", guestId).select("id");
2939
+ if (error) throw new Error(error.message);
2940
+ assertTocou(mudados, "a identifica\xE7\xE3o do participante");
2941
+ const dono = await db().from(GUESTS).select("order_id").eq("id", guestId).maybeSingle();
2942
+ const orderId = dono.data?.order_id;
2943
+ if (orderId) await db().rpc("comanda_apply_cover_charges", { p_order_id: orderId });
2944
+ },
1926
2945
  async removeGuest(guestId) {
1927
2946
  requireWrites();
1928
2947
  const { data: guest } = await db().from(GUESTS).select("order_id").eq("id", guestId).maybeSingle();
1929
- const { error } = await db().from(GUESTS).delete().eq("id", guestId);
2948
+ const { count } = await db().from(ITEM_GUESTS).select("item_id", { count: "exact", head: true }).eq("guest_id", guestId);
2949
+ const { data: removidos, error } = await db().from(GUESTS).delete().eq("id", guestId).select("id");
1930
2950
  if (error) throw new Error(error.message);
2951
+ assertTocou(removidos, "a sa\xEDda do participante");
1931
2952
  if (guest?.order_id) await recalc(guest.order_id);
2953
+ return { movedLines: count ?? 0 };
1932
2954
  },
1933
2955
  async setGuestServiceCharge(guestId, percent) {
1934
2956
  requireWrites();
1935
2957
  const { data: guest } = await db().from(GUESTS).select("order_id").eq("id", guestId).maybeSingle();
1936
- const { error } = await db().from(GUESTS).update({ service_charge_percent: percent }).eq("id", guestId);
2958
+ const { data: ajustados, error } = await db().from(GUESTS).update({ service_charge_percent: percent }).eq("id", guestId).select("id");
1937
2959
  if (error) throw new Error(error.message);
2960
+ assertTocou(ajustados, "a taxa deste participante");
1938
2961
  if (guest?.order_id) await recalc(guest.order_id);
1939
2962
  },
1940
- async setOrderServiceCharge(orderId, percent) {
2963
+ async setOrderServiceCharge(orderId, percent, audit) {
2964
+ requireWrites();
2965
+ if (audit && (audit.operationKey || audit.authorizedByName || audit.reason)) {
2966
+ const { data: antes } = await db().from(ORDER_EXT).select("service_charge_percent, service_charge_amount").eq("order_id", orderId).maybeSingle();
2967
+ const linha = antes ?? null;
2968
+ const antesDoPercentual = linha == null ? { missing: true } : { percent: linha.service_charge_percent == null ? null : Number(linha.service_charge_percent) };
2969
+ const { error: auditError } = await db().from(SERVICE_AUDIT).insert({
2970
+ tenant_id: tenant(),
2971
+ order_id: orderId,
2972
+ action: "set_rate",
2973
+ operation_key: audit.operationKey ?? null,
2974
+ reason: audit.reason?.trim() || null,
2975
+ authorized_by_name: audit.authorizedByName ?? null,
2976
+ before_state: antesDoPercentual,
2977
+ after_state: { percent }
2978
+ });
2979
+ if (auditError && !String(auditError.message).includes("duplicate key")) {
2980
+ throw new Error(
2981
+ "N\xE3o foi poss\xEDvel registrar quem autorizou a mudan\xE7a da taxa, e por isso ela N\xC3O foi alterada. A comanda segue com o percentual anterior."
2982
+ );
2983
+ }
2984
+ }
2985
+ const { data: ajustada, error } = await db().from(ORDER_EXT).update({ service_charge_percent: percent }).eq("order_id", orderId).select("order_id");
2986
+ if (error) throw new Error(error.message);
2987
+ assertTocou(ajustada, "a taxa desta comanda");
2988
+ await recalc(orderId);
2989
+ },
2990
+ /**
2991
+ * TIRAR o abatimento de uma linha.
2992
+ *
2993
+ * A lixeira do V1 (`pendingRemoval`), que o V2 não tinha: um desconto
2994
+ * lançado no item errado — ou com o valor errado — não tinha volta, e o
2995
+ * único caminho era cancelar a linha e lançá-la de novo, o que troca um
2996
+ * erro de desconto por um cancelamento no relatório do turno.
2997
+ *
2998
+ * Devolve a linha ao bruto: `discount = 0` e `total = preço × quantidade`.
2999
+ * É o inverso exato do que `discountLines` escreve, e por isso não precisa
3000
+ * saber QUAL desconto foi dado — precisa saber que agora não há nenhum.
3001
+ */
3002
+ async removeLineDiscount(orderId, lineIds) {
1941
3003
  requireWrites();
1942
- const { error } = await db().from(ORDER_EXT).update({ service_charge_percent: percent }).eq("order_id", orderId);
3004
+ if (lineIds.length === 0) return;
3005
+ const { data: lines, error } = await db().from(LINES).select("id, name, quantity, unit_price, discount").in("id", lineIds);
1943
3006
  if (error) throw new Error(error.message);
3007
+ for (const line of lines ?? []) {
3008
+ if (num(line.discount) <= 0) continue;
3009
+ const gross = num(line.unit_price) * num(line.quantity);
3010
+ const { data: limpas, error: upError } = await db().from(LINES).update({ discount: 0, total: gross }).eq("id", line.id).select("id");
3011
+ if (upError) throw new Error(upError.message);
3012
+ assertTocou(limpas, `a remo\xE7\xE3o do desconto em ${line.name ?? "um item"}`);
3013
+ }
1944
3014
  await recalc(orderId);
1945
3015
  },
3016
+ async waivePendingServiceCharge(orderId, input) {
3017
+ requireWrites();
3018
+ const { data, error } = await db().rpc("comanda_waive_pending_service_charge", {
3019
+ p_order_id: orderId,
3020
+ p_reason: input.reason,
3021
+ p_authorizer: input.authorizerName ?? null,
3022
+ p_operation_key: input.operationKey ?? null
3023
+ });
3024
+ if (error) throw new Error(error.message);
3025
+ return data;
3026
+ },
1946
3027
  // -- Desconto -------------------------------------------------------------
1947
3028
  async discountLines(orderId, input) {
1948
3029
  requireWrites();
1949
3030
  if (input.lineIds.length === 0) return;
1950
3031
  const { data: lines, error } = await db().from(LINES).select("id, quantity, unit_price").in("id", input.lineIds);
1951
3032
  if (error) throw new Error(error.message);
3033
+ const brutoDe = (l) => Math.round(num(l.unit_price) * num(l.quantity) * 100);
3034
+ const fatias = input.mode === "percent" ? null : fixedDiscountShares({
3035
+ lines: (lines ?? []).map((l) => ({ id: l.id, grossCents: brutoDe(l) })),
3036
+ amountCents: Math.round(input.value * 100)
3037
+ });
1952
3038
  for (const line of lines ?? []) {
1953
3039
  const gross = num(line.unit_price) * num(line.quantity);
1954
- const raw = input.mode === "percent" ? gross * (input.value / 100) : input.value;
1955
- const discount = Math.min(Math.max(raw, 0), gross);
1956
- const { error: upError } = await db().from(LINES).update({ discount, total: gross - discount }).eq("id", line.id);
3040
+ const discount = fatias ? (fatias.get(line.id) ?? 0) / 100 : Math.min(Math.max(gross * (input.value / 100), 0), gross);
3041
+ const { data: descontadas, error: upError } = await db().from(LINES).update({ discount, total: gross - discount }).eq("id", line.id).select("id");
1957
3042
  if (upError) throw new Error(upError.message);
3043
+ assertTocou(descontadas, `o desconto em ${line.name ?? "um item"}`);
1958
3044
  }
1959
3045
  await recalc(orderId);
1960
3046
  },
1961
3047
  // -- Cancelamento ---------------------------------------------------------
1962
3048
  // -- A política da taxa ---------------------------------------------------
1963
3049
  async getServiceChargePresets() {
1964
- const { data, error } = await db().from(SERVICE_PRESETS).select("id, name, percent, is_default, position").order("position").order("percent");
3050
+ const { data, error } = await db().from(SERVICE_PRESETS).select("id, name, percent, is_default, position").eq("is_active", true).order("position").order("percent");
1965
3051
  if (error) throw new Error(error.message);
1966
3052
  return (data ?? []).map(rowToPreset);
1967
3053
  },
@@ -1978,18 +3064,21 @@ function createCoreTablesProvider(options) {
1978
3064
  const row = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
1979
3065
  if (patch.name != null) row.name = patch.name;
1980
3066
  if (patch.percent != null) row.percent = patch.percent;
1981
- const { error } = await db().from(SERVICE_PRESETS).update(row).eq("id", id);
3067
+ const { data: mudados, error } = await db().from(SERVICE_PRESETS).update(row).eq("id", id).select("id");
1982
3068
  if (error) throw new Error(error.message);
3069
+ assertTocou(mudados, "a altera\xE7\xE3o da taxa predefinida");
1983
3070
  },
1984
3071
  async deleteServiceChargePreset(id) {
1985
3072
  requireWrites();
1986
- const { error } = await db().from(SERVICE_PRESETS).delete().eq("id", id);
3073
+ const { data: apagadas, error } = await db().from(SERVICE_PRESETS).delete().eq("id", id).select("id");
1987
3074
  if (error) throw new Error(error.message);
3075
+ assertTocou(apagadas, "a remo\xE7\xE3o da taxa predefinida");
1988
3076
  },
1989
3077
  async setDefaultServiceChargePreset(id) {
1990
3078
  requireWrites();
1991
- const { error } = await db().from(SERVICE_PRESETS).update({ is_default: true, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id);
3079
+ const { data: marcada, error } = await db().from(SERVICE_PRESETS).update({ is_default: true, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select("id");
1992
3080
  if (error) throw new Error(error.message);
3081
+ assertTocou(marcada, "a taxa padr\xE3o da casa");
1993
3082
  },
1994
3083
  async getServiceChargeExemptions() {
1995
3084
  const { data, error } = await db().from(SERVICE_EXEMPTIONS).select("id, target_kind, target_id");
@@ -2111,22 +3200,52 @@ function createCoreTablesProvider(options) {
2111
3200
  if (patch.qtyIdentified != null) row.qty_identified = patch.qtyIdentified;
2112
3201
  if (patch.qtyUnidentified != null) row.qty_unidentified = patch.qtyUnidentified;
2113
3202
  if (patch.isActive != null) row.is_active = patch.isActive;
2114
- const { error } = await db().from(COVER_CHARGES).update(row).eq("id", id);
3203
+ const { data: mudados, error } = await db().from(COVER_CHARGES).update(row).eq("id", id).select("id");
2115
3204
  if (error) throw new Error(error.message);
3205
+ assertTocou(mudados, "a altera\xE7\xE3o do couvert");
2116
3206
  if (patch.zoneIds || patch.schedules) await writeCoverScope(id, tenantId, patch);
2117
3207
  },
2118
3208
  async deleteCoverCharge(id) {
2119
3209
  requireWrites();
2120
- const { error } = await db().from(COVER_CHARGES).delete().eq("id", id);
3210
+ const { data: apagados, error } = await db().from(COVER_CHARGES).delete().eq("id", id).select("id");
2121
3211
  if (error) throw new Error(error.message);
3212
+ assertTocou(apagados, "a remo\xE7\xE3o do couvert");
2122
3213
  },
2123
3214
  async applyCoverCharges(orderId) {
2124
3215
  requireWrites();
2125
3216
  const { error } = await db().rpc("comanda_apply_cover_charges", { p_order_id: orderId });
2126
3217
  if (error) throw new Error(error.message);
2127
3218
  },
3219
+ async getOrderDiscounts(orderId) {
3220
+ const { data, error } = await db().from(DISCOUNT_GRANTS).select("id, item_id, percent, amount, notes, reason_id, approved_by_user_id, created_at").eq("order_id", orderId).order("created_at", { ascending: false });
3221
+ if (error) throw new Error(error.message);
3222
+ const linhas = data ?? [];
3223
+ if (linhas.length === 0) return [];
3224
+ const itemIds = [...new Set(linhas.map((r) => r.item_id).filter(Boolean))];
3225
+ const reasonIds = [...new Set(linhas.map((r) => r.reason_id).filter(Boolean))];
3226
+ const [itens, motivos] = await Promise.all([
3227
+ itemIds.length ? db().from(LINES).select("id, name").in("id", itemIds) : Promise.resolve({ data: [] }),
3228
+ reasonIds.length ? db().from(DISCOUNT_REASONS).select("id, name").in("id", reasonIds) : Promise.resolve({ data: [] })
3229
+ ]);
3230
+ const nomeDoItem = new Map(
3231
+ (itens.data ?? []).map((r) => [r.id, r.name ?? ""])
3232
+ );
3233
+ const nomeDoMotivo = new Map(
3234
+ (motivos.data ?? []).map((r) => [r.id, r.name ?? ""])
3235
+ );
3236
+ return linhas.map((r) => ({
3237
+ id: r.id,
3238
+ itemName: r.item_id ? nomeDoItem.get(r.item_id) ?? null : null,
3239
+ percent: r.percent == null ? null : num(r.percent),
3240
+ amount: num(r.amount),
3241
+ reasonName: r.reason_id ? nomeDoMotivo.get(r.reason_id) ?? null : null,
3242
+ memo: r.notes ?? null,
3243
+ approvedByName: null,
3244
+ createdAt: r.created_at ?? null
3245
+ }));
3246
+ },
2128
3247
  async getCancelReasons() {
2129
- const { data, error } = await db().from(CANCEL_REASONS).select("id, label, is_active, sort_order").order("sort_order");
3248
+ const { data, error } = await db().from(CANCEL_REASONS).select("id, label, is_active, sort_order").order("sort_order").order("label");
2130
3249
  if (error) throw new Error(error.message);
2131
3250
  return (data ?? []).map((r) => ({
2132
3251
  id: r.id,
@@ -2148,49 +3267,141 @@ function createCoreTablesProvider(options) {
2148
3267
  if (patch.label != null) row.label = patch.label;
2149
3268
  if (patch.isActive != null) row.is_active = patch.isActive;
2150
3269
  if (patch.sortOrder != null) row.sort_order = patch.sortOrder;
2151
- const { error } = await db().from(CANCEL_REASONS).update(row).eq("id", id);
3270
+ const { data: mudados, error } = await db().from(CANCEL_REASONS).update(row).eq("id", id).select("id");
2152
3271
  if (error) throw new Error(error.message);
3272
+ assertTocou(mudados, "a altera\xE7\xE3o do motivo de cancelamento");
2153
3273
  },
2154
3274
  async deleteCancelReason(id) {
2155
3275
  requireWrites();
2156
- const { error } = await db().from(CANCEL_REASONS).delete().eq("id", id);
3276
+ const { data: apagados, error } = await db().from(CANCEL_REASONS).delete().eq("id", id).select("id");
2157
3277
  if (error) throw new Error(error.message);
2158
- },
3278
+ assertTocou(apagados, "a remo\xE7\xE3o do motivo de cancelamento");
3279
+ },
3280
+ /**
3281
+ * Cancelamento POR QUANTIDADE.
3282
+ *
3283
+ * Cancelar a linha inteira é o caso fácil: marca e pronto. O caso que
3284
+ * importa é o parcial — três chopes saíram, um voltou. A linha original
3285
+ * encolhe para dois e nasce uma linha CANCELADA com um. Duas razões para
3286
+ * ser assim, e não um contador na mesma linha:
3287
+ *
3288
+ * - a linha cancelada continua na comanda, riscada, e é dela que sai o
3289
+ * "Top Itens Cancelados" com nome e dinheiro;
3290
+ * - a conta volta a fechar sozinha, porque `comanda_recalc` soma o que
3291
+ * não está cancelado — sem regra nova em lugar nenhum.
3292
+ *
3293
+ * Marca, nunca apaga: apagar seria mais simples e levaria junto o único
3294
+ * relatório do V1 que presta.
3295
+ */
2159
3296
  async cancelLines(orderId, input) {
2160
3297
  requireWrites();
2161
- if (input.lineIds.length === 0) return;
2162
- const { error } = await db().from(LINES).update({ cancelled_at: (/* @__PURE__ */ new Date()).toISOString(), cancel_reason: input.reason }).in("id", input.lineIds);
2163
- if (error) throw new Error(error.message);
3298
+ const pedidos = (input.lines ?? []).filter((l) => l.quantity > 0);
3299
+ if (pedidos.length === 0) return [];
3300
+ const tenantId = tenant();
3301
+ const agora = (/* @__PURE__ */ new Date()).toISOString();
3302
+ if (input.operationKey) {
3303
+ const { data: jaFeito } = await db().from(LINES).select("id, quantity, metadata").eq("order_id", orderId).not("cancelled_at", "is", null);
3304
+ const jaSaiu = cancelReplayResults(jaFeito ?? [], input.operationKey);
3305
+ if (jaSaiu.length > 0) return jaSaiu;
3306
+ }
3307
+ const marca = input.operationKey ? { cancel_operation_key: input.operationKey } : {};
3308
+ const { data: atuais, error: readError } = await db().from(LINES).select("id, product_id, name, quantity, unit_price, discount, sort_order, metadata, cancelled_at").in("id", pedidos.map((l) => l.lineId));
3309
+ if (readError) throw new Error(readError.message);
3310
+ const porId = new Map((atuais ?? []).map((r) => [r.id, r]));
3311
+ const saiu = [];
3312
+ for (const pedido of pedidos) {
3313
+ const linha = porId.get(pedido.lineId);
3314
+ if (!linha || linha.cancelled_at) continue;
3315
+ const tinha = Number(linha.quantity) || 0;
3316
+ const corta = Math.min(pedido.quantity, tinha);
3317
+ if (corta <= 0) continue;
3318
+ if (corta >= tinha) {
3319
+ const { data: canceladas, error } = await db().from(LINES).update({
3320
+ cancelled_at: agora,
3321
+ cancel_reason: input.reason,
3322
+ metadata: { ...linha.metadata ?? {}, ...marca }
3323
+ }).eq("id", linha.id).select("id");
3324
+ if (error) throw new Error(error.message);
3325
+ assertTocou(canceladas, `o cancelamento de ${linha.name ?? "um item"}`);
3326
+ saiu.push({ lineId: linha.id, cancelledQuantity: tinha, fullyCancelled: true });
3327
+ continue;
3328
+ }
3329
+ const resta = tinha - corta;
3330
+ const preco = Number(linha.unit_price) || 0;
3331
+ const { data: encolhidas, error: upError } = await db().from(LINES).update({ quantity: resta, total: preco * resta }).eq("id", linha.id).select("id");
3332
+ if (upError) throw new Error(upError.message);
3333
+ assertTocou(encolhidas, `a redu\xE7\xE3o de ${linha.name ?? "um item"}`);
3334
+ const { data: nova, error: insError } = await db().from(LINES).insert({
3335
+ tenant_id: tenantId,
3336
+ order_id: orderId,
3337
+ product_id: linha.product_id,
3338
+ name: linha.name,
3339
+ quantity: corta,
3340
+ unit_price: preco,
3341
+ discount: 0,
3342
+ total: preco * corta,
3343
+ sort_order: linha.sort_order,
3344
+ // `cancelled_from` é o que permite o resultado da repetição falar do id
3345
+ // da ORIGINAL, que é o que a tela compara item a item.
3346
+ metadata: { ...linha.metadata ?? {}, ...marca, cancelled_from: linha.id },
3347
+ cancelled_at: agora,
3348
+ cancel_reason: input.reason
3349
+ }).select("id").single();
3350
+ if (insError) throw new Error(insError.message);
3351
+ const { data: dono } = await db().from(ITEM_GUESTS).select("guest_id").eq("item_id", linha.id).maybeSingle();
3352
+ if (dono?.guest_id && nova?.id) {
3353
+ await db().from(ITEM_GUESTS).insert({
3354
+ item_id: nova.id,
3355
+ guest_id: dono.guest_id,
3356
+ tenant_id: tenantId
3357
+ });
3358
+ }
3359
+ saiu.push({ lineId: linha.id, cancelledQuantity: corta, fullyCancelled: false });
3360
+ }
2164
3361
  await recalc(orderId);
3362
+ return saiu;
2165
3363
  },
2166
3364
  // -- Transferência --------------------------------------------------------
2167
3365
  async transfer(orderId, input) {
2168
3366
  const tenantId = tenant();
3367
+ if (input.operationKey) {
3368
+ const { data: jaFoi } = await db().from(TRANSFERS).select("id").eq("tenant_id", tenantId).eq("operation_key", input.operationKey).maybeSingle();
3369
+ if (jaFoi) return;
3370
+ }
2169
3371
  const audit = {
2170
3372
  tenant_id: tenantId,
2171
3373
  order_id: orderId,
2172
3374
  kind: input.kind,
2173
3375
  note: input.note ?? null,
2174
- item_ids: input.lineIds ?? []
3376
+ item_ids: input.lineIds ?? [],
3377
+ // A folha PROMETE «Fica registrado quem autorizou.» — e esta era a
3378
+ // única das quatro ações que deixava a coluna nula. Ver `TransferInput`.
3379
+ authorized_by_name: input.authorizedByName ?? null,
3380
+ ...input.operationKey ? { operation_key: input.operationKey } : {}
2175
3381
  };
2176
3382
  if (input.kind === "table") {
2177
3383
  if (!input.toTableId) throw new Error("Escolha a mesa de destino");
2178
3384
  const { data: current } = await db().from(ORDER_EXT).select("table_id").eq("order_id", orderId).maybeSingle();
2179
3385
  const { data: busy } = await db().from(ORDER_EXT).select("order_id, orders!inner(status)").eq("table_id", input.toTableId).not("orders.status", "in", '("completed","cancelled")').limit(1);
2180
3386
  if ((busy ?? []).length > 0) throw new Error("A mesa de destino j\xE1 tem comanda aberta");
2181
- const { error } = await db().from(ORDER_EXT).update({ table_id: input.toTableId }).eq("order_id", orderId);
3387
+ const { data: mudadas, error } = await db().from(ORDER_EXT).update({ table_id: input.toTableId }).eq("order_id", orderId).select("order_id");
2182
3388
  if (error) throw new Error(error.message);
3389
+ assertTocou(mudadas, "a transfer\xEAncia da comanda");
2183
3390
  audit.from_table_id = current?.table_id ?? null;
2184
3391
  audit.to_table_id = input.toTableId;
2185
3392
  } else if (input.kind === "guest") {
2186
3393
  if (!input.guestId || !input.toOrderId) throw new Error("Escolha o participante e a comanda de destino");
2187
- const { error } = await db().from(GUESTS).update({ order_id: input.toOrderId }).eq("id", input.guestId);
3394
+ const { data: movidos, error } = await db().from(GUESTS).update({ order_id: input.toOrderId }).eq("id", input.guestId).select("id");
2188
3395
  if (error) throw new Error(error.message);
3396
+ assertTocou(movidos, "a transfer\xEAncia do participante");
2189
3397
  const { data: moved } = await db().from(ITEM_GUESTS).select("item_id").eq("guest_id", input.guestId);
2190
3398
  const ids = (moved ?? []).map((r) => r.item_id);
2191
3399
  if (ids.length > 0) {
2192
- const { error: itemError } = await db().from(LINES).update({ order_id: input.toOrderId }).in("id", ids);
3400
+ const { data: levados, error: itemError } = await db().from(LINES).update({ order_id: input.toOrderId }).in("id", ids).select("id");
2193
3401
  if (itemError) throw new Error(itemError.message);
3402
+ if ((levados ?? []).length !== ids.length) {
3403
+ throw new Error("O servidor n\xE3o confirmou a transfer\xEAncia de todos os itens do participante.");
3404
+ }
2194
3405
  }
2195
3406
  audit.guest_id = input.guestId;
2196
3407
  audit.target_order_id = input.toOrderId;
@@ -2213,7 +3424,7 @@ function createCoreTablesProvider(options) {
2213
3424
  await recalc(orderId);
2214
3425
  },
2215
3426
  async getTransfers(orderId) {
2216
- const { data, error } = await db().from(TRANSFERS).select("id, kind, from_table_id, to_table_id, guest_id, item_ids, note, created_at").eq("order_id", orderId).order("created_at", { ascending: false });
3427
+ const { data, error } = await db().from(TRANSFERS).select("id, kind, from_table_id, to_table_id, guest_id, item_ids, note, created_at, authorized_by_name").eq("order_id", orderId).order("created_at", { ascending: false });
2217
3428
  if (error) throw new Error(error.message);
2218
3429
  const rows = data ?? [];
2219
3430
  const tableIds = Array.from(new Set(
@@ -2229,13 +3440,17 @@ function createCoreTablesProvider(options) {
2229
3440
  toTableName: named(r.to_table_id),
2230
3441
  itemCount: (r.item_ids ?? []).length,
2231
3442
  note: r.note ?? void 0,
3443
+ authorizedByName: r.authorized_by_name ?? void 0,
2232
3444
  createdAt: r.created_at
2233
3445
  }));
2234
3446
  },
2235
3447
  async updateSessionGuests(orderId, guests) {
2236
3448
  requireWrites();
2237
- const { error } = await db().from(ORDER_EXT).update({ guests }).eq("order_id", orderId);
3449
+ const { data: atualizada, error } = await db().from(ORDER_EXT).update({ guests }).eq("order_id", orderId).select("order_id");
2238
3450
  if (error) throw new Error(error.message);
3451
+ assertTocou(atualizada, "o n\xFAmero de pessoas na comanda");
3452
+ const { error: couvert } = await db().rpc("comanda_apply_cover_charges", { p_order_id: orderId });
3453
+ if (couvert) throw new Error(couvert.message);
2239
3454
  },
2240
3455
  async getSummary() {
2241
3456
  const tables = await loadTables();
@@ -2254,12 +3469,782 @@ function createCoreTablesProvider(options) {
2254
3469
  }
2255
3470
  };
2256
3471
  }
3472
+ var NO_NAME = {
3473
+ field: "name",
3474
+ title: "Informe o nome do KDS"
3475
+ };
3476
+ var NO_ITEMS = {
3477
+ field: "catalog",
3478
+ title: "Selecione ao menos um item",
3479
+ description: "Marque uma categoria, um produto ou use \u201CTodos os itens\u201D."
3480
+ };
3481
+ function refuseStation(draft) {
3482
+ if (!draft.name.trim()) return NO_NAME;
3483
+ if (draft.role === "produce" && draft.catalogMode === "selected" && draft.selectedProductCount === 0 && !draft.fallback) return NO_ITEMS;
3484
+ return null;
3485
+ }
3486
+ var NAME_MAX = 80;
3487
+ var TARGET_MIN = 1;
3488
+ var TARGET_MAX = 240;
3489
+ var ORDER_MIN = 0;
3490
+ var ORDER_MAX = 999;
3491
+ var UNCATEGORIZED_KEY = "uncategorized";
3492
+ var UNCATEGORIZED_LABEL = "Sem categoria";
3493
+ function categoryKey(category) {
3494
+ return category.id === null ? UNCATEGORIZED_KEY : category.id;
3495
+ }
3496
+ function normalizeTerm(value) {
3497
+ return value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLocaleLowerCase("pt-BR");
3498
+ }
3499
+ function groupCatalog(categories, products) {
3500
+ const grouped = categories.map((c) => ({ id: c.id, name: c.name, products: [] }));
3501
+ const byId = new Map(grouped.map((c) => [c.id, c]));
3502
+ const soltos = { id: null, name: UNCATEGORIZED_LABEL, products: [] };
3503
+ for (const p of products) {
3504
+ const alvo = (p.categoryId ? byId.get(p.categoryId) : void 0) ?? soltos;
3505
+ alvo.products.push({ id: p.id, name: p.name });
3506
+ }
3507
+ if (soltos.products.length > 0) grouped.push(soltos);
3508
+ return grouped;
3509
+ }
3510
+ function filterCatalog(categories, search) {
3511
+ const termo = normalizeTerm(search.trim());
3512
+ if (!termo) {
3513
+ return categories.map((c) => ({ category: c, visibleProducts: c.products, matchedByName: false }));
3514
+ }
3515
+ const saida = [];
3516
+ for (const category of categories) {
3517
+ const porNome = normalizeTerm(category.name).includes(termo);
3518
+ const casaram = category.products.filter((p) => normalizeTerm(p.name).includes(termo));
3519
+ if (!porNome && casaram.length === 0) continue;
3520
+ saida.push({
3521
+ category,
3522
+ visibleProducts: porNome ? category.products : casaram,
3523
+ matchedByName: porNome
3524
+ });
3525
+ }
3526
+ return saida;
3527
+ }
3528
+ function isWholeCategory(category, selection) {
3529
+ return category.id !== null && selection.categoryIds.includes(category.id);
3530
+ }
3531
+ function categoryCount(category, selection) {
3532
+ if (isWholeCategory(category, selection)) return category.products.length;
3533
+ return category.products.filter((p) => selection.productIds.includes(p.id)).length;
3534
+ }
3535
+ function categoryState(category, selection) {
3536
+ if (isWholeCategory(category, selection)) return true;
3537
+ const marcados = categoryCount(category, selection);
3538
+ if (marcados === 0) return false;
3539
+ return marcados === category.products.length ? true : "indeterminate";
3540
+ }
3541
+ function toggleCategory(selection, category, checked) {
3542
+ const produtos = new Set(selection.productIds);
3543
+ const categorias = new Set(selection.categoryIds);
3544
+ if (category.id === null) {
3545
+ for (const p of category.products) checked ? produtos.add(p.id) : produtos.delete(p.id);
3546
+ } else if (checked) {
3547
+ categorias.add(category.id);
3548
+ for (const p of category.products) produtos.delete(p.id);
3549
+ } else {
3550
+ categorias.delete(category.id);
3551
+ for (const p of category.products) produtos.delete(p.id);
3552
+ }
3553
+ return { categoryIds: [...categorias], productIds: [...produtos] };
3554
+ }
3555
+ function toggleProduct(selection, category, productId, checked) {
3556
+ const categorias = new Set(selection.categoryIds);
3557
+ const produtos = new Set(selection.productIds);
3558
+ if (category.id !== null && categorias.has(category.id)) {
3559
+ categorias.delete(category.id);
3560
+ for (const p of category.products) {
3561
+ if (p.id !== productId || checked) produtos.add(p.id);
3562
+ }
3563
+ }
3564
+ if (checked) produtos.add(productId);
3565
+ else produtos.delete(productId);
3566
+ if (category.id !== null && category.products.length > 0 && category.products.every((p) => produtos.has(p.id))) {
3567
+ categorias.add(category.id);
3568
+ for (const p of category.products) produtos.delete(p.id);
3569
+ }
3570
+ return { categoryIds: [...categorias], productIds: [...produtos] };
3571
+ }
3572
+ function selectedProductCount(categories, selection, options) {
3573
+ if (options?.role === "expo") {
3574
+ return categories.reduce((s, c) => s + c.products.length, 0);
3575
+ }
3576
+ if (options?.catalogMode === "all") {
3577
+ return categories.filter((c) => c.id !== null).reduce((s, c) => s + c.products.length, 0);
3578
+ }
3579
+ const ids = new Set(selection.productIds);
3580
+ for (const c of categories) {
3581
+ if (isWholeCategory(c, selection)) for (const p of c.products) ids.add(p.id);
3582
+ }
3583
+ return ids.size;
3584
+ }
3585
+ function uncategorizedCount(categories) {
3586
+ return categories.filter((c) => c.id === null).reduce((s, c) => s + c.products.length, 0);
3587
+ }
3588
+ function expandToWholeCatalog(categories) {
3589
+ return {
3590
+ categoryIds: categories.map((c) => c.id).filter((id) => id !== null),
3591
+ productIds: []
3592
+ };
3593
+ }
3594
+ function coversWholeCatalog(categories, selection) {
3595
+ const comId = categories.filter((c) => c.id !== null);
3596
+ if (comId.length === 0) return false;
3597
+ if (selection.productIds.length > 0) return false;
3598
+ const marcadas = new Set(selection.categoryIds);
3599
+ return comId.every((c) => marcadas.has(c.id));
3600
+ }
3601
+ var STATIONS = "plg_kds_stations";
3602
+ var ROUTING = "plg_kds_routing";
3603
+ function keyOf(label) {
3604
+ const base = label.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
3605
+ return /^[a-z]/.test(base) ? base.slice(0, 40) : `kds-${base}`.slice(0, 40);
3606
+ }
3607
+ async function paginate(page, size = 1e3) {
3608
+ const todos = [];
3609
+ for (let from = 0; ; from += size) {
3610
+ const { data, error } = await page(from, from + size - 1);
3611
+ if (error) throw new Error(error.message);
3612
+ todos.push(...data ?? []);
3613
+ if (!data || data.length < size) break;
3614
+ }
3615
+ return todos;
3616
+ }
3617
+ function createKdsProvider(opts) {
3618
+ const db = () => {
3619
+ const c = getSupabaseClientOptional();
3620
+ if (!c) throw new Error("Sem conex\xE3o com o banco.");
3621
+ return c;
3622
+ };
3623
+ const tenant = () => {
3624
+ const t = opts.tenantId();
3625
+ if (!t) throw new Error("Sem inquilino ativo.");
3626
+ return t;
3627
+ };
3628
+ const syncRouting = async (stationId, input) => {
3629
+ const tenantId = tenant();
3630
+ const unitId = input.unitId !== void 0 ? input.unitId : opts.unitId?.() ?? null;
3631
+ const { error: limpou } = await db().from(ROUTING).delete().eq("station_id", stationId);
3632
+ if (limpou) throw new Error(limpou.message);
3633
+ const novas = [];
3634
+ const comum = { tenant_id: tenantId, unit_id: unitId, station_id: stationId };
3635
+ if (input.fallback) novas.push({ ...comum, match_kind: "fallback" });
3636
+ for (const c of input.categoryIds) novas.push({ ...comum, match_kind: "category", category_id: c });
3637
+ for (const p of input.productIds) novas.push({ ...comum, match_kind: "product", product_id: p });
3638
+ if (novas.length > 0) {
3639
+ const { error } = await db().from(ROUTING).insert(novas);
3640
+ if (error) throw new Error(error.message);
3641
+ }
3642
+ };
3643
+ return {
3644
+ async listCatalog() {
3645
+ const daUnidade = (q) => {
3646
+ const u = opts.unitId?.();
3647
+ return u ? q.or(`unit_id.eq.${u},unit_id.is.null`) : q;
3648
+ };
3649
+ const [cats, prods] = await Promise.all([
3650
+ paginate((from, to) => daUnidade(db().from("categories").select("id, name").eq("is_active", true)).order("sort_order").order("name").range(from, to)),
3651
+ paginate((from, to) => daUnidade(db().from("products").select("id, name, category_id").eq("is_active", true)).order("name").range(from, to))
3652
+ ]);
3653
+ return groupCatalog(
3654
+ cats.map((c) => ({ id: c.id, name: c.name ?? "" })),
3655
+ prods.map((p) => ({ id: p.id, name: p.name ?? "", categoryId: p.category_id ?? null }))
3656
+ );
3657
+ },
3658
+ async listStations() {
3659
+ const { data, error } = await db().from(STATIONS).select("id, key, label, role, sla_minutes, sort_order, is_active").order("sort_order").order("label");
3660
+ if (error) throw new Error(error.message);
3661
+ return (data ?? []).map((r) => ({
3662
+ id: r.id,
3663
+ key: r.key,
3664
+ label: r.label ?? "",
3665
+ role: r.role === "expo" ? "expo" : "produce",
3666
+ slaMinutes: r.sla_minutes ?? null,
3667
+ sortOrder: r.sort_order ?? 0,
3668
+ isActive: r.is_active !== false
3669
+ }));
3670
+ },
3671
+ async listRouting() {
3672
+ const { data, error } = await db().from(ROUTING).select("id, station_id, match_kind, category_id, product_id");
3673
+ if (error) throw new Error(error.message);
3674
+ return (data ?? []).map((r) => ({
3675
+ id: r.id,
3676
+ stationId: r.station_id,
3677
+ kind: r.match_kind,
3678
+ categoryId: r.category_id ?? null,
3679
+ productId: r.product_id ?? null
3680
+ }));
3681
+ },
3682
+ async saveStation(input) {
3683
+ const tenantId = tenant();
3684
+ const unitId = opts.unitId?.() ?? null;
3685
+ const linha = {
3686
+ tenant_id: tenantId,
3687
+ unit_id: unitId,
3688
+ label: input.label.trim(),
3689
+ role: input.role,
3690
+ sla_minutes: input.slaMinutes,
3691
+ sort_order: input.sortOrder ?? 0
3692
+ };
3693
+ let id = input.id;
3694
+ if (id) {
3695
+ const { error } = await db().from(STATIONS).update(linha).eq("id", id);
3696
+ if (error) throw new Error(error.message);
3697
+ } else {
3698
+ const { data, error } = await db().from(STATIONS).insert({ ...linha, key: keyOf(input.label) }).select("id").single();
3699
+ if (error) throw new Error(error.message);
3700
+ id = data.id;
3701
+ }
3702
+ await syncRouting(id, {
3703
+ fallback: input.fallback,
3704
+ categoryIds: input.catalogMode === "all" ? input.allCategoryIds ?? [] : input.categoryIds,
3705
+ // Produto solto só no modo específico: no «todos» ele já veio pela
3706
+ // categoria, e a linha repetida não acrescenta nada.
3707
+ productIds: input.catalogMode === "selected" ? input.productIds : [],
3708
+ unitId
3709
+ });
3710
+ return id;
3711
+ },
3712
+ syncRouting,
3713
+ async setStationActive(id, active) {
3714
+ const { error } = await db().from(STATIONS).update({ is_active: active }).eq("id", id);
3715
+ if (error) throw new Error(error.message);
3716
+ }
3717
+ };
3718
+ }
3719
+ function catalogSummary(selection, fallback, mode) {
3720
+ if (mode === "all") {
3721
+ return fallback ? "Todos os itens, e o que ningu\xE9m roteou." : "Todos os itens.";
3722
+ }
3723
+ const partes = [];
3724
+ const c = selection.categoryIds.length;
3725
+ const p = selection.productIds.length;
3726
+ if (c > 0) partes.push(`${c} categoria${c > 1 ? "s" : ""}`);
3727
+ if (p > 0) partes.push(`${p} produto${p > 1 ? "s" : ""}`);
3728
+ if (partes.length === 0) {
3729
+ return fallback ? "S\xF3 o que ningu\xE9m roteou (destino padr\xE3o)." : "Nenhum item associado.";
3730
+ }
3731
+ return `${partes.join(" e ")}${fallback ? ", e o que ningu\xE9m roteou." : "."}`;
3732
+ }
3733
+ function readStationRouting(rows, catalog) {
3734
+ const catalogo = {
3735
+ categoryIds: rows.filter((r) => r.match_kind === "category" && r.category_id).map((r) => r.category_id),
3736
+ productIds: rows.filter((r) => r.match_kind === "product" && r.product_id).map((r) => r.product_id)
3737
+ };
3738
+ const fallback = rows.some((r) => r.match_kind === "fallback");
3739
+ const catalogMode = catalog && coversWholeCatalog(catalog, catalogo) ? "all" : "selected";
3740
+ return { fallback, catalogMode, catalogo, catalogSummary: catalogSummary(catalogo, fallback, catalogMode) };
3741
+ }
3742
+ function routingToWrite(mode, selection, catalog) {
3743
+ return mode === "all" ? expandToWholeCatalog(catalog) : selection;
3744
+ }
3745
+ function asSelection(value) {
3746
+ const v = value;
3747
+ return {
3748
+ categoryIds: Array.isArray(v?.categoryIds) ? v.categoryIds : [],
3749
+ productIds: Array.isArray(v?.productIds) ? v.productIds : []
3750
+ };
3751
+ }
3752
+ var CARDAPIO_TTL_MS = 6e4;
3753
+ var cardapioEmVoo = null;
3754
+ var cardapioDe = null;
3755
+ var cardapioEm = 0;
3756
+ function loadCatalog() {
3757
+ const chave = `${getActiveTenantId() ?? ""}:${getActiveUnitId() ?? ""}`;
3758
+ const vencido = Date.now() - cardapioEm > CARDAPIO_TTL_MS;
3759
+ if (!cardapioEmVoo || cardapioDe !== chave || vencido) {
3760
+ cardapioDe = chave;
3761
+ cardapioEm = Date.now();
3762
+ cardapioEmVoo = createKdsProvider({
3763
+ tenantId: () => getActiveTenantId(),
3764
+ unitId: () => getActiveUnitId()
3765
+ }).listCatalog().catch((e) => {
3766
+ cardapioEmVoo = null;
3767
+ throw e;
3768
+ });
3769
+ }
3770
+ return cardapioEmVoo;
3771
+ }
3772
+ function KdsCatalogField({
3773
+ value,
3774
+ onChange,
3775
+ values
3776
+ }) {
3777
+ const selecao = asSelection(value);
3778
+ const modo = values.catalogMode ?? "selected";
3779
+ const role = values.role ?? "produce";
3780
+ const fallback = values.fallback === true;
3781
+ const [catalogo, setCatalogo] = React3.useState(null);
3782
+ const [erro, setErro] = React3.useState(null);
3783
+ const [busca, setBusca] = React3.useState("");
3784
+ const [abertas, setAbertas] = React3.useState(() => /* @__PURE__ */ new Set());
3785
+ React3.useEffect(() => {
3786
+ let vivo = true;
3787
+ loadCatalog().then((c) => {
3788
+ if (vivo) setCatalogo(c);
3789
+ }).catch((e) => {
3790
+ if (vivo) {
3791
+ setCatalogo([]);
3792
+ setErro(e instanceof Error ? e.message : "Falha ao ler o card\xE1pio.");
3793
+ }
3794
+ });
3795
+ return () => {
3796
+ vivo = false;
3797
+ };
3798
+ }, []);
3799
+ if (role === "expo") {
3800
+ return /* @__PURE__ */ jsx("p", { className: "rounded-lg bg-info-soft p-3 text-sm text-info-soft-foreground", children: "A tela de Expedi\xE7\xE3o recebe todos os itens para conseguir conferir e finalizar o pedido completo." });
3801
+ }
3802
+ if (catalogo === null) {
3803
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3804
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-9 w-full rounded-input" }),
3805
+ [0, 1, 2].map((i) => /* @__PURE__ */ jsx(Skeleton, { className: "h-11 w-full rounded-lg" }, i))
3806
+ ] });
3807
+ }
3808
+ const marcados = selectedProductCount(catalogo, selecao, { catalogMode: modo, role });
3809
+ const semCategoria = uncategorizedCount(catalogo);
3810
+ const filtrado = filterCatalog(catalogo, busca);
3811
+ const aplicar = (s) => onChange(s);
3812
+ const recusa = modo === "selected" && marcados === 0 && !fallback;
3813
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
3814
+ erro && /* @__PURE__ */ jsxs("p", { className: "text-xs text-destructive", role: "alert", children: [
3815
+ "N\xE3o foi poss\xEDvel ler o card\xE1pio: ",
3816
+ erro
3817
+ ] }),
3818
+ modo === "selected" && /* @__PURE__ */ jsxs(Fragment, { children: [
3819
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
3820
+ /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
3821
+ /* @__PURE__ */ jsx(
3822
+ Input,
3823
+ {
3824
+ className: "pl-9",
3825
+ value: busca,
3826
+ placeholder: "Buscar categoria ou produto\u2026",
3827
+ onChange: (e) => setBusca(e.target.value),
3828
+ "aria-label": "Buscar categoria ou produto"
3829
+ }
3830
+ )
3831
+ ] }),
3832
+ /* @__PURE__ */ jsxs("div", { className: "fz-container max-h-80 overflow-y-auto rounded-lg border", children: [
3833
+ filtrado.map(({ category, visibleProducts }) => {
3834
+ const chave = categoryKey(category);
3835
+ const estado = categoryState(category, selecao);
3836
+ const aberta = abertas.has(chave) || busca.trim() !== "";
3837
+ return /* @__PURE__ */ jsxs("div", { className: "border-b last:border-0", children: [
3838
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 bg-muted/30 px-3 py-2.5", children: [
3839
+ /* @__PURE__ */ jsx(
3840
+ "button",
3841
+ {
3842
+ type: "button",
3843
+ className: "rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",
3844
+ "aria-label": aberta ? `Recolher ${category.name}` : `Expandir ${category.name}`,
3845
+ "aria-expanded": aberta,
3846
+ onClick: () => setAbertas((atual) => {
3847
+ const proxima = new Set(atual);
3848
+ proxima.has(chave) ? proxima.delete(chave) : proxima.add(chave);
3849
+ return proxima;
3850
+ }),
3851
+ children: aberta ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
3852
+ }
3853
+ ),
3854
+ /* @__PURE__ */ jsx(
3855
+ Checkbox,
3856
+ {
3857
+ checked: estado === true,
3858
+ indeterminate: estado === "indeterminate",
3859
+ "aria-label": `Selecionar categoria ${category.name}`,
3860
+ onChange: (marcar) => aplicar(toggleCategory(selecao, category, marcar))
3861
+ }
3862
+ ),
3863
+ /* @__PURE__ */ jsxs(
3864
+ "button",
3865
+ {
3866
+ type: "button",
3867
+ className: "flex min-w-0 flex-1 items-center justify-between gap-3 text-left",
3868
+ onClick: () => setAbertas((atual) => {
3869
+ const proxima = new Set(atual);
3870
+ proxima.has(chave) ? proxima.delete(chave) : proxima.add(chave);
3871
+ return proxima;
3872
+ }),
3873
+ children: [
3874
+ /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium", children: category.name }),
3875
+ /* @__PURE__ */ jsxs(Badge, { variant: "secondary", className: "shrink-0 tabular-nums", children: [
3876
+ categoryCount(category, selecao),
3877
+ "/",
3878
+ category.products.length,
3879
+ " itens"
3880
+ ] })
3881
+ ]
3882
+ }
3883
+ )
3884
+ ] }),
3885
+ aberta && /* @__PURE__ */ jsxs("div", { className: "grid gap-0.5 px-3 py-2 fz-fields-2", children: [
3886
+ visibleProducts.map((p) => /* @__PURE__ */ jsxs(
3887
+ "label",
3888
+ {
3889
+ className: "flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/50",
3890
+ children: [
3891
+ /* @__PURE__ */ jsx(
3892
+ Checkbox,
3893
+ {
3894
+ checked: estado === true || selecao.productIds.includes(p.id),
3895
+ "aria-label": `Selecionar produto ${p.name}`,
3896
+ onChange: (marcar) => aplicar(toggleProduct(selecao, category, p.id, marcar))
3897
+ }
3898
+ ),
3899
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: p.name })
3900
+ ]
3901
+ },
3902
+ p.id
3903
+ )),
3904
+ visibleProducts.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-2 py-1.5 text-sm text-muted-foreground", children: "Nenhum item nesta categoria." })
3905
+ ] })
3906
+ ] }, chave);
3907
+ }),
3908
+ filtrado.length === 0 && /* @__PURE__ */ jsx("p", { className: "p-8 text-center text-sm text-muted-foreground", children: erro ?? "Nenhum item encontrado." })
3909
+ ] })
3910
+ ] }),
3911
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-lg bg-muted/60 px-3 py-2 text-sm", children: [
3912
+ /* @__PURE__ */ jsx(Utensils, { className: "h-4 w-4 shrink-0 text-primary" }),
3913
+ /* @__PURE__ */ jsxs("span", { children: [
3914
+ /* @__PURE__ */ jsx("strong", { className: "tabular-nums", children: marcados }),
3915
+ " ",
3916
+ marcados === 1 ? "item chegar\xE1" : "itens chegar\xE3o",
3917
+ " neste KDS."
3918
+ ] })
3919
+ ] }),
3920
+ modo === "all" && semCategoria > 0 && !fallback && /* @__PURE__ */ jsxs("p", { className: "text-xs text-warning", children: [
3921
+ semCategoria,
3922
+ " ",
3923
+ semCategoria === 1 ? "item est\xE1" : "itens est\xE3o",
3924
+ " sem categoria e n\xE3o",
3925
+ " ",
3926
+ "chegam por aqui. Ligue \xABDestino padr\xE3o\xBB para que esta tela tamb\xE9m os receba."
3927
+ ] }),
3928
+ recusa && /* @__PURE__ */ jsxs("p", { className: "text-xs text-destructive", role: "alert", children: [
3929
+ /* @__PURE__ */ jsx("strong", { children: "Selecione ao menos um item." }),
3930
+ " ",
3931
+ "Marque uma categoria, um produto ou use \u201CTodos os itens\u201D."
3932
+ ] })
3933
+ ] });
3934
+ }
3935
+
3936
+ // src/views/kdsStationEntity.ts
3937
+ function buildKdsStationEntity(options) {
3938
+ return {
3939
+ name: "Tela KDS",
3940
+ namePlural: "Telas KDS",
3941
+ icon: "Monitor",
3942
+ displayField: "label",
3943
+ defaultSort: "sortOrder",
3944
+ formColumns: 2,
3945
+ fieldGroups: [
3946
+ { id: "identidade", label: "A tela", columns: 1 },
3947
+ { id: "ritmo", label: "Ritmo e ordem", columns: 2, column: "side" },
3948
+ {
3949
+ id: "catalogo",
3950
+ label: "Itens do cat\xE1logo",
3951
+ description: "Escolha exatamente quais produtos devem chegar nesta tela.",
3952
+ columns: 1
3953
+ }
3954
+ ],
3955
+ fields: [
3956
+ {
3957
+ key: "label",
3958
+ label: "Nome do KDS",
3959
+ type: "text",
3960
+ required: true,
3961
+ searchable: true,
3962
+ showInTable: true,
3963
+ group: "identidade",
3964
+ // `max` num campo de texto é o teto de caracteres: o `maxLength={80}`
3965
+ // do V1, que a tela do V2 não tinha.
3966
+ placeholder: "Ex.: Bar, Chapa, Cozinha",
3967
+ max: NAME_MAX
3968
+ },
3969
+ {
3970
+ key: "role",
3971
+ label: "Fun\xE7\xE3o da tela",
3972
+ type: "segmented",
3973
+ showInTable: true,
3974
+ group: "identidade",
3975
+ defaultValue: "produce",
3976
+ options: [
3977
+ { label: "Produ\xE7\xE3o", value: "produce", description: "Prepara o que chega nela." },
3978
+ { label: "Expedi\xE7\xE3o", value: "expo", description: "Confere o que as outras produziram \u2014 e v\xEA a comanda inteira." }
3979
+ ]
3980
+ },
3981
+ {
3982
+ // «Sem limite» é AUSÊNCIA, não zero: uma estação sem tempo-meta não é
3983
+ // uma estação que promete zero minuto.
3984
+ key: "slaMinutes",
3985
+ label: "Tempo-meta (min)",
3986
+ type: "number",
3987
+ showInTable: true,
3988
+ group: "ritmo",
3989
+ min: TARGET_MIN,
3990
+ max: TARGET_MAX,
3991
+ placeholder: "Sem limite"
3992
+ },
3993
+ {
3994
+ // No cartão também: o V1 mostra «Ordem da tela» ao lado do
3995
+ // tempo-meta, e é ela que explica por que a Chapa aparece antes da
3996
+ // Expedição na central.
3997
+ key: "sortOrder",
3998
+ label: "Ordem na central",
3999
+ type: "number",
4000
+ showInTable: true,
4001
+ group: "ritmo",
4002
+ min: ORDER_MIN,
4003
+ max: ORDER_MAX,
4004
+ placeholder: "Autom\xE1tica"
4005
+ },
4006
+ {
4007
+ key: "isActive",
4008
+ label: "Ativa",
4009
+ type: "boolean",
4010
+ defaultValue: true,
4011
+ showInTable: true,
4012
+ inlineToggle: true,
4013
+ group: "ritmo"
4014
+ },
4015
+ // ── «Itens do catálogo» ────────────────────────────────────────────
4016
+ //
4017
+ // Os três campos abaixo NÃO são colunas de `plg_kds_stations`: cada um
4018
+ // vira linha de `plg_kds_routing`. Quem faz a tradução é o
4019
+ // `buildKdsStationProvider` — declarar aqui é o que dá a eles o rótulo,
4020
+ // o grupo e a ordem do resto do cadastro.
4021
+ {
4022
+ // A REDE DE SEGURANÇA. Sem ela, um produto novo no cardápio não chega
4023
+ // a cozinha nenhuma — e ninguém percebe até o cliente perguntar.
4024
+ key: "fallback",
4025
+ label: "Destino padr\xE3o",
4026
+ type: "boolean",
4027
+ defaultValue: false,
4028
+ group: "catalogo",
4029
+ showInTable: false,
4030
+ hint: "Recebe itens que n\xE3o foram associados a nenhuma tela de produ\xE7\xE3o."
4031
+ },
4032
+ {
4033
+ // As DUAS CARTAS do V1. `segmented` com descrição já as desenha —
4034
+ // borda destacada, título e a frase embaixo —, então não há tela
4035
+ // nova aqui, só a declaração.
4036
+ //
4037
+ // «Todos os itens» é o padrão do V1 para uma tela que já existe; um
4038
+ // cadastro NOVO nasce em «específicos», como lá.
4039
+ key: "catalogMode",
4040
+ label: "Como escolher",
4041
+ type: "segmented",
4042
+ defaultValue: "selected",
4043
+ group: "catalogo",
4044
+ showInTable: false,
4045
+ visibleWhen: (v) => v.role !== "expo",
4046
+ options: [
4047
+ { label: "Todos os itens", value: "all", description: "Tudo que for vendido chega neste KDS." },
4048
+ { label: "Categorias e produtos espec\xEDficos", value: "selected", description: "Monte o cat\xE1logo desta esta\xE7\xE3o." }
4049
+ ]
4050
+ },
4051
+ {
4052
+ // A árvore. É o único pedaço que o CRUD genérico não sabe desenhar —
4053
+ // e por isso o único que entra pela saída declarada.
4054
+ key: "catalogo",
4055
+ label: "Categorias e produtos",
4056
+ type: "custom",
4057
+ group: "catalogo",
4058
+ span: 2,
4059
+ showInTable: false,
4060
+ showInDetail: false,
4061
+ defaultValue: { categoryIds: [], productIds: [] },
4062
+ renderInput: ({ value, onChange, values }) => React3.createElement(KdsCatalogField, { value, onChange, values })
4063
+ }
4064
+ ],
4065
+ /**
4066
+ * O CARTÃO, como no V1: ícone fixo, o que a tela é sob o nome, o estado no
4067
+ * canto, os dois números em caixas, a frase do catálogo e «Abrir tela».
4068
+ *
4069
+ * A miniatura genérica não serve aqui — uma estação de cozinha não tem
4070
+ * foto, e o ícone diz a espécie melhor que um quadrado vazio.
4071
+ */
4072
+ card: {
4073
+ icon: "Monitor",
4074
+ subtitle: (s) => s.role === "expo" ? "Expedi\xE7\xE3o e confer\xEAncia" : "Esta\xE7\xE3o de produ\xE7\xE3o",
4075
+ badge: (s) => ({ label: s.isActive ? "Ativo" : "Inativo" }),
4076
+ // Os dois do V1, e «Sem limite»/«Automática» por extenso: vazio é uma
4077
+ // ESCOLHA da casa, não um campo que ninguém preencheu.
4078
+ tiles: (s) => [
4079
+ { label: "Tempo-meta", value: s.slaMinutes ? `${s.slaMinutes} min` : "Sem limite" },
4080
+ { label: "Ordem da tela", value: s.sortOrder ? String(s.sortOrder) : "Autom\xE1tica" }
4081
+ ],
4082
+ // A frase do V1, e ela é a resposta a «por que esta tela está vazia?».
4083
+ // Sem regra a estação existe e não recebe nada — o pior estado possível,
4084
+ // porque parece configurada.
4085
+ //
4086
+ // Quem leu as regras já a montou (`catalogSummary`). Antes, este trecho
4087
+ // procurava `plg_kds_routing` na linha e o provedor genérico entrega
4088
+ // `plgKdsRouting`: TODA estação, configurada ou não, dizia «Nenhum item
4089
+ // associado.».
4090
+ note: (s) => s.catalogSummary ?? "Nenhum item associado.",
4091
+ // «ABRIR TELA» — o botão do V1, com o destino que o aplicativo diz.
4092
+ //
4093
+ // A cozinha olha OUTRO app (`chef-kds`), e o endereço dele muda entre a
4094
+ // máquina de quem desenvolve e a casa do cliente. Por isso o plugin
4095
+ // declara o botão e o app diz para onde: cravar uma porta aqui acertaria
4096
+ // num lugar e erraria em todos os outros.
4097
+ //
4098
+ // Vai a CHAVE, não o uuid: é ela que o tablet guarda na barra de
4099
+ // endereços, e é ela que sobrevive a renomear «Chapa» para «Grelha». E
4100
+ // abre em outra aba porque quem configura no escritório não quer perder
4101
+ // a lista de vista.
4102
+ actions: options?.kdsUrl ? [{
4103
+ id: "open",
4104
+ label: "Abrir tela",
4105
+ icon: "MonitorPlay",
4106
+ onAction: (row) => window.open(
4107
+ `${options.kdsUrl}?station=${encodeURIComponent(row.key ?? row.id)}`,
4108
+ "_blank",
4109
+ "noopener"
4110
+ )
4111
+ }] : []
4112
+ },
4113
+ data: {
4114
+ table: "plg_kds_stations",
4115
+ tenantScoped: true,
4116
+ // Uma tela de KDS é um APARELHO, e aparelho fica numa unidade. A tabela
4117
+ // tem `unit_id` e não está em `scoped_resources`, então o cadastro
4118
+ // precisa dizer — sem isto a tela nova nasce sem unidade e aparece para
4119
+ // TODAS as filiais, ao lado das quatro do Pertinho que já têm a sua.
4120
+ // Sem unidade ativa nada muda: `resolveUnitScope` devolve null.
4121
+ unitScoped: true,
4122
+ searchColumns: ["label", "key"],
4123
+ // As REGRAS junto da estação, e não só a contagem delas: é com elas que
4124
+ // o formulário reabre com as categorias já marcadas, e o cartão diz o
4125
+ // que a tela recebe. Embutida do PostgREST — uma ida ao banco, não uma
4126
+ // por cartão.
4127
+ selectColumns: "*, plg_kds_routing(match_kind, category_id, product_id)"
4128
+ }
4129
+ };
4130
+ }
4131
+ var VIRTUAIS = ["fallback", "catalogMode", "catalogo", "catalogSummary", "plgKdsRouting"];
4132
+ function regrasDe(row) {
4133
+ const cru = row.plgKdsRouting ?? row.plg_kds_routing;
4134
+ return Array.isArray(cru) ? cru : [];
4135
+ }
4136
+ async function catalogoOuNada() {
4137
+ try {
4138
+ return await loadCatalog();
4139
+ } catch {
4140
+ return null;
4141
+ }
4142
+ }
4143
+ function buildKdsStationProvider(entityDef) {
4144
+ let generico = null;
4145
+ const inner = () => generico ?? (generico = resolveDataProvider(entityDef));
4146
+ const routing = () => createKdsProvider({
4147
+ tenantId: () => getActiveTenantId(),
4148
+ unitId: () => getActiveUnitId()
4149
+ });
4150
+ const enriquecer = (row, catalogo) => ({ ...row, ...readStationRouting(regrasDe(row), catalogo) });
4151
+ const separar = (data) => {
4152
+ const tabela = { ...data };
4153
+ for (const k of VIRTUAIS) delete tabela[k];
4154
+ if (tabela.sortOrder == null) tabela.sortOrder = 0;
4155
+ return {
4156
+ tabela,
4157
+ fallback: data.fallback === true,
4158
+ modo: data.catalogMode ?? "selected",
4159
+ selecao: data.catalogo ?? { categoryIds: [], productIds: [] },
4160
+ role: data.role ?? "produce",
4161
+ label: String(data.label ?? "")
4162
+ };
4163
+ };
4164
+ const conferir = (p, catalogo) => {
4165
+ const marcados = catalogo ? selectedProductCount(catalogo, p.selecao, { role: p.role, catalogMode: p.modo }) : p.selecao.categoryIds.length + p.selecao.productIds.length;
4166
+ const nao = refuseStation({
4167
+ name: p.label,
4168
+ role: p.role,
4169
+ catalogMode: p.modo,
4170
+ selectedProductCount: marcados,
4171
+ fallback: p.fallback
4172
+ });
4173
+ if (nao) throw new Error(`${nao.title}${nao.description ? `. ${nao.description}` : ""}`);
4174
+ };
4175
+ const gravarRegras = async (stationId, p, catalogo, unitId) => {
4176
+ if (p.modo === "all" && !catalogo) {
4177
+ throw new Error("N\xE3o foi poss\xEDvel ler o card\xE1pio para aplicar \xABTodos os itens\xBB. Tente de novo.");
4178
+ }
4179
+ const conjunto = routingToWrite(p.modo, p.selecao, catalogo ?? []);
4180
+ await routing().syncRouting(stationId, {
4181
+ ...conjunto,
4182
+ fallback: p.fallback,
4183
+ unitId: unitId ?? null
4184
+ });
4185
+ return conjunto;
4186
+ };
4187
+ const recemGravada = (linha, p, conjunto) => ({
4188
+ ...linha,
4189
+ fallback: p.fallback,
4190
+ catalogMode: p.modo,
4191
+ catalogo: conjunto,
4192
+ catalogSummary: catalogSummary(conjunto, p.fallback, p.modo)
4193
+ });
4194
+ const chaveLivre = async (label) => {
4195
+ const base = keyOf(label) || "kds";
4196
+ let usadas = /* @__PURE__ */ new Set();
4197
+ try {
4198
+ const { data } = await inner().list({ page: 1, pageSize: 200 });
4199
+ usadas = new Set(data.map((r) => r.key).filter(Boolean));
4200
+ } catch {
4201
+ return base;
4202
+ }
4203
+ if (!usadas.has(base)) return base;
4204
+ for (let n = 2; n < 100; n++) {
4205
+ const tentativa = `${base.slice(0, 36)}-${n}`;
4206
+ if (!usadas.has(tentativa)) return tentativa;
4207
+ }
4208
+ return `${base.slice(0, 30)}-${Date.now().toString(36).slice(-6)}`;
4209
+ };
4210
+ return {
4211
+ async list(query) {
4212
+ const [resultado, catalogo] = await Promise.all([inner().list(query), catalogoOuNada()]);
4213
+ return {
4214
+ ...resultado,
4215
+ data: resultado.data.map((r) => enriquecer(r, catalogo))
4216
+ };
4217
+ },
4218
+ async create(data) {
4219
+ const p = separar(data);
4220
+ const catalogo = await catalogoOuNada();
4221
+ conferir(p, catalogo);
4222
+ p.tabela.key = await chaveLivre(p.label);
4223
+ const criada = await inner().create(p.tabela);
4224
+ const conjunto = await gravarRegras(criada.id, p, catalogo, criada.unitId);
4225
+ return recemGravada(criada, p, conjunto);
4226
+ },
4227
+ async update(id, data) {
4228
+ const p = separar(data);
4229
+ const catalogo = await catalogoOuNada();
4230
+ conferir(p, catalogo);
4231
+ delete p.tabela.key;
4232
+ const linha = await inner().update(id, p.tabela);
4233
+ const conjunto = await gravarRegras(id, p, catalogo, linha.unitId);
4234
+ return recemGravada(linha, p, conjunto);
4235
+ },
4236
+ // O banco apaga as regras junto (`ON DELETE CASCADE`), então remover é
4237
+ // remover — não há rastro a limpar aqui.
4238
+ remove: (id) => inner().remove(id),
4239
+ removeMany: (ids) => inner().removeMany ? inner().removeMany(ids) : Promise.all(ids.map((i) => inner().remove(i))).then(() => void 0)
4240
+ };
4241
+ }
2257
4242
 
2258
4243
  // src/index.ts
2259
- var TablesPage = React.lazy(() => import('./TablesPage-VVDNK3GN.js').then((m) => ({ default: m.TablesPage })));
2260
- var ComandaSettingsView = React.lazy(() => import('./ComandaSettingsView-66M6MS6M.js').then((m) => ({ default: m.ComandaSettingsView })));
2261
- var ServiceChargePolicyView = React.lazy(() => import('./ServiceChargePolicyView-CMG2OHRQ.js').then((m) => ({ default: m.ServiceChargePolicyView })));
2262
- var CoverChargePolicyView = React.lazy(() => import('./CoverChargePolicyView-6UWTMPM7.js').then((m) => ({ default: m.CoverChargePolicyView })));
4244
+ var TablesPage = React3.lazy(() => import('./TablesPage-VCUJE5UR.js').then((m) => ({ default: m.TablesPage })));
4245
+ var ComandaSettingsView = React3.lazy(() => import('./ComandaSettingsView-66M6MS6M.js').then((m) => ({ default: m.ComandaSettingsView })));
4246
+ var ServiceChargePolicyView = React3.lazy(() => import('./ServiceChargePolicyView-CMG2OHRQ.js').then((m) => ({ default: m.ServiceChargePolicyView })));
4247
+ var CoverChargePolicyView = React3.lazy(() => import('./CoverChargePolicyView-YFM74L54.js').then((m) => ({ default: m.CoverChargePolicyView })));
2263
4248
  var DEFAULT_LABELS = {
2264
4249
  pageTitle: "Tables",
2265
4250
  floorPlan: "Floor Plan",
@@ -2288,13 +4273,13 @@ function createTablesPlugin(options) {
2288
4273
  const config = resolveConfig(options);
2289
4274
  const provider = options?.dataProvider ?? createMockTablesProvider();
2290
4275
  const store = createTablesStore(provider);
2291
- const PageComponent = () => React.createElement(
2292
- React.Suspense,
4276
+ const PageComponent = () => React3.createElement(
4277
+ React3.Suspense,
2293
4278
  { fallback: null },
2294
- React.createElement(TablesPage, { config, provider, store, registries: tablesRegistries })
4279
+ React3.createElement(TablesPage, { config, provider, store, registries: tablesRegistries })
2295
4280
  );
2296
4281
  registerComponent(FLOOR_PLAN_COMPONENT_ID, PageComponent);
2297
- const ContextBoundary = ({ children }) => React.createElement(TablesContextProvider, { config, provider, store }, children);
4282
+ const ContextBoundary = ({ children }) => React3.createElement(TablesContextProvider, { config, provider, store }, children);
2298
4283
  ContextBoundary.displayName = "TablesContextBoundary";
2299
4284
  return {
2300
4285
  id: "tables",
@@ -2306,23 +4291,24 @@ function createTablesPlugin(options) {
2306
4291
  verticalId: options?.verticalId,
2307
4292
  defaultEnabled: true,
2308
4293
  dependencies: [],
2309
- navigation: [
2310
- {
2311
- section: options?.navSection ?? "main",
2312
- position: options?.navPosition ?? 4,
2313
- label: config.labels.pageTitle,
2314
- route: "/tables",
2315
- icon: "MapPin",
2316
- permission: { feature: "tables", action: "read" }
2317
- }
2318
- ],
2319
- routes: [
2320
- {
2321
- path: "/tables",
2322
- component: PageComponent,
2323
- permission: { feature: "tables", action: "read" }
2324
- }
2325
- ],
4294
+ /**
4295
+ * SEM página de retaguarda.
4296
+ *
4297
+ * `/tables` era a tela de Salão do começo do porte — ambientes, mesas e
4298
+ * uma planta em grade de células. O PDV passou a fazer tudo o que ela
4299
+ * fazia e melhor: a planta em METROS, as praças desenhadas, a ficha da
4300
+ * mesa, «Organizar automaticamente». A tela antiga ficou para trás e
4301
+ * mostrava um salão que já não é o da casa.
4302
+ *
4303
+ * Duas telas para o mesmo salão é pior que uma: o operador arruma numa e
4304
+ * não vê na outra, e a desatualizada é sempre a que alguém abre primeiro.
4305
+ * Decisão do founder em 28-09.
4306
+ *
4307
+ * O que a casa ainda precisa CADASTRAR — mesa nova, numeração, lote — não
4308
+ * tem lugar hoje. Fica anotado no checklist, não escondido aqui.
4309
+ */
4310
+ navigation: [],
4311
+ routes: [],
2326
4312
  widgets: [],
2327
4313
  aiTools: [
2328
4314
  {
@@ -2369,7 +4355,7 @@ function createTablesPlugin(options) {
2369
4355
  label: config.labels.pageTitle,
2370
4356
  icon: "MapPin",
2371
4357
  component: (() => {
2372
- const TablesSettingsTab = () => React.createElement(PluginSettingsPanel, {
4358
+ const TablesSettingsTab = () => React3.createElement(PluginSettingsPanel, {
2373
4359
  title: "Tables Settings",
2374
4360
  registries: tablesRegistries,
2375
4361
  routeBase: "/settings/tables"
@@ -2395,17 +4381,17 @@ function createTablesPlugin(options) {
2395
4381
  label: "Taxas",
2396
4382
  icon: "Percent",
2397
4383
  component: (() => {
2398
- const FeesSettingsTab = () => React.createElement(
4384
+ const FeesSettingsTab = () => React3.createElement(
2399
4385
  ContextBoundary,
2400
4386
  null,
2401
- React.createElement(
2402
- React.Suspense,
4387
+ React3.createElement(
4388
+ React3.Suspense,
2403
4389
  { fallback: null },
2404
- React.createElement(
4390
+ React3.createElement(
2405
4391
  "div",
2406
4392
  { className: "space-y-6" },
2407
- React.createElement(ServiceChargePolicyView, { key: "service" }),
2408
- React.createElement(CoverChargePolicyView, { key: "cover" })
4393
+ React3.createElement(ServiceChargePolicyView, { key: "service" }),
4394
+ React3.createElement(CoverChargePolicyView, { key: "cover" })
2409
4395
  )
2410
4396
  )
2411
4397
  );
@@ -2421,13 +4407,13 @@ function createTablesPlugin(options) {
2421
4407
  label: "Comanda",
2422
4408
  icon: "Receipt",
2423
4409
  component: (() => {
2424
- const ComandaSettingsTab = () => React.createElement(
4410
+ const ComandaSettingsTab = () => React3.createElement(
2425
4411
  ContextBoundary,
2426
4412
  null,
2427
- React.createElement(
2428
- React.Suspense,
4413
+ React3.createElement(
4414
+ React3.Suspense,
2429
4415
  { fallback: null },
2430
- React.createElement(ComandaSettingsView)
4416
+ React3.createElement(ComandaSettingsView)
2431
4417
  )
2432
4418
  );
2433
4419
  ComandaSettingsTab.displayName = "ComandaSettingsTab";
@@ -2443,6 +4429,6 @@ function createTablesPlugin(options) {
2443
4429
  };
2444
4430
  }
2445
4431
 
2446
- export { FLOOR_PLAN_COMPONENT_ID, createCoreTablesProvider, createFayzTablesProvider, createTablesPlugin };
4432
+ export { FLOOR_PLAN_COMPONENT_ID, buildKdsStationEntity, buildKdsStationProvider, createCoreTablesProvider, createFayzTablesProvider, createTablesPlugin };
2447
4433
  //# sourceMappingURL=index.js.map
2448
4434
  //# sourceMappingURL=index.js.map