@fayz-ai/shop 0.8.4 → 0.9.0-next.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/index.cjs DELETED
@@ -1,1365 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@fayz-ai/core');
4
-
5
- // src/mock-catalog.ts
6
- var T0 = "2026-01-01T12:00:00.000Z";
7
- function svgPlaceholder(label, hueA, hueB) {
8
- const initials = label.split(/\s+/).map((w) => w[0]).slice(0, 2).join("").toUpperCase();
9
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="600" height="600"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${hueA},45%,82%)"/><stop offset="1" stop-color="hsl(${hueB},50%,62%)"/></linearGradient></defs><rect width="600" height="600" fill="url(#g)"/><text x="300" y="330" font-family="sans-serif" font-size="120" font-weight="700" fill="rgba(255,255,255,0.85)" text-anchor="middle">${initials}</text></svg>`;
10
- return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
11
- }
12
- function image(productId, name, hueA, hueB, idx = 0) {
13
- return {
14
- id: `img-${productId}-${idx}`,
15
- productId,
16
- url: svgPlaceholder(name, hueA, hueB),
17
- altText: name,
18
- sortOrder: idx,
19
- isPrimary: idx === 0,
20
- createdAt: T0
21
- };
22
- }
23
- var MOCK_CATEGORIES = [
24
- { id: "cat-apparel", tenantId: "mock", name: "Apparel", slug: "apparel", description: "Clothing and wearables", parentId: null, sortOrder: 0, createdAt: T0 },
25
- { id: "cat-bags", tenantId: "mock", name: "Bags & Accessories", slug: "bags-accessories", description: "Bags, wallets and carry gear", parentId: null, sortOrder: 1, createdAt: T0 },
26
- { id: "cat-home", tenantId: "mock", name: "Home & Kitchen", slug: "home-kitchen", description: "Everyday home goods", parentId: null, sortOrder: 2, createdAt: T0 },
27
- { id: "cat-tech", tenantId: "mock", name: "Stationery & Tech", slug: "stationery-tech", description: "Desk, audio and paper goods", parentId: null, sortOrder: 3, createdAt: T0 }
28
- ];
29
- var SEEDS = [
30
- // --- Apparel ---
31
- { id: "p-01", name: "Classic T-Shirt", slug: "classic-t-shirt", description: "A timeless crew-neck tee in heavyweight combed cotton. Pre-shrunk, breathable, and built to outlast trends.", price: 59.9, compareAtPrice: 79.9, inventoryCount: 50, sku: "TSH-001", categoryId: "cat-apparel", hues: [210, 240], weight: 0.2 },
32
- { id: "p-02", name: "Linen Shirt", slug: "linen-shirt", description: "A relaxed-fit shirt in 100% European linen. Naturally breathable and softer with every wash.", price: 189.9, inventoryCount: 24, sku: "LNS-002", categoryId: "cat-apparel", hues: [35, 20], weight: 0.3 },
33
- { id: "p-03", name: "Denim Jacket", slug: "denim-jacket", description: "A structured trucker jacket in 12oz raw denim. Ages beautifully with hidden interior pockets.", price: 299.9, inventoryCount: 12, sku: "DNJ-003", categoryId: "cat-apparel", hues: [215, 200], weight: 0.8 },
34
- { id: "p-04", name: "Wool Beanie", slug: "wool-beanie", description: "A double-layer merino wool beanie. Warm without itch, with a low-profile cuffed fit.", price: 79.9, inventoryCount: 0, sku: "WBN-004", categoryId: "cat-apparel", hues: [0, 350], weight: 0.1 },
35
- // --- Bags & Accessories ---
36
- { id: "p-05", name: "Canvas Tote Bag", slug: "canvas-tote-bag", description: "An everyday carryall in 16oz waxed canvas with reinforced straps and an interior zip pocket.", price: 39.9, inventoryCount: 30, sku: "BAG-001", categoryId: "cat-bags", hues: [80, 110], weight: 0.3 },
37
- { id: "p-06", name: "Leather Backpack", slug: "leather-backpack", description: 'Full-grain leather backpack with a padded 15" laptop sleeve, magnetic closures and brass hardware.', price: 549.9, inventoryCount: 8, sku: "LBP-006", categoryId: "cat-bags", hues: [25, 15], weight: 1.4 },
38
- { id: "p-07", name: "Leather Card Wallet", slug: "leather-card-wallet", description: "A slim six-card wallet in vegetable-tanned leather. RFID-shielded with a center cash slot.", price: 89.9, compareAtPrice: 119.9, inventoryCount: 45, sku: "LCW-007", categoryId: "cat-bags", hues: [30, 45], weight: 0.08 },
39
- { id: "p-08", name: "Travel Duffel", slug: "travel-duffel", description: "A 40L weekender in ballistic nylon with a trolley sleeve, shoe compartment and detachable strap.", price: 329.9, inventoryCount: 15, sku: "TDF-008", categoryId: "cat-bags", hues: [150, 170], weight: 1.1 },
40
- // --- Home & Kitchen ---
41
- { id: "p-09", name: "Ceramic Coffee Mug", slug: "ceramic-coffee-mug", description: "A 350ml stoneware mug with a matte glaze and comfortable wide handle. Dishwasher and microwave safe.", price: 34.9, inventoryCount: 0, sku: "MUG-001", categoryId: "cat-home", hues: [190, 210], weight: 0.4 },
42
- { id: "p-10", name: "Scented Soy Candle", slug: "scented-soy-candle", description: "Hand-poured soy wax candle with cedar and bergamot notes. 45-hour burn time in a reusable glass jar.", price: 69.9, inventoryCount: 60, sku: "SSC-010", categoryId: "cat-home", hues: [45, 30], weight: 0.5 },
43
- { id: "p-11", name: "Bamboo Cutting Board", slug: "bamboo-cutting-board", description: "An end-grain bamboo board that is gentle on knives, with a juice groove and inset handles.", price: 119.9, inventoryCount: 22, sku: "BCB-011", categoryId: "cat-home", hues: [90, 70], weight: 1.2 },
44
- { id: "p-12", name: "Stoneware Plate Set", slug: "stoneware-plate-set", description: "A set of four reactive-glaze dinner plates. Each piece is unique, oven-safe to 220\xB0C.", price: 249.9, inventoryCount: 10, sku: "SPS-012", categoryId: "cat-home", hues: [200, 180], weight: 2.4 },
45
- // --- Stationery & Tech ---
46
- { id: "p-13", name: "Wireless Headphones", slug: "wireless-headphones", description: "Over-ear headphones with active noise cancelling, 40-hour battery and multipoint Bluetooth 5.3.", price: 899.9, inventoryCount: 18, sku: "WHP-013", categoryId: "cat-tech", hues: [260, 280], weight: 0.35 },
47
- { id: "p-14", name: "Notebook Set", slug: "notebook-set", description: "Three A5 dot-grid notebooks with 120gsm paper, lay-flat binding and numbered pages.", price: 29.9, inventoryCount: 80, sku: "NBS-014", categoryId: "cat-tech", hues: [330, 310], weight: 0.45 },
48
- { id: "p-15", name: "Bluetooth Speaker", slug: "bluetooth-speaker", description: "A pocket-size speaker with surprising low end, IPX7 waterproofing and 14-hour playtime.", price: 199.9, compareAtPrice: 259.9, inventoryCount: 26, sku: "BTS-015", categoryId: "cat-tech", hues: [170, 190], weight: 0.3 },
49
- { id: "p-16", name: "Felt Desk Mat", slug: "felt-desk-mat", description: "A 80x30cm merino felt desk mat with a cork base. Protects the desk and quiets the keyboard.", price: 99.9, inventoryCount: 34, sku: "FDM-016", categoryId: "cat-tech", hues: [220, 230], weight: 0.6 }
50
- ];
51
- var CATEGORY_NAME = Object.fromEntries(
52
- MOCK_CATEGORIES.map((c) => [c.id, c.name])
53
- );
54
- var MOCK_PRODUCTS = SEEDS.map((s, i) => ({
55
- id: s.id,
56
- tenantId: "mock",
57
- name: s.name,
58
- slug: s.slug,
59
- description: s.description,
60
- price: s.price,
61
- compareAtPrice: s.compareAtPrice ?? null,
62
- currency: "BRL",
63
- status: "active",
64
- inventoryCount: s.inventoryCount,
65
- sku: s.sku,
66
- sortOrder: i,
67
- metadata: {},
68
- images: [image(s.id, s.name, s.hues[0], s.hues[1])],
69
- categoryId: s.categoryId,
70
- categoryName: CATEGORY_NAME[s.categoryId] ?? null,
71
- isPhysical: true,
72
- weight: s.weight,
73
- weightUnit: "kg",
74
- // staggered timestamps → deterministic 'newest' sort (p-16 newest)
75
- createdAt: `2026-01-${String(i + 1).padStart(2, "0")}T12:00:00.000Z`,
76
- updatedAt: `2026-01-${String(i + 1).padStart(2, "0")}T12:00:00.000Z`
77
- }));
78
- var MOCK_DISCOUNTS = [
79
- {
80
- id: "disc-welcome",
81
- tenantId: "mock",
82
- title: "Welcome 10%",
83
- code: "BEMVINDO10",
84
- type: "percentage",
85
- method: "code",
86
- value: 10,
87
- usageLimit: null,
88
- oncePerCustomer: false,
89
- minSubtotal: null,
90
- appliesTo: "all",
91
- productIds: [],
92
- categoryIds: [],
93
- startsAt: T0,
94
- endsAt: null,
95
- status: "active",
96
- timesUsed: 0,
97
- createdAt: T0,
98
- updatedAt: T0
99
- }
100
- ];
101
- function slugifyName(name) {
102
- return name.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
103
- }
104
- function buildMockCatalog(input) {
105
- const categories = input.categories.map((c, i) => ({
106
- id: `cat-${slugifyName(c.name)}`,
107
- tenantId: "mock",
108
- name: c.name,
109
- slug: slugifyName(c.name),
110
- description: c.description ?? null,
111
- parentId: null,
112
- sortOrder: i,
113
- imageUrl: c.image ?? null,
114
- createdAt: T0
115
- }));
116
- const byName = Object.fromEntries(categories.map((c) => [c.name, c]));
117
- const products = input.products.map((p, i) => {
118
- const cat = byName[p.category];
119
- const id = `p-${String(i + 1).padStart(2, "0")}`;
120
- const hues = p.hues ?? [i * 47 % 360, (i * 47 + 50) % 360];
121
- const stamp = `2026-01-${String(i % 27 + 1).padStart(2, "0")}T12:00:00.000Z`;
122
- return {
123
- id,
124
- tenantId: "mock",
125
- name: p.name,
126
- slug: slugifyName(p.name),
127
- description: p.description,
128
- price: p.price,
129
- compareAtPrice: p.compareAtPrice ?? null,
130
- currency: input.currency ?? "BRL",
131
- status: "active",
132
- inventoryCount: p.inventory,
133
- sku: p.sku,
134
- sortOrder: i,
135
- metadata: p.metadata ?? {},
136
- images: [
137
- {
138
- id: `img-${id}-0`,
139
- productId: id,
140
- url: p.image ?? svgPlaceholder(p.name, hues[0], hues[1]),
141
- altText: p.name,
142
- sortOrder: 0,
143
- isPrimary: true,
144
- createdAt: T0
145
- }
146
- ],
147
- categoryId: cat?.id ?? null,
148
- categoryName: cat?.name ?? null,
149
- isPhysical: true,
150
- weight: p.weight ?? 0.5,
151
- weightUnit: "kg",
152
- createdAt: stamp,
153
- updatedAt: stamp
154
- };
155
- });
156
- const discounts = (input.discounts ?? []).map((d, i) => ({
157
- id: `disc-${slugifyName(d.code)}`,
158
- tenantId: "mock",
159
- title: d.title ?? `${d.percent}% off`,
160
- code: d.code,
161
- type: "percentage",
162
- method: "code",
163
- value: d.percent,
164
- usageLimit: null,
165
- oncePerCustomer: false,
166
- minSubtotal: null,
167
- appliesTo: "all",
168
- productIds: [],
169
- categoryIds: [],
170
- startsAt: T0,
171
- endsAt: null,
172
- status: "active",
173
- timesUsed: 0,
174
- createdAt: T0,
175
- updatedAt: T0
176
- }));
177
- return { products, categories, discounts };
178
- }
179
-
180
- // src/mock-provider.ts
181
- function uid() {
182
- return Math.random().toString(36).slice(2);
183
- }
184
- function now() {
185
- return (/* @__PURE__ */ new Date()).toISOString();
186
- }
187
- var ORDERS_KEY = "fayz.shop.mock.orders.v1";
188
- var CUSTOMERS_KEY = "fayz.shop.mock.customers.v1";
189
- var ENQUIRIES_KEY = "fayz.shop.mock.enquiries.v1";
190
- var CHANNELS_KEY = "fayz.shop.mock.channels.v1";
191
- var DEFAULT_CHANNELS = [
192
- { id: "online-store", tenantId: "mock", kind: "online_store", label: "Loja Online", url: null, enabled: true, position: 0, createdAt: now(), updatedAt: now() }
193
- ];
194
- function loadStored(key) {
195
- try {
196
- if (typeof localStorage === "undefined") return [];
197
- const raw = localStorage.getItem(key);
198
- return raw ? JSON.parse(raw) : [];
199
- } catch {
200
- return [];
201
- }
202
- }
203
- function store(key, value) {
204
- try {
205
- if (typeof localStorage === "undefined") return;
206
- localStorage.setItem(key, JSON.stringify(value));
207
- } catch {
208
- }
209
- }
210
- var MockShopProvider = class {
211
- constructor(seed) {
212
- this.orders = loadStored(ORDERS_KEY);
213
- this.customers = loadStored(CUSTOMERS_KEY);
214
- this.enquiries = loadStored(ENQUIRIES_KEY);
215
- this.channels = (() => {
216
- const stored = loadStored(CHANNELS_KEY);
217
- return stored.length ? stored : DEFAULT_CHANNELS.map((c) => ({ ...c }));
218
- })();
219
- this.products = (seed?.products ?? MOCK_PRODUCTS).map((p) => ({ ...p }));
220
- this.categories = (seed?.categories ?? MOCK_CATEGORIES).map((c) => ({ ...c }));
221
- this.discounts = (seed?.discounts ?? MOCK_DISCOUNTS).map((d) => ({ ...d }));
222
- }
223
- // Re-read before mutating: HMR can re-instantiate the provider mid-session
224
- // and a stale in-memory copy must not clobber persisted records.
225
- syncOrders() {
226
- this.orders = loadStored(ORDERS_KEY);
227
- }
228
- syncCustomers() {
229
- this.customers = loadStored(CUSTOMERS_KEY);
230
- }
231
- syncEnquiries() {
232
- this.enquiries = loadStored(ENQUIRIES_KEY);
233
- }
234
- syncChannels() {
235
- const stored = loadStored(CHANNELS_KEY);
236
- if (stored.length) this.channels = stored;
237
- }
238
- persistOrders() {
239
- store(ORDERS_KEY, this.orders);
240
- }
241
- persistCustomers() {
242
- store(CUSTOMERS_KEY, this.customers);
243
- }
244
- persistEnquiries() {
245
- store(ENQUIRIES_KEY, this.enquiries);
246
- }
247
- persistChannels() {
248
- store(CHANNELS_KEY, this.channels);
249
- }
250
- // ---------------------------------------------------------------------------
251
- // Products
252
- // ---------------------------------------------------------------------------
253
- async listProducts(opts) {
254
- let list = [...this.products];
255
- if (opts?.status) list = list.filter((p) => p.status === opts.status);
256
- if (opts?.categoryId) list = list.filter((p) => p.categoryId === opts.categoryId);
257
- if (opts?.slug) list = list.filter((p) => p.slug === opts.slug);
258
- if (opts?.search) {
259
- const q = opts.search.toLowerCase();
260
- list = list.filter(
261
- (p) => p.name.toLowerCase().includes(q) || (p.description ?? "").toLowerCase().includes(q) || (p.sku ?? "").toLowerCase().includes(q)
262
- );
263
- }
264
- const orderBy = opts?.orderBy ?? "sort_order";
265
- const dir = opts?.order === "desc" ? -1 : 1;
266
- list.sort((a, b) => {
267
- switch (orderBy) {
268
- case "name":
269
- return a.name.localeCompare(b.name) * dir;
270
- case "price":
271
- return (a.price - b.price) * dir;
272
- case "created_at":
273
- return a.createdAt.localeCompare(b.createdAt) * dir;
274
- default:
275
- return (a.sortOrder - b.sortOrder) * dir;
276
- }
277
- });
278
- const offset = opts?.offset ?? 0;
279
- if (offset || opts?.limit) list = list.slice(offset, opts?.limit ? offset + opts.limit : void 0);
280
- return list;
281
- }
282
- async getProduct(id) {
283
- return this.products.find((p) => p.id === id) ?? null;
284
- }
285
- async createProduct(input) {
286
- const p = { id: uid(), tenantId: "mock", name: input.name, slug: input.slug ?? input.name.toLowerCase().replace(/\s+/g, "-"), description: input.description ?? null, price: input.price, compareAtPrice: input.compareAtPrice ?? null, currency: input.currency ?? "BRL", status: input.status ?? "active", inventoryCount: input.inventoryCount ?? 0, sku: input.sku ?? null, sortOrder: input.sortOrder ?? 0, metadata: input.metadata ?? {}, images: [], categoryId: input.categoryId ?? null, categoryName: null, isPhysical: input.isPhysical ?? true, weight: input.weight ?? null, weightUnit: input.weightUnit ?? "kg", createdAt: now(), updatedAt: now() };
287
- this.products.push(p);
288
- return p;
289
- }
290
- async updateProduct(id, input) {
291
- const i = this.products.findIndex((p) => p.id === id);
292
- if (i < 0) throw new Error("Product not found");
293
- this.products[i] = { ...this.products[i], ...input, updatedAt: now() };
294
- return this.products[i];
295
- }
296
- async deleteProduct(id) {
297
- this.products = this.products.filter((p) => p.id !== id);
298
- }
299
- async uploadProductImage(_productId, _file) {
300
- throw new Error("Image upload not available in mock mode");
301
- }
302
- async deleteProductImage(_imageId) {
303
- }
304
- async createProductEnquiry(input) {
305
- this.syncEnquiries();
306
- const ts = now();
307
- const enquiry = {
308
- id: uid(),
309
- tenantId: "mock",
310
- productId: input.productId ?? null,
311
- productName: input.productName,
312
- productSlug: input.productSlug ?? null,
313
- customerName: input.customerName,
314
- customerEmail: input.customerEmail,
315
- customerPhone: input.customerPhone ?? null,
316
- subject: input.subject ?? null,
317
- message: input.message,
318
- sourceUrl: input.sourceUrl ?? null,
319
- status: "new",
320
- metadata: input.metadata ?? {},
321
- createdAt: ts,
322
- updatedAt: ts
323
- };
324
- this.enquiries.unshift(enquiry);
325
- this.persistEnquiries();
326
- return enquiry;
327
- }
328
- async listProductEnquiries(opts) {
329
- this.syncEnquiries();
330
- let list = [...this.enquiries];
331
- if (opts?.productId) list = list.filter((e) => e.productId === opts.productId);
332
- if (opts?.customerEmail) {
333
- const email = opts.customerEmail.toLowerCase();
334
- list = list.filter((e) => e.customerEmail.toLowerCase() === email);
335
- }
336
- if (opts?.status) list = list.filter((e) => e.status === opts.status);
337
- list.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
338
- const offset = opts?.offset ?? 0;
339
- if (offset || opts?.limit) list = list.slice(offset, opts?.limit ? offset + opts.limit : void 0);
340
- return list;
341
- }
342
- // ---------------------------------------------------------------------------
343
- // Categories
344
- // ---------------------------------------------------------------------------
345
- async listCategories() {
346
- return [...this.categories].sort((a, b) => a.sortOrder - b.sortOrder);
347
- }
348
- async createCategory(input) {
349
- const c = { id: uid(), tenantId: "mock", name: input.name, slug: input.slug ?? input.name.toLowerCase().replace(/\s+/g, "-"), description: input.description ?? null, parentId: input.parentId ?? null, sortOrder: input.sortOrder ?? 0, createdAt: now() };
350
- this.categories.push(c);
351
- return c;
352
- }
353
- async updateCategory(id, input) {
354
- const i = this.categories.findIndex((c) => c.id === id);
355
- if (i < 0) throw new Error("Category not found");
356
- this.categories[i] = { ...this.categories[i], ...input };
357
- return this.categories[i];
358
- }
359
- async deleteCategory(id) {
360
- this.categories = this.categories.filter((c) => c.id !== id);
361
- }
362
- // ---------------------------------------------------------------------------
363
- // Orders
364
- // ---------------------------------------------------------------------------
365
- async listOrders(opts) {
366
- this.syncOrders();
367
- let list = [...this.orders];
368
- if (opts?.status) list = list.filter((o) => o.status === opts.status);
369
- if (opts?.financialStatus) list = list.filter((o) => o.financialStatus === opts.financialStatus);
370
- if (opts?.fulfillmentStatus) list = list.filter((o) => o.fulfillmentStatus === opts.fulfillmentStatus);
371
- if (opts?.customerId) list = list.filter((o) => o.customerId === opts.customerId);
372
- if (opts?.customerEmail) {
373
- const email = opts.customerEmail.toLowerCase();
374
- list = list.filter((o) => (o.customerEmail ?? "").toLowerCase() === email);
375
- }
376
- if (opts?.search) {
377
- const q = opts.search.toLowerCase();
378
- list = list.filter(
379
- (o) => (o.customerName ?? "").toLowerCase().includes(q) || (o.customerEmail ?? "").toLowerCase().includes(q) || String(o.orderNumber).includes(q)
380
- );
381
- }
382
- list.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
383
- if (opts?.limit) list = list.slice(0, opts.limit);
384
- return list;
385
- }
386
- async getOrder(id) {
387
- this.syncOrders();
388
- return this.orders.find((o) => o.id === id) ?? null;
389
- }
390
- async createOrder(input) {
391
- this.syncOrders();
392
- const subtotal = input.items.reduce((s, i) => s + i.quantity * i.unitPrice, 0);
393
- const discountTotal = input.discountTotal ?? 0;
394
- const shippingTotal = input.shippingTotal ?? 0;
395
- const total = Math.round((subtotal - discountTotal + shippingTotal) * 100) / 100;
396
- const orderId = uid();
397
- const maxNumber = this.orders.reduce((m, o2) => Math.max(m, o2.orderNumber), 1e3);
398
- const o = {
399
- id: orderId,
400
- tenantId: "mock",
401
- orderNumber: maxNumber + 1,
402
- status: "open",
403
- financialStatus: "pending",
404
- fulfillmentStatus: "unfulfilled",
405
- currency: input.currency ?? "BRL",
406
- subtotal: Math.round(subtotal * 100) / 100,
407
- taxTotal: 0,
408
- discountTotal,
409
- shippingTotal,
410
- total,
411
- customerId: input.customerId ?? null,
412
- customerName: input.customerName ?? null,
413
- customerEmail: input.customerEmail ?? null,
414
- discountCode: input.discountCode ?? null,
415
- notes: input.notes ?? null,
416
- shippingAddress: null,
417
- // CreateOrderInput has no payment method — that is a PlaceOrderInput
418
- // concern; the mock records none rather than inventing one.
419
- paymentMethodKind: null,
420
- paidAt: null,
421
- items: input.items.map((i) => ({ id: uid(), orderId, productId: i.productId ?? null, name: i.name, sku: i.sku ?? null, quantity: i.quantity, unitPrice: i.unitPrice, total: Math.round(i.quantity * i.unitPrice * 100) / 100, imageUrl: i.imageUrl ?? null })),
422
- createdAt: now(),
423
- updatedAt: now()
424
- };
425
- this.orders.push(o);
426
- this.persistOrders();
427
- return o;
428
- }
429
- async updateOrder(id, input) {
430
- this.syncOrders();
431
- const i = this.orders.findIndex((o) => o.id === id);
432
- if (i < 0) throw new Error("Order not found");
433
- this.orders[i] = { ...this.orders[i], ...input, updatedAt: now() };
434
- this.persistOrders();
435
- return this.orders[i];
436
- }
437
- // Trusted placement (mock parity with the shop_place_order RPC): re-reads
438
- // prices + stock from the catalog, validates the discount, decrements
439
- // inventory. The browser-supplied prices are never used.
440
- async placeOrder(input) {
441
- this.syncOrders();
442
- this.syncCustomers();
443
- let customerId = input.customerId ?? null;
444
- let customerName = input.customer?.name?.trim() || null;
445
- const email = input.customer?.email?.trim().toLowerCase() || null;
446
- if (!customerId && email) {
447
- const existing = this.customers.find((c) => (c.email ?? "").toLowerCase() === email);
448
- if (existing) {
449
- customerId = existing.id;
450
- customerName = customerName ?? `${existing.firstName} ${existing.lastName}`.trim();
451
- } else {
452
- const [first, ...rest] = (customerName ?? email).split(" ");
453
- const created = await this.createCustomer({ firstName: first || email, lastName: rest.join(" "), email });
454
- customerId = created.id;
455
- }
456
- }
457
- const items = [];
458
- const lineDetails = [];
459
- let subtotal = 0;
460
- for (const line of input.items) {
461
- const product = this.products.find((p) => p.id === line.productId);
462
- if (!product || product.status !== "active") throw new Error(`Product unavailable: ${line.productId}`);
463
- if (product.inventoryCount < line.quantity) throw new Error(`Insufficient stock for ${product.name}`);
464
- const name = line.optionsLabel ? `${product.name} (${line.optionsLabel})` : product.name;
465
- const lineTotal = product.price * line.quantity;
466
- subtotal += lineTotal;
467
- lineDetails.push({ productId: product.id, categoryId: product.categoryId, lineTotal });
468
- items.push({ productId: product.id, name, sku: product.sku ?? void 0, quantity: line.quantity, unitPrice: product.price, imageUrl: product.images[0]?.url });
469
- }
470
- subtotal = Math.round(subtotal * 100) / 100;
471
- let shippingTotal = Math.max(input.shippingTotal ?? 0, 0);
472
- let discountTotal = 0;
473
- let appliedCode = null;
474
- if (input.discountCode) {
475
- const code = input.discountCode.trim().toLowerCase();
476
- const d = this.discounts.find((x) => (x.code ?? "").toLowerCase() === code);
477
- const ts = now();
478
- const meetsMin = !d?.minSubtotal || subtotal >= d.minSubtotal;
479
- const valid = !!d && d.status === "active" && d.startsAt <= ts && (!d.endsAt || d.endsAt >= ts) && (d.usageLimit == null || d.timesUsed < d.usageLimit) && meetsMin;
480
- if (valid && d) {
481
- appliedCode = d.code;
482
- let eligible = subtotal;
483
- if (d.appliesTo === "products") {
484
- eligible = lineDetails.filter((l) => d.productIds.includes(l.productId)).reduce((s, l) => s + l.lineTotal, 0);
485
- } else if (d.appliesTo === "categories") {
486
- eligible = lineDetails.filter((l) => l.categoryId && d.categoryIds.includes(l.categoryId)).reduce((s, l) => s + l.lineTotal, 0);
487
- }
488
- eligible = Math.round(eligible * 100) / 100;
489
- if (d.type === "percentage") discountTotal = Math.round(eligible * d.value) / 100;
490
- else if (d.type === "fixed_amount") discountTotal = Math.min(d.value, eligible);
491
- else if (d.type === "free_shipping") shippingTotal = 0;
492
- d.timesUsed += 1;
493
- }
494
- }
495
- discountTotal = Math.round(Math.min(Math.max(discountTotal, 0), subtotal) * 100) / 100;
496
- const order = await this.createOrder({
497
- customerId: customerId ?? void 0,
498
- customerName: customerName ?? void 0,
499
- customerEmail: input.customer?.email ?? void 0,
500
- currency: input.currency,
501
- notes: input.notes,
502
- discountCode: appliedCode ?? void 0,
503
- discountTotal,
504
- shippingTotal,
505
- items
506
- });
507
- for (const line of input.items) {
508
- const product = this.products.find((p) => p.id === line.productId);
509
- if (product) product.inventoryCount = Math.max(0, product.inventoryCount - line.quantity);
510
- }
511
- return order;
512
- }
513
- // ---------------------------------------------------------------------------
514
- // Customers
515
- // ---------------------------------------------------------------------------
516
- async listCustomers(opts) {
517
- this.syncCustomers();
518
- let list = [...this.customers];
519
- if (opts?.search) list = list.filter((c) => `${c.firstName} ${c.lastName} ${c.email}`.toLowerCase().includes(opts.search.toLowerCase()));
520
- if (opts?.limit) list = list.slice(0, opts.limit);
521
- return list;
522
- }
523
- async getCustomer(id) {
524
- this.syncCustomers();
525
- return this.customers.find((c) => c.id === id) ?? null;
526
- }
527
- async createCustomer(input) {
528
- this.syncCustomers();
529
- const c = { id: uid(), tenantId: "mock", firstName: input.firstName, lastName: input.lastName ?? "", email: input.email ?? null, phone: input.phone ?? null, notes: input.notes ?? null, ordersCount: 0, totalSpent: 0, createdAt: now(), updatedAt: now() };
530
- this.customers.push(c);
531
- this.persistCustomers();
532
- return c;
533
- }
534
- async updateCustomer(id, input) {
535
- this.syncCustomers();
536
- const i = this.customers.findIndex((c) => c.id === id);
537
- if (i < 0) throw new Error("Customer not found");
538
- this.customers[i] = { ...this.customers[i], ...input, updatedAt: now() };
539
- this.persistCustomers();
540
- return this.customers[i];
541
- }
542
- async deleteCustomer(id) {
543
- this.syncCustomers();
544
- this.customers = this.customers.filter((c) => c.id !== id);
545
- this.persistCustomers();
546
- }
547
- async resolveCustomer(input) {
548
- this.syncCustomers();
549
- const email = input.email.trim().toLowerCase();
550
- const existing = this.customers.find((c) => (c.email ?? "").toLowerCase() === email);
551
- if (existing) return existing;
552
- const [first, ...rest] = (input.name?.trim() || email).split(/\s+/);
553
- return this.createCustomer({ firstName: first || email, lastName: rest.join(" "), email });
554
- }
555
- // ---------------------------------------------------------------------------
556
- // Discounts
557
- // ---------------------------------------------------------------------------
558
- async listDiscounts(opts) {
559
- let list = [...this.discounts];
560
- if (opts?.status) list = list.filter((d) => d.status === opts.status);
561
- if (opts?.type) list = list.filter((d) => d.type === opts.type);
562
- if (opts?.search) list = list.filter((d) => d.title.toLowerCase().includes(opts.search.toLowerCase()));
563
- if (opts?.limit) list = list.slice(0, opts.limit);
564
- return list;
565
- }
566
- async getDiscount(id) {
567
- return this.discounts.find((d) => d.id === id) ?? null;
568
- }
569
- async createDiscount(input) {
570
- const d = { id: uid(), tenantId: "mock", title: input.title, code: input.code ?? null, type: input.type, method: input.method ?? "code", value: input.value, usageLimit: input.usageLimit ?? null, oncePerCustomer: input.oncePerCustomer ?? false, minSubtotal: input.minSubtotal ?? null, appliesTo: input.appliesTo ?? "all", productIds: input.productIds ?? [], categoryIds: input.categoryIds ?? [], startsAt: input.startsAt ?? now(), endsAt: input.endsAt ?? null, status: input.status ?? "active", timesUsed: 0, createdAt: now(), updatedAt: now() };
571
- this.discounts.push(d);
572
- return d;
573
- }
574
- async updateDiscount(id, input) {
575
- const i = this.discounts.findIndex((d) => d.id === id);
576
- if (i < 0) throw new Error("Discount not found");
577
- this.discounts[i] = { ...this.discounts[i], ...input, updatedAt: now() };
578
- return this.discounts[i];
579
- }
580
- async deleteDiscount(id) {
581
- this.discounts = this.discounts.filter((d) => d.id !== id);
582
- }
583
- // ---------------------------------------------------------------------------
584
- // Sales channels
585
- // ---------------------------------------------------------------------------
586
- async listSalesChannels() {
587
- this.syncChannels();
588
- return [...this.channels].sort((a, b) => a.position - b.position);
589
- }
590
- async createSalesChannel(input) {
591
- this.syncChannels();
592
- const c = { id: uid(), tenantId: "mock", kind: input.kind, label: input.label, url: input.url ?? null, enabled: input.enabled ?? true, position: input.position ?? this.channels.length, createdAt: now(), updatedAt: now() };
593
- this.channels.push(c);
594
- this.persistChannels();
595
- return c;
596
- }
597
- async updateSalesChannel(id, input) {
598
- this.syncChannels();
599
- const i = this.channels.findIndex((c) => c.id === id);
600
- if (i < 0) throw new Error("Sales channel not found");
601
- this.channels[i] = { ...this.channels[i], ...input, updatedAt: now() };
602
- this.persistChannels();
603
- return this.channels[i];
604
- }
605
- async deleteSalesChannel(id) {
606
- this.syncChannels();
607
- this.channels = this.channels.filter((c) => c.id !== id);
608
- this.persistChannels();
609
- }
610
- };
611
- function createMockShopProvider(seed) {
612
- return new MockShopProvider(seed);
613
- }
614
-
615
- // src/runtime.ts
616
- var provider = null;
617
- var mockFallback = null;
618
- function getShopProvider() {
619
- if (provider) return provider;
620
- if (!mockFallback) mockFallback = createMockShopProvider();
621
- return mockFallback;
622
- }
623
- function setShopProvider(nextProvider) {
624
- provider = nextProvider;
625
- }
626
- function resetShopProvider() {
627
- provider = null;
628
- mockFallback = null;
629
- }
630
-
631
- // src/commerce.ts
632
- function round2(n) {
633
- return Math.round(n * 100) / 100;
634
- }
635
- async function validateDiscount(input, provider2 = getShopProvider()) {
636
- const code = input.code.trim();
637
- if (!code) return { valid: false, code: null, type: null, value: 0, reason: "empty" };
638
- const list = await provider2.listDiscounts({ status: "active" });
639
- const discount = list.find((d) => (d.code ?? "").toUpperCase() === code.toUpperCase());
640
- if (!discount) return { valid: false, code: null, type: null, value: 0, reason: "not_found" };
641
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
642
- if (discount.startsAt > now2) return { valid: false, code: discount.code, type: discount.type, value: 0, reason: "not_started" };
643
- if (discount.endsAt && discount.endsAt < now2) return { valid: false, code: discount.code, type: discount.type, value: 0, reason: "expired" };
644
- if (discount.usageLimit != null && discount.timesUsed >= discount.usageLimit) {
645
- return { valid: false, code: discount.code, type: discount.type, value: 0, reason: "usage_limit" };
646
- }
647
- if (discount.type !== "percentage" && discount.type !== "fixed_amount") {
648
- return { valid: false, code: discount.code, type: discount.type, value: 0, reason: "unsupported" };
649
- }
650
- return { valid: true, code: discount.code, type: discount.type, value: discount.value };
651
- }
652
- function applyDiscount(validation, subtotal) {
653
- if (!validation.valid) return { discountTotal: 0, code: null };
654
- if (validation.type === "percentage") {
655
- return { discountTotal: round2(Math.min(subtotal, subtotal * validation.value / 100)), code: validation.code };
656
- }
657
- if (validation.type === "fixed_amount") {
658
- return { discountTotal: round2(Math.min(subtotal, validation.value)), code: validation.code };
659
- }
660
- return { discountTotal: 0, code: validation.code };
661
- }
662
- async function checkInventory(lines, provider2 = getShopProvider()) {
663
- const issues = [];
664
- for (const line of lines) {
665
- const product = await provider2.getProduct(line.productId);
666
- if (!product || product.status !== "active") {
667
- issues.push({ productId: line.productId, name: product?.name ?? line.productId, requested: line.quantity, available: 0 });
668
- continue;
669
- }
670
- if (product.inventoryCount < line.quantity) {
671
- issues.push({ productId: line.productId, name: product.name, requested: line.quantity, available: product.inventoryCount });
672
- }
673
- }
674
- return { ok: issues.length === 0, issues };
675
- }
676
- async function computeCartTotals(input, provider2 = getShopProvider()) {
677
- const lines = [];
678
- let subtotal = 0;
679
- for (const line of input.lines) {
680
- const product = await provider2.getProduct(line.productId);
681
- if (!product) continue;
682
- const lineTotal = round2(product.price * line.quantity);
683
- subtotal += lineTotal;
684
- lines.push({ productId: product.id, name: product.name, sku: product.sku, unitPrice: product.price, quantity: line.quantity, lineTotal });
685
- }
686
- subtotal = round2(subtotal);
687
- let discountTotal = 0;
688
- let discountCode = null;
689
- if (input.discountCode) {
690
- const applied = applyDiscount(
691
- await validateDiscount({ code: input.discountCode, customerId: input.customerId }, provider2),
692
- subtotal
693
- );
694
- discountTotal = applied.discountTotal;
695
- discountCode = applied.code;
696
- }
697
- const shippingTotal = round2(Math.max(input.shipping ?? 0, 0));
698
- const taxTotal = 0;
699
- const total = round2(Math.max(subtotal - discountTotal + shippingTotal + taxTotal, 0));
700
- return { lines, subtotal, discountTotal, discountCode, taxTotal, shippingTotal, total };
701
- }
702
- async function getCustomerOrders(customerId, provider2 = getShopProvider()) {
703
- return provider2.listOrders({ customerId, limit: 100 });
704
- }
705
-
706
- // src/tenant.ts
707
- var _resolver = null;
708
- function setShopTenantResolver(resolver) {
709
- _resolver = resolver;
710
- }
711
- function getShopTenantId() {
712
- if (!_resolver) return void 0;
713
- try {
714
- return _resolver();
715
- } catch {
716
- return void 0;
717
- }
718
- }
719
-
720
- // src/tables.ts
721
- var T = {
722
- products: "plg_shop_products",
723
- productImages: "plg_shop_product_images",
724
- categories: "plg_shop_categories",
725
- orders: "plg_shop_orders",
726
- orderItems: "plg_shop_order_items",
727
- customers: "plg_shop_customers",
728
- discounts: "plg_shop_discounts",
729
- salesChannels: "plg_shop_channels",
730
- // Core, not plg_shop_*: a delivery zone is a fact about the business, and
731
- // fulfilment and financial read it too. Same reasoning as addresses and
732
- // orders — see migration 0021.
733
- shippingZones: "shipping_zones"
734
- };
735
-
736
- // src/supabase-provider.ts
737
- function getDb() {
738
- const supabase = core.getSupabaseClientOptional();
739
- if (!supabase) throw new Error("@fayz-ai/shop: Supabase client not initialized. Call setGlobalSupabaseClient() first.");
740
- return supabase;
741
- }
742
- var getTenantId = getShopTenantId;
743
- function slugify(name) {
744
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
745
- }
746
- function asUuid(value) {
747
- if (!value) return null;
748
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
749
- }
750
- function toPostalDigits(value) {
751
- const digits = String(value ?? "").replace(/\D/g, "");
752
- return digits ? digits.padStart(8, "0").slice(0, 8) : void 0;
753
- }
754
- function rowToShippingZone(row) {
755
- return {
756
- id: row.id,
757
- tenantId: row.tenant_id,
758
- name: row.name,
759
- carrier: row.carrier ?? null,
760
- postalFrom: String(row.postal_from ?? "").trim(),
761
- postalTo: String(row.postal_to ?? "").trim(),
762
- rate: Number(row.rate ?? 0),
763
- freeAbove: row.free_above == null ? null : Number(row.free_above),
764
- etaMinDays: row.eta_min_days ?? null,
765
- etaMaxDays: row.eta_max_days ?? null,
766
- active: row.active ?? true,
767
- sortOrder: row.sort_order ?? 0
768
- };
769
- }
770
- function shippingZonePayload(input) {
771
- const payload = {};
772
- if (input.name !== void 0) payload.name = input.name;
773
- if (input.carrier !== void 0) payload.carrier = input.carrier || null;
774
- if (input.postalFrom !== void 0) payload.postal_from = toPostalDigits(input.postalFrom);
775
- if (input.postalTo !== void 0) payload.postal_to = toPostalDigits(input.postalTo);
776
- if (input.rate !== void 0) payload.rate = input.rate;
777
- if (input.freeAbove !== void 0) payload.free_above = input.freeAbove ?? null;
778
- if (input.etaMinDays !== void 0) payload.eta_min_days = input.etaMinDays ?? null;
779
- if (input.etaMaxDays !== void 0) payload.eta_max_days = input.etaMaxDays ?? null;
780
- if (input.active !== void 0) payload.active = input.active;
781
- if (input.sortOrder !== void 0) payload.sort_order = input.sortOrder;
782
- return payload;
783
- }
784
- function rowToProduct(row) {
785
- return {
786
- id: row.id,
787
- tenantId: row.tenant_id,
788
- name: row.name,
789
- slug: row.slug ?? slugify(row.name),
790
- description: row.description,
791
- price: row.price ?? 0,
792
- compareAtPrice: row.compare_at_price,
793
- currency: row.currency ?? "BRL",
794
- status: row.status ?? "active",
795
- inventoryCount: row.inventory_count ?? 0,
796
- sku: row.sku,
797
- sortOrder: row.sort_order ?? 0,
798
- metadata: row.metadata ?? {},
799
- images: Array.isArray(row.images) ? row.images.map(rowToImage) : [],
800
- categoryId: row.category_id,
801
- categoryName: row.category_name ?? null,
802
- isPhysical: row.is_physical ?? true,
803
- weight: row.weight,
804
- weightUnit: row.weight_unit ?? "kg",
805
- createdAt: row.created_at,
806
- updatedAt: row.updated_at
807
- };
808
- }
809
- function rowToImage(row) {
810
- return {
811
- id: row.id,
812
- productId: row.product_id,
813
- url: row.url,
814
- altText: row.alt_text,
815
- sortOrder: row.sort_order ?? 0,
816
- isPrimary: row.is_primary ?? false,
817
- createdAt: row.created_at
818
- };
819
- }
820
- function rowToCategory(row) {
821
- return {
822
- id: row.id,
823
- tenantId: row.tenant_id,
824
- name: row.name,
825
- slug: row.slug ?? slugify(row.name),
826
- description: row.description,
827
- parentId: row.parent_id,
828
- sortOrder: row.sort_order ?? 0,
829
- createdAt: row.created_at
830
- };
831
- }
832
- function rowToOrderItem(row) {
833
- return {
834
- id: row.id,
835
- orderId: row.order_id,
836
- productId: row.product_id ?? null,
837
- name: row.name,
838
- sku: row.sku ?? null,
839
- quantity: row.quantity ?? 0,
840
- unitPrice: row.unit_price ?? 0,
841
- total: row.total ?? 0,
842
- imageUrl: row.image_url ?? null
843
- };
844
- }
845
- function rowToOrder(row) {
846
- return {
847
- id: row.id,
848
- tenantId: row.tenant_id,
849
- orderNumber: row.order_number,
850
- status: row.status ?? "open",
851
- financialStatus: row.financial_status ?? "pending",
852
- fulfillmentStatus: row.fulfillment_status ?? "unfulfilled",
853
- currency: row.currency ?? "BRL",
854
- subtotal: row.subtotal ?? 0,
855
- taxTotal: row.tax_total ?? 0,
856
- discountTotal: row.discount_total ?? 0,
857
- shippingTotal: row.shipping_total ?? 0,
858
- total: row.total ?? 0,
859
- customerId: row.customer_id,
860
- customerName: row.customer_name,
861
- customerEmail: row.customer_email,
862
- discountCode: row.discount_code,
863
- notes: row.notes,
864
- shippingAddress: row.shipping_address ?? null,
865
- paymentMethodKind: row.payment_method_kind ?? null,
866
- paidAt: row.paid_at ?? null,
867
- items: Array.isArray(row.items) ? row.items.map(rowToOrderItem) : [],
868
- createdAt: row.created_at,
869
- updatedAt: row.updated_at
870
- };
871
- }
872
- function rowToCustomer(row) {
873
- return {
874
- id: row.id,
875
- tenantId: row.tenant_id,
876
- firstName: row.first_name,
877
- lastName: row.last_name ?? "",
878
- email: row.email,
879
- phone: row.phone,
880
- notes: row.notes,
881
- ordersCount: row.orders_count ?? 0,
882
- totalSpent: row.total_spent ?? 0,
883
- createdAt: row.created_at,
884
- updatedAt: row.updated_at
885
- };
886
- }
887
- function rowToDiscount(row) {
888
- return {
889
- id: row.id,
890
- tenantId: row.tenant_id,
891
- title: row.title,
892
- code: row.code,
893
- type: row.type,
894
- method: row.method ?? "code",
895
- value: row.value ?? 0,
896
- usageLimit: row.usage_limit,
897
- oncePerCustomer: row.once_per_customer ?? false,
898
- minSubtotal: row.min_subtotal ?? null,
899
- appliesTo: row.applies_to ?? "all",
900
- productIds: row.product_ids ?? [],
901
- categoryIds: row.category_ids ?? [],
902
- startsAt: row.starts_at,
903
- endsAt: row.ends_at,
904
- status: row.status ?? "active",
905
- timesUsed: row.times_used ?? 0,
906
- createdAt: row.created_at,
907
- updatedAt: row.updated_at
908
- };
909
- }
910
- function rowToSalesChannel(row) {
911
- return {
912
- id: row.id,
913
- tenantId: row.tenant_id,
914
- kind: row.kind,
915
- label: row.label,
916
- url: row.url,
917
- enabled: row.enabled ?? true,
918
- position: row.position ?? 0,
919
- createdAt: row.created_at,
920
- updatedAt: row.updated_at
921
- };
922
- }
923
- var SupabaseShopProvider = class {
924
- // ---------------------------------------------------------------------------
925
- // Products
926
- // ---------------------------------------------------------------------------
927
- async listProducts(options) {
928
- const db = getDb();
929
- const tenantId = getTenantId();
930
- let q = db.from(T.products).select(`*, images:${T.productImages}(*)`);
931
- if (tenantId) q = q.eq("tenant_id", tenantId);
932
- if (options?.status) q = q.eq("status", options.status);
933
- if (options?.categoryId) q = q.eq("category_id", options.categoryId);
934
- if (options?.slug) q = q.eq("slug", options.slug);
935
- if (options?.search) q = q.ilike("name", `%${options.search}%`);
936
- q = q.order(options?.orderBy ?? "sort_order", { ascending: options?.order !== "desc" });
937
- if (options?.limit) q = q.limit(options.limit);
938
- if (options?.offset) q = q.range(options.offset, (options.offset ?? 0) + (options.limit ?? 50) - 1);
939
- const { data, error } = await q;
940
- if (error) throw error;
941
- return (data ?? []).map(rowToProduct);
942
- }
943
- async getProduct(id) {
944
- const db = getDb();
945
- const { data, error } = await db.from(T.products).select(`*, images:${T.productImages}(*)`).eq("id", id).maybeSingle();
946
- if (error) throw error;
947
- return data ? rowToProduct(data) : null;
948
- }
949
- async createProduct(input) {
950
- const db = getDb();
951
- const tenantId = getTenantId();
952
- const { data, error } = await db.from(T.products).insert({
953
- tenant_id: tenantId,
954
- name: input.name,
955
- slug: input.slug ?? slugify(input.name),
956
- description: input.description ?? null,
957
- price: input.price,
958
- compare_at_price: input.compareAtPrice ?? null,
959
- currency: input.currency ?? "BRL",
960
- status: input.status ?? "active",
961
- inventory_count: input.inventoryCount ?? 0,
962
- sku: input.sku ?? null,
963
- sort_order: input.sortOrder ?? 0,
964
- metadata: input.metadata ?? {},
965
- category_id: input.categoryId ?? null,
966
- is_physical: input.isPhysical ?? true,
967
- weight: input.weight ?? null,
968
- weight_unit: input.weightUnit ?? "kg"
969
- }).select(`*, images:${T.productImages}(*)`).single();
970
- if (error) throw error;
971
- return rowToProduct(data);
972
- }
973
- async updateProduct(id, input) {
974
- const db = getDb();
975
- const updates = {};
976
- if (input.name !== void 0) {
977
- updates.name = input.name;
978
- updates.slug = input.slug ?? slugify(input.name);
979
- }
980
- if (input.slug !== void 0) updates.slug = input.slug;
981
- if (input.description !== void 0) updates.description = input.description;
982
- if (input.price !== void 0) updates.price = input.price;
983
- if (input.compareAtPrice !== void 0) updates.compare_at_price = input.compareAtPrice;
984
- if (input.currency !== void 0) updates.currency = input.currency;
985
- if (input.status !== void 0) updates.status = input.status;
986
- if (input.inventoryCount !== void 0) updates.inventory_count = input.inventoryCount;
987
- if (input.sku !== void 0) updates.sku = input.sku;
988
- if (input.categoryId !== void 0) updates.category_id = input.categoryId;
989
- if (input.isPhysical !== void 0) updates.is_physical = input.isPhysical;
990
- if (input.weight !== void 0) updates.weight = input.weight;
991
- const { data, error } = await db.from(T.products).update(updates).eq("id", id).select(`*, images:${T.productImages}(*)`).single();
992
- if (error) throw error;
993
- return rowToProduct(data);
994
- }
995
- async deleteProduct(id) {
996
- const { error } = await getDb().from(T.products).delete().eq("id", id);
997
- if (error) throw error;
998
- }
999
- async uploadProductImage(productId, file) {
1000
- const db = getDb();
1001
- const tenantId = getTenantId();
1002
- const path = `${tenantId}/products/${productId}/${Date.now()}-${file.name}`;
1003
- const { error: uploadErr } = await db.storage.from("shop-images").upload(path, file);
1004
- if (uploadErr) throw uploadErr;
1005
- const { data: { publicUrl } } = db.storage.from("shop-images").getPublicUrl(path);
1006
- const { data: existing } = await db.from(T.productImages).select("id,sort_order").eq("product_id", productId).order("sort_order", { ascending: false }).limit(1);
1007
- const first = !existing || existing.length === 0;
1008
- const nextOrder = first ? 0 : (existing[0].sort_order ?? 0) + 1;
1009
- const { data, error } = await db.from(T.productImages).insert({
1010
- product_id: productId,
1011
- tenant_id: tenantId,
1012
- url: publicUrl,
1013
- sort_order: nextOrder,
1014
- is_primary: first
1015
- }).select().single();
1016
- if (error) throw error;
1017
- return rowToImage(data);
1018
- }
1019
- async updateProductImage(imageId, input) {
1020
- const db = getDb();
1021
- const updates = {};
1022
- if (input.sortOrder !== void 0) updates.sort_order = input.sortOrder;
1023
- if (input.altText !== void 0) updates.alt_text = input.altText;
1024
- if (input.isPrimary !== void 0) updates.is_primary = input.isPrimary;
1025
- if (input.isPrimary) {
1026
- const { data: target } = await db.from(T.productImages).select("product_id").eq("id", imageId).single();
1027
- if (target?.product_id) {
1028
- await db.from(T.productImages).update({ is_primary: false }).eq("product_id", target.product_id).neq("id", imageId);
1029
- }
1030
- }
1031
- const { data, error } = await db.from(T.productImages).update(updates).eq("id", imageId).select().single();
1032
- if (error) throw error;
1033
- return rowToImage(data);
1034
- }
1035
- async deleteProductImage(imageId) {
1036
- const { error } = await getDb().from(T.productImages).delete().eq("id", imageId);
1037
- if (error) throw error;
1038
- }
1039
- // ---------------------------------------------------------------------------
1040
- // Categories
1041
- // ---------------------------------------------------------------------------
1042
- async listCategories() {
1043
- const db = getDb();
1044
- const tenantId = getTenantId();
1045
- let q = db.from(T.categories).select("*").order("sort_order", { ascending: true });
1046
- if (tenantId) q = q.eq("tenant_id", tenantId);
1047
- const { data, error } = await q;
1048
- if (error) throw error;
1049
- return (data ?? []).map(rowToCategory);
1050
- }
1051
- async createCategory(input) {
1052
- const db = getDb();
1053
- const { data, error } = await db.from(T.categories).insert({ tenant_id: getTenantId(), name: input.name, slug: input.slug ?? slugify(input.name), description: input.description ?? null, parent_id: input.parentId ?? null, sort_order: input.sortOrder ?? 0 }).select().single();
1054
- if (error) throw error;
1055
- return rowToCategory(data);
1056
- }
1057
- async updateCategory(id, input) {
1058
- const db = getDb();
1059
- const updates = {};
1060
- if (input.name !== void 0) updates.name = input.name;
1061
- if (input.slug !== void 0) updates.slug = input.slug;
1062
- if (input.description !== void 0) updates.description = input.description;
1063
- if (input.parentId !== void 0) updates.parent_id = input.parentId;
1064
- if (input.sortOrder !== void 0) updates.sort_order = input.sortOrder;
1065
- const { data, error } = await db.from(T.categories).update(updates).eq("id", id).select().single();
1066
- if (error) throw error;
1067
- return rowToCategory(data);
1068
- }
1069
- async deleteCategory(id) {
1070
- const { error } = await getDb().from(T.categories).delete().eq("id", id);
1071
- if (error) throw error;
1072
- }
1073
- // ---------------------------------------------------------------------------
1074
- // Orders
1075
- // ---------------------------------------------------------------------------
1076
- async listOrders(options) {
1077
- const db = getDb();
1078
- const tenantId = getTenantId();
1079
- let q = db.from(T.orders).select(`*, items:${T.orderItems}(*)`);
1080
- if (tenantId) q = q.eq("tenant_id", tenantId);
1081
- if (options?.status) q = q.eq("status", options.status);
1082
- if (options?.financialStatus) q = q.eq("financial_status", options.financialStatus);
1083
- if (options?.fulfillmentStatus) q = q.eq("fulfillment_status", options.fulfillmentStatus);
1084
- if (options?.customerId) q = q.eq("customer_id", options.customerId);
1085
- if (options?.customerEmail) q = q.eq("customer_email", options.customerEmail);
1086
- if (options?.search) q = q.or(`customer_name.ilike.%${options.search}%,customer_email.ilike.%${options.search}%`);
1087
- q = q.order("created_at", { ascending: false });
1088
- if (options?.limit) q = q.limit(options.limit);
1089
- const { data, error } = await q;
1090
- if (error) throw error;
1091
- return (data ?? []).map(rowToOrder);
1092
- }
1093
- async getOrder(id) {
1094
- const { data, error } = await getDb().from(T.orders).select(`*, items:${T.orderItems}(*)`).eq("id", id).maybeSingle();
1095
- if (error) throw error;
1096
- return data ? rowToOrder(data) : null;
1097
- }
1098
- async createOrder(input) {
1099
- const db = getDb();
1100
- const tenantId = getTenantId();
1101
- const subtotal = input.items.reduce((s, i) => s + i.quantity * i.unitPrice, 0);
1102
- const discountTotal = input.discountTotal ?? 0;
1103
- const shippingTotal = input.shippingTotal ?? 0;
1104
- const total = Math.round((subtotal - discountTotal + shippingTotal) * 100) / 100;
1105
- const { data: order, error: orderErr } = await db.from(T.orders).insert({ tenant_id: tenantId, customer_id: input.customerId ?? null, customer_name: input.customerName ?? null, customer_email: input.customerEmail ?? null, currency: input.currency ?? "BRL", notes: input.notes ?? null, subtotal, discount_total: discountTotal, shipping_total: shippingTotal, discount_code: input.discountCode ?? null, total, status: "open", financial_status: "pending", fulfillment_status: "unfulfilled" }).select().single();
1106
- if (orderErr) throw orderErr;
1107
- const items = input.items.map((i) => ({ order_id: order.id, product_id: asUuid(i.productId), name: i.name, sku: i.sku ?? null, quantity: i.quantity, unit_price: i.unitPrice, total: i.quantity * i.unitPrice, image_url: i.imageUrl ?? null }));
1108
- await db.from(T.orderItems).insert(items);
1109
- return this.getOrder(order.id);
1110
- }
1111
- async updateOrder(id, input) {
1112
- const updates = {};
1113
- if (input.status !== void 0) updates.status = input.status;
1114
- if (input.financialStatus !== void 0) updates.financial_status = input.financialStatus;
1115
- if (input.fulfillmentStatus !== void 0) updates.fulfillment_status = input.fulfillmentStatus;
1116
- if (input.notes !== void 0) updates.notes = input.notes;
1117
- const { error } = await getDb().from(T.orders).update(updates).eq("id", id);
1118
- if (error) throw error;
1119
- return this.getOrder(id);
1120
- }
1121
- // -------------------------------------------------------------------------
1122
- // Delivery zones
1123
- //
1124
- // Postal codes are stored as 8 bare digits so the range test in
1125
- // shop_quote_shipping is a plain BETWEEN. Accepting '22.041-001' from the
1126
- // form and normalising here means the merchant never has to think about it.
1127
- // -------------------------------------------------------------------------
1128
- async listShippingZones() {
1129
- const tenantId = getTenantId();
1130
- const { data, error } = await getDb().from(T.shippingZones).select("*").eq("tenant_id", tenantId).order("sort_order", { ascending: true }).order("postal_from", { ascending: true });
1131
- if (error) throw error;
1132
- return (data ?? []).map(rowToShippingZone);
1133
- }
1134
- async createShippingZone(input) {
1135
- const tenantId = getTenantId();
1136
- if (!tenantId) throw new Error("@fayz-ai/shop: createShippingZone requires a tenant id.");
1137
- const { data, error } = await getDb().from(T.shippingZones).insert({ tenant_id: tenantId, ...shippingZonePayload(input) }).select().single();
1138
- if (error) throw error;
1139
- return rowToShippingZone(data);
1140
- }
1141
- async updateShippingZone(id, input) {
1142
- const { data, error } = await getDb().from(T.shippingZones).update(shippingZonePayload(input)).eq("id", id).select().single();
1143
- if (error) throw error;
1144
- return rowToShippingZone(data);
1145
- }
1146
- async deleteShippingZone(id) {
1147
- const { error } = await getDb().from(T.shippingZones).delete().eq("id", id);
1148
- if (error) throw error;
1149
- }
1150
- /**
1151
- * Settle a pending order: the merchant confirming that the money arrived.
1152
- *
1153
- * Goes through the RPC rather than an UPDATE so the payment ledger row in
1154
- * public.transactions closes in the same transaction as the order — set
1155
- * financial_status by hand and the order says paid while the ledger still
1156
- * says pending. Since 0019 the RPC also enforces who may call it: a member of
1157
- * the owning tenant, or a PSP webhook with the service role.
1158
- */
1159
- async confirmPayment(id, reference) {
1160
- const { error } = await getDb().rpc("shop_confirm_payment", {
1161
- p_order_id: id,
1162
- p_reference: reference ?? null
1163
- });
1164
- if (error) throw error;
1165
- return this.getOrder(id);
1166
- }
1167
- // Trusted placement — delegates all price/discount/inventory authority to the
1168
- // shop_place_order RPC (SECURITY DEFINER). The browser never sets a price.
1169
- async placeOrder(input) {
1170
- const db = getDb();
1171
- const tenantId = input.tenantId ?? getTenantId();
1172
- if (!tenantId) throw new Error("@fayz-ai/shop: placeOrder requires a tenant id (configure the shop tenant resolver).");
1173
- const { data, error } = await db.rpc("shop_place_order", {
1174
- p_tenant_id: tenantId,
1175
- p_items: input.items.map((i) => ({ product_id: i.productId, quantity: i.quantity, options_label: i.optionsLabel ?? null })),
1176
- p_customer_id: asUuid(input.customerId),
1177
- p_customer_name: input.customer?.name ?? null,
1178
- p_customer_email: input.customer?.email ?? null,
1179
- p_currency: input.currency ?? "BRL",
1180
- p_discount_code: input.discountCode ?? null,
1181
- p_shipping_total: input.shippingTotal ?? 0,
1182
- // snake_case keys on purpose: the RPC freezes this jsonb onto the
1183
- // order and public.addresses uses these exact column names.
1184
- p_shipping_address: input.shippingAddress ? {
1185
- postal_code: input.shippingAddress.postalCode,
1186
- street: input.shippingAddress.street,
1187
- number: input.shippingAddress.number ?? null,
1188
- complement: input.shippingAddress.complement ?? null,
1189
- district: input.shippingAddress.district ?? null,
1190
- city: input.shippingAddress.city,
1191
- state: input.shippingAddress.state,
1192
- country: input.shippingAddress.country ?? "BR",
1193
- recipient: input.shippingAddress.recipient ?? null,
1194
- phone: input.shippingAddress.phone ?? null,
1195
- label: input.shippingAddress.label ?? null
1196
- } : null,
1197
- p_payment_method: input.paymentMethod ?? null,
1198
- p_notes: input.notes ?? null
1199
- });
1200
- if (error) throw error;
1201
- const orderId = typeof data === "string" ? data : data?.id ?? data?.order_id ?? data;
1202
- const order = await this.getOrder(orderId);
1203
- if (!order) throw new Error("@fayz-ai/shop: placeOrder did not return a persisted order.");
1204
- return order;
1205
- }
1206
- // ---------------------------------------------------------------------------
1207
- // Customers
1208
- // ---------------------------------------------------------------------------
1209
- async listCustomers(options) {
1210
- const db = getDb();
1211
- const tenantId = getTenantId();
1212
- let q = db.from(T.customers).select("*").order("first_name", { ascending: true });
1213
- if (tenantId) q = q.eq("tenant_id", tenantId);
1214
- if (options?.search) q = q.or(`first_name.ilike.%${options.search}%,last_name.ilike.%${options.search}%,email.ilike.%${options.search}%`);
1215
- if (options?.limit) q = q.limit(options.limit);
1216
- const { data, error } = await q;
1217
- if (error) throw error;
1218
- return (data ?? []).map(rowToCustomer);
1219
- }
1220
- async getCustomer(id) {
1221
- const { data, error } = await getDb().from(T.customers).select("*").eq("id", id).maybeSingle();
1222
- if (error) throw error;
1223
- return data ? rowToCustomer(data) : null;
1224
- }
1225
- async createCustomer(input) {
1226
- const { data, error } = await getDb().from(T.customers).insert({ tenant_id: getTenantId(), first_name: input.firstName, last_name: input.lastName ?? "", email: input.email ?? null, phone: input.phone ?? null, notes: input.notes ?? null }).select().single();
1227
- if (error) throw error;
1228
- return rowToCustomer(data);
1229
- }
1230
- async updateCustomer(id, input) {
1231
- const updates = {};
1232
- if (input.firstName !== void 0) updates.first_name = input.firstName;
1233
- if (input.lastName !== void 0) updates.last_name = input.lastName;
1234
- if (input.email !== void 0) updates.email = input.email;
1235
- if (input.phone !== void 0) updates.phone = input.phone;
1236
- if (input.notes !== void 0) updates.notes = input.notes;
1237
- const { data, error } = await getDb().from(T.customers).update(updates).eq("id", id).select().single();
1238
- if (error) throw error;
1239
- return rowToCustomer(data);
1240
- }
1241
- async deleteCustomer(id) {
1242
- const { error } = await getDb().from(T.customers).delete().eq("id", id);
1243
- if (error) throw error;
1244
- }
1245
- // Find-or-create + link to auth.uid server-side (SECURITY DEFINER RPC), so the
1246
- // browser never supplies the auth id and "my orders" is RLS-scoped to the owner.
1247
- async resolveCustomer(input) {
1248
- const db = getDb();
1249
- const tenantId = input.tenantId ?? getTenantId();
1250
- if (!tenantId) throw new Error("@fayz-ai/shop: resolveCustomer requires a tenant id.");
1251
- const { data, error } = await db.rpc("shop_resolve_customer", {
1252
- p_tenant_id: tenantId,
1253
- p_email: input.email,
1254
- p_name: input.name ?? null
1255
- });
1256
- if (error) throw error;
1257
- const row = Array.isArray(data) ? data[0] : data;
1258
- if (!row) throw new Error("@fayz-ai/shop: resolveCustomer returned no row.");
1259
- return rowToCustomer(row);
1260
- }
1261
- // ---------------------------------------------------------------------------
1262
- // Discounts
1263
- // ---------------------------------------------------------------------------
1264
- async listDiscounts(options) {
1265
- const db = getDb();
1266
- const tenantId = getTenantId();
1267
- let q = db.from(T.discounts).select("*").order("created_at", { ascending: false });
1268
- if (tenantId) q = q.eq("tenant_id", tenantId);
1269
- if (options?.status) q = q.eq("status", options.status);
1270
- if (options?.type) q = q.eq("type", options.type);
1271
- if (options?.search) q = q.ilike("title", `%${options.search}%`);
1272
- if (options?.limit) q = q.limit(options.limit);
1273
- const { data, error } = await q;
1274
- if (error) throw error;
1275
- return (data ?? []).map(rowToDiscount);
1276
- }
1277
- async getDiscount(id) {
1278
- const { data, error } = await getDb().from(T.discounts).select("*").eq("id", id).maybeSingle();
1279
- if (error) throw error;
1280
- return data ? rowToDiscount(data) : null;
1281
- }
1282
- async createDiscount(input) {
1283
- const { data, error } = await getDb().from(T.discounts).insert({ tenant_id: getTenantId(), title: input.title, code: input.code ?? null, type: input.type, method: input.method ?? "code", value: input.value, usage_limit: input.usageLimit ?? null, once_per_customer: input.oncePerCustomer ?? false, min_subtotal: input.minSubtotal ?? null, applies_to: input.appliesTo ?? "all", product_ids: input.productIds ?? [], category_ids: input.categoryIds ?? [], starts_at: input.startsAt ?? (/* @__PURE__ */ new Date()).toISOString(), ends_at: input.endsAt ?? null, status: input.status ?? "active", times_used: 0 }).select().single();
1284
- if (error) throw error;
1285
- return rowToDiscount(data);
1286
- }
1287
- async updateDiscount(id, input) {
1288
- const updates = {};
1289
- if (input.title !== void 0) updates.title = input.title;
1290
- if (input.code !== void 0) updates.code = input.code;
1291
- if (input.type !== void 0) updates.type = input.type;
1292
- if (input.value !== void 0) updates.value = input.value;
1293
- if (input.usageLimit !== void 0) updates.usage_limit = input.usageLimit;
1294
- if (input.minSubtotal !== void 0) updates.min_subtotal = input.minSubtotal;
1295
- if (input.appliesTo !== void 0) updates.applies_to = input.appliesTo;
1296
- if (input.productIds !== void 0) updates.product_ids = input.productIds;
1297
- if (input.categoryIds !== void 0) updates.category_ids = input.categoryIds;
1298
- if (input.status !== void 0) updates.status = input.status;
1299
- if (input.endsAt !== void 0) updates.ends_at = input.endsAt;
1300
- const { data, error } = await getDb().from(T.discounts).update(updates).eq("id", id).select().single();
1301
- if (error) throw error;
1302
- return rowToDiscount(data);
1303
- }
1304
- async deleteDiscount(id) {
1305
- const { error } = await getDb().from(T.discounts).delete().eq("id", id);
1306
- if (error) throw error;
1307
- }
1308
- // ---------------------------------------------------------------------------
1309
- // Sales channels
1310
- // ---------------------------------------------------------------------------
1311
- async listSalesChannels() {
1312
- const db = getDb();
1313
- const tenantId = getTenantId();
1314
- let q = db.from(T.salesChannels).select("*").order("position", { ascending: true });
1315
- if (tenantId) q = q.eq("tenant_id", tenantId);
1316
- const { data, error } = await q;
1317
- if (error) throw error;
1318
- return (data ?? []).map(rowToSalesChannel);
1319
- }
1320
- async createSalesChannel(input) {
1321
- const { data, error } = await getDb().from(T.salesChannels).insert({ tenant_id: getTenantId(), kind: input.kind, label: input.label, url: input.url ?? null, enabled: input.enabled ?? true, position: input.position ?? 0 }).select().single();
1322
- if (error) throw error;
1323
- return rowToSalesChannel(data);
1324
- }
1325
- async updateSalesChannel(id, input) {
1326
- const updates = {};
1327
- if (input.kind !== void 0) updates.kind = input.kind;
1328
- if (input.label !== void 0) updates.label = input.label;
1329
- if (input.url !== void 0) updates.url = input.url;
1330
- if (input.enabled !== void 0) updates.enabled = input.enabled;
1331
- if (input.position !== void 0) updates.position = input.position;
1332
- const { data, error } = await getDb().from(T.salesChannels).update(updates).eq("id", id).select().single();
1333
- if (error) throw error;
1334
- return rowToSalesChannel(data);
1335
- }
1336
- async deleteSalesChannel(id) {
1337
- const { error } = await getDb().from(T.salesChannels).delete().eq("id", id);
1338
- if (error) throw error;
1339
- }
1340
- };
1341
- function createSupabaseShopProvider() {
1342
- return new SupabaseShopProvider();
1343
- }
1344
-
1345
- exports.MOCK_CATEGORIES = MOCK_CATEGORIES;
1346
- exports.MOCK_DISCOUNTS = MOCK_DISCOUNTS;
1347
- exports.MOCK_PRODUCTS = MOCK_PRODUCTS;
1348
- exports.MockShopProvider = MockShopProvider;
1349
- exports.SupabaseShopProvider = SupabaseShopProvider;
1350
- exports.applyDiscount = applyDiscount;
1351
- exports.buildMockCatalog = buildMockCatalog;
1352
- exports.checkInventory = checkInventory;
1353
- exports.computeCartTotals = computeCartTotals;
1354
- exports.createMockShopProvider = createMockShopProvider;
1355
- exports.createSupabaseShopProvider = createSupabaseShopProvider;
1356
- exports.getCustomerOrders = getCustomerOrders;
1357
- exports.getShopProvider = getShopProvider;
1358
- exports.getShopTenantId = getShopTenantId;
1359
- exports.resetShopProvider = resetShopProvider;
1360
- exports.setShopProvider = setShopProvider;
1361
- exports.setShopTenantResolver = setShopTenantResolver;
1362
- exports.svgPlaceholder = svgPlaceholder;
1363
- exports.validateDiscount = validateDiscount;
1364
- //# sourceMappingURL=index.cjs.map
1365
- //# sourceMappingURL=index.cjs.map