@fayz-ai/plugin-shop 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,10 +4,10 @@ import { listProductsDetailed, invalidateProductLists, listProductsCached } from
4
4
  import { errorMessage } from './chunk-2MXOKJQO.js';
5
5
  import * as React7 from 'react';
6
6
  import React7__default, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
7
- import { Button, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, Input, ModalFooter, formatPhone, toast, Textarea, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, DataTable, ConfirmDialog, Skeleton, ModalPortal, ModalOverlay, ModalBody, SearchSelect } from '@fayz-ai/ui';
7
+ 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';
8
8
  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';
9
- import { formatDocument, getShopProvider, CHARGEABLE_PROVIDERS, supportsPaymentLink, resolveShippingLabelProvider, documentDigits, isValidDocument } from '@fayz-ai/shop';
10
- import { useAdminPath, adminNavigateTo, useOrderReceivable, OrderDetailSkeleton, PageActions, OrderDetailBlock, OrderDetailRow, WidgetSlot, ORDER_DETAIL_ZONES, toOrderDetailReceivable, PersonLink, OrderDetailView as OrderDetailView$1, OrderFormBlock, OrderCreateScreen, OrderListView, askAI, useConnectors, CrudRecordModal, AddressFormModal, useAgentSurface, ClientOrdersTab, createClientOrdersProvider, duplicateWrite } from '@fayz-ai/admin';
9
+ import { formatDocument, getShopProvider, CHARGEABLE_PROVIDERS, supportsPaymentLink, resolveShippingLabelProvider, getShopTenantId, documentDigits, isValidDocument } from '@fayz-ai/shop';
10
+ 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
11
  import { FINANCIAL_ZONES } from '@fayz-ai/financial/views/zones';
12
12
  import { usePluginRuntimeOptional, getWidgetsForZone, getSupabaseClientOptional, formatCurrency, getActiveTenantId } from '@fayz-ai/core';
13
13
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -2326,6 +2326,40 @@ function OrderDetailView({ orderId, provider, onBack, fallback }) {
2326
2326
  )
2327
2327
  ] });
2328
2328
  }
