@easy-cms/plugin-ecommerce 0.0.0-stage → 0.45.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.
@@ -0,0 +1,1937 @@
1
+ // src/shared.ts
2
+ var CURRENCIES = {
3
+ THB: { code: "THB", symbol: "\u0E3F", label: "Thai baht", decimals: 2 },
4
+ USD: { code: "USD", symbol: "$", label: "US dollar", decimals: 2 },
5
+ EUR: { code: "EUR", symbol: "\u20AC", label: "Euro", decimals: 2 },
6
+ GBP: { code: "GBP", symbol: "\xA3", label: "Pound sterling", decimals: 2 },
7
+ JPY: { code: "JPY", symbol: "\xA5", label: "Japanese yen", decimals: 0 }
8
+ };
9
+ var priceField = (code) => `priceIn${code.toUpperCase()}`;
10
+ function formatPrice(amount, currency, locale = "en") {
11
+ const value = amount / 10 ** currency.decimals;
12
+ try {
13
+ return new Intl.NumberFormat(locale, {
14
+ style: "currency",
15
+ currency: currency.code,
16
+ minimumFractionDigits: currency.decimals,
17
+ maximumFractionDigits: currency.decimals
18
+ }).format(value);
19
+ } catch {
20
+ return `${currency.symbol}${value.toFixed(currency.decimals)}`;
21
+ }
22
+ }
23
+ var ORDER_STATUSES = ["pending", "paid", "fulfilled", "cancelled", "refunded"];
24
+ var TRANSACTION_STATUSES = [
25
+ "pending",
26
+ "processing",
27
+ "succeeded",
28
+ "failed",
29
+ "refunded"
30
+ ];
31
+
32
+ // src/collections.ts
33
+ import {
34
+ anyone,
35
+ isLoggedIn,
36
+ ValidationError
37
+ } from "@easy-cms/core";
38
+ var PRODUCTS = "products";
39
+ var VARIANT_TYPES = "variant-types";
40
+ var VARIANT_OPTIONS = "variant-options";
41
+ var VARIANTS = "variants";
42
+ var CARTS = "carts";
43
+ var ADDRESSES = "addresses";
44
+ var ORDERS = "orders";
45
+ var TRANSACTIONS = "transactions";
46
+ var COUNTERS = "shop-counters";
47
+ var SHOP_COLLECTIONS = [
48
+ PRODUCTS,
49
+ VARIANT_TYPES,
50
+ VARIANT_OPTIONS,
51
+ VARIANTS,
52
+ CARTS,
53
+ ADDRESSES,
54
+ ORDERS,
55
+ TRANSACTIONS,
56
+ COUNTERS
57
+ ];
58
+ var price = {
59
+ name: "price",
60
+ base: "number",
61
+ validate: (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? true : "must be a whole amount of the smallest unit, 0 or more (e.g. 12345 for 123.45)",
62
+ admin: {
63
+ component: "ecms-price-field",
64
+ cell: "ecms-price-cell",
65
+ module: "@easy-cms/plugin-ecommerce/admin",
66
+ props: ["currency", "decimals", "symbol"]
67
+ },
68
+ typescript: "number"
69
+ };
70
+ var staff = isLoggedIn;
71
+ var staffOrOwner = ({ user }) => {
72
+ if (!user) return false;
73
+ if (user.member !== true) return true;
74
+ return { customer: { equals: user.id } };
75
+ };
76
+ var nobody = () => false;
77
+ var bySystem = { update: () => false };
78
+ var priceFields = (currencies, extra = {}) => currencies.map(
79
+ (c) => ({
80
+ name: priceField(c.code),
81
+ type: "price",
82
+ currency: c.code,
83
+ decimals: c.decimals,
84
+ symbol: c.symbol,
85
+ label: { en: `Price (${c.code})`, th: `\u0E23\u0E32\u0E04\u0E32 (${c.code})` },
86
+ ...extra
87
+ })
88
+ );
89
+ var stockField = {
90
+ name: "inventory",
91
+ type: "number",
92
+ min: 0,
93
+ label: { en: "In stock (empty: not counted)", th: "\u0E2A\u0E15\u0E47\u0E2D\u0E01 (\u0E27\u0E48\u0E32\u0E07: \u0E44\u0E21\u0E48\u0E19\u0E31\u0E1A)" },
94
+ validate: (value) => value === null || value === void 0 || Number.isInteger(value) ? true : "must be whole"
95
+ };
96
+ function addressFields(countries) {
97
+ return [
98
+ { name: "name", type: "text", required: true, label: { en: "Name", th: "\u0E0A\u0E37\u0E48\u0E2D\u0E1C\u0E39\u0E49\u0E23\u0E31\u0E1A" } },
99
+ { name: "phone", type: "text", label: { en: "Phone", th: "\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C" } },
100
+ { name: "line1", type: "text", required: true, label: { en: "Address", th: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48" } },
101
+ { name: "line2", type: "text", label: { en: "Address (more)", th: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 (\u0E15\u0E48\u0E2D)" } },
102
+ {
103
+ name: "subdistrict",
104
+ type: "text",
105
+ label: { en: "Sub-district", th: "\u0E41\u0E02\u0E27\u0E07 / \u0E15\u0E33\u0E1A\u0E25" }
106
+ },
107
+ { name: "district", type: "text", label: { en: "District", th: "\u0E40\u0E02\u0E15 / \u0E2D\u0E33\u0E40\u0E20\u0E2D" } },
108
+ { name: "province", type: "text", label: { en: "Province", th: "\u0E08\u0E31\u0E07\u0E2B\u0E27\u0E31\u0E14" } },
109
+ { name: "postalCode", type: "text", label: { en: "Postal code", th: "\u0E23\u0E2B\u0E31\u0E2A\u0E44\u0E1B\u0E23\u0E29\u0E13\u0E35\u0E22\u0E4C" } },
110
+ {
111
+ name: "country",
112
+ type: "select",
113
+ options: [...countries],
114
+ required: true,
115
+ ...countries[0] ? { defaultValue: countries[0] } : {},
116
+ label: { en: "Country", th: "\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28" }
117
+ }
118
+ ];
119
+ }
120
+ function productLayout(o) {
121
+ return [
122
+ {
123
+ tab: { en: "Product", th: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25" },
124
+ fields: ["title", "slug", "description", "images"]
125
+ },
126
+ {
127
+ tab: { en: "Price & stock", th: "\u0E23\u0E32\u0E04\u0E32\u0E41\u0E25\u0E30\u0E2A\u0E15\u0E47\u0E2D\u0E01" },
128
+ fields: [
129
+ { row: o.currencies.map((c) => priceField(c.code)) },
130
+ { row: ["sku", ...o.inventory ? ["inventory"] : []] }
131
+ ]
132
+ },
133
+ ...o.variants ? [{ tab: { en: "Options", th: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" }, fields: ["variantTypes"] }] : []
134
+ ];
135
+ }
136
+ function shopCollections(o) {
137
+ const address = o.addressFields ?? addressFields(o.countries);
138
+ const currencyOptions = o.currencies.map((c) => c.code);
139
+ const products = {
140
+ slug: PRODUCTS,
141
+ labels: {
142
+ singular: { en: "Product", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" },
143
+ plural: { en: "Products", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" }
144
+ },
145
+ icon: "shopping-bag",
146
+ useAsTitle: "title",
147
+ drafts: true,
148
+ admin: {
149
+ group: "shop.catalog",
150
+ layout: productLayout(o),
151
+ empty: {
152
+ description: {
153
+ en: "Add the first product of the shop: a name, a price, then publish it.",
154
+ th: "\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E41\u0E23\u0E01\u0E02\u0E2D\u0E07\u0E23\u0E49\u0E32\u0E19: \u0E15\u0E31\u0E49\u0E07\u0E0A\u0E37\u0E48\u0E2D \u0E43\u0E2A\u0E48\u0E23\u0E32\u0E04\u0E32 \u0E41\u0E25\u0E49\u0E27\u0E40\u0E1C\u0E22\u0E41\u0E1E\u0E23\u0E48"
155
+ }
156
+ }
157
+ },
158
+ access: { read: anyone, create: staff, update: staff, delete: staff },
159
+ fields: [
160
+ { name: "title", type: "text", required: true, label: { en: "Name", th: "\u0E0A\u0E37\u0E48\u0E2D\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" } },
161
+ { name: "slug", type: "slug", from: "title", unique: true, label: "Slug" },
162
+ {
163
+ name: "description",
164
+ type: "richText",
165
+ label: { en: "Description", th: "\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14" }
166
+ },
167
+ {
168
+ name: "images",
169
+ type: "upload",
170
+ hasMany: true,
171
+ mimeTypes: ["image/*"],
172
+ label: { en: "Images", th: "\u0E23\u0E39\u0E1B\u0E20\u0E32\u0E1E" }
173
+ },
174
+ ...priceFields(o.currencies),
175
+ { name: "sku", type: "text", index: true, label: "SKU" },
176
+ ...o.inventory ? [stockField] : [],
177
+ ...o.variants ? [
178
+ {
179
+ name: "variantTypes",
180
+ type: "relationship",
181
+ to: VARIANT_TYPES,
182
+ hasMany: true,
183
+ label: {
184
+ en: "Options (e.g. color, size)",
185
+ th: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01 (\u0E40\u0E0A\u0E48\u0E19 \u0E2A\u0E35 \u0E02\u0E19\u0E32\u0E14)"
186
+ }
187
+ }
188
+ ] : [],
189
+ ...o.productFields
190
+ ]
191
+ };
192
+ const variantTypes = {
193
+ slug: VARIANT_TYPES,
194
+ labels: {
195
+ singular: { en: "Option type", th: "\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" },
196
+ plural: { en: "Option types", th: "\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" }
197
+ },
198
+ icon: "sliders-horizontal",
199
+ useAsTitle: "name",
200
+ editIn: "drawer",
201
+ admin: { group: "shop.catalog" },
202
+ access: { read: anyone, create: staff, update: staff, delete: staff },
203
+ fields: [
204
+ {
205
+ name: "name",
206
+ type: "text",
207
+ required: true,
208
+ label: { en: "Name (e.g. Color)", th: "\u0E0A\u0E37\u0E48\u0E2D (\u0E40\u0E0A\u0E48\u0E19 \u0E2A\u0E35)" }
209
+ }
210
+ ]
211
+ };
212
+ const variantOptions = {
213
+ slug: VARIANT_OPTIONS,
214
+ labels: {
215
+ singular: { en: "Option", th: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" },
216
+ plural: { en: "Options", th: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" }
217
+ },
218
+ icon: "tags",
219
+ useAsTitle: "label",
220
+ editIn: "drawer",
221
+ admin: { group: "shop.catalog" },
222
+ access: { read: anyone, create: staff, update: staff, delete: staff },
223
+ fields: [
224
+ {
225
+ name: "type",
226
+ type: "relationship",
227
+ to: VARIANT_TYPES,
228
+ required: true,
229
+ index: true,
230
+ admin: { column: true },
231
+ label: { en: "Type", th: "\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17" }
232
+ },
233
+ {
234
+ name: "label",
235
+ type: "text",
236
+ required: true,
237
+ label: { en: "Label (e.g. Red)", th: "\u0E0A\u0E37\u0E48\u0E2D (\u0E40\u0E0A\u0E48\u0E19 \u0E41\u0E14\u0E07)" }
238
+ }
239
+ ]
240
+ };
241
+ const variants = {
242
+ slug: VARIANTS,
243
+ labels: {
244
+ singular: { en: "Variant", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22" },
245
+ plural: { en: "Variants", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22" }
246
+ },
247
+ icon: "layers",
248
+ useAsTitle: "title",
249
+ admin: { group: "shop.catalog" },
250
+ access: { read: anyone, create: staff, update: staff, delete: staff },
251
+ fields: [
252
+ {
253
+ name: "product",
254
+ type: "relationship",
255
+ to: PRODUCTS,
256
+ required: true,
257
+ index: true,
258
+ admin: { column: true },
259
+ label: { en: "Product", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" }
260
+ },
261
+ {
262
+ name: "options",
263
+ type: "relationship",
264
+ to: VARIANT_OPTIONS,
265
+ hasMany: true,
266
+ required: true,
267
+ label: { en: "Options", th: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01" }
268
+ },
269
+ // "Red / L": set from the options on save.
270
+ {
271
+ name: "title",
272
+ type: "text",
273
+ access: bySystem,
274
+ label: { en: "Name", th: "\u0E0A\u0E37\u0E48\u0E2D" }
275
+ },
276
+ ...priceFields(o.currencies, {
277
+ label: { en: "Price (empty: the product\u2019s)", th: "\u0E23\u0E32\u0E04\u0E32 (\u0E27\u0E48\u0E32\u0E07: \u0E15\u0E32\u0E21\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32)" }
278
+ }).map((f) => ({
279
+ ...f,
280
+ label: {
281
+ en: `Price ${f.currency} (empty: the product\u2019s)`,
282
+ th: `\u0E23\u0E32\u0E04\u0E32 ${f.currency} (\u0E27\u0E48\u0E32\u0E07: \u0E15\u0E32\u0E21\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32)`
283
+ }
284
+ })),
285
+ { name: "sku", type: "text", index: true, label: "SKU" },
286
+ ...o.inventory ? [stockField] : []
287
+ ],
288
+ hooks: { beforeChange: [checkVariant] }
289
+ };
290
+ const carts = {
291
+ slug: CARTS,
292
+ labels: {
293
+ singular: { en: "Cart", th: "\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32" },
294
+ plural: { en: "Carts", th: "\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32" }
295
+ },
296
+ icon: "shopping-cart",
297
+ admin: { group: "shop.sales", list: { sort: "-updatedAt" } },
298
+ // Changed through the shop's endpoints only.
299
+ access: { read: staffOrOwner, create: nobody, update: nobody, delete: staff },
300
+ fields: [
301
+ {
302
+ name: "customer",
303
+ type: "relationship",
304
+ to: "users",
305
+ index: true,
306
+ admin: { column: true },
307
+ label: { en: "Customer", th: "\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32" }
308
+ },
309
+ {
310
+ name: "currency",
311
+ type: "select",
312
+ options: currencyOptions,
313
+ required: true,
314
+ ...currencyOptions[0] ? { defaultValue: currencyOptions[0] } : {},
315
+ label: { en: "Currency", th: "\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19" }
316
+ },
317
+ {
318
+ name: "items",
319
+ type: "array",
320
+ label: { en: "Items", th: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23" },
321
+ fields: [
322
+ {
323
+ name: "product",
324
+ type: "relationship",
325
+ to: PRODUCTS,
326
+ required: true,
327
+ label: { en: "Product", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" }
328
+ },
329
+ ...o.variants ? [
330
+ {
331
+ name: "variant",
332
+ type: "relationship",
333
+ to: VARIANTS,
334
+ label: { en: "Variant", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22" }
335
+ }
336
+ ] : [],
337
+ {
338
+ name: "quantity",
339
+ type: "number",
340
+ min: 1,
341
+ required: true,
342
+ label: { en: "Quantity", th: "\u0E08\u0E33\u0E19\u0E27\u0E19" }
343
+ }
344
+ ]
345
+ },
346
+ {
347
+ name: "purchasedAt",
348
+ type: "date",
349
+ index: true,
350
+ admin: { column: true },
351
+ label: { en: "Purchased", th: "\u0E0B\u0E37\u0E49\u0E2D\u0E41\u0E25\u0E49\u0E27\u0E40\u0E21\u0E37\u0E48\u0E2D" }
352
+ },
353
+ // A guest's cart: its secret, hashed; the browser keeps the secret.
354
+ { name: "secret", type: "text", unique: true, hidden: true }
355
+ ]
356
+ };
357
+ const addresses = {
358
+ slug: ADDRESSES,
359
+ labels: {
360
+ singular: { en: "Address", th: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48" },
361
+ plural: { en: "Addresses", th: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48" }
362
+ },
363
+ icon: "map-pin",
364
+ useAsTitle: "name",
365
+ admin: { group: "shop.customers" },
366
+ access: {
367
+ read: staffOrOwner,
368
+ create: ({ user }) => user !== null,
369
+ update: staffOrOwner,
370
+ delete: staffOrOwner
371
+ },
372
+ fields: [
373
+ {
374
+ name: "customer",
375
+ type: "relationship",
376
+ to: "users",
377
+ required: true,
378
+ index: true,
379
+ admin: { column: true },
380
+ label: { en: "Customer", th: "\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32" }
381
+ },
382
+ ...address
383
+ ],
384
+ hooks: {
385
+ // Customers keep addresses for themselves only.
386
+ beforeValidate: [
387
+ ({ data, user }) => user?.member === true ? { ...data, customer: user.id } : data
388
+ ]
389
+ }
390
+ };
391
+ const money = (name, label) => ({
392
+ name,
393
+ type: "price",
394
+ access: bySystem,
395
+ label
396
+ });
397
+ const orders = {
398
+ slug: ORDERS,
399
+ labels: {
400
+ singular: { en: "Order", th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D" },
401
+ plural: { en: "Orders", th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D" }
402
+ },
403
+ icon: "package",
404
+ useAsTitle: "orderNumber",
405
+ admin: {
406
+ group: "shop.sales",
407
+ list: { sort: "-createdAt" },
408
+ // What to do next, at the top of the side column.
409
+ sidebar: [{ tag: "ecms-order-actions", position: "top" }],
410
+ // Paid orders wait to be sent.
411
+ badge: {
412
+ where: { status: { equals: "paid" } },
413
+ label: { en: "to send", th: "\u0E23\u0E2D\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07" }
414
+ },
415
+ empty: {
416
+ description: {
417
+ en: "Orders appear here once customers check out.",
418
+ th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E08\u0E30\u0E41\u0E2A\u0E14\u0E07\u0E17\u0E35\u0E48\u0E19\u0E35\u0E48\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19"
419
+ }
420
+ }
421
+ },
422
+ // Made at checkout; their status changes with the order's actions (`/shop/orders/:id/…`).
423
+ access: { read: staffOrOwner, create: nobody, update: staff, delete: staff },
424
+ fields: [
425
+ {
426
+ name: "orderNumber",
427
+ type: "text",
428
+ unique: true,
429
+ access: bySystem,
430
+ label: { en: "Order number", th: "\u0E40\u0E25\u0E02\u0E17\u0E35\u0E48\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D" }
431
+ },
432
+ {
433
+ name: "status",
434
+ type: "select",
435
+ options: ORDER_STATUSES.map((value) => ({ value, label: STATUS_LABELS[value] })),
436
+ required: true,
437
+ defaultValue: "pending",
438
+ index: true,
439
+ access: bySystem,
440
+ position: "sidebar",
441
+ admin: { column: true },
442
+ label: { en: "Status", th: "\u0E2A\u0E16\u0E32\u0E19\u0E30" }
443
+ },
444
+ {
445
+ name: "customer",
446
+ type: "relationship",
447
+ to: "users",
448
+ index: true,
449
+ access: bySystem,
450
+ label: { en: "Customer", th: "\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32" }
451
+ },
452
+ {
453
+ name: "email",
454
+ type: "email",
455
+ required: true,
456
+ access: bySystem,
457
+ admin: { column: true },
458
+ label: { en: "Email", th: "\u0E2D\u0E35\u0E40\u0E21\u0E25" }
459
+ },
460
+ {
461
+ name: "currency",
462
+ type: "select",
463
+ options: currencyOptions,
464
+ required: true,
465
+ access: bySystem,
466
+ label: { en: "Currency", th: "\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19" }
467
+ },
468
+ {
469
+ name: "items",
470
+ type: "array",
471
+ access: bySystem,
472
+ label: { en: "Items", th: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23" },
473
+ fields: [
474
+ {
475
+ name: "product",
476
+ type: "relationship",
477
+ to: PRODUCTS,
478
+ label: { en: "Product", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" }
479
+ },
480
+ ...o.variants ? [
481
+ {
482
+ name: "variant",
483
+ type: "relationship",
484
+ to: VARIANTS,
485
+ label: { en: "Variant", th: "\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22" }
486
+ }
487
+ ] : [],
488
+ // As it was when bought.
489
+ {
490
+ name: "title",
491
+ type: "text",
492
+ required: true,
493
+ label: { en: "Item as bought", th: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E15\u0E2D\u0E19\u0E0B\u0E37\u0E49\u0E2D" }
494
+ },
495
+ { name: "sku", type: "text", label: "SKU" },
496
+ money("unitPrice", { en: "Price", th: "\u0E23\u0E32\u0E04\u0E32" }),
497
+ {
498
+ name: "quantity",
499
+ type: "number",
500
+ required: true,
501
+ label: { en: "Quantity", th: "\u0E08\u0E33\u0E19\u0E27\u0E19" }
502
+ },
503
+ money("total", { en: "Total", th: "\u0E23\u0E27\u0E21" })
504
+ ]
505
+ },
506
+ money("subtotal", { en: "Subtotal", th: "\u0E22\u0E2D\u0E14\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32" }),
507
+ {
508
+ name: "adjustments",
509
+ type: "array",
510
+ access: bySystem,
511
+ label: { en: "Shipping, tax, discounts", th: "\u0E04\u0E48\u0E32\u0E2A\u0E48\u0E07 \u0E20\u0E32\u0E29\u0E35 \u0E2A\u0E48\u0E27\u0E19\u0E25\u0E14" },
512
+ fields: [
513
+ { name: "label", type: "text", required: true },
514
+ { name: "amount", type: "number", required: true }
515
+ ]
516
+ },
517
+ money("total", { en: "Total", th: "\u0E22\u0E2D\u0E14\u0E23\u0E27\u0E21" }),
518
+ {
519
+ name: "shippingAddress",
520
+ type: "group",
521
+ access: bySystem,
522
+ label: { en: "Ship to", th: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07" },
523
+ fields: address.map((f) => {
524
+ const {
525
+ required: _required,
526
+ defaultValue: _default,
527
+ ...rest
528
+ } = f;
529
+ return rest;
530
+ })
531
+ },
532
+ {
533
+ name: "payment",
534
+ type: "text",
535
+ access: bySystem,
536
+ label: { en: "Paid with", th: "\u0E0A\u0E33\u0E23\u0E30\u0E14\u0E49\u0E27\u0E22" }
537
+ },
538
+ // The payment method's name (`payment` is its label).
539
+ {
540
+ name: "paymentMethod",
541
+ type: "text",
542
+ access: bySystem,
543
+ label: { en: "Method", th: "\u0E27\u0E34\u0E18\u0E35\u0E0A\u0E33\u0E23\u0E30" }
544
+ },
545
+ // The language of the checkout, for emails about the order.
546
+ {
547
+ name: "locale",
548
+ type: "text",
549
+ access: bySystem,
550
+ label: { en: "Language", th: "\u0E20\u0E32\u0E29\u0E32" }
551
+ },
552
+ // Stock ran out while the customer paid: the money is in, the items may not be.
553
+ {
554
+ name: "stockShort",
555
+ type: "boolean",
556
+ access: bySystem,
557
+ label: { en: "Not enough stock", th: "\u0E2A\u0E15\u0E47\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E1E\u0E2D" }
558
+ },
559
+ {
560
+ name: "paidAt",
561
+ type: "date",
562
+ access: bySystem,
563
+ label: { en: "Paid", th: "\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E21\u0E37\u0E48\u0E2D" }
564
+ },
565
+ {
566
+ name: "note",
567
+ type: "textarea",
568
+ label: { en: "Note (staff only)", th: "\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01 (\u0E40\u0E09\u0E1E\u0E32\u0E30\u0E40\u0E08\u0E49\u0E32\u0E2B\u0E19\u0E49\u0E32\u0E17\u0E35\u0E48)" },
569
+ access: { read: ({ user }) => user !== null && user.member !== true }
570
+ }
571
+ ]
572
+ };
573
+ const transactions = {
574
+ slug: TRANSACTIONS,
575
+ labels: {
576
+ singular: { en: "Payment", th: "\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19" },
577
+ plural: { en: "Payments", th: "\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19" }
578
+ },
579
+ icon: "ticket",
580
+ admin: { group: "shop.sales", list: { sort: "-createdAt" } },
581
+ access: { read: staff, create: nobody, update: nobody, delete: nobody },
582
+ fields: [
583
+ {
584
+ name: "status",
585
+ type: "select",
586
+ options: [...TRANSACTION_STATUSES],
587
+ required: true,
588
+ index: true,
589
+ admin: { column: true },
590
+ label: { en: "Status", th: "\u0E2A\u0E16\u0E32\u0E19\u0E30" }
591
+ },
592
+ {
593
+ name: "method",
594
+ type: "text",
595
+ required: true,
596
+ admin: { column: true },
597
+ label: { en: "Method", th: "\u0E27\u0E34\u0E18\u0E35\u0E0A\u0E33\u0E23\u0E30" }
598
+ },
599
+ money("amount", { en: "Amount", th: "\u0E08\u0E33\u0E19\u0E27\u0E19\u0E40\u0E07\u0E34\u0E19" }),
600
+ {
601
+ name: "currency",
602
+ type: "select",
603
+ options: currencyOptions,
604
+ required: true,
605
+ label: { en: "Currency", th: "\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19" }
606
+ },
607
+ { name: "email", type: "email", label: { en: "Email", th: "\u0E2D\u0E35\u0E40\u0E21\u0E25" } },
608
+ {
609
+ name: "customer",
610
+ type: "relationship",
611
+ to: "users",
612
+ label: { en: "Customer", th: "\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32" }
613
+ },
614
+ { name: "cart", type: "relationship", to: CARTS, label: { en: "Cart", th: "\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32" } },
615
+ {
616
+ name: "order",
617
+ type: "relationship",
618
+ to: ORDERS,
619
+ index: true,
620
+ admin: { column: true },
621
+ label: { en: "Order", th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D" }
622
+ },
623
+ // What the order will be: lines, totals and address, worked out at checkout.
624
+ { name: "checkout", type: "json", label: { en: "Checkout", th: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E15\u0E2D\u0E19\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D" } },
625
+ // The adapter's own, e.g. Stripe's payment intent.
626
+ { name: "data", type: "json", label: { en: "Provider data", th: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1C\u0E39\u0E49\u0E43\u0E2B\u0E49\u0E1A\u0E23\u0E34\u0E01\u0E32\u0E23" } },
627
+ // For finding a transaction by the provider's id (e.g. from a webhook).
628
+ { name: "reference", type: "text", index: true, label: { en: "Reference", th: "\u0E2D\u0E49\u0E32\u0E07\u0E2D\u0E34\u0E07" } },
629
+ { name: "error", type: "text", label: { en: "Error", th: "\u0E02\u0E49\u0E2D\u0E1C\u0E34\u0E14\u0E1E\u0E25\u0E32\u0E14" } }
630
+ ]
631
+ };
632
+ const counters = {
633
+ slug: COUNTERS,
634
+ access: { read: nobody, create: nobody, update: nobody, delete: nobody },
635
+ fields: [
636
+ { name: "key", type: "text", required: true, unique: true },
637
+ { name: "value", type: "number" }
638
+ ]
639
+ };
640
+ return [
641
+ products,
642
+ ...o.variants ? [variantTypes, variantOptions, variants] : [],
643
+ carts,
644
+ addresses,
645
+ orders,
646
+ transactions,
647
+ counters
648
+ ];
649
+ }
650
+ var idOf = (value) => {
651
+ if (value === null || value === void 0) return null;
652
+ if (typeof value === "object") return value.id ?? null;
653
+ return value;
654
+ };
655
+ var checkVariant = async ({ data, cms, originalDoc }) => {
656
+ const fail = (field, message) => new ValidationError(VARIANTS, [{ field, message }]);
657
+ const productId = idOf(data.product);
658
+ if (productId === null) return data;
659
+ const product = await cms.findById(PRODUCTS, productId, { depth: 0, draft: true }).catch(() => null);
660
+ if (!product) throw fail("product", "was not found");
661
+ const types = (Array.isArray(product.variantTypes) ? product.variantTypes : []).map(
662
+ (t) => String(idOf(t))
663
+ );
664
+ const ids = (Array.isArray(data.options) ? data.options : []).map(idOf).filter((v) => v !== null);
665
+ const options = ids.length ? (await cms.find(VARIANT_OPTIONS, { where: { id: { in: ids } }, limit: 0, depth: 0 })).docs : [];
666
+ const seen = /* @__PURE__ */ new Set();
667
+ for (const option of options) {
668
+ const type = String(idOf(option.type));
669
+ if (!types.includes(type))
670
+ throw fail("options", `"${String(option.label)}" is not one of the product\u2019s option types`);
671
+ if (seen.has(type)) throw fail("options", "choose one option of each type");
672
+ seen.add(type);
673
+ }
674
+ if (seen.size !== types.length)
675
+ throw fail("options", "choose one option of each of the product\u2019s types");
676
+ const key = [...ids].map(String).sort().join(",");
677
+ const siblings = await cms.find(VARIANTS, {
678
+ where: { product: { equals: productId } },
679
+ limit: 0,
680
+ depth: 0
681
+ });
682
+ for (const other of siblings.docs) {
683
+ if (originalDoc && String(other.id) === String(originalDoc.id)) continue;
684
+ const theirs = (Array.isArray(other.options) ? other.options : []).map((v) => String(idOf(v)));
685
+ if (theirs.sort().join(",") === key)
686
+ throw fail("options", "the product has a variant with these options");
687
+ }
688
+ const ordered = [...options].sort(
689
+ (a, b) => types.indexOf(String(idOf(a.type))) - types.indexOf(String(idOf(b.type)))
690
+ );
691
+ return { ...data, title: ordered.map((o) => String(o.label)).join(" / ") };
692
+ };
693
+ var STATUS_LABELS = {
694
+ pending: { en: "Awaiting payment", th: "\u0E23\u0E2D\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19" },
695
+ paid: { en: "Paid", th: "\u0E0A\u0E33\u0E23\u0E30\u0E41\u0E25\u0E49\u0E27" },
696
+ fulfilled: { en: "Fulfilled", th: "\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27" },
697
+ cancelled: { en: "Cancelled", th: "\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01" },
698
+ refunded: { en: "Refunded", th: "\u0E04\u0E37\u0E19\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27" }
699
+ };
700
+
701
+ // src/plugin.ts
702
+ import { AsyncLocalStorage } from "async_hooks";
703
+ import {
704
+ definePlugin,
705
+ ForbiddenError,
706
+ UnauthorizedError
707
+ } from "@easy-cms/core";
708
+
709
+ // src/emails.ts
710
+ var esc = (value) => value.replace(
711
+ /[&<>"']/g,
712
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]
713
+ );
714
+ function summary(order, currency, locale) {
715
+ const money = (n) => formatPrice(n, currency, locale === "th" ? "th-TH" : "en");
716
+ const items = (order.items ?? []).map((i) => ({
717
+ label: `${i.title} \xD7 ${i.quantity}`,
718
+ value: money(i.total)
719
+ }));
720
+ const extra = (order.adjustments ?? []).map((a) => ({
721
+ label: a.label,
722
+ value: money(a.amount)
723
+ }));
724
+ const total = { label: locale === "th" ? "\u0E22\u0E2D\u0E14\u0E23\u0E27\u0E21" : "Total", value: money(order.total) };
725
+ const rows = [...items, ...extra, total];
726
+ const text = rows.map((r) => `${r.label}: ${r.value}`).join("\n");
727
+ const html = `<table style="border-collapse:collapse;width:100%;max-width:480px">${rows.map(
728
+ (r, i) => `<tr${i === rows.length - 1 ? ' style="font-weight:600;border-top:1px solid #d0d7de"' : ""}><td style="padding:4px 0">${esc(r.label)}</td><td style="padding:4px 0;text-align:right">${esc(r.value)}</td></tr>`
729
+ ).join("")}</table>`;
730
+ return { text, html };
731
+ }
732
+ function layout(lines, table, after = []) {
733
+ const p = (line) => `<p>${esc(line)}</p>`;
734
+ return `<div style="font-family:system-ui,sans-serif;font-size:15px;line-height:1.5;color:#1f2328">${lines.map(p).join("")}${table}${after.map(p).join("")}</div>`;
735
+ }
736
+ var orderConfirmation = ({ order, locale, currency, instructions }) => {
737
+ const { text, html } = summary(order, currency, locale);
738
+ const th = locale === "th";
739
+ const pending = order.status === "pending";
740
+ const lines = th ? [
741
+ `\u0E02\u0E2D\u0E1A\u0E04\u0E38\u0E13\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D \u0E40\u0E25\u0E02\u0E17\u0E35\u0E48 ${order.orderNumber}`,
742
+ pending ? "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E08\u0E30\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E22\u0E37\u0E19\u0E22\u0E31\u0E19\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E23\u0E32\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27" : "\u0E40\u0E23\u0E32\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27 \u0E41\u0E25\u0E30\u0E08\u0E30\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E43\u0E2B\u0E49\u0E40\u0E23\u0E47\u0E27\u0E17\u0E35\u0E48\u0E2A\u0E38\u0E14"
743
+ ] : [
744
+ `Thank you for your order ${order.orderNumber}.`,
745
+ pending ? "We will confirm it once your payment arrives." : "We received your payment and will send your order soon."
746
+ ];
747
+ const after = pending && instructions ? [instructions] : [];
748
+ return {
749
+ subject: th ? `\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D ${order.orderNumber}` : `Your order ${order.orderNumber}`,
750
+ text: [...lines, "", text, ...after.length ? ["", ...after] : []].join("\n"),
751
+ html: layout(lines, html, after)
752
+ };
753
+ };
754
+ var paymentReceived = ({ order, locale, currency }) => {
755
+ const { text, html } = summary(order, currency, locale);
756
+ const th = locale === "th";
757
+ const lines = th ? [`\u0E40\u0E23\u0E32\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D ${order.orderNumber} \u0E41\u0E25\u0E49\u0E27 \u0E41\u0E25\u0E30\u0E08\u0E30\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E43\u0E2B\u0E49\u0E40\u0E23\u0E47\u0E27\u0E17\u0E35\u0E48\u0E2A\u0E38\u0E14`] : [`We received your payment for order ${order.orderNumber} and will send it soon.`];
758
+ return {
759
+ subject: th ? `\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27: ${order.orderNumber}` : `Payment received: ${order.orderNumber}`,
760
+ text: [...lines, "", text].join("\n"),
761
+ html: layout(lines, html)
762
+ };
763
+ };
764
+ var newOrder = ({ order, locale, currency }) => {
765
+ const { text, html } = summary(order, currency, locale);
766
+ const th = locale === "th";
767
+ const lines = th ? [
768
+ `\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E43\u0E2B\u0E21\u0E48 ${order.orderNumber} \u0E08\u0E32\u0E01 ${order.email}`,
769
+ order.status === "pending" ? "\u0E2A\u0E16\u0E32\u0E19\u0E30: \u0E23\u0E2D\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19" : "\u0E2A\u0E16\u0E32\u0E19\u0E30: \u0E0A\u0E33\u0E23\u0E30\u0E41\u0E25\u0E49\u0E27"
770
+ ] : [
771
+ `New order ${order.orderNumber} from ${order.email}`,
772
+ order.status === "pending" ? "Status: awaiting payment" : "Status: paid"
773
+ ];
774
+ return {
775
+ subject: th ? `\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E43\u0E2B\u0E21\u0E48 ${order.orderNumber}` : `New order ${order.orderNumber}`,
776
+ text: [...lines, "", text].join("\n"),
777
+ html: layout(lines, html)
778
+ };
779
+ };
780
+
781
+ // src/info.ts
782
+ var INFO = {
783
+ name: "@easy-cms/plugin-ecommerce",
784
+ ...true ? { version: "0.45.0" } : {}
785
+ };
786
+
787
+ // src/shop.ts
788
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
789
+ import {
790
+ NotFoundError,
791
+ QueryError,
792
+ ValidationError as ValidationError2
793
+ } from "@easy-cms/core";
794
+ var MAX_QUANTITY = 999;
795
+ var hash = (secret) => createHash("sha256").update(secret).digest("hex");
796
+ var sameSecret = (secret, stored) => {
797
+ if (typeof stored !== "string" || stored.length === 0) return false;
798
+ const a = Buffer.from(hash(secret));
799
+ const b = Buffer.from(stored);
800
+ return a.length === b.length && timingSafeEqual(a, b);
801
+ };
802
+ var idOf2 = (value) => {
803
+ if (value === null || value === void 0) return null;
804
+ if (typeof value === "object") return value.id ?? null;
805
+ return value;
806
+ };
807
+ var same = (a, b) => idOf2(a) !== null && String(idOf2(a)) === String(idOf2(b));
808
+ var invalid = (collection, field, message) => new ValidationError2(collection, [{ field, message }]);
809
+ function labelText(label, locale = "en") {
810
+ if (typeof label === "string") return label;
811
+ return label[locale] ?? label.en ?? Object.values(label)[0] ?? "";
812
+ }
813
+ async function scope(cms, collection, field, who) {
814
+ const values = await cms.uniqueScope(collection, field, who);
815
+ const parts = Object.entries(values).map(
816
+ ([name, value]) => value === null || value === void 0 ? { [name]: { exists: false } } : { [name]: { equals: idOf2(value) } }
817
+ );
818
+ return parts;
819
+ }
820
+ var writeAs = (who) => ({ context: who.context, user: who.user });
821
+ var Carts = class {
822
+ constructor(cms, shop) {
823
+ this.cms = cms;
824
+ this.shop = shop;
825
+ }
826
+ cms;
827
+ shop;
828
+ /** The open cart of a customer, or a guest's by its secret; `null` when there is none. */
829
+ async find(who, ref) {
830
+ const { cms } = this;
831
+ const within = await scope(cms, CARTS, "secret", who);
832
+ if (ref && typeof ref.secret === "string" && ref.secret) {
833
+ const found2 = await cms.find(CARTS, {
834
+ where: { and: [{ id: { equals: ref.id } }, { purchasedAt: { exists: false } }, ...within] },
835
+ limit: 1,
836
+ depth: 0
837
+ });
838
+ const cart = found2.docs[0];
839
+ if (!cart) return null;
840
+ const raw = await cms.db.findById({ collection: CARTS, id: cart.id });
841
+ if (sameSecret(ref.secret, raw?.secret)) return cart;
842
+ if (who.user && same(cart.customer, who.user.id)) return cart;
843
+ return null;
844
+ }
845
+ if (!who.user) return null;
846
+ const found = await cms.find(CARTS, {
847
+ where: {
848
+ and: [{ customer: { equals: who.user.id } }, { purchasedAt: { exists: false } }, ...within]
849
+ },
850
+ sort: "-updatedAt",
851
+ limit: 1,
852
+ depth: 0
853
+ });
854
+ return found.docs[0] ?? null;
855
+ }
856
+ /** The cart to add to: found, or made (a guest's with a new secret). */
857
+ async open(who, ref, currency) {
858
+ const found = await this.find(who, ref);
859
+ if (found) return { cart: found, secret: void 0 };
860
+ if (!who.user && !this.shop.guests) throw invalid(CARTS, "customer", "sign in to shop");
861
+ const secret = who.user ? void 0 : randomBytes(24).toString("base64url");
862
+ const created = await this.cms.create(
863
+ CARTS,
864
+ {
865
+ currency: this.currency(currency),
866
+ items: [],
867
+ ...who.user ? { customer: who.user.id } : {}
868
+ },
869
+ writeAs(who)
870
+ );
871
+ if (secret) await this.setSecret(created.id, hash(secret));
872
+ return { cart: created, secret };
873
+ }
874
+ async setSecret(id, value) {
875
+ const raw = await this.cms.db.findById({ collection: CARTS, id });
876
+ if (!raw) return;
877
+ const { id: _id, ...rest } = raw;
878
+ await this.cms.db.update({ collection: CARTS, id, data: { ...rest, secret: value } });
879
+ }
880
+ currency(code) {
881
+ if (typeof code === "string" && this.shop.currencies.some((c) => c.code === code)) return code;
882
+ return this.shop.defaultCurrency;
883
+ }
884
+ items(cart) {
885
+ return Array.isArray(cart.items) ? cart.items : [];
886
+ }
887
+ async save(cart, patch, who) {
888
+ return await this.cms.update(CARTS, cart.id, patch, writeAs(who));
889
+ }
890
+ /** Adds a product (and variant) to the cart, or more of it. */
891
+ async add(who, ref, input) {
892
+ const quantity = input.quantity === void 0 ? 1 : Number(input.quantity);
893
+ if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_QUANTITY)
894
+ throw invalid(CARTS, "quantity", `must be a whole number from 1 to ${MAX_QUANTITY}`);
895
+ const { product, variant } = await this.item(who, input.product, input.variant);
896
+ const { cart, secret } = await this.open(who, ref, input.currency);
897
+ const currency = this.currencyOf(cart);
898
+ if (unitPrice(product, variant, currency.code) === null)
899
+ throw invalid(CARTS, "product", `has no price in ${currency.code}`);
900
+ const items = this.items(cart).map((i) => ({ ...i }));
901
+ const existing = items.find(
902
+ (i) => same(i.product, product.id) && (variant ? same(i.variant, variant.id) : !idOf2(i.variant))
903
+ );
904
+ const total = (existing ? Number(existing.quantity) : 0) + quantity;
905
+ this.checkStock(product, variant, total);
906
+ if (existing) existing.quantity = Math.min(total, MAX_QUANTITY);
907
+ else
908
+ items.push({
909
+ product: product.id,
910
+ ...variant ? { variant: variant.id } : {},
911
+ quantity
912
+ });
913
+ const saved = await this.save(cart, { items }, who);
914
+ return { cart: await this.view(saved, who), ...secret ? { secret } : {} };
915
+ }
916
+ /** Sets a line's quantity; 0 removes it. */
917
+ async update(who, ref, line, quantity) {
918
+ const cart = await this.require(who, ref);
919
+ const n = Number(quantity);
920
+ if (!Number.isInteger(n) || n < 0 || n > MAX_QUANTITY)
921
+ throw invalid(CARTS, "quantity", `must be a whole number from 0 to ${MAX_QUANTITY}`);
922
+ const items = this.items(cart);
923
+ const target = items.find((i) => i.id === line);
924
+ if (!target) throw new NotFoundError(CARTS, String(line));
925
+ if (n > Number(target.quantity)) {
926
+ const { product, variant } = await this.item(who, target.product, target.variant);
927
+ this.checkStock(product, variant, n);
928
+ }
929
+ const next = n === 0 ? items.filter((i) => i !== target) : items.map((i) => i === target ? { ...i, quantity: n } : i);
930
+ return this.view(await this.save(cart, { items: next }, who), who);
931
+ }
932
+ async remove(who, ref, line) {
933
+ return this.update(who, ref, line, 0);
934
+ }
935
+ async clear(who, ref) {
936
+ const cart = await this.require(who, ref);
937
+ return this.view(await this.save(cart, { items: [] }, who), who);
938
+ }
939
+ async setCurrency(who, ref, code) {
940
+ if (typeof code !== "string" || !this.shop.currencies.some((c) => c.code === code))
941
+ throw invalid(CARTS, "currency", "is not one of the shop\u2019s currencies");
942
+ const { cart } = await this.open(who, ref, code);
943
+ return this.view(await this.save(cart, { currency: code }, who), who);
944
+ }
945
+ /**
946
+ * After signing in: a guest's cart joins the customer's. With no cart of their own, the guest
947
+ * cart becomes theirs; otherwise its lines are added to theirs. The secret stops working.
948
+ */
949
+ async merge(who, ref) {
950
+ const user = who.user;
951
+ if (!user) throw invalid(CARTS, "customer", "sign in first");
952
+ const guest = await this.find({ user: null, context: who.context }, ref);
953
+ const own = await this.find(who);
954
+ if (!guest) return own ? this.view(own, who) : null;
955
+ if (same(guest.id, own?.id)) return this.view(guest, who);
956
+ if (!own) {
957
+ const saved2 = await this.save(guest, { customer: user.id }, who);
958
+ await this.setSecret(guest.id, null);
959
+ return this.view(saved2, who);
960
+ }
961
+ const items = this.items(own).map((i) => ({ ...i }));
962
+ for (const line of this.items(guest)) {
963
+ const match = items.find(
964
+ (i) => same(i.product, line.product) && String(idOf2(i.variant)) === String(idOf2(line.variant))
965
+ );
966
+ if (match)
967
+ match.quantity = Math.min(Number(match.quantity) + Number(line.quantity), MAX_QUANTITY);
968
+ else {
969
+ const { id: _id, ...rest } = line;
970
+ items.push(rest);
971
+ }
972
+ }
973
+ const saved = await this.save(own, { items }, who);
974
+ await this.cms.delete(CARTS, guest.id, writeAs(who));
975
+ return this.view(saved, who);
976
+ }
977
+ async require(who, ref) {
978
+ const cart = await this.find(who, ref);
979
+ if (!cart) throw new NotFoundError(CARTS, String(ref?.id ?? "cart"));
980
+ return cart;
981
+ }
982
+ currencyOf(cart) {
983
+ const code = this.currency(cart.currency);
984
+ return this.shop.currencies.find((c) => c.code === code);
985
+ }
986
+ /** A product (published, readable for this request) and its variant, checked together. */
987
+ async item(who, productId, variantId) {
988
+ const id = idOf2(productId);
989
+ const read = { overrideAccess: false, user: who.user, context: who.context, depth: 0 };
990
+ const product = id === null ? null : (await this.cms.find(PRODUCTS, { where: { id: { equals: id } }, limit: 1, ...read })).docs[0];
991
+ if (!product) throw invalid(CARTS, "product", "is not for sale");
992
+ const types = Array.isArray(product.variantTypes) ? product.variantTypes : [];
993
+ const vid = idOf2(variantId);
994
+ if (!this.shop.variants || types.length === 0) {
995
+ if (vid !== null) throw invalid(CARTS, "variant", "this product has no variants");
996
+ return { product, variant: null };
997
+ }
998
+ if (vid === null) throw invalid(CARTS, "variant", "choose one of the product\u2019s options");
999
+ const variant = (await this.cms.find(VARIANTS, { where: { id: { equals: vid } }, limit: 1, ...read })).docs[0];
1000
+ if (!variant || !same(variant.product, product.id))
1001
+ throw invalid(CARTS, "variant", "is not one of this product\u2019s");
1002
+ return { product, variant };
1003
+ }
1004
+ checkStock(product, variant, quantity) {
1005
+ const left = stockOf(this.shop, product, variant);
1006
+ if (left !== null && quantity > left)
1007
+ throw invalid(CARTS, "quantity", left === 0 ? "out of stock" : `only ${left} left`);
1008
+ }
1009
+ /** The cart as pages see it: lines with prices and stock, totals. */
1010
+ async view(cart, who, shippingAddress) {
1011
+ const currency = this.currencyOf(cart);
1012
+ const items = this.items(cart);
1013
+ const read = { overrideAccess: false, user: who.user, context: who.context };
1014
+ const productIds = [...new Set(items.map((i) => idOf2(i.product)).filter((v) => v !== null))];
1015
+ const variantIds = [...new Set(items.map((i) => idOf2(i.variant)).filter((v) => v !== null))];
1016
+ const products = productIds.length ? (await this.cms.find(PRODUCTS, {
1017
+ where: { id: { in: productIds } },
1018
+ limit: 0,
1019
+ depth: 1,
1020
+ ...read
1021
+ })).docs : [];
1022
+ const variants = variantIds.length && this.shop.variants ? (await this.cms.find(VARIANTS, {
1023
+ where: { id: { in: variantIds } },
1024
+ limit: 0,
1025
+ depth: 0,
1026
+ ...read
1027
+ })).docs : [];
1028
+ const lines = items.map((item) => {
1029
+ const product = products.find((p) => same(p.id, item.product));
1030
+ const variant = variants.find((v) => same(v.id, item.variant)) ?? null;
1031
+ const quantity = Number(item.quantity);
1032
+ const price2 = product ? unitPrice(product, variant, currency.code) : null;
1033
+ const stock = product ? stockOf(this.shop, product, variant) : null;
1034
+ const images = Array.isArray(product?.images) ? product.images : [];
1035
+ const wantsVariant = idOf2(item.variant) !== null;
1036
+ return {
1037
+ id: String(item.id),
1038
+ product: {
1039
+ id: idOf2(item.product),
1040
+ title: String(product?.title ?? ""),
1041
+ slug: typeof product?.slug === "string" ? product.slug : null,
1042
+ image: typeof images[0]?.url === "string" ? images[0].url : null
1043
+ },
1044
+ variant: variant ? { id: variant.id, title: String(variant.title ?? "") } : null,
1045
+ quantity,
1046
+ unitPrice: price2,
1047
+ total: (price2 ?? 0) * quantity,
1048
+ available: product !== void 0 && price2 !== null && (!wantsVariant || variant !== null) && (stock === null || stock >= quantity),
1049
+ stock
1050
+ };
1051
+ });
1052
+ const subtotal = lines.reduce((sum, l) => sum + l.total, 0);
1053
+ const base = {
1054
+ id: cart.id,
1055
+ currency: currency.code,
1056
+ lines,
1057
+ count: lines.reduce((sum, l) => sum + l.quantity, 0),
1058
+ subtotal,
1059
+ adjustments: [],
1060
+ total: subtotal
1061
+ };
1062
+ const adjustments = await this.adjust(base, currency, who, shippingAddress);
1063
+ return { ...base, adjustments, total: subtotal + adjustments.reduce((s, a) => s + a.amount, 0) };
1064
+ }
1065
+ async adjust(cart, currency, who, shippingAddress) {
1066
+ if (!this.shop.totals || cart.lines.length === 0) return [];
1067
+ const result = await this.shop.totals({
1068
+ cart,
1069
+ currency,
1070
+ ...shippingAddress ? { shippingAddress } : {},
1071
+ customer: who.user,
1072
+ context: who.context,
1073
+ cms: this.cms
1074
+ });
1075
+ return result.map((a) => {
1076
+ if (typeof a?.label !== "string" || !Number.isInteger(a.amount))
1077
+ throw new QueryError("totals must return [{ label, amount }] with whole amounts");
1078
+ return { label: a.label, amount: a.amount };
1079
+ });
1080
+ }
1081
+ };
1082
+ function unitPrice(product, variant, code) {
1083
+ const field = priceField(code);
1084
+ const own = variant?.[field];
1085
+ if (typeof own === "number") return own;
1086
+ const base = product[field];
1087
+ return typeof base === "number" ? base : null;
1088
+ }
1089
+ function stockOf(shop, product, variant) {
1090
+ if (!shop.inventory) return null;
1091
+ const value = (variant ?? product).inventory;
1092
+ return typeof value === "number" ? value : null;
1093
+ }
1094
+ var toPayment = (tx) => ({
1095
+ id: tx.id,
1096
+ amount: Number(tx.amount),
1097
+ currency: String(tx.currency),
1098
+ email: String(tx.email ?? ""),
1099
+ status: tx.status,
1100
+ data: tx.data ?? {}
1101
+ });
1102
+ var orderRef = (order) => order ? {
1103
+ id: order.id,
1104
+ orderNumber: String(order.orderNumber),
1105
+ status: order.status
1106
+ } : null;
1107
+ var EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1108
+ function plainContext(context) {
1109
+ const plain = {};
1110
+ for (const [key, value] of Object.entries(context))
1111
+ if (value === null || ["string", "number", "boolean"].includes(typeof value)) plain[key] = value;
1112
+ return plain;
1113
+ }
1114
+ var Orders = class {
1115
+ constructor(cms, shop, carts) {
1116
+ this.cms = cms;
1117
+ this.shop = shop;
1118
+ this.carts = carts;
1119
+ }
1120
+ cms;
1121
+ shop;
1122
+ carts;
1123
+ adapter(name) {
1124
+ const adapter = typeof name === "string" ? this.shop.methods.get(name) : void 0;
1125
+ if (!adapter) throw invalid(TRANSACTIONS, "method", "is not a payment method of the shop");
1126
+ return adapter;
1127
+ }
1128
+ /**
1129
+ * Starts paying for a cart: checks it, works out the totals, keeps them on a new transaction
1130
+ * and asks the payment method to start. Manual methods (bank transfer) make the order now.
1131
+ */
1132
+ async checkout(who, ref, input) {
1133
+ const adapter = this.adapter(input.method);
1134
+ const cart = await this.carts.require(who, ref);
1135
+ const email = (who.user?.email ?? (typeof input.email === "string" ? input.email.trim() : "")).toString().toLowerCase();
1136
+ if (!EMAIL.test(email)) throw invalid(ORDERS, "email", "must be a valid email address");
1137
+ const shippingAddress = await this.address(who, input);
1138
+ const view = await this.carts.view(cart, who, shippingAddress ?? void 0);
1139
+ if (view.lines.length === 0) throw invalid(CARTS, "items", "the cart is empty");
1140
+ const unavailable = view.lines.filter((l) => !l.available);
1141
+ if (unavailable.length > 0)
1142
+ throw new ValidationError2(
1143
+ CARTS,
1144
+ unavailable.map((l) => ({
1145
+ field: `items.${l.id}`,
1146
+ message: `${l.product.title}${l.variant ? ` (${l.variant.title})` : ""} is not available as it is`
1147
+ }))
1148
+ );
1149
+ if (view.total < 0) throw invalid(ORDERS, "total", "can\u2019t be below 0");
1150
+ const read = { overrideAccess: false, user: who.user, context: who.context, depth: 0 };
1151
+ const lines = [];
1152
+ for (const line of view.lines) {
1153
+ const product = await this.cms.findById(PRODUCTS, line.product.id, read);
1154
+ const variant = line.variant ? await this.cms.findById(VARIANTS, line.variant.id, read) : null;
1155
+ lines.push({
1156
+ product: line.product.id,
1157
+ ...line.variant ? { variant: line.variant.id } : {},
1158
+ title: line.variant ? `${line.product.title} (${line.variant.title})` : line.product.title,
1159
+ sku: variant?.sku ?? product.sku ?? null,
1160
+ unitPrice: line.unitPrice,
1161
+ quantity: line.quantity,
1162
+ total: line.total
1163
+ });
1164
+ }
1165
+ const snapshot = {
1166
+ lines,
1167
+ subtotal: view.subtotal,
1168
+ adjustments: [...view.adjustments],
1169
+ total: view.total,
1170
+ shippingAddress,
1171
+ locale: input.locale === "th" ? "th" : "en",
1172
+ context: plainContext(who.context)
1173
+ };
1174
+ const tx = await this.cms.create(
1175
+ TRANSACTIONS,
1176
+ {
1177
+ status: "pending",
1178
+ method: adapter.name,
1179
+ amount: view.total,
1180
+ currency: view.currency,
1181
+ email,
1182
+ ...who.user ? { customer: who.user.id } : {},
1183
+ cart: cart.id,
1184
+ checkout: snapshot
1185
+ },
1186
+ writeAs(who)
1187
+ );
1188
+ let started;
1189
+ try {
1190
+ started = await adapter.initiate({ cms: this.cms, transaction: toPayment(tx) });
1191
+ } catch (error) {
1192
+ await this.setTransaction(tx, { status: "failed", error: error.message });
1193
+ throw error;
1194
+ }
1195
+ const saved = await this.setTransaction(tx, {
1196
+ data: started.data ?? {},
1197
+ ...started.reference ? { reference: started.reference } : {}
1198
+ });
1199
+ const order = adapter.manual ? await this.finalize(saved.id, "pending") : null;
1200
+ const client = {
1201
+ ...adapter.instructions ? { instructions: labelText(adapter.instructions, snapshot.locale) } : {},
1202
+ ...started.client
1203
+ };
1204
+ return { transaction: tx.id, payment: client, order: orderRef(order) };
1205
+ }
1206
+ async address(who, input) {
1207
+ const id = idOf2(input.address);
1208
+ if (id !== null) {
1209
+ if (!who.user) throw invalid(ORDERS, "address", "sign in to use a saved address");
1210
+ const found = await this.cms.findById("addresses", id, { overrideAccess: false, user: who.user, context: who.context }).catch(() => null);
1211
+ if (!found) throw invalid(ORDERS, "address", "is not one of yours");
1212
+ const { id: _id, customer: _c, createdAt: _a, updatedAt: _u, ...rest } = found;
1213
+ return this.checkAddress(rest);
1214
+ }
1215
+ if (input.shippingAddress === void 0 || input.shippingAddress === null) return null;
1216
+ if (typeof input.shippingAddress !== "object" || Array.isArray(input.shippingAddress))
1217
+ throw invalid(ORDERS, "shippingAddress", "must be an object");
1218
+ return this.checkAddress(input.shippingAddress);
1219
+ }
1220
+ checkAddress(address) {
1221
+ const errors = this.shop.addressRequired.filter((f) => typeof address[f] !== "string" || address[f].trim() === "").map((f) => ({ field: `shippingAddress.${f}`, message: "is required" }));
1222
+ const country = address.country;
1223
+ if (country !== void 0 && !this.shop.countries.includes(String(country)))
1224
+ errors.push({
1225
+ field: "shippingAddress.country",
1226
+ message: "is not a country the shop sends to"
1227
+ });
1228
+ if (errors.length > 0) throw new ValidationError2(ORDERS, errors);
1229
+ const clean = {};
1230
+ for (const [key, value] of Object.entries(address))
1231
+ if (typeof value === "string" || value === null) clean[key] = value;
1232
+ return clean;
1233
+ }
1234
+ /**
1235
+ * After the page says the payment went through: asks the payment method, and makes the order
1236
+ * when it did. Safe to call again: the order is made once.
1237
+ */
1238
+ async confirm(id, input) {
1239
+ const tx = await this.transaction(id);
1240
+ if (tx.order)
1241
+ return { status: tx.status, order: orderRef(await this.order(tx.order)) };
1242
+ const adapter = this.adapter(tx.method);
1243
+ if (adapter.manual || !adapter.confirm)
1244
+ return { status: tx.status, order: null };
1245
+ const outcome = await adapter.confirm({ cms: this.cms, transaction: toPayment(tx), input });
1246
+ if (outcome === "succeeded") {
1247
+ const order = await this.finalize(tx.id, "paid");
1248
+ return { status: "succeeded", order: orderRef(order) };
1249
+ }
1250
+ if (outcome === "failed" && tx.status === "pending")
1251
+ await this.cms.update(
1252
+ TRANSACTIONS,
1253
+ tx.id,
1254
+ { status: "failed" },
1255
+ {
1256
+ where: { status: { equals: "pending" } }
1257
+ }
1258
+ );
1259
+ return { status: outcome === "failed" ? "failed" : "processing", order: null };
1260
+ }
1261
+ /** A payment the provider reports as failed (e.g. from its webhook). */
1262
+ async fail(id, error) {
1263
+ await this.cms.update(
1264
+ TRANSACTIONS,
1265
+ id,
1266
+ { status: "failed", error },
1267
+ {
1268
+ where: {
1269
+ and: [{ status: { in: ["pending", "processing"] } }, { order: { exists: false } }]
1270
+ }
1271
+ }
1272
+ );
1273
+ }
1274
+ /** A transaction by the provider's reference (e.g. Stripe's payment intent id). */
1275
+ async byReference(reference) {
1276
+ const found = await this.cms.find(TRANSACTIONS, {
1277
+ where: { reference: { equals: reference } },
1278
+ limit: 1,
1279
+ depth: 0
1280
+ });
1281
+ return found.docs[0] ?? null;
1282
+ }
1283
+ async transaction(id) {
1284
+ const tid = idOf2(id);
1285
+ const tx = tid === null ? null : await this.cms.findById(TRANSACTIONS, tid, { depth: 0 }).catch(() => null);
1286
+ if (!tx) throw new NotFoundError(TRANSACTIONS, String(id));
1287
+ return tx;
1288
+ }
1289
+ async order(id) {
1290
+ const oid = idOf2(id);
1291
+ return oid === null ? null : await this.cms.findById(ORDERS, oid, { depth: 0 }).catch(() => null);
1292
+ }
1293
+ async setTransaction(tx, patch) {
1294
+ return await this.cms.update(TRANSACTIONS, tx.id, patch, { depth: 0 });
1295
+ }
1296
+ /**
1297
+ * Makes the order of a transaction whose payment succeeded (`paid`) or will come later
1298
+ * (`pending`), exactly once however often it is called: the first call claims the
1299
+ * transaction; the others get the same order.
1300
+ */
1301
+ async finalize(id, status) {
1302
+ const tx = await this.transaction(id);
1303
+ if (tx.order) return await this.order(tx.order);
1304
+ const claimed = await this.cms.update(
1305
+ TRANSACTIONS,
1306
+ id,
1307
+ { status: "processing" },
1308
+ {
1309
+ where: { and: [{ status: { in: ["pending", "failed"] } }, { order: { exists: false } }] },
1310
+ depth: 0
1311
+ }
1312
+ );
1313
+ if (!claimed) {
1314
+ for (let i = 0; i < 50; i++) {
1315
+ await new Promise((resolve) => setTimeout(resolve, 100));
1316
+ const again = await this.transaction(id);
1317
+ if (again.order) return await this.order(again.order);
1318
+ }
1319
+ throw new QueryError("The order is still being made; try again in a moment");
1320
+ }
1321
+ try {
1322
+ return await this.makeOrder(claimed, status);
1323
+ } catch (error) {
1324
+ await this.setTransaction(claimed, {
1325
+ status: "pending",
1326
+ error: error.message
1327
+ });
1328
+ throw error;
1329
+ }
1330
+ }
1331
+ async makeOrder(tx, status) {
1332
+ const snapshot = tx.checkout;
1333
+ const context = snapshot.context ?? {};
1334
+ const who = { user: null, context };
1335
+ let short = false;
1336
+ for (const line of snapshot.lines) if (!await this.take(line, -line.quantity)) short = true;
1337
+ const adapter = this.shop.methods.get(String(tx.method));
1338
+ const order = await this.cms.create(
1339
+ ORDERS,
1340
+ {
1341
+ orderNumber: await this.nextNumber(who),
1342
+ status,
1343
+ ...tx.customer ? { customer: idOf2(tx.customer) } : {},
1344
+ email: tx.email,
1345
+ currency: tx.currency,
1346
+ items: snapshot.lines,
1347
+ subtotal: snapshot.subtotal,
1348
+ adjustments: snapshot.adjustments,
1349
+ total: snapshot.total,
1350
+ ...snapshot.shippingAddress ? { shippingAddress: snapshot.shippingAddress } : {},
1351
+ payment: adapter ? labelText(adapter.label, snapshot.locale) : String(tx.method),
1352
+ paymentMethod: String(tx.method),
1353
+ stockShort: short,
1354
+ locale: snapshot.locale,
1355
+ ...status === "paid" ? { paidAt: (/* @__PURE__ */ new Date()).toISOString() } : {}
1356
+ },
1357
+ { context, depth: 0 }
1358
+ );
1359
+ if (tx.cart)
1360
+ await this.cms.update(CARTS, idOf2(tx.cart), { purchasedAt: (/* @__PURE__ */ new Date()).toISOString() }, { context }).catch(() => {
1361
+ });
1362
+ await this.setTransaction(tx, {
1363
+ status: status === "paid" ? "succeeded" : "pending",
1364
+ order: order.id,
1365
+ error: null
1366
+ });
1367
+ await this.shop.onOrder("created", order, this.cms);
1368
+ return order;
1369
+ }
1370
+ /** Takes items from stock (or puts them back): `false` when there weren't enough. */
1371
+ async take(line, by) {
1372
+ if (!this.shop.inventory) return true;
1373
+ const target = line.variant ? { collection: VARIANTS, id: idOf2(line.variant) } : { collection: PRODUCTS, id: idOf2(line.product) };
1374
+ if (target.id === null) return true;
1375
+ const doc = await this.cms.db.findById({ collection: target.collection, id: target.id });
1376
+ if (!doc || typeof doc.inventory !== "number") return true;
1377
+ const result = await this.cms.increment(target.collection, target.id, "inventory", by, {
1378
+ min: 0
1379
+ });
1380
+ return result !== null;
1381
+ }
1382
+ async nextNumber(who) {
1383
+ const within = await scope(this.cms, COUNTERS, "key", who);
1384
+ const where = { and: [{ key: { equals: "orders" } }, ...within] };
1385
+ let counter = (await this.cms.find(COUNTERS, { where, limit: 1, depth: 0 })).docs[0];
1386
+ if (!counter) {
1387
+ try {
1388
+ counter = await this.cms.create(
1389
+ COUNTERS,
1390
+ { key: "orders", value: 0 },
1391
+ { context: who.context }
1392
+ );
1393
+ } catch {
1394
+ counter = (await this.cms.find(COUNTERS, { where, limit: 1, depth: 0 })).docs[0];
1395
+ }
1396
+ }
1397
+ const n = await this.cms.increment(COUNTERS, counter.id, "value", 1);
1398
+ return this.shop.orderNumber(n);
1399
+ }
1400
+ /** The actions on an order in the admin, by staff. */
1401
+ async act(id, action, who) {
1402
+ const oid = idOf2(id);
1403
+ const visible = oid === null ? null : await this.cms.findById(ORDERS, oid, {
1404
+ overrideAccess: false,
1405
+ user: who.user,
1406
+ context: who.context,
1407
+ depth: 0
1408
+ }).catch(() => null);
1409
+ if (!visible) throw new NotFoundError(ORDERS, String(id));
1410
+ const transaction = await this.transactionOf(visible);
1411
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1412
+ const move = async (from, to, extra = {}) => {
1413
+ const moved = await this.cms.update(
1414
+ ORDERS,
1415
+ oid,
1416
+ { status: to, ...extra },
1417
+ { where: { status: { in: from } }, context: who.context, user: who.user, depth: 0 }
1418
+ );
1419
+ if (!moved)
1420
+ throw invalid(ORDERS, "status", `can\u2019t be changed to ${to} from ${String(visible.status)}`);
1421
+ return moved;
1422
+ };
1423
+ switch (action) {
1424
+ case "paid": {
1425
+ const order = await move(["pending"], "paid", { paidAt: now });
1426
+ if (transaction) await this.setTransaction(transaction, { status: "succeeded" });
1427
+ await this.shop.onOrder("paid", order, this.cms);
1428
+ return order;
1429
+ }
1430
+ case "fulfilled": {
1431
+ const order = await move(["paid"], "fulfilled");
1432
+ await this.shop.onOrder("fulfilled", order, this.cms);
1433
+ return order;
1434
+ }
1435
+ case "cancelled": {
1436
+ const order = await move(["pending"], "cancelled");
1437
+ await this.restock(order);
1438
+ if (transaction)
1439
+ await this.setTransaction(transaction, { status: "failed", error: "cancelled" });
1440
+ await this.shop.onOrder("cancelled", order, this.cms);
1441
+ return order;
1442
+ }
1443
+ case "refunded": {
1444
+ const before = visible.status;
1445
+ const order = await move(["paid", "fulfilled"], "refunded");
1446
+ const adapter = transaction ? this.shop.methods.get(String(transaction.method)) : void 0;
1447
+ try {
1448
+ if (transaction && adapter?.refund)
1449
+ await adapter.refund({ cms: this.cms, transaction: toPayment(transaction) });
1450
+ } catch (error) {
1451
+ await this.cms.update(ORDERS, oid, { status: before }, { depth: 0 });
1452
+ throw error;
1453
+ }
1454
+ if (transaction) await this.setTransaction(transaction, { status: "refunded" });
1455
+ await this.restock(order);
1456
+ await this.shop.onOrder("refunded", order, this.cms);
1457
+ return order;
1458
+ }
1459
+ default:
1460
+ throw new NotFoundError(ORDERS, `${String(id)}/${action}`);
1461
+ }
1462
+ }
1463
+ async transactionOf(order) {
1464
+ const found = await this.cms.find(TRANSACTIONS, {
1465
+ where: { order: { equals: order.id } },
1466
+ sort: "-createdAt",
1467
+ limit: 1,
1468
+ depth: 0
1469
+ });
1470
+ return found.docs[0] ?? null;
1471
+ }
1472
+ /** Puts an order's items back in stock, unless they were short when it was made. */
1473
+ async restock(order) {
1474
+ if (order.stockShort === true) return;
1475
+ for (const item of order.items ?? [])
1476
+ await this.take({ product: item.product, variant: item.variant }, Number(item.quantity));
1477
+ }
1478
+ /**
1479
+ * Upkeep: transactions left `processing` by a stopped process go back to `pending`, so the
1480
+ * next confirmation or webhook makes the order.
1481
+ */
1482
+ async release(now) {
1483
+ const stale = new Date(now.getTime() - 10 * 6e4).toISOString();
1484
+ const stuck = await this.cms.find(TRANSACTIONS, {
1485
+ where: {
1486
+ and: [
1487
+ { status: { equals: "processing" } },
1488
+ { order: { exists: false } },
1489
+ { updatedAt: { lt: stale } }
1490
+ ]
1491
+ },
1492
+ limit: 100,
1493
+ depth: 0
1494
+ });
1495
+ for (const tx of stuck.docs)
1496
+ await this.cms.update(
1497
+ TRANSACTIONS,
1498
+ tx.id,
1499
+ { status: "pending" },
1500
+ {
1501
+ where: { status: { equals: "processing" } }
1502
+ }
1503
+ );
1504
+ return stuck.docs.length;
1505
+ }
1506
+ };
1507
+
1508
+ // src/plugin.ts
1509
+ var ORDER_EVENTS = [
1510
+ "order.created",
1511
+ "order.paid",
1512
+ "order.fulfilled",
1513
+ "order.cancelled",
1514
+ "order.refunded"
1515
+ ];
1516
+ var ORDER_ACTIONS = /* @__PURE__ */ new Set(["paid", "fulfilled", "cancelled", "refunded"]);
1517
+ var running = new AsyncLocalStorage();
1518
+ function current() {
1519
+ const store = running.getStore();
1520
+ if (!store) throw new Error("Call this from a payment adapter\u2019s endpoint");
1521
+ return store.orders;
1522
+ }
1523
+ async function paymentSucceeded(reference) {
1524
+ const orders = current();
1525
+ const tx = await orders.byReference(reference);
1526
+ if (!tx) return null;
1527
+ const order = await orders.finalize(tx.id, "paid");
1528
+ return { order: order.id };
1529
+ }
1530
+ async function paymentFailed(reference, error) {
1531
+ const orders = current();
1532
+ const tx = await orders.byReference(reference);
1533
+ if (tx) await orders.fail(tx.id, error);
1534
+ }
1535
+ var signedIn = (req) => {
1536
+ if (!req.user) throw new UnauthorizedError();
1537
+ return req.user;
1538
+ };
1539
+ var staffOnly = (req) => {
1540
+ const user = signedIn(req);
1541
+ if (user.member === true) throw new ForbiddenError();
1542
+ return user;
1543
+ };
1544
+ function cartRef(body) {
1545
+ const cart = body.cart;
1546
+ if (!cart || typeof cart !== "object") return null;
1547
+ const id = cart.id;
1548
+ if (typeof id !== "string" && typeof id !== "number" || typeof cart.secret !== "string")
1549
+ return null;
1550
+ return { id, secret: cart.secret };
1551
+ }
1552
+ function ecommercePlugin(options) {
1553
+ const currencies = (options.currencies?.supported ?? ["THB"]).map((c) => {
1554
+ if (typeof c !== "string") return c;
1555
+ const known = CURRENCIES[c.toUpperCase()];
1556
+ if (!known)
1557
+ throw new Error(
1558
+ `ecommercePlugin: unknown currency "${c}": give { code, symbol, label, decimals }`
1559
+ );
1560
+ return known;
1561
+ });
1562
+ if (currencies.length === 0) throw new Error("ecommercePlugin: give at least one currency");
1563
+ const defaultCurrency = options.currencies?.default ?? currencies[0].code;
1564
+ if (!currencies.some((c) => c.code === defaultCurrency))
1565
+ throw new Error(`ecommercePlugin: the default currency "${defaultCurrency}" is not supported`);
1566
+ const methods = /* @__PURE__ */ new Map();
1567
+ for (const method of options.payments?.methods ?? []) {
1568
+ if (!/^[a-z][a-z0-9-]*$/.test(method.name))
1569
+ throw new Error(
1570
+ `ecommercePlugin: payment method "${method.name}": use lowercase letters, digits and -`
1571
+ );
1572
+ if (methods.has(method.name))
1573
+ throw new Error(`ecommercePlugin: two payment methods are named "${method.name}"`);
1574
+ methods.set(method.name, method);
1575
+ }
1576
+ const countries = options.addresses?.supportedCountries ?? ["TH"];
1577
+ const role = options.customers?.role ?? "customer";
1578
+ const variants = options.products?.variants !== false;
1579
+ const inventory = options.inventory !== false;
1580
+ const group = options.group ?? { en: "Shop", th: "\u0E23\u0E49\u0E32\u0E19\u0E04\u0E49\u0E32" };
1581
+ const emails = options.emails ?? {};
1582
+ const collectionOptions = {
1583
+ currencies,
1584
+ variants,
1585
+ inventory,
1586
+ countries,
1587
+ addressFields: options.addresses?.fields,
1588
+ productFields: options.products?.fields ?? []
1589
+ };
1590
+ const collections = shopCollections(collectionOptions).map((c) => {
1591
+ const override = options.overrides?.[c.slug];
1592
+ return override ? override(c) : c;
1593
+ });
1594
+ const addressCollection = collections.find((c) => c.slug === "addresses");
1595
+ const addressRequired = (addressCollection?.fields ?? []).filter((f) => f.required === true && f.name !== "customer").map((f) => f.name);
1596
+ const sendOrderEmail = async (cms, write, to, order) => {
1597
+ if (!write || !cms.config.email) return;
1598
+ const currency = currencies.find((c) => c.code === order.currency) ?? currencies[0];
1599
+ const locale = order.locale === "th" ? "th" : "en";
1600
+ const adapter = methods.get(String(order.paymentMethod));
1601
+ const instructions = adapter?.instructions ? labelText(adapter.instructions, locale) : null;
1602
+ const content = await write({ order, locale, currency, instructions, cms });
1603
+ await cms.sendEmail({ to: typeof to === "string" ? to : [...to], ...content });
1604
+ };
1605
+ const shop = {
1606
+ currencies,
1607
+ defaultCurrency,
1608
+ variants,
1609
+ inventory,
1610
+ guests: options.carts?.allowGuests !== false,
1611
+ countries,
1612
+ methods,
1613
+ totals: options.totals,
1614
+ orderNumber: options.orders?.number ?? ((n) => String(1e3 + n)),
1615
+ addressRequired,
1616
+ onOrder: async (event, order, cms) => {
1617
+ const about = { collection: ORDERS, id: order.id };
1618
+ cms.emit(`order.${event}`, order, about);
1619
+ if (event === "created" && order.status === "paid") cms.emit("order.paid", order, about);
1620
+ try {
1621
+ if (event === "created") {
1622
+ await sendOrderEmail(
1623
+ cms,
1624
+ emails.orderConfirmation ?? orderConfirmation,
1625
+ order.email,
1626
+ order
1627
+ );
1628
+ if (emails.notify)
1629
+ await sendOrderEmail(cms, emails.newOrder ?? newOrder, emails.notify, order);
1630
+ }
1631
+ if (event === "paid")
1632
+ await sendOrderEmail(cms, emails.paymentReceived ?? paymentReceived, order.email, order);
1633
+ } catch (error) {
1634
+ cms.logger.error(`Shop: email for order ${order.orderNumber}: ${error.message}`);
1635
+ }
1636
+ }
1637
+ };
1638
+ const runtimes = /* @__PURE__ */ new WeakMap();
1639
+ const runtime = (cms) => {
1640
+ let found = runtimes.get(cms);
1641
+ if (!found) {
1642
+ const carts = new Carts(cms, shop);
1643
+ found = { carts, orders: new Orders(cms, shop, carts) };
1644
+ runtimes.set(cms, found);
1645
+ }
1646
+ return found;
1647
+ };
1648
+ const who = (req) => ({ user: req.user, context: req.context });
1649
+ const settings = () => ({
1650
+ currencies,
1651
+ defaultCurrency,
1652
+ paymentMethods: [...methods.values()].map((m) => ({ name: m.name, label: labelText(m.label) })),
1653
+ guests: shop.guests,
1654
+ countries
1655
+ });
1656
+ const endpoints = [
1657
+ { path: "/shop/config", method: "get", handler: () => settings() },
1658
+ {
1659
+ path: "/shop/cart",
1660
+ method: "post",
1661
+ handler: async (req) => {
1662
+ const body = await req.json();
1663
+ const { carts } = runtime(req.cms);
1664
+ const cart = await carts.find(who(req), cartRef(body));
1665
+ return { cart: cart ? await carts.view(cart, who(req)) : null };
1666
+ }
1667
+ },
1668
+ {
1669
+ path: "/shop/cart/add",
1670
+ method: "post",
1671
+ handler: async (req) => {
1672
+ const body = await req.json();
1673
+ return runtime(req.cms).carts.add(who(req), cartRef(body), {
1674
+ product: body.product,
1675
+ variant: body.variant,
1676
+ quantity: body.quantity,
1677
+ currency: body.currency
1678
+ });
1679
+ }
1680
+ },
1681
+ {
1682
+ path: "/shop/cart/update",
1683
+ method: "post",
1684
+ handler: async (req) => {
1685
+ const body = await req.json();
1686
+ const cart = await runtime(req.cms).carts.update(
1687
+ who(req),
1688
+ cartRef(body),
1689
+ body.line,
1690
+ body.quantity
1691
+ );
1692
+ return { cart };
1693
+ }
1694
+ },
1695
+ {
1696
+ path: "/shop/cart/remove",
1697
+ method: "post",
1698
+ handler: async (req) => {
1699
+ const body = await req.json();
1700
+ return { cart: await runtime(req.cms).carts.remove(who(req), cartRef(body), body.line) };
1701
+ }
1702
+ },
1703
+ {
1704
+ path: "/shop/cart/clear",
1705
+ method: "post",
1706
+ handler: async (req) => {
1707
+ const body = await req.json();
1708
+ return { cart: await runtime(req.cms).carts.clear(who(req), cartRef(body)) };
1709
+ }
1710
+ },
1711
+ {
1712
+ path: "/shop/cart/currency",
1713
+ method: "post",
1714
+ handler: async (req) => {
1715
+ const body = await req.json();
1716
+ return {
1717
+ cart: await runtime(req.cms).carts.setCurrency(who(req), cartRef(body), body.currency)
1718
+ };
1719
+ }
1720
+ },
1721
+ {
1722
+ path: "/shop/cart/merge",
1723
+ method: "post",
1724
+ handler: async (req) => {
1725
+ signedIn(req);
1726
+ const body = await req.json();
1727
+ const ref = cartRef(body);
1728
+ const { carts } = runtime(req.cms);
1729
+ if (!ref) {
1730
+ const own = await carts.find(who(req));
1731
+ return { cart: own ? await carts.view(own, who(req)) : null };
1732
+ }
1733
+ return { cart: await carts.merge(who(req), ref) };
1734
+ }
1735
+ },
1736
+ {
1737
+ path: "/shop/checkout",
1738
+ method: "post",
1739
+ handler: async (req) => {
1740
+ const body = await req.json();
1741
+ return runtime(req.cms).orders.checkout(who(req), cartRef(body), {
1742
+ method: body.method,
1743
+ email: body.email,
1744
+ shippingAddress: body.shippingAddress,
1745
+ address: body.address,
1746
+ locale: body.locale
1747
+ });
1748
+ }
1749
+ },
1750
+ {
1751
+ path: "/shop/confirm",
1752
+ method: "post",
1753
+ handler: async (req) => {
1754
+ const body = await req.json();
1755
+ const { transaction, ...input } = body;
1756
+ return runtime(req.cms).orders.confirm(transaction, input);
1757
+ }
1758
+ },
1759
+ {
1760
+ path: "/shop/orders/:id/:action",
1761
+ method: "post",
1762
+ handler: async (req) => {
1763
+ staffOnly(req);
1764
+ const action = req.params.action;
1765
+ if (!ORDER_ACTIONS.has(action)) throw new ForbiddenError();
1766
+ const order = await runtime(req.cms).orders.act(req.params.id, action, who(req));
1767
+ return { order };
1768
+ }
1769
+ },
1770
+ {
1771
+ path: "/shop/overview",
1772
+ method: "get",
1773
+ handler: async (req) => {
1774
+ staffOnly(req);
1775
+ return overview(req);
1776
+ }
1777
+ },
1778
+ ...[...methods.values()].flatMap(
1779
+ (method) => (method.endpoints ?? []).map(
1780
+ (endpoint) => ({
1781
+ ...endpoint,
1782
+ path: `/shop/payments/${method.name}${endpoint.path.startsWith("/") ? "" : "/"}${endpoint.path}`,
1783
+ handler: (req) => {
1784
+ const { orders } = runtime(req.cms);
1785
+ return running.run({ shop, orders }, () => endpoint.handler(req));
1786
+ }
1787
+ })
1788
+ )
1789
+ )
1790
+ ];
1791
+ async function overview(req) {
1792
+ const read = { overrideAccess: false, user: req.user, context: req.context, depth: 0 };
1793
+ const now = /* @__PURE__ */ new Date();
1794
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
1795
+ const month = new Date(now.getTime() - 30 * 864e5).toISOString();
1796
+ const sold = { status: { in: ["paid", "fulfilled"] } };
1797
+ const recent = await req.cms.find(ORDERS, {
1798
+ ...read,
1799
+ where: { and: [sold, { paidAt: { gte: month } }] },
1800
+ limit: 0
1801
+ });
1802
+ const sums = (since) => {
1803
+ const totals = {};
1804
+ for (const order of recent.docs) {
1805
+ if (String(order.paidAt) < since) continue;
1806
+ const code = String(order.currency);
1807
+ const entry = totals[code] ?? { total: 0, orders: 0 };
1808
+ entry.total += Number(order.total);
1809
+ entry.orders++;
1810
+ totals[code] = entry;
1811
+ }
1812
+ return totals;
1813
+ };
1814
+ const count = (status) => req.cms.count(ORDERS, { ...read, where: { status: { equals: status } } });
1815
+ return {
1816
+ today: sums(today),
1817
+ month: sums(month),
1818
+ pending: await count("pending"),
1819
+ toFulfil: await count("paid"),
1820
+ currencies
1821
+ };
1822
+ }
1823
+ return definePlugin((config) => {
1824
+ const auth = config.auth ?? {};
1825
+ const roles = auth.roles ?? ["admin", "editor"];
1826
+ const members = auth.members;
1827
+ const signup = options.customers?.signup ?? true;
1828
+ const pages = members?.pages ?? options.customers?.pages;
1829
+ const memberSignup = members?.signup ?? (signup === false ? void 0 : { role, ...signup === true ? {} : signup });
1830
+ return {
1831
+ ...config,
1832
+ collections: [...config.collections ?? [], ...collections],
1833
+ endpoints: [...config.endpoints ?? [], ...endpoints],
1834
+ fieldTypes: [...config.fieldTypes ?? [], price],
1835
+ events: [.../* @__PURE__ */ new Set([...config.events ?? [], ...ORDER_EVENTS])],
1836
+ jobs: [
1837
+ ...config.jobs ?? [],
1838
+ {
1839
+ name: "shop:payments",
1840
+ every: 300,
1841
+ run: ({ cms, now }) => runtime(cms).orders.release(now)
1842
+ },
1843
+ {
1844
+ name: "shop:carts",
1845
+ every: 86400,
1846
+ run: async ({ cms, now }) => {
1847
+ const before = new Date(
1848
+ now.getTime() - (options.carts?.guestCartDays ?? 30) * 864e5
1849
+ ).toISOString();
1850
+ const old = await cms.find(CARTS, {
1851
+ where: {
1852
+ and: [
1853
+ { customer: { exists: false } },
1854
+ { purchasedAt: { exists: false } },
1855
+ { updatedAt: { lt: before } }
1856
+ ]
1857
+ },
1858
+ limit: 500,
1859
+ depth: 0
1860
+ });
1861
+ for (const cart of old.docs) await cms.delete(CARTS, cart.id);
1862
+ }
1863
+ }
1864
+ ],
1865
+ auth: {
1866
+ ...auth,
1867
+ roles: roles.includes(role) ? roles : [...roles, role],
1868
+ members: {
1869
+ ...members,
1870
+ roles: [.../* @__PURE__ */ new Set([...members?.roles ?? [], role])],
1871
+ ...memberSignup ? { signup: memberSignup } : {},
1872
+ ...pages ? { pages } : {}
1873
+ }
1874
+ },
1875
+ admin: {
1876
+ ...config.admin,
1877
+ modules: [...config.admin?.modules ?? [], "@easy-cms/plugin-ecommerce/admin"],
1878
+ nav: [
1879
+ ...config.admin?.nav ?? [],
1880
+ {
1881
+ id: "shop",
1882
+ label: group,
1883
+ icon: "store",
1884
+ order: 100,
1885
+ children: [
1886
+ { id: "catalog", label: { en: "Catalog", th: "\u0E41\u0E04\u0E15\u0E15\u0E32\u0E25\u0E47\u0E2D\u0E01" } },
1887
+ { id: "sales", label: { en: "Sales", th: "\u0E01\u0E32\u0E23\u0E02\u0E32\u0E22" } },
1888
+ { id: "customers", label: { en: "Customers", th: "\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32" } }
1889
+ ]
1890
+ }
1891
+ ],
1892
+ commands: [
1893
+ ...config.admin?.commands ?? [],
1894
+ {
1895
+ label: { en: "Orders to send", th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E17\u0E35\u0E48\u0E23\u0E2D\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07" },
1896
+ to: "/collections/orders?f_status=paid",
1897
+ icon: "package",
1898
+ keywords: ["ship", "\u0E2A\u0E48\u0E07\u0E02\u0E2D\u0E07"]
1899
+ },
1900
+ {
1901
+ label: { en: "Orders awaiting payment", th: "\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E17\u0E35\u0E48\u0E23\u0E2D\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19" },
1902
+ to: "/collections/orders?f_status=pending",
1903
+ icon: "package"
1904
+ }
1905
+ ],
1906
+ dashboard: [
1907
+ ...config.admin?.dashboard ?? [],
1908
+ {
1909
+ component: {
1910
+ tag: "ecms-shop-overview",
1911
+ props: { adminPath: config.admin?.path ?? "/admin" }
1912
+ },
1913
+ width: "full",
1914
+ label: { en: "Shop", th: "\u0E23\u0E49\u0E32\u0E19\u0E04\u0E49\u0E32" },
1915
+ access: ({ user }) => user.member !== true
1916
+ }
1917
+ ]
1918
+ }
1919
+ };
1920
+ }, INFO);
1921
+ }
1922
+
1923
+ export {
1924
+ CURRENCIES,
1925
+ priceField,
1926
+ formatPrice,
1927
+ ORDER_STATUSES,
1928
+ TRANSACTION_STATUSES,
1929
+ SHOP_COLLECTIONS,
1930
+ price,
1931
+ addressFields,
1932
+ STATUS_LABELS,
1933
+ ORDER_EVENTS,
1934
+ paymentSucceeded,
1935
+ paymentFailed,
1936
+ ecommercePlugin
1937
+ };