@fayz-ai/plugin-shop 0.32.0 → 0.33.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.
@@ -8,9 +8,9 @@ import React7__default, { useState, useEffect, useRef, useCallback, useMemo } fr
8
8
  import { Button, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, Input, ModalFooter, formatPhone, toast, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Textarea, DataTable, ConfirmDialog, Skeleton, ModalPortal, ModalOverlay, ModalBody, SearchSelect } from '@fayz-ai/ui';
9
9
  import { RotateCcw, QrCode, Pencil, Archive, Ban, CreditCard, XCircle, ShoppingBag, Package, Wallet, Plus, WandSparkles, ChefHat, Bike, Check, X, CheckCircle2, Printer, RefreshCw, ExternalLink, Truck, AlertTriangle, Loader2, Copy, Link2, HandCoins, Share2, MessageCircle, MapPin } from 'lucide-react';
10
10
  import { formatDocument, getShopProvider, CHARGEABLE_PROVIDERS, supportsPaymentLink, resolveShippingLabelProvider, getShopTenantId, documentDigits, isValidDocument } from '@fayz-ai/shop';
11
- import { useAdminPath, adminNavigateTo, useOrderReceivable, OrderDetailSkeleton, PageActions, OrderDetailBlock, OrderDetailRow, WidgetSlot, ORDER_DETAIL_ZONES, toOrderDetailReceivable, PersonLink, OrderDetailView as OrderDetailView$1, listPickablePriceTables, initialPriceTableId, OrderFormBlock, OrderCreateScreen, OrderListView, askAI, useConnectors, CrudRecordModal, AddressFormModal, useAgentSurface, ClientOrdersTab, createClientOrdersProvider, duplicateWrite } from '@fayz-ai/admin';
11
+ import { useAdminPath, adminNavigateTo, useOrderReceivable, OrderDetailSkeleton, PageActions, OrderDetailBlock, OrderDetailRow, WidgetSlot, ORDER_DETAIL_ZONES, toOrderDetailReceivable, PersonLink, OrderDetailView as OrderDetailView$1, listPickablePriceTables, initialPriceTableId, OrderFormBlock, OrderCreateScreen, OrderListView, askAI, useConnectors, CrudRecordModal, AddressFormModal, useAgentSurface, customerPriceTableField, ClientOrdersTab, createClientOrdersProvider, duplicateWrite } from '@fayz-ai/admin';
12
12
  import { FINANCIAL_ZONES } from '@fayz-ai/financial/views/zones';
13
- import { usePluginRuntimeOptional, getWidgetsForZone, getSupabaseClientOptional, formatCurrency, normalizeBrPhoneToE164, getActiveTenantId } from '@fayz-ai/core';
13
+ import { usePluginRuntimeOptional, getWidgetsForZone, getSupabaseClientOptional, formatCurrency, tl, normalizeBrPhoneToE164, getActiveTenantId } from '@fayz-ai/core';
14
14
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
15
15
  import { listStockReasonCodes } from '@fayz-ai/shop/inventory';
16
16
 
