@nymbalhq/platform 1.3.0 → 1.4.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/{chunk-2PLYK5RU.js → chunk-GMV3B3SC.js} +3369 -606
- package/dist/chunk-GMV3B3SC.js.map +1 -0
- package/dist/{chunk-QN56IB4G.js → chunk-SNNK2OX3.js} +119 -5
- package/dist/chunk-SNNK2OX3.js.map +1 -0
- package/dist/db/schema/index.d.ts +1766 -404
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +224 -10
- package/dist/index.js +659 -2172
- package/dist/index.js.map +1 -1
- package/dist/register-N2XGSFUF.js +8 -0
- package/migrations/postgres/0013_order_access_keys.sql +11 -0
- package/migrations/postgres/0014_alert_subscriptions.sql +22 -0
- package/migrations/postgres/0015_events_retry_at.sql +1 -0
- package/migrations/postgres/meta/0013_snapshot.json +2000 -0
- package/migrations/postgres/meta/0014_snapshot.json +2185 -0
- package/migrations/postgres/meta/0015_snapshot.json +2191 -0
- package/migrations/postgres/meta/_journal.json +21 -0
- package/migrations/sqlite/0013_order_access_keys.sql +11 -0
- package/migrations/sqlite/0014_alert_subscriptions.sql +22 -0
- package/migrations/sqlite/0015_events_retry_at.sql +1 -0
- package/migrations/sqlite/meta/0013_snapshot.json +1788 -0
- package/migrations/sqlite/meta/0014_snapshot.json +1931 -0
- package/migrations/sqlite/meta/0015_snapshot.json +1938 -0
- package/migrations/sqlite/meta/_journal.json +21 -0
- package/package.json +19 -19
- package/dist/chunk-2PLYK5RU.js.map +0 -1
- package/dist/chunk-QN56IB4G.js.map +0 -1
- package/dist/register-UUQ64HZP.js +0 -8
- /package/dist/{register-UUQ64HZP.js.map → register-N2XGSFUF.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
+
CATEGORIES,
|
|
2
3
|
COMMERCE_SLOTS,
|
|
3
4
|
CSRF_COOKIE,
|
|
4
5
|
CSRF_HEADER,
|
|
6
|
+
CUSTOMER_PROFILES,
|
|
7
|
+
KEY_OF,
|
|
8
|
+
ORDERS,
|
|
9
|
+
ORDERS_BY_CUSTOMER,
|
|
10
|
+
PRODUCTS,
|
|
11
|
+
PRODUCTS_BY_CATEGORY,
|
|
5
12
|
PROVIDER_PACKAGES,
|
|
6
13
|
PROVIDER_REFUND_REASON,
|
|
7
14
|
SECRETS_KEY_ENV,
|
|
@@ -13,11 +20,24 @@ import {
|
|
|
13
20
|
auditEntriesInOrder,
|
|
14
21
|
auditedCommand,
|
|
15
22
|
buildAdapters,
|
|
23
|
+
buildCategoryDoc,
|
|
24
|
+
buildCustomerProfile,
|
|
25
|
+
buildOrderDoc,
|
|
26
|
+
buildProductDoc,
|
|
27
|
+
buildSearchDoc,
|
|
16
28
|
buildSecurityHeaders,
|
|
29
|
+
buildServices,
|
|
17
30
|
checkInjectedAdapters,
|
|
18
31
|
checkInjectedSlot,
|
|
32
|
+
createAlertService,
|
|
19
33
|
createAuditEntryRepository,
|
|
34
|
+
createAuthService,
|
|
35
|
+
createCartService,
|
|
36
|
+
createCategoryService,
|
|
37
|
+
createCheckoutService,
|
|
20
38
|
createCommandStore,
|
|
39
|
+
createCustomerService,
|
|
40
|
+
createInventoryService,
|
|
21
41
|
createMiddlewareSecurityAdapter,
|
|
22
42
|
createNativeAnalyticsAdapter,
|
|
23
43
|
createNativeEmailAdapter,
|
|
@@ -26,19 +46,23 @@ import {
|
|
|
26
46
|
createNativeShippingAdapter,
|
|
27
47
|
createNativeStubPaymentsAdapter,
|
|
28
48
|
createNativeTaxAdapter,
|
|
49
|
+
createOrderService,
|
|
50
|
+
createProductService,
|
|
51
|
+
createRecentlyViewedService,
|
|
29
52
|
createRefundService,
|
|
53
|
+
createSearchService,
|
|
30
54
|
createSettingsRepository,
|
|
31
55
|
currentActor,
|
|
32
56
|
currentCorrelationId,
|
|
33
57
|
declaredSettings,
|
|
34
58
|
decrypt,
|
|
59
|
+
emailDelivers,
|
|
35
60
|
encodeSearchCursor,
|
|
36
61
|
encrypt,
|
|
37
62
|
fillFromSettings,
|
|
38
63
|
findAppliedByKey,
|
|
39
64
|
formatMoney,
|
|
40
65
|
importProviderPackage,
|
|
41
|
-
inOrderScope,
|
|
42
66
|
installLine,
|
|
43
67
|
isMissingSettingsTable,
|
|
44
68
|
isValidCorrelationId,
|
|
@@ -48,20 +72,27 @@ import {
|
|
|
48
72
|
listStoredSettings,
|
|
49
73
|
loadBootSettings,
|
|
50
74
|
loadProviderAdapter,
|
|
75
|
+
mintOrderKey,
|
|
51
76
|
nativeIndexDocuments,
|
|
77
|
+
newAlertToken,
|
|
52
78
|
newCorrelationId,
|
|
53
|
-
noopInitialize,
|
|
54
|
-
okHealth,
|
|
55
79
|
orderPayment,
|
|
80
|
+
orderWrites,
|
|
56
81
|
outsideActor,
|
|
57
82
|
outsideCommand,
|
|
58
83
|
outsideCorrelation,
|
|
84
|
+
parseDurationToMs,
|
|
59
85
|
postgresDb,
|
|
86
|
+
productByCategoryKey,
|
|
87
|
+
productWrites,
|
|
60
88
|
rawClients,
|
|
61
89
|
readSecretsKey,
|
|
90
|
+
recentlyViewed,
|
|
62
91
|
refreshRefunded,
|
|
63
92
|
registerAdminStaticRoute,
|
|
93
|
+
registerAlertRoutes,
|
|
64
94
|
registerAllRoutes,
|
|
95
|
+
registerRecentlyViewedProjection,
|
|
65
96
|
resolvePaymentsAdapter,
|
|
66
97
|
resolveSecurityAdapter,
|
|
67
98
|
routeSchemas,
|
|
@@ -75,9 +106,11 @@ import {
|
|
|
75
106
|
slotBuilders,
|
|
76
107
|
sqliteDb,
|
|
77
108
|
sqliteFile,
|
|
78
|
-
|
|
79
|
-
} from "./chunk-
|
|
109
|
+
subscribeDerived
|
|
110
|
+
} from "./chunk-GMV3B3SC.js";
|
|
80
111
|
import {
|
|
112
|
+
alertSubscriptions,
|
|
113
|
+
alertSubscriptions2,
|
|
81
114
|
carts,
|
|
82
115
|
carts2,
|
|
83
116
|
categories,
|
|
@@ -88,6 +121,8 @@ import {
|
|
|
88
121
|
events2,
|
|
89
122
|
inventoryReservations,
|
|
90
123
|
inventoryReservations2,
|
|
124
|
+
orderAccessKeys,
|
|
125
|
+
orderAccessKeys2,
|
|
91
126
|
orderHistory,
|
|
92
127
|
orderHistory2,
|
|
93
128
|
orderRefunds,
|
|
@@ -112,7 +147,7 @@ import {
|
|
|
112
147
|
stockAdjustments2,
|
|
113
148
|
variants,
|
|
114
149
|
variants2
|
|
115
|
-
} from "./chunk-
|
|
150
|
+
} from "./chunk-SNNK2OX3.js";
|
|
116
151
|
|
|
117
152
|
// src/platform.ts
|
|
118
153
|
import { join as join2 } from "path";
|
|
@@ -243,7 +278,7 @@ var InMemoryDocumentStore = class {
|
|
|
243
278
|
|
|
244
279
|
// src/event-bus/in-process.ts
|
|
245
280
|
import { v7 as uuidv7 } from "uuid";
|
|
246
|
-
import { ValidationError } from "@nymbalhq/types";
|
|
281
|
+
import { handlerFailedError, ValidationError } from "@nymbalhq/types";
|
|
247
282
|
var InProcessEventBus = class {
|
|
248
283
|
#registrations = /* @__PURE__ */ new Map();
|
|
249
284
|
#logger;
|
|
@@ -258,35 +293,44 @@ var InProcessEventBus = class {
|
|
|
258
293
|
return { status: "healthy" };
|
|
259
294
|
}
|
|
260
295
|
async publish(event) {
|
|
261
|
-
await this.#deliver(event, () => true);
|
|
296
|
+
const failed = await this.#deliver(event, () => true);
|
|
297
|
+
if (failed.length > 0) throw handlerFailedError(event, failed);
|
|
262
298
|
}
|
|
263
299
|
async publishBatch(events3) {
|
|
300
|
+
let first;
|
|
264
301
|
for (const event of events3) {
|
|
265
|
-
await this
|
|
302
|
+
const failed = await this.#deliver(event, () => true);
|
|
303
|
+
if (failed.length > 0) first ??= handlerFailedError(event, failed);
|
|
266
304
|
}
|
|
305
|
+
if (first !== void 0) throw first;
|
|
267
306
|
}
|
|
268
307
|
async replay(events3) {
|
|
269
308
|
for (const event of events3) {
|
|
270
309
|
await this.#deliver(event, (r) => r.config?.derived === true);
|
|
271
310
|
}
|
|
272
311
|
}
|
|
312
|
+
/** Runs every matching handler to the end, each error logged; returns the named subscriptions that threw. */
|
|
273
313
|
async #deliver(event, eligible) {
|
|
274
314
|
this.#validate(event);
|
|
275
315
|
const matches = Array.from(this.#registrations.values()).filter(
|
|
276
316
|
(r) => eligible(r) && r.regexes.some((re) => re.test(event.type))
|
|
277
317
|
);
|
|
278
|
-
await Promise.all(
|
|
318
|
+
const outcomes = await Promise.all(
|
|
279
319
|
matches.map(async (r) => {
|
|
280
320
|
try {
|
|
281
321
|
await r.handler(event);
|
|
322
|
+
return null;
|
|
282
323
|
} catch (err) {
|
|
324
|
+
const subscription = r.config?.name;
|
|
283
325
|
this.#logger?.error(
|
|
284
|
-
{ err, subscriptionId: r.id, eventType: event.type, eventId: event.id },
|
|
326
|
+
{ err, subscriptionId: r.id, subscription, eventType: event.type, eventId: event.id },
|
|
285
327
|
"Event handler failed"
|
|
286
328
|
);
|
|
329
|
+
return subscription === void 0 ? null : { subscription, message: messageOf(err) };
|
|
287
330
|
}
|
|
288
331
|
})
|
|
289
332
|
);
|
|
333
|
+
return outcomes.filter((o) => o !== null);
|
|
290
334
|
}
|
|
291
335
|
async subscribe(eventPattern, handler, config) {
|
|
292
336
|
const patterns = Array.isArray(eventPattern) ? eventPattern : [eventPattern];
|
|
@@ -322,6 +366,9 @@ var InProcessEventBus = class {
|
|
|
322
366
|
}
|
|
323
367
|
}
|
|
324
368
|
};
|
|
369
|
+
function messageOf(err) {
|
|
370
|
+
return err instanceof Error ? err.message : String(err);
|
|
371
|
+
}
|
|
325
372
|
function compilePattern(pattern) {
|
|
326
373
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\*]/g, "\\$&").replace(/\\\*/g, ".*");
|
|
327
374
|
return new RegExp(`^${escaped}$`);
|
|
@@ -1821,8 +1868,34 @@ function createOrderSequenceRepository(store) {
|
|
|
1821
1868
|
};
|
|
1822
1869
|
}
|
|
1823
1870
|
|
|
1871
|
+
// src/repositories/order-access-key.ts
|
|
1872
|
+
import { and as and6, eq as eq12 } from "drizzle-orm";
|
|
1873
|
+
function createOrderAccessKeyRepository(store) {
|
|
1874
|
+
return {
|
|
1875
|
+
store,
|
|
1876
|
+
async insert(tx, k) {
|
|
1877
|
+
const row = { id: k.id, orderId: k.orderId, keyHash: k.keyHash, purpose: k.purpose };
|
|
1878
|
+
if (tx.kind === "sqlite") {
|
|
1879
|
+
sqliteDb(tx).insert(orderAccessKeys).values({ ...row, createdAt: k.createdAt.toISOString() }).run();
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
await postgresDb(tx).insert(orderAccessKeys2).values({ ...row, createdAt: k.createdAt });
|
|
1883
|
+
},
|
|
1884
|
+
async opens(tx, orderId, keyHash) {
|
|
1885
|
+
if (tx.kind === "sqlite") {
|
|
1886
|
+
const t2 = orderAccessKeys;
|
|
1887
|
+
const row = sqliteDb(tx).select({ id: t2.id }).from(t2).where(and6(eq12(t2.orderId, orderId), eq12(t2.keyHash, keyHash))).get();
|
|
1888
|
+
return row !== void 0;
|
|
1889
|
+
}
|
|
1890
|
+
const t = orderAccessKeys2;
|
|
1891
|
+
const rows = await postgresDb(tx).select({ id: t.id }).from(t).where(and6(eq12(t.orderId, orderId), eq12(t.keyHash, keyHash))).limit(1);
|
|
1892
|
+
return rows.length > 0;
|
|
1893
|
+
}
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1824
1897
|
// src/repositories/inventory-reservation.ts
|
|
1825
|
-
import { eq as
|
|
1898
|
+
import { eq as eq13, lt as lt2 } from "drizzle-orm";
|
|
1826
1899
|
function rowToReservation(row) {
|
|
1827
1900
|
return {
|
|
1828
1901
|
reservationId: String(row.reservationId),
|
|
@@ -1859,26 +1932,26 @@ function createInventoryReservationRepository(store) {
|
|
|
1859
1932
|
},
|
|
1860
1933
|
async findById(tx, reservationId) {
|
|
1861
1934
|
if (tx.kind === "sqlite") {
|
|
1862
|
-
const row2 = sqliteDb(tx).select().from(inventoryReservations).where(
|
|
1935
|
+
const row2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).get();
|
|
1863
1936
|
return row2 ? rowToReservation(row2) : null;
|
|
1864
1937
|
}
|
|
1865
|
-
const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(
|
|
1938
|
+
const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId));
|
|
1866
1939
|
return row ? rowToReservation(row) : null;
|
|
1867
1940
|
},
|
|
1868
1941
|
async findByVariant(tx, variantId) {
|
|
1869
1942
|
if (tx.kind === "sqlite") {
|
|
1870
|
-
const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(
|
|
1943
|
+
const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.variantId, variantId)).all();
|
|
1871
1944
|
return rows2.map((r) => rowToReservation(r));
|
|
1872
1945
|
}
|
|
1873
|
-
const rows = await postgresDb(tx).select().from(inventoryReservations2).where(
|
|
1946
|
+
const rows = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.variantId, variantId));
|
|
1874
1947
|
return rows.map((r) => rowToReservation(r));
|
|
1875
1948
|
},
|
|
1876
1949
|
async deleteById(tx, reservationId) {
|
|
1877
1950
|
if (tx.kind === "sqlite") {
|
|
1878
|
-
const row2 = sqliteDb(tx).delete(inventoryReservations).where(
|
|
1951
|
+
const row2 = sqliteDb(tx).delete(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).returning().get();
|
|
1879
1952
|
return row2 ? rowToReservation(row2) : null;
|
|
1880
1953
|
}
|
|
1881
|
-
const [row] = await postgresDb(tx).delete(inventoryReservations2).where(
|
|
1954
|
+
const [row] = await postgresDb(tx).delete(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId)).returning();
|
|
1882
1955
|
return row ? rowToReservation(row) : null;
|
|
1883
1956
|
},
|
|
1884
1957
|
async findExpiredBefore(tx, at) {
|
|
@@ -1891,16 +1964,16 @@ function createInventoryReservationRepository(store) {
|
|
|
1891
1964
|
},
|
|
1892
1965
|
async setOrderRef(tx, reservationId, orderRef) {
|
|
1893
1966
|
if (tx.kind === "sqlite") {
|
|
1894
|
-
sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(
|
|
1967
|
+
sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(eq13(inventoryReservations.reservationId, reservationId)).run();
|
|
1895
1968
|
return;
|
|
1896
1969
|
}
|
|
1897
|
-
await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(
|
|
1970
|
+
await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(eq13(inventoryReservations2.reservationId, reservationId));
|
|
1898
1971
|
}
|
|
1899
1972
|
};
|
|
1900
1973
|
}
|
|
1901
1974
|
|
|
1902
1975
|
// src/repositories/stock-adjustment.ts
|
|
1903
|
-
import { desc as desc2, eq as
|
|
1976
|
+
import { desc as desc2, eq as eq14 } from "drizzle-orm";
|
|
1904
1977
|
function rowToAdjustment(row) {
|
|
1905
1978
|
return {
|
|
1906
1979
|
id: String(row.id),
|
|
@@ -1934,17 +2007,17 @@ function createStockAdjustmentRepository(store) {
|
|
|
1934
2007
|
},
|
|
1935
2008
|
async listByVariant(tx, variantId, limit = 100) {
|
|
1936
2009
|
if (tx.kind === "sqlite") {
|
|
1937
|
-
const rows2 = sqliteDb(tx).select().from(stockAdjustments).where(
|
|
2010
|
+
const rows2 = sqliteDb(tx).select().from(stockAdjustments).where(eq14(stockAdjustments.variantId, variantId)).orderBy(desc2(stockAdjustments.timestamp)).limit(limit).all();
|
|
1938
2011
|
return rows2.map((r) => rowToAdjustment(r));
|
|
1939
2012
|
}
|
|
1940
|
-
const rows = await postgresDb(tx).select().from(stockAdjustments2).where(
|
|
2013
|
+
const rows = await postgresDb(tx).select().from(stockAdjustments2).where(eq14(stockAdjustments2.variantId, variantId)).orderBy(desc2(stockAdjustments2.timestamp)).limit(limit);
|
|
1941
2014
|
return rows.map((r) => rowToAdjustment(r));
|
|
1942
2015
|
}
|
|
1943
2016
|
};
|
|
1944
2017
|
}
|
|
1945
2018
|
|
|
1946
2019
|
// src/repositories/review.ts
|
|
1947
|
-
import { and as
|
|
2020
|
+
import { and as and7, desc as desc3, eq as eq15, lt as lt3, or } from "drizzle-orm";
|
|
1948
2021
|
function rowToReview(row) {
|
|
1949
2022
|
return {
|
|
1950
2023
|
id: String(row.id),
|
|
@@ -1965,40 +2038,40 @@ function createReviewRepository(store) {
|
|
|
1965
2038
|
store,
|
|
1966
2039
|
async findById(tx, id) {
|
|
1967
2040
|
if (tx.kind === "sqlite") {
|
|
1968
|
-
const row2 = sqliteDb(tx).select().from(reviews).where(
|
|
2041
|
+
const row2 = sqliteDb(tx).select().from(reviews).where(eq15(reviews.id, id)).get();
|
|
1969
2042
|
return row2 ? rowToReview(row2) : null;
|
|
1970
2043
|
}
|
|
1971
|
-
const [row] = await postgresDb(tx).select().from(reviews2).where(
|
|
2044
|
+
const [row] = await postgresDb(tx).select().from(reviews2).where(eq15(reviews2.id, id));
|
|
1972
2045
|
return row ? rowToReview(row) : null;
|
|
1973
2046
|
},
|
|
1974
2047
|
async listByProduct(tx, productId, status, limit = 50, after) {
|
|
1975
2048
|
if (tx.kind === "sqlite") {
|
|
1976
2049
|
const t2 = reviews;
|
|
1977
|
-
const conds2 = [
|
|
1978
|
-
if (status) conds2.push(
|
|
2050
|
+
const conds2 = [eq15(t2.productId, productId)];
|
|
2051
|
+
if (status) conds2.push(eq15(t2.moderationStatus, status));
|
|
1979
2052
|
if (after) {
|
|
1980
2053
|
const at = new Date(after.submittedAt).toISOString();
|
|
1981
|
-
conds2.push(or(lt3(t2.submittedAt, at),
|
|
2054
|
+
conds2.push(or(lt3(t2.submittedAt, at), and7(eq15(t2.submittedAt, at), lt3(t2.id, after.id))));
|
|
1982
2055
|
}
|
|
1983
|
-
const rows2 = sqliteDb(tx).select().from(t2).where(
|
|
2056
|
+
const rows2 = sqliteDb(tx).select().from(t2).where(and7(...conds2)).orderBy(desc3(t2.submittedAt), desc3(t2.id)).limit(limit).all();
|
|
1984
2057
|
return rows2.map((r) => rowToReview(r));
|
|
1985
2058
|
}
|
|
1986
2059
|
const t = reviews2;
|
|
1987
|
-
const conds = [
|
|
1988
|
-
if (status) conds.push(
|
|
2060
|
+
const conds = [eq15(t.productId, productId)];
|
|
2061
|
+
if (status) conds.push(eq15(t.moderationStatus, status));
|
|
1989
2062
|
if (after) {
|
|
1990
2063
|
const at = new Date(after.submittedAt);
|
|
1991
|
-
conds.push(or(lt3(t.submittedAt, at),
|
|
2064
|
+
conds.push(or(lt3(t.submittedAt, at), and7(eq15(t.submittedAt, at), lt3(t.id, after.id))));
|
|
1992
2065
|
}
|
|
1993
|
-
const rows = await postgresDb(tx).select().from(t).where(
|
|
2066
|
+
const rows = await postgresDb(tx).select().from(t).where(and7(...conds)).orderBy(desc3(t.submittedAt), desc3(t.id)).limit(limit);
|
|
1994
2067
|
return rows.map((r) => rowToReview(r));
|
|
1995
2068
|
},
|
|
1996
2069
|
async listByStatus(tx, status, limit = 100) {
|
|
1997
2070
|
if (tx.kind === "sqlite") {
|
|
1998
|
-
const rows2 = sqliteDb(tx).select().from(reviews).where(
|
|
2071
|
+
const rows2 = sqliteDb(tx).select().from(reviews).where(eq15(reviews.moderationStatus, status)).orderBy(desc3(reviews.submittedAt)).limit(limit).all();
|
|
1999
2072
|
return rows2.map((r) => rowToReview(r));
|
|
2000
2073
|
}
|
|
2001
|
-
const rows = await postgresDb(tx).select().from(reviews2).where(
|
|
2074
|
+
const rows = await postgresDb(tx).select().from(reviews2).where(eq15(reviews2.moderationStatus, status)).orderBy(desc3(reviews2.submittedAt)).limit(limit);
|
|
2002
2075
|
return rows.map((r) => rowToReview(r));
|
|
2003
2076
|
},
|
|
2004
2077
|
async insert(tx, r) {
|
|
@@ -2034,10 +2107,10 @@ function createReviewRepository(store) {
|
|
|
2034
2107
|
moderationStatus: status,
|
|
2035
2108
|
moderatedBy,
|
|
2036
2109
|
moderatedAt: moderatedAt.toISOString()
|
|
2037
|
-
}).where(
|
|
2110
|
+
}).where(eq15(reviews.id, id)).run();
|
|
2038
2111
|
return;
|
|
2039
2112
|
}
|
|
2040
|
-
await postgresDb(tx).update(reviews2).set({ moderationStatus: status, moderatedBy, moderatedAt }).where(
|
|
2113
|
+
await postgresDb(tx).update(reviews2).set({ moderationStatus: status, moderatedBy, moderatedAt }).where(eq15(reviews2.id, id));
|
|
2041
2114
|
},
|
|
2042
2115
|
async aggregateByProduct(tx, productId) {
|
|
2043
2116
|
const approved = await this.listByProduct(tx, productId, "approved", 1e3);
|
|
@@ -2064,7 +2137,7 @@ function createReviewRepository(store) {
|
|
|
2064
2137
|
}
|
|
2065
2138
|
|
|
2066
2139
|
// src/repositories/processed-event.ts
|
|
2067
|
-
import { and as
|
|
2140
|
+
import { and as and8, eq as eq16, lt as lt4 } from "drizzle-orm";
|
|
2068
2141
|
function createProcessedEventRepository(store) {
|
|
2069
2142
|
const s = processedEvents;
|
|
2070
2143
|
const p = processedEvents2;
|
|
@@ -2072,10 +2145,10 @@ function createProcessedEventRepository(store) {
|
|
|
2072
2145
|
store,
|
|
2073
2146
|
async seen(tx, handlerName, eventId) {
|
|
2074
2147
|
if (tx.kind === "sqlite") {
|
|
2075
|
-
const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(
|
|
2148
|
+
const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(and8(eq16(s.handlerName, handlerName), eq16(s.eventId, eventId))).get();
|
|
2076
2149
|
return row !== void 0;
|
|
2077
2150
|
}
|
|
2078
|
-
const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(
|
|
2151
|
+
const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(and8(eq16(p.handlerName, handlerName), eq16(p.eventId, eventId))).limit(1);
|
|
2079
2152
|
return rows.length > 0;
|
|
2080
2153
|
},
|
|
2081
2154
|
async markProcessed(tx, handlerName, eventId, at) {
|
|
@@ -2085,6 +2158,14 @@ function createProcessedEventRepository(store) {
|
|
|
2085
2158
|
}
|
|
2086
2159
|
await postgresDb(tx).insert(p).values({ handlerName, eventId, processedAt: at }).onConflictDoNothing();
|
|
2087
2160
|
},
|
|
2161
|
+
async claim(tx, handlerName, eventId, at) {
|
|
2162
|
+
if (tx.kind === "sqlite") {
|
|
2163
|
+
const result2 = sqliteDb(tx).insert(s).values({ handlerName, eventId, processedAt: at.toISOString() }).onConflictDoNothing().run();
|
|
2164
|
+
return result2.changes > 0;
|
|
2165
|
+
}
|
|
2166
|
+
const result = await postgresDb(tx).insert(p).values({ handlerName, eventId, processedAt: at }).onConflictDoNothing();
|
|
2167
|
+
return (result.rowCount ?? 0) > 0;
|
|
2168
|
+
},
|
|
2088
2169
|
async deleteBefore(tx, at) {
|
|
2089
2170
|
if (tx.kind === "sqlite") {
|
|
2090
2171
|
return sqliteDb(tx).delete(s).where(lt4(s.processedAt, at.toISOString())).run().changes;
|
|
@@ -2097,9 +2178,9 @@ function createProcessedEventRepository(store) {
|
|
|
2097
2178
|
|
|
2098
2179
|
// src/repositories/event-log.ts
|
|
2099
2180
|
import {
|
|
2100
|
-
and as
|
|
2181
|
+
and as and9,
|
|
2101
2182
|
asc as asc8,
|
|
2102
|
-
eq as
|
|
2183
|
+
eq as eq17,
|
|
2103
2184
|
gt as gt5,
|
|
2104
2185
|
gte as gte2,
|
|
2105
2186
|
inArray as inArray2,
|
|
@@ -2112,6 +2193,7 @@ import {
|
|
|
2112
2193
|
} from "drizzle-orm";
|
|
2113
2194
|
|
|
2114
2195
|
// src/history/subject.ts
|
|
2196
|
+
import { EVT_PRODUCT_VIEWED } from "@nymbalhq/types";
|
|
2115
2197
|
function text(value) {
|
|
2116
2198
|
return typeof value === "string" ? value : void 0;
|
|
2117
2199
|
}
|
|
@@ -2123,6 +2205,7 @@ function subjectOf(envelope) {
|
|
|
2123
2205
|
const type = envelope.type;
|
|
2124
2206
|
let subject;
|
|
2125
2207
|
let id;
|
|
2208
|
+
if (type === EVT_PRODUCT_VIEWED) return null;
|
|
2126
2209
|
if (type.startsWith("product.")) {
|
|
2127
2210
|
subject = "product";
|
|
2128
2211
|
id = nestedId(payload["product"]) ?? text(payload["productId"]);
|
|
@@ -2142,6 +2225,7 @@ function subjectOf(envelope) {
|
|
|
2142
2225
|
// src/repositories/event-log.ts
|
|
2143
2226
|
var APPEND_CHUNK = 100;
|
|
2144
2227
|
var DELETE_CHUNK = 500;
|
|
2228
|
+
var APPEND_INTO = "INSERT INTO events (id, type, envelope, correlation_id, subject_type, subject_id, created_at) VALUES";
|
|
2145
2229
|
var CATCH_UP_LIMIT = 1e4;
|
|
2146
2230
|
function sqliteGlob(glob) {
|
|
2147
2231
|
return glob.replace(/[[?]/g, (c) => `[${c}]`);
|
|
@@ -2207,48 +2291,57 @@ function createEventLogRepository(store) {
|
|
|
2207
2291
|
}
|
|
2208
2292
|
async function select(tx, where, limit) {
|
|
2209
2293
|
if (tx.kind === "sqlite") {
|
|
2210
|
-
return sqliteDb(tx).select().from(s).where(
|
|
2294
|
+
return sqliteDb(tx).select(sqliteLogged).from(s).where(and9(...where.sqlite)).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
|
|
2211
2295
|
}
|
|
2212
|
-
const rows = await postgresDb(tx).select().from(p).where(
|
|
2296
|
+
const rows = await postgresDb(tx).select(postgresLogged).from(p).where(and9(...where.postgres)).orderBy(asc8(p.seq)).limit(limit);
|
|
2213
2297
|
return rows.map(rowToLogged);
|
|
2214
2298
|
}
|
|
2215
2299
|
return {
|
|
2216
2300
|
store,
|
|
2301
|
+
// The columns are named, not taken from the schema: a store a migration behind, before a later column of the log
|
|
2302
|
+
// (retry_at), still takes appends.
|
|
2217
2303
|
async append(tx, events3) {
|
|
2218
2304
|
const now = /* @__PURE__ */ new Date();
|
|
2219
2305
|
for (let i = 0; i < events3.length; i += APPEND_CHUNK) {
|
|
2220
2306
|
const chunk = events3.slice(i, i + APPEND_CHUNK);
|
|
2307
|
+
const rows = (row) => sql4.join(chunk.map(row), sql4`, `);
|
|
2221
2308
|
if (tx.kind === "sqlite") {
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
createdAt: now.toISOString()
|
|
2230
|
-
}))
|
|
2231
|
-
).run();
|
|
2309
|
+
const at = now.toISOString();
|
|
2310
|
+
sqliteDb(tx).run(
|
|
2311
|
+
sql4`${sql4.raw(APPEND_INTO)} ${rows((e) => {
|
|
2312
|
+
const { subjectType, subjectId } = subjectColumns(e);
|
|
2313
|
+
return sql4`(${e.id}, ${e.type}, ${JSON.stringify(e)}, ${e.correlationId}, ${subjectType}, ${subjectId}, ${at})`;
|
|
2314
|
+
})}`
|
|
2315
|
+
);
|
|
2232
2316
|
} else {
|
|
2233
|
-
await postgresDb(tx).
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
correlationId: e.correlationId,
|
|
2239
|
-
...subjectColumns(e),
|
|
2240
|
-
createdAt: now
|
|
2241
|
-
}))
|
|
2317
|
+
await postgresDb(tx).execute(
|
|
2318
|
+
sql4`${sql4.raw(APPEND_INTO)} ${rows((e) => {
|
|
2319
|
+
const { subjectType, subjectId } = subjectColumns(e);
|
|
2320
|
+
return sql4`(${e.id}, ${e.type}, ${JSON.stringify(e)}::jsonb, ${e.correlationId}, ${subjectType}, ${subjectId}, ${now.toISOString()}::timestamptz)`;
|
|
2321
|
+
})}`
|
|
2242
2322
|
);
|
|
2243
2323
|
}
|
|
2244
2324
|
}
|
|
2245
2325
|
},
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2326
|
+
listUndelivered(tx, limit, afterSeq = 0, now) {
|
|
2327
|
+
return select(
|
|
2328
|
+
tx,
|
|
2329
|
+
{
|
|
2330
|
+
sqlite: [
|
|
2331
|
+
isNull2(s.deliveredAt),
|
|
2332
|
+
isNull2(s.deadAt),
|
|
2333
|
+
gt5(s.seq, afterSeq),
|
|
2334
|
+
...now === void 0 ? [] : [or2(isNull2(s.retryAt), lte(s.retryAt, now.toISOString()))]
|
|
2335
|
+
],
|
|
2336
|
+
postgres: [
|
|
2337
|
+
isNull2(p.deliveredAt),
|
|
2338
|
+
isNull2(p.deadAt),
|
|
2339
|
+
gt5(p.seq, afterSeq),
|
|
2340
|
+
...now === void 0 ? [] : [or2(isNull2(p.retryAt), lte(p.retryAt, now))]
|
|
2341
|
+
]
|
|
2342
|
+
},
|
|
2343
|
+
limit
|
|
2344
|
+
);
|
|
2252
2345
|
},
|
|
2253
2346
|
async markDelivered(tx, ids, at) {
|
|
2254
2347
|
if (ids.length === 0) return;
|
|
@@ -2258,40 +2351,61 @@ function createEventLogRepository(store) {
|
|
|
2258
2351
|
}
|
|
2259
2352
|
await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray2(p.id, ids));
|
|
2260
2353
|
},
|
|
2261
|
-
async recordFailure(tx, id, at, maxAttempts) {
|
|
2354
|
+
async recordFailure(tx, id, at, maxAttempts, retryAt) {
|
|
2262
2355
|
if (tx.kind === "sqlite") {
|
|
2263
2356
|
sqliteDb(tx).update(s).set({
|
|
2264
2357
|
attempts: sql4`${s.attempts} + 1`,
|
|
2265
|
-
deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END
|
|
2266
|
-
|
|
2358
|
+
deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`,
|
|
2359
|
+
...retryAt !== void 0 && { retryAt: retryAt.toISOString() }
|
|
2360
|
+
}).where(eq17(s.id, id)).run();
|
|
2267
2361
|
return;
|
|
2268
2362
|
}
|
|
2269
2363
|
await postgresDb(tx).update(p).set({
|
|
2270
2364
|
attempts: sql4`${p.attempts} + 1`,
|
|
2271
|
-
deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END
|
|
2272
|
-
|
|
2365
|
+
deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`,
|
|
2366
|
+
...retryAt !== void 0 && { retryAt }
|
|
2367
|
+
}).where(eq17(p.id, id));
|
|
2368
|
+
},
|
|
2369
|
+
async countDead(tx) {
|
|
2370
|
+
if (tx.kind === "sqlite") {
|
|
2371
|
+
const row2 = sqliteDb(tx).select({ n: sql4`count(*)` }).from(s).where(isNotNull(s.deadAt)).get();
|
|
2372
|
+
return Number(row2?.n ?? 0);
|
|
2373
|
+
}
|
|
2374
|
+
const [row] = await postgresDb(tx).select({ n: sql4`count(*)` }).from(p).where(isNotNull(p.deadAt));
|
|
2375
|
+
return Number(row?.n ?? 0);
|
|
2376
|
+
},
|
|
2377
|
+
listDead(tx, limit) {
|
|
2378
|
+
return select(tx, { sqlite: [isNotNull(s.deadAt)], postgres: [isNotNull(p.deadAt)] }, limit);
|
|
2379
|
+
},
|
|
2380
|
+
async countRetrying(tx) {
|
|
2381
|
+
if (tx.kind === "sqlite") {
|
|
2382
|
+
const row2 = sqliteDb(tx).select({ n: sql4`count(*)` }).from(s).where(and9(isNull2(s.deliveredAt), isNull2(s.deadAt), gt5(s.attempts, 0))).get();
|
|
2383
|
+
return Number(row2?.n ?? 0);
|
|
2384
|
+
}
|
|
2385
|
+
const [row] = await postgresDb(tx).select({ n: sql4`count(*)` }).from(p).where(and9(isNull2(p.deliveredAt), isNull2(p.deadAt), gt5(p.attempts, 0)));
|
|
2386
|
+
return Number(row?.n ?? 0);
|
|
2273
2387
|
},
|
|
2274
2388
|
async deleteDeliveredBefore(tx, at) {
|
|
2275
2389
|
if (tx.kind === "sqlite") {
|
|
2276
|
-
const result2 = sqliteDb(tx).delete(s).where(
|
|
2390
|
+
const result2 = sqliteDb(tx).delete(s).where(and9(isNotNull(s.deliveredAt), lt5(s.deliveredAt, at.toISOString()))).run();
|
|
2277
2391
|
return result2.changes;
|
|
2278
2392
|
}
|
|
2279
|
-
const result = await postgresDb(tx).delete(p).where(
|
|
2393
|
+
const result = await postgresDb(tx).delete(p).where(and9(isNotNull(p.deliveredAt), lt5(p.deliveredAt, at)));
|
|
2280
2394
|
return result.rowCount ?? 0;
|
|
2281
2395
|
},
|
|
2282
2396
|
async listAll(tx) {
|
|
2283
2397
|
if (tx.kind === "sqlite") {
|
|
2284
|
-
return sqliteDb(tx).select().from(s).orderBy(asc8(s.seq)).all().map(rowToLogged);
|
|
2398
|
+
return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc8(s.seq)).all().map(rowToLogged);
|
|
2285
2399
|
}
|
|
2286
|
-
const rows = await postgresDb(tx).select().from(p).orderBy(asc8(p.seq));
|
|
2400
|
+
const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc8(p.seq));
|
|
2287
2401
|
return rows.map(rowToLogged);
|
|
2288
2402
|
},
|
|
2289
2403
|
queryByCorrelation(tx, correlationId, filter) {
|
|
2290
2404
|
return select(
|
|
2291
2405
|
tx,
|
|
2292
2406
|
{
|
|
2293
|
-
sqlite: [
|
|
2294
|
-
postgres: [
|
|
2407
|
+
sqlite: [eq17(s.correlationId, correlationId), ...sqliteWhere(filter)],
|
|
2408
|
+
postgres: [eq17(p.correlationId, correlationId), ...postgresWhere(filter)]
|
|
2295
2409
|
},
|
|
2296
2410
|
filter.limit
|
|
2297
2411
|
);
|
|
@@ -2320,7 +2434,7 @@ function createEventLogRepository(store) {
|
|
|
2320
2434
|
const limit = page.limit ?? CATCH_UP_LIMIT;
|
|
2321
2435
|
if (tx.kind === "sqlite") {
|
|
2322
2436
|
return sqliteDb(tx).select(sqliteLogged).from(s).where(
|
|
2323
|
-
|
|
2437
|
+
and9(
|
|
2324
2438
|
isNull2(s.deadAt),
|
|
2325
2439
|
or2(isNull2(s.deliveredAt), gte2(s.deliveredAt, since.toISOString())),
|
|
2326
2440
|
gt5(s.seq, afterSeq)
|
|
@@ -2328,7 +2442,7 @@ function createEventLogRepository(store) {
|
|
|
2328
2442
|
).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
|
|
2329
2443
|
}
|
|
2330
2444
|
const rows = await postgresDb(tx).select(postgresLogged).from(p).where(
|
|
2331
|
-
|
|
2445
|
+
and9(
|
|
2332
2446
|
isNull2(p.deadAt),
|
|
2333
2447
|
or2(isNull2(p.deliveredAt), gte2(p.deliveredAt, since)),
|
|
2334
2448
|
gt5(p.seq, afterSeq)
|
|
@@ -2351,9 +2465,9 @@ function createEventLogRepository(store) {
|
|
|
2351
2465
|
for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {
|
|
2352
2466
|
const chunk = seqs.slice(i, i + DELETE_CHUNK);
|
|
2353
2467
|
if (tx.kind === "sqlite") {
|
|
2354
|
-
deleted += sqliteDb(tx).delete(s).where(
|
|
2468
|
+
deleted += sqliteDb(tx).delete(s).where(and9(inArray2(s.seq, chunk), isNotNull(s.deliveredAt), isNull2(s.deadAt))).run().changes;
|
|
2355
2469
|
} else {
|
|
2356
|
-
const result = await postgresDb(tx).delete(p).where(
|
|
2470
|
+
const result = await postgresDb(tx).delete(p).where(and9(inArray2(p.seq, chunk), isNotNull(p.deliveredAt), isNull2(p.deadAt)));
|
|
2357
2471
|
deleted += result.rowCount ?? 0;
|
|
2358
2472
|
}
|
|
2359
2473
|
}
|
|
@@ -2366,12 +2480,12 @@ function createEventLogRepository(store) {
|
|
|
2366
2480
|
tx,
|
|
2367
2481
|
{
|
|
2368
2482
|
sqlite: [
|
|
2369
|
-
or2(...subjects.map((x) =>
|
|
2483
|
+
or2(...subjects.map((x) => and9(eq17(s.subjectType, x.type), eq17(s.subjectId, x.id)))),
|
|
2370
2484
|
gt5(s.seq, afterSeq),
|
|
2371
2485
|
...page.until === void 0 ? [] : [lte(s.createdAt, page.until.toISOString())]
|
|
2372
2486
|
],
|
|
2373
2487
|
postgres: [
|
|
2374
|
-
or2(...subjects.map((x) =>
|
|
2488
|
+
or2(...subjects.map((x) => and9(eq17(p.subjectType, x.type), eq17(p.subjectId, x.id)))),
|
|
2375
2489
|
gt5(p.seq, afterSeq),
|
|
2376
2490
|
...page.until === void 0 ? [] : [lte(p.createdAt, page.until)]
|
|
2377
2491
|
]
|
|
@@ -2383,7 +2497,7 @@ function createEventLogRepository(store) {
|
|
|
2383
2497
|
}
|
|
2384
2498
|
|
|
2385
2499
|
// src/repositories/cart.ts
|
|
2386
|
-
import { and as
|
|
2500
|
+
import { and as and10, asc as asc9, eq as eq18, gt as gt6, isNull as isNull3, lt as lt6, lte as lte2, sql as sql5 } from "drizzle-orm";
|
|
2387
2501
|
function rowToCart(store, row) {
|
|
2388
2502
|
return {
|
|
2389
2503
|
token: String(row.token),
|
|
@@ -2437,7 +2551,7 @@ var fromExcluded = {
|
|
|
2437
2551
|
};
|
|
2438
2552
|
function sqliteDue(window) {
|
|
2439
2553
|
const t = carts;
|
|
2440
|
-
return
|
|
2554
|
+
return and10(
|
|
2441
2555
|
isNull3(t.abandonedNotifiedAt),
|
|
2442
2556
|
gt6(t.lineCount, 0),
|
|
2443
2557
|
lt6(t.updatedAt, window.cutoff.toISOString()),
|
|
@@ -2446,7 +2560,7 @@ function sqliteDue(window) {
|
|
|
2446
2560
|
}
|
|
2447
2561
|
function postgresDue(window) {
|
|
2448
2562
|
const t = carts2;
|
|
2449
|
-
return
|
|
2563
|
+
return and10(
|
|
2450
2564
|
isNull3(t.abandonedNotifiedAt),
|
|
2451
2565
|
gt6(t.lineCount, 0),
|
|
2452
2566
|
lt6(t.updatedAt, window.cutoff),
|
|
@@ -2456,15 +2570,15 @@ function postgresDue(window) {
|
|
|
2456
2570
|
function createCartRepository(store) {
|
|
2457
2571
|
async function findByToken(tx, token) {
|
|
2458
2572
|
if (tx.kind === "sqlite") {
|
|
2459
|
-
const row2 = sqliteDb(tx).select().from(carts).where(
|
|
2573
|
+
const row2 = sqliteDb(tx).select().from(carts).where(eq18(carts.token, token)).get();
|
|
2460
2574
|
return row2 ? rowToCart("sqlite", row2) : null;
|
|
2461
2575
|
}
|
|
2462
|
-
const [row] = await postgresDb(tx).select().from(carts2).where(
|
|
2576
|
+
const [row] = await postgresDb(tx).select().from(carts2).where(eq18(carts2.token, token));
|
|
2463
2577
|
return row ? rowToCart("postgres", row) : null;
|
|
2464
2578
|
}
|
|
2465
2579
|
async function lock(tx, token) {
|
|
2466
2580
|
if (tx.kind === "sqlite") return findByToken(tx, token);
|
|
2467
|
-
const [row] = await postgresDb(tx).select().from(carts2).where(
|
|
2581
|
+
const [row] = await postgresDb(tx).select().from(carts2).where(eq18(carts2.token, token)).for("update");
|
|
2468
2582
|
return row ? rowToCart("postgres", row) : null;
|
|
2469
2583
|
}
|
|
2470
2584
|
return {
|
|
@@ -2501,10 +2615,10 @@ function createCartRepository(store) {
|
|
|
2501
2615
|
},
|
|
2502
2616
|
async remove(tx, token) {
|
|
2503
2617
|
if (tx.kind === "sqlite") {
|
|
2504
|
-
sqliteDb(tx).delete(carts).where(
|
|
2618
|
+
sqliteDb(tx).delete(carts).where(eq18(carts.token, token)).run();
|
|
2505
2619
|
return;
|
|
2506
2620
|
}
|
|
2507
|
-
await postgresDb(tx).delete(carts2).where(
|
|
2621
|
+
await postgresDb(tx).delete(carts2).where(eq18(carts2.token, token));
|
|
2508
2622
|
},
|
|
2509
2623
|
async clearIfLive(tx, token, at) {
|
|
2510
2624
|
if (tx.kind === "sqlite") {
|
|
@@ -2515,7 +2629,7 @@ function createCartRepository(store) {
|
|
|
2515
2629
|
subtotalMinor: 0,
|
|
2516
2630
|
updatedAt: at.toISOString(),
|
|
2517
2631
|
abandonedNotifiedAt: null
|
|
2518
|
-
}).where(
|
|
2632
|
+
}).where(and10(eq18(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
|
|
2519
2633
|
return result.changes > 0;
|
|
2520
2634
|
}
|
|
2521
2635
|
const t = carts2;
|
|
@@ -2525,7 +2639,7 @@ function createCartRepository(store) {
|
|
|
2525
2639
|
subtotalMinor: 0,
|
|
2526
2640
|
updatedAt: at,
|
|
2527
2641
|
abandonedNotifiedAt: null
|
|
2528
|
-
}).where(
|
|
2642
|
+
}).where(and10(eq18(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
|
|
2529
2643
|
return rows.length > 0;
|
|
2530
2644
|
},
|
|
2531
2645
|
async deleteExpired(tx, at) {
|
|
@@ -2540,29 +2654,126 @@ function createCartRepository(store) {
|
|
|
2540
2654
|
if (tx.kind === "sqlite") {
|
|
2541
2655
|
const t2 = carts;
|
|
2542
2656
|
const rows2 = sqliteDb(tx).select({ token: t2.token }).from(t2).where(
|
|
2543
|
-
|
|
2657
|
+
and10(sqliteDue(window), page.after === void 0 ? void 0 : gt6(t2.token, page.after))
|
|
2544
2658
|
).orderBy(asc9(t2.token)).limit(page.limit).all();
|
|
2545
2659
|
return rows2.map((r) => r.token);
|
|
2546
2660
|
}
|
|
2547
2661
|
const t = carts2;
|
|
2548
2662
|
const rows = await postgresDb(tx).select({ token: t.token }).from(t).where(
|
|
2549
|
-
|
|
2663
|
+
and10(postgresDue(window), page.after === void 0 ? void 0 : gt6(t.token, page.after))
|
|
2550
2664
|
).orderBy(asc9(t.token)).limit(page.limit);
|
|
2551
2665
|
return rows.map((r) => r.token);
|
|
2552
2666
|
},
|
|
2553
2667
|
async claimAbandoned(tx, token, window) {
|
|
2554
2668
|
if (tx.kind === "sqlite") {
|
|
2555
2669
|
const t2 = carts;
|
|
2556
|
-
const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(
|
|
2670
|
+
const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(and10(eq18(t2.token, token), sqliteDue(window))).returning({ token: t2.token, updatedAt: t2.updatedAt }).get();
|
|
2557
2671
|
return row2 ? { token: row2.token, lastActivityAt: fromTimestamp(row2.updatedAt) } : null;
|
|
2558
2672
|
}
|
|
2559
2673
|
const t = carts2;
|
|
2560
|
-
const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(
|
|
2674
|
+
const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(and10(eq18(t.token, token), postgresDue(window))).returning({ token: t.token, updatedAt: t.updatedAt });
|
|
2561
2675
|
return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null;
|
|
2562
2676
|
}
|
|
2563
2677
|
};
|
|
2564
2678
|
}
|
|
2565
2679
|
|
|
2680
|
+
// src/repositories/alert-subscription.ts
|
|
2681
|
+
import { and as and11, eq as eq19, inArray as inArray3, sql as sql6 } from "drizzle-orm";
|
|
2682
|
+
function fromSqlite(row) {
|
|
2683
|
+
return {
|
|
2684
|
+
...row,
|
|
2685
|
+
kind: row.kind,
|
|
2686
|
+
status: row.status,
|
|
2687
|
+
createdAt: new Date(row.createdAt),
|
|
2688
|
+
updatedAt: new Date(row.updatedAt),
|
|
2689
|
+
confirmedAt: row.confirmedAt === null ? null : new Date(row.confirmedAt)
|
|
2690
|
+
};
|
|
2691
|
+
}
|
|
2692
|
+
function fromPostgres(row) {
|
|
2693
|
+
return { ...row, kind: row.kind, status: row.status };
|
|
2694
|
+
}
|
|
2695
|
+
function createAlertSubscriptionRepository(store) {
|
|
2696
|
+
const s = alertSubscriptions;
|
|
2697
|
+
const p = alertSubscriptions2;
|
|
2698
|
+
async function findOne(tx, where) {
|
|
2699
|
+
if (tx.kind === "sqlite") {
|
|
2700
|
+
const row2 = sqliteDb(tx).select().from(s).where(where(s)).get();
|
|
2701
|
+
return row2 === void 0 ? null : fromSqlite(row2);
|
|
2702
|
+
}
|
|
2703
|
+
const [row] = await postgresDb(tx).select().from(p).where(where(p)).limit(1);
|
|
2704
|
+
return row === void 0 ? null : fromPostgres(row);
|
|
2705
|
+
}
|
|
2706
|
+
return {
|
|
2707
|
+
store,
|
|
2708
|
+
async upsertPending(tx, r) {
|
|
2709
|
+
const keep = (t) => sql6`${t.status} = 'active'`;
|
|
2710
|
+
const reissue = (t) => sql6`${t.status} IN ('unsubscribed', 'fired')`;
|
|
2711
|
+
const set = (t) => ({
|
|
2712
|
+
status: sql6`CASE WHEN ${keep(t)} THEN ${t.status} ELSE 'pending' END`,
|
|
2713
|
+
origin: sql6`CASE WHEN ${keep(t)} THEN ${t.origin} ELSE excluded.origin END`,
|
|
2714
|
+
confirmToken: sql6`CASE WHEN ${reissue(t)} THEN excluded.confirm_token ELSE ${t.confirmToken} END`,
|
|
2715
|
+
baselinePriceMinor: sql6`CASE WHEN ${reissue(t)} THEN excluded.baseline_price_minor ELSE ${t.baselinePriceMinor} END`,
|
|
2716
|
+
confirmedAt: sql6`CASE WHEN ${keep(t)} THEN ${t.confirmedAt} ELSE NULL END`,
|
|
2717
|
+
updatedAt: sql6`excluded.updated_at`
|
|
2718
|
+
});
|
|
2719
|
+
const values = {
|
|
2720
|
+
id: r.id,
|
|
2721
|
+
email: r.email,
|
|
2722
|
+
kind: r.kind,
|
|
2723
|
+
variantId: r.variantId,
|
|
2724
|
+
productId: r.productId,
|
|
2725
|
+
status: "pending",
|
|
2726
|
+
confirmToken: r.confirmToken,
|
|
2727
|
+
unsubscribeToken: r.unsubscribeToken,
|
|
2728
|
+
origin: r.origin,
|
|
2729
|
+
baselinePriceMinor: r.baselinePriceMinor,
|
|
2730
|
+
confirmedAt: null
|
|
2731
|
+
};
|
|
2732
|
+
if (tx.kind === "sqlite") {
|
|
2733
|
+
const at = r.at.toISOString();
|
|
2734
|
+
const row2 = sqliteDb(tx).insert(s).values({ ...values, createdAt: at, updatedAt: at }).onConflictDoUpdate({ target: [s.email, s.variantId, s.kind], set: set(s) }).returning().get();
|
|
2735
|
+
return fromSqlite(row2);
|
|
2736
|
+
}
|
|
2737
|
+
const [row] = await postgresDb(tx).insert(p).values({ ...values, createdAt: r.at, updatedAt: r.at }).onConflictDoUpdate({ target: [p.email, p.variantId, p.kind], set: set(p) }).returning();
|
|
2738
|
+
return fromPostgres(row);
|
|
2739
|
+
},
|
|
2740
|
+
findById: (tx, id) => findOne(tx, (t) => eq19(t.id, id)),
|
|
2741
|
+
findByConfirmToken: (tx, token) => findOne(tx, (t) => eq19(t.confirmToken, token)),
|
|
2742
|
+
findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq19(t.unsubscribeToken, token)),
|
|
2743
|
+
async listActive(tx, variantId, kind) {
|
|
2744
|
+
if (tx.kind === "sqlite") {
|
|
2745
|
+
return sqliteDb(tx).select().from(s).where(and11(eq19(s.variantId, variantId), eq19(s.kind, kind), eq19(s.status, "active"))).orderBy(s.id).all().map(fromSqlite);
|
|
2746
|
+
}
|
|
2747
|
+
const rows = await postgresDb(tx).select().from(p).where(and11(eq19(p.variantId, variantId), eq19(p.kind, kind), eq19(p.status, "active"))).orderBy(p.id);
|
|
2748
|
+
return rows.map(fromPostgres);
|
|
2749
|
+
},
|
|
2750
|
+
async update(tx, id, patch, from) {
|
|
2751
|
+
if (tx.kind === "sqlite") {
|
|
2752
|
+
const row2 = sqliteDb(tx).update(s).set({
|
|
2753
|
+
status: patch.status,
|
|
2754
|
+
updatedAt: patch.updatedAt.toISOString(),
|
|
2755
|
+
...patch.confirmedAt !== void 0 && {
|
|
2756
|
+
confirmedAt: patch.confirmedAt.toISOString()
|
|
2757
|
+
},
|
|
2758
|
+
...patch.baselinePriceMinor !== void 0 && {
|
|
2759
|
+
baselinePriceMinor: patch.baselinePriceMinor
|
|
2760
|
+
}
|
|
2761
|
+
}).where(and11(eq19(s.id, id), inArray3(s.status, [...from]))).returning().get();
|
|
2762
|
+
return row2 === void 0 ? null : fromSqlite(row2);
|
|
2763
|
+
}
|
|
2764
|
+
const [row] = await postgresDb(tx).update(p).set({
|
|
2765
|
+
status: patch.status,
|
|
2766
|
+
updatedAt: patch.updatedAt,
|
|
2767
|
+
...patch.confirmedAt !== void 0 && { confirmedAt: patch.confirmedAt },
|
|
2768
|
+
...patch.baselinePriceMinor !== void 0 && {
|
|
2769
|
+
baselinePriceMinor: patch.baselinePriceMinor
|
|
2770
|
+
}
|
|
2771
|
+
}).where(and11(eq19(p.id, id), inArray3(p.status, [...from]))).returning();
|
|
2772
|
+
return row === void 0 ? null : fromPostgres(row);
|
|
2773
|
+
}
|
|
2774
|
+
};
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2566
2777
|
// src/repositories/index.ts
|
|
2567
2778
|
function buildRepositories(commandStore, _documentStore) {
|
|
2568
2779
|
return {
|
|
@@ -2576,6 +2787,7 @@ function buildRepositories(commandStore, _documentStore) {
|
|
|
2576
2787
|
orderHistory: createOrderHistoryRepository(commandStore),
|
|
2577
2788
|
orderRefund: createOrderRefundRepository(commandStore),
|
|
2578
2789
|
orderSequence: createOrderSequenceRepository(commandStore),
|
|
2790
|
+
orderAccessKey: createOrderAccessKeyRepository(commandStore),
|
|
2579
2791
|
inventoryReservation: createInventoryReservationRepository(commandStore),
|
|
2580
2792
|
stockAdjustment: createStockAdjustmentRepository(commandStore),
|
|
2581
2793
|
review: createReviewRepository(commandStore),
|
|
@@ -2583,7 +2795,8 @@ function buildRepositories(commandStore, _documentStore) {
|
|
|
2583
2795
|
eventLog: createEventLogRepository(commandStore),
|
|
2584
2796
|
cart: createCartRepository(commandStore),
|
|
2585
2797
|
settings: createSettingsRepository(commandStore),
|
|
2586
|
-
auditEntry: createAuditEntryRepository(commandStore)
|
|
2798
|
+
auditEntry: createAuditEntryRepository(commandStore),
|
|
2799
|
+
alertSubscription: createAlertSubscriptionRepository(commandStore)
|
|
2587
2800
|
};
|
|
2588
2801
|
}
|
|
2589
2802
|
|
|
@@ -2635,6 +2848,11 @@ function createEventPublisher(opts) {
|
|
|
2635
2848
|
async publishMany(events3) {
|
|
2636
2849
|
await append(events3.map((e) => build(e.type, e.payload, e.options ?? {})));
|
|
2637
2850
|
},
|
|
2851
|
+
async publishUntyped(events3, options) {
|
|
2852
|
+
const built = events3.map((e) => build(e.type, e.payload, options ?? {}));
|
|
2853
|
+
await append(built);
|
|
2854
|
+
return built;
|
|
2855
|
+
},
|
|
2638
2856
|
correlated(correlationId) {
|
|
2639
2857
|
return createEventPublisher({ ...opts, correlationId });
|
|
2640
2858
|
}
|
|
@@ -2651,10 +2869,16 @@ function deferred() {
|
|
|
2651
2869
|
});
|
|
2652
2870
|
return { promise, resolve: resolve4 };
|
|
2653
2871
|
}
|
|
2872
|
+
function failedOf(err) {
|
|
2873
|
+
const failed = err?.context?.failed;
|
|
2874
|
+
return Array.isArray(failed) ? { failed } : {};
|
|
2875
|
+
}
|
|
2654
2876
|
function createRelay(opts) {
|
|
2655
2877
|
const { store, eventLog } = opts;
|
|
2656
2878
|
const maxAttempts = opts.maxAttempts ?? 5;
|
|
2657
2879
|
const intervalMs = opts.intervalMs ?? 1e4;
|
|
2880
|
+
const retryDelayMs = opts.retryDelayMs ?? intervalMs;
|
|
2881
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
2658
2882
|
const logger = opts.logger.child({ component: "event-relay" });
|
|
2659
2883
|
const delivering = new AsyncLocalStorage();
|
|
2660
2884
|
let active = false;
|
|
@@ -2666,13 +2890,26 @@ function createRelay(opts) {
|
|
|
2666
2890
|
try {
|
|
2667
2891
|
await delivering.run(true, () => opts.eventBus.publish(event));
|
|
2668
2892
|
} catch (err) {
|
|
2669
|
-
const at =
|
|
2670
|
-
|
|
2671
|
-
const
|
|
2672
|
-
|
|
2893
|
+
const at = now();
|
|
2894
|
+
const failures = attempts + 1;
|
|
2895
|
+
const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** (failures - 1));
|
|
2896
|
+
await store.transaction(
|
|
2897
|
+
(tx) => eventLog.recordFailure(tx, event.id, at, maxAttempts, retryAt)
|
|
2898
|
+
);
|
|
2899
|
+
const context = {
|
|
2900
|
+
err,
|
|
2901
|
+
eventId: event.id,
|
|
2902
|
+
eventType: event.type,
|
|
2903
|
+
attempts: failures,
|
|
2904
|
+
...failedOf(err)
|
|
2905
|
+
};
|
|
2906
|
+
if (failures >= maxAttempts) {
|
|
2673
2907
|
logger.error(context, "event delivery failed for the last time; the event is dead");
|
|
2674
2908
|
} else {
|
|
2675
|
-
logger.warn(
|
|
2909
|
+
logger.warn(
|
|
2910
|
+
{ ...context, retryAt: retryAt.toISOString() },
|
|
2911
|
+
"event delivery failed; the event stays in the log and is tried again from retryAt"
|
|
2912
|
+
);
|
|
2676
2913
|
}
|
|
2677
2914
|
return;
|
|
2678
2915
|
}
|
|
@@ -2683,7 +2920,9 @@ function createRelay(opts) {
|
|
|
2683
2920
|
let afterSeq = 0;
|
|
2684
2921
|
for (; ; ) {
|
|
2685
2922
|
if (stopped) return;
|
|
2686
|
-
const page = await store.read(
|
|
2923
|
+
const page = await store.read(
|
|
2924
|
+
(tx) => eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq, now())
|
|
2925
|
+
);
|
|
2687
2926
|
for (const logged of page) {
|
|
2688
2927
|
if (stopped) return;
|
|
2689
2928
|
afterSeq = logged.seq;
|
|
@@ -2777,158 +3016,6 @@ import {
|
|
|
2777
3016
|
EVT_CATEGORY_DELETED,
|
|
2778
3017
|
EVT_CATEGORY_UPDATED
|
|
2779
3018
|
} from "@nymbalhq/types";
|
|
2780
|
-
|
|
2781
|
-
// src/read-models/builders.ts
|
|
2782
|
-
var CATEGORIES = "categories";
|
|
2783
|
-
var PRODUCTS = "products";
|
|
2784
|
-
var PRODUCTS_BY_CATEGORY = "products-by-category";
|
|
2785
|
-
var ORDERS = "orders";
|
|
2786
|
-
var ORDERS_BY_CUSTOMER = "orders-by-customer";
|
|
2787
|
-
var CUSTOMER_PROFILES = "customer-profiles";
|
|
2788
|
-
function buildCategoryDoc(category, storeId) {
|
|
2789
|
-
return {
|
|
2790
|
-
id: category.id,
|
|
2791
|
-
storeId,
|
|
2792
|
-
parentId: category.parentId,
|
|
2793
|
-
slug: category.slug,
|
|
2794
|
-
name: category.name,
|
|
2795
|
-
description: category.description,
|
|
2796
|
-
position: category.position,
|
|
2797
|
-
createdAt: category.createdAt
|
|
2798
|
-
};
|
|
2799
|
-
}
|
|
2800
|
-
var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
|
|
2801
|
-
function variantOptions(raw, sku, logger) {
|
|
2802
|
-
let value = raw;
|
|
2803
|
-
if (typeof raw === "string") {
|
|
2804
|
-
try {
|
|
2805
|
-
value = JSON.parse(raw);
|
|
2806
|
-
} catch (err) {
|
|
2807
|
-
logger?.warn({ sku, err }, "variant options are not JSON; projected as none");
|
|
2808
|
-
return [];
|
|
2809
|
-
}
|
|
2810
|
-
}
|
|
2811
|
-
if (!Array.isArray(value)) return [];
|
|
2812
|
-
return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
|
|
2813
|
-
}
|
|
2814
|
-
function buildProductDoc(p, categories3, ctx) {
|
|
2815
|
-
const prices = p.variants.map((v) => v.priceMinor);
|
|
2816
|
-
return {
|
|
2817
|
-
id: p.id,
|
|
2818
|
-
storeId: ctx.storeId,
|
|
2819
|
-
slug: p.slug,
|
|
2820
|
-
name: p.name,
|
|
2821
|
-
description: p.description,
|
|
2822
|
-
shortDescription: p.shortDescription,
|
|
2823
|
-
status: p.status,
|
|
2824
|
-
type: p.type,
|
|
2825
|
-
media: p.media,
|
|
2826
|
-
variantCount: p.variants.length,
|
|
2827
|
-
inStock: p.variants.some((v) => v.stock > 0),
|
|
2828
|
-
priceRange: prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null,
|
|
2829
|
-
currency: ctx.currency,
|
|
2830
|
-
priceMinor: prices[0] ?? null,
|
|
2831
|
-
variants: p.variants.map((v) => ({
|
|
2832
|
-
id: v.id,
|
|
2833
|
-
sku: v.sku,
|
|
2834
|
-
name: v.name,
|
|
2835
|
-
priceMinor: v.priceMinor,
|
|
2836
|
-
stock: v.stock,
|
|
2837
|
-
options: variantOptions(v.options, v.sku, ctx.logger)
|
|
2838
|
-
})),
|
|
2839
|
-
categoryIds: p.categoryIds,
|
|
2840
|
-
categories: p.categoryIds.flatMap((id) => {
|
|
2841
|
-
const c = categories3.get(id);
|
|
2842
|
-
return c ? [{ id: c.id, name: c.name, slug: c.slug }] : [];
|
|
2843
|
-
}),
|
|
2844
|
-
createdAt: p.createdAt,
|
|
2845
|
-
updatedAt: p.updatedAt
|
|
2846
|
-
};
|
|
2847
|
-
}
|
|
2848
|
-
var productByCategoryKey = (categorySlug, productSlug) => `category:${categorySlug}#product:${productSlug}`;
|
|
2849
|
-
function productWrites(doc) {
|
|
2850
|
-
return [
|
|
2851
|
-
{ collection: PRODUCTS, key: doc.slug, doc },
|
|
2852
|
-
...doc.categories.map((c) => ({
|
|
2853
|
-
collection: PRODUCTS_BY_CATEGORY,
|
|
2854
|
-
key: productByCategoryKey(c.slug, doc.slug),
|
|
2855
|
-
doc: { ...doc, partitionKey: `category:${c.slug}`, sortKey: `product:${doc.slug}` }
|
|
2856
|
-
}))
|
|
2857
|
-
];
|
|
2858
|
-
}
|
|
2859
|
-
function customerSortKey(o) {
|
|
2860
|
-
return `order:${String(Number.MAX_SAFE_INTEGER - new Date(String(o.createdAt)).getTime()).padStart(16, "0")}:${o.orderNumber}`;
|
|
2861
|
-
}
|
|
2862
|
-
function buildOrderDoc(order, history) {
|
|
2863
|
-
return {
|
|
2864
|
-
...order,
|
|
2865
|
-
history: history.map((h) => ({
|
|
2866
|
-
fromStatus: h.fromStatus,
|
|
2867
|
-
toStatus: h.toStatus,
|
|
2868
|
-
actor: h.actor,
|
|
2869
|
-
note: h.note,
|
|
2870
|
-
timestamp: String(h.timestamp)
|
|
2871
|
-
}))
|
|
2872
|
-
};
|
|
2873
|
-
}
|
|
2874
|
-
function orderWrites(doc) {
|
|
2875
|
-
const writes = [{ collection: ORDERS, key: doc.orderNumber, doc }];
|
|
2876
|
-
if (doc.customerId) {
|
|
2877
|
-
const sortKey = customerSortKey(doc);
|
|
2878
|
-
writes.push({
|
|
2879
|
-
collection: ORDERS_BY_CUSTOMER,
|
|
2880
|
-
key: `customer:${doc.customerId}#${sortKey}`,
|
|
2881
|
-
doc: { ...doc, partitionKey: `customer:${doc.customerId}`, sortKey }
|
|
2882
|
-
});
|
|
2883
|
-
}
|
|
2884
|
-
return writes;
|
|
2885
|
-
}
|
|
2886
|
-
function buildCustomerProfile(c) {
|
|
2887
|
-
const { orderCount, totalSpentMinor } = c;
|
|
2888
|
-
return {
|
|
2889
|
-
customerId: c.id,
|
|
2890
|
-
orderCount,
|
|
2891
|
-
totalSpentMinor,
|
|
2892
|
-
segment: totalSpentMinor > 1e5 ? "vip" : orderCount > 3 ? "returning" : orderCount > 0 ? "active" : "new",
|
|
2893
|
-
createdAt: String(c.createdAt)
|
|
2894
|
-
};
|
|
2895
|
-
}
|
|
2896
|
-
var partitioned = (doc) => {
|
|
2897
|
-
const { partitionKey, sortKey } = doc;
|
|
2898
|
-
return `${String(partitionKey)}#${String(sortKey)}`;
|
|
2899
|
-
};
|
|
2900
|
-
var KEY_OF = {
|
|
2901
|
-
[CATEGORIES]: (doc) => String(doc.slug),
|
|
2902
|
-
[PRODUCTS]: (doc) => String(doc.slug),
|
|
2903
|
-
[PRODUCTS_BY_CATEGORY]: partitioned,
|
|
2904
|
-
[ORDERS]: (doc) => String(doc.orderNumber),
|
|
2905
|
-
[ORDERS_BY_CUSTOMER]: partitioned,
|
|
2906
|
-
[CUSTOMER_PROFILES]: (doc) => String(doc.customerId)
|
|
2907
|
-
};
|
|
2908
|
-
function buildSearchDoc(p) {
|
|
2909
|
-
return {
|
|
2910
|
-
id: p.id,
|
|
2911
|
-
type: "product",
|
|
2912
|
-
fields: {
|
|
2913
|
-
slug: p.slug,
|
|
2914
|
-
name: p.name,
|
|
2915
|
-
description: p.description,
|
|
2916
|
-
status: p.status,
|
|
2917
|
-
categoryIds: p.categoryIds,
|
|
2918
|
-
variants: p.variants.map((v) => ({ sku: v.sku, name: v.name, priceMinor: v.priceMinor }))
|
|
2919
|
-
}
|
|
2920
|
-
};
|
|
2921
|
-
}
|
|
2922
|
-
|
|
2923
|
-
// src/handlers/derived.ts
|
|
2924
|
-
async function subscribeDerived(eventBus, handlers) {
|
|
2925
|
-
for (const h of handlers) {
|
|
2926
|
-
const pattern = h.types.length === 1 ? h.types[0] : [...h.types];
|
|
2927
|
-
await eventBus.subscribe(pattern, h.handle, { name: h.name, derived: true });
|
|
2928
|
-
}
|
|
2929
|
-
}
|
|
2930
|
-
|
|
2931
|
-
// src/handlers/projections/category-projection.ts
|
|
2932
3019
|
function categoryProjection(deps) {
|
|
2933
3020
|
const { documentStore, logger, storeId, repos } = deps;
|
|
2934
3021
|
const onUpsert = async (event) => {
|
|
@@ -2991,8 +3078,8 @@ async function categoriesOf(tx, repos, ids) {
|
|
|
2991
3078
|
async function loadProduct(tx, repos, productId) {
|
|
2992
3079
|
const product = await repos.product.findById(tx, productId);
|
|
2993
3080
|
if (!product) return null;
|
|
2994
|
-
const
|
|
2995
|
-
return { snapshot
|
|
3081
|
+
const snapshot = await productSnapshot(tx, repos, product);
|
|
3082
|
+
return { snapshot, categories: await categoriesOf(tx, repos, snapshot.categoryIds) };
|
|
2996
3083
|
}
|
|
2997
3084
|
async function loadOrderDoc(tx, repos, orderId) {
|
|
2998
3085
|
const order = await repos.order.findById(tx, orderId);
|
|
@@ -3203,15 +3290,46 @@ async function registerInventoryProjection(deps) {
|
|
|
3203
3290
|
}
|
|
3204
3291
|
|
|
3205
3292
|
// src/handlers/side-effects/email-handler.ts
|
|
3293
|
+
import { v7 as uuidv73 } from "uuid";
|
|
3206
3294
|
import {
|
|
3207
3295
|
EVT_CART_ABANDONED,
|
|
3208
3296
|
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED2,
|
|
3297
|
+
EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
|
|
3209
3298
|
EVT_ORDER_PAID as EVT_ORDER_PAID3,
|
|
3210
3299
|
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2
|
|
3211
3300
|
} from "@nymbalhq/types";
|
|
3212
3301
|
var ORDER_PAID_EMAIL = "email:order-paid";
|
|
3213
3302
|
async function registerEmailHandler(deps) {
|
|
3214
|
-
const { eventBus, email, logger, processedEventRepo, orderRepo,
|
|
3303
|
+
const { eventBus, email, logger, processedEventRepo, orderRepo, orderAccessKeyRepo } = deps;
|
|
3304
|
+
const { storeName, storeUrl } = deps;
|
|
3305
|
+
async function orderLink(base, order) {
|
|
3306
|
+
const { key, hash } = mintOrderKey();
|
|
3307
|
+
await orderAccessKeyRepo.store.transaction(
|
|
3308
|
+
(tx) => orderAccessKeyRepo.insert(tx, {
|
|
3309
|
+
id: uuidv73(),
|
|
3310
|
+
orderId: order.id,
|
|
3311
|
+
keyHash: hash,
|
|
3312
|
+
purpose: "email",
|
|
3313
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
3314
|
+
})
|
|
3315
|
+
);
|
|
3316
|
+
const orderUrl = `${base}/order/${encodeURIComponent(order.orderNumber)}?key=${key}`;
|
|
3317
|
+
return { orderUrl, orderLink: `
|
|
3318
|
+
|
|
3319
|
+
View your order: ${orderUrl}` };
|
|
3320
|
+
}
|
|
3321
|
+
async function sendOrderPlaced(order) {
|
|
3322
|
+
await email.sendTransactional({
|
|
3323
|
+
template: "order-placed",
|
|
3324
|
+
to: order.email,
|
|
3325
|
+
vars: {
|
|
3326
|
+
orderNumber: order.orderNumber,
|
|
3327
|
+
customerName: order.billingAddress.firstName,
|
|
3328
|
+
totalFormatted: formatMoney(order.totalMinor, order.currency),
|
|
3329
|
+
...storeUrl !== void 0 && await orderLink(storeUrl, order)
|
|
3330
|
+
}
|
|
3331
|
+
});
|
|
3332
|
+
}
|
|
3215
3333
|
const onOrderPaid = async (event) => {
|
|
3216
3334
|
const { orderId } = event.payload;
|
|
3217
3335
|
const { store } = processedEventRepo;
|
|
@@ -3221,19 +3339,20 @@ async function registerEmailHandler(deps) {
|
|
|
3221
3339
|
logger.warn({ orderId, eventId: event.id }, "email handler: paid order not found");
|
|
3222
3340
|
return;
|
|
3223
3341
|
}
|
|
3224
|
-
await
|
|
3225
|
-
template: "order-placed",
|
|
3226
|
-
to: order.email,
|
|
3227
|
-
vars: {
|
|
3228
|
-
orderNumber: order.orderNumber,
|
|
3229
|
-
customerName: order.billingAddress.firstName,
|
|
3230
|
-
totalFormatted: formatMoney(order.totalMinor, order.currency)
|
|
3231
|
-
}
|
|
3232
|
-
});
|
|
3342
|
+
await sendOrderPlaced(order);
|
|
3233
3343
|
await store.transaction(
|
|
3234
3344
|
(tx) => processedEventRepo.markProcessed(tx, ORDER_PAID_EMAIL, orderId, /* @__PURE__ */ new Date())
|
|
3235
3345
|
);
|
|
3236
3346
|
};
|
|
3347
|
+
const onConfirmationResendRequested = async (event) => {
|
|
3348
|
+
const { orderId } = event.payload;
|
|
3349
|
+
const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId));
|
|
3350
|
+
if (order === null) {
|
|
3351
|
+
logger.warn({ orderId, eventId: event.id }, "email handler: resent order not found");
|
|
3352
|
+
return;
|
|
3353
|
+
}
|
|
3354
|
+
await sendOrderPlaced(order);
|
|
3355
|
+
};
|
|
3237
3356
|
const onOrderShipped = async (event) => {
|
|
3238
3357
|
logger.debug({ orderId: event.payload.orderId }, "email handler: order shipped");
|
|
3239
3358
|
};
|
|
@@ -3250,6 +3369,15 @@ async function registerEmailHandler(deps) {
|
|
|
3250
3369
|
await eventBus.subscribe(EVT_ORDER_PAID3, onOrderPaid, {
|
|
3251
3370
|
name: "email-order-paid"
|
|
3252
3371
|
});
|
|
3372
|
+
await eventBus.subscribe(
|
|
3373
|
+
EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
|
|
3374
|
+
withIdempotency(
|
|
3375
|
+
"email:order-confirmation-resend",
|
|
3376
|
+
onConfirmationResendRequested,
|
|
3377
|
+
{ repo: processedEventRepo, logger }
|
|
3378
|
+
),
|
|
3379
|
+
{ name: "email-order-confirmation-resend" }
|
|
3380
|
+
);
|
|
3253
3381
|
await eventBus.subscribe(
|
|
3254
3382
|
EVT_ORDER_SHIPPED2,
|
|
3255
3383
|
withIdempotency("email:order-shipped", onOrderShipped, {
|
|
@@ -3286,11 +3414,11 @@ function searchHandler(deps) {
|
|
|
3286
3414
|
const { search: search2, repos } = deps;
|
|
3287
3415
|
const onUpsert = async (event) => {
|
|
3288
3416
|
const { id } = event.payload.product;
|
|
3289
|
-
const
|
|
3417
|
+
const snapshot = await repos.product.store.read(async (tx) => {
|
|
3290
3418
|
const product = await repos.product.findById(tx, id);
|
|
3291
3419
|
return product ? productSnapshot(tx, repos, product) : null;
|
|
3292
3420
|
});
|
|
3293
|
-
if (
|
|
3421
|
+
if (snapshot) await search2.index([buildSearchDoc(snapshot)]);
|
|
3294
3422
|
else await search2.remove([id]);
|
|
3295
3423
|
};
|
|
3296
3424
|
const onDelete = async (event) => {
|
|
@@ -3332,9 +3460,127 @@ async function registerReviewsHandler(deps) {
|
|
|
3332
3460
|
);
|
|
3333
3461
|
}
|
|
3334
3462
|
|
|
3463
|
+
// src/handlers/side-effects/alert-handler.ts
|
|
3464
|
+
import {
|
|
3465
|
+
EVT_ALERT_REQUESTED,
|
|
3466
|
+
EVT_PRODUCT_RESTOCKED,
|
|
3467
|
+
EVT_PRODUCT_VARIANT_PRICE_CHANGED
|
|
3468
|
+
} from "@nymbalhq/types";
|
|
3469
|
+
var HANDLER = "email:alert";
|
|
3470
|
+
function links(row, product) {
|
|
3471
|
+
const token = (value) => encodeURIComponent(value);
|
|
3472
|
+
return {
|
|
3473
|
+
confirmUrl: `${row.origin}/alerts/confirm?token=${token(row.confirmToken)}`,
|
|
3474
|
+
unsubscribeUrl: `${row.origin}/alerts/unsubscribe?token=${token(row.unsubscribeToken)}`,
|
|
3475
|
+
productUrl: `${row.origin}/product/${encodeURIComponent(product.slug)}`
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
async function registerAlertHandler(deps) {
|
|
3479
|
+
const { eventBus, email, logger, repos, alerts, storeName } = deps;
|
|
3480
|
+
const { store } = repos.processedEvent;
|
|
3481
|
+
const onRequested = async (event) => {
|
|
3482
|
+
const key = `${event.id}:${event.payload.subscriptionId}`;
|
|
3483
|
+
const found = await store.read(async (tx) => {
|
|
3484
|
+
if (await repos.processedEvent.seen(tx, HANDLER, key)) return null;
|
|
3485
|
+
const row2 = await repos.alertSubscription.findById(tx, event.payload.subscriptionId);
|
|
3486
|
+
if (row2 === null || row2.status !== "pending") return null;
|
|
3487
|
+
const product2 = await repos.product.findById(tx, row2.productId);
|
|
3488
|
+
return product2 === null ? null : { row: row2, product: product2 };
|
|
3489
|
+
});
|
|
3490
|
+
if (found === null) return;
|
|
3491
|
+
const { row, product } = found;
|
|
3492
|
+
const { confirmUrl, unsubscribeUrl, productUrl } = links(row, product);
|
|
3493
|
+
await email.sendTransactional({
|
|
3494
|
+
template: row.kind === "price_drop" ? "alert-confirm-price-drop" : "alert-confirm",
|
|
3495
|
+
to: row.email,
|
|
3496
|
+
vars: { storeName, productName: product.name, productUrl, confirmUrl, unsubscribeUrl }
|
|
3497
|
+
});
|
|
3498
|
+
await store.transaction(
|
|
3499
|
+
(tx) => repos.processedEvent.markProcessed(tx, HANDLER, key, /* @__PURE__ */ new Date())
|
|
3500
|
+
);
|
|
3501
|
+
};
|
|
3502
|
+
async function fanOut(event, rows, what, message) {
|
|
3503
|
+
const failed = [];
|
|
3504
|
+
for (const row of rows) {
|
|
3505
|
+
const key = `${event.id}:${row.id}`;
|
|
3506
|
+
if (await store.read((tx) => repos.processedEvent.seen(tx, HANDLER, key))) continue;
|
|
3507
|
+
try {
|
|
3508
|
+
await email.sendTransactional({ ...message(row), to: row.email });
|
|
3509
|
+
await store.transaction(async (tx) => {
|
|
3510
|
+
await repos.processedEvent.markProcessed(tx, HANDLER, key, /* @__PURE__ */ new Date());
|
|
3511
|
+
await alerts.recordSent(tx, row, event);
|
|
3512
|
+
});
|
|
3513
|
+
} catch (err) {
|
|
3514
|
+
failed.push(row.id);
|
|
3515
|
+
logger.warn(
|
|
3516
|
+
{ err, subscriptionId: row.id, eventId: event.id },
|
|
3517
|
+
`${what.alert} alert failed; the subscription stays active until a retry or the next ${what.next}`
|
|
3518
|
+
);
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
if (failed.length > 0) {
|
|
3522
|
+
throw new Error(
|
|
3523
|
+
`${what.alert} alerts for event ${event.id} failed for subscriptions ${failed.join(", ")}`
|
|
3524
|
+
);
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
const onRestocked = async (event) => {
|
|
3528
|
+
const { variantId, productId } = event.payload;
|
|
3529
|
+
const { rows, product } = await store.read(async (tx) => ({
|
|
3530
|
+
rows: await repos.alertSubscription.listActive(tx, variantId, "back_in_stock"),
|
|
3531
|
+
product: await repos.product.findById(tx, productId)
|
|
3532
|
+
}));
|
|
3533
|
+
if (product === null) return;
|
|
3534
|
+
await fanOut(event, rows, { alert: "back-in-stock", next: "restock" }, (row) => {
|
|
3535
|
+
const { productUrl, unsubscribeUrl } = links(row, product);
|
|
3536
|
+
return {
|
|
3537
|
+
template: "alert-back-in-stock",
|
|
3538
|
+
vars: { storeName, productName: product.name, productUrl, unsubscribeUrl }
|
|
3539
|
+
};
|
|
3540
|
+
});
|
|
3541
|
+
};
|
|
3542
|
+
const onPriceChanged = async (event) => {
|
|
3543
|
+
const { variantId, productId, previousPriceMinor, priceMinor, currency } = event.payload;
|
|
3544
|
+
if (priceMinor >= previousPriceMinor) return;
|
|
3545
|
+
const { rows, product } = await store.read(async (tx) => ({
|
|
3546
|
+
rows: await repos.alertSubscription.listActive(tx, variantId, "price_drop"),
|
|
3547
|
+
product: await repos.product.findById(tx, productId)
|
|
3548
|
+
}));
|
|
3549
|
+
if (product === null) return;
|
|
3550
|
+
const due = rows.filter(
|
|
3551
|
+
(row) => row.baselinePriceMinor !== null && priceMinor < row.baselinePriceMinor
|
|
3552
|
+
);
|
|
3553
|
+
const previousPriceFormatted = formatMoney(previousPriceMinor, currency);
|
|
3554
|
+
const priceFormatted = formatMoney(priceMinor, currency);
|
|
3555
|
+
await fanOut(event, due, { alert: "price-drop", next: "drop" }, (row) => {
|
|
3556
|
+
const { productUrl, unsubscribeUrl } = links(row, product);
|
|
3557
|
+
return {
|
|
3558
|
+
template: "alert-price-drop",
|
|
3559
|
+
vars: {
|
|
3560
|
+
storeName,
|
|
3561
|
+
productName: product.name,
|
|
3562
|
+
productUrl,
|
|
3563
|
+
unsubscribeUrl,
|
|
3564
|
+
previousPriceFormatted,
|
|
3565
|
+
priceFormatted
|
|
3566
|
+
}
|
|
3567
|
+
};
|
|
3568
|
+
});
|
|
3569
|
+
};
|
|
3570
|
+
await eventBus.subscribe(EVT_ALERT_REQUESTED, onRequested, {
|
|
3571
|
+
name: "email-alert-requested"
|
|
3572
|
+
});
|
|
3573
|
+
await eventBus.subscribe(EVT_PRODUCT_RESTOCKED, onRestocked, {
|
|
3574
|
+
name: "email-alert-back-in-stock"
|
|
3575
|
+
});
|
|
3576
|
+
await eventBus.subscribe(EVT_PRODUCT_VARIANT_PRICE_CHANGED, onPriceChanged, {
|
|
3577
|
+
name: "email-alert-price-drop"
|
|
3578
|
+
});
|
|
3579
|
+
}
|
|
3580
|
+
|
|
3335
3581
|
// src/handlers/register.ts
|
|
3336
3582
|
async function registerHandlers(deps) {
|
|
3337
|
-
const { config, eventBus, documentStore, repos, adapters, logger } = deps;
|
|
3583
|
+
const { config, eventBus, documentStore, repos, adapters, alerts, logger } = deps;
|
|
3338
3584
|
const handlerLogger = logger.child({ component: "handlers" });
|
|
3339
3585
|
await registerCategoryProjection({
|
|
3340
3586
|
eventBus,
|
|
@@ -3373,12 +3619,27 @@ async function registerHandlers(deps) {
|
|
|
3373
3619
|
currency: config.store.currency,
|
|
3374
3620
|
repos
|
|
3375
3621
|
});
|
|
3622
|
+
await registerRecentlyViewedProjection({
|
|
3623
|
+
eventBus,
|
|
3624
|
+
documentStore,
|
|
3625
|
+
logger: handlerLogger.child({ projection: "recently-viewed" })
|
|
3626
|
+
});
|
|
3376
3627
|
await registerEmailHandler({
|
|
3377
3628
|
eventBus,
|
|
3378
3629
|
email: adapters.email,
|
|
3379
3630
|
logger: handlerLogger.child({ handler: "email" }),
|
|
3380
3631
|
processedEventRepo: repos.processedEvent,
|
|
3381
3632
|
orderRepo: repos.order,
|
|
3633
|
+
orderAccessKeyRepo: repos.orderAccessKey,
|
|
3634
|
+
storeName: config.store.name,
|
|
3635
|
+
...config.store.url !== void 0 && { storeUrl: config.store.url }
|
|
3636
|
+
});
|
|
3637
|
+
await registerAlertHandler({
|
|
3638
|
+
eventBus,
|
|
3639
|
+
email: adapters.email,
|
|
3640
|
+
logger: handlerLogger.child({ handler: "alert" }),
|
|
3641
|
+
repos,
|
|
3642
|
+
alerts,
|
|
3382
3643
|
storeName: config.store.name
|
|
3383
3644
|
});
|
|
3384
3645
|
await registerSearchHandler({
|
|
@@ -3399,1849 +3660,17 @@ async function registerHandlers(deps) {
|
|
|
3399
3660
|
import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
|
|
3400
3661
|
import { ConfigError as ConfigError2 } from "@nymbalhq/types";
|
|
3401
3662
|
|
|
3402
|
-
// src/
|
|
3403
|
-
import {
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
ValidationError as ValidationError2
|
|
3412
|
-
} from "@nymbalhq/types";
|
|
3413
|
-
async function snapshot(tx, repos, product) {
|
|
3414
|
-
const [variants3, categoryIds] = await Promise.all([
|
|
3415
|
-
repos.variant.findByProduct(tx, product.id),
|
|
3416
|
-
repos.productCategory.listCategoriesForProduct(tx, product.id)
|
|
3417
|
-
]);
|
|
3418
|
-
return { ...product, variants: variants3, categoryIds };
|
|
3419
|
-
}
|
|
3420
|
-
function createProductService(deps) {
|
|
3421
|
-
const { store, repos, publisher } = deps;
|
|
3422
|
-
async function requireProduct(tx, id) {
|
|
3423
|
-
const product = await repos.product.findById(tx, id);
|
|
3424
|
-
if (!product) throw new NotFoundError("product", id);
|
|
3425
|
-
return product;
|
|
3426
|
-
}
|
|
3427
|
-
return {
|
|
3428
|
-
async create(input) {
|
|
3429
|
-
audit.note("product.create");
|
|
3430
|
-
if (!input.slug.trim()) throw new ValidationError2("Product slug is required");
|
|
3431
|
-
if (!input.name.trim()) throw new ValidationError2("Product name is required");
|
|
3432
|
-
const existing = await store.read((tx) => repos.product.findBySlug(tx, input.slug));
|
|
3433
|
-
if (existing) {
|
|
3434
|
-
throw new ValidationError2(`Product slug already exists: ${input.slug}`, {
|
|
3435
|
-
context: { slug: input.slug }
|
|
3436
|
-
});
|
|
3437
|
-
}
|
|
3438
|
-
return store.transaction(async (tx) => {
|
|
3439
|
-
const now = /* @__PURE__ */ new Date();
|
|
3440
|
-
const productId = uuidv73();
|
|
3441
|
-
audit.note("product.create", [{ type: "product", id: productId }]);
|
|
3442
|
-
const insert = {
|
|
3443
|
-
id: productId,
|
|
3444
|
-
slug: input.slug,
|
|
3445
|
-
name: input.name,
|
|
3446
|
-
...input.description !== void 0 && { description: input.description },
|
|
3447
|
-
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
3448
|
-
...input.status !== void 0 && { status: input.status },
|
|
3449
|
-
...input.type !== void 0 && { type: input.type },
|
|
3450
|
-
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
3451
|
-
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
3452
|
-
...input.media !== void 0 && { media: input.media },
|
|
3453
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
3454
|
-
createdAt: now,
|
|
3455
|
-
updatedAt: now
|
|
3456
|
-
};
|
|
3457
|
-
await repos.product.insert(tx, insert);
|
|
3458
|
-
const variantRows = [];
|
|
3459
|
-
for (const v of input.variants ?? []) {
|
|
3460
|
-
const id = v.id ?? uuidv73();
|
|
3461
|
-
const vi = {
|
|
3462
|
-
...v,
|
|
3463
|
-
id,
|
|
3464
|
-
productId,
|
|
3465
|
-
createdAt: now,
|
|
3466
|
-
updatedAt: now
|
|
3467
|
-
};
|
|
3468
|
-
await repos.variant.insert(tx, vi);
|
|
3469
|
-
const stored = await repos.variant.findById(tx, id);
|
|
3470
|
-
if (stored) variantRows.push(stored);
|
|
3471
|
-
}
|
|
3472
|
-
for (const categoryId of input.categoryIds ?? []) {
|
|
3473
|
-
await repos.productCategory.attach(tx, productId, categoryId);
|
|
3474
|
-
}
|
|
3475
|
-
const created = await requireProduct(tx, productId);
|
|
3476
|
-
const snap = {
|
|
3477
|
-
...created,
|
|
3478
|
-
variants: variantRows,
|
|
3479
|
-
categoryIds: input.categoryIds ?? []
|
|
3480
|
-
};
|
|
3481
|
-
await publisher.publish(EVT_PRODUCT_CREATED3, { product: snap });
|
|
3482
|
-
return snap;
|
|
3483
|
-
});
|
|
3484
|
-
},
|
|
3485
|
-
async update(id, input) {
|
|
3486
|
-
return store.transaction(async (tx) => {
|
|
3487
|
-
audit.note("product.update", [{ type: "product", id }]);
|
|
3488
|
-
const product = await requireProduct(tx, id);
|
|
3489
|
-
const now = /* @__PURE__ */ new Date();
|
|
3490
|
-
const updateInput = {
|
|
3491
|
-
...input.name !== void 0 && { name: input.name },
|
|
3492
|
-
...input.description !== void 0 && { description: input.description },
|
|
3493
|
-
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
3494
|
-
...input.status !== void 0 && { status: input.status },
|
|
3495
|
-
...input.type !== void 0 && { type: input.type },
|
|
3496
|
-
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
3497
|
-
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
3498
|
-
...input.media !== void 0 && { media: input.media },
|
|
3499
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
3500
|
-
updatedAt: now
|
|
3501
|
-
};
|
|
3502
|
-
await repos.product.update(tx, product.id, updateInput);
|
|
3503
|
-
if (input.categoryIds) {
|
|
3504
|
-
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
3505
|
-
for (const categoryId of input.categoryIds) {
|
|
3506
|
-
await repos.productCategory.attach(tx, product.id, categoryId);
|
|
3507
|
-
}
|
|
3508
|
-
}
|
|
3509
|
-
const snap = await snapshot(tx, repos, await requireProduct(tx, product.id));
|
|
3510
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3511
|
-
return snap;
|
|
3512
|
-
});
|
|
3513
|
-
},
|
|
3514
|
-
async delete(id) {
|
|
3515
|
-
await store.transaction(async (tx) => {
|
|
3516
|
-
audit.note("product.delete", [{ type: "product", id }]);
|
|
3517
|
-
const product = await requireProduct(tx, id);
|
|
3518
|
-
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
3519
|
-
const variants3 = await repos.variant.findByProduct(tx, product.id);
|
|
3520
|
-
for (const v of variants3) await repos.variant.delete(tx, v.id);
|
|
3521
|
-
await repos.product.delete(tx, product.id);
|
|
3522
|
-
await publisher.publish(EVT_PRODUCT_DELETED3, {
|
|
3523
|
-
productId: product.id,
|
|
3524
|
-
slug: product.slug
|
|
3525
|
-
});
|
|
3526
|
-
});
|
|
3527
|
-
},
|
|
3528
|
-
async publish(id) {
|
|
3529
|
-
await store.transaction(async (tx) => {
|
|
3530
|
-
audit.note("product.publish", [{ type: "product", id }]);
|
|
3531
|
-
const product = await requireProduct(tx, id);
|
|
3532
|
-
if (product.status === "active") return;
|
|
3533
|
-
await repos.product.setStatus(tx, product.id, "active", /* @__PURE__ */ new Date());
|
|
3534
|
-
await publisher.publish(EVT_PRODUCT_PUBLISHED, {
|
|
3535
|
-
productId: product.id,
|
|
3536
|
-
slug: product.slug
|
|
3537
|
-
});
|
|
3538
|
-
const fresh = await requireProduct(tx, product.id);
|
|
3539
|
-
const snap = await snapshot(tx, repos, fresh);
|
|
3540
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3541
|
-
});
|
|
3542
|
-
},
|
|
3543
|
-
async unpublish(id) {
|
|
3544
|
-
await store.transaction(async (tx) => {
|
|
3545
|
-
audit.note("product.unpublish", [{ type: "product", id }]);
|
|
3546
|
-
const product = await requireProduct(tx, id);
|
|
3547
|
-
if (product.status === "draft") return;
|
|
3548
|
-
await repos.product.setStatus(tx, product.id, "draft", /* @__PURE__ */ new Date());
|
|
3549
|
-
await publisher.publish(EVT_PRODUCT_UNPUBLISHED, {
|
|
3550
|
-
productId: product.id,
|
|
3551
|
-
slug: product.slug
|
|
3552
|
-
});
|
|
3553
|
-
const fresh = await requireProduct(tx, product.id);
|
|
3554
|
-
const snap = await snapshot(tx, repos, fresh);
|
|
3555
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3556
|
-
});
|
|
3557
|
-
},
|
|
3558
|
-
async getById(id) {
|
|
3559
|
-
return store.read(async (tx) => snapshot(tx, repos, await requireProduct(tx, id)));
|
|
3560
|
-
},
|
|
3561
|
-
async getBySlug(slug) {
|
|
3562
|
-
return store.read(async (tx) => {
|
|
3563
|
-
const product = await repos.product.findBySlug(tx, slug);
|
|
3564
|
-
if (!product) throw new NotFoundError("product", slug);
|
|
3565
|
-
return snapshot(tx, repos, product);
|
|
3566
|
-
});
|
|
3567
|
-
},
|
|
3568
|
-
async list(opts = {}) {
|
|
3569
|
-
return store.read(async (tx) => {
|
|
3570
|
-
const products3 = await repos.product.list(tx, opts);
|
|
3571
|
-
const out = [];
|
|
3572
|
-
for (const p of products3) {
|
|
3573
|
-
out.push(await snapshot(tx, repos, p));
|
|
3574
|
-
}
|
|
3575
|
-
return out;
|
|
3576
|
-
});
|
|
3663
|
+
// src/read-models/index.ts
|
|
3664
|
+
import { errorText } from "@nymbalhq/types";
|
|
3665
|
+
|
|
3666
|
+
// src/read-models/catalogue.ts
|
|
3667
|
+
function snapshotsOf({ repos }) {
|
|
3668
|
+
return async (tx, page) => {
|
|
3669
|
+
const out = [];
|
|
3670
|
+
for (const p of await repos.product.listPage(tx, page)) {
|
|
3671
|
+
out.push(await productSnapshot(tx, repos, p));
|
|
3577
3672
|
}
|
|
3578
|
-
|
|
3579
|
-
}
|
|
3580
|
-
|
|
3581
|
-
// src/services/category-service.ts
|
|
3582
|
-
import { v7 as uuidv74 } from "uuid";
|
|
3583
|
-
import {
|
|
3584
|
-
EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3,
|
|
3585
|
-
EVT_CATEGORY_UPDATED as EVT_CATEGORY_UPDATED3,
|
|
3586
|
-
EVT_CATEGORY_DELETED as EVT_CATEGORY_DELETED3,
|
|
3587
|
-
NotFoundError as NotFoundError2,
|
|
3588
|
-
ValidationError as ValidationError3
|
|
3589
|
-
} from "@nymbalhq/types";
|
|
3590
|
-
function createCategoryService(deps) {
|
|
3591
|
-
const { repos, publisher } = deps;
|
|
3592
|
-
const { store } = repos.category;
|
|
3593
|
-
return {
|
|
3594
|
-
async list() {
|
|
3595
|
-
return store.read((tx) => repos.category.list(tx));
|
|
3596
|
-
},
|
|
3597
|
-
async getById(id) {
|
|
3598
|
-
const c = await store.read((tx) => repos.category.findById(tx, id));
|
|
3599
|
-
if (!c) throw new NotFoundError2("category", id);
|
|
3600
|
-
return c;
|
|
3601
|
-
},
|
|
3602
|
-
async getBySlug(slug) {
|
|
3603
|
-
const c = await store.read((tx) => repos.category.findBySlug(tx, slug));
|
|
3604
|
-
if (!c) throw new NotFoundError2("category", slug);
|
|
3605
|
-
return c;
|
|
3606
|
-
},
|
|
3607
|
-
async create(input) {
|
|
3608
|
-
audit.note("category.create");
|
|
3609
|
-
if (!input.slug.trim()) throw new ValidationError3("Category slug is required");
|
|
3610
|
-
return store.transaction(async (tx) => {
|
|
3611
|
-
if (await repos.category.findBySlug(tx, input.slug)) {
|
|
3612
|
-
throw new ValidationError3(`Category slug already exists: ${input.slug}`);
|
|
3613
|
-
}
|
|
3614
|
-
const now = /* @__PURE__ */ new Date();
|
|
3615
|
-
const id = uuidv74();
|
|
3616
|
-
audit.note("category.create", [{ type: "category", id }]);
|
|
3617
|
-
const category = {
|
|
3618
|
-
id,
|
|
3619
|
-
parentId: input.parentId ?? null,
|
|
3620
|
-
slug: input.slug,
|
|
3621
|
-
name: input.name,
|
|
3622
|
-
description: input.description ?? "",
|
|
3623
|
-
position: input.position ?? 0,
|
|
3624
|
-
createdAt: now.toISOString()
|
|
3625
|
-
};
|
|
3626
|
-
await repos.category.insert(tx, { ...category, createdAt: now });
|
|
3627
|
-
await publisher.publish(EVT_CATEGORY_CREATED3, { category });
|
|
3628
|
-
return category;
|
|
3629
|
-
});
|
|
3630
|
-
},
|
|
3631
|
-
async update(id, input) {
|
|
3632
|
-
return store.transaction(async (tx) => {
|
|
3633
|
-
audit.note("category.update", [{ type: "category", id }]);
|
|
3634
|
-
const existing = await repos.category.findById(tx, id);
|
|
3635
|
-
if (!existing) throw new NotFoundError2("category", id);
|
|
3636
|
-
await repos.category.update(tx, id, input);
|
|
3637
|
-
const fresh = await repos.category.findById(tx, id);
|
|
3638
|
-
await publisher.publish(EVT_CATEGORY_UPDATED3, { category: fresh });
|
|
3639
|
-
return fresh;
|
|
3640
|
-
});
|
|
3641
|
-
},
|
|
3642
|
-
async delete(id) {
|
|
3643
|
-
await store.transaction(async (tx) => {
|
|
3644
|
-
audit.note("category.delete", [{ type: "category", id }]);
|
|
3645
|
-
const existing = await repos.category.findById(tx, id);
|
|
3646
|
-
if (!existing) throw new NotFoundError2("category", id);
|
|
3647
|
-
await repos.category.delete(tx, id);
|
|
3648
|
-
await publisher.publish(EVT_CATEGORY_DELETED3, {
|
|
3649
|
-
categoryId: existing.id,
|
|
3650
|
-
slug: existing.slug
|
|
3651
|
-
});
|
|
3652
|
-
});
|
|
3653
|
-
}
|
|
3654
|
-
};
|
|
3655
|
-
}
|
|
3656
|
-
|
|
3657
|
-
// src/services/cart-service.ts
|
|
3658
|
-
import { v7 as uuidv75 } from "uuid";
|
|
3659
|
-
import {
|
|
3660
|
-
EVT_CART_CREATED,
|
|
3661
|
-
EVT_CART_ITEM_ADDED,
|
|
3662
|
-
EVT_CART_ITEM_REMOVED,
|
|
3663
|
-
EVT_CART_UPDATED,
|
|
3664
|
-
NotFoundError as NotFoundError3,
|
|
3665
|
-
ValidationError as ValidationError4
|
|
3666
|
-
} from "@nymbalhq/types";
|
|
3667
|
-
var TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 30;
|
|
3668
|
-
function calcSubtotal(items) {
|
|
3669
|
-
return items.reduce((sum, item) => sum + item.priceMinor * item.qty, 0);
|
|
3670
|
-
}
|
|
3671
|
-
function createCartService(deps) {
|
|
3672
|
-
const { store, carts: carts3, publisher, currency } = deps;
|
|
3673
|
-
const ttlMs = (deps.ttlSeconds ?? TTL_SECONDS_DEFAULT) * 1e3;
|
|
3674
|
-
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
3675
|
-
function live(cart, at) {
|
|
3676
|
-
return cart !== null && Date.parse(cart.expiresAt) > at.getTime();
|
|
3677
|
-
}
|
|
3678
|
-
function written(cart, items, at) {
|
|
3679
|
-
return {
|
|
3680
|
-
...cart,
|
|
3681
|
-
items,
|
|
3682
|
-
subtotalMinor: calcSubtotal(items),
|
|
3683
|
-
updatedAt: at.toISOString(),
|
|
3684
|
-
expiresAt: new Date(at.getTime() + ttlMs).toISOString()
|
|
3685
|
-
};
|
|
3686
|
-
}
|
|
3687
|
-
async function requireCart(tx, token, at) {
|
|
3688
|
-
const cart = await carts3.lock(tx, token);
|
|
3689
|
-
if (!live(cart, at)) throw new NotFoundError3("cart", token);
|
|
3690
|
-
return cart;
|
|
3691
|
-
}
|
|
3692
|
-
async function emitUpdated(cart) {
|
|
3693
|
-
await publisher.publish(EVT_CART_UPDATED, {
|
|
3694
|
-
cartId: cart.token,
|
|
3695
|
-
itemCount: cart.items.reduce((n, i) => n + i.qty, 0),
|
|
3696
|
-
totalMinor: cart.subtotalMinor
|
|
3697
|
-
});
|
|
3698
|
-
}
|
|
3699
|
-
function command(token, change) {
|
|
3700
|
-
return store.transaction(async (tx) => {
|
|
3701
|
-
const at = now();
|
|
3702
|
-
const next = await change(await requireCart(tx, token, at), at);
|
|
3703
|
-
await carts3.put(tx, next);
|
|
3704
|
-
await emitUpdated(next);
|
|
3705
|
-
return next;
|
|
3706
|
-
});
|
|
3707
|
-
}
|
|
3708
|
-
return {
|
|
3709
|
-
async getOrCreate(token, customerId = null) {
|
|
3710
|
-
return store.transaction(async (tx) => {
|
|
3711
|
-
const at = now();
|
|
3712
|
-
const { cart, created } = await carts3.create(tx, {
|
|
3713
|
-
token: token ?? uuidv75(),
|
|
3714
|
-
customerId,
|
|
3715
|
-
items: [],
|
|
3716
|
-
subtotalMinor: 0,
|
|
3717
|
-
currency,
|
|
3718
|
-
expiresAt: new Date(at.getTime() + ttlMs).toISOString(),
|
|
3719
|
-
createdAt: at.toISOString(),
|
|
3720
|
-
updatedAt: at.toISOString()
|
|
3721
|
-
});
|
|
3722
|
-
if (created) {
|
|
3723
|
-
await publisher.publish(EVT_CART_CREATED, { cartId: cart.token, token: cart.token });
|
|
3724
|
-
}
|
|
3725
|
-
return cart;
|
|
3726
|
-
});
|
|
3727
|
-
},
|
|
3728
|
-
async get(token) {
|
|
3729
|
-
const at = now();
|
|
3730
|
-
const cart = await store.read((tx) => carts3.findByToken(tx, token));
|
|
3731
|
-
return live(cart, at) ? cart : null;
|
|
3732
|
-
},
|
|
3733
|
-
async addItem(token, item) {
|
|
3734
|
-
return command(token, async (cart, at) => {
|
|
3735
|
-
const qty = item.qty ?? 1;
|
|
3736
|
-
if (qty <= 0) throw new ValidationError4(`qty must be positive, got ${qty}`);
|
|
3737
|
-
const onCart = cart.items.some((i) => i.variantId === item.variantId);
|
|
3738
|
-
const items = onCart ? cart.items.map((i) => i.variantId === item.variantId ? { ...i, qty: i.qty + qty } : i) : [
|
|
3739
|
-
...cart.items,
|
|
3740
|
-
{
|
|
3741
|
-
variantId: item.variantId,
|
|
3742
|
-
productId: item.productId,
|
|
3743
|
-
productName: item.productName,
|
|
3744
|
-
variantName: item.variantName,
|
|
3745
|
-
priceMinor: item.priceMinor,
|
|
3746
|
-
imageUrl: item.imageUrl,
|
|
3747
|
-
qty
|
|
3748
|
-
}
|
|
3749
|
-
];
|
|
3750
|
-
await publisher.publish(EVT_CART_ITEM_ADDED, {
|
|
3751
|
-
cartId: cart.token,
|
|
3752
|
-
variantId: item.variantId,
|
|
3753
|
-
qty
|
|
3754
|
-
});
|
|
3755
|
-
return written(cart, items, at);
|
|
3756
|
-
});
|
|
3757
|
-
},
|
|
3758
|
-
async updateItemQuantity(token, variantId, qty) {
|
|
3759
|
-
if (qty < 0) throw new ValidationError4(`qty must be non-negative, got ${qty}`);
|
|
3760
|
-
return command(token, async (cart, at) => {
|
|
3761
|
-
if (!cart.items.some((i) => i.variantId === variantId)) {
|
|
3762
|
-
throw new NotFoundError3("cart_item", variantId);
|
|
3763
|
-
}
|
|
3764
|
-
if (qty === 0) {
|
|
3765
|
-
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
3766
|
-
return written(
|
|
3767
|
-
cart,
|
|
3768
|
-
cart.items.filter((i) => i.variantId !== variantId),
|
|
3769
|
-
at
|
|
3770
|
-
);
|
|
3771
|
-
}
|
|
3772
|
-
return written(
|
|
3773
|
-
cart,
|
|
3774
|
-
cart.items.map((i) => i.variantId === variantId ? { ...i, qty } : i),
|
|
3775
|
-
at
|
|
3776
|
-
);
|
|
3777
|
-
});
|
|
3778
|
-
},
|
|
3779
|
-
async removeItem(token, variantId) {
|
|
3780
|
-
return command(token, async (cart, at) => {
|
|
3781
|
-
const items = cart.items.filter((i) => i.variantId !== variantId);
|
|
3782
|
-
if (items.length < cart.items.length) {
|
|
3783
|
-
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
3784
|
-
}
|
|
3785
|
-
return written(cart, items, at);
|
|
3786
|
-
});
|
|
3787
|
-
},
|
|
3788
|
-
async clear(token) {
|
|
3789
|
-
return command(token, async (cart, at) => written(cart, [], at));
|
|
3790
|
-
},
|
|
3791
|
-
async attachCustomer(token, customerId) {
|
|
3792
|
-
return command(token, async (cart, at) => ({ ...written(cart, cart.items, at), customerId }));
|
|
3793
|
-
},
|
|
3794
|
-
async merge(guestToken, customerToken) {
|
|
3795
|
-
return store.transaction(async (tx) => {
|
|
3796
|
-
const at = now();
|
|
3797
|
-
const guest = await carts3.lock(tx, guestToken);
|
|
3798
|
-
if (!live(guest, at)) return requireCart(tx, customerToken, at);
|
|
3799
|
-
const customerCart = await carts3.lock(tx, customerToken);
|
|
3800
|
-
let merged;
|
|
3801
|
-
if (live(customerCart, at)) {
|
|
3802
|
-
const held = customerCart.items;
|
|
3803
|
-
const items = [
|
|
3804
|
-
...held.map((i) => {
|
|
3805
|
-
const g = guest.items.find((x) => x.variantId === i.variantId);
|
|
3806
|
-
return g ? { ...i, qty: Math.max(i.qty, g.qty) } : i;
|
|
3807
|
-
}),
|
|
3808
|
-
...guest.items.filter((g) => !held.some((i) => i.variantId === g.variantId))
|
|
3809
|
-
];
|
|
3810
|
-
merged = written(customerCart, items, at);
|
|
3811
|
-
} else {
|
|
3812
|
-
merged = written({ ...guest, token: customerToken }, guest.items, at);
|
|
3813
|
-
}
|
|
3814
|
-
await carts3.remove(tx, guestToken);
|
|
3815
|
-
await carts3.put(tx, merged);
|
|
3816
|
-
await emitUpdated(merged);
|
|
3817
|
-
return merged;
|
|
3818
|
-
});
|
|
3819
|
-
}
|
|
3820
|
-
};
|
|
3821
|
-
}
|
|
3822
|
-
|
|
3823
|
-
// src/services/customer-service.ts
|
|
3824
|
-
import { v7 as uuidv76 } from "uuid";
|
|
3825
|
-
import {
|
|
3826
|
-
EVT_CUSTOMER_UPDATED as EVT_CUSTOMER_UPDATED2,
|
|
3827
|
-
NotFoundError as NotFoundError4,
|
|
3828
|
-
ValidationError as ValidationError5
|
|
3829
|
-
} from "@nymbalhq/types";
|
|
3830
|
-
function stripPassword(c) {
|
|
3831
|
-
const { passwordHash: _pw, ...rest } = c;
|
|
3832
|
-
return rest;
|
|
3833
|
-
}
|
|
3834
|
-
function createCustomerService(deps) {
|
|
3835
|
-
const { repos, publisher } = deps;
|
|
3836
|
-
const { store } = repos.customer;
|
|
3837
|
-
async function loadOrThrow(tx, id) {
|
|
3838
|
-
const c = await repos.customer.findById(tx, id);
|
|
3839
|
-
if (!c) throw new NotFoundError4("customer", id);
|
|
3840
|
-
return c;
|
|
3841
|
-
}
|
|
3842
|
-
async function publishUpdated(tx, customerId) {
|
|
3843
|
-
const fresh = stripPassword(await loadOrThrow(tx, customerId));
|
|
3844
|
-
await publisher.publish(EVT_CUSTOMER_UPDATED2, {
|
|
3845
|
-
customerId,
|
|
3846
|
-
customer: toCustomerSnapshot(fresh)
|
|
3847
|
-
});
|
|
3848
|
-
return fresh;
|
|
3849
|
-
}
|
|
3850
|
-
return {
|
|
3851
|
-
async getProfile(customerId) {
|
|
3852
|
-
return stripPassword(await store.read((tx) => loadOrThrow(tx, customerId)));
|
|
3853
|
-
},
|
|
3854
|
-
async updateProfile(customerId, patch) {
|
|
3855
|
-
return store.transaction(async (tx) => {
|
|
3856
|
-
audit.note("customer.update", [{ type: "customer", id: customerId }]);
|
|
3857
|
-
await loadOrThrow(tx, customerId);
|
|
3858
|
-
const now = /* @__PURE__ */ new Date();
|
|
3859
|
-
await repos.customer.update(tx, customerId, { ...patch, updatedAt: now });
|
|
3860
|
-
return publishUpdated(tx, customerId);
|
|
3861
|
-
});
|
|
3862
|
-
},
|
|
3863
|
-
async listAddresses(customerId) {
|
|
3864
|
-
const customer = await store.read((tx) => loadOrThrow(tx, customerId));
|
|
3865
|
-
return customer.addresses;
|
|
3866
|
-
},
|
|
3867
|
-
async addAddress(customerId, addr) {
|
|
3868
|
-
return store.transaction(async (tx) => {
|
|
3869
|
-
audit.note("customer.addAddress", [{ type: "customer", id: customerId }]);
|
|
3870
|
-
const customer = await loadOrThrow(tx, customerId);
|
|
3871
|
-
const newAddr = { ...addr, id: uuidv76() };
|
|
3872
|
-
const defaultBilling = newAddr.isDefaultBilling;
|
|
3873
|
-
const defaultShipping = newAddr.isDefaultShipping;
|
|
3874
|
-
const addresses = customer.addresses.map((a) => ({
|
|
3875
|
-
...a,
|
|
3876
|
-
isDefaultBilling: defaultBilling ? false : a.isDefaultBilling,
|
|
3877
|
-
isDefaultShipping: defaultShipping ? false : a.isDefaultShipping
|
|
3878
|
-
}));
|
|
3879
|
-
addresses.push(newAddr);
|
|
3880
|
-
const now = /* @__PURE__ */ new Date();
|
|
3881
|
-
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
3882
|
-
await publishUpdated(tx, customerId);
|
|
3883
|
-
return newAddr;
|
|
3884
|
-
});
|
|
3885
|
-
},
|
|
3886
|
-
async deleteAddress(customerId, addressId) {
|
|
3887
|
-
await store.transaction(async (tx) => {
|
|
3888
|
-
audit.note("customer.removeAddress", [{ type: "customer", id: customerId }]);
|
|
3889
|
-
const customer = await loadOrThrow(tx, customerId);
|
|
3890
|
-
const addresses = customer.addresses.filter((a) => a.id !== addressId);
|
|
3891
|
-
if (addresses.length === customer.addresses.length) {
|
|
3892
|
-
throw new NotFoundError4("address", addressId);
|
|
3893
|
-
}
|
|
3894
|
-
if (!addresses.length) {
|
|
3895
|
-
throw new ValidationError5("Cannot remove last address");
|
|
3896
|
-
}
|
|
3897
|
-
const now = /* @__PURE__ */ new Date();
|
|
3898
|
-
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
3899
|
-
await publishUpdated(tx, customerId);
|
|
3900
|
-
});
|
|
3901
|
-
}
|
|
3902
|
-
};
|
|
3903
|
-
}
|
|
3904
|
-
|
|
3905
|
-
// src/services/auth-service.ts
|
|
3906
|
-
import { v7 as uuidv77 } from "uuid";
|
|
3907
|
-
import bcrypt from "bcryptjs";
|
|
3908
|
-
import { SignJWT, jwtVerify } from "jose";
|
|
3909
|
-
import { createHash } from "crypto";
|
|
3910
|
-
import {
|
|
3911
|
-
AuthError,
|
|
3912
|
-
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3,
|
|
3913
|
-
ValidationError as ValidationError6
|
|
3914
|
-
} from "@nymbalhq/types";
|
|
3915
|
-
var { hash: bcryptHash, compare: bcryptCompare } = bcrypt;
|
|
3916
|
-
function parseDurationToMs(s) {
|
|
3917
|
-
const match = /^(\d+)(ms|s|m|h|d)$/.exec(s);
|
|
3918
|
-
if (!match) throw new ValidationError6(`invalid duration: ${s}`);
|
|
3919
|
-
const qty = Number(match[1]);
|
|
3920
|
-
switch (match[2]) {
|
|
3921
|
-
case "ms":
|
|
3922
|
-
return qty;
|
|
3923
|
-
case "s":
|
|
3924
|
-
return qty * 1e3;
|
|
3925
|
-
case "m":
|
|
3926
|
-
return qty * 60 * 1e3;
|
|
3927
|
-
case "h":
|
|
3928
|
-
return qty * 60 * 60 * 1e3;
|
|
3929
|
-
case "d":
|
|
3930
|
-
return qty * 24 * 60 * 60 * 1e3;
|
|
3931
|
-
/* c8 ignore next 2 -- regex above only matches ms|s|m|h|d, making this unreachable */
|
|
3932
|
-
default:
|
|
3933
|
-
throw new ValidationError6(`invalid duration unit: ${match[2]}`);
|
|
3934
|
-
}
|
|
3935
|
-
}
|
|
3936
|
-
function hashRefresh(token) {
|
|
3937
|
-
return createHash("sha256").update(token).digest("hex");
|
|
3938
|
-
}
|
|
3939
|
-
function stripPassword2(c) {
|
|
3940
|
-
const { passwordHash: _pw, ...rest } = c;
|
|
3941
|
-
return rest;
|
|
3942
|
-
}
|
|
3943
|
-
function createAuthService(deps) {
|
|
3944
|
-
const { repos, publisher, logger, jwtSecret, accessTtl, refreshTtl } = deps;
|
|
3945
|
-
const { store } = repos.customer;
|
|
3946
|
-
const issuer = deps.issuer ?? "nymbal";
|
|
3947
|
-
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
3948
|
-
const accessTtlMs = parseDurationToMs(accessTtl);
|
|
3949
|
-
const refreshTtlMs = parseDurationToMs(refreshTtl);
|
|
3950
|
-
async function mintAccess(customer) {
|
|
3951
|
-
return new SignJWT({
|
|
3952
|
-
sub: customer.id,
|
|
3953
|
-
email: customer.email,
|
|
3954
|
-
roles: customer.roles,
|
|
3955
|
-
type: "access"
|
|
3956
|
-
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setIssuer(issuer).setExpirationTime(new Date(Date.now() + accessTtlMs)).sign(secretKey);
|
|
3957
|
-
}
|
|
3958
|
-
async function mintRefresh(customer, jti) {
|
|
3959
|
-
return new SignJWT({
|
|
3960
|
-
sub: customer.id,
|
|
3961
|
-
email: customer.email,
|
|
3962
|
-
roles: ["customer"],
|
|
3963
|
-
type: "refresh",
|
|
3964
|
-
jti
|
|
3965
|
-
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setJti(jti).setIssuer(issuer).setExpirationTime(new Date(Date.now() + refreshTtlMs)).sign(secretKey);
|
|
3966
|
-
}
|
|
3967
|
-
async function issueTokens(customer) {
|
|
3968
|
-
const jti = uuidv77();
|
|
3969
|
-
const refreshToken = await mintRefresh(customer, jti);
|
|
3970
|
-
await store.transaction(
|
|
3971
|
-
(tx) => repos.refreshToken.insert(tx, {
|
|
3972
|
-
id: jti,
|
|
3973
|
-
customerId: customer.id,
|
|
3974
|
-
tokenHash: hashRefresh(refreshToken),
|
|
3975
|
-
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
3976
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
3977
|
-
})
|
|
3978
|
-
);
|
|
3979
|
-
const accessToken = await mintAccess(customer);
|
|
3980
|
-
return {
|
|
3981
|
-
accessToken,
|
|
3982
|
-
refreshToken,
|
|
3983
|
-
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
3984
|
-
};
|
|
3985
|
-
}
|
|
3986
|
-
return {
|
|
3987
|
-
async register(input) {
|
|
3988
|
-
audit.note("customer.register");
|
|
3989
|
-
if (!input.email.includes("@")) throw new ValidationError6("invalid email");
|
|
3990
|
-
if (input.password.length < 8) throw new ValidationError6("password must be \u2265 8 characters");
|
|
3991
|
-
const email = input.email.toLowerCase();
|
|
3992
|
-
const existing = await store.read((tx) => repos.customer.findByEmail(tx, email));
|
|
3993
|
-
if (existing) {
|
|
3994
|
-
throw new AuthError("invalid_credentials", "An account with this email already exists");
|
|
3995
|
-
}
|
|
3996
|
-
const id = uuidv77();
|
|
3997
|
-
const passwordHash = await bcryptHash(input.password, 10);
|
|
3998
|
-
const now = /* @__PURE__ */ new Date();
|
|
3999
|
-
const customer = await store.transaction(async (tx) => {
|
|
4000
|
-
audit.note("customer.register", [{ type: "customer", id }]);
|
|
4001
|
-
await repos.customer.insert(tx, {
|
|
4002
|
-
id,
|
|
4003
|
-
email,
|
|
4004
|
-
passwordHash,
|
|
4005
|
-
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
4006
|
-
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
4007
|
-
...input.phone !== void 0 && { phone: input.phone },
|
|
4008
|
-
createdAt: now,
|
|
4009
|
-
updatedAt: now
|
|
4010
|
-
});
|
|
4011
|
-
const inserted = await repos.customer.findById(tx, id);
|
|
4012
|
-
if (!inserted) throw new Error("customer disappeared after insert");
|
|
4013
|
-
await publisher.publish(EVT_CUSTOMER_CREATED3, {
|
|
4014
|
-
customerId: id,
|
|
4015
|
-
email,
|
|
4016
|
-
customer: toCustomerSnapshot(inserted)
|
|
4017
|
-
});
|
|
4018
|
-
return inserted;
|
|
4019
|
-
});
|
|
4020
|
-
const tokens = await issueTokens(customer);
|
|
4021
|
-
logger.info({ customerId: id }, "customer registered");
|
|
4022
|
-
return { customer: stripPassword2(customer), tokens };
|
|
4023
|
-
},
|
|
4024
|
-
async login(email, password) {
|
|
4025
|
-
const customer = await store.read((tx) => repos.customer.findByEmail(tx, email.toLowerCase()));
|
|
4026
|
-
if (!customer) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
4027
|
-
const ok = await bcryptCompare(password, customer.passwordHash);
|
|
4028
|
-
if (!ok) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
4029
|
-
const tokens = await issueTokens(customer);
|
|
4030
|
-
logger.info({ customerId: customer.id }, "customer login");
|
|
4031
|
-
return { customer: stripPassword2(customer), tokens };
|
|
4032
|
-
},
|
|
4033
|
-
async refresh(refreshToken) {
|
|
4034
|
-
let verified;
|
|
4035
|
-
try {
|
|
4036
|
-
verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
4037
|
-
} catch {
|
|
4038
|
-
throw new AuthError("token_invalid", "refresh token invalid");
|
|
4039
|
-
}
|
|
4040
|
-
const payload = verified.payload;
|
|
4041
|
-
if (payload.type !== "refresh" || !payload.jti || !payload.sub) {
|
|
4042
|
-
throw new AuthError("token_invalid", "not a refresh token");
|
|
4043
|
-
}
|
|
4044
|
-
const jti = payload.jti;
|
|
4045
|
-
const customerId = payload.sub;
|
|
4046
|
-
const record = await store.read((tx) => repos.refreshToken.findById(tx, jti));
|
|
4047
|
-
if (!record) throw new AuthError("token_invalid", "refresh token unknown");
|
|
4048
|
-
if (record.revokedAt) throw new AuthError("token_invalid", "refresh token revoked");
|
|
4049
|
-
if (record.tokenHash !== hashRefresh(refreshToken)) {
|
|
4050
|
-
await store.transaction((tx) => repos.refreshToken.revokeAllForCustomer(tx, customerId));
|
|
4051
|
-
throw new AuthError("token_invalid", "refresh token mismatch; revoking chain");
|
|
4052
|
-
}
|
|
4053
|
-
const customer = await store.read((tx) => repos.customer.findById(tx, customerId));
|
|
4054
|
-
if (!customer) throw new AuthError("token_invalid", "customer missing");
|
|
4055
|
-
const nextJti = uuidv77();
|
|
4056
|
-
const nextRefresh = await mintRefresh(customer, nextJti);
|
|
4057
|
-
await store.transaction(
|
|
4058
|
-
(tx) => repos.refreshToken.rotate(tx, jti, {
|
|
4059
|
-
id: nextJti,
|
|
4060
|
-
customerId: customer.id,
|
|
4061
|
-
tokenHash: hashRefresh(nextRefresh),
|
|
4062
|
-
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
4063
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
4064
|
-
})
|
|
4065
|
-
);
|
|
4066
|
-
const accessToken = await mintAccess(customer);
|
|
4067
|
-
return {
|
|
4068
|
-
accessToken,
|
|
4069
|
-
refreshToken: nextRefresh,
|
|
4070
|
-
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
4071
|
-
};
|
|
4072
|
-
},
|
|
4073
|
-
async logout(refreshToken) {
|
|
4074
|
-
try {
|
|
4075
|
-
const verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
4076
|
-
const payload = verified.payload;
|
|
4077
|
-
const { jti } = payload;
|
|
4078
|
-
if (jti) await store.transaction((tx) => repos.refreshToken.revoke(tx, jti));
|
|
4079
|
-
} catch {
|
|
4080
|
-
}
|
|
4081
|
-
},
|
|
4082
|
-
async verifyAccessToken(token) {
|
|
4083
|
-
try {
|
|
4084
|
-
const verified = await jwtVerify(token, secretKey, { issuer });
|
|
4085
|
-
const payload = verified.payload;
|
|
4086
|
-
if (payload.type !== "access") throw new AuthError("token_invalid", "not an access token");
|
|
4087
|
-
return payload;
|
|
4088
|
-
} catch (err) {
|
|
4089
|
-
if (err instanceof AuthError) throw err;
|
|
4090
|
-
throw new AuthError("token_invalid", "access token invalid", { cause: err });
|
|
4091
|
-
}
|
|
4092
|
-
},
|
|
4093
|
-
async importCustomer(input) {
|
|
4094
|
-
if (!input.email.includes("@")) throw new ValidationError6("invalid email");
|
|
4095
|
-
const email = input.email.toLowerCase();
|
|
4096
|
-
const customer = await store.transaction(async (tx) => {
|
|
4097
|
-
const existing = await repos.customer.findByEmail(tx, email);
|
|
4098
|
-
if (existing) return existing;
|
|
4099
|
-
const id = uuidv77();
|
|
4100
|
-
audit.note("customer.import", [{ type: "customer", id }]);
|
|
4101
|
-
const now = /* @__PURE__ */ new Date();
|
|
4102
|
-
await repos.customer.insert(tx, {
|
|
4103
|
-
id,
|
|
4104
|
-
email,
|
|
4105
|
-
passwordHash: "IMPORTED_NO_PASSWORD",
|
|
4106
|
-
requiresPasswordReset: true,
|
|
4107
|
-
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
4108
|
-
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
4109
|
-
...input.phone !== void 0 && { phone: input.phone },
|
|
4110
|
-
...input.addresses !== void 0 && { addresses: input.addresses },
|
|
4111
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
4112
|
-
roles: ["customer"],
|
|
4113
|
-
createdAt: now,
|
|
4114
|
-
updatedAt: now
|
|
4115
|
-
});
|
|
4116
|
-
const inserted = await repos.customer.findById(tx, id);
|
|
4117
|
-
if (!inserted) throw new Error("customer disappeared after insert");
|
|
4118
|
-
await publisher.publish(EVT_CUSTOMER_CREATED3, {
|
|
4119
|
-
customerId: id,
|
|
4120
|
-
email,
|
|
4121
|
-
customer: toCustomerSnapshot(inserted)
|
|
4122
|
-
});
|
|
4123
|
-
logger.info({ customerId: id }, "customer imported");
|
|
4124
|
-
return inserted;
|
|
4125
|
-
});
|
|
4126
|
-
return stripPassword2(customer);
|
|
4127
|
-
}
|
|
4128
|
-
};
|
|
4129
|
-
}
|
|
4130
|
-
|
|
4131
|
-
// src/services/order-service.ts
|
|
4132
|
-
import { v7 as uuidv78 } from "uuid";
|
|
4133
|
-
import {
|
|
4134
|
-
EVT_ORDER_CANCELLED as EVT_ORDER_CANCELLED2,
|
|
4135
|
-
EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED3,
|
|
4136
|
-
EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
|
|
4137
|
-
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED3,
|
|
4138
|
-
EVT_ORDER_STATUS_CHANGED as EVT_ORDER_STATUS_CHANGED2,
|
|
4139
|
-
NotFoundError as NotFoundError5,
|
|
4140
|
-
OrderConflictError,
|
|
4141
|
-
StatusTransitionError,
|
|
4142
|
-
ValidationError as ValidationError7,
|
|
4143
|
-
assertOrderTransition
|
|
4144
|
-
} from "@nymbalhq/types";
|
|
4145
|
-
function createOrderService(deps) {
|
|
4146
|
-
const { store, repos, publisher } = deps;
|
|
4147
|
-
async function requireOrder(tx, id) {
|
|
4148
|
-
const order = await repos.order.findById(tx, id);
|
|
4149
|
-
if (!order) throw new NotFoundError5("order", id);
|
|
4150
|
-
return order;
|
|
4151
|
-
}
|
|
4152
|
-
async function doTransition(tx, order, toStatus, actor, note) {
|
|
4153
|
-
assertOrderTransition(order.status, toStatus);
|
|
4154
|
-
const now = /* @__PURE__ */ new Date();
|
|
4155
|
-
await repos.order.setStatus(tx, order.id, toStatus, now);
|
|
4156
|
-
await repos.orderHistory.append(tx, {
|
|
4157
|
-
id: uuidv78(),
|
|
4158
|
-
orderId: order.id,
|
|
4159
|
-
fromStatus: order.status,
|
|
4160
|
-
toStatus,
|
|
4161
|
-
actor,
|
|
4162
|
-
note,
|
|
4163
|
-
timestamp: now
|
|
4164
|
-
});
|
|
4165
|
-
return requireOrder(tx, order.id);
|
|
4166
|
-
}
|
|
4167
|
-
return {
|
|
4168
|
-
async createFromCheckout(input) {
|
|
4169
|
-
return store.transaction(async (tx) => {
|
|
4170
|
-
audit.note("order.place", [{ type: "order", id: input.orderId }]);
|
|
4171
|
-
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
4172
|
-
const orderNumber = `${deps.orderNumberPrefix}-${sequence + 1}`;
|
|
4173
|
-
const now = /* @__PURE__ */ new Date();
|
|
4174
|
-
await repos.order.insert(tx, {
|
|
4175
|
-
id: input.orderId,
|
|
4176
|
-
orderNumber,
|
|
4177
|
-
sequence,
|
|
4178
|
-
customerId: input.customerId,
|
|
4179
|
-
status: "pending",
|
|
4180
|
-
email: input.email,
|
|
4181
|
-
billingAddress: input.billingAddress,
|
|
4182
|
-
shippingAddress: input.shippingAddress,
|
|
4183
|
-
lineItems: input.lineItems,
|
|
4184
|
-
subtotalMinor: input.subtotalMinor,
|
|
4185
|
-
taxTotalMinor: input.taxTotalMinor,
|
|
4186
|
-
shippingTotalMinor: input.shippingTotalMinor,
|
|
4187
|
-
discountTotalMinor: input.discountTotalMinor,
|
|
4188
|
-
totalMinor: input.totalMinor,
|
|
4189
|
-
currency: input.currency,
|
|
4190
|
-
notes: input.notes ?? "",
|
|
4191
|
-
metadata: input.metadata ?? {},
|
|
4192
|
-
paymentIntentId: input.paymentIntentId ?? null,
|
|
4193
|
-
cartToken: input.cartToken ?? null,
|
|
4194
|
-
createdAt: now,
|
|
4195
|
-
updatedAt: now
|
|
4196
|
-
});
|
|
4197
|
-
await repos.orderHistory.append(tx, {
|
|
4198
|
-
id: uuidv78(),
|
|
4199
|
-
orderId: input.orderId,
|
|
4200
|
-
fromStatus: null,
|
|
4201
|
-
toStatus: "pending",
|
|
4202
|
-
actor: "system:checkout",
|
|
4203
|
-
note: "order draft created",
|
|
4204
|
-
timestamp: now
|
|
4205
|
-
});
|
|
4206
|
-
const fresh = await requireOrder(tx, input.orderId);
|
|
4207
|
-
await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
|
|
4208
|
-
return fresh;
|
|
4209
|
-
});
|
|
4210
|
-
},
|
|
4211
|
-
async getById(id) {
|
|
4212
|
-
return store.read((tx) => requireOrder(tx, id));
|
|
4213
|
-
},
|
|
4214
|
-
async getByOrderNumber(orderNumber) {
|
|
4215
|
-
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
4216
|
-
if (!order) throw new NotFoundError5("order", orderNumber);
|
|
4217
|
-
return order;
|
|
4218
|
-
},
|
|
4219
|
-
async listByCustomer(customerId) {
|
|
4220
|
-
return store.read((tx) => repos.order.listByCustomer(tx, customerId));
|
|
4221
|
-
},
|
|
4222
|
-
async updateStatus(id, toStatus, actor, note = "") {
|
|
4223
|
-
return store.transaction(async (tx) => {
|
|
4224
|
-
audit.note("order.updateStatus", [{ type: "order", id }]);
|
|
4225
|
-
const order = await requireOrder(tx, id);
|
|
4226
|
-
const fresh = await doTransition(tx, order, toStatus, actor, note);
|
|
4227
|
-
await publisher.publish(EVT_ORDER_STATUS_CHANGED2, {
|
|
4228
|
-
orderId: fresh.id,
|
|
4229
|
-
from: order.status,
|
|
4230
|
-
to: fresh.status
|
|
4231
|
-
});
|
|
4232
|
-
return fresh;
|
|
4233
|
-
});
|
|
4234
|
-
},
|
|
4235
|
-
async markShipped(id, trackingNumber, carrier, actor) {
|
|
4236
|
-
return store.transaction(async (tx) => {
|
|
4237
|
-
audit.note("order.ship", [{ type: "order", id }]);
|
|
4238
|
-
const order = await requireOrder(tx, id);
|
|
4239
|
-
const fresh = await doTransition(
|
|
4240
|
-
tx,
|
|
4241
|
-
order,
|
|
4242
|
-
"shipped",
|
|
4243
|
-
actor,
|
|
4244
|
-
`Shipped via ${carrier}: ${trackingNumber}`
|
|
4245
|
-
);
|
|
4246
|
-
await publisher.publish(EVT_ORDER_SHIPPED3, {
|
|
4247
|
-
orderId: fresh.id,
|
|
4248
|
-
trackingNumber,
|
|
4249
|
-
carrier
|
|
4250
|
-
});
|
|
4251
|
-
return fresh;
|
|
4252
|
-
});
|
|
4253
|
-
},
|
|
4254
|
-
async markDelivered(id, actor) {
|
|
4255
|
-
return store.transaction(async (tx) => {
|
|
4256
|
-
audit.note("order.markDelivered", [{ type: "order", id }]);
|
|
4257
|
-
const order = await requireOrder(tx, id);
|
|
4258
|
-
const fresh = await doTransition(tx, order, "delivered", actor, "Delivered");
|
|
4259
|
-
await publisher.publish(EVT_ORDER_DELIVERED3, { orderId: fresh.id });
|
|
4260
|
-
return fresh;
|
|
4261
|
-
});
|
|
4262
|
-
},
|
|
4263
|
-
async cancel(id, reason, actor) {
|
|
4264
|
-
return store.transaction(async (tx) => {
|
|
4265
|
-
audit.note("order.cancel", [{ type: "order", id }]);
|
|
4266
|
-
const order = await repos.order.lock(tx, id);
|
|
4267
|
-
if (!order) throw new NotFoundError5("order", id);
|
|
4268
|
-
if (order.capturedMinor > 0) {
|
|
4269
|
-
throw new OrderConflictError(
|
|
4270
|
-
"order.paid",
|
|
4271
|
-
`Order ${order.orderNumber} is paid: refund it instead of cancelling`
|
|
4272
|
-
);
|
|
4273
|
-
}
|
|
4274
|
-
assertOrderTransition(order.status, "cancelled");
|
|
4275
|
-
const now = /* @__PURE__ */ new Date();
|
|
4276
|
-
if (!await repos.order.setStatusIf(tx, order.id, order.status, "cancelled", now)) {
|
|
4277
|
-
const current = await requireOrder(tx, order.id);
|
|
4278
|
-
throw new StatusTransitionError("order", current.status, "cancelled");
|
|
4279
|
-
}
|
|
4280
|
-
await repos.orderHistory.append(tx, {
|
|
4281
|
-
id: uuidv78(),
|
|
4282
|
-
orderId: order.id,
|
|
4283
|
-
fromStatus: order.status,
|
|
4284
|
-
toStatus: "cancelled",
|
|
4285
|
-
actor,
|
|
4286
|
-
note: reason,
|
|
4287
|
-
timestamp: now
|
|
4288
|
-
});
|
|
4289
|
-
const fresh = await requireOrder(tx, order.id);
|
|
4290
|
-
await publisher.publish(EVT_ORDER_CANCELLED2, { orderId: fresh.id, reason });
|
|
4291
|
-
return fresh;
|
|
4292
|
-
});
|
|
4293
|
-
},
|
|
4294
|
-
async importOrder(input) {
|
|
4295
|
-
const capturedMinor = input.capturedMinor ?? 0;
|
|
4296
|
-
const refundedMinor = input.refundedMinor ?? 0;
|
|
4297
|
-
if (!(0 <= refundedMinor && refundedMinor <= capturedMinor && capturedMinor <= input.totalMinor) || capturedMinor > 0 !== (input.captureMethod != null)) {
|
|
4298
|
-
throw new ValidationError7("imported payment amounts are inconsistent", {
|
|
4299
|
-
context: { capturedMinor, refundedMinor, totalMinor: input.totalMinor }
|
|
4300
|
-
});
|
|
4301
|
-
}
|
|
4302
|
-
return store.transaction(async (tx) => {
|
|
4303
|
-
audit.note("order.import", [{ type: "order", id: input.orderId }]);
|
|
4304
|
-
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
4305
|
-
await repos.order.insert(tx, {
|
|
4306
|
-
id: input.orderId,
|
|
4307
|
-
orderNumber: input.orderNumber,
|
|
4308
|
-
sequence,
|
|
4309
|
-
customerId: input.customerId,
|
|
4310
|
-
status: input.status,
|
|
4311
|
-
email: input.email,
|
|
4312
|
-
billingAddress: input.billingAddress,
|
|
4313
|
-
shippingAddress: input.shippingAddress,
|
|
4314
|
-
lineItems: input.lineItems,
|
|
4315
|
-
subtotalMinor: input.subtotalMinor,
|
|
4316
|
-
taxTotalMinor: input.taxTotalMinor,
|
|
4317
|
-
shippingTotalMinor: input.shippingTotalMinor,
|
|
4318
|
-
discountTotalMinor: input.discountTotalMinor,
|
|
4319
|
-
totalMinor: input.totalMinor,
|
|
4320
|
-
currency: input.currency,
|
|
4321
|
-
notes: input.notes ?? "",
|
|
4322
|
-
metadata: input.metadata ?? {},
|
|
4323
|
-
paymentIntentId: input.paymentIntentId ?? null,
|
|
4324
|
-
...input.captureMethod != null && {
|
|
4325
|
-
capture: {
|
|
4326
|
-
amountMinor: capturedMinor,
|
|
4327
|
-
method: input.captureMethod,
|
|
4328
|
-
at: input.createdAt,
|
|
4329
|
-
refundedMinor
|
|
4330
|
-
}
|
|
4331
|
-
},
|
|
4332
|
-
createdAt: input.createdAt,
|
|
4333
|
-
updatedAt: input.createdAt
|
|
4334
|
-
});
|
|
4335
|
-
const fresh = await requireOrder(tx, input.orderId);
|
|
4336
|
-
await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
|
|
4337
|
-
return fresh;
|
|
4338
|
-
});
|
|
4339
|
-
}
|
|
4340
|
-
};
|
|
4341
|
-
}
|
|
4342
|
-
|
|
4343
|
-
// src/services/inventory-service.ts
|
|
4344
|
-
import { v7 as uuidv79 } from "uuid";
|
|
4345
|
-
import {
|
|
4346
|
-
AdapterError as AdapterError2,
|
|
4347
|
-
NotFoundError as NotFoundError6,
|
|
4348
|
-
ValidationError as ValidationError8,
|
|
4349
|
-
EVT_INVENTORY_CHANGED as EVT_INVENTORY_CHANGED2,
|
|
4350
|
-
EVT_INVENTORY_RESERVED,
|
|
4351
|
-
EVT_INVENTORY_RELEASED,
|
|
4352
|
-
EVT_INVENTORY_LOW_STOCK,
|
|
4353
|
-
EVT_INVENTORY_OUT_OF_STOCK
|
|
4354
|
-
} from "@nymbalhq/types";
|
|
4355
|
-
function classifyStock(stock, threshold) {
|
|
4356
|
-
if (stock <= 0) return "out_of_stock";
|
|
4357
|
-
if (stock <= threshold) return "low_stock";
|
|
4358
|
-
return "in_stock";
|
|
4359
|
-
}
|
|
4360
|
-
function createInventoryService(deps) {
|
|
4361
|
-
const { store, repos, publisher, logger } = deps;
|
|
4362
|
-
const defaultTtl = deps.defaultReservationTtlSeconds ?? 15 * 60;
|
|
4363
|
-
async function emitThresholdEvents(variantId, newQty, threshold) {
|
|
4364
|
-
if (newQty <= 0) {
|
|
4365
|
-
await publisher.publish(EVT_INVENTORY_OUT_OF_STOCK, { variantId });
|
|
4366
|
-
} else if (newQty <= threshold) {
|
|
4367
|
-
await publisher.publish(EVT_INVENTORY_LOW_STOCK, {
|
|
4368
|
-
variantId,
|
|
4369
|
-
currentQty: newQty,
|
|
4370
|
-
threshold
|
|
4371
|
-
});
|
|
4372
|
-
}
|
|
4373
|
-
}
|
|
4374
|
-
async function take(variantId, qty, orderRef, ttlSeconds) {
|
|
4375
|
-
if (qty <= 0) throw new ValidationError8(`Reservation qty must be positive, got ${qty}`);
|
|
4376
|
-
return store.transaction(async (tx) => {
|
|
4377
|
-
audit.note("inventory.reserve", [{ type: "variant", id: variantId }]);
|
|
4378
|
-
const variant = await repos.variant.findById(tx, variantId);
|
|
4379
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4380
|
-
const now = /* @__PURE__ */ new Date();
|
|
4381
|
-
const remaining = await repos.variant.decrementStock(tx, variant.id, qty, now);
|
|
4382
|
-
if (remaining === null) return { available: variant.stock };
|
|
4383
|
-
const expiresAt = new Date(now.getTime() + (ttlSeconds ?? defaultTtl) * 1e3);
|
|
4384
|
-
const reservationId = uuidv79();
|
|
4385
|
-
await repos.inventoryReservation.insert(tx, {
|
|
4386
|
-
reservationId,
|
|
4387
|
-
variantId: variant.id,
|
|
4388
|
-
qty,
|
|
4389
|
-
orderRef,
|
|
4390
|
-
expiresAt,
|
|
4391
|
-
createdAt: now
|
|
4392
|
-
});
|
|
4393
|
-
await publisher.publish(EVT_INVENTORY_RESERVED, {
|
|
4394
|
-
variantId: variant.id,
|
|
4395
|
-
qty,
|
|
4396
|
-
reservationId,
|
|
4397
|
-
expiresAt: expiresAt.toISOString()
|
|
4398
|
-
});
|
|
4399
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4400
|
-
variantId: variant.id,
|
|
4401
|
-
previousQty: remaining + qty,
|
|
4402
|
-
newQty: remaining,
|
|
4403
|
-
reason: "manual"
|
|
4404
|
-
});
|
|
4405
|
-
await emitThresholdEvents(variant.id, remaining, variant.lowStockThreshold);
|
|
4406
|
-
return { reservationId, expiresAt: expiresAt.toISOString() };
|
|
4407
|
-
});
|
|
4408
|
-
}
|
|
4409
|
-
return {
|
|
4410
|
-
async adjustStock(variantId, delta, reason, actor) {
|
|
4411
|
-
return store.transaction(async (tx) => {
|
|
4412
|
-
audit.note("inventory.adjust", [{ type: "variant", id: variantId }]);
|
|
4413
|
-
const variant = await repos.variant.findById(tx, variantId);
|
|
4414
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4415
|
-
const now = /* @__PURE__ */ new Date();
|
|
4416
|
-
const newQty = delta < 0 ? await repos.variant.decrementStock(tx, variant.id, -delta, now) : await repos.variant.incrementStock(tx, variant.id, delta, now);
|
|
4417
|
-
if (newQty === null) {
|
|
4418
|
-
throw new ValidationError8(`Cannot reduce stock below zero (variant ${variantId})`, {
|
|
4419
|
-
context: { variantId, stock: variant.stock, delta }
|
|
4420
|
-
});
|
|
4421
|
-
}
|
|
4422
|
-
const previousQty = newQty - delta;
|
|
4423
|
-
await repos.stockAdjustment.append(tx, {
|
|
4424
|
-
id: uuidv79(),
|
|
4425
|
-
variantId: variant.id,
|
|
4426
|
-
adjustment: delta,
|
|
4427
|
-
reason,
|
|
4428
|
-
actor,
|
|
4429
|
-
previousQty,
|
|
4430
|
-
newQty,
|
|
4431
|
-
timestamp: now
|
|
4432
|
-
});
|
|
4433
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4434
|
-
variantId: variant.id,
|
|
4435
|
-
previousQty,
|
|
4436
|
-
newQty,
|
|
4437
|
-
reason
|
|
4438
|
-
});
|
|
4439
|
-
await emitThresholdEvents(variant.id, newQty, variant.lowStockThreshold);
|
|
4440
|
-
logger.debug({ variantId, delta, newQty, reason }, "stock adjusted");
|
|
4441
|
-
return { newQty };
|
|
4442
|
-
});
|
|
4443
|
-
},
|
|
4444
|
-
async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
4445
|
-
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
4446
|
-
if ("available" in taken) {
|
|
4447
|
-
throw new AdapterError2(
|
|
4448
|
-
"inventory.insufficient",
|
|
4449
|
-
`Insufficient stock for variant ${variantId}`,
|
|
4450
|
-
{
|
|
4451
|
-
context: { variantId, requested: qty, available: taken.available }
|
|
4452
|
-
}
|
|
4453
|
-
);
|
|
4454
|
-
}
|
|
4455
|
-
return taken;
|
|
4456
|
-
},
|
|
4457
|
-
async tryReserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
4458
|
-
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
4459
|
-
return "available" in taken ? null : taken;
|
|
4460
|
-
},
|
|
4461
|
-
async releaseReservation(reservationId, reason) {
|
|
4462
|
-
await store.transaction(async (tx) => {
|
|
4463
|
-
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
4464
|
-
if (!reservation) {
|
|
4465
|
-
logger.debug(
|
|
4466
|
-
{ reservationId },
|
|
4467
|
-
"reservation already released, committed or never existed"
|
|
4468
|
-
);
|
|
4469
|
-
return;
|
|
4470
|
-
}
|
|
4471
|
-
audit.note("inventory.release", [{ type: "variant", id: reservation.variantId }]);
|
|
4472
|
-
const now = /* @__PURE__ */ new Date();
|
|
4473
|
-
const newQty = await repos.variant.incrementStock(
|
|
4474
|
-
tx,
|
|
4475
|
-
reservation.variantId,
|
|
4476
|
-
reservation.qty,
|
|
4477
|
-
now
|
|
4478
|
-
);
|
|
4479
|
-
if (newQty !== null) {
|
|
4480
|
-
const previousQty = newQty - reservation.qty;
|
|
4481
|
-
await repos.stockAdjustment.append(tx, {
|
|
4482
|
-
id: uuidv79(),
|
|
4483
|
-
variantId: reservation.variantId,
|
|
4484
|
-
adjustment: reservation.qty,
|
|
4485
|
-
reason: "reservation-release",
|
|
4486
|
-
actor: `system:release:${reason}`,
|
|
4487
|
-
previousQty,
|
|
4488
|
-
newQty,
|
|
4489
|
-
timestamp: now
|
|
4490
|
-
});
|
|
4491
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4492
|
-
variantId: reservation.variantId,
|
|
4493
|
-
previousQty,
|
|
4494
|
-
newQty,
|
|
4495
|
-
reason: "reservation-release"
|
|
4496
|
-
});
|
|
4497
|
-
}
|
|
4498
|
-
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
4499
|
-
variantId: reservation.variantId,
|
|
4500
|
-
qty: reservation.qty,
|
|
4501
|
-
reservationId: reservation.reservationId,
|
|
4502
|
-
reason
|
|
4503
|
-
});
|
|
4504
|
-
});
|
|
4505
|
-
},
|
|
4506
|
-
async commitReservation(reservationId, actor) {
|
|
4507
|
-
await store.transaction(async (tx) => {
|
|
4508
|
-
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
4509
|
-
if (!reservation) throw new NotFoundError6("reservation", reservationId);
|
|
4510
|
-
audit.note("inventory.commit", [{ type: "variant", id: reservation.variantId }]);
|
|
4511
|
-
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
4512
|
-
if (!variant) throw new NotFoundError6("variant", reservation.variantId);
|
|
4513
|
-
await repos.stockAdjustment.append(tx, {
|
|
4514
|
-
id: uuidv79(),
|
|
4515
|
-
variantId: variant.id,
|
|
4516
|
-
adjustment: -reservation.qty,
|
|
4517
|
-
reason: "reservation-commit",
|
|
4518
|
-
actor,
|
|
4519
|
-
previousQty: variant.stock + reservation.qty,
|
|
4520
|
-
newQty: variant.stock,
|
|
4521
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
4522
|
-
});
|
|
4523
|
-
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
4524
|
-
variantId: reservation.variantId,
|
|
4525
|
-
qty: reservation.qty,
|
|
4526
|
-
reservationId: reservation.reservationId,
|
|
4527
|
-
reason: "committed"
|
|
4528
|
-
});
|
|
4529
|
-
});
|
|
4530
|
-
},
|
|
4531
|
-
async getStockStatus(variantId) {
|
|
4532
|
-
const variant = await store.read((tx) => repos.variant.findById(tx, variantId));
|
|
4533
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4534
|
-
return {
|
|
4535
|
-
stock: variant.stock,
|
|
4536
|
-
threshold: variant.lowStockThreshold,
|
|
4537
|
-
status: classifyStock(variant.stock, variant.lowStockThreshold)
|
|
4538
|
-
};
|
|
4539
|
-
}
|
|
4540
|
-
};
|
|
4541
|
-
}
|
|
4542
|
-
|
|
4543
|
-
// src/services/checkout-service.ts
|
|
4544
|
-
import { v5 as uuidv5, v7 as uuidv710 } from "uuid";
|
|
4545
|
-
import {
|
|
4546
|
-
CheckoutError,
|
|
4547
|
-
EVT_CART_CONVERTED,
|
|
4548
|
-
EVT_CART_UPDATED as EVT_CART_UPDATED2,
|
|
4549
|
-
EVT_ORDER_PAID as EVT_ORDER_PAID4,
|
|
4550
|
-
EVT_PAYMENT_CAPTURED,
|
|
4551
|
-
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
|
|
4552
|
-
EVT_PAYMENT_INTENT_CREATED as EVT_PAYMENT_INTENT_CREATED2,
|
|
4553
|
-
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
|
|
4554
|
-
NotFoundError as NotFoundError7,
|
|
4555
|
-
OrderConflictError as OrderConflictError2,
|
|
4556
|
-
PaymentError,
|
|
4557
|
-
StatusTransitionError as StatusTransitionError2
|
|
4558
|
-
} from "@nymbalhq/types";
|
|
4559
|
-
var StockUnavailable = class extends Error {
|
|
4560
|
-
constructor(variantId) {
|
|
4561
|
-
super(`stock unavailable for variant ${variantId}`);
|
|
4562
|
-
this.variantId = variantId;
|
|
4563
|
-
}
|
|
4564
|
-
variantId;
|
|
4565
|
-
};
|
|
4566
|
-
var NoLongerPending = class extends Error {
|
|
4567
|
-
};
|
|
4568
|
-
var PROVIDER_CAPTURE = {
|
|
4569
|
-
method: "provider",
|
|
4570
|
-
actor: "system:checkout",
|
|
4571
|
-
note: "payment captured"
|
|
4572
|
-
};
|
|
4573
|
-
var FINALIZE_ACTOR = "system:checkout-finalize";
|
|
4574
|
-
var CANCEL_ACTOR = "system:checkout-cancel";
|
|
4575
|
-
var DUPLICATE_CAPTURE = "duplicate_capture_refunded";
|
|
4576
|
-
var DUPLICATE_CAPTURE_HANDLER = "checkout:duplicate-capture";
|
|
4577
|
-
var CAPTURE_REFUND_NAMESPACE = "49e623d3-5784-4331-80e9-6f951d97f7c0";
|
|
4578
|
-
var SUPERSEDE_ATTEMPTS = 3;
|
|
4579
|
-
var ABANDON_AFTER_MS = 12e4;
|
|
4580
|
-
function outcomeOf(status) {
|
|
4581
|
-
if (status === "succeeded") return "succeeded";
|
|
4582
|
-
if (status === "failed" || status === "cancelled") return "failed";
|
|
4583
|
-
return "requires_action";
|
|
4584
|
-
}
|
|
4585
|
-
function sameLines(order, cart) {
|
|
4586
|
-
if (order.totalMinor !== cart.subtotalMinor || order.currency !== cart.currency) return false;
|
|
4587
|
-
if (order.lineItems.length !== cart.items.length) return false;
|
|
4588
|
-
return cart.items.every((item, i) => {
|
|
4589
|
-
const line = order.lineItems[i];
|
|
4590
|
-
return line?.variantId === item.variantId && line.qty === item.qty && line.unitPriceMinor === item.priceMinor;
|
|
4591
|
-
});
|
|
4592
|
-
}
|
|
4593
|
-
function createCheckoutService(deps) {
|
|
4594
|
-
const { store, repos, publisher, logger, cart, orders: orders4, inventory, payments, currency } = deps;
|
|
4595
|
-
async function cartEmpty(token) {
|
|
4596
|
-
const converted = await store.read((tx) => repos.order.findLastConvertedByCartToken(tx, token));
|
|
4597
|
-
return new CheckoutError(
|
|
4598
|
-
"cart_empty",
|
|
4599
|
-
"Cart has no items",
|
|
4600
|
-
converted ? { context: { orderNumber: converted.orderNumber } } : {}
|
|
4601
|
-
);
|
|
4602
|
-
}
|
|
4603
|
-
async function loadValidCart(token) {
|
|
4604
|
-
const c = await cart.get(token);
|
|
4605
|
-
if (!c) throw new NotFoundError7("cart", token);
|
|
4606
|
-
if (!c.items.length) throw await cartEmpty(token);
|
|
4607
|
-
if (c.currency !== currency) {
|
|
4608
|
-
throw new CheckoutError(
|
|
4609
|
-
"cart_empty",
|
|
4610
|
-
`Cart currency ${c.currency} does not match store currency ${currency}`
|
|
4611
|
-
);
|
|
4612
|
-
}
|
|
4613
|
-
return c;
|
|
4614
|
-
}
|
|
4615
|
-
async function settled(tx, paymentIntentId, order, paid) {
|
|
4616
|
-
if (order === null) return recordOutcome(tx, paymentIntentId, null, "no_order");
|
|
4617
|
-
if (order.captureMethod === "manual" || order.captureMethod === "import") {
|
|
4618
|
-
return refundDuplicateCapture(tx, paymentIntentId, paid, order);
|
|
4619
|
-
}
|
|
4620
|
-
if (order.status === "confirmed") return { orderNumber: order.orderNumber, finalized: true };
|
|
4621
|
-
if (order.status === "cancelled") {
|
|
4622
|
-
if (order.capturedMinor === 0) await refundCancelledCapture(paymentIntentId, paid, order);
|
|
4623
|
-
return recordOutcome(tx, paymentIntentId, order, "order_cancelled_refunded");
|
|
4624
|
-
}
|
|
4625
|
-
return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
|
|
4626
|
-
}
|
|
4627
|
-
async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
|
|
4628
|
-
await publisher.publish(EVT_PAYMENT_FAILED2, {
|
|
4629
|
-
paymentId: paymentIntentId,
|
|
4630
|
-
orderId: order?.id ?? "",
|
|
4631
|
-
reason
|
|
4632
|
-
});
|
|
4633
|
-
if (order !== null) {
|
|
4634
|
-
audit.note("payment.recordOutcome", [{ type: "order", id: order.id }]);
|
|
4635
|
-
await repos.orderHistory.append(tx, {
|
|
4636
|
-
id: uuidv710(),
|
|
4637
|
-
orderId: order.id,
|
|
4638
|
-
fromStatus: order.status,
|
|
4639
|
-
toStatus: order.status,
|
|
4640
|
-
actor: FINALIZE_ACTOR,
|
|
4641
|
-
note: `captured payment not applied: ${reason}${detail === void 0 ? "" : ` (${detail})`}`,
|
|
4642
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
4643
|
-
});
|
|
4644
|
-
}
|
|
4645
|
-
logger.warn({ paymentIntentId, orderId: order?.id, reason }, "captured payment not applied");
|
|
4646
|
-
return { orderNumber: order?.orderNumber ?? null, finalized: false, reason };
|
|
4647
|
-
}
|
|
4648
|
-
async function reservationFor(tx, order, reservationId, index) {
|
|
4649
|
-
const held = await repos.inventoryReservation.findById(tx, reservationId);
|
|
4650
|
-
if (held !== null) return reservationId;
|
|
4651
|
-
const line = order.lineItems[index];
|
|
4652
|
-
if (line === void 0) {
|
|
4653
|
-
throw new CheckoutError(
|
|
4654
|
-
"finalize_failed",
|
|
4655
|
-
`Order ${order.id} has no line for reservation ${reservationId}`
|
|
4656
|
-
);
|
|
4657
|
-
}
|
|
4658
|
-
const retaken = await inventory.tryReserveStock(line.variantId, line.qty, order.id).catch((err) => {
|
|
4659
|
-
if (err instanceof NotFoundError7) return null;
|
|
4660
|
-
throw err;
|
|
4661
|
-
});
|
|
4662
|
-
if (retaken === null) throw new StockUnavailable(line.variantId);
|
|
4663
|
-
return retaken.reservationId;
|
|
4664
|
-
}
|
|
4665
|
-
async function refundCapture(paymentIntentId, paid, currency2, key, context) {
|
|
4666
|
-
try {
|
|
4667
|
-
const answer = await payments.refund(
|
|
4668
|
-
paymentIntentId,
|
|
4669
|
-
paid.amountMinor,
|
|
4670
|
-
PROVIDER_REFUND_REASON,
|
|
4671
|
-
{
|
|
4672
|
-
idempotencyKey: key,
|
|
4673
|
-
currency: currency2
|
|
4674
|
-
}
|
|
4675
|
-
);
|
|
4676
|
-
const settlement = settlementOf(answer, { amountMinor: paid.amountMinor, currency: currency2 });
|
|
4677
|
-
if (settlement.mismatch) {
|
|
4678
|
-
logger.error(
|
|
4679
|
-
{ ...context, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
4680
|
-
"provider refund answer differs from the capture; left pending"
|
|
4681
|
-
);
|
|
4682
|
-
}
|
|
4683
|
-
return settlement;
|
|
4684
|
-
} catch (err) {
|
|
4685
|
-
if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
|
|
4686
|
-
logger.error({ ...context, err }, "provider refused the refund of a capture");
|
|
4687
|
-
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
4688
|
-
}
|
|
4689
|
-
logger.error(
|
|
4690
|
-
{ ...context, err },
|
|
4691
|
-
"capture refund outcome unknown; left pending until reconciled"
|
|
4692
|
-
);
|
|
4693
|
-
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
4694
|
-
}
|
|
4695
|
-
}
|
|
4696
|
-
async function refundCancelledCapture(paymentIntentId, paid, order) {
|
|
4697
|
-
const refundId = uuidv5(`cancelled-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
4698
|
-
const held = await store.transaction(async (tx) => {
|
|
4699
|
-
audit.note("payment.refundCapture", [{ type: "order", id: order.id }]);
|
|
4700
|
-
const locked = await repos.order.lock(tx, order.id);
|
|
4701
|
-
if (locked === null || locked.capturedMinor > 0) return false;
|
|
4702
|
-
const now = /* @__PURE__ */ new Date();
|
|
4703
|
-
await repos.order.recordCapture(tx, order.id, {
|
|
4704
|
-
amountMinor: paid.amountMinor,
|
|
4705
|
-
method: "provider",
|
|
4706
|
-
at: now
|
|
4707
|
-
});
|
|
4708
|
-
await repos.orderRefund.insert(tx, {
|
|
4709
|
-
id: refundId,
|
|
4710
|
-
orderId: order.id,
|
|
4711
|
-
amountMinor: paid.amountMinor,
|
|
4712
|
-
currency: order.currency,
|
|
4713
|
-
providerRefundId: null,
|
|
4714
|
-
status: "pending",
|
|
4715
|
-
reason: "captured for a cancelled order",
|
|
4716
|
-
actor: "system:checkout",
|
|
4717
|
-
createdAt: now
|
|
4718
|
-
});
|
|
4719
|
-
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
4720
|
-
paymentId: paymentIntentId,
|
|
4721
|
-
orderId: order.id,
|
|
4722
|
-
amountMinor: paid.amountMinor,
|
|
4723
|
-
currency: order.currency
|
|
4724
|
-
});
|
|
4725
|
-
return true;
|
|
4726
|
-
});
|
|
4727
|
-
if (!held) return;
|
|
4728
|
-
const settlement = await refundCapture(paymentIntentId, paid, order.currency, refundId, {
|
|
4729
|
-
orderId: order.id,
|
|
4730
|
-
refundId
|
|
4731
|
-
});
|
|
4732
|
-
if (settlement.status === "pending") return;
|
|
4733
|
-
await store.transaction(async (tx) => {
|
|
4734
|
-
await repos.order.lock(tx, order.id);
|
|
4735
|
-
await repos.orderRefund.settle(tx, refundId, {
|
|
4736
|
-
status: settlement.status,
|
|
4737
|
-
providerRefundId: settlement.providerRefundId
|
|
4738
|
-
});
|
|
4739
|
-
await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
|
|
4740
|
-
if (settlement.status === "succeeded") {
|
|
4741
|
-
await publisher.publish(EVT_PAYMENT_REFUNDED2, {
|
|
4742
|
-
paymentId: paymentIntentId,
|
|
4743
|
-
orderId: order.id,
|
|
4744
|
-
refundId,
|
|
4745
|
-
amountMinor: paid.amountMinor,
|
|
4746
|
-
currency: order.currency
|
|
4747
|
-
});
|
|
4748
|
-
}
|
|
4749
|
-
});
|
|
4750
|
-
}
|
|
4751
|
-
async function refundDuplicateCapture(tx, paymentIntentId, paid, order) {
|
|
4752
|
-
if (await repos.processedEvent.seen(tx, DUPLICATE_CAPTURE_HANDLER, paymentIntentId)) {
|
|
4753
|
-
return { orderNumber: order.orderNumber, finalized: false, reason: DUPLICATE_CAPTURE };
|
|
4754
|
-
}
|
|
4755
|
-
const key = uuidv5(`duplicate-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
4756
|
-
const settlement = await refundCapture(
|
|
4757
|
-
paymentIntentId,
|
|
4758
|
-
paid,
|
|
4759
|
-
paid.currency.toUpperCase(),
|
|
4760
|
-
key,
|
|
4761
|
-
{
|
|
4762
|
-
orderId: order.id,
|
|
4763
|
-
idempotencyKey: key
|
|
4764
|
-
}
|
|
4765
|
-
);
|
|
4766
|
-
if (settlement.status === "pending" && !settlement.mismatch) {
|
|
4767
|
-
throw new CheckoutError(
|
|
4768
|
-
"finalize_failed",
|
|
4769
|
-
`The refund of a second capture of order ${order.orderNumber} has no known outcome`,
|
|
4770
|
-
{ context: { orderNumber: order.orderNumber } }
|
|
4771
|
-
);
|
|
4772
|
-
}
|
|
4773
|
-
await repos.processedEvent.markProcessed(
|
|
4774
|
-
tx,
|
|
4775
|
-
DUPLICATE_CAPTURE_HANDLER,
|
|
4776
|
-
paymentIntentId,
|
|
4777
|
-
/* @__PURE__ */ new Date()
|
|
4778
|
-
);
|
|
4779
|
-
const reason = settlement.status === "succeeded" ? DUPLICATE_CAPTURE : `duplicate_capture_refund_${settlement.status}`;
|
|
4780
|
-
return recordOutcome(
|
|
4781
|
-
tx,
|
|
4782
|
-
paymentIntentId,
|
|
4783
|
-
order,
|
|
4784
|
-
reason,
|
|
4785
|
-
`capture of ${formatMoney(paid.amountMinor, paid.currency)}`
|
|
4786
|
-
);
|
|
4787
|
-
}
|
|
4788
|
-
async function confirm(tx, paymentIntentId, paid, order, capture) {
|
|
4789
|
-
const metadata = order.metadata;
|
|
4790
|
-
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
4791
|
-
audit.note("order.confirm", [{ type: "order", id: order.id }]);
|
|
4792
|
-
for (const [index, reservationId] of reservationIds.entries()) {
|
|
4793
|
-
const reservation = await reservationFor(tx, order, reservationId, index);
|
|
4794
|
-
await inventory.commitReservation(reservation, FINALIZE_ACTOR);
|
|
4795
|
-
}
|
|
4796
|
-
const now = /* @__PURE__ */ new Date();
|
|
4797
|
-
if (!await repos.order.setStatusIf(tx, order.id, "pending", "confirmed", now)) {
|
|
4798
|
-
throw new NoLongerPending();
|
|
4799
|
-
}
|
|
4800
|
-
await repos.order.recordCapture(tx, order.id, {
|
|
4801
|
-
amountMinor: paid.amountMinor,
|
|
4802
|
-
method: capture.method,
|
|
4803
|
-
at: now
|
|
4804
|
-
});
|
|
4805
|
-
await repos.orderHistory.append(tx, {
|
|
4806
|
-
id: uuidv710(),
|
|
4807
|
-
orderId: order.id,
|
|
4808
|
-
fromStatus: "pending",
|
|
4809
|
-
toStatus: "confirmed",
|
|
4810
|
-
actor: capture.actor,
|
|
4811
|
-
note: capture.note,
|
|
4812
|
-
timestamp: now
|
|
4813
|
-
});
|
|
4814
|
-
if (order.customerId) {
|
|
4815
|
-
await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
|
|
4816
|
-
}
|
|
4817
|
-
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
4818
|
-
paymentId: paymentIntentId,
|
|
4819
|
-
orderId: order.id,
|
|
4820
|
-
amountMinor: paid.amountMinor,
|
|
4821
|
-
currency: order.currency
|
|
4822
|
-
});
|
|
4823
|
-
await publisher.publish(EVT_ORDER_PAID4, {
|
|
4824
|
-
orderId: order.id,
|
|
4825
|
-
paymentIntentId,
|
|
4826
|
-
amountMinor: paid.amountMinor,
|
|
4827
|
-
currency: order.currency
|
|
4828
|
-
});
|
|
4829
|
-
const cartToken = metadata.cartToken;
|
|
4830
|
-
if (cartToken) {
|
|
4831
|
-
if (await repos.cart.clearIfLive(tx, cartToken, now)) {
|
|
4832
|
-
await publisher.publish(EVT_CART_UPDATED2, {
|
|
4833
|
-
cartId: cartToken,
|
|
4834
|
-
itemCount: 0,
|
|
4835
|
-
totalMinor: 0
|
|
4836
|
-
});
|
|
4837
|
-
}
|
|
4838
|
-
await publisher.publish(EVT_CART_CONVERTED, {
|
|
4839
|
-
cartId: cartToken,
|
|
4840
|
-
orderId: order.id
|
|
4841
|
-
});
|
|
4842
|
-
}
|
|
4843
|
-
logger.info({ orderId: order.id, orderNumber: order.orderNumber }, "checkout finalized");
|
|
4844
|
-
return { orderNumber: order.orderNumber, finalized: true };
|
|
4845
|
-
}
|
|
4846
|
-
async function cancelDraft(orderId, reason) {
|
|
4847
|
-
await store.transaction(async (tx) => {
|
|
4848
|
-
const order = await repos.order.findById(tx, orderId);
|
|
4849
|
-
if (!order) throw new NotFoundError7("order", orderId);
|
|
4850
|
-
const metadata = order.metadata;
|
|
4851
|
-
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
4852
|
-
for (const rid of reservationIds) {
|
|
4853
|
-
await inventory.releaseReservation(rid, "cancelled");
|
|
4854
|
-
}
|
|
4855
|
-
await orders4.cancel(orderId, reason, CANCEL_ACTOR);
|
|
4856
|
-
});
|
|
4857
|
-
}
|
|
4858
|
-
async function checkStock(tx, cartDoc) {
|
|
4859
|
-
for (const item of cartDoc.items) {
|
|
4860
|
-
const v = await repos.variant.findById(tx, item.variantId);
|
|
4861
|
-
if (!v) {
|
|
4862
|
-
throw new CheckoutError("variant_missing", `Variant missing: ${item.variantId}`);
|
|
4863
|
-
}
|
|
4864
|
-
if (v.stock < item.qty) {
|
|
4865
|
-
throw new CheckoutError(
|
|
4866
|
-
"out_of_stock",
|
|
4867
|
-
`Insufficient stock for ${item.variantName}: available ${v.stock}, requested ${item.qty}`
|
|
4868
|
-
);
|
|
4869
|
-
}
|
|
4870
|
-
}
|
|
4871
|
-
}
|
|
4872
|
-
async function place(tx, input, closed) {
|
|
4873
|
-
const cartDoc = await repos.cart.lock(tx, input.cartToken);
|
|
4874
|
-
if (cartDoc === null) throw new NotFoundError7("cart", input.cartToken);
|
|
4875
|
-
if (!cartDoc.items.length) throw await cartEmpty(input.cartToken);
|
|
4876
|
-
const pending = await repos.order.findPendingByCartToken(tx, input.cartToken);
|
|
4877
|
-
if (pending !== null) {
|
|
4878
|
-
const { paymentIntentId } = pending;
|
|
4879
|
-
if (paymentIntentId === null) {
|
|
4880
|
-
if (Date.now() - Date.parse(pending.createdAt) <= ABANDON_AFTER_MS) {
|
|
4881
|
-
throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
|
|
4882
|
-
}
|
|
4883
|
-
await cancelDraft(pending.id, "abandoned: no payment intent");
|
|
4884
|
-
} else {
|
|
4885
|
-
const reason = closed.get(paymentIntentId);
|
|
4886
|
-
if (reason === void 0) {
|
|
4887
|
-
if (sameLines(pending, cartDoc))
|
|
4888
|
-
return { kind: "existing", order: { ...pending, paymentIntentId } };
|
|
4889
|
-
return { kind: "cancel-first", order: { ...pending, paymentIntentId } };
|
|
4890
|
-
}
|
|
4891
|
-
await cancelDraft(pending.id, reason);
|
|
4892
|
-
}
|
|
4893
|
-
}
|
|
4894
|
-
await checkStock(tx, cartDoc);
|
|
4895
|
-
const lineItems = cartDoc.items.map((item) => ({
|
|
4896
|
-
variantId: item.variantId,
|
|
4897
|
-
productId: item.productId,
|
|
4898
|
-
productName: item.productName,
|
|
4899
|
-
variantName: item.variantName,
|
|
4900
|
-
sku: "",
|
|
4901
|
-
qty: item.qty,
|
|
4902
|
-
unitPriceMinor: item.priceMinor,
|
|
4903
|
-
lineSubtotalMinor: item.priceMinor * item.qty,
|
|
4904
|
-
lineTaxMinor: 0,
|
|
4905
|
-
lineTotalMinor: item.priceMinor * item.qty,
|
|
4906
|
-
imageUrl: item.imageUrl
|
|
4907
|
-
}));
|
|
4908
|
-
const orderId = uuidv710();
|
|
4909
|
-
audit.note("checkout.place", [{ type: "order", id: orderId }]);
|
|
4910
|
-
const correlationId = currentCorrelationId();
|
|
4911
|
-
const reservationIds = [];
|
|
4912
|
-
for (const item of cartDoc.items) {
|
|
4913
|
-
try {
|
|
4914
|
-
const r = await inventory.reserveStock(item.variantId, item.qty, orderId);
|
|
4915
|
-
reservationIds.push(r.reservationId);
|
|
4916
|
-
} catch (err) {
|
|
4917
|
-
if (err instanceof CheckoutError) throw err;
|
|
4918
|
-
throw new CheckoutError("reservation_failed", "Inventory reservation failed", {
|
|
4919
|
-
cause: err
|
|
4920
|
-
});
|
|
4921
|
-
}
|
|
4922
|
-
}
|
|
4923
|
-
const order = await orders4.createFromCheckout({
|
|
4924
|
-
orderId,
|
|
4925
|
-
customerId: input.customerId ?? null,
|
|
4926
|
-
email: input.email,
|
|
4927
|
-
billingAddress: input.billingAddress,
|
|
4928
|
-
shippingAddress: input.shippingAddress,
|
|
4929
|
-
lineItems,
|
|
4930
|
-
subtotalMinor: cartDoc.subtotalMinor,
|
|
4931
|
-
taxTotalMinor: 0,
|
|
4932
|
-
shippingTotalMinor: 0,
|
|
4933
|
-
discountTotalMinor: 0,
|
|
4934
|
-
totalMinor: cartDoc.subtotalMinor,
|
|
4935
|
-
currency: cartDoc.currency,
|
|
4936
|
-
...input.notes !== void 0 && { notes: input.notes },
|
|
4937
|
-
metadata: {
|
|
4938
|
-
cartToken: cartDoc.token,
|
|
4939
|
-
reservationIds,
|
|
4940
|
-
...correlationId !== void 0 && { correlationId }
|
|
4941
|
-
},
|
|
4942
|
-
cartToken: cartDoc.token
|
|
4943
|
-
});
|
|
4944
|
-
return { kind: "placed", order };
|
|
4945
|
-
}
|
|
4946
|
-
async function answerExisting(order) {
|
|
4947
|
-
const paymentIntent = await payments.getPaymentIntent(order.paymentIntentId);
|
|
4948
|
-
if (outcomeOf(paymentIntent.status) === "failed") {
|
|
4949
|
-
return { closed: `payment_${paymentIntent.status}` };
|
|
4950
|
-
}
|
|
4951
|
-
return {
|
|
4952
|
-
orderId: order.id,
|
|
4953
|
-
orderNumber: order.orderNumber,
|
|
4954
|
-
paymentIntent,
|
|
4955
|
-
currency: order.currency,
|
|
4956
|
-
totalMinor: order.totalMinor,
|
|
4957
|
-
orderStatus: order.status,
|
|
4958
|
-
payment: { status: "requires_action" }
|
|
4959
|
-
};
|
|
4960
|
-
}
|
|
4961
|
-
async function cancelIntent(order) {
|
|
4962
|
-
try {
|
|
4963
|
-
await payments.cancelPaymentIntent(order.paymentIntentId);
|
|
4964
|
-
} catch (err) {
|
|
4965
|
-
if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
|
|
4966
|
-
throw new CheckoutError(
|
|
4967
|
-
"payment_in_progress",
|
|
4968
|
-
`The payment for order ${order.orderNumber} is already under way`,
|
|
4969
|
-
{ cause: err, context: { orderNumber: order.orderNumber } }
|
|
4970
|
-
);
|
|
4971
|
-
}
|
|
4972
|
-
}
|
|
4973
|
-
async function pay(input, order) {
|
|
4974
|
-
const params = {
|
|
4975
|
-
amountMinor: order.totalMinor,
|
|
4976
|
-
currency: order.currency,
|
|
4977
|
-
orderRef: order.id,
|
|
4978
|
-
receiptEmail: input.email,
|
|
4979
|
-
metadata: { orderId: order.id, orderNumber: order.orderNumber }
|
|
4980
|
-
};
|
|
4981
|
-
if (input.customerId != null) params.customerId = input.customerId;
|
|
4982
|
-
let intent;
|
|
4983
|
-
try {
|
|
4984
|
-
intent = await payments.createPaymentIntent(params);
|
|
4985
|
-
} catch (err) {
|
|
4986
|
-
await cancelDraft(order.id, "payment intent not created");
|
|
4987
|
-
throw err;
|
|
4988
|
-
}
|
|
4989
|
-
let unconfirmed = null;
|
|
4990
|
-
const answer = await store.transaction(async (tx) => {
|
|
4991
|
-
await repos.cart.lock(tx, input.cartToken);
|
|
4992
|
-
await repos.order.setPaymentIntent(tx, order.id, intent.id, /* @__PURE__ */ new Date());
|
|
4993
|
-
await publisher.publish(EVT_PAYMENT_INTENT_CREATED2, {
|
|
4994
|
-
paymentId: intent.id,
|
|
4995
|
-
orderId: order.id
|
|
4996
|
-
});
|
|
4997
|
-
let payment;
|
|
4998
|
-
const outcome = outcomeOf(intent.status);
|
|
4999
|
-
if (outcome === "succeeded") {
|
|
5000
|
-
const done = await finalize(intent.id, {
|
|
5001
|
-
amountMinor: intent.amountMinor,
|
|
5002
|
-
currency: intent.currency
|
|
5003
|
-
});
|
|
5004
|
-
if (!done.finalized) unconfirmed = done.reason ?? "not_confirmed";
|
|
5005
|
-
payment = unconfirmed === null ? { status: "succeeded" } : { status: "failed", reason: unconfirmed };
|
|
5006
|
-
} else if (outcome === "failed") {
|
|
5007
|
-
const reason = `payment_${intent.status}`;
|
|
5008
|
-
await cancelDraft(order.id, reason);
|
|
5009
|
-
await publisher.publish(EVT_PAYMENT_FAILED2, {
|
|
5010
|
-
paymentId: intent.id,
|
|
5011
|
-
orderId: order.id,
|
|
5012
|
-
reason
|
|
5013
|
-
});
|
|
5014
|
-
payment = { status: "failed", reason };
|
|
5015
|
-
} else {
|
|
5016
|
-
payment = { status: "requires_action" };
|
|
5017
|
-
}
|
|
5018
|
-
const current = await repos.order.findById(tx, order.id);
|
|
5019
|
-
logger.info(
|
|
5020
|
-
{ orderId: order.id, orderNumber: order.orderNumber, payment: payment.status },
|
|
5021
|
-
"checkout started"
|
|
5022
|
-
);
|
|
5023
|
-
return {
|
|
5024
|
-
orderId: order.id,
|
|
5025
|
-
orderNumber: order.orderNumber,
|
|
5026
|
-
paymentIntent: intent,
|
|
5027
|
-
currency: order.currency,
|
|
5028
|
-
totalMinor: order.totalMinor,
|
|
5029
|
-
orderStatus: current?.status ?? order.status,
|
|
5030
|
-
payment
|
|
5031
|
-
};
|
|
5032
|
-
});
|
|
5033
|
-
if (unconfirmed !== null && answer.orderStatus === "pending") {
|
|
5034
|
-
await cancelDraft(order.id, unconfirmed);
|
|
5035
|
-
await refundCancelledCapture(
|
|
5036
|
-
intent.id,
|
|
5037
|
-
{ amountMinor: intent.amountMinor, currency: intent.currency },
|
|
5038
|
-
order
|
|
5039
|
-
);
|
|
5040
|
-
return { ...answer, orderStatus: "cancelled" };
|
|
5041
|
-
}
|
|
5042
|
-
return answer;
|
|
5043
|
-
}
|
|
5044
|
-
async function finalize(paymentIntentId, paid) {
|
|
5045
|
-
return store.transaction(async (tx) => {
|
|
5046
|
-
const order = await repos.order.findByPaymentIntentId(tx, paymentIntentId);
|
|
5047
|
-
return inOrderScope(order, () => finalizeLoaded(tx, paymentIntentId, paid, order));
|
|
5048
|
-
});
|
|
5049
|
-
}
|
|
5050
|
-
async function finalizeLoaded(tx, paymentIntentId, paid, order) {
|
|
5051
|
-
const outcome = (order2, reason) => recordOutcome(tx, paymentIntentId, order2, reason);
|
|
5052
|
-
if (order === null || order.status !== "pending") {
|
|
5053
|
-
return settled(tx, paymentIntentId, order, paid);
|
|
5054
|
-
}
|
|
5055
|
-
if (paid.amountMinor !== order.totalMinor || paid.currency.toUpperCase() !== order.currency.toUpperCase()) {
|
|
5056
|
-
return outcome(
|
|
5057
|
-
order,
|
|
5058
|
-
`amount_mismatch: paid ${paid.amountMinor} ${paid.currency.toUpperCase()}, due ${order.totalMinor} ${order.currency.toUpperCase()}`
|
|
5059
|
-
);
|
|
5060
|
-
}
|
|
5061
|
-
try {
|
|
5062
|
-
return await store.savepoint(
|
|
5063
|
-
() => confirm(tx, paymentIntentId, paid, order, PROVIDER_CAPTURE)
|
|
5064
|
-
);
|
|
5065
|
-
} catch (err) {
|
|
5066
|
-
if (err instanceof StockUnavailable) {
|
|
5067
|
-
const current = await repos.order.findById(tx, order.id);
|
|
5068
|
-
if (current?.status !== "pending") return settled(tx, paymentIntentId, current, paid);
|
|
5069
|
-
return outcome(current, `stock_unavailable: ${err.variantId}`);
|
|
5070
|
-
}
|
|
5071
|
-
if (!(err instanceof NoLongerPending)) throw err;
|
|
5072
|
-
}
|
|
5073
|
-
return settled(tx, paymentIntentId, await repos.order.findById(tx, order.id), paid);
|
|
5074
|
-
}
|
|
5075
|
-
return {
|
|
5076
|
-
async beginCheckout(input) {
|
|
5077
|
-
audit.note("checkout.place");
|
|
5078
|
-
await loadValidCart(input.cartToken);
|
|
5079
|
-
const closed = /* @__PURE__ */ new Map();
|
|
5080
|
-
for (let attempt = 0; ; attempt += 1) {
|
|
5081
|
-
const placement = await store.transaction((tx) => place(tx, input, closed));
|
|
5082
|
-
if (placement.kind === "placed") return pay(input, placement.order);
|
|
5083
|
-
if (placement.kind === "existing") {
|
|
5084
|
-
const answer = await answerExisting(placement.order);
|
|
5085
|
-
if (!("closed" in answer)) return answer;
|
|
5086
|
-
closed.set(placement.order.paymentIntentId, answer.closed);
|
|
5087
|
-
continue;
|
|
5088
|
-
}
|
|
5089
|
-
if (attempt === SUPERSEDE_ATTEMPTS) {
|
|
5090
|
-
throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
|
|
5091
|
-
}
|
|
5092
|
-
await cancelIntent(placement.order);
|
|
5093
|
-
closed.set(placement.order.paymentIntentId, "superseded: the cart changed");
|
|
5094
|
-
}
|
|
5095
|
-
},
|
|
5096
|
-
finalize,
|
|
5097
|
-
async cancel(orderId, reason) {
|
|
5098
|
-
await cancelDraft(orderId, reason);
|
|
5099
|
-
},
|
|
5100
|
-
async markPaid(orderId, actor, note) {
|
|
5101
|
-
audit.note("order.markPaid", [{ type: "order", id: orderId }]);
|
|
5102
|
-
const found = await store.read((tx) => repos.order.findById(tx, orderId));
|
|
5103
|
-
if (!found) throw new NotFoundError7("order", orderId);
|
|
5104
|
-
if (found.status !== "pending") {
|
|
5105
|
-
throw new StatusTransitionError2("order", found.status, "confirmed");
|
|
5106
|
-
}
|
|
5107
|
-
if (found.paymentIntentId) {
|
|
5108
|
-
try {
|
|
5109
|
-
await payments.cancelPaymentIntent(found.paymentIntentId);
|
|
5110
|
-
} catch (err) {
|
|
5111
|
-
if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
|
|
5112
|
-
throw new OrderConflictError2(
|
|
5113
|
-
"order.payment_in_progress",
|
|
5114
|
-
`The payment for order ${found.orderNumber} is under way with the provider`,
|
|
5115
|
-
{ cause: err, context: { orderNumber: found.orderNumber } }
|
|
5116
|
-
);
|
|
5117
|
-
}
|
|
5118
|
-
}
|
|
5119
|
-
return store.transaction(async (tx) => {
|
|
5120
|
-
const order = await repos.order.lock(tx, orderId);
|
|
5121
|
-
if (!order) throw new NotFoundError7("order", orderId);
|
|
5122
|
-
if (order.status !== "pending") {
|
|
5123
|
-
throw new StatusTransitionError2("order", order.status, "confirmed");
|
|
5124
|
-
}
|
|
5125
|
-
const capture = {
|
|
5126
|
-
method: "manual",
|
|
5127
|
-
actor,
|
|
5128
|
-
note: note ? `payment recorded manually: ${note}` : "payment recorded manually"
|
|
5129
|
-
};
|
|
5130
|
-
const paid = { amountMinor: order.totalMinor, currency: order.currency };
|
|
5131
|
-
try {
|
|
5132
|
-
await inOrderScope(order, () => confirm(tx, "", paid, order, capture));
|
|
5133
|
-
} catch (err) {
|
|
5134
|
-
if (!(err instanceof StockUnavailable)) throw err;
|
|
5135
|
-
throw new OrderConflictError2(
|
|
5136
|
-
"order.stock_unavailable",
|
|
5137
|
-
`The stock order ${order.orderNumber} held has gone to another order`,
|
|
5138
|
-
{ context: { variantId: err.variantId } }
|
|
5139
|
-
);
|
|
5140
|
-
}
|
|
5141
|
-
return await repos.order.findById(tx, order.id);
|
|
5142
|
-
});
|
|
5143
|
-
}
|
|
5144
|
-
};
|
|
5145
|
-
}
|
|
5146
|
-
|
|
5147
|
-
// src/services/search-service.ts
|
|
5148
|
-
function createSearchService(deps) {
|
|
5149
|
-
return {
|
|
5150
|
-
async products(query, params) {
|
|
5151
|
-
return deps.adapter.search(query, params);
|
|
5152
|
-
}
|
|
5153
|
-
};
|
|
5154
|
-
}
|
|
5155
|
-
|
|
5156
|
-
// src/services/index.ts
|
|
5157
|
-
function buildServices(deps) {
|
|
5158
|
-
const { config, store, repos, publisher, logger, payments, searchAdapter } = deps;
|
|
5159
|
-
const inventory = createInventoryService({
|
|
5160
|
-
store,
|
|
5161
|
-
repos,
|
|
5162
|
-
publisher,
|
|
5163
|
-
logger: logger.child({ service: "inventory" })
|
|
5164
|
-
});
|
|
5165
|
-
const orders4 = createOrderService({
|
|
5166
|
-
store,
|
|
5167
|
-
repos,
|
|
5168
|
-
publisher,
|
|
5169
|
-
logger: logger.child({ service: "order" }),
|
|
5170
|
-
orderNumberPrefix: config.commerce.orders.numberPrefix,
|
|
5171
|
-
orderNumberStart: config.commerce.orders.numberStart
|
|
5172
|
-
});
|
|
5173
|
-
const cart = createCartService({
|
|
5174
|
-
store,
|
|
5175
|
-
carts: repos.cart,
|
|
5176
|
-
publisher,
|
|
5177
|
-
logger: logger.child({ service: "cart" }),
|
|
5178
|
-
currency: config.store.currency
|
|
5179
|
-
});
|
|
5180
|
-
const checkout = createCheckoutService({
|
|
5181
|
-
store,
|
|
5182
|
-
repos,
|
|
5183
|
-
publisher,
|
|
5184
|
-
logger: logger.child({ service: "checkout" }),
|
|
5185
|
-
cart,
|
|
5186
|
-
orders: orders4,
|
|
5187
|
-
inventory,
|
|
5188
|
-
payments,
|
|
5189
|
-
currency: config.store.currency
|
|
5190
|
-
});
|
|
5191
|
-
return {
|
|
5192
|
-
product: createProductService({
|
|
5193
|
-
store,
|
|
5194
|
-
repos,
|
|
5195
|
-
publisher,
|
|
5196
|
-
logger: logger.child({ service: "product" })
|
|
5197
|
-
}),
|
|
5198
|
-
category: createCategoryService({
|
|
5199
|
-
repos,
|
|
5200
|
-
publisher,
|
|
5201
|
-
logger: logger.child({ service: "category" })
|
|
5202
|
-
}),
|
|
5203
|
-
cart,
|
|
5204
|
-
customer: createCustomerService({
|
|
5205
|
-
repos,
|
|
5206
|
-
publisher,
|
|
5207
|
-
logger: logger.child({ service: "customer" })
|
|
5208
|
-
}),
|
|
5209
|
-
auth: createAuthService({
|
|
5210
|
-
repos,
|
|
5211
|
-
publisher,
|
|
5212
|
-
logger: logger.child({ service: "auth" }),
|
|
5213
|
-
jwtSecret: config.security.auth.jwtSecret,
|
|
5214
|
-
accessTtl: config.security.auth.accessTtl,
|
|
5215
|
-
refreshTtl: config.security.auth.refreshTtl
|
|
5216
|
-
}),
|
|
5217
|
-
order: orders4,
|
|
5218
|
-
inventory,
|
|
5219
|
-
checkout,
|
|
5220
|
-
refund: createRefundService({
|
|
5221
|
-
store,
|
|
5222
|
-
repos,
|
|
5223
|
-
publisher,
|
|
5224
|
-
logger: logger.child({ service: "refund" }),
|
|
5225
|
-
payments
|
|
5226
|
-
}),
|
|
5227
|
-
search: createSearchService({
|
|
5228
|
-
adapter: searchAdapter,
|
|
5229
|
-
logger: logger.child({ service: "search" })
|
|
5230
|
-
})
|
|
5231
|
-
};
|
|
5232
|
-
}
|
|
5233
|
-
|
|
5234
|
-
// src/read-models/index.ts
|
|
5235
|
-
import { errorText } from "@nymbalhq/types";
|
|
5236
|
-
|
|
5237
|
-
// src/read-models/catalogue.ts
|
|
5238
|
-
function snapshotsOf({ repos }) {
|
|
5239
|
-
return async (tx, page) => {
|
|
5240
|
-
const out = [];
|
|
5241
|
-
for (const p of await repos.product.listPage(tx, page)) {
|
|
5242
|
-
out.push(await productSnapshot(tx, repos, p));
|
|
5243
|
-
}
|
|
5244
|
-
return out;
|
|
3673
|
+
return out;
|
|
5245
3674
|
};
|
|
5246
3675
|
}
|
|
5247
3676
|
var catalogue = {
|
|
@@ -5260,8 +3689,8 @@ var catalogue = {
|
|
|
5260
3689
|
}
|
|
5261
3690
|
const context = { storeId, currency: config.store.currency, logger };
|
|
5262
3691
|
for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
|
|
5263
|
-
for (const
|
|
5264
|
-
yield* productWrites(buildProductDoc(
|
|
3692
|
+
for (const snapshot of page) {
|
|
3693
|
+
yield* productWrites(buildProductDoc(snapshot, categories3, context));
|
|
5265
3694
|
}
|
|
5266
3695
|
}
|
|
5267
3696
|
},
|
|
@@ -5346,8 +3775,8 @@ var search = {
|
|
|
5346
3775
|
collections: [],
|
|
5347
3776
|
async *rebuild(ctx) {
|
|
5348
3777
|
for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
|
|
5349
|
-
for (const
|
|
5350
|
-
const doc = buildSearchDoc(
|
|
3778
|
+
for (const snapshot of page) {
|
|
3779
|
+
const doc = buildSearchDoc(snapshot);
|
|
5351
3780
|
yield { collection: SEARCH_INDEX, key: doc.id, doc };
|
|
5352
3781
|
}
|
|
5353
3782
|
}
|
|
@@ -5358,7 +3787,13 @@ var search = {
|
|
|
5358
3787
|
};
|
|
5359
3788
|
|
|
5360
3789
|
// src/read-models/index.ts
|
|
5361
|
-
var READ_MODELS = [
|
|
3790
|
+
var READ_MODELS = [
|
|
3791
|
+
catalogue,
|
|
3792
|
+
orders3,
|
|
3793
|
+
customers3,
|
|
3794
|
+
search,
|
|
3795
|
+
recentlyViewed
|
|
3796
|
+
];
|
|
5362
3797
|
var READ_MODEL_NAMES = READ_MODELS.map((m) => m.name);
|
|
5363
3798
|
var CATCH_UP_MARGIN_MS = 10 * 6e4;
|
|
5364
3799
|
var DEFAULT_PAGE_SIZE = 200;
|
|
@@ -5389,7 +3824,8 @@ function modelsOf(names) {
|
|
|
5389
3824
|
function contextFor(model, deps) {
|
|
5390
3825
|
const limit = deps.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
5391
3826
|
let page = 0;
|
|
5392
|
-
|
|
3827
|
+
let logReadThrough;
|
|
3828
|
+
const ctx = {
|
|
5393
3829
|
deps,
|
|
5394
3830
|
async *pages(table, read) {
|
|
5395
3831
|
let after;
|
|
@@ -5402,15 +3838,35 @@ function contextFor(model, deps) {
|
|
|
5402
3838
|
if (rows.length < limit) return;
|
|
5403
3839
|
after = rows[rows.length - 1].id;
|
|
5404
3840
|
}
|
|
3841
|
+
},
|
|
3842
|
+
async *events(types) {
|
|
3843
|
+
let after = 0;
|
|
3844
|
+
logReadThrough ??= 0;
|
|
3845
|
+
for (; ; ) {
|
|
3846
|
+
await deps.onPage?.({ model: model.name, table: "events", page });
|
|
3847
|
+
page += 1;
|
|
3848
|
+
const rows = await deps.store.read(
|
|
3849
|
+
(tx) => deps.repos.eventLog.listAfter(tx, after, { types: [...types], limit })
|
|
3850
|
+
);
|
|
3851
|
+
if (rows.length > 0) {
|
|
3852
|
+
after = rows[rows.length - 1].seq;
|
|
3853
|
+
logReadThrough = Math.max(logReadThrough, after);
|
|
3854
|
+
const live = rows.filter((r) => r.deadAt === null);
|
|
3855
|
+
if (live.length > 0) yield live;
|
|
3856
|
+
}
|
|
3857
|
+
if (rows.length < limit) return;
|
|
3858
|
+
}
|
|
5405
3859
|
}
|
|
5406
3860
|
};
|
|
3861
|
+
return { ctx, logReadThrough: () => logReadThrough };
|
|
5407
3862
|
}
|
|
5408
3863
|
async function collect(model, deps) {
|
|
5409
3864
|
const startedAt = Date.now();
|
|
5410
3865
|
const owned = model.target === "search" ? [SEARCH_INDEX] : model.collections;
|
|
5411
3866
|
const writes = new Map(owned.map((c) => [c, /* @__PURE__ */ new Map()]));
|
|
3867
|
+
const { ctx, logReadThrough } = contextFor(model, deps);
|
|
5412
3868
|
try {
|
|
5413
|
-
for await (const w of model.rebuild(
|
|
3869
|
+
for await (const w of model.rebuild(ctx)) {
|
|
5414
3870
|
const into = writes.get(w.collection);
|
|
5415
3871
|
if (into === void 0) throw new Error(`it wrote to ${w.collection}, which it does not own`);
|
|
5416
3872
|
into.set(w.key, w.doc);
|
|
@@ -5418,7 +3874,7 @@ async function collect(model, deps) {
|
|
|
5418
3874
|
} catch (error) {
|
|
5419
3875
|
throw new RebuildError(model.name, error);
|
|
5420
3876
|
}
|
|
5421
|
-
return { model, startedAt, writes };
|
|
3877
|
+
return { model, startedAt, writes, logReadThrough: logReadThrough() };
|
|
5422
3878
|
}
|
|
5423
3879
|
async function* entries(docs) {
|
|
5424
3880
|
yield* docs;
|
|
@@ -5439,11 +3895,10 @@ async function swap({ model, writes }, deps) {
|
|
|
5439
3895
|
await search2.index(docs);
|
|
5440
3896
|
return `${search2.providerName} has no replaceAll: every document was indexed, removals not guaranteed`;
|
|
5441
3897
|
}
|
|
5442
|
-
async function catchUp(model, since, deps) {
|
|
3898
|
+
async function catchUp(model, since, deps, afterSeq = 0) {
|
|
5443
3899
|
const handlers = model.handlers(deps);
|
|
5444
3900
|
const failures = [];
|
|
5445
3901
|
let applied = 0;
|
|
5446
|
-
let afterSeq = 0;
|
|
5447
3902
|
for (; ; ) {
|
|
5448
3903
|
const page = await deps.store.read(
|
|
5449
3904
|
(tx) => deps.repos.eventLog.listForCatchUp(tx, since, { afterSeq, limit: CATCH_UP_PAGE })
|
|
@@ -5479,7 +3934,8 @@ async function rebuild(names, deps) {
|
|
|
5479
3934
|
const { applied, failures } = await catchUp(
|
|
5480
3935
|
c.model,
|
|
5481
3936
|
new Date(c.startedAt - CATCH_UP_MARGIN_MS),
|
|
5482
|
-
deps
|
|
3937
|
+
deps,
|
|
3938
|
+
c.logReadThrough
|
|
5483
3939
|
);
|
|
5484
3940
|
const entry = {
|
|
5485
3941
|
model: c.model.name,
|
|
@@ -5840,7 +4296,8 @@ async function createApp(config, options = {}) {
|
|
|
5840
4296
|
store: platform.commandStore,
|
|
5841
4297
|
eventLog: repos.eventLog,
|
|
5842
4298
|
eventBus: platform.eventBus,
|
|
5843
|
-
logger
|
|
4299
|
+
logger,
|
|
4300
|
+
...options.relay
|
|
5844
4301
|
});
|
|
5845
4302
|
const subscriberBus = deliveringBus(platform.eventBus, relay);
|
|
5846
4303
|
const publisher = createEventPublisher({
|
|
@@ -5862,7 +4319,8 @@ async function createApp(config, options = {}) {
|
|
|
5862
4319
|
publisher,
|
|
5863
4320
|
logger: logger.child({ layer: "service" }),
|
|
5864
4321
|
payments: adapters.payments,
|
|
5865
|
-
searchAdapter: adapters.search
|
|
4322
|
+
searchAdapter: adapters.search,
|
|
4323
|
+
email: adapters.email
|
|
5866
4324
|
});
|
|
5867
4325
|
await registerHandlers({
|
|
5868
4326
|
config,
|
|
@@ -5870,6 +4328,7 @@ async function createApp(config, options = {}) {
|
|
|
5870
4328
|
documentStore: platform.documentStore,
|
|
5871
4329
|
repos,
|
|
5872
4330
|
adapters,
|
|
4331
|
+
alerts: services.alert,
|
|
5873
4332
|
logger
|
|
5874
4333
|
});
|
|
5875
4334
|
await rebuild(READ_MODEL_NAMES, {
|
|
@@ -5912,7 +4371,7 @@ async function createApp(config, options = {}) {
|
|
|
5912
4371
|
relay,
|
|
5913
4372
|
async attachHttp(adapter, options2 = {}) {
|
|
5914
4373
|
await adapters.security.applyMiddleware(adapter, config.security);
|
|
5915
|
-
const { registerAllRoutes: registerAllRoutes2 } = await import("./register-
|
|
4374
|
+
const { registerAllRoutes: registerAllRoutes2 } = await import("./register-N2XGSFUF.js");
|
|
5916
4375
|
registerAllRoutes2({
|
|
5917
4376
|
config,
|
|
5918
4377
|
adapter,
|
|
@@ -6033,26 +4492,6 @@ function compilePathPattern(pattern) {
|
|
|
6033
4492
|
return new RegExp(`^${escaped}$`);
|
|
6034
4493
|
}
|
|
6035
4494
|
|
|
6036
|
-
// src/adapters/ai/native-adapter.ts
|
|
6037
|
-
import { AdapterError as AdapterError3 } from "@nymbalhq/types";
|
|
6038
|
-
function createNativeAiAdapter(_logger) {
|
|
6039
|
-
return {
|
|
6040
|
-
kind: "ai",
|
|
6041
|
-
providerName: "native",
|
|
6042
|
-
capabilities: () => [],
|
|
6043
|
-
producesEvents: [],
|
|
6044
|
-
consumesEvents: [],
|
|
6045
|
-
initialize: noopInitialize,
|
|
6046
|
-
healthCheck: () => okHealth("AI adapter is stubbed \u2014 configure a real provider for v1.0"),
|
|
6047
|
-
async embed() {
|
|
6048
|
-
throw new AdapterError3("not_configured", "AI embedding is not configured in v0.1");
|
|
6049
|
-
},
|
|
6050
|
-
async complete() {
|
|
6051
|
-
throw new AdapterError3("not_configured", "AI completion is not configured in v0.1");
|
|
6052
|
-
}
|
|
6053
|
-
};
|
|
6054
|
-
}
|
|
6055
|
-
|
|
6056
4495
|
// src/diagnose.ts
|
|
6057
4496
|
import { existsSync } from "fs";
|
|
6058
4497
|
import { resolve as resolve3 } from "path";
|
|
@@ -6335,6 +4774,7 @@ async function diagnose(input, options = {}) {
|
|
|
6335
4774
|
primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
|
|
6336
4775
|
}
|
|
6337
4776
|
}
|
|
4777
|
+
const eventsCheck = commandStore === void 0 ? { name: "events", status: "down", detail: notChecked("command store") } : migrationsCheck.status !== "ok" ? { name: "events", status: "down", detail: notChecked("migrations") } : await eventLogCheck(commandStore, timeoutMs);
|
|
6338
4778
|
for (const close of closers) {
|
|
6339
4779
|
const closed = await within(timeoutMs, close);
|
|
6340
4780
|
if (!closed.ok) logger.debug({ detail: closed.detail }, "diagnose: a connection did not close");
|
|
@@ -6348,22 +4788,47 @@ async function diagnose(input, options = {}) {
|
|
|
6348
4788
|
storeCheck,
|
|
6349
4789
|
migrationsCheck,
|
|
6350
4790
|
...slots,
|
|
6351
|
-
...primitives
|
|
4791
|
+
...primitives,
|
|
4792
|
+
eventsCheck
|
|
6352
4793
|
].map((check) => ({
|
|
6353
4794
|
...check,
|
|
6354
4795
|
detail: scrub(secrets.reduce((text2, secret) => text2.split(secret).join("***"), check.detail))
|
|
6355
4796
|
}));
|
|
6356
4797
|
return { checks };
|
|
6357
4798
|
}
|
|
4799
|
+
var DEAD_SHOWN = 5;
|
|
4800
|
+
async function eventLogCheck(store, timeoutMs) {
|
|
4801
|
+
const eventLog = createEventLogRepository(store);
|
|
4802
|
+
const read = await within(
|
|
4803
|
+
timeoutMs,
|
|
4804
|
+
() => store.read(async (tx) => ({
|
|
4805
|
+
dead: await eventLog.countDead(tx),
|
|
4806
|
+
shown: await eventLog.listDead(tx, DEAD_SHOWN),
|
|
4807
|
+
waiting: await eventLog.countRetrying(tx)
|
|
4808
|
+
}))
|
|
4809
|
+
);
|
|
4810
|
+
if (!read.ok) return { name: "events", status: "down", detail: read.detail };
|
|
4811
|
+
const { dead, shown, waiting } = read.value;
|
|
4812
|
+
if (dead === 0) {
|
|
4813
|
+
return { name: "events", status: "ok", detail: `none dead, ${waiting} waiting to retry` };
|
|
4814
|
+
}
|
|
4815
|
+
const named = shown.map((e) => `seq ${e.seq} ${e.event.type} ${e.event.id}`);
|
|
4816
|
+
if (dead > shown.length) named.push(`${dead - shown.length} more`);
|
|
4817
|
+
return {
|
|
4818
|
+
name: "events",
|
|
4819
|
+
status: "degraded",
|
|
4820
|
+
detail: `${dead} dead: ${named.join(", ")}; ${waiting} waiting to retry`
|
|
4821
|
+
};
|
|
4822
|
+
}
|
|
6358
4823
|
function fromReport(name, what, report) {
|
|
6359
4824
|
return { name, status: report.status, detail: described(what, report.detail) };
|
|
6360
4825
|
}
|
|
6361
4826
|
|
|
6362
4827
|
// src/seed/run.ts
|
|
6363
|
-
import { inArray as
|
|
6364
|
-
import { v7 as
|
|
6365
|
-
import
|
|
6366
|
-
import { EVT_CATEGORY_CREATED as
|
|
4828
|
+
import { inArray as inArray4 } from "drizzle-orm";
|
|
4829
|
+
import { v7 as uuidv74 } from "uuid";
|
|
4830
|
+
import bcrypt from "bcryptjs";
|
|
4831
|
+
import { EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3, EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3, EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3 } from "@nymbalhq/types";
|
|
6367
4832
|
|
|
6368
4833
|
// src/seed/data.ts
|
|
6369
4834
|
var seedCategories = [
|
|
@@ -6423,7 +4888,7 @@ function seedImage(product) {
|
|
|
6423
4888
|
}
|
|
6424
4889
|
|
|
6425
4890
|
// src/seed/run.ts
|
|
6426
|
-
var { hashSync } =
|
|
4891
|
+
var { hashSync } = bcrypt;
|
|
6427
4892
|
async function insertVariants(store, rows) {
|
|
6428
4893
|
if (rows.length === 0) return;
|
|
6429
4894
|
const clients = rawClients(store);
|
|
@@ -6480,13 +4945,13 @@ async function demoRowsPresent(store, emails) {
|
|
|
6480
4945
|
const clients = rawClients(store);
|
|
6481
4946
|
if (clients.kind === "sqlite") {
|
|
6482
4947
|
const { categories: categories4, products: products4, customers: customers5 } = sqlite_exports;
|
|
6483
|
-
return clients.db.select({ id: categories4.id }).from(categories4).where(
|
|
4948
|
+
return clients.db.select({ id: categories4.id }).from(categories4).where(inArray4(categories4.slug, categorySlugs)).limit(1).all().length > 0 || clients.db.select({ id: products4.id }).from(products4).where(inArray4(products4.slug, productSlugs)).limit(1).all().length > 0 || clients.db.select({ id: customers5.id }).from(customers5).where(inArray4(customers5.email, emails)).limit(1).all().length > 0;
|
|
6484
4949
|
}
|
|
6485
4950
|
const { categories: categories3, products: products3, customers: customers4 } = postgres_exports;
|
|
6486
4951
|
const [category, product, customer] = await Promise.all([
|
|
6487
|
-
clients.db.select({ id: categories3.id }).from(categories3).where(
|
|
6488
|
-
clients.db.select({ id: products3.id }).from(products3).where(
|
|
6489
|
-
clients.db.select({ id: customers4.id }).from(customers4).where(
|
|
4952
|
+
clients.db.select({ id: categories3.id }).from(categories3).where(inArray4(categories3.slug, categorySlugs)).limit(1),
|
|
4953
|
+
clients.db.select({ id: products3.id }).from(products3).where(inArray4(products3.slug, productSlugs)).limit(1),
|
|
4954
|
+
clients.db.select({ id: customers4.id }).from(customers4).where(inArray4(customers4.email, emails)).limit(1)
|
|
6490
4955
|
]);
|
|
6491
4956
|
return category.length > 0 || product.length > 0 || customer.length > 0;
|
|
6492
4957
|
}
|
|
@@ -6529,6 +4994,9 @@ async function insertCustomer(store, row) {
|
|
|
6529
4994
|
updatedAt: row.updatedAt
|
|
6530
4995
|
});
|
|
6531
4996
|
}
|
|
4997
|
+
function failedOf2(err) {
|
|
4998
|
+
return err.context?.failed ?? [];
|
|
4999
|
+
}
|
|
6532
5000
|
async function runSeed(deps) {
|
|
6533
5001
|
const { config, commandStore, documentStore, eventBus, logger, version } = deps;
|
|
6534
5002
|
const categoryRepo = createCategoryRepository(commandStore);
|
|
@@ -6547,7 +5015,7 @@ async function runSeed(deps) {
|
|
|
6547
5015
|
}
|
|
6548
5016
|
const now = /* @__PURE__ */ new Date();
|
|
6549
5017
|
const categoryInserts = seedCategories.map((c, i) => ({
|
|
6550
|
-
id:
|
|
5018
|
+
id: uuidv74(),
|
|
6551
5019
|
slug: c.slug,
|
|
6552
5020
|
name: c.name,
|
|
6553
5021
|
description: c.description,
|
|
@@ -6565,7 +5033,7 @@ async function runSeed(deps) {
|
|
|
6565
5033
|
}
|
|
6566
5034
|
}
|
|
6567
5035
|
const productInserts = seedProducts.map((p) => ({
|
|
6568
|
-
id:
|
|
5036
|
+
id: uuidv74(),
|
|
6569
5037
|
slug: p.slug,
|
|
6570
5038
|
name: p.title,
|
|
6571
5039
|
description: p.description,
|
|
@@ -6583,7 +5051,7 @@ async function runSeed(deps) {
|
|
|
6583
5051
|
const variantInserts = productInserts.map((p, i) => {
|
|
6584
5052
|
const seed = seedProducts[i];
|
|
6585
5053
|
return {
|
|
6586
|
-
id:
|
|
5054
|
+
id: uuidv74(),
|
|
6587
5055
|
productId: p.id,
|
|
6588
5056
|
sku: p.slug.toUpperCase().replaceAll("-", "_"),
|
|
6589
5057
|
name: "Default",
|
|
@@ -6603,7 +5071,7 @@ async function runSeed(deps) {
|
|
|
6603
5071
|
});
|
|
6604
5072
|
await insertProductCategories(commandStore, joinRows);
|
|
6605
5073
|
const demoCustomer = {
|
|
6606
|
-
id:
|
|
5074
|
+
id: uuidv74(),
|
|
6607
5075
|
email: demoEmail,
|
|
6608
5076
|
passwordHash: hashSync("nymbal", 10),
|
|
6609
5077
|
firstName: "Demo",
|
|
@@ -6615,7 +5083,7 @@ async function runSeed(deps) {
|
|
|
6615
5083
|
const adminPassword = process.env["NYMBAL_ADMIN_PASSWORD"] ?? "nymbal-admin-dev";
|
|
6616
5084
|
const adminRoles = ["admin"];
|
|
6617
5085
|
const adminCustomer = {
|
|
6618
|
-
id:
|
|
5086
|
+
id: uuidv74(),
|
|
6619
5087
|
email: adminEmail,
|
|
6620
5088
|
passwordHash: hashSync(adminPassword, 10),
|
|
6621
5089
|
firstName: "Admin",
|
|
@@ -6627,7 +5095,7 @@ async function runSeed(deps) {
|
|
|
6627
5095
|
await insertCustomer(commandStore, adminCustomer);
|
|
6628
5096
|
const events3 = [
|
|
6629
5097
|
...categoryInserts.map(
|
|
6630
|
-
(c) => makeEvent(
|
|
5098
|
+
(c) => makeEvent(EVT_CATEGORY_CREATED3, {
|
|
6631
5099
|
category: {
|
|
6632
5100
|
id: c.id,
|
|
6633
5101
|
parentId: c.parentId,
|
|
@@ -6643,7 +5111,7 @@ async function runSeed(deps) {
|
|
|
6643
5111
|
const v = variantInserts[i];
|
|
6644
5112
|
const seed = seedProducts[i];
|
|
6645
5113
|
const cat = categoryBySlug.get(seed.categorySlug);
|
|
6646
|
-
return makeEvent(
|
|
5114
|
+
return makeEvent(EVT_PRODUCT_CREATED3, {
|
|
6647
5115
|
product: {
|
|
6648
5116
|
id: p.id,
|
|
6649
5117
|
slug: p.slug,
|
|
@@ -6680,16 +5148,27 @@ async function runSeed(deps) {
|
|
|
6680
5148
|
}
|
|
6681
5149
|
});
|
|
6682
5150
|
}),
|
|
6683
|
-
makeEvent(
|
|
5151
|
+
makeEvent(EVT_CUSTOMER_CREATED3, {
|
|
6684
5152
|
customerId: demoCustomer.id,
|
|
6685
5153
|
email: demoCustomer.email
|
|
6686
5154
|
}),
|
|
6687
|
-
makeEvent(
|
|
5155
|
+
makeEvent(EVT_CUSTOMER_CREATED3, {
|
|
6688
5156
|
customerId: adminCustomer.id,
|
|
6689
5157
|
email: adminCustomer.email
|
|
6690
5158
|
})
|
|
6691
5159
|
];
|
|
6692
|
-
|
|
5160
|
+
const failures = [];
|
|
5161
|
+
for (const event of events3) {
|
|
5162
|
+
try {
|
|
5163
|
+
await eventBus.publish(event);
|
|
5164
|
+
} catch (err) {
|
|
5165
|
+
if (err?.code !== "adapter.handler_failed") throw err;
|
|
5166
|
+
failures.push({ eventId: event.id, eventType: event.type, failed: failedOf2(err) });
|
|
5167
|
+
}
|
|
5168
|
+
}
|
|
5169
|
+
if (failures.length > 0) {
|
|
5170
|
+
logger.warn({ failures }, "seed events whose handlers failed; they are not retried");
|
|
5171
|
+
}
|
|
6693
5172
|
logger.info({ adminEmail }, "Admin user seeded");
|
|
6694
5173
|
if (!process.env["NYMBAL_ADMIN_EMAIL"]) {
|
|
6695
5174
|
console.log(
|
|
@@ -6786,6 +5265,8 @@ export {
|
|
|
6786
5265
|
buildRepositories,
|
|
6787
5266
|
buildSecurityHeaders,
|
|
6788
5267
|
buildServices,
|
|
5268
|
+
createAlertService,
|
|
5269
|
+
createAlertSubscriptionRepository,
|
|
6789
5270
|
createApp,
|
|
6790
5271
|
createAuditEntryRepository,
|
|
6791
5272
|
createAuthService,
|
|
@@ -6807,7 +5288,6 @@ export {
|
|
|
6807
5288
|
createLocalFsMediaStorage,
|
|
6808
5289
|
createLogger,
|
|
6809
5290
|
createMiddlewareSecurityAdapter,
|
|
6810
|
-
createNativeAiAdapter,
|
|
6811
5291
|
createNativeAnalyticsAdapter,
|
|
6812
5292
|
createNativeEmailAdapter,
|
|
6813
5293
|
createNativeReviewsAdapter,
|
|
@@ -6815,6 +5295,7 @@ export {
|
|
|
6815
5295
|
createNativeShippingAdapter,
|
|
6816
5296
|
createNativeStubPaymentsAdapter,
|
|
6817
5297
|
createNativeTaxAdapter,
|
|
5298
|
+
createOrderAccessKeyRepository,
|
|
6818
5299
|
createOrderHistoryRepository,
|
|
6819
5300
|
createOrderRefundRepository,
|
|
6820
5301
|
createOrderRepository,
|
|
@@ -6825,6 +5306,7 @@ export {
|
|
|
6825
5306
|
createProductCategoryRepository,
|
|
6826
5307
|
createProductRepository2 as createProductRepository,
|
|
6827
5308
|
createProductService,
|
|
5309
|
+
createRecentlyViewedService,
|
|
6828
5310
|
createRefreshTokenRepository,
|
|
6829
5311
|
createRefundService,
|
|
6830
5312
|
createRelay,
|
|
@@ -6838,6 +5320,7 @@ export {
|
|
|
6838
5320
|
decrypt,
|
|
6839
5321
|
diagnose,
|
|
6840
5322
|
diffReadModel,
|
|
5323
|
+
emailDelivers,
|
|
6841
5324
|
encodeSearchCursor,
|
|
6842
5325
|
encrypt,
|
|
6843
5326
|
fillFromSettings,
|
|
@@ -6849,14 +5332,18 @@ export {
|
|
|
6849
5332
|
keyId,
|
|
6850
5333
|
keyProblem,
|
|
6851
5334
|
listAuditEntries,
|
|
5335
|
+
newAlertToken,
|
|
6852
5336
|
newCorrelationId,
|
|
6853
5337
|
openReadModels,
|
|
6854
5338
|
orderPayment,
|
|
5339
|
+
parseDurationToMs,
|
|
6855
5340
|
rawClients,
|
|
6856
5341
|
readSecretsKey,
|
|
6857
5342
|
rebuild,
|
|
6858
5343
|
refreshRefunded,
|
|
6859
5344
|
registerAdminStaticRoute,
|
|
5345
|
+
registerAlertHandler,
|
|
5346
|
+
registerAlertRoutes,
|
|
6860
5347
|
registerAllRoutes,
|
|
6861
5348
|
registerHandlers,
|
|
6862
5349
|
resolvePrimitives,
|