@fayz-ai/plugin-tables 0.11.1 → 0.12.0
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/{CoverChargePolicyView-6UWTMPM7.js → CoverChargePolicyView-YFM74L54.js} +4 -10
- package/dist/{CoverChargePolicyView-6UWTMPM7.js.map → CoverChargePolicyView-YFM74L54.js.map} +1 -1
- package/dist/{TablesPage-VVDNK3GN.js → TablesPage-VCUJE5UR.js} +10 -4
- package/dist/TablesPage-VCUJE5UR.js.map +1 -0
- package/dist/data/core-supabase.d.ts.map +1 -1
- package/dist/data/types.d.ts +344 -6
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1841 -128
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +27 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +475 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/views/ComandaActions.d.ts.map +1 -1
- package/dist/views/CoverChargePolicyView.d.ts.map +1 -1
- package/dist/views/KdsCatalogField.d.ts +11 -0
- package/dist/views/KdsCatalogField.d.ts.map +1 -0
- package/dist/views/kdsStationEntity.d.ts +24 -0
- package/dist/views/kdsStationEntity.d.ts.map +1 -0
- package/dist/views/kdsStationProvider.d.ts +5 -0
- package/dist/views/kdsStationProvider.d.ts.map +1 -0
- package/package.json +5 -4
- package/dist/TablesPage-VVDNK3GN.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { TablesContextProvider } from './chunk-XHRPH676.js';
|
|
2
|
-
import
|
|
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, getActiveUnitId, getActiveTenantId } from '@fayz-ai/core';
|
|
7
7
|
import { createFayzClient } from '@fayz-ai/sdk';
|
|
8
|
+
import { settle } from '@fayz-ai/core/orders';
|
|
9
|
+
import { NAME_MAX, TARGET_MAX, TARGET_MIN, ORDER_MAX, ORDER_MIN, readStationRouting, selectedProductCount, refuseStation, routingToWrite, catalogSummary, keyOf, uncategorizedCount, filterCatalog, categoryKey, categoryState, toggleCategory, categoryCount, toggleProduct, createKdsProvider } from '@fayz-ai/kds';
|
|
10
|
+
import { Search, ChevronDown, ChevronRight, Utensils } from 'lucide-react';
|
|
11
|
+
import { Skeleton, Input, Checkbox, Badge } from '@fayz-ai/ui';
|
|
12
|
+
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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 {
|
|
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) {
|
|
1941
2964
|
requireWrites();
|
|
1942
|
-
|
|
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");
|
|
1943
2986
|
if (error) throw new Error(error.message);
|
|
2987
|
+
assertTocou(ajustada, "a taxa desta comanda");
|
|
1944
2988
|
await recalc(orderId);
|
|
1945
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) {
|
|
3003
|
+
requireWrites();
|
|
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);
|
|
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
|
+
}
|
|
3014
|
+
await recalc(orderId);
|
|
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
|
|
1955
|
-
const
|
|
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
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
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,509 @@ function createCoreTablesProvider(options) {
|
|
|
2254
3469
|
}
|
|
2255
3470
|
};
|
|
2256
3471
|
}
|
|
3472
|
+
function asSelection(value) {
|
|
3473
|
+
const v = value;
|
|
3474
|
+
return {
|
|
3475
|
+
categoryIds: Array.isArray(v?.categoryIds) ? v.categoryIds : [],
|
|
3476
|
+
productIds: Array.isArray(v?.productIds) ? v.productIds : []
|
|
3477
|
+
};
|
|
3478
|
+
}
|
|
3479
|
+
var CARDAPIO_TTL_MS = 6e4;
|
|
3480
|
+
var cardapioEmVoo = null;
|
|
3481
|
+
var cardapioDe = null;
|
|
3482
|
+
var cardapioEm = 0;
|
|
3483
|
+
function loadCatalog() {
|
|
3484
|
+
const chave = `${getActiveTenantId() ?? ""}:${getActiveUnitId() ?? ""}`;
|
|
3485
|
+
const vencido = Date.now() - cardapioEm > CARDAPIO_TTL_MS;
|
|
3486
|
+
if (!cardapioEmVoo || cardapioDe !== chave || vencido) {
|
|
3487
|
+
cardapioDe = chave;
|
|
3488
|
+
cardapioEm = Date.now();
|
|
3489
|
+
cardapioEmVoo = createKdsProvider({
|
|
3490
|
+
tenantId: () => getActiveTenantId(),
|
|
3491
|
+
unitId: () => getActiveUnitId()
|
|
3492
|
+
}).listCatalog().catch((e) => {
|
|
3493
|
+
cardapioEmVoo = null;
|
|
3494
|
+
throw e;
|
|
3495
|
+
});
|
|
3496
|
+
}
|
|
3497
|
+
return cardapioEmVoo;
|
|
3498
|
+
}
|
|
3499
|
+
function KdsCatalogField({
|
|
3500
|
+
value,
|
|
3501
|
+
onChange,
|
|
3502
|
+
values
|
|
3503
|
+
}) {
|
|
3504
|
+
const selecao = asSelection(value);
|
|
3505
|
+
const modo = values.catalogMode ?? "selected";
|
|
3506
|
+
const role = values.role ?? "produce";
|
|
3507
|
+
const fallback = values.fallback === true;
|
|
3508
|
+
const [catalogo, setCatalogo] = React3.useState(null);
|
|
3509
|
+
const [erro, setErro] = React3.useState(null);
|
|
3510
|
+
const [busca, setBusca] = React3.useState("");
|
|
3511
|
+
const [abertas, setAbertas] = React3.useState(() => /* @__PURE__ */ new Set());
|
|
3512
|
+
React3.useEffect(() => {
|
|
3513
|
+
let vivo = true;
|
|
3514
|
+
loadCatalog().then((c) => {
|
|
3515
|
+
if (vivo) setCatalogo(c);
|
|
3516
|
+
}).catch((e) => {
|
|
3517
|
+
if (vivo) {
|
|
3518
|
+
setCatalogo([]);
|
|
3519
|
+
setErro(e instanceof Error ? e.message : "Falha ao ler o card\xE1pio.");
|
|
3520
|
+
}
|
|
3521
|
+
});
|
|
3522
|
+
return () => {
|
|
3523
|
+
vivo = false;
|
|
3524
|
+
};
|
|
3525
|
+
}, []);
|
|
3526
|
+
if (role === "expo") {
|
|
3527
|
+
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." });
|
|
3528
|
+
}
|
|
3529
|
+
if (catalogo === null) {
|
|
3530
|
+
return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
|
|
3531
|
+
/* @__PURE__ */ jsx(Skeleton, { className: "h-9 w-full rounded-input" }),
|
|
3532
|
+
[0, 1, 2].map((i) => /* @__PURE__ */ jsx(Skeleton, { className: "h-11 w-full rounded-lg" }, i))
|
|
3533
|
+
] });
|
|
3534
|
+
}
|
|
3535
|
+
const marcados = selectedProductCount(catalogo, selecao, { catalogMode: modo, role });
|
|
3536
|
+
const semCategoria = uncategorizedCount(catalogo);
|
|
3537
|
+
const filtrado = filterCatalog(catalogo, busca);
|
|
3538
|
+
const aplicar = (s) => onChange(s);
|
|
3539
|
+
const recusa = modo === "selected" && marcados === 0 && !fallback;
|
|
3540
|
+
return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
|
|
3541
|
+
erro && /* @__PURE__ */ jsxs("p", { className: "text-xs text-destructive", role: "alert", children: [
|
|
3542
|
+
"N\xE3o foi poss\xEDvel ler o card\xE1pio: ",
|
|
3543
|
+
erro
|
|
3544
|
+
] }),
|
|
3545
|
+
modo === "selected" && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
3546
|
+
/* @__PURE__ */ jsxs("div", { className: "relative", children: [
|
|
3547
|
+
/* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
|
|
3548
|
+
/* @__PURE__ */ jsx(
|
|
3549
|
+
Input,
|
|
3550
|
+
{
|
|
3551
|
+
className: "pl-9",
|
|
3552
|
+
value: busca,
|
|
3553
|
+
placeholder: "Buscar categoria ou produto\u2026",
|
|
3554
|
+
onChange: (e) => setBusca(e.target.value),
|
|
3555
|
+
"aria-label": "Buscar categoria ou produto"
|
|
3556
|
+
}
|
|
3557
|
+
)
|
|
3558
|
+
] }),
|
|
3559
|
+
/* @__PURE__ */ jsxs("div", { className: "fz-container max-h-80 overflow-y-auto rounded-lg border", children: [
|
|
3560
|
+
filtrado.map(({ category, visibleProducts }) => {
|
|
3561
|
+
const chave = categoryKey(category);
|
|
3562
|
+
const estado = categoryState(category, selecao);
|
|
3563
|
+
const aberta = abertas.has(chave) || busca.trim() !== "";
|
|
3564
|
+
return /* @__PURE__ */ jsxs("div", { className: "border-b last:border-0", children: [
|
|
3565
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 bg-muted/30 px-3 py-2.5", children: [
|
|
3566
|
+
/* @__PURE__ */ jsx(
|
|
3567
|
+
"button",
|
|
3568
|
+
{
|
|
3569
|
+
type: "button",
|
|
3570
|
+
className: "rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",
|
|
3571
|
+
"aria-label": aberta ? `Recolher ${category.name}` : `Expandir ${category.name}`,
|
|
3572
|
+
"aria-expanded": aberta,
|
|
3573
|
+
onClick: () => setAbertas((atual) => {
|
|
3574
|
+
const proxima = new Set(atual);
|
|
3575
|
+
proxima.has(chave) ? proxima.delete(chave) : proxima.add(chave);
|
|
3576
|
+
return proxima;
|
|
3577
|
+
}),
|
|
3578
|
+
children: aberta ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
|
|
3579
|
+
}
|
|
3580
|
+
),
|
|
3581
|
+
/* @__PURE__ */ jsx(
|
|
3582
|
+
Checkbox,
|
|
3583
|
+
{
|
|
3584
|
+
checked: estado === true,
|
|
3585
|
+
indeterminate: estado === "indeterminate",
|
|
3586
|
+
"aria-label": `Selecionar categoria ${category.name}`,
|
|
3587
|
+
onChange: (marcar) => aplicar(toggleCategory(selecao, category, marcar))
|
|
3588
|
+
}
|
|
3589
|
+
),
|
|
3590
|
+
/* @__PURE__ */ jsxs(
|
|
3591
|
+
"button",
|
|
3592
|
+
{
|
|
3593
|
+
type: "button",
|
|
3594
|
+
className: "flex min-w-0 flex-1 items-center justify-between gap-3 text-left",
|
|
3595
|
+
onClick: () => setAbertas((atual) => {
|
|
3596
|
+
const proxima = new Set(atual);
|
|
3597
|
+
proxima.has(chave) ? proxima.delete(chave) : proxima.add(chave);
|
|
3598
|
+
return proxima;
|
|
3599
|
+
}),
|
|
3600
|
+
children: [
|
|
3601
|
+
/* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium", children: category.name }),
|
|
3602
|
+
/* @__PURE__ */ jsxs(Badge, { variant: "secondary", className: "shrink-0 tabular-nums", children: [
|
|
3603
|
+
categoryCount(category, selecao),
|
|
3604
|
+
"/",
|
|
3605
|
+
category.products.length,
|
|
3606
|
+
" itens"
|
|
3607
|
+
] })
|
|
3608
|
+
]
|
|
3609
|
+
}
|
|
3610
|
+
)
|
|
3611
|
+
] }),
|
|
3612
|
+
aberta && /* @__PURE__ */ jsxs("div", { className: "grid gap-0.5 px-3 py-2 fz-fields-2", children: [
|
|
3613
|
+
visibleProducts.map((p) => /* @__PURE__ */ jsxs(
|
|
3614
|
+
"label",
|
|
3615
|
+
{
|
|
3616
|
+
className: "flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/50",
|
|
3617
|
+
children: [
|
|
3618
|
+
/* @__PURE__ */ jsx(
|
|
3619
|
+
Checkbox,
|
|
3620
|
+
{
|
|
3621
|
+
checked: estado === true || selecao.productIds.includes(p.id),
|
|
3622
|
+
"aria-label": `Selecionar produto ${p.name}`,
|
|
3623
|
+
onChange: (marcar) => aplicar(toggleProduct(selecao, category, p.id, marcar))
|
|
3624
|
+
}
|
|
3625
|
+
),
|
|
3626
|
+
/* @__PURE__ */ jsx("span", { className: "truncate", children: p.name })
|
|
3627
|
+
]
|
|
3628
|
+
},
|
|
3629
|
+
p.id
|
|
3630
|
+
)),
|
|
3631
|
+
visibleProducts.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-2 py-1.5 text-sm text-muted-foreground", children: "Nenhum item nesta categoria." })
|
|
3632
|
+
] })
|
|
3633
|
+
] }, chave);
|
|
3634
|
+
}),
|
|
3635
|
+
filtrado.length === 0 && /* @__PURE__ */ jsx("p", { className: "p-8 text-center text-sm text-muted-foreground", children: erro ?? "Nenhum item encontrado." })
|
|
3636
|
+
] })
|
|
3637
|
+
] }),
|
|
3638
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-lg bg-muted/60 px-3 py-2 text-sm", children: [
|
|
3639
|
+
/* @__PURE__ */ jsx(Utensils, { className: "h-4 w-4 shrink-0 text-primary" }),
|
|
3640
|
+
/* @__PURE__ */ jsxs("span", { children: [
|
|
3641
|
+
/* @__PURE__ */ jsx("strong", { className: "tabular-nums", children: marcados }),
|
|
3642
|
+
" ",
|
|
3643
|
+
marcados === 1 ? "item chegar\xE1" : "itens chegar\xE3o",
|
|
3644
|
+
" neste KDS."
|
|
3645
|
+
] })
|
|
3646
|
+
] }),
|
|
3647
|
+
modo === "all" && semCategoria > 0 && !fallback && /* @__PURE__ */ jsxs("p", { className: "text-xs text-warning", children: [
|
|
3648
|
+
semCategoria,
|
|
3649
|
+
" ",
|
|
3650
|
+
semCategoria === 1 ? "item est\xE1" : "itens est\xE3o",
|
|
3651
|
+
" sem categoria e n\xE3o",
|
|
3652
|
+
" ",
|
|
3653
|
+
"chegam por aqui. Ligue \xABDestino padr\xE3o\xBB para que esta tela tamb\xE9m os receba."
|
|
3654
|
+
] }),
|
|
3655
|
+
recusa && /* @__PURE__ */ jsxs("p", { className: "text-xs text-destructive", role: "alert", children: [
|
|
3656
|
+
/* @__PURE__ */ jsx("strong", { children: "Selecione ao menos um item." }),
|
|
3657
|
+
" ",
|
|
3658
|
+
"Marque uma categoria, um produto ou use \u201CTodos os itens\u201D."
|
|
3659
|
+
] })
|
|
3660
|
+
] });
|
|
3661
|
+
}
|
|
3662
|
+
|
|
3663
|
+
// src/views/kdsStationEntity.ts
|
|
3664
|
+
function buildKdsStationEntity(options) {
|
|
3665
|
+
return {
|
|
3666
|
+
name: "Tela KDS",
|
|
3667
|
+
namePlural: "Telas KDS",
|
|
3668
|
+
icon: "Monitor",
|
|
3669
|
+
displayField: "label",
|
|
3670
|
+
defaultSort: "sortOrder",
|
|
3671
|
+
formColumns: 2,
|
|
3672
|
+
fieldGroups: [
|
|
3673
|
+
{ id: "identidade", label: "A tela", columns: 1 },
|
|
3674
|
+
{ id: "ritmo", label: "Ritmo e ordem", columns: 2, column: "side" },
|
|
3675
|
+
{
|
|
3676
|
+
id: "catalogo",
|
|
3677
|
+
label: "Itens do cat\xE1logo",
|
|
3678
|
+
description: "Escolha exatamente quais produtos devem chegar nesta tela.",
|
|
3679
|
+
columns: 1
|
|
3680
|
+
}
|
|
3681
|
+
],
|
|
3682
|
+
fields: [
|
|
3683
|
+
{
|
|
3684
|
+
key: "label",
|
|
3685
|
+
label: "Nome do KDS",
|
|
3686
|
+
type: "text",
|
|
3687
|
+
required: true,
|
|
3688
|
+
searchable: true,
|
|
3689
|
+
showInTable: true,
|
|
3690
|
+
group: "identidade",
|
|
3691
|
+
// `max` num campo de texto é o teto de caracteres: o `maxLength={80}`
|
|
3692
|
+
// do V1, que a tela do V2 não tinha.
|
|
3693
|
+
placeholder: "Ex.: Bar, Chapa, Cozinha",
|
|
3694
|
+
max: NAME_MAX
|
|
3695
|
+
},
|
|
3696
|
+
{
|
|
3697
|
+
key: "role",
|
|
3698
|
+
label: "Fun\xE7\xE3o da tela",
|
|
3699
|
+
type: "segmented",
|
|
3700
|
+
showInTable: true,
|
|
3701
|
+
group: "identidade",
|
|
3702
|
+
defaultValue: "produce",
|
|
3703
|
+
options: [
|
|
3704
|
+
{ label: "Produ\xE7\xE3o", value: "produce", description: "Prepara o que chega nela." },
|
|
3705
|
+
{ label: "Expedi\xE7\xE3o", value: "expo", description: "Confere o que as outras produziram \u2014 e v\xEA a comanda inteira." }
|
|
3706
|
+
]
|
|
3707
|
+
},
|
|
3708
|
+
{
|
|
3709
|
+
// «Sem limite» é AUSÊNCIA, não zero: uma estação sem tempo-meta não é
|
|
3710
|
+
// uma estação que promete zero minuto.
|
|
3711
|
+
key: "slaMinutes",
|
|
3712
|
+
label: "Tempo-meta (min)",
|
|
3713
|
+
type: "number",
|
|
3714
|
+
showInTable: true,
|
|
3715
|
+
group: "ritmo",
|
|
3716
|
+
min: TARGET_MIN,
|
|
3717
|
+
max: TARGET_MAX,
|
|
3718
|
+
placeholder: "Sem limite"
|
|
3719
|
+
},
|
|
3720
|
+
{
|
|
3721
|
+
// No cartão também: o V1 mostra «Ordem da tela» ao lado do
|
|
3722
|
+
// tempo-meta, e é ela que explica por que a Chapa aparece antes da
|
|
3723
|
+
// Expedição na central.
|
|
3724
|
+
key: "sortOrder",
|
|
3725
|
+
label: "Ordem na central",
|
|
3726
|
+
type: "number",
|
|
3727
|
+
showInTable: true,
|
|
3728
|
+
group: "ritmo",
|
|
3729
|
+
min: ORDER_MIN,
|
|
3730
|
+
max: ORDER_MAX,
|
|
3731
|
+
placeholder: "Autom\xE1tica"
|
|
3732
|
+
},
|
|
3733
|
+
{
|
|
3734
|
+
key: "isActive",
|
|
3735
|
+
label: "Ativa",
|
|
3736
|
+
type: "boolean",
|
|
3737
|
+
defaultValue: true,
|
|
3738
|
+
showInTable: true,
|
|
3739
|
+
inlineToggle: true,
|
|
3740
|
+
group: "ritmo"
|
|
3741
|
+
},
|
|
3742
|
+
// ── «Itens do catálogo» ────────────────────────────────────────────
|
|
3743
|
+
//
|
|
3744
|
+
// Os três campos abaixo NÃO são colunas de `plg_kds_stations`: cada um
|
|
3745
|
+
// vira linha de `plg_kds_routing`. Quem faz a tradução é o
|
|
3746
|
+
// `buildKdsStationProvider` — declarar aqui é o que dá a eles o rótulo,
|
|
3747
|
+
// o grupo e a ordem do resto do cadastro.
|
|
3748
|
+
{
|
|
3749
|
+
// A REDE DE SEGURANÇA. Sem ela, um produto novo no cardápio não chega
|
|
3750
|
+
// a cozinha nenhuma — e ninguém percebe até o cliente perguntar.
|
|
3751
|
+
key: "fallback",
|
|
3752
|
+
label: "Destino padr\xE3o",
|
|
3753
|
+
type: "boolean",
|
|
3754
|
+
defaultValue: false,
|
|
3755
|
+
group: "catalogo",
|
|
3756
|
+
showInTable: false,
|
|
3757
|
+
hint: "Recebe itens que n\xE3o foram associados a nenhuma tela de produ\xE7\xE3o."
|
|
3758
|
+
},
|
|
3759
|
+
{
|
|
3760
|
+
// As DUAS CARTAS do V1. `segmented` com descrição já as desenha —
|
|
3761
|
+
// borda destacada, título e a frase embaixo —, então não há tela
|
|
3762
|
+
// nova aqui, só a declaração.
|
|
3763
|
+
//
|
|
3764
|
+
// «Todos os itens» é o padrão do V1 para uma tela que já existe; um
|
|
3765
|
+
// cadastro NOVO nasce em «específicos», como lá.
|
|
3766
|
+
key: "catalogMode",
|
|
3767
|
+
label: "Como escolher",
|
|
3768
|
+
type: "segmented",
|
|
3769
|
+
defaultValue: "selected",
|
|
3770
|
+
group: "catalogo",
|
|
3771
|
+
showInTable: false,
|
|
3772
|
+
visibleWhen: (v) => v.role !== "expo",
|
|
3773
|
+
options: [
|
|
3774
|
+
{ label: "Todos os itens", value: "all", description: "Tudo que for vendido chega neste KDS." },
|
|
3775
|
+
{ label: "Categorias e produtos espec\xEDficos", value: "selected", description: "Monte o cat\xE1logo desta esta\xE7\xE3o." }
|
|
3776
|
+
]
|
|
3777
|
+
},
|
|
3778
|
+
{
|
|
3779
|
+
// A árvore. É o único pedaço que o CRUD genérico não sabe desenhar —
|
|
3780
|
+
// e por isso o único que entra pela saída declarada.
|
|
3781
|
+
key: "catalogo",
|
|
3782
|
+
label: "Categorias e produtos",
|
|
3783
|
+
type: "custom",
|
|
3784
|
+
group: "catalogo",
|
|
3785
|
+
span: 2,
|
|
3786
|
+
showInTable: false,
|
|
3787
|
+
showInDetail: false,
|
|
3788
|
+
defaultValue: { categoryIds: [], productIds: [] },
|
|
3789
|
+
renderInput: ({ value, onChange, values }) => React3.createElement(KdsCatalogField, { value, onChange, values })
|
|
3790
|
+
}
|
|
3791
|
+
],
|
|
3792
|
+
/**
|
|
3793
|
+
* O CARTÃO, como no V1: ícone fixo, o que a tela é sob o nome, o estado no
|
|
3794
|
+
* canto, os dois números em caixas, a frase do catálogo e «Abrir tela».
|
|
3795
|
+
*
|
|
3796
|
+
* A miniatura genérica não serve aqui — uma estação de cozinha não tem
|
|
3797
|
+
* foto, e o ícone diz a espécie melhor que um quadrado vazio.
|
|
3798
|
+
*/
|
|
3799
|
+
card: {
|
|
3800
|
+
icon: "Monitor",
|
|
3801
|
+
subtitle: (s) => s.role === "expo" ? "Expedi\xE7\xE3o e confer\xEAncia" : "Esta\xE7\xE3o de produ\xE7\xE3o",
|
|
3802
|
+
badge: (s) => ({ label: s.isActive ? "Ativo" : "Inativo" }),
|
|
3803
|
+
// Os dois do V1, e «Sem limite»/«Automática» por extenso: vazio é uma
|
|
3804
|
+
// ESCOLHA da casa, não um campo que ninguém preencheu.
|
|
3805
|
+
tiles: (s) => [
|
|
3806
|
+
{ label: "Tempo-meta", value: s.slaMinutes ? `${s.slaMinutes} min` : "Sem limite" },
|
|
3807
|
+
{ label: "Ordem da tela", value: s.sortOrder ? String(s.sortOrder) : "Autom\xE1tica" }
|
|
3808
|
+
],
|
|
3809
|
+
// A frase do V1, e ela é a resposta a «por que esta tela está vazia?».
|
|
3810
|
+
// Sem regra a estação existe e não recebe nada — o pior estado possível,
|
|
3811
|
+
// porque parece configurada.
|
|
3812
|
+
//
|
|
3813
|
+
// Quem leu as regras já a montou (`catalogSummary`). Antes, este trecho
|
|
3814
|
+
// procurava `plg_kds_routing` na linha e o provedor genérico entrega
|
|
3815
|
+
// `plgKdsRouting`: TODA estação, configurada ou não, dizia «Nenhum item
|
|
3816
|
+
// associado.».
|
|
3817
|
+
note: (s) => s.catalogSummary ?? "Nenhum item associado.",
|
|
3818
|
+
// «ABRIR TELA» — o botão do V1, com o destino que o aplicativo diz.
|
|
3819
|
+
//
|
|
3820
|
+
// A cozinha olha OUTRO app (`chef-kds`), e o endereço dele muda entre a
|
|
3821
|
+
// máquina de quem desenvolve e a casa do cliente. Por isso o plugin
|
|
3822
|
+
// declara o botão e o app diz para onde: cravar uma porta aqui acertaria
|
|
3823
|
+
// num lugar e erraria em todos os outros.
|
|
3824
|
+
//
|
|
3825
|
+
// Vai a CHAVE, não o uuid: é ela que o tablet guarda na barra de
|
|
3826
|
+
// endereços, e é ela que sobrevive a renomear «Chapa» para «Grelha». E
|
|
3827
|
+
// abre em outra aba porque quem configura no escritório não quer perder
|
|
3828
|
+
// a lista de vista.
|
|
3829
|
+
actions: options?.kdsUrl ? [{
|
|
3830
|
+
id: "open",
|
|
3831
|
+
label: "Abrir tela",
|
|
3832
|
+
icon: "MonitorPlay",
|
|
3833
|
+
onAction: (row) => window.open(
|
|
3834
|
+
`${options.kdsUrl}?station=${encodeURIComponent(row.key ?? row.id)}`,
|
|
3835
|
+
"_blank",
|
|
3836
|
+
"noopener"
|
|
3837
|
+
)
|
|
3838
|
+
}] : []
|
|
3839
|
+
},
|
|
3840
|
+
data: {
|
|
3841
|
+
table: "plg_kds_stations",
|
|
3842
|
+
tenantScoped: true,
|
|
3843
|
+
// Uma tela de KDS é um APARELHO, e aparelho fica numa unidade. A tabela
|
|
3844
|
+
// tem `unit_id` e não está em `scoped_resources`, então o cadastro
|
|
3845
|
+
// precisa dizer — sem isto a tela nova nasce sem unidade e aparece para
|
|
3846
|
+
// TODAS as filiais, ao lado das quatro do Pertinho que já têm a sua.
|
|
3847
|
+
// Sem unidade ativa nada muda: `resolveUnitScope` devolve null.
|
|
3848
|
+
unitScoped: true,
|
|
3849
|
+
searchColumns: ["label", "key"],
|
|
3850
|
+
// As REGRAS junto da estação, e não só a contagem delas: é com elas que
|
|
3851
|
+
// o formulário reabre com as categorias já marcadas, e o cartão diz o
|
|
3852
|
+
// que a tela recebe. Embutida do PostgREST — uma ida ao banco, não uma
|
|
3853
|
+
// por cartão.
|
|
3854
|
+
selectColumns: "*, plg_kds_routing(match_kind, category_id, product_id)"
|
|
3855
|
+
}
|
|
3856
|
+
};
|
|
3857
|
+
}
|
|
3858
|
+
var VIRTUAIS = ["fallback", "catalogMode", "catalogo", "catalogSummary", "plgKdsRouting"];
|
|
3859
|
+
function regrasDe(row) {
|
|
3860
|
+
const cru = row.plgKdsRouting ?? row.plg_kds_routing;
|
|
3861
|
+
return Array.isArray(cru) ? cru : [];
|
|
3862
|
+
}
|
|
3863
|
+
async function catalogoOuNada() {
|
|
3864
|
+
try {
|
|
3865
|
+
return await loadCatalog();
|
|
3866
|
+
} catch {
|
|
3867
|
+
return null;
|
|
3868
|
+
}
|
|
3869
|
+
}
|
|
3870
|
+
function buildKdsStationProvider(entityDef) {
|
|
3871
|
+
let generico = null;
|
|
3872
|
+
const inner = () => generico ?? (generico = resolveDataProvider(entityDef));
|
|
3873
|
+
const routing = () => createKdsProvider({
|
|
3874
|
+
tenantId: () => getActiveTenantId(),
|
|
3875
|
+
unitId: () => getActiveUnitId()
|
|
3876
|
+
});
|
|
3877
|
+
const enriquecer = (row, catalogo) => ({ ...row, ...readStationRouting(regrasDe(row), catalogo) });
|
|
3878
|
+
const separar = (data) => {
|
|
3879
|
+
const tabela = { ...data };
|
|
3880
|
+
for (const k of VIRTUAIS) delete tabela[k];
|
|
3881
|
+
if (tabela.sortOrder == null) tabela.sortOrder = 0;
|
|
3882
|
+
return {
|
|
3883
|
+
tabela,
|
|
3884
|
+
fallback: data.fallback === true,
|
|
3885
|
+
modo: data.catalogMode ?? "selected",
|
|
3886
|
+
selecao: data.catalogo ?? { categoryIds: [], productIds: [] },
|
|
3887
|
+
role: data.role ?? "produce",
|
|
3888
|
+
label: String(data.label ?? "")
|
|
3889
|
+
};
|
|
3890
|
+
};
|
|
3891
|
+
const conferir = (p, catalogo) => {
|
|
3892
|
+
const marcados = catalogo ? selectedProductCount(catalogo, p.selecao, { role: p.role, catalogMode: p.modo }) : p.selecao.categoryIds.length + p.selecao.productIds.length;
|
|
3893
|
+
const nao = refuseStation({
|
|
3894
|
+
name: p.label,
|
|
3895
|
+
role: p.role,
|
|
3896
|
+
catalogMode: p.modo,
|
|
3897
|
+
selectedProductCount: marcados,
|
|
3898
|
+
fallback: p.fallback
|
|
3899
|
+
});
|
|
3900
|
+
if (nao) throw new Error(`${nao.title}${nao.description ? `. ${nao.description}` : ""}`);
|
|
3901
|
+
};
|
|
3902
|
+
const gravarRegras = async (stationId, p, catalogo, unitId) => {
|
|
3903
|
+
if (p.modo === "all" && !catalogo) {
|
|
3904
|
+
throw new Error("N\xE3o foi poss\xEDvel ler o card\xE1pio para aplicar \xABTodos os itens\xBB. Tente de novo.");
|
|
3905
|
+
}
|
|
3906
|
+
const conjunto = routingToWrite(p.modo, p.selecao, catalogo ?? []);
|
|
3907
|
+
await routing().syncRouting(stationId, {
|
|
3908
|
+
...conjunto,
|
|
3909
|
+
fallback: p.fallback,
|
|
3910
|
+
unitId: unitId ?? null
|
|
3911
|
+
});
|
|
3912
|
+
return conjunto;
|
|
3913
|
+
};
|
|
3914
|
+
const recemGravada = (linha, p, conjunto) => ({
|
|
3915
|
+
...linha,
|
|
3916
|
+
fallback: p.fallback,
|
|
3917
|
+
catalogMode: p.modo,
|
|
3918
|
+
catalogo: conjunto,
|
|
3919
|
+
catalogSummary: catalogSummary(conjunto, p.fallback, p.modo)
|
|
3920
|
+
});
|
|
3921
|
+
const chaveLivre = async (label) => {
|
|
3922
|
+
const base = keyOf(label) || "kds";
|
|
3923
|
+
let usadas = /* @__PURE__ */ new Set();
|
|
3924
|
+
try {
|
|
3925
|
+
const { data } = await inner().list({ page: 1, pageSize: 200 });
|
|
3926
|
+
usadas = new Set(data.map((r) => r.key).filter(Boolean));
|
|
3927
|
+
} catch {
|
|
3928
|
+
return base;
|
|
3929
|
+
}
|
|
3930
|
+
if (!usadas.has(base)) return base;
|
|
3931
|
+
for (let n = 2; n < 100; n++) {
|
|
3932
|
+
const tentativa = `${base.slice(0, 36)}-${n}`;
|
|
3933
|
+
if (!usadas.has(tentativa)) return tentativa;
|
|
3934
|
+
}
|
|
3935
|
+
return `${base.slice(0, 30)}-${Date.now().toString(36).slice(-6)}`;
|
|
3936
|
+
};
|
|
3937
|
+
return {
|
|
3938
|
+
async list(query) {
|
|
3939
|
+
const [resultado, catalogo] = await Promise.all([inner().list(query), catalogoOuNada()]);
|
|
3940
|
+
return {
|
|
3941
|
+
...resultado,
|
|
3942
|
+
data: resultado.data.map((r) => enriquecer(r, catalogo))
|
|
3943
|
+
};
|
|
3944
|
+
},
|
|
3945
|
+
async create(data) {
|
|
3946
|
+
const p = separar(data);
|
|
3947
|
+
const catalogo = await catalogoOuNada();
|
|
3948
|
+
conferir(p, catalogo);
|
|
3949
|
+
p.tabela.key = await chaveLivre(p.label);
|
|
3950
|
+
const criada = await inner().create(p.tabela);
|
|
3951
|
+
const conjunto = await gravarRegras(criada.id, p, catalogo, criada.unitId);
|
|
3952
|
+
return recemGravada(criada, p, conjunto);
|
|
3953
|
+
},
|
|
3954
|
+
async update(id, data) {
|
|
3955
|
+
const p = separar(data);
|
|
3956
|
+
const catalogo = await catalogoOuNada();
|
|
3957
|
+
conferir(p, catalogo);
|
|
3958
|
+
delete p.tabela.key;
|
|
3959
|
+
const linha = await inner().update(id, p.tabela);
|
|
3960
|
+
const conjunto = await gravarRegras(id, p, catalogo, linha.unitId);
|
|
3961
|
+
return recemGravada(linha, p, conjunto);
|
|
3962
|
+
},
|
|
3963
|
+
// O banco apaga as regras junto (`ON DELETE CASCADE`), então remover é
|
|
3964
|
+
// remover — não há rastro a limpar aqui.
|
|
3965
|
+
remove: (id) => inner().remove(id),
|
|
3966
|
+
removeMany: (ids) => inner().removeMany ? inner().removeMany(ids) : Promise.all(ids.map((i) => inner().remove(i))).then(() => void 0)
|
|
3967
|
+
};
|
|
3968
|
+
}
|
|
2257
3969
|
|
|
2258
3970
|
// src/index.ts
|
|
2259
|
-
var TablesPage =
|
|
2260
|
-
var ComandaSettingsView =
|
|
2261
|
-
var ServiceChargePolicyView =
|
|
2262
|
-
var CoverChargePolicyView =
|
|
3971
|
+
var TablesPage = React3.lazy(() => import('./TablesPage-VCUJE5UR.js').then((m) => ({ default: m.TablesPage })));
|
|
3972
|
+
var ComandaSettingsView = React3.lazy(() => import('./ComandaSettingsView-66M6MS6M.js').then((m) => ({ default: m.ComandaSettingsView })));
|
|
3973
|
+
var ServiceChargePolicyView = React3.lazy(() => import('./ServiceChargePolicyView-CMG2OHRQ.js').then((m) => ({ default: m.ServiceChargePolicyView })));
|
|
3974
|
+
var CoverChargePolicyView = React3.lazy(() => import('./CoverChargePolicyView-YFM74L54.js').then((m) => ({ default: m.CoverChargePolicyView })));
|
|
2263
3975
|
var DEFAULT_LABELS = {
|
|
2264
3976
|
pageTitle: "Tables",
|
|
2265
3977
|
floorPlan: "Floor Plan",
|
|
@@ -2288,13 +4000,13 @@ function createTablesPlugin(options) {
|
|
|
2288
4000
|
const config = resolveConfig(options);
|
|
2289
4001
|
const provider = options?.dataProvider ?? createMockTablesProvider();
|
|
2290
4002
|
const store = createTablesStore(provider);
|
|
2291
|
-
const PageComponent = () =>
|
|
2292
|
-
|
|
4003
|
+
const PageComponent = () => React3.createElement(
|
|
4004
|
+
React3.Suspense,
|
|
2293
4005
|
{ fallback: null },
|
|
2294
|
-
|
|
4006
|
+
React3.createElement(TablesPage, { config, provider, store, registries: tablesRegistries })
|
|
2295
4007
|
);
|
|
2296
4008
|
registerComponent(FLOOR_PLAN_COMPONENT_ID, PageComponent);
|
|
2297
|
-
const ContextBoundary = ({ children }) =>
|
|
4009
|
+
const ContextBoundary = ({ children }) => React3.createElement(TablesContextProvider, { config, provider, store }, children);
|
|
2298
4010
|
ContextBoundary.displayName = "TablesContextBoundary";
|
|
2299
4011
|
return {
|
|
2300
4012
|
id: "tables",
|
|
@@ -2306,23 +4018,24 @@ function createTablesPlugin(options) {
|
|
|
2306
4018
|
verticalId: options?.verticalId,
|
|
2307
4019
|
defaultEnabled: true,
|
|
2308
4020
|
dependencies: [],
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
],
|
|
4021
|
+
/**
|
|
4022
|
+
* SEM página de retaguarda.
|
|
4023
|
+
*
|
|
4024
|
+
* `/tables` era a tela de Salão do começo do porte — ambientes, mesas e
|
|
4025
|
+
* uma planta em grade de células. O PDV passou a fazer tudo o que ela
|
|
4026
|
+
* fazia e melhor: a planta em METROS, as praças desenhadas, a ficha da
|
|
4027
|
+
* mesa, «Organizar automaticamente». A tela antiga ficou para trás e
|
|
4028
|
+
* mostrava um salão que já não é o da casa.
|
|
4029
|
+
*
|
|
4030
|
+
* Duas telas para o mesmo salão é pior que uma: o operador arruma numa e
|
|
4031
|
+
* não vê na outra, e a desatualizada é sempre a que alguém abre primeiro.
|
|
4032
|
+
* Decisão do founder em 28-09.
|
|
4033
|
+
*
|
|
4034
|
+
* O que a casa ainda precisa CADASTRAR — mesa nova, numeração, lote — não
|
|
4035
|
+
* tem lugar hoje. Fica anotado no checklist, não escondido aqui.
|
|
4036
|
+
*/
|
|
4037
|
+
navigation: [],
|
|
4038
|
+
routes: [],
|
|
2326
4039
|
widgets: [],
|
|
2327
4040
|
aiTools: [
|
|
2328
4041
|
{
|
|
@@ -2369,7 +4082,7 @@ function createTablesPlugin(options) {
|
|
|
2369
4082
|
label: config.labels.pageTitle,
|
|
2370
4083
|
icon: "MapPin",
|
|
2371
4084
|
component: (() => {
|
|
2372
|
-
const TablesSettingsTab = () =>
|
|
4085
|
+
const TablesSettingsTab = () => React3.createElement(PluginSettingsPanel, {
|
|
2373
4086
|
title: "Tables Settings",
|
|
2374
4087
|
registries: tablesRegistries,
|
|
2375
4088
|
routeBase: "/settings/tables"
|
|
@@ -2395,17 +4108,17 @@ function createTablesPlugin(options) {
|
|
|
2395
4108
|
label: "Taxas",
|
|
2396
4109
|
icon: "Percent",
|
|
2397
4110
|
component: (() => {
|
|
2398
|
-
const FeesSettingsTab = () =>
|
|
4111
|
+
const FeesSettingsTab = () => React3.createElement(
|
|
2399
4112
|
ContextBoundary,
|
|
2400
4113
|
null,
|
|
2401
|
-
|
|
2402
|
-
|
|
4114
|
+
React3.createElement(
|
|
4115
|
+
React3.Suspense,
|
|
2403
4116
|
{ fallback: null },
|
|
2404
|
-
|
|
4117
|
+
React3.createElement(
|
|
2405
4118
|
"div",
|
|
2406
4119
|
{ className: "space-y-6" },
|
|
2407
|
-
|
|
2408
|
-
|
|
4120
|
+
React3.createElement(ServiceChargePolicyView, { key: "service" }),
|
|
4121
|
+
React3.createElement(CoverChargePolicyView, { key: "cover" })
|
|
2409
4122
|
)
|
|
2410
4123
|
)
|
|
2411
4124
|
);
|
|
@@ -2421,13 +4134,13 @@ function createTablesPlugin(options) {
|
|
|
2421
4134
|
label: "Comanda",
|
|
2422
4135
|
icon: "Receipt",
|
|
2423
4136
|
component: (() => {
|
|
2424
|
-
const ComandaSettingsTab = () =>
|
|
4137
|
+
const ComandaSettingsTab = () => React3.createElement(
|
|
2425
4138
|
ContextBoundary,
|
|
2426
4139
|
null,
|
|
2427
|
-
|
|
2428
|
-
|
|
4140
|
+
React3.createElement(
|
|
4141
|
+
React3.Suspense,
|
|
2429
4142
|
{ fallback: null },
|
|
2430
|
-
|
|
4143
|
+
React3.createElement(ComandaSettingsView)
|
|
2431
4144
|
)
|
|
2432
4145
|
);
|
|
2433
4146
|
ComandaSettingsTab.displayName = "ComandaSettingsTab";
|
|
@@ -2443,6 +4156,6 @@ function createTablesPlugin(options) {
|
|
|
2443
4156
|
};
|
|
2444
4157
|
}
|
|
2445
4158
|
|
|
2446
|
-
export { FLOOR_PLAN_COMPONENT_ID, createCoreTablesProvider, createFayzTablesProvider, createTablesPlugin };
|
|
4159
|
+
export { FLOOR_PLAN_COMPONENT_ID, buildKdsStationEntity, buildKdsStationProvider, createCoreTablesProvider, createFayzTablesProvider, createTablesPlugin };
|
|
2447
4160
|
//# sourceMappingURL=index.js.map
|
|
2448
4161
|
//# sourceMappingURL=index.js.map
|