@@ -1384,6 +1384,20 @@ ${payable}`;
1384
1384
  ] })
1385
1385
  ] }) }) }) });
1386
1386
  }
1387
+
1388
+ // src/locales/en.ts
1389
+ var en = {
1390
+ "shop.customer.priceTable": "Default price table",
1391
+ "shop.customer.priceTableHint": "Pre-picked when this customer is chosen on an order. Each order can still change it.",
1392
+ "shop.customer.priceTableSaveError": "The customer was saved, but the default price table was not."
1393
+ };
1394
+
1395
+ // src/locales/pt-BR.ts
1396
+ var ptBR = {
1397
+ "shop.customer.priceTable": "Tabela de pre\xE7o padr\xE3o",
1398
+ "shop.customer.priceTableHint": "J\xE1 vem escolhida quando este cliente entra num pedido. D\xE1 para trocar em cada pedido.",
1399
+ "shop.customer.priceTableSaveError": "O cliente foi salvo, mas a tabela de pre\xE7o padr\xE3o n\xE3o."
1400
+ };
1387
1401
  function money2(value) {
1388
1402
  const n = Number(value);
1389
1403
  return formatCurrency(Number.isFinite(n) ? n : 0, "BRL");
@@ -1453,6 +1467,15 @@ function buildShopCustomerEntity() {
1453
1467
  }
1454
1468
  )
1455
1469
  },
1470
+ // The table a sale to this customer opens on. Stored on the person
1471
+ // (people.price_table_id, db 215), not on this row: CustomerModal writes it
1472
+ // there, so the CRM record and every document read one answer.
1473
+ customerPriceTableField({
1474
+ label: tl(en["shop.customer.priceTable"], ptBR["shop.customer.priceTable"]),
1475
+ hint: tl(en["shop.customer.priceTableHint"], ptBR["shop.customer.priceTableHint"]),
1476
+ group: "contact",
1477
+ span: 2
1478
+ }),
1456
1479
  // — Histórico (somente leitura) —
1457
1480
  {
1458
1481
  key: "ordersCount",
@@ -1524,11 +1547,61 @@ function buildShopCustomerEntity() {
1524
1547
  ]
1525
1548
  };
1526
1549
  }
1550
+ var client = () => getSupabaseClientOptional();
1551
+ var saleLineKey = (productId, variantId) => `${productId}:${variantId ?? ""}`;
1552
+ async function quoteSaleUnitPrices(tableId, lines) {
1553
+ const supabase = client();
1554
+ const tenantId = getShopTenantId();
1555
+ const prices = /* @__PURE__ */ new Map();
1556
+ if (!supabase || !tenantId || !lines.length) return prices;
1557
+ const { data, error } = await supabase.rpc("shop_sale_unit_prices", {
1558
+ p_tenant_id: tenantId,
1559
+ p_price_table_id: tableId,
1560
+ p_items: lines.map((l) => ({ product_id: l.productId, variant_id: l.variantId ?? null }))
1561
+ });
1562
+ if (error) throw new Error(error.message);
1563
+ for (const row of data ?? []) {
1564
+ prices.set(saleLineKey(row.product_id, row.variant_id), {
1565
+ price: Number(row.unit_price),
1566
+ inTable: row.in_table !== false,
1567
+ pending: row.price_pending === true
1568
+ });
1569
+ }
1570
+ return prices;
1571
+ }
1572
+ async function customerPersonId(supabase, shopCustomerId) {
1573
+ const { data: customer } = await supabase.from("plg_shop_customers").select("person_id").eq("id", shopCustomerId).maybeSingle();
1574
+ return customer?.person_id ?? null;
1575
+ }
1576
+ async function customerPriceTableId(shopCustomerId) {
1577
+ const supabase = client();
1578
+ if (!supabase) return null;
1579
+ const personId = await customerPersonId(supabase, shopCustomerId);
1580
+ if (!personId) return null;
1581
+ const { data: person } = await supabase.from("people").select("price_table_id").eq("id", personId).maybeSingle();
1582
+ return person?.price_table_id ?? null;
1583
+ }
1584
+ async function setCustomerPriceTableId(shopCustomerId, tableId) {
1585
+ const supabase = client();
1586
+ if (!supabase) return;
1587
+ const personId = await customerPersonId(supabase, shopCustomerId);
1588
+ if (!personId) throw new Error("customer has no registration to hold a price table");
1589
+ const { error } = await supabase.from("people").update({ price_table_id: tableId }).eq("id", personId);
1590
+ if (error) throw new Error(error.message);
1591
+ }
1592
+ async function orderPriceTableId(orderId) {
1593
+ const supabase = client();
1594
+ if (!supabase) return null;
1595
+ const { data } = await supabase.from("orders").select("metadata").eq("id", orderId).maybeSingle();
1596
+ const id = data?.metadata?.price_table_id;
1597
+ return typeof id === "string" && id ? id : null;
1598
+ }
1527
1599
  var onlyDigits = (value) => value.replace(/\D/gu, "");
1528
1600
  function CustomerModal({ open, initialName, customerId, initial, provider, onClose, onSaved }) {
1529
1601
  const entityDef = useMemo(() => buildShopCustomerEntity(), []);
1530
1602
  const [conflict, setConflict] = useState(null);
1531
1603
  const [refused, setRefused] = useState(null);
1604
+ const refusedTable = useRef(null);
1532
1605
  const [forcing, setForcing] = useState(false);
1533
1606
  const initialData = useMemo(() => {
1534
1607
  const [head, ...rest] = String(initial?.name ?? initialName ?? "").trim().split(/\s+/u);
@@ -1537,9 +1610,28 @@ function CustomerModal({ open, initialName, customerId, initial, provider, onClo
1537
1610
  lastName: rest.join(" "),
1538
1611
  email: initial?.email ?? "",
1539
1612
  phone: initial?.phone ?? "",
1540
- document: initial?.document ?? ""
1613
+ document: initial?.document ?? "",
1614
+ priceTableId: null
1541
1615
  };
1542
1616
  }, [initial, initialName]);
1617
+ const loadedTableRef = useRef(null);
1618
+ const load = useMemo(() => customerId ? async () => {
1619
+ const own = await customerPriceTableId(customerId).catch(() => null);
1620
+ loadedTableRef.current = own;
1621
+ return { ...initialData, priceTableId: own };
1622
+ } : void 0, [customerId, initialData]);
1623
+ async function saveTable(saved, picked) {
1624
+ const next = typeof picked === "string" && picked ? picked : null;
1625
+ if (next === (customerId ? loadedTableRef.current : null)) return;
1626
+ try {
1627
+ await setCustomerPriceTableId(saved.id, next);
1628
+ loadedTableRef.current = next;
1629
+ } catch (err) {
1630
+ toast.error(tl(en["shop.customer.priceTableSaveError"], ptBR["shop.customer.priceTableSaveError"]), {
1631
+ description: errorMessage(err)
1632
+ });
1633
+ }
1634
+ }
1543
1635
  useEffect(() => {
1544
1636
  if (open) {
1545
1637
  setConflict(null);
@@ -1552,6 +1644,7 @@ function CustomerModal({ open, initialName, customerId, initial, provider, onClo
1552
1644
  try {
1553
1645
  const fields = { ...refused, [conflict.field]: void 0 };
1554
1646
  const saved = customerId ? await provider().updateCustomer(customerId, fields) : await provider().createCustomer(fields);
1647
+ await saveTable(saved, refusedTable.current);
1555
1648
  toast.success(`Cadastro salvo sem o ${conflict.label} \u2014 ele j\xE1 pertence a outro cadastro.`);
1556
1649
  onSaved(saved);
1557
1650
  } catch (err) {
@@ -1578,12 +1671,14 @@ function CustomerModal({ open, initialName, customerId, initial, provider, onClo
1578
1671
  };
1579
1672
  try {
1580
1673
  const saved = customerId ? await provider().updateCustomer(customerId, fields) : await provider().createCustomer(fields);
1674
+ await saveTable(saved, data.priceTableId);
1581
1675
  onSaved(saved);
1582
1676
  return saved;
1583
1677
  } catch (err) {
1584
1678
  const clash = duplicateWrite(err);
1585
1679
  if (!clash?.field) throw err;
1586
1680
  setRefused(fields);
1681
+ refusedTable.current = data.priceTableId;
1587
1682
  const hit = clash.field === "email" && email ? (await provider().listCustomers({ search: email, limit: 5 }).catch(() => [])).find((c) => (c.email ?? "").toLowerCase() === email) ?? null : null;
1588
1683
  setConflict({ field: clash.field, label: clash.label, hit });
1589
1684
  return;
@@ -1596,6 +1691,7 @@ function CustomerModal({ open, initialName, customerId, initial, provider, onClo
1596
1691
  mode: customerId ? "edit" : "create",
1597
1692
  entityDef,
1598
1693
  initialData,
1694
+ load,
1599
1695
  title: customerId ? "Cadastro do cliente" : "Novo cliente",
1600
1696
  onClose,
1601
1697
  save,
@@ -2310,44 +2406,6 @@ function OrderDetailView({ orderId, provider, onBack, fallback }) {
2310
2406
  )
2311
2407
  ] });
2312
2408
  }
2313
- var client = () => getSupabaseClientOptional();
2314
- var saleLineKey = (productId, variantId) => `${productId}:${variantId ?? ""}`;
2315
- async function quoteSaleUnitPrices(tableId, lines) {
2316
- const supabase = client();
2317
- const tenantId = getShopTenantId();
2318
- const prices = /* @__PURE__ */ new Map();
2319
- if (!supabase || !tenantId || !lines.length) return prices;
2320
- const { data, error } = await supabase.rpc("shop_sale_unit_prices", {
2321
- p_tenant_id: tenantId,
2322
- p_price_table_id: tableId,
2323
- p_items: lines.map((l) => ({ product_id: l.productId, variant_id: l.variantId ?? null }))
2324
- });
2325
- if (error) throw new Error(error.message);
2326
- for (const row of data ?? []) {
2327
- prices.set(saleLineKey(row.product_id, row.variant_id), {
2328
- price: Number(row.unit_price),
2329
- inTable: row.in_table !== false,
2330
- pending: row.price_pending === true
2331
- });
2332
- }
2333
- return prices;
2334
- }
2335
- async function customerPriceTableId(shopCustomerId) {
2336
- const supabase = client();
2337
- if (!supabase) return null;
2338
- const { data: customer } = await supabase.from("plg_shop_customers").select("person_id").eq("id", shopCustomerId).maybeSingle();
2339
- const personId = customer?.person_id;
2340
- if (!personId) return null;
2341
- const { data: person } = await supabase.from("people").select("price_table_id").eq("id", personId).maybeSingle();
2342
- return person?.price_table_id ?? null;
2343
- }
2344
- async function orderPriceTableId(orderId) {
2345
- const supabase = client();
2346
- if (!supabase) return null;
2347
- const { data } = await supabase.from("orders").select("metadata").eq("id", orderId).maybeSingle();
2348
- const id = data?.metadata?.price_table_id;
2349
- return typeof id === "string" && id ? id : null;
2350
- }
2351
2409
  function today() {
2352
2410
  const d = /* @__PURE__ */ new Date();
2353
2411
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
@@ -2640,7 +2698,7 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2640
2698
  return () => {
2641
2699
  cancelled = true;
2642
2700
  };
2643
- }, [editing, customer.id, priceTables]);
2701
+ }, [editing, customer, priceTables]);
2644
2702
  const lineSignature = lines.map((line) => saleLineKey(line.itemId, line.variantId)).join("|");
2645
2703
  useEffect(() => {
2646
2704
  if (!lineSignature) {
@@ -4444,5 +4502,5 @@ var ShopPage = ({ provider, section }) => {
4444
4502
  ShopPage.displayName = "ShopPage";
4445
4503
 
4446
4504
  export { ShopOrderDetailSlot, ShopPage };
4447
- //# sourceMappingURL=ShopPage-WH5SL4WX.js.map
4448
- //# sourceMappingURL=ShopPage-WH5SL4WX.js.map
4505
+ //# sourceMappingURL=ShopPage-KF65QBTS.js.map
4506
+ //# sourceMappingURL=ShopPage-KF65QBTS.js.map