2329
+ var client = () => getSupabaseClientOptional();
2330
+ var saleLineKey = (productId, variantId) => `${productId}:${variantId ?? ""}`;
2331
+ async function quoteSaleUnitPrices(tableId, lines) {
2332
+ const supabase = client();
2333
+ const tenantId = getShopTenantId();
2334
+ const prices = /* @__PURE__ */ new Map();
2335
+ if (!supabase || !tenantId || !lines.length) return prices;
2336
+ const { data, error } = await supabase.rpc("shop_sale_unit_prices", {
2337
+ p_tenant_id: tenantId,
2338
+ p_price_table_id: tableId,
2339
+ p_items: lines.map((l) => ({ product_id: l.productId, variant_id: l.variantId ?? null }))
2340
+ });
2341
+ if (error) throw new Error(error.message);
2342
+ for (const row of data ?? []) {
2343
+ prices.set(saleLineKey(row.product_id, row.variant_id), Number(row.unit_price));
2344
+ }
2345
+ return prices;
2346
+ }
2347
+ async function customerPriceTableId(shopCustomerId) {
2348
+ const supabase = client();
2349
+ if (!supabase) return null;
2350
+ const { data: customer } = await supabase.from("plg_shop_customers").select("person_id").eq("id", shopCustomerId).maybeSingle();
2351
+ const personId = customer?.person_id;
2352
+ if (!personId) return null;
2353
+ const { data: person } = await supabase.from("people").select("price_table_id").eq("id", personId).maybeSingle();
2354
+ return person?.price_table_id ?? null;
2355
+ }
2356
+ async function orderPriceTableId(orderId) {
2357
+ const supabase = client();
2358
+ if (!supabase) return null;
2359
+ const { data } = await supabase.from("orders").select("metadata").eq("id", orderId).maybeSingle();
2360
+ const id = data?.metadata?.price_table_id;
2361
+ return typeof id === "string" && id ? id : null;
2362
+ }
2329
2363
  function today() {
2330
2364
  const d = /* @__PURE__ */ new Date();
2331
2365
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
@@ -2493,6 +2527,7 @@ var maskPostal = (value) => {
2493
2527
  return digits2.length > 5 ? `${digits2.slice(0, 5)}-${digits2.slice(5)}` : digits2;
2494
2528
  };
2495
2529
  var fieldClass = "mt-1 px-2.5";
2530
+ var NO_PRICE_TABLE = "__none__";
2496
2531
  function Field({ label, hint, children }) {
2497
2532
  return /* @__PURE__ */ jsxs("label", { className: "block", children: [
2498
2533
  /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-muted-foreground", children: label }),
@@ -2523,6 +2558,9 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2523
2558
  const [lastEnding, setLastEnding] = useState(null);
2524
2559
  const [entryOpen, setEntryOpen] = useState(false);
2525
2560
  const [editingCustomer, setEditingCustomer] = useState(false);
2561
+ const [priceTables, setPriceTables] = useState([]);
2562
+ const [priceTableId, setPriceTableId] = useState();
2563
+ const [tablePriced, setTablePriced] = useState(false);
2526
2564
  useEffect(() => {
2527
2565
  if (!orderId) return;
2528
2566
  let cancelled = false;
@@ -2591,6 +2629,57 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2591
2629
  cancelled = true;
2592
2630
  };
2593
2631
  }, [provider]);
2632
+ useEffect(() => {
2633
+ let cancelled = false;
2634
+ void listPickablePriceTables().then(async (tables) => {
2635
+ if (cancelled) return;
2636
+ setPriceTables(tables);
2637
+ const sold = orderId ? await orderPriceTableId(orderId).catch(() => null) : void 0;
2638
+ if (cancelled) return;
2639
+ setPriceTableId((current) => orderId ? sold ?? void 0 : current ?? initialPriceTableId(tables));
2640
+ });
2641
+ return () => {
2642
+ cancelled = true;
2643
+ };
2644
+ }, [orderId]);
2645
+ useEffect(() => {
2646
+ if (editing || !customer.id || !priceTables.length) return;
2647
+ let cancelled = false;
2648
+ customerPriceTableId(customer.id).then((own) => {
2649
+ if (!cancelled) setPriceTableId(initialPriceTableId(priceTables, own));
2650
+ }).catch(() => {
2651
+ });
2652
+ return () => {
2653
+ cancelled = true;
2654
+ };
2655
+ }, [editing, customer.id, priceTables]);
2656
+ const lineSignature = lines.map((line) => saleLineKey(line.itemId, line.variantId)).join("|");
2657
+ useEffect(() => {
2658
+ if (!lineSignature) {
2659
+ setTablePriced(false);
2660
+ return;
2661
+ }
2662
+ let cancelled = false;
2663
+ const wanted = lineSignature.split("|").map((key) => {
2664
+ const [productId, variantId] = key.split(":");
2665
+ return { productId, variantId: variantId || null };
2666
+ });
2667
+ void Promise.all([
2668
+ quoteSaleUnitPrices(priceTableId ?? null, wanted),
2669
+ priceTableId ? quoteSaleUnitPrices(null, wanted) : Promise.resolve(null)
2670
+ ]).then(([table, site]) => {
2671
+ if (cancelled) return;
2672
+ setLines((current) => current.map((line) => {
2673
+ const price = table.get(saleLineKey(line.itemId, line.variantId));
2674
+ return price === void 0 || price === line.unitPrice ? line : { ...line, unitPrice: price };
2675
+ }));
2676
+ setTablePriced(Boolean(site && [...table].some(([key, price]) => site.get(key) !== price)));
2677
+ }).catch(() => {
2678
+ });
2679
+ return () => {
2680
+ cancelled = true;
2681
+ };
2682
+ }, [priceTableId, lineSignature]);
2594
2683
  const acquirer = settings?.paymentProvider ?? null;
2595
2684
  const canCharge = Boolean(acquirer && CHARGEABLE_PROVIDERS.includes(acquirer));
2596
2685
  const canLink = canCharge && supportsPaymentLink(acquirer);
@@ -2742,9 +2831,13 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2742
2831
  optionsLabel: line.optionsLabel ?? void 0
2743
2832
  })),
2744
2833
  shippingAddress,
2834
+ // No address is a pickup — the card says so, and the order should too.
2835
+ fulfillmentType: delivers ? "delivery" : "pickup",
2745
2836
  discountCode: discountCode.trim() || void 0,
2746
2837
  paymentMethod: ending === "received" ? method : void 0,
2747
- notes: notes.trim() || void 0
2838
+ notes: notes.trim() || void 0,
2839
+ // 0138: the server charges this table; an edit keeps the one it was sold in.
2840
+ ...priceTableId ? { metadata: { price_table_id: priceTableId } } : {}
2748
2841
  };
2749
2842
  const order = orderId ? await provider().reviseOrder(orderId, payload) : await provider().placeOrder(payload);
2750
2843
  if (ending === "received") {
@@ -2766,16 +2859,36 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2766
2859
  const wanted = name.trim().toLowerCase();
2767
2860
  return lines.find((line) => line.name.trim().toLowerCase() === wanted) ?? null;
2768
2861
  }, [error, lines]);
2769
- const leadSections = /* @__PURE__ */ jsx(OrderFormBlock, { title: "Cliente", children: /* @__PURE__ */ jsx(
2770
- CustomerPicker,
2771
- {
2772
- provider,
2773
- value: customer,
2774
- onChange: setCustomer,
2775
- editing: editingCustomer,
2776
- onEditing: setEditingCustomer
2777
- }
2778
- ) });
2862
+ const leadSections = /* @__PURE__ */ jsxs(Fragment, { children: [
2863
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: "Cliente", children: /* @__PURE__ */ jsx(
2864
+ CustomerPicker,
2865
+ {
2866
+ provider,
2867
+ value: customer,
2868
+ onChange: setCustomer,
2869
+ editing: editingCustomer,
2870
+ onEditing: setEditingCustomer
2871
+ }
2872
+ ) }),
2873
+ priceTables.length > 0 && /* @__PURE__ */ jsxs(OrderFormBlock, { title: "Tabela de pre\xE7o", children: [
2874
+ /* @__PURE__ */ jsxs(
2875
+ Select,
2876
+ {
2877
+ value: priceTableId ?? NO_PRICE_TABLE,
2878
+ onValueChange: (v) => setPriceTableId(v === NO_PRICE_TABLE ? void 0 : v),
2879
+ disabled: editing,
2880
+ children: [
2881
+ /* @__PURE__ */ jsx(SelectTrigger, { "aria-label": "Tabela de pre\xE7o", "data-testid": "new-order-price-table", className: "px-2.5", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
2882
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
2883
+ /* @__PURE__ */ jsx(SelectItem, { value: NO_PRICE_TABLE, children: "Pre\xE7o do site" }),
2884
+ priceTables.map((table) => /* @__PURE__ */ jsx(SelectItem, { value: table.id, children: table.name }, table.id))
2885
+ ] })
2886
+ ]
2887
+ }
2888
+ ),
2889
+ /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-xs text-muted-foreground", children: editing ? "A tabela em que o pedido foi vendido." : "Vem do cadastro do cliente. Os itens s\xE3o cobrados pelo pre\xE7o desta tabela." })
2890
+ ] })
2891
+ ] });
2779
2892
  const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
2780
2893
  /* @__PURE__ */ jsx(OrderFormBlock, { title: "Entrega", children: /* @__PURE__ */ jsx(
2781
2894
  DeliveryAddress,
@@ -2922,7 +3035,7 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2922
3035
  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "A cobran\xE7a est\xE1 aberta \u2014 o pedido entra sozinho quando ela for paga." })
2923
3036
  ] })
2924
3037
  ) : /* @__PURE__ */ jsxs(Fragment, { children: [
2925
- canCharge && /* @__PURE__ */ jsx(
3038
+ canCharge && !tablePriced && /* @__PURE__ */ jsx(
2926
3039
  Button,
2927
3040
  {
2928
3041
  onClick: () => canLink ? setCharging(true) : void finish("charge"),
@@ -2934,12 +3047,13 @@ function NewOrderPage({ provider, onDone, onCancel, orderId }) {
2934
3047
  /* @__PURE__ */ jsx(
2935
3048
  Button,
2936
3049
  {
2937
- variant: canCharge ? "ghost" : "default",
3050
+ variant: canCharge && !tablePriced ? "ghost" : "default",
2938
3051
  onClick: () => setSettling(true),
2939
3052
  "data-testid": "new-order-received",
2940
3053
  children: "J\xE1 recebi"
2941
3054
  }
2942
- )
3055
+ ),
3056
+ canCharge && tablePriced && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Para cobrar por Pix ou link no pre\xE7o da tabela, salve o pedido e cobre pela tela dele." })
2943
3057
  ] }) })
2944
3058
  ] });
2945
3059
  const overlays = /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -4328,5 +4442,5 @@ var ShopPage = ({ provider, section }) => {
4328
4442
  ShopPage.displayName = "ShopPage";
4329
4443
 
4330
4444
  export { ShopOrderDetailSlot, ShopPage };
4331
- //# sourceMappingURL=ShopPage-Z4MF334D.js.map
4332
- //# sourceMappingURL=ShopPage-Z4MF334D.js.map
4445
+ //# sourceMappingURL=ShopPage-7UKCFJKT.js.map
4446
+ //# sourceMappingURL=ShopPage-7UKCFJKT.js.map