@nymbalhq/platform 1.2.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-UBEGSSFI.js → chunk-GMV3B3SC.js} +3681 -389
- package/dist/chunk-GMV3B3SC.js.map +1 -0
- package/dist/{chunk-XVUH34US.js → chunk-SNNK2OX3.js} +129 -7
- package/dist/chunk-SNNK2OX3.js.map +1 -0
- package/dist/db/schema/index.d.ts +1821 -323
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +239 -10
- package/dist/index.js +734 -2169
- package/dist/index.js.map +1 -1
- package/dist/register-N2XGSFUF.js +8 -0
- package/migrations/postgres/0012_event_subject.sql +27 -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/0012_snapshot.json +1926 -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 +28 -0
- package/migrations/sqlite/0012_event_subject.sql +27 -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/0012_snapshot.json +1728 -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 +28 -0
- package/package.json +19 -19
- package/dist/chunk-UBEGSSFI.js.map +0 -1
- package/dist/chunk-XVUH34US.js.map +0 -1
- package/dist/register-NHG3TIRQ.js +0 -8
- /package/dist/{register-NHG3TIRQ.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,
|
|
@@ -74,9 +105,12 @@ import {
|
|
|
74
105
|
settlementOf,
|
|
75
106
|
slotBuilders,
|
|
76
107
|
sqliteDb,
|
|
77
|
-
sqliteFile
|
|
78
|
-
|
|
108
|
+
sqliteFile,
|
|
109
|
+
subscribeDerived
|
|
110
|
+
} from "./chunk-GMV3B3SC.js";
|
|
79
111
|
import {
|
|
112
|
+
alertSubscriptions,
|
|
113
|
+
alertSubscriptions2,
|
|
80
114
|
carts,
|
|
81
115
|
carts2,
|
|
82
116
|
categories,
|
|
@@ -87,6 +121,8 @@ import {
|
|
|
87
121
|
events2,
|
|
88
122
|
inventoryReservations,
|
|
89
123
|
inventoryReservations2,
|
|
124
|
+
orderAccessKeys,
|
|
125
|
+
orderAccessKeys2,
|
|
90
126
|
orderHistory,
|
|
91
127
|
orderHistory2,
|
|
92
128
|
orderRefunds,
|
|
@@ -111,7 +147,7 @@ import {
|
|
|
111
147
|
stockAdjustments2,
|
|
112
148
|
variants,
|
|
113
149
|
variants2
|
|
114
|
-
} from "./chunk-
|
|
150
|
+
} from "./chunk-SNNK2OX3.js";
|
|
115
151
|
|
|
116
152
|
// src/platform.ts
|
|
117
153
|
import { join as join2 } from "path";
|
|
@@ -242,7 +278,7 @@ var InMemoryDocumentStore = class {
|
|
|
242
278
|
|
|
243
279
|
// src/event-bus/in-process.ts
|
|
244
280
|
import { v7 as uuidv7 } from "uuid";
|
|
245
|
-
import { ValidationError } from "@nymbalhq/types";
|
|
281
|
+
import { handlerFailedError, ValidationError } from "@nymbalhq/types";
|
|
246
282
|
var InProcessEventBus = class {
|
|
247
283
|
#registrations = /* @__PURE__ */ new Map();
|
|
248
284
|
#logger;
|
|
@@ -257,35 +293,44 @@ var InProcessEventBus = class {
|
|
|
257
293
|
return { status: "healthy" };
|
|
258
294
|
}
|
|
259
295
|
async publish(event) {
|
|
260
|
-
await this.#deliver(event, () => true);
|
|
296
|
+
const failed = await this.#deliver(event, () => true);
|
|
297
|
+
if (failed.length > 0) throw handlerFailedError(event, failed);
|
|
261
298
|
}
|
|
262
299
|
async publishBatch(events3) {
|
|
300
|
+
let first;
|
|
263
301
|
for (const event of events3) {
|
|
264
|
-
await this
|
|
302
|
+
const failed = await this.#deliver(event, () => true);
|
|
303
|
+
if (failed.length > 0) first ??= handlerFailedError(event, failed);
|
|
265
304
|
}
|
|
305
|
+
if (first !== void 0) throw first;
|
|
266
306
|
}
|
|
267
307
|
async replay(events3) {
|
|
268
308
|
for (const event of events3) {
|
|
269
309
|
await this.#deliver(event, (r) => r.config?.derived === true);
|
|
270
310
|
}
|
|
271
311
|
}
|
|
312
|
+
/** Runs every matching handler to the end, each error logged; returns the named subscriptions that threw. */
|
|
272
313
|
async #deliver(event, eligible) {
|
|
273
314
|
this.#validate(event);
|
|
274
315
|
const matches = Array.from(this.#registrations.values()).filter(
|
|
275
316
|
(r) => eligible(r) && r.regexes.some((re) => re.test(event.type))
|
|
276
317
|
);
|
|
277
|
-
await Promise.all(
|
|
318
|
+
const outcomes = await Promise.all(
|
|
278
319
|
matches.map(async (r) => {
|
|
279
320
|
try {
|
|
280
321
|
await r.handler(event);
|
|
322
|
+
return null;
|
|
281
323
|
} catch (err) {
|
|
324
|
+
const subscription = r.config?.name;
|
|
282
325
|
this.#logger?.error(
|
|
283
|
-
{ err, subscriptionId: r.id, eventType: event.type, eventId: event.id },
|
|
326
|
+
{ err, subscriptionId: r.id, subscription, eventType: event.type, eventId: event.id },
|
|
284
327
|
"Event handler failed"
|
|
285
328
|
);
|
|
329
|
+
return subscription === void 0 ? null : { subscription, message: messageOf(err) };
|
|
286
330
|
}
|
|
287
331
|
})
|
|
288
332
|
);
|
|
333
|
+
return outcomes.filter((o) => o !== null);
|
|
289
334
|
}
|
|
290
335
|
async subscribe(eventPattern, handler, config) {
|
|
291
336
|
const patterns = Array.isArray(eventPattern) ? eventPattern : [eventPattern];
|
|
@@ -321,6 +366,9 @@ var InProcessEventBus = class {
|
|
|
321
366
|
}
|
|
322
367
|
}
|
|
323
368
|
};
|
|
369
|
+
function messageOf(err) {
|
|
370
|
+
return err instanceof Error ? err.message : String(err);
|
|
371
|
+
}
|
|
324
372
|
function compilePattern(pattern) {
|
|
325
373
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\*]/g, "\\$&").replace(/\\\*/g, ".*");
|
|
326
374
|
return new RegExp(`^${escaped}$`);
|
|
@@ -1820,8 +1868,34 @@ function createOrderSequenceRepository(store) {
|
|
|
1820
1868
|
};
|
|
1821
1869
|
}
|
|
1822
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
|
+
|
|
1823
1897
|
// src/repositories/inventory-reservation.ts
|
|
1824
|
-
import { eq as
|
|
1898
|
+
import { eq as eq13, lt as lt2 } from "drizzle-orm";
|
|
1825
1899
|
function rowToReservation(row) {
|
|
1826
1900
|
return {
|
|
1827
1901
|
reservationId: String(row.reservationId),
|
|
@@ -1858,26 +1932,26 @@ function createInventoryReservationRepository(store) {
|
|
|
1858
1932
|
},
|
|
1859
1933
|
async findById(tx, reservationId) {
|
|
1860
1934
|
if (tx.kind === "sqlite") {
|
|
1861
|
-
const row2 = sqliteDb(tx).select().from(inventoryReservations).where(
|
|
1935
|
+
const row2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).get();
|
|
1862
1936
|
return row2 ? rowToReservation(row2) : null;
|
|
1863
1937
|
}
|
|
1864
|
-
const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(
|
|
1938
|
+
const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId));
|
|
1865
1939
|
return row ? rowToReservation(row) : null;
|
|
1866
1940
|
},
|
|
1867
1941
|
async findByVariant(tx, variantId) {
|
|
1868
1942
|
if (tx.kind === "sqlite") {
|
|
1869
|
-
const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(
|
|
1943
|
+
const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.variantId, variantId)).all();
|
|
1870
1944
|
return rows2.map((r) => rowToReservation(r));
|
|
1871
1945
|
}
|
|
1872
|
-
const rows = await postgresDb(tx).select().from(inventoryReservations2).where(
|
|
1946
|
+
const rows = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.variantId, variantId));
|
|
1873
1947
|
return rows.map((r) => rowToReservation(r));
|
|
1874
1948
|
},
|
|
1875
1949
|
async deleteById(tx, reservationId) {
|
|
1876
1950
|
if (tx.kind === "sqlite") {
|
|
1877
|
-
const row2 = sqliteDb(tx).delete(inventoryReservations).where(
|
|
1951
|
+
const row2 = sqliteDb(tx).delete(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).returning().get();
|
|
1878
1952
|
return row2 ? rowToReservation(row2) : null;
|
|
1879
1953
|
}
|
|
1880
|
-
const [row] = await postgresDb(tx).delete(inventoryReservations2).where(
|
|
1954
|
+
const [row] = await postgresDb(tx).delete(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId)).returning();
|
|
1881
1955
|
return row ? rowToReservation(row) : null;
|
|
1882
1956
|
},
|
|
1883
1957
|
async findExpiredBefore(tx, at) {
|
|
@@ -1890,16 +1964,16 @@ function createInventoryReservationRepository(store) {
|
|
|
1890
1964
|
},
|
|
1891
1965
|
async setOrderRef(tx, reservationId, orderRef) {
|
|
1892
1966
|
if (tx.kind === "sqlite") {
|
|
1893
|
-
sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(
|
|
1967
|
+
sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(eq13(inventoryReservations.reservationId, reservationId)).run();
|
|
1894
1968
|
return;
|
|
1895
1969
|
}
|
|
1896
|
-
await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(
|
|
1970
|
+
await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(eq13(inventoryReservations2.reservationId, reservationId));
|
|
1897
1971
|
}
|
|
1898
1972
|
};
|
|
1899
1973
|
}
|
|
1900
1974
|
|
|
1901
1975
|
// src/repositories/stock-adjustment.ts
|
|
1902
|
-
import { desc as desc2, eq as
|
|
1976
|
+
import { desc as desc2, eq as eq14 } from "drizzle-orm";
|
|
1903
1977
|
function rowToAdjustment(row) {
|
|
1904
1978
|
return {
|
|
1905
1979
|
id: String(row.id),
|
|
@@ -1933,17 +2007,17 @@ function createStockAdjustmentRepository(store) {
|
|
|
1933
2007
|
},
|
|
1934
2008
|
async listByVariant(tx, variantId, limit = 100) {
|
|
1935
2009
|
if (tx.kind === "sqlite") {
|
|
1936
|
-
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();
|
|
1937
2011
|
return rows2.map((r) => rowToAdjustment(r));
|
|
1938
2012
|
}
|
|
1939
|
-
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);
|
|
1940
2014
|
return rows.map((r) => rowToAdjustment(r));
|
|
1941
2015
|
}
|
|
1942
2016
|
};
|
|
1943
2017
|
}
|
|
1944
2018
|
|
|
1945
2019
|
// src/repositories/review.ts
|
|
1946
|
-
import { and as
|
|
2020
|
+
import { and as and7, desc as desc3, eq as eq15, lt as lt3, or } from "drizzle-orm";
|
|
1947
2021
|
function rowToReview(row) {
|
|
1948
2022
|
return {
|
|
1949
2023
|
id: String(row.id),
|
|
@@ -1964,40 +2038,40 @@ function createReviewRepository(store) {
|
|
|
1964
2038
|
store,
|
|
1965
2039
|
async findById(tx, id) {
|
|
1966
2040
|
if (tx.kind === "sqlite") {
|
|
1967
|
-
const row2 = sqliteDb(tx).select().from(reviews).where(
|
|
2041
|
+
const row2 = sqliteDb(tx).select().from(reviews).where(eq15(reviews.id, id)).get();
|
|
1968
2042
|
return row2 ? rowToReview(row2) : null;
|
|
1969
2043
|
}
|
|
1970
|
-
const [row] = await postgresDb(tx).select().from(reviews2).where(
|
|
2044
|
+
const [row] = await postgresDb(tx).select().from(reviews2).where(eq15(reviews2.id, id));
|
|
1971
2045
|
return row ? rowToReview(row) : null;
|
|
1972
2046
|
},
|
|
1973
2047
|
async listByProduct(tx, productId, status, limit = 50, after) {
|
|
1974
2048
|
if (tx.kind === "sqlite") {
|
|
1975
2049
|
const t2 = reviews;
|
|
1976
|
-
const conds2 = [
|
|
1977
|
-
if (status) conds2.push(
|
|
2050
|
+
const conds2 = [eq15(t2.productId, productId)];
|
|
2051
|
+
if (status) conds2.push(eq15(t2.moderationStatus, status));
|
|
1978
2052
|
if (after) {
|
|
1979
2053
|
const at = new Date(after.submittedAt).toISOString();
|
|
1980
|
-
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))));
|
|
1981
2055
|
}
|
|
1982
|
-
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();
|
|
1983
2057
|
return rows2.map((r) => rowToReview(r));
|
|
1984
2058
|
}
|
|
1985
2059
|
const t = reviews2;
|
|
1986
|
-
const conds = [
|
|
1987
|
-
if (status) conds.push(
|
|
2060
|
+
const conds = [eq15(t.productId, productId)];
|
|
2061
|
+
if (status) conds.push(eq15(t.moderationStatus, status));
|
|
1988
2062
|
if (after) {
|
|
1989
2063
|
const at = new Date(after.submittedAt);
|
|
1990
|
-
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))));
|
|
1991
2065
|
}
|
|
1992
|
-
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);
|
|
1993
2067
|
return rows.map((r) => rowToReview(r));
|
|
1994
2068
|
},
|
|
1995
2069
|
async listByStatus(tx, status, limit = 100) {
|
|
1996
2070
|
if (tx.kind === "sqlite") {
|
|
1997
|
-
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();
|
|
1998
2072
|
return rows2.map((r) => rowToReview(r));
|
|
1999
2073
|
}
|
|
2000
|
-
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);
|
|
2001
2075
|
return rows.map((r) => rowToReview(r));
|
|
2002
2076
|
},
|
|
2003
2077
|
async insert(tx, r) {
|
|
@@ -2033,10 +2107,10 @@ function createReviewRepository(store) {
|
|
|
2033
2107
|
moderationStatus: status,
|
|
2034
2108
|
moderatedBy,
|
|
2035
2109
|
moderatedAt: moderatedAt.toISOString()
|
|
2036
|
-
}).where(
|
|
2110
|
+
}).where(eq15(reviews.id, id)).run();
|
|
2037
2111
|
return;
|
|
2038
2112
|
}
|
|
2039
|
-
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));
|
|
2040
2114
|
},
|
|
2041
2115
|
async aggregateByProduct(tx, productId) {
|
|
2042
2116
|
const approved = await this.listByProduct(tx, productId, "approved", 1e3);
|
|
@@ -2063,7 +2137,7 @@ function createReviewRepository(store) {
|
|
|
2063
2137
|
}
|
|
2064
2138
|
|
|
2065
2139
|
// src/repositories/processed-event.ts
|
|
2066
|
-
import { and as
|
|
2140
|
+
import { and as and8, eq as eq16, lt as lt4 } from "drizzle-orm";
|
|
2067
2141
|
function createProcessedEventRepository(store) {
|
|
2068
2142
|
const s = processedEvents;
|
|
2069
2143
|
const p = processedEvents2;
|
|
@@ -2071,10 +2145,10 @@ function createProcessedEventRepository(store) {
|
|
|
2071
2145
|
store,
|
|
2072
2146
|
async seen(tx, handlerName, eventId) {
|
|
2073
2147
|
if (tx.kind === "sqlite") {
|
|
2074
|
-
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();
|
|
2075
2149
|
return row !== void 0;
|
|
2076
2150
|
}
|
|
2077
|
-
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);
|
|
2078
2152
|
return rows.length > 0;
|
|
2079
2153
|
},
|
|
2080
2154
|
async markProcessed(tx, handlerName, eventId, at) {
|
|
@@ -2084,6 +2158,14 @@ function createProcessedEventRepository(store) {
|
|
|
2084
2158
|
}
|
|
2085
2159
|
await postgresDb(tx).insert(p).values({ handlerName, eventId, processedAt: at }).onConflictDoNothing();
|
|
2086
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
|
+
},
|
|
2087
2169
|
async deleteBefore(tx, at) {
|
|
2088
2170
|
if (tx.kind === "sqlite") {
|
|
2089
2171
|
return sqliteDb(tx).delete(s).where(lt4(s.processedAt, at.toISOString())).run().changes;
|
|
@@ -2096,20 +2178,54 @@ function createProcessedEventRepository(store) {
|
|
|
2096
2178
|
|
|
2097
2179
|
// src/repositories/event-log.ts
|
|
2098
2180
|
import {
|
|
2099
|
-
and as
|
|
2181
|
+
and as and9,
|
|
2100
2182
|
asc as asc8,
|
|
2101
|
-
eq as
|
|
2183
|
+
eq as eq17,
|
|
2102
2184
|
gt as gt5,
|
|
2103
2185
|
gte as gte2,
|
|
2104
2186
|
inArray as inArray2,
|
|
2105
2187
|
isNotNull,
|
|
2106
2188
|
isNull as isNull2,
|
|
2107
2189
|
lt as lt5,
|
|
2190
|
+
lte,
|
|
2108
2191
|
or as or2,
|
|
2109
2192
|
sql as sql4
|
|
2110
2193
|
} from "drizzle-orm";
|
|
2194
|
+
|
|
2195
|
+
// src/history/subject.ts
|
|
2196
|
+
import { EVT_PRODUCT_VIEWED } from "@nymbalhq/types";
|
|
2197
|
+
function text(value) {
|
|
2198
|
+
return typeof value === "string" ? value : void 0;
|
|
2199
|
+
}
|
|
2200
|
+
function nestedId(value) {
|
|
2201
|
+
return value !== null && typeof value === "object" ? text(value.id) : void 0;
|
|
2202
|
+
}
|
|
2203
|
+
function subjectOf(envelope) {
|
|
2204
|
+
const payload = envelope.payload ?? {};
|
|
2205
|
+
const type = envelope.type;
|
|
2206
|
+
let subject;
|
|
2207
|
+
let id;
|
|
2208
|
+
if (type === EVT_PRODUCT_VIEWED) return null;
|
|
2209
|
+
if (type.startsWith("product.")) {
|
|
2210
|
+
subject = "product";
|
|
2211
|
+
id = nestedId(payload["product"]) ?? text(payload["productId"]);
|
|
2212
|
+
} else if (type.startsWith("order.") || type.startsWith("payment.")) {
|
|
2213
|
+
subject = "order";
|
|
2214
|
+
id = nestedId(payload["order"]) ?? text(payload["orderId"]);
|
|
2215
|
+
} else if (type.startsWith("customer.")) {
|
|
2216
|
+
subject = "customer";
|
|
2217
|
+
id = text(payload["customerId"]);
|
|
2218
|
+
} else if (type.startsWith("inventory.")) {
|
|
2219
|
+
subject = "variant";
|
|
2220
|
+
id = text(payload["variantId"]);
|
|
2221
|
+
}
|
|
2222
|
+
return subject === void 0 || id === void 0 ? null : { type: subject, id };
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
// src/repositories/event-log.ts
|
|
2111
2226
|
var APPEND_CHUNK = 100;
|
|
2112
2227
|
var DELETE_CHUNK = 500;
|
|
2228
|
+
var APPEND_INTO = "INSERT INTO events (id, type, envelope, correlation_id, subject_type, subject_id, created_at) VALUES";
|
|
2113
2229
|
var CATCH_UP_LIMIT = 1e4;
|
|
2114
2230
|
function sqliteGlob(glob) {
|
|
2115
2231
|
return glob.replace(/[[?]/g, (c) => `[${c}]`);
|
|
@@ -2117,6 +2233,10 @@ function sqliteGlob(glob) {
|
|
|
2117
2233
|
function likePattern(glob) {
|
|
2118
2234
|
return glob.replace(/[\\%_]/g, (c) => `\\${c}`).replace(/\*/g, "%");
|
|
2119
2235
|
}
|
|
2236
|
+
function subjectColumns(e) {
|
|
2237
|
+
const subject = subjectOf(e);
|
|
2238
|
+
return { subjectType: subject?.type ?? null, subjectId: subject?.id ?? null };
|
|
2239
|
+
}
|
|
2120
2240
|
function toDate(value) {
|
|
2121
2241
|
if (value === null || value === void 0) return null;
|
|
2122
2242
|
return value instanceof Date ? value : new Date(String(value));
|
|
@@ -2171,46 +2291,57 @@ function createEventLogRepository(store) {
|
|
|
2171
2291
|
}
|
|
2172
2292
|
async function select(tx, where, limit) {
|
|
2173
2293
|
if (tx.kind === "sqlite") {
|
|
2174
|
-
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);
|
|
2175
2295
|
}
|
|
2176
|
-
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);
|
|
2177
2297
|
return rows.map(rowToLogged);
|
|
2178
2298
|
}
|
|
2179
2299
|
return {
|
|
2180
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.
|
|
2181
2303
|
async append(tx, events3) {
|
|
2182
2304
|
const now = /* @__PURE__ */ new Date();
|
|
2183
2305
|
for (let i = 0; i < events3.length; i += APPEND_CHUNK) {
|
|
2184
2306
|
const chunk = events3.slice(i, i + APPEND_CHUNK);
|
|
2307
|
+
const rows = (row) => sql4.join(chunk.map(row), sql4`, `);
|
|
2185
2308
|
if (tx.kind === "sqlite") {
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
}))
|
|
2194
|
-
).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
|
+
);
|
|
2195
2316
|
} else {
|
|
2196
|
-
await postgresDb(tx).
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
correlationId: e.correlationId,
|
|
2202
|
-
createdAt: now
|
|
2203
|
-
}))
|
|
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
|
+
})}`
|
|
2204
2322
|
);
|
|
2205
2323
|
}
|
|
2206
2324
|
}
|
|
2207
2325
|
},
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
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
|
+
);
|
|
2214
2345
|
},
|
|
2215
2346
|
async markDelivered(tx, ids, at) {
|
|
2216
2347
|
if (ids.length === 0) return;
|
|
@@ -2220,40 +2351,61 @@ function createEventLogRepository(store) {
|
|
|
2220
2351
|
}
|
|
2221
2352
|
await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray2(p.id, ids));
|
|
2222
2353
|
},
|
|
2223
|
-
async recordFailure(tx, id, at, maxAttempts) {
|
|
2354
|
+
async recordFailure(tx, id, at, maxAttempts, retryAt) {
|
|
2224
2355
|
if (tx.kind === "sqlite") {
|
|
2225
2356
|
sqliteDb(tx).update(s).set({
|
|
2226
2357
|
attempts: sql4`${s.attempts} + 1`,
|
|
2227
|
-
deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END
|
|
2228
|
-
|
|
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();
|
|
2229
2361
|
return;
|
|
2230
2362
|
}
|
|
2231
2363
|
await postgresDb(tx).update(p).set({
|
|
2232
2364
|
attempts: sql4`${p.attempts} + 1`,
|
|
2233
|
-
deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END
|
|
2234
|
-
|
|
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);
|
|
2235
2387
|
},
|
|
2236
2388
|
async deleteDeliveredBefore(tx, at) {
|
|
2237
2389
|
if (tx.kind === "sqlite") {
|
|
2238
|
-
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();
|
|
2239
2391
|
return result2.changes;
|
|
2240
2392
|
}
|
|
2241
|
-
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)));
|
|
2242
2394
|
return result.rowCount ?? 0;
|
|
2243
2395
|
},
|
|
2244
2396
|
async listAll(tx) {
|
|
2245
2397
|
if (tx.kind === "sqlite") {
|
|
2246
|
-
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);
|
|
2247
2399
|
}
|
|
2248
|
-
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));
|
|
2249
2401
|
return rows.map(rowToLogged);
|
|
2250
2402
|
},
|
|
2251
2403
|
queryByCorrelation(tx, correlationId, filter) {
|
|
2252
2404
|
return select(
|
|
2253
2405
|
tx,
|
|
2254
2406
|
{
|
|
2255
|
-
sqlite: [
|
|
2256
|
-
postgres: [
|
|
2407
|
+
sqlite: [eq17(s.correlationId, correlationId), ...sqliteWhere(filter)],
|
|
2408
|
+
postgres: [eq17(p.correlationId, correlationId), ...postgresWhere(filter)]
|
|
2257
2409
|
},
|
|
2258
2410
|
filter.limit
|
|
2259
2411
|
);
|
|
@@ -2282,7 +2434,7 @@ function createEventLogRepository(store) {
|
|
|
2282
2434
|
const limit = page.limit ?? CATCH_UP_LIMIT;
|
|
2283
2435
|
if (tx.kind === "sqlite") {
|
|
2284
2436
|
return sqliteDb(tx).select(sqliteLogged).from(s).where(
|
|
2285
|
-
|
|
2437
|
+
and9(
|
|
2286
2438
|
isNull2(s.deadAt),
|
|
2287
2439
|
or2(isNull2(s.deliveredAt), gte2(s.deliveredAt, since.toISOString())),
|
|
2288
2440
|
gt5(s.seq, afterSeq)
|
|
@@ -2290,7 +2442,7 @@ function createEventLogRepository(store) {
|
|
|
2290
2442
|
).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
|
|
2291
2443
|
}
|
|
2292
2444
|
const rows = await postgresDb(tx).select(postgresLogged).from(p).where(
|
|
2293
|
-
|
|
2445
|
+
and9(
|
|
2294
2446
|
isNull2(p.deadAt),
|
|
2295
2447
|
or2(isNull2(p.deliveredAt), gte2(p.deliveredAt, since)),
|
|
2296
2448
|
gt5(p.seq, afterSeq)
|
|
@@ -2313,19 +2465,39 @@ function createEventLogRepository(store) {
|
|
|
2313
2465
|
for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {
|
|
2314
2466
|
const chunk = seqs.slice(i, i + DELETE_CHUNK);
|
|
2315
2467
|
if (tx.kind === "sqlite") {
|
|
2316
|
-
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;
|
|
2317
2469
|
} else {
|
|
2318
|
-
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)));
|
|
2319
2471
|
deleted += result.rowCount ?? 0;
|
|
2320
2472
|
}
|
|
2321
2473
|
}
|
|
2322
2474
|
return deleted;
|
|
2475
|
+
},
|
|
2476
|
+
async listBySubjects(tx, subjects, page) {
|
|
2477
|
+
if (subjects.length === 0) return [];
|
|
2478
|
+
const afterSeq = page.afterSeq ?? 0;
|
|
2479
|
+
return select(
|
|
2480
|
+
tx,
|
|
2481
|
+
{
|
|
2482
|
+
sqlite: [
|
|
2483
|
+
or2(...subjects.map((x) => and9(eq17(s.subjectType, x.type), eq17(s.subjectId, x.id)))),
|
|
2484
|
+
gt5(s.seq, afterSeq),
|
|
2485
|
+
...page.until === void 0 ? [] : [lte(s.createdAt, page.until.toISOString())]
|
|
2486
|
+
],
|
|
2487
|
+
postgres: [
|
|
2488
|
+
or2(...subjects.map((x) => and9(eq17(p.subjectType, x.type), eq17(p.subjectId, x.id)))),
|
|
2489
|
+
gt5(p.seq, afterSeq),
|
|
2490
|
+
...page.until === void 0 ? [] : [lte(p.createdAt, page.until)]
|
|
2491
|
+
]
|
|
2492
|
+
},
|
|
2493
|
+
page.limit
|
|
2494
|
+
);
|
|
2323
2495
|
}
|
|
2324
2496
|
};
|
|
2325
2497
|
}
|
|
2326
2498
|
|
|
2327
2499
|
// src/repositories/cart.ts
|
|
2328
|
-
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";
|
|
2329
2501
|
function rowToCart(store, row) {
|
|
2330
2502
|
return {
|
|
2331
2503
|
token: String(row.token),
|
|
@@ -2379,7 +2551,7 @@ var fromExcluded = {
|
|
|
2379
2551
|
};
|
|
2380
2552
|
function sqliteDue(window) {
|
|
2381
2553
|
const t = carts;
|
|
2382
|
-
return
|
|
2554
|
+
return and10(
|
|
2383
2555
|
isNull3(t.abandonedNotifiedAt),
|
|
2384
2556
|
gt6(t.lineCount, 0),
|
|
2385
2557
|
lt6(t.updatedAt, window.cutoff.toISOString()),
|
|
@@ -2388,7 +2560,7 @@ function sqliteDue(window) {
|
|
|
2388
2560
|
}
|
|
2389
2561
|
function postgresDue(window) {
|
|
2390
2562
|
const t = carts2;
|
|
2391
|
-
return
|
|
2563
|
+
return and10(
|
|
2392
2564
|
isNull3(t.abandonedNotifiedAt),
|
|
2393
2565
|
gt6(t.lineCount, 0),
|
|
2394
2566
|
lt6(t.updatedAt, window.cutoff),
|
|
@@ -2398,15 +2570,15 @@ function postgresDue(window) {
|
|
|
2398
2570
|
function createCartRepository(store) {
|
|
2399
2571
|
async function findByToken(tx, token) {
|
|
2400
2572
|
if (tx.kind === "sqlite") {
|
|
2401
|
-
const row2 = sqliteDb(tx).select().from(carts).where(
|
|
2573
|
+
const row2 = sqliteDb(tx).select().from(carts).where(eq18(carts.token, token)).get();
|
|
2402
2574
|
return row2 ? rowToCart("sqlite", row2) : null;
|
|
2403
2575
|
}
|
|
2404
|
-
const [row] = await postgresDb(tx).select().from(carts2).where(
|
|
2576
|
+
const [row] = await postgresDb(tx).select().from(carts2).where(eq18(carts2.token, token));
|
|
2405
2577
|
return row ? rowToCart("postgres", row) : null;
|
|
2406
2578
|
}
|
|
2407
2579
|
async function lock(tx, token) {
|
|
2408
2580
|
if (tx.kind === "sqlite") return findByToken(tx, token);
|
|
2409
|
-
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");
|
|
2410
2582
|
return row ? rowToCart("postgres", row) : null;
|
|
2411
2583
|
}
|
|
2412
2584
|
return {
|
|
@@ -2419,14 +2591,14 @@ function createCartRepository(store) {
|
|
|
2419
2591
|
inserted = sqliteDb(tx).insert(carts).values(sqliteValues(cart)).onConflictDoUpdate({
|
|
2420
2592
|
target: carts.token,
|
|
2421
2593
|
set: fromExcluded,
|
|
2422
|
-
setWhere:
|
|
2594
|
+
setWhere: lte2(carts.expiresAt, sql5`excluded.updated_at`)
|
|
2423
2595
|
}).returning().get();
|
|
2424
2596
|
} else {
|
|
2425
2597
|
;
|
|
2426
2598
|
[inserted] = await postgresDb(tx).insert(carts2).values(postgresValues(cart)).onConflictDoUpdate({
|
|
2427
2599
|
target: carts2.token,
|
|
2428
2600
|
set: fromExcluded,
|
|
2429
|
-
setWhere:
|
|
2601
|
+
setWhere: lte2(carts2.expiresAt, sql5`excluded.updated_at`)
|
|
2430
2602
|
}).returning();
|
|
2431
2603
|
}
|
|
2432
2604
|
if (inserted !== void 0) return { cart: rowToCart(tx.kind, inserted), created: true };
|
|
@@ -2443,10 +2615,10 @@ function createCartRepository(store) {
|
|
|
2443
2615
|
},
|
|
2444
2616
|
async remove(tx, token) {
|
|
2445
2617
|
if (tx.kind === "sqlite") {
|
|
2446
|
-
sqliteDb(tx).delete(carts).where(
|
|
2618
|
+
sqliteDb(tx).delete(carts).where(eq18(carts.token, token)).run();
|
|
2447
2619
|
return;
|
|
2448
2620
|
}
|
|
2449
|
-
await postgresDb(tx).delete(carts2).where(
|
|
2621
|
+
await postgresDb(tx).delete(carts2).where(eq18(carts2.token, token));
|
|
2450
2622
|
},
|
|
2451
2623
|
async clearIfLive(tx, token, at) {
|
|
2452
2624
|
if (tx.kind === "sqlite") {
|
|
@@ -2457,7 +2629,7 @@ function createCartRepository(store) {
|
|
|
2457
2629
|
subtotalMinor: 0,
|
|
2458
2630
|
updatedAt: at.toISOString(),
|
|
2459
2631
|
abandonedNotifiedAt: null
|
|
2460
|
-
}).where(
|
|
2632
|
+
}).where(and10(eq18(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
|
|
2461
2633
|
return result.changes > 0;
|
|
2462
2634
|
}
|
|
2463
2635
|
const t = carts2;
|
|
@@ -2467,44 +2639,141 @@ function createCartRepository(store) {
|
|
|
2467
2639
|
subtotalMinor: 0,
|
|
2468
2640
|
updatedAt: at,
|
|
2469
2641
|
abandonedNotifiedAt: null
|
|
2470
|
-
}).where(
|
|
2642
|
+
}).where(and10(eq18(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
|
|
2471
2643
|
return rows.length > 0;
|
|
2472
2644
|
},
|
|
2473
2645
|
async deleteExpired(tx, at) {
|
|
2474
2646
|
if (tx.kind === "sqlite") {
|
|
2475
|
-
const result = sqliteDb(tx).delete(carts).where(
|
|
2647
|
+
const result = sqliteDb(tx).delete(carts).where(lte2(carts.expiresAt, at.toISOString())).run();
|
|
2476
2648
|
return result.changes;
|
|
2477
2649
|
}
|
|
2478
|
-
const rows = await postgresDb(tx).delete(carts2).where(
|
|
2650
|
+
const rows = await postgresDb(tx).delete(carts2).where(lte2(carts2.expiresAt, at)).returning({ token: carts2.token });
|
|
2479
2651
|
return rows.length;
|
|
2480
2652
|
},
|
|
2481
2653
|
async listAbandoned(tx, window, page) {
|
|
2482
2654
|
if (tx.kind === "sqlite") {
|
|
2483
2655
|
const t2 = carts;
|
|
2484
2656
|
const rows2 = sqliteDb(tx).select({ token: t2.token }).from(t2).where(
|
|
2485
|
-
|
|
2657
|
+
and10(sqliteDue(window), page.after === void 0 ? void 0 : gt6(t2.token, page.after))
|
|
2486
2658
|
).orderBy(asc9(t2.token)).limit(page.limit).all();
|
|
2487
2659
|
return rows2.map((r) => r.token);
|
|
2488
2660
|
}
|
|
2489
2661
|
const t = carts2;
|
|
2490
2662
|
const rows = await postgresDb(tx).select({ token: t.token }).from(t).where(
|
|
2491
|
-
|
|
2663
|
+
and10(postgresDue(window), page.after === void 0 ? void 0 : gt6(t.token, page.after))
|
|
2492
2664
|
).orderBy(asc9(t.token)).limit(page.limit);
|
|
2493
2665
|
return rows.map((r) => r.token);
|
|
2494
2666
|
},
|
|
2495
2667
|
async claimAbandoned(tx, token, window) {
|
|
2496
2668
|
if (tx.kind === "sqlite") {
|
|
2497
2669
|
const t2 = carts;
|
|
2498
|
-
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();
|
|
2499
2671
|
return row2 ? { token: row2.token, lastActivityAt: fromTimestamp(row2.updatedAt) } : null;
|
|
2500
2672
|
}
|
|
2501
2673
|
const t = carts2;
|
|
2502
|
-
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 });
|
|
2503
2675
|
return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null;
|
|
2504
2676
|
}
|
|
2505
2677
|
};
|
|
2506
2678
|
}
|
|
2507
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
|
+
|
|
2508
2777
|
// src/repositories/index.ts
|
|
2509
2778
|
function buildRepositories(commandStore, _documentStore) {
|
|
2510
2779
|
return {
|
|
@@ -2518,6 +2787,7 @@ function buildRepositories(commandStore, _documentStore) {
|
|
|
2518
2787
|
orderHistory: createOrderHistoryRepository(commandStore),
|
|
2519
2788
|
orderRefund: createOrderRefundRepository(commandStore),
|
|
2520
2789
|
orderSequence: createOrderSequenceRepository(commandStore),
|
|
2790
|
+
orderAccessKey: createOrderAccessKeyRepository(commandStore),
|
|
2521
2791
|
inventoryReservation: createInventoryReservationRepository(commandStore),
|
|
2522
2792
|
stockAdjustment: createStockAdjustmentRepository(commandStore),
|
|
2523
2793
|
review: createReviewRepository(commandStore),
|
|
@@ -2525,7 +2795,8 @@ function buildRepositories(commandStore, _documentStore) {
|
|
|
2525
2795
|
eventLog: createEventLogRepository(commandStore),
|
|
2526
2796
|
cart: createCartRepository(commandStore),
|
|
2527
2797
|
settings: createSettingsRepository(commandStore),
|
|
2528
|
-
auditEntry: createAuditEntryRepository(commandStore)
|
|
2798
|
+
auditEntry: createAuditEntryRepository(commandStore),
|
|
2799
|
+
alertSubscription: createAlertSubscriptionRepository(commandStore)
|
|
2529
2800
|
};
|
|
2530
2801
|
}
|
|
2531
2802
|
|
|
@@ -2577,6 +2848,11 @@ function createEventPublisher(opts) {
|
|
|
2577
2848
|
async publishMany(events3) {
|
|
2578
2849
|
await append(events3.map((e) => build(e.type, e.payload, e.options ?? {})));
|
|
2579
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
|
+
},
|
|
2580
2856
|
correlated(correlationId) {
|
|
2581
2857
|
return createEventPublisher({ ...opts, correlationId });
|
|
2582
2858
|
}
|
|
@@ -2593,10 +2869,16 @@ function deferred() {
|
|
|
2593
2869
|
});
|
|
2594
2870
|
return { promise, resolve: resolve4 };
|
|
2595
2871
|
}
|
|
2872
|
+
function failedOf(err) {
|
|
2873
|
+
const failed = err?.context?.failed;
|
|
2874
|
+
return Array.isArray(failed) ? { failed } : {};
|
|
2875
|
+
}
|
|
2596
2876
|
function createRelay(opts) {
|
|
2597
2877
|
const { store, eventLog } = opts;
|
|
2598
2878
|
const maxAttempts = opts.maxAttempts ?? 5;
|
|
2599
2879
|
const intervalMs = opts.intervalMs ?? 1e4;
|
|
2880
|
+
const retryDelayMs = opts.retryDelayMs ?? intervalMs;
|
|
2881
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
2600
2882
|
const logger = opts.logger.child({ component: "event-relay" });
|
|
2601
2883
|
const delivering = new AsyncLocalStorage();
|
|
2602
2884
|
let active = false;
|
|
@@ -2608,13 +2890,26 @@ function createRelay(opts) {
|
|
|
2608
2890
|
try {
|
|
2609
2891
|
await delivering.run(true, () => opts.eventBus.publish(event));
|
|
2610
2892
|
} catch (err) {
|
|
2611
|
-
const at =
|
|
2612
|
-
|
|
2613
|
-
const
|
|
2614
|
-
|
|
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) {
|
|
2615
2907
|
logger.error(context, "event delivery failed for the last time; the event is dead");
|
|
2616
2908
|
} else {
|
|
2617
|
-
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
|
+
);
|
|
2618
2913
|
}
|
|
2619
2914
|
return;
|
|
2620
2915
|
}
|
|
@@ -2625,7 +2920,9 @@ function createRelay(opts) {
|
|
|
2625
2920
|
let afterSeq = 0;
|
|
2626
2921
|
for (; ; ) {
|
|
2627
2922
|
if (stopped) return;
|
|
2628
|
-
const page = await store.read(
|
|
2923
|
+
const page = await store.read(
|
|
2924
|
+
(tx) => eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq, now())
|
|
2925
|
+
);
|
|
2629
2926
|
for (const logged of page) {
|
|
2630
2927
|
if (stopped) return;
|
|
2631
2928
|
afterSeq = logged.seq;
|
|
@@ -2719,158 +3016,6 @@ import {
|
|
|
2719
3016
|
EVT_CATEGORY_DELETED,
|
|
2720
3017
|
EVT_CATEGORY_UPDATED
|
|
2721
3018
|
} from "@nymbalhq/types";
|
|
2722
|
-
|
|
2723
|
-
// src/read-models/builders.ts
|
|
2724
|
-
var CATEGORIES = "categories";
|
|
2725
|
-
var PRODUCTS = "products";
|
|
2726
|
-
var PRODUCTS_BY_CATEGORY = "products-by-category";
|
|
2727
|
-
var ORDERS = "orders";
|
|
2728
|
-
var ORDERS_BY_CUSTOMER = "orders-by-customer";
|
|
2729
|
-
var CUSTOMER_PROFILES = "customer-profiles";
|
|
2730
|
-
function buildCategoryDoc(category, storeId) {
|
|
2731
|
-
return {
|
|
2732
|
-
id: category.id,
|
|
2733
|
-
storeId,
|
|
2734
|
-
parentId: category.parentId,
|
|
2735
|
-
slug: category.slug,
|
|
2736
|
-
name: category.name,
|
|
2737
|
-
description: category.description,
|
|
2738
|
-
position: category.position,
|
|
2739
|
-
createdAt: category.createdAt
|
|
2740
|
-
};
|
|
2741
|
-
}
|
|
2742
|
-
var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
|
|
2743
|
-
function variantOptions(raw, sku, logger) {
|
|
2744
|
-
let value = raw;
|
|
2745
|
-
if (typeof raw === "string") {
|
|
2746
|
-
try {
|
|
2747
|
-
value = JSON.parse(raw);
|
|
2748
|
-
} catch (err) {
|
|
2749
|
-
logger?.warn({ sku, err }, "variant options are not JSON; projected as none");
|
|
2750
|
-
return [];
|
|
2751
|
-
}
|
|
2752
|
-
}
|
|
2753
|
-
if (!Array.isArray(value)) return [];
|
|
2754
|
-
return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
|
|
2755
|
-
}
|
|
2756
|
-
function buildProductDoc(p, categories3, ctx) {
|
|
2757
|
-
const prices = p.variants.map((v) => v.priceMinor);
|
|
2758
|
-
return {
|
|
2759
|
-
id: p.id,
|
|
2760
|
-
storeId: ctx.storeId,
|
|
2761
|
-
slug: p.slug,
|
|
2762
|
-
name: p.name,
|
|
2763
|
-
description: p.description,
|
|
2764
|
-
shortDescription: p.shortDescription,
|
|
2765
|
-
status: p.status,
|
|
2766
|
-
type: p.type,
|
|
2767
|
-
media: p.media,
|
|
2768
|
-
variantCount: p.variants.length,
|
|
2769
|
-
inStock: p.variants.some((v) => v.stock > 0),
|
|
2770
|
-
priceRange: prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null,
|
|
2771
|
-
currency: ctx.currency,
|
|
2772
|
-
priceMinor: prices[0] ?? null,
|
|
2773
|
-
variants: p.variants.map((v) => ({
|
|
2774
|
-
id: v.id,
|
|
2775
|
-
sku: v.sku,
|
|
2776
|
-
name: v.name,
|
|
2777
|
-
priceMinor: v.priceMinor,
|
|
2778
|
-
stock: v.stock,
|
|
2779
|
-
options: variantOptions(v.options, v.sku, ctx.logger)
|
|
2780
|
-
})),
|
|
2781
|
-
categoryIds: p.categoryIds,
|
|
2782
|
-
categories: p.categoryIds.flatMap((id) => {
|
|
2783
|
-
const c = categories3.get(id);
|
|
2784
|
-
return c ? [{ id: c.id, name: c.name, slug: c.slug }] : [];
|
|
2785
|
-
}),
|
|
2786
|
-
createdAt: p.createdAt,
|
|
2787
|
-
updatedAt: p.updatedAt
|
|
2788
|
-
};
|
|
2789
|
-
}
|
|
2790
|
-
var productByCategoryKey = (categorySlug, productSlug) => `category:${categorySlug}#product:${productSlug}`;
|
|
2791
|
-
function productWrites(doc) {
|
|
2792
|
-
return [
|
|
2793
|
-
{ collection: PRODUCTS, key: doc.slug, doc },
|
|
2794
|
-
...doc.categories.map((c) => ({
|
|
2795
|
-
collection: PRODUCTS_BY_CATEGORY,
|
|
2796
|
-
key: productByCategoryKey(c.slug, doc.slug),
|
|
2797
|
-
doc: { ...doc, partitionKey: `category:${c.slug}`, sortKey: `product:${doc.slug}` }
|
|
2798
|
-
}))
|
|
2799
|
-
];
|
|
2800
|
-
}
|
|
2801
|
-
function customerSortKey(o) {
|
|
2802
|
-
return `order:${String(Number.MAX_SAFE_INTEGER - new Date(String(o.createdAt)).getTime()).padStart(16, "0")}:${o.orderNumber}`;
|
|
2803
|
-
}
|
|
2804
|
-
function buildOrderDoc(order, history) {
|
|
2805
|
-
return {
|
|
2806
|
-
...order,
|
|
2807
|
-
history: history.map((h) => ({
|
|
2808
|
-
fromStatus: h.fromStatus,
|
|
2809
|
-
toStatus: h.toStatus,
|
|
2810
|
-
actor: h.actor,
|
|
2811
|
-
note: h.note,
|
|
2812
|
-
timestamp: String(h.timestamp)
|
|
2813
|
-
}))
|
|
2814
|
-
};
|
|
2815
|
-
}
|
|
2816
|
-
function orderWrites(doc) {
|
|
2817
|
-
const writes = [{ collection: ORDERS, key: doc.orderNumber, doc }];
|
|
2818
|
-
if (doc.customerId) {
|
|
2819
|
-
const sortKey = customerSortKey(doc);
|
|
2820
|
-
writes.push({
|
|
2821
|
-
collection: ORDERS_BY_CUSTOMER,
|
|
2822
|
-
key: `customer:${doc.customerId}#${sortKey}`,
|
|
2823
|
-
doc: { ...doc, partitionKey: `customer:${doc.customerId}`, sortKey }
|
|
2824
|
-
});
|
|
2825
|
-
}
|
|
2826
|
-
return writes;
|
|
2827
|
-
}
|
|
2828
|
-
function buildCustomerProfile(c) {
|
|
2829
|
-
const { orderCount, totalSpentMinor } = c;
|
|
2830
|
-
return {
|
|
2831
|
-
customerId: c.id,
|
|
2832
|
-
orderCount,
|
|
2833
|
-
totalSpentMinor,
|
|
2834
|
-
segment: totalSpentMinor > 1e5 ? "vip" : orderCount > 3 ? "returning" : orderCount > 0 ? "active" : "new",
|
|
2835
|
-
createdAt: String(c.createdAt)
|
|
2836
|
-
};
|
|
2837
|
-
}
|
|
2838
|
-
var partitioned = (doc) => {
|
|
2839
|
-
const { partitionKey, sortKey } = doc;
|
|
2840
|
-
return `${String(partitionKey)}#${String(sortKey)}`;
|
|
2841
|
-
};
|
|
2842
|
-
var KEY_OF = {
|
|
2843
|
-
[CATEGORIES]: (doc) => String(doc.slug),
|
|
2844
|
-
[PRODUCTS]: (doc) => String(doc.slug),
|
|
2845
|
-
[PRODUCTS_BY_CATEGORY]: partitioned,
|
|
2846
|
-
[ORDERS]: (doc) => String(doc.orderNumber),
|
|
2847
|
-
[ORDERS_BY_CUSTOMER]: partitioned,
|
|
2848
|
-
[CUSTOMER_PROFILES]: (doc) => String(doc.customerId)
|
|
2849
|
-
};
|
|
2850
|
-
function buildSearchDoc(p) {
|
|
2851
|
-
return {
|
|
2852
|
-
id: p.id,
|
|
2853
|
-
type: "product",
|
|
2854
|
-
fields: {
|
|
2855
|
-
slug: p.slug,
|
|
2856
|
-
name: p.name,
|
|
2857
|
-
description: p.description,
|
|
2858
|
-
status: p.status,
|
|
2859
|
-
categoryIds: p.categoryIds,
|
|
2860
|
-
variants: p.variants.map((v) => ({ sku: v.sku, name: v.name, priceMinor: v.priceMinor }))
|
|
2861
|
-
}
|
|
2862
|
-
};
|
|
2863
|
-
}
|
|
2864
|
-
|
|
2865
|
-
// src/handlers/derived.ts
|
|
2866
|
-
async function subscribeDerived(eventBus, handlers) {
|
|
2867
|
-
for (const h of handlers) {
|
|
2868
|
-
const pattern = h.types.length === 1 ? h.types[0] : [...h.types];
|
|
2869
|
-
await eventBus.subscribe(pattern, h.handle, { name: h.name, derived: true });
|
|
2870
|
-
}
|
|
2871
|
-
}
|
|
2872
|
-
|
|
2873
|
-
// src/handlers/projections/category-projection.ts
|
|
2874
3019
|
function categoryProjection(deps) {
|
|
2875
3020
|
const { documentStore, logger, storeId, repos } = deps;
|
|
2876
3021
|
const onUpsert = async (event) => {
|
|
@@ -2933,8 +3078,8 @@ async function categoriesOf(tx, repos, ids) {
|
|
|
2933
3078
|
async function loadProduct(tx, repos, productId) {
|
|
2934
3079
|
const product = await repos.product.findById(tx, productId);
|
|
2935
3080
|
if (!product) return null;
|
|
2936
|
-
const
|
|
2937
|
-
return { snapshot
|
|
3081
|
+
const snapshot = await productSnapshot(tx, repos, product);
|
|
3082
|
+
return { snapshot, categories: await categoriesOf(tx, repos, snapshot.categoryIds) };
|
|
2938
3083
|
}
|
|
2939
3084
|
async function loadOrderDoc(tx, repos, orderId) {
|
|
2940
3085
|
const order = await repos.order.findById(tx, orderId);
|
|
@@ -3145,15 +3290,46 @@ async function registerInventoryProjection(deps) {
|
|
|
3145
3290
|
}
|
|
3146
3291
|
|
|
3147
3292
|
// src/handlers/side-effects/email-handler.ts
|
|
3293
|
+
import { v7 as uuidv73 } from "uuid";
|
|
3148
3294
|
import {
|
|
3149
3295
|
EVT_CART_ABANDONED,
|
|
3150
3296
|
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED2,
|
|
3297
|
+
EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
|
|
3151
3298
|
EVT_ORDER_PAID as EVT_ORDER_PAID3,
|
|
3152
3299
|
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2
|
|
3153
3300
|
} from "@nymbalhq/types";
|
|
3154
3301
|
var ORDER_PAID_EMAIL = "email:order-paid";
|
|
3155
3302
|
async function registerEmailHandler(deps) {
|
|
3156
|
-
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
|
+
}
|
|
3157
3333
|
const onOrderPaid = async (event) => {
|
|
3158
3334
|
const { orderId } = event.payload;
|
|
3159
3335
|
const { store } = processedEventRepo;
|
|
@@ -3163,19 +3339,20 @@ async function registerEmailHandler(deps) {
|
|
|
3163
3339
|
logger.warn({ orderId, eventId: event.id }, "email handler: paid order not found");
|
|
3164
3340
|
return;
|
|
3165
3341
|
}
|
|
3166
|
-
await
|
|
3167
|
-
template: "order-placed",
|
|
3168
|
-
to: order.email,
|
|
3169
|
-
vars: {
|
|
3170
|
-
orderNumber: order.orderNumber,
|
|
3171
|
-
customerName: order.billingAddress.firstName,
|
|
3172
|
-
totalFormatted: formatMoney(order.totalMinor, order.currency)
|
|
3173
|
-
}
|
|
3174
|
-
});
|
|
3342
|
+
await sendOrderPlaced(order);
|
|
3175
3343
|
await store.transaction(
|
|
3176
3344
|
(tx) => processedEventRepo.markProcessed(tx, ORDER_PAID_EMAIL, orderId, /* @__PURE__ */ new Date())
|
|
3177
3345
|
);
|
|
3178
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
|
+
};
|
|
3179
3356
|
const onOrderShipped = async (event) => {
|
|
3180
3357
|
logger.debug({ orderId: event.payload.orderId }, "email handler: order shipped");
|
|
3181
3358
|
};
|
|
@@ -3192,6 +3369,15 @@ async function registerEmailHandler(deps) {
|
|
|
3192
3369
|
await eventBus.subscribe(EVT_ORDER_PAID3, onOrderPaid, {
|
|
3193
3370
|
name: "email-order-paid"
|
|
3194
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
|
+
);
|
|
3195
3381
|
await eventBus.subscribe(
|
|
3196
3382
|
EVT_ORDER_SHIPPED2,
|
|
3197
3383
|
withIdempotency("email:order-shipped", onOrderShipped, {
|
|
@@ -3228,11 +3414,11 @@ function searchHandler(deps) {
|
|
|
3228
3414
|
const { search: search2, repos } = deps;
|
|
3229
3415
|
const onUpsert = async (event) => {
|
|
3230
3416
|
const { id } = event.payload.product;
|
|
3231
|
-
const
|
|
3417
|
+
const snapshot = await repos.product.store.read(async (tx) => {
|
|
3232
3418
|
const product = await repos.product.findById(tx, id);
|
|
3233
3419
|
return product ? productSnapshot(tx, repos, product) : null;
|
|
3234
3420
|
});
|
|
3235
|
-
if (
|
|
3421
|
+
if (snapshot) await search2.index([buildSearchDoc(snapshot)]);
|
|
3236
3422
|
else await search2.remove([id]);
|
|
3237
3423
|
};
|
|
3238
3424
|
const onDelete = async (event) => {
|
|
@@ -3274,9 +3460,127 @@ async function registerReviewsHandler(deps) {
|
|
|
3274
3460
|
);
|
|
3275
3461
|
}
|
|
3276
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
|
+
|
|
3277
3581
|
// src/handlers/register.ts
|
|
3278
3582
|
async function registerHandlers(deps) {
|
|
3279
|
-
const { config, eventBus, documentStore, repos, adapters, logger } = deps;
|
|
3583
|
+
const { config, eventBus, documentStore, repos, adapters, alerts, logger } = deps;
|
|
3280
3584
|
const handlerLogger = logger.child({ component: "handlers" });
|
|
3281
3585
|
await registerCategoryProjection({
|
|
3282
3586
|
eventBus,
|
|
@@ -3315,12 +3619,27 @@ async function registerHandlers(deps) {
|
|
|
3315
3619
|
currency: config.store.currency,
|
|
3316
3620
|
repos
|
|
3317
3621
|
});
|
|
3622
|
+
await registerRecentlyViewedProjection({
|
|
3623
|
+
eventBus,
|
|
3624
|
+
documentStore,
|
|
3625
|
+
logger: handlerLogger.child({ projection: "recently-viewed" })
|
|
3626
|
+
});
|
|
3318
3627
|
await registerEmailHandler({
|
|
3319
3628
|
eventBus,
|
|
3320
3629
|
email: adapters.email,
|
|
3321
3630
|
logger: handlerLogger.child({ handler: "email" }),
|
|
3322
3631
|
processedEventRepo: repos.processedEvent,
|
|
3323
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,
|
|
3324
3643
|
storeName: config.store.name
|
|
3325
3644
|
});
|
|
3326
3645
|
await registerSearchHandler({
|
|
@@ -3341,1849 +3660,37 @@ async function registerHandlers(deps) {
|
|
|
3341
3660
|
import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
|
|
3342
3661
|
import { ConfigError as ConfigError2 } from "@nymbalhq/types";
|
|
3343
3662
|
|
|
3344
|
-
// src/
|
|
3345
|
-
import {
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
const
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
return {
|
|
3370
|
-
async create(input) {
|
|
3371
|
-
audit.note("product.create");
|
|
3372
|
-
if (!input.slug.trim()) throw new ValidationError2("Product slug is required");
|
|
3373
|
-
if (!input.name.trim()) throw new ValidationError2("Product name is required");
|
|
3374
|
-
const existing = await store.read((tx) => repos.product.findBySlug(tx, input.slug));
|
|
3375
|
-
if (existing) {
|
|
3376
|
-
throw new ValidationError2(`Product slug already exists: ${input.slug}`, {
|
|
3377
|
-
context: { slug: input.slug }
|
|
3378
|
-
});
|
|
3379
|
-
}
|
|
3380
|
-
return store.transaction(async (tx) => {
|
|
3381
|
-
const now = /* @__PURE__ */ new Date();
|
|
3382
|
-
const productId = uuidv73();
|
|
3383
|
-
audit.note("product.create", [{ type: "product", id: productId }]);
|
|
3384
|
-
const insert = {
|
|
3385
|
-
id: productId,
|
|
3386
|
-
slug: input.slug,
|
|
3387
|
-
name: input.name,
|
|
3388
|
-
...input.description !== void 0 && { description: input.description },
|
|
3389
|
-
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
3390
|
-
...input.status !== void 0 && { status: input.status },
|
|
3391
|
-
...input.type !== void 0 && { type: input.type },
|
|
3392
|
-
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
3393
|
-
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
3394
|
-
...input.media !== void 0 && { media: input.media },
|
|
3395
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
3396
|
-
createdAt: now,
|
|
3397
|
-
updatedAt: now
|
|
3398
|
-
};
|
|
3399
|
-
await repos.product.insert(tx, insert);
|
|
3400
|
-
const variantRows = [];
|
|
3401
|
-
for (const v of input.variants ?? []) {
|
|
3402
|
-
const id = v.id ?? uuidv73();
|
|
3403
|
-
const vi = {
|
|
3404
|
-
...v,
|
|
3405
|
-
id,
|
|
3406
|
-
productId,
|
|
3407
|
-
createdAt: now,
|
|
3408
|
-
updatedAt: now
|
|
3409
|
-
};
|
|
3410
|
-
await repos.variant.insert(tx, vi);
|
|
3411
|
-
const stored = await repos.variant.findById(tx, id);
|
|
3412
|
-
if (stored) variantRows.push(stored);
|
|
3413
|
-
}
|
|
3414
|
-
for (const categoryId of input.categoryIds ?? []) {
|
|
3415
|
-
await repos.productCategory.attach(tx, productId, categoryId);
|
|
3416
|
-
}
|
|
3417
|
-
const created = await requireProduct(tx, productId);
|
|
3418
|
-
const snap = {
|
|
3419
|
-
...created,
|
|
3420
|
-
variants: variantRows,
|
|
3421
|
-
categoryIds: input.categoryIds ?? []
|
|
3422
|
-
};
|
|
3423
|
-
await publisher.publish(EVT_PRODUCT_CREATED3, { product: snap });
|
|
3424
|
-
return snap;
|
|
3425
|
-
});
|
|
3426
|
-
},
|
|
3427
|
-
async update(id, input) {
|
|
3428
|
-
return store.transaction(async (tx) => {
|
|
3429
|
-
audit.note("product.update", [{ type: "product", id }]);
|
|
3430
|
-
const product = await requireProduct(tx, id);
|
|
3431
|
-
const now = /* @__PURE__ */ new Date();
|
|
3432
|
-
const updateInput = {
|
|
3433
|
-
...input.name !== void 0 && { name: input.name },
|
|
3434
|
-
...input.description !== void 0 && { description: input.description },
|
|
3435
|
-
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
3436
|
-
...input.status !== void 0 && { status: input.status },
|
|
3437
|
-
...input.type !== void 0 && { type: input.type },
|
|
3438
|
-
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
3439
|
-
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
3440
|
-
...input.media !== void 0 && { media: input.media },
|
|
3441
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
3442
|
-
updatedAt: now
|
|
3443
|
-
};
|
|
3444
|
-
await repos.product.update(tx, product.id, updateInput);
|
|
3445
|
-
if (input.categoryIds) {
|
|
3446
|
-
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
3447
|
-
for (const categoryId of input.categoryIds) {
|
|
3448
|
-
await repos.productCategory.attach(tx, product.id, categoryId);
|
|
3449
|
-
}
|
|
3450
|
-
}
|
|
3451
|
-
const snap = await snapshot(tx, repos, await requireProduct(tx, product.id));
|
|
3452
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3453
|
-
return snap;
|
|
3454
|
-
});
|
|
3455
|
-
},
|
|
3456
|
-
async delete(id) {
|
|
3457
|
-
await store.transaction(async (tx) => {
|
|
3458
|
-
audit.note("product.delete", [{ type: "product", id }]);
|
|
3459
|
-
const product = await requireProduct(tx, id);
|
|
3460
|
-
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
3461
|
-
const variants3 = await repos.variant.findByProduct(tx, product.id);
|
|
3462
|
-
for (const v of variants3) await repos.variant.delete(tx, v.id);
|
|
3463
|
-
await repos.product.delete(tx, product.id);
|
|
3464
|
-
await publisher.publish(EVT_PRODUCT_DELETED3, {
|
|
3465
|
-
productId: product.id,
|
|
3466
|
-
slug: product.slug
|
|
3467
|
-
});
|
|
3468
|
-
});
|
|
3469
|
-
},
|
|
3470
|
-
async publish(id) {
|
|
3471
|
-
await store.transaction(async (tx) => {
|
|
3472
|
-
audit.note("product.publish", [{ type: "product", id }]);
|
|
3473
|
-
const product = await requireProduct(tx, id);
|
|
3474
|
-
if (product.status === "active") return;
|
|
3475
|
-
await repos.product.setStatus(tx, product.id, "active", /* @__PURE__ */ new Date());
|
|
3476
|
-
await publisher.publish(EVT_PRODUCT_PUBLISHED, {
|
|
3477
|
-
productId: product.id,
|
|
3478
|
-
slug: product.slug
|
|
3479
|
-
});
|
|
3480
|
-
const fresh = await requireProduct(tx, product.id);
|
|
3481
|
-
const snap = await snapshot(tx, repos, fresh);
|
|
3482
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3483
|
-
});
|
|
3484
|
-
},
|
|
3485
|
-
async unpublish(id) {
|
|
3486
|
-
await store.transaction(async (tx) => {
|
|
3487
|
-
audit.note("product.unpublish", [{ type: "product", id }]);
|
|
3488
|
-
const product = await requireProduct(tx, id);
|
|
3489
|
-
if (product.status === "draft") return;
|
|
3490
|
-
await repos.product.setStatus(tx, product.id, "draft", /* @__PURE__ */ new Date());
|
|
3491
|
-
await publisher.publish(EVT_PRODUCT_UNPUBLISHED, {
|
|
3492
|
-
productId: product.id,
|
|
3493
|
-
slug: product.slug
|
|
3494
|
-
});
|
|
3495
|
-
const fresh = await requireProduct(tx, product.id);
|
|
3496
|
-
const snap = await snapshot(tx, repos, fresh);
|
|
3497
|
-
await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
|
|
3498
|
-
});
|
|
3499
|
-
},
|
|
3500
|
-
async getById(id) {
|
|
3501
|
-
return store.read(async (tx) => snapshot(tx, repos, await requireProduct(tx, id)));
|
|
3502
|
-
},
|
|
3503
|
-
async getBySlug(slug) {
|
|
3504
|
-
return store.read(async (tx) => {
|
|
3505
|
-
const product = await repos.product.findBySlug(tx, slug);
|
|
3506
|
-
if (!product) throw new NotFoundError("product", slug);
|
|
3507
|
-
return snapshot(tx, repos, product);
|
|
3508
|
-
});
|
|
3509
|
-
},
|
|
3510
|
-
async list(opts = {}) {
|
|
3511
|
-
return store.read(async (tx) => {
|
|
3512
|
-
const products3 = await repos.product.list(tx, opts);
|
|
3513
|
-
const out = [];
|
|
3514
|
-
for (const p of products3) {
|
|
3515
|
-
out.push(await snapshot(tx, repos, p));
|
|
3516
|
-
}
|
|
3517
|
-
return out;
|
|
3518
|
-
});
|
|
3519
|
-
}
|
|
3520
|
-
};
|
|
3521
|
-
}
|
|
3522
|
-
|
|
3523
|
-
// src/services/category-service.ts
|
|
3524
|
-
import { v7 as uuidv74 } from "uuid";
|
|
3525
|
-
import {
|
|
3526
|
-
EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3,
|
|
3527
|
-
EVT_CATEGORY_UPDATED as EVT_CATEGORY_UPDATED3,
|
|
3528
|
-
EVT_CATEGORY_DELETED as EVT_CATEGORY_DELETED3,
|
|
3529
|
-
NotFoundError as NotFoundError2,
|
|
3530
|
-
ValidationError as ValidationError3
|
|
3531
|
-
} from "@nymbalhq/types";
|
|
3532
|
-
function createCategoryService(deps) {
|
|
3533
|
-
const { repos, publisher } = deps;
|
|
3534
|
-
const { store } = repos.category;
|
|
3535
|
-
return {
|
|
3536
|
-
async list() {
|
|
3537
|
-
return store.read((tx) => repos.category.list(tx));
|
|
3538
|
-
},
|
|
3539
|
-
async getById(id) {
|
|
3540
|
-
const c = await store.read((tx) => repos.category.findById(tx, id));
|
|
3541
|
-
if (!c) throw new NotFoundError2("category", id);
|
|
3542
|
-
return c;
|
|
3543
|
-
},
|
|
3544
|
-
async getBySlug(slug) {
|
|
3545
|
-
const c = await store.read((tx) => repos.category.findBySlug(tx, slug));
|
|
3546
|
-
if (!c) throw new NotFoundError2("category", slug);
|
|
3547
|
-
return c;
|
|
3548
|
-
},
|
|
3549
|
-
async create(input) {
|
|
3550
|
-
audit.note("category.create");
|
|
3551
|
-
if (!input.slug.trim()) throw new ValidationError3("Category slug is required");
|
|
3552
|
-
return store.transaction(async (tx) => {
|
|
3553
|
-
if (await repos.category.findBySlug(tx, input.slug)) {
|
|
3554
|
-
throw new ValidationError3(`Category slug already exists: ${input.slug}`);
|
|
3555
|
-
}
|
|
3556
|
-
const now = /* @__PURE__ */ new Date();
|
|
3557
|
-
const id = uuidv74();
|
|
3558
|
-
audit.note("category.create", [{ type: "category", id }]);
|
|
3559
|
-
const category = {
|
|
3560
|
-
id,
|
|
3561
|
-
parentId: input.parentId ?? null,
|
|
3562
|
-
slug: input.slug,
|
|
3563
|
-
name: input.name,
|
|
3564
|
-
description: input.description ?? "",
|
|
3565
|
-
position: input.position ?? 0,
|
|
3566
|
-
createdAt: now.toISOString()
|
|
3567
|
-
};
|
|
3568
|
-
await repos.category.insert(tx, { ...category, createdAt: now });
|
|
3569
|
-
await publisher.publish(EVT_CATEGORY_CREATED3, { category });
|
|
3570
|
-
return category;
|
|
3571
|
-
});
|
|
3572
|
-
},
|
|
3573
|
-
async update(id, input) {
|
|
3574
|
-
return store.transaction(async (tx) => {
|
|
3575
|
-
audit.note("category.update", [{ type: "category", id }]);
|
|
3576
|
-
const existing = await repos.category.findById(tx, id);
|
|
3577
|
-
if (!existing) throw new NotFoundError2("category", id);
|
|
3578
|
-
await repos.category.update(tx, id, input);
|
|
3579
|
-
const fresh = await repos.category.findById(tx, id);
|
|
3580
|
-
await publisher.publish(EVT_CATEGORY_UPDATED3, { category: fresh });
|
|
3581
|
-
return fresh;
|
|
3582
|
-
});
|
|
3583
|
-
},
|
|
3584
|
-
async delete(id) {
|
|
3585
|
-
await store.transaction(async (tx) => {
|
|
3586
|
-
audit.note("category.delete", [{ type: "category", id }]);
|
|
3587
|
-
const existing = await repos.category.findById(tx, id);
|
|
3588
|
-
if (!existing) throw new NotFoundError2("category", id);
|
|
3589
|
-
await repos.category.delete(tx, id);
|
|
3590
|
-
await publisher.publish(EVT_CATEGORY_DELETED3, {
|
|
3591
|
-
categoryId: existing.id,
|
|
3592
|
-
slug: existing.slug
|
|
3593
|
-
});
|
|
3594
|
-
});
|
|
3595
|
-
}
|
|
3596
|
-
};
|
|
3597
|
-
}
|
|
3598
|
-
|
|
3599
|
-
// src/services/cart-service.ts
|
|
3600
|
-
import { v7 as uuidv75 } from "uuid";
|
|
3601
|
-
import {
|
|
3602
|
-
EVT_CART_CREATED,
|
|
3603
|
-
EVT_CART_ITEM_ADDED,
|
|
3604
|
-
EVT_CART_ITEM_REMOVED,
|
|
3605
|
-
EVT_CART_UPDATED,
|
|
3606
|
-
NotFoundError as NotFoundError3,
|
|
3607
|
-
ValidationError as ValidationError4
|
|
3608
|
-
} from "@nymbalhq/types";
|
|
3609
|
-
var TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 30;
|
|
3610
|
-
function calcSubtotal(items) {
|
|
3611
|
-
return items.reduce((sum, item) => sum + item.priceMinor * item.qty, 0);
|
|
3612
|
-
}
|
|
3613
|
-
function createCartService(deps) {
|
|
3614
|
-
const { store, carts: carts3, publisher, currency } = deps;
|
|
3615
|
-
const ttlMs = (deps.ttlSeconds ?? TTL_SECONDS_DEFAULT) * 1e3;
|
|
3616
|
-
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
3617
|
-
function live(cart, at) {
|
|
3618
|
-
return cart !== null && Date.parse(cart.expiresAt) > at.getTime();
|
|
3619
|
-
}
|
|
3620
|
-
function written(cart, items, at) {
|
|
3621
|
-
return {
|
|
3622
|
-
...cart,
|
|
3623
|
-
items,
|
|
3624
|
-
subtotalMinor: calcSubtotal(items),
|
|
3625
|
-
updatedAt: at.toISOString(),
|
|
3626
|
-
expiresAt: new Date(at.getTime() + ttlMs).toISOString()
|
|
3627
|
-
};
|
|
3628
|
-
}
|
|
3629
|
-
async function requireCart(tx, token, at) {
|
|
3630
|
-
const cart = await carts3.lock(tx, token);
|
|
3631
|
-
if (!live(cart, at)) throw new NotFoundError3("cart", token);
|
|
3632
|
-
return cart;
|
|
3633
|
-
}
|
|
3634
|
-
async function emitUpdated(cart) {
|
|
3635
|
-
await publisher.publish(EVT_CART_UPDATED, {
|
|
3636
|
-
cartId: cart.token,
|
|
3637
|
-
itemCount: cart.items.reduce((n, i) => n + i.qty, 0),
|
|
3638
|
-
totalMinor: cart.subtotalMinor
|
|
3639
|
-
});
|
|
3640
|
-
}
|
|
3641
|
-
function command(token, change) {
|
|
3642
|
-
return store.transaction(async (tx) => {
|
|
3643
|
-
const at = now();
|
|
3644
|
-
const next = await change(await requireCart(tx, token, at), at);
|
|
3645
|
-
await carts3.put(tx, next);
|
|
3646
|
-
await emitUpdated(next);
|
|
3647
|
-
return next;
|
|
3648
|
-
});
|
|
3649
|
-
}
|
|
3650
|
-
return {
|
|
3651
|
-
async getOrCreate(token, customerId = null) {
|
|
3652
|
-
return store.transaction(async (tx) => {
|
|
3653
|
-
const at = now();
|
|
3654
|
-
const { cart, created } = await carts3.create(tx, {
|
|
3655
|
-
token: token ?? uuidv75(),
|
|
3656
|
-
customerId,
|
|
3657
|
-
items: [],
|
|
3658
|
-
subtotalMinor: 0,
|
|
3659
|
-
currency,
|
|
3660
|
-
expiresAt: new Date(at.getTime() + ttlMs).toISOString(),
|
|
3661
|
-
createdAt: at.toISOString(),
|
|
3662
|
-
updatedAt: at.toISOString()
|
|
3663
|
-
});
|
|
3664
|
-
if (created) {
|
|
3665
|
-
await publisher.publish(EVT_CART_CREATED, { cartId: cart.token, token: cart.token });
|
|
3666
|
-
}
|
|
3667
|
-
return cart;
|
|
3668
|
-
});
|
|
3669
|
-
},
|
|
3670
|
-
async get(token) {
|
|
3671
|
-
const at = now();
|
|
3672
|
-
const cart = await store.read((tx) => carts3.findByToken(tx, token));
|
|
3673
|
-
return live(cart, at) ? cart : null;
|
|
3674
|
-
},
|
|
3675
|
-
async addItem(token, item) {
|
|
3676
|
-
return command(token, async (cart, at) => {
|
|
3677
|
-
const qty = item.qty ?? 1;
|
|
3678
|
-
if (qty <= 0) throw new ValidationError4(`qty must be positive, got ${qty}`);
|
|
3679
|
-
const onCart = cart.items.some((i) => i.variantId === item.variantId);
|
|
3680
|
-
const items = onCart ? cart.items.map((i) => i.variantId === item.variantId ? { ...i, qty: i.qty + qty } : i) : [
|
|
3681
|
-
...cart.items,
|
|
3682
|
-
{
|
|
3683
|
-
variantId: item.variantId,
|
|
3684
|
-
productId: item.productId,
|
|
3685
|
-
productName: item.productName,
|
|
3686
|
-
variantName: item.variantName,
|
|
3687
|
-
priceMinor: item.priceMinor,
|
|
3688
|
-
imageUrl: item.imageUrl,
|
|
3689
|
-
qty
|
|
3690
|
-
}
|
|
3691
|
-
];
|
|
3692
|
-
await publisher.publish(EVT_CART_ITEM_ADDED, {
|
|
3693
|
-
cartId: cart.token,
|
|
3694
|
-
variantId: item.variantId,
|
|
3695
|
-
qty
|
|
3696
|
-
});
|
|
3697
|
-
return written(cart, items, at);
|
|
3698
|
-
});
|
|
3699
|
-
},
|
|
3700
|
-
async updateItemQuantity(token, variantId, qty) {
|
|
3701
|
-
if (qty < 0) throw new ValidationError4(`qty must be non-negative, got ${qty}`);
|
|
3702
|
-
return command(token, async (cart, at) => {
|
|
3703
|
-
if (!cart.items.some((i) => i.variantId === variantId)) {
|
|
3704
|
-
throw new NotFoundError3("cart_item", variantId);
|
|
3705
|
-
}
|
|
3706
|
-
if (qty === 0) {
|
|
3707
|
-
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
3708
|
-
return written(
|
|
3709
|
-
cart,
|
|
3710
|
-
cart.items.filter((i) => i.variantId !== variantId),
|
|
3711
|
-
at
|
|
3712
|
-
);
|
|
3713
|
-
}
|
|
3714
|
-
return written(
|
|
3715
|
-
cart,
|
|
3716
|
-
cart.items.map((i) => i.variantId === variantId ? { ...i, qty } : i),
|
|
3717
|
-
at
|
|
3718
|
-
);
|
|
3719
|
-
});
|
|
3720
|
-
},
|
|
3721
|
-
async removeItem(token, variantId) {
|
|
3722
|
-
return command(token, async (cart, at) => {
|
|
3723
|
-
const items = cart.items.filter((i) => i.variantId !== variantId);
|
|
3724
|
-
if (items.length < cart.items.length) {
|
|
3725
|
-
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
3726
|
-
}
|
|
3727
|
-
return written(cart, items, at);
|
|
3728
|
-
});
|
|
3729
|
-
},
|
|
3730
|
-
async clear(token) {
|
|
3731
|
-
return command(token, async (cart, at) => written(cart, [], at));
|
|
3732
|
-
},
|
|
3733
|
-
async attachCustomer(token, customerId) {
|
|
3734
|
-
return command(token, async (cart, at) => ({ ...written(cart, cart.items, at), customerId }));
|
|
3735
|
-
},
|
|
3736
|
-
async merge(guestToken, customerToken) {
|
|
3737
|
-
return store.transaction(async (tx) => {
|
|
3738
|
-
const at = now();
|
|
3739
|
-
const guest = await carts3.lock(tx, guestToken);
|
|
3740
|
-
if (!live(guest, at)) return requireCart(tx, customerToken, at);
|
|
3741
|
-
const customerCart = await carts3.lock(tx, customerToken);
|
|
3742
|
-
let merged;
|
|
3743
|
-
if (live(customerCart, at)) {
|
|
3744
|
-
const held = customerCart.items;
|
|
3745
|
-
const items = [
|
|
3746
|
-
...held.map((i) => {
|
|
3747
|
-
const g = guest.items.find((x) => x.variantId === i.variantId);
|
|
3748
|
-
return g ? { ...i, qty: Math.max(i.qty, g.qty) } : i;
|
|
3749
|
-
}),
|
|
3750
|
-
...guest.items.filter((g) => !held.some((i) => i.variantId === g.variantId))
|
|
3751
|
-
];
|
|
3752
|
-
merged = written(customerCart, items, at);
|
|
3753
|
-
} else {
|
|
3754
|
-
merged = written({ ...guest, token: customerToken }, guest.items, at);
|
|
3755
|
-
}
|
|
3756
|
-
await carts3.remove(tx, guestToken);
|
|
3757
|
-
await carts3.put(tx, merged);
|
|
3758
|
-
await emitUpdated(merged);
|
|
3759
|
-
return merged;
|
|
3760
|
-
});
|
|
3761
|
-
}
|
|
3762
|
-
};
|
|
3763
|
-
}
|
|
3764
|
-
|
|
3765
|
-
// src/services/customer-service.ts
|
|
3766
|
-
import { v7 as uuidv76 } from "uuid";
|
|
3767
|
-
import {
|
|
3768
|
-
EVT_CUSTOMER_UPDATED as EVT_CUSTOMER_UPDATED2,
|
|
3769
|
-
NotFoundError as NotFoundError4,
|
|
3770
|
-
ValidationError as ValidationError5
|
|
3771
|
-
} from "@nymbalhq/types";
|
|
3772
|
-
function stripPassword(c) {
|
|
3773
|
-
const { passwordHash: _pw, ...rest } = c;
|
|
3774
|
-
return rest;
|
|
3775
|
-
}
|
|
3776
|
-
function createCustomerService(deps) {
|
|
3777
|
-
const { repos, publisher } = deps;
|
|
3778
|
-
const { store } = repos.customer;
|
|
3779
|
-
async function loadOrThrow(tx, id) {
|
|
3780
|
-
const c = await repos.customer.findById(tx, id);
|
|
3781
|
-
if (!c) throw new NotFoundError4("customer", id);
|
|
3782
|
-
return c;
|
|
3783
|
-
}
|
|
3784
|
-
return {
|
|
3785
|
-
async getProfile(customerId) {
|
|
3786
|
-
return stripPassword(await store.read((tx) => loadOrThrow(tx, customerId)));
|
|
3787
|
-
},
|
|
3788
|
-
async updateProfile(customerId, patch) {
|
|
3789
|
-
return store.transaction(async (tx) => {
|
|
3790
|
-
audit.note("customer.update", [{ type: "customer", id: customerId }]);
|
|
3791
|
-
await loadOrThrow(tx, customerId);
|
|
3792
|
-
const now = /* @__PURE__ */ new Date();
|
|
3793
|
-
await repos.customer.update(tx, customerId, { ...patch, updatedAt: now });
|
|
3794
|
-
await publisher.publish(EVT_CUSTOMER_UPDATED2, { customerId });
|
|
3795
|
-
const fresh = await loadOrThrow(tx, customerId);
|
|
3796
|
-
return stripPassword(fresh);
|
|
3797
|
-
});
|
|
3798
|
-
},
|
|
3799
|
-
async listAddresses(customerId) {
|
|
3800
|
-
const customer = await store.read((tx) => loadOrThrow(tx, customerId));
|
|
3801
|
-
return customer.addresses;
|
|
3802
|
-
},
|
|
3803
|
-
async addAddress(customerId, addr) {
|
|
3804
|
-
return store.transaction(async (tx) => {
|
|
3805
|
-
audit.note("customer.addAddress", [{ type: "customer", id: customerId }]);
|
|
3806
|
-
const customer = await loadOrThrow(tx, customerId);
|
|
3807
|
-
const newAddr = { ...addr, id: uuidv76() };
|
|
3808
|
-
const defaultBilling = newAddr.isDefaultBilling;
|
|
3809
|
-
const defaultShipping = newAddr.isDefaultShipping;
|
|
3810
|
-
const addresses = customer.addresses.map((a) => ({
|
|
3811
|
-
...a,
|
|
3812
|
-
isDefaultBilling: defaultBilling ? false : a.isDefaultBilling,
|
|
3813
|
-
isDefaultShipping: defaultShipping ? false : a.isDefaultShipping
|
|
3814
|
-
}));
|
|
3815
|
-
addresses.push(newAddr);
|
|
3816
|
-
const now = /* @__PURE__ */ new Date();
|
|
3817
|
-
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
3818
|
-
await publisher.publish(EVT_CUSTOMER_UPDATED2, { customerId });
|
|
3819
|
-
return newAddr;
|
|
3820
|
-
});
|
|
3821
|
-
},
|
|
3822
|
-
async deleteAddress(customerId, addressId) {
|
|
3823
|
-
await store.transaction(async (tx) => {
|
|
3824
|
-
audit.note("customer.removeAddress", [{ type: "customer", id: customerId }]);
|
|
3825
|
-
const customer = await loadOrThrow(tx, customerId);
|
|
3826
|
-
const addresses = customer.addresses.filter((a) => a.id !== addressId);
|
|
3827
|
-
if (addresses.length === customer.addresses.length) {
|
|
3828
|
-
throw new NotFoundError4("address", addressId);
|
|
3829
|
-
}
|
|
3830
|
-
if (!addresses.length) {
|
|
3831
|
-
throw new ValidationError5("Cannot remove last address");
|
|
3832
|
-
}
|
|
3833
|
-
const now = /* @__PURE__ */ new Date();
|
|
3834
|
-
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
3835
|
-
await publisher.publish(EVT_CUSTOMER_UPDATED2, { customerId });
|
|
3836
|
-
});
|
|
3837
|
-
}
|
|
3838
|
-
};
|
|
3839
|
-
}
|
|
3840
|
-
|
|
3841
|
-
// src/services/auth-service.ts
|
|
3842
|
-
import { v7 as uuidv77 } from "uuid";
|
|
3843
|
-
import bcrypt from "bcryptjs";
|
|
3844
|
-
import { SignJWT, jwtVerify } from "jose";
|
|
3845
|
-
import { createHash } from "crypto";
|
|
3846
|
-
import {
|
|
3847
|
-
AuthError,
|
|
3848
|
-
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3,
|
|
3849
|
-
ValidationError as ValidationError6
|
|
3850
|
-
} from "@nymbalhq/types";
|
|
3851
|
-
var { hash: bcryptHash, compare: bcryptCompare } = bcrypt;
|
|
3852
|
-
function parseDurationToMs(s) {
|
|
3853
|
-
const match = /^(\d+)(ms|s|m|h|d)$/.exec(s);
|
|
3854
|
-
if (!match) throw new ValidationError6(`invalid duration: ${s}`);
|
|
3855
|
-
const qty = Number(match[1]);
|
|
3856
|
-
switch (match[2]) {
|
|
3857
|
-
case "ms":
|
|
3858
|
-
return qty;
|
|
3859
|
-
case "s":
|
|
3860
|
-
return qty * 1e3;
|
|
3861
|
-
case "m":
|
|
3862
|
-
return qty * 60 * 1e3;
|
|
3863
|
-
case "h":
|
|
3864
|
-
return qty * 60 * 60 * 1e3;
|
|
3865
|
-
case "d":
|
|
3866
|
-
return qty * 24 * 60 * 60 * 1e3;
|
|
3867
|
-
/* c8 ignore next 2 -- regex above only matches ms|s|m|h|d, making this unreachable */
|
|
3868
|
-
default:
|
|
3869
|
-
throw new ValidationError6(`invalid duration unit: ${match[2]}`);
|
|
3870
|
-
}
|
|
3871
|
-
}
|
|
3872
|
-
function hashRefresh(token) {
|
|
3873
|
-
return createHash("sha256").update(token).digest("hex");
|
|
3874
|
-
}
|
|
3875
|
-
function stripPassword2(c) {
|
|
3876
|
-
const { passwordHash: _pw, ...rest } = c;
|
|
3877
|
-
return rest;
|
|
3878
|
-
}
|
|
3879
|
-
function createAuthService(deps) {
|
|
3880
|
-
const { repos, publisher, logger, jwtSecret, accessTtl, refreshTtl } = deps;
|
|
3881
|
-
const { store } = repos.customer;
|
|
3882
|
-
const issuer = deps.issuer ?? "nymbal";
|
|
3883
|
-
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
3884
|
-
const accessTtlMs = parseDurationToMs(accessTtl);
|
|
3885
|
-
const refreshTtlMs = parseDurationToMs(refreshTtl);
|
|
3886
|
-
async function mintAccess(customer) {
|
|
3887
|
-
return new SignJWT({
|
|
3888
|
-
sub: customer.id,
|
|
3889
|
-
email: customer.email,
|
|
3890
|
-
roles: customer.roles,
|
|
3891
|
-
type: "access"
|
|
3892
|
-
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setIssuer(issuer).setExpirationTime(new Date(Date.now() + accessTtlMs)).sign(secretKey);
|
|
3893
|
-
}
|
|
3894
|
-
async function mintRefresh(customer, jti) {
|
|
3895
|
-
return new SignJWT({
|
|
3896
|
-
sub: customer.id,
|
|
3897
|
-
email: customer.email,
|
|
3898
|
-
roles: ["customer"],
|
|
3899
|
-
type: "refresh",
|
|
3900
|
-
jti
|
|
3901
|
-
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setJti(jti).setIssuer(issuer).setExpirationTime(new Date(Date.now() + refreshTtlMs)).sign(secretKey);
|
|
3902
|
-
}
|
|
3903
|
-
async function issueTokens(customer) {
|
|
3904
|
-
const jti = uuidv77();
|
|
3905
|
-
const refreshToken = await mintRefresh(customer, jti);
|
|
3906
|
-
await store.transaction(
|
|
3907
|
-
(tx) => repos.refreshToken.insert(tx, {
|
|
3908
|
-
id: jti,
|
|
3909
|
-
customerId: customer.id,
|
|
3910
|
-
tokenHash: hashRefresh(refreshToken),
|
|
3911
|
-
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
3912
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
3913
|
-
})
|
|
3914
|
-
);
|
|
3915
|
-
const accessToken = await mintAccess(customer);
|
|
3916
|
-
return {
|
|
3917
|
-
accessToken,
|
|
3918
|
-
refreshToken,
|
|
3919
|
-
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
3920
|
-
};
|
|
3921
|
-
}
|
|
3922
|
-
return {
|
|
3923
|
-
async register(input) {
|
|
3924
|
-
audit.note("customer.register");
|
|
3925
|
-
if (!input.email.includes("@")) throw new ValidationError6("invalid email");
|
|
3926
|
-
if (input.password.length < 8) throw new ValidationError6("password must be \u2265 8 characters");
|
|
3927
|
-
const email = input.email.toLowerCase();
|
|
3928
|
-
const existing = await store.read((tx) => repos.customer.findByEmail(tx, email));
|
|
3929
|
-
if (existing) {
|
|
3930
|
-
throw new AuthError("invalid_credentials", "An account with this email already exists");
|
|
3931
|
-
}
|
|
3932
|
-
const id = uuidv77();
|
|
3933
|
-
const passwordHash = await bcryptHash(input.password, 10);
|
|
3934
|
-
const now = /* @__PURE__ */ new Date();
|
|
3935
|
-
const customer = await store.transaction(async (tx) => {
|
|
3936
|
-
audit.note("customer.register", [{ type: "customer", id }]);
|
|
3937
|
-
await repos.customer.insert(tx, {
|
|
3938
|
-
id,
|
|
3939
|
-
email,
|
|
3940
|
-
passwordHash,
|
|
3941
|
-
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
3942
|
-
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
3943
|
-
...input.phone !== void 0 && { phone: input.phone },
|
|
3944
|
-
createdAt: now,
|
|
3945
|
-
updatedAt: now
|
|
3946
|
-
});
|
|
3947
|
-
const inserted = await repos.customer.findById(tx, id);
|
|
3948
|
-
if (!inserted) throw new Error("customer disappeared after insert");
|
|
3949
|
-
await publisher.publish(EVT_CUSTOMER_CREATED3, { customerId: id, email });
|
|
3950
|
-
return inserted;
|
|
3951
|
-
});
|
|
3952
|
-
const tokens = await issueTokens(customer);
|
|
3953
|
-
logger.info({ customerId: id }, "customer registered");
|
|
3954
|
-
return { customer: stripPassword2(customer), tokens };
|
|
3955
|
-
},
|
|
3956
|
-
async login(email, password) {
|
|
3957
|
-
const customer = await store.read((tx) => repos.customer.findByEmail(tx, email.toLowerCase()));
|
|
3958
|
-
if (!customer) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
3959
|
-
const ok = await bcryptCompare(password, customer.passwordHash);
|
|
3960
|
-
if (!ok) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
3961
|
-
const tokens = await issueTokens(customer);
|
|
3962
|
-
logger.info({ customerId: customer.id }, "customer login");
|
|
3963
|
-
return { customer: stripPassword2(customer), tokens };
|
|
3964
|
-
},
|
|
3965
|
-
async refresh(refreshToken) {
|
|
3966
|
-
let verified;
|
|
3967
|
-
try {
|
|
3968
|
-
verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
3969
|
-
} catch {
|
|
3970
|
-
throw new AuthError("token_invalid", "refresh token invalid");
|
|
3971
|
-
}
|
|
3972
|
-
const payload = verified.payload;
|
|
3973
|
-
if (payload.type !== "refresh" || !payload.jti || !payload.sub) {
|
|
3974
|
-
throw new AuthError("token_invalid", "not a refresh token");
|
|
3975
|
-
}
|
|
3976
|
-
const jti = payload.jti;
|
|
3977
|
-
const customerId = payload.sub;
|
|
3978
|
-
const record = await store.read((tx) => repos.refreshToken.findById(tx, jti));
|
|
3979
|
-
if (!record) throw new AuthError("token_invalid", "refresh token unknown");
|
|
3980
|
-
if (record.revokedAt) throw new AuthError("token_invalid", "refresh token revoked");
|
|
3981
|
-
if (record.tokenHash !== hashRefresh(refreshToken)) {
|
|
3982
|
-
await store.transaction((tx) => repos.refreshToken.revokeAllForCustomer(tx, customerId));
|
|
3983
|
-
throw new AuthError("token_invalid", "refresh token mismatch; revoking chain");
|
|
3984
|
-
}
|
|
3985
|
-
const customer = await store.read((tx) => repos.customer.findById(tx, customerId));
|
|
3986
|
-
if (!customer) throw new AuthError("token_invalid", "customer missing");
|
|
3987
|
-
const nextJti = uuidv77();
|
|
3988
|
-
const nextRefresh = await mintRefresh(customer, nextJti);
|
|
3989
|
-
await store.transaction(
|
|
3990
|
-
(tx) => repos.refreshToken.rotate(tx, jti, {
|
|
3991
|
-
id: nextJti,
|
|
3992
|
-
customerId: customer.id,
|
|
3993
|
-
tokenHash: hashRefresh(nextRefresh),
|
|
3994
|
-
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
3995
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
3996
|
-
})
|
|
3997
|
-
);
|
|
3998
|
-
const accessToken = await mintAccess(customer);
|
|
3999
|
-
return {
|
|
4000
|
-
accessToken,
|
|
4001
|
-
refreshToken: nextRefresh,
|
|
4002
|
-
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
4003
|
-
};
|
|
4004
|
-
},
|
|
4005
|
-
async logout(refreshToken) {
|
|
4006
|
-
try {
|
|
4007
|
-
const verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
4008
|
-
const payload = verified.payload;
|
|
4009
|
-
const { jti } = payload;
|
|
4010
|
-
if (jti) await store.transaction((tx) => repos.refreshToken.revoke(tx, jti));
|
|
4011
|
-
} catch {
|
|
4012
|
-
}
|
|
4013
|
-
},
|
|
4014
|
-
async verifyAccessToken(token) {
|
|
4015
|
-
try {
|
|
4016
|
-
const verified = await jwtVerify(token, secretKey, { issuer });
|
|
4017
|
-
const payload = verified.payload;
|
|
4018
|
-
if (payload.type !== "access") throw new AuthError("token_invalid", "not an access token");
|
|
4019
|
-
return payload;
|
|
4020
|
-
} catch (err) {
|
|
4021
|
-
if (err instanceof AuthError) throw err;
|
|
4022
|
-
throw new AuthError("token_invalid", "access token invalid", { cause: err });
|
|
4023
|
-
}
|
|
4024
|
-
},
|
|
4025
|
-
async importCustomer(input) {
|
|
4026
|
-
if (!input.email.includes("@")) throw new ValidationError6("invalid email");
|
|
4027
|
-
const email = input.email.toLowerCase();
|
|
4028
|
-
const customer = await store.transaction(async (tx) => {
|
|
4029
|
-
const existing = await repos.customer.findByEmail(tx, email);
|
|
4030
|
-
if (existing) return existing;
|
|
4031
|
-
const id = uuidv77();
|
|
4032
|
-
audit.note("customer.import", [{ type: "customer", id }]);
|
|
4033
|
-
const now = /* @__PURE__ */ new Date();
|
|
4034
|
-
await repos.customer.insert(tx, {
|
|
4035
|
-
id,
|
|
4036
|
-
email,
|
|
4037
|
-
passwordHash: "IMPORTED_NO_PASSWORD",
|
|
4038
|
-
requiresPasswordReset: true,
|
|
4039
|
-
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
4040
|
-
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
4041
|
-
...input.phone !== void 0 && { phone: input.phone },
|
|
4042
|
-
...input.addresses !== void 0 && { addresses: input.addresses },
|
|
4043
|
-
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
4044
|
-
roles: ["customer"],
|
|
4045
|
-
createdAt: now,
|
|
4046
|
-
updatedAt: now
|
|
4047
|
-
});
|
|
4048
|
-
const inserted = await repos.customer.findById(tx, id);
|
|
4049
|
-
if (!inserted) throw new Error("customer disappeared after insert");
|
|
4050
|
-
await publisher.publish(EVT_CUSTOMER_CREATED3, { customerId: id, email });
|
|
4051
|
-
logger.info({ customerId: id }, "customer imported");
|
|
4052
|
-
return inserted;
|
|
4053
|
-
});
|
|
4054
|
-
return stripPassword2(customer);
|
|
4055
|
-
}
|
|
4056
|
-
};
|
|
4057
|
-
}
|
|
4058
|
-
|
|
4059
|
-
// src/services/order-service.ts
|
|
4060
|
-
import { v7 as uuidv78 } from "uuid";
|
|
4061
|
-
import {
|
|
4062
|
-
EVT_ORDER_CANCELLED as EVT_ORDER_CANCELLED2,
|
|
4063
|
-
EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED3,
|
|
4064
|
-
EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
|
|
4065
|
-
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED3,
|
|
4066
|
-
EVT_ORDER_STATUS_CHANGED as EVT_ORDER_STATUS_CHANGED2,
|
|
4067
|
-
NotFoundError as NotFoundError5,
|
|
4068
|
-
OrderConflictError,
|
|
4069
|
-
StatusTransitionError,
|
|
4070
|
-
ValidationError as ValidationError7,
|
|
4071
|
-
assertOrderTransition
|
|
4072
|
-
} from "@nymbalhq/types";
|
|
4073
|
-
function createOrderService(deps) {
|
|
4074
|
-
const { store, repos, publisher } = deps;
|
|
4075
|
-
async function requireOrder(tx, id) {
|
|
4076
|
-
const order = await repos.order.findById(tx, id);
|
|
4077
|
-
if (!order) throw new NotFoundError5("order", id);
|
|
4078
|
-
return order;
|
|
4079
|
-
}
|
|
4080
|
-
async function doTransition(tx, order, toStatus, actor, note) {
|
|
4081
|
-
assertOrderTransition(order.status, toStatus);
|
|
4082
|
-
const now = /* @__PURE__ */ new Date();
|
|
4083
|
-
await repos.order.setStatus(tx, order.id, toStatus, now);
|
|
4084
|
-
await repos.orderHistory.append(tx, {
|
|
4085
|
-
id: uuidv78(),
|
|
4086
|
-
orderId: order.id,
|
|
4087
|
-
fromStatus: order.status,
|
|
4088
|
-
toStatus,
|
|
4089
|
-
actor,
|
|
4090
|
-
note,
|
|
4091
|
-
timestamp: now
|
|
4092
|
-
});
|
|
4093
|
-
return requireOrder(tx, order.id);
|
|
4094
|
-
}
|
|
4095
|
-
return {
|
|
4096
|
-
async createFromCheckout(input) {
|
|
4097
|
-
return store.transaction(async (tx) => {
|
|
4098
|
-
audit.note("order.place", [{ type: "order", id: input.orderId }]);
|
|
4099
|
-
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
4100
|
-
const orderNumber = `${deps.orderNumberPrefix}-${sequence + 1}`;
|
|
4101
|
-
const now = /* @__PURE__ */ new Date();
|
|
4102
|
-
await repos.order.insert(tx, {
|
|
4103
|
-
id: input.orderId,
|
|
4104
|
-
orderNumber,
|
|
4105
|
-
sequence,
|
|
4106
|
-
customerId: input.customerId,
|
|
4107
|
-
status: "pending",
|
|
4108
|
-
email: input.email,
|
|
4109
|
-
billingAddress: input.billingAddress,
|
|
4110
|
-
shippingAddress: input.shippingAddress,
|
|
4111
|
-
lineItems: input.lineItems,
|
|
4112
|
-
subtotalMinor: input.subtotalMinor,
|
|
4113
|
-
taxTotalMinor: input.taxTotalMinor,
|
|
4114
|
-
shippingTotalMinor: input.shippingTotalMinor,
|
|
4115
|
-
discountTotalMinor: input.discountTotalMinor,
|
|
4116
|
-
totalMinor: input.totalMinor,
|
|
4117
|
-
currency: input.currency,
|
|
4118
|
-
notes: input.notes ?? "",
|
|
4119
|
-
metadata: input.metadata ?? {},
|
|
4120
|
-
paymentIntentId: input.paymentIntentId ?? null,
|
|
4121
|
-
cartToken: input.cartToken ?? null,
|
|
4122
|
-
createdAt: now,
|
|
4123
|
-
updatedAt: now
|
|
4124
|
-
});
|
|
4125
|
-
await repos.orderHistory.append(tx, {
|
|
4126
|
-
id: uuidv78(),
|
|
4127
|
-
orderId: input.orderId,
|
|
4128
|
-
fromStatus: null,
|
|
4129
|
-
toStatus: "pending",
|
|
4130
|
-
actor: "system:checkout",
|
|
4131
|
-
note: "order draft created",
|
|
4132
|
-
timestamp: now
|
|
4133
|
-
});
|
|
4134
|
-
const fresh = await requireOrder(tx, input.orderId);
|
|
4135
|
-
await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
|
|
4136
|
-
return fresh;
|
|
4137
|
-
});
|
|
4138
|
-
},
|
|
4139
|
-
async getById(id) {
|
|
4140
|
-
return store.read((tx) => requireOrder(tx, id));
|
|
4141
|
-
},
|
|
4142
|
-
async getByOrderNumber(orderNumber) {
|
|
4143
|
-
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
4144
|
-
if (!order) throw new NotFoundError5("order", orderNumber);
|
|
4145
|
-
return order;
|
|
4146
|
-
},
|
|
4147
|
-
async listByCustomer(customerId) {
|
|
4148
|
-
return store.read((tx) => repos.order.listByCustomer(tx, customerId));
|
|
4149
|
-
},
|
|
4150
|
-
async updateStatus(id, toStatus, actor, note = "") {
|
|
4151
|
-
return store.transaction(async (tx) => {
|
|
4152
|
-
audit.note("order.updateStatus", [{ type: "order", id }]);
|
|
4153
|
-
const order = await requireOrder(tx, id);
|
|
4154
|
-
const fresh = await doTransition(tx, order, toStatus, actor, note);
|
|
4155
|
-
await publisher.publish(EVT_ORDER_STATUS_CHANGED2, {
|
|
4156
|
-
orderId: fresh.id,
|
|
4157
|
-
from: order.status,
|
|
4158
|
-
to: fresh.status
|
|
4159
|
-
});
|
|
4160
|
-
return fresh;
|
|
4161
|
-
});
|
|
4162
|
-
},
|
|
4163
|
-
async markShipped(id, trackingNumber, carrier, actor) {
|
|
4164
|
-
return store.transaction(async (tx) => {
|
|
4165
|
-
audit.note("order.ship", [{ type: "order", id }]);
|
|
4166
|
-
const order = await requireOrder(tx, id);
|
|
4167
|
-
const fresh = await doTransition(
|
|
4168
|
-
tx,
|
|
4169
|
-
order,
|
|
4170
|
-
"shipped",
|
|
4171
|
-
actor,
|
|
4172
|
-
`Shipped via ${carrier}: ${trackingNumber}`
|
|
4173
|
-
);
|
|
4174
|
-
await publisher.publish(EVT_ORDER_SHIPPED3, {
|
|
4175
|
-
orderId: fresh.id,
|
|
4176
|
-
trackingNumber,
|
|
4177
|
-
carrier
|
|
4178
|
-
});
|
|
4179
|
-
return fresh;
|
|
4180
|
-
});
|
|
4181
|
-
},
|
|
4182
|
-
async markDelivered(id, actor) {
|
|
4183
|
-
return store.transaction(async (tx) => {
|
|
4184
|
-
audit.note("order.markDelivered", [{ type: "order", id }]);
|
|
4185
|
-
const order = await requireOrder(tx, id);
|
|
4186
|
-
const fresh = await doTransition(tx, order, "delivered", actor, "Delivered");
|
|
4187
|
-
await publisher.publish(EVT_ORDER_DELIVERED3, { orderId: fresh.id });
|
|
4188
|
-
return fresh;
|
|
4189
|
-
});
|
|
4190
|
-
},
|
|
4191
|
-
async cancel(id, reason, actor) {
|
|
4192
|
-
return store.transaction(async (tx) => {
|
|
4193
|
-
audit.note("order.cancel", [{ type: "order", id }]);
|
|
4194
|
-
const order = await repos.order.lock(tx, id);
|
|
4195
|
-
if (!order) throw new NotFoundError5("order", id);
|
|
4196
|
-
if (order.capturedMinor > 0) {
|
|
4197
|
-
throw new OrderConflictError(
|
|
4198
|
-
"order.paid",
|
|
4199
|
-
`Order ${order.orderNumber} is paid: refund it instead of cancelling`
|
|
4200
|
-
);
|
|
4201
|
-
}
|
|
4202
|
-
assertOrderTransition(order.status, "cancelled");
|
|
4203
|
-
const now = /* @__PURE__ */ new Date();
|
|
4204
|
-
if (!await repos.order.setStatusIf(tx, order.id, order.status, "cancelled", now)) {
|
|
4205
|
-
const current = await requireOrder(tx, order.id);
|
|
4206
|
-
throw new StatusTransitionError("order", current.status, "cancelled");
|
|
4207
|
-
}
|
|
4208
|
-
await repos.orderHistory.append(tx, {
|
|
4209
|
-
id: uuidv78(),
|
|
4210
|
-
orderId: order.id,
|
|
4211
|
-
fromStatus: order.status,
|
|
4212
|
-
toStatus: "cancelled",
|
|
4213
|
-
actor,
|
|
4214
|
-
note: reason,
|
|
4215
|
-
timestamp: now
|
|
4216
|
-
});
|
|
4217
|
-
const fresh = await requireOrder(tx, order.id);
|
|
4218
|
-
await publisher.publish(EVT_ORDER_CANCELLED2, { orderId: fresh.id, reason });
|
|
4219
|
-
return fresh;
|
|
4220
|
-
});
|
|
4221
|
-
},
|
|
4222
|
-
async importOrder(input) {
|
|
4223
|
-
const capturedMinor = input.capturedMinor ?? 0;
|
|
4224
|
-
const refundedMinor = input.refundedMinor ?? 0;
|
|
4225
|
-
if (!(0 <= refundedMinor && refundedMinor <= capturedMinor && capturedMinor <= input.totalMinor) || capturedMinor > 0 !== (input.captureMethod != null)) {
|
|
4226
|
-
throw new ValidationError7("imported payment amounts are inconsistent", {
|
|
4227
|
-
context: { capturedMinor, refundedMinor, totalMinor: input.totalMinor }
|
|
4228
|
-
});
|
|
4229
|
-
}
|
|
4230
|
-
return store.transaction(async (tx) => {
|
|
4231
|
-
audit.note("order.import", [{ type: "order", id: input.orderId }]);
|
|
4232
|
-
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
4233
|
-
await repos.order.insert(tx, {
|
|
4234
|
-
id: input.orderId,
|
|
4235
|
-
orderNumber: input.orderNumber,
|
|
4236
|
-
sequence,
|
|
4237
|
-
customerId: input.customerId,
|
|
4238
|
-
status: input.status,
|
|
4239
|
-
email: input.email,
|
|
4240
|
-
billingAddress: input.billingAddress,
|
|
4241
|
-
shippingAddress: input.shippingAddress,
|
|
4242
|
-
lineItems: input.lineItems,
|
|
4243
|
-
subtotalMinor: input.subtotalMinor,
|
|
4244
|
-
taxTotalMinor: input.taxTotalMinor,
|
|
4245
|
-
shippingTotalMinor: input.shippingTotalMinor,
|
|
4246
|
-
discountTotalMinor: input.discountTotalMinor,
|
|
4247
|
-
totalMinor: input.totalMinor,
|
|
4248
|
-
currency: input.currency,
|
|
4249
|
-
notes: input.notes ?? "",
|
|
4250
|
-
metadata: input.metadata ?? {},
|
|
4251
|
-
paymentIntentId: input.paymentIntentId ?? null,
|
|
4252
|
-
...input.captureMethod != null && {
|
|
4253
|
-
capture: {
|
|
4254
|
-
amountMinor: capturedMinor,
|
|
4255
|
-
method: input.captureMethod,
|
|
4256
|
-
at: input.createdAt,
|
|
4257
|
-
refundedMinor
|
|
4258
|
-
}
|
|
4259
|
-
},
|
|
4260
|
-
createdAt: input.createdAt,
|
|
4261
|
-
updatedAt: input.createdAt
|
|
4262
|
-
});
|
|
4263
|
-
const fresh = await requireOrder(tx, input.orderId);
|
|
4264
|
-
await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
|
|
4265
|
-
return fresh;
|
|
4266
|
-
});
|
|
4267
|
-
}
|
|
4268
|
-
};
|
|
4269
|
-
}
|
|
4270
|
-
|
|
4271
|
-
// src/services/inventory-service.ts
|
|
4272
|
-
import { v7 as uuidv79 } from "uuid";
|
|
4273
|
-
import {
|
|
4274
|
-
AdapterError as AdapterError2,
|
|
4275
|
-
NotFoundError as NotFoundError6,
|
|
4276
|
-
ValidationError as ValidationError8,
|
|
4277
|
-
EVT_INVENTORY_CHANGED as EVT_INVENTORY_CHANGED2,
|
|
4278
|
-
EVT_INVENTORY_RESERVED,
|
|
4279
|
-
EVT_INVENTORY_RELEASED,
|
|
4280
|
-
EVT_INVENTORY_LOW_STOCK,
|
|
4281
|
-
EVT_INVENTORY_OUT_OF_STOCK
|
|
4282
|
-
} from "@nymbalhq/types";
|
|
4283
|
-
function classifyStock(stock, threshold) {
|
|
4284
|
-
if (stock <= 0) return "out_of_stock";
|
|
4285
|
-
if (stock <= threshold) return "low_stock";
|
|
4286
|
-
return "in_stock";
|
|
4287
|
-
}
|
|
4288
|
-
function createInventoryService(deps) {
|
|
4289
|
-
const { store, repos, publisher, logger } = deps;
|
|
4290
|
-
const defaultTtl = deps.defaultReservationTtlSeconds ?? 15 * 60;
|
|
4291
|
-
async function emitThresholdEvents(variantId, newQty, threshold) {
|
|
4292
|
-
if (newQty <= 0) {
|
|
4293
|
-
await publisher.publish(EVT_INVENTORY_OUT_OF_STOCK, { variantId });
|
|
4294
|
-
} else if (newQty <= threshold) {
|
|
4295
|
-
await publisher.publish(EVT_INVENTORY_LOW_STOCK, {
|
|
4296
|
-
variantId,
|
|
4297
|
-
currentQty: newQty,
|
|
4298
|
-
threshold
|
|
4299
|
-
});
|
|
4300
|
-
}
|
|
4301
|
-
}
|
|
4302
|
-
async function take(variantId, qty, orderRef, ttlSeconds) {
|
|
4303
|
-
if (qty <= 0) throw new ValidationError8(`Reservation qty must be positive, got ${qty}`);
|
|
4304
|
-
return store.transaction(async (tx) => {
|
|
4305
|
-
audit.note("inventory.reserve", [{ type: "variant", id: variantId }]);
|
|
4306
|
-
const variant = await repos.variant.findById(tx, variantId);
|
|
4307
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4308
|
-
const now = /* @__PURE__ */ new Date();
|
|
4309
|
-
const remaining = await repos.variant.decrementStock(tx, variant.id, qty, now);
|
|
4310
|
-
if (remaining === null) return { available: variant.stock };
|
|
4311
|
-
const expiresAt = new Date(now.getTime() + (ttlSeconds ?? defaultTtl) * 1e3);
|
|
4312
|
-
const reservationId = uuidv79();
|
|
4313
|
-
await repos.inventoryReservation.insert(tx, {
|
|
4314
|
-
reservationId,
|
|
4315
|
-
variantId: variant.id,
|
|
4316
|
-
qty,
|
|
4317
|
-
orderRef,
|
|
4318
|
-
expiresAt,
|
|
4319
|
-
createdAt: now
|
|
4320
|
-
});
|
|
4321
|
-
await publisher.publish(EVT_INVENTORY_RESERVED, {
|
|
4322
|
-
variantId: variant.id,
|
|
4323
|
-
qty,
|
|
4324
|
-
reservationId,
|
|
4325
|
-
expiresAt: expiresAt.toISOString()
|
|
4326
|
-
});
|
|
4327
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4328
|
-
variantId: variant.id,
|
|
4329
|
-
previousQty: remaining + qty,
|
|
4330
|
-
newQty: remaining,
|
|
4331
|
-
reason: "manual"
|
|
4332
|
-
});
|
|
4333
|
-
await emitThresholdEvents(variant.id, remaining, variant.lowStockThreshold);
|
|
4334
|
-
return { reservationId, expiresAt: expiresAt.toISOString() };
|
|
4335
|
-
});
|
|
4336
|
-
}
|
|
4337
|
-
return {
|
|
4338
|
-
async adjustStock(variantId, delta, reason, actor) {
|
|
4339
|
-
return store.transaction(async (tx) => {
|
|
4340
|
-
audit.note("inventory.adjust", [{ type: "variant", id: variantId }]);
|
|
4341
|
-
const variant = await repos.variant.findById(tx, variantId);
|
|
4342
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4343
|
-
const now = /* @__PURE__ */ new Date();
|
|
4344
|
-
const newQty = delta < 0 ? await repos.variant.decrementStock(tx, variant.id, -delta, now) : await repos.variant.incrementStock(tx, variant.id, delta, now);
|
|
4345
|
-
if (newQty === null) {
|
|
4346
|
-
throw new ValidationError8(`Cannot reduce stock below zero (variant ${variantId})`, {
|
|
4347
|
-
context: { variantId, stock: variant.stock, delta }
|
|
4348
|
-
});
|
|
4349
|
-
}
|
|
4350
|
-
const previousQty = newQty - delta;
|
|
4351
|
-
await repos.stockAdjustment.append(tx, {
|
|
4352
|
-
id: uuidv79(),
|
|
4353
|
-
variantId: variant.id,
|
|
4354
|
-
adjustment: delta,
|
|
4355
|
-
reason,
|
|
4356
|
-
actor,
|
|
4357
|
-
previousQty,
|
|
4358
|
-
newQty,
|
|
4359
|
-
timestamp: now
|
|
4360
|
-
});
|
|
4361
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4362
|
-
variantId: variant.id,
|
|
4363
|
-
previousQty,
|
|
4364
|
-
newQty,
|
|
4365
|
-
reason
|
|
4366
|
-
});
|
|
4367
|
-
await emitThresholdEvents(variant.id, newQty, variant.lowStockThreshold);
|
|
4368
|
-
logger.debug({ variantId, delta, newQty, reason }, "stock adjusted");
|
|
4369
|
-
return { newQty };
|
|
4370
|
-
});
|
|
4371
|
-
},
|
|
4372
|
-
async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
4373
|
-
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
4374
|
-
if ("available" in taken) {
|
|
4375
|
-
throw new AdapterError2(
|
|
4376
|
-
"inventory.insufficient",
|
|
4377
|
-
`Insufficient stock for variant ${variantId}`,
|
|
4378
|
-
{
|
|
4379
|
-
context: { variantId, requested: qty, available: taken.available }
|
|
4380
|
-
}
|
|
4381
|
-
);
|
|
4382
|
-
}
|
|
4383
|
-
return taken;
|
|
4384
|
-
},
|
|
4385
|
-
async tryReserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
4386
|
-
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
4387
|
-
return "available" in taken ? null : taken;
|
|
4388
|
-
},
|
|
4389
|
-
async releaseReservation(reservationId, reason) {
|
|
4390
|
-
await store.transaction(async (tx) => {
|
|
4391
|
-
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
4392
|
-
if (!reservation) {
|
|
4393
|
-
logger.debug(
|
|
4394
|
-
{ reservationId },
|
|
4395
|
-
"reservation already released, committed or never existed"
|
|
4396
|
-
);
|
|
4397
|
-
return;
|
|
4398
|
-
}
|
|
4399
|
-
audit.note("inventory.release", [{ type: "variant", id: reservation.variantId }]);
|
|
4400
|
-
const now = /* @__PURE__ */ new Date();
|
|
4401
|
-
const newQty = await repos.variant.incrementStock(
|
|
4402
|
-
tx,
|
|
4403
|
-
reservation.variantId,
|
|
4404
|
-
reservation.qty,
|
|
4405
|
-
now
|
|
4406
|
-
);
|
|
4407
|
-
if (newQty !== null) {
|
|
4408
|
-
const previousQty = newQty - reservation.qty;
|
|
4409
|
-
await repos.stockAdjustment.append(tx, {
|
|
4410
|
-
id: uuidv79(),
|
|
4411
|
-
variantId: reservation.variantId,
|
|
4412
|
-
adjustment: reservation.qty,
|
|
4413
|
-
reason: "reservation-release",
|
|
4414
|
-
actor: `system:release:${reason}`,
|
|
4415
|
-
previousQty,
|
|
4416
|
-
newQty,
|
|
4417
|
-
timestamp: now
|
|
4418
|
-
});
|
|
4419
|
-
await publisher.publish(EVT_INVENTORY_CHANGED2, {
|
|
4420
|
-
variantId: reservation.variantId,
|
|
4421
|
-
previousQty,
|
|
4422
|
-
newQty,
|
|
4423
|
-
reason: "reservation-release"
|
|
4424
|
-
});
|
|
4425
|
-
}
|
|
4426
|
-
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
4427
|
-
variantId: reservation.variantId,
|
|
4428
|
-
qty: reservation.qty,
|
|
4429
|
-
reservationId: reservation.reservationId,
|
|
4430
|
-
reason
|
|
4431
|
-
});
|
|
4432
|
-
});
|
|
4433
|
-
},
|
|
4434
|
-
async commitReservation(reservationId, actor) {
|
|
4435
|
-
await store.transaction(async (tx) => {
|
|
4436
|
-
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
4437
|
-
if (!reservation) throw new NotFoundError6("reservation", reservationId);
|
|
4438
|
-
audit.note("inventory.commit", [{ type: "variant", id: reservation.variantId }]);
|
|
4439
|
-
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
4440
|
-
if (!variant) throw new NotFoundError6("variant", reservation.variantId);
|
|
4441
|
-
await repos.stockAdjustment.append(tx, {
|
|
4442
|
-
id: uuidv79(),
|
|
4443
|
-
variantId: variant.id,
|
|
4444
|
-
adjustment: -reservation.qty,
|
|
4445
|
-
reason: "reservation-commit",
|
|
4446
|
-
actor,
|
|
4447
|
-
previousQty: variant.stock + reservation.qty,
|
|
4448
|
-
newQty: variant.stock,
|
|
4449
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
4450
|
-
});
|
|
4451
|
-
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
4452
|
-
variantId: reservation.variantId,
|
|
4453
|
-
qty: reservation.qty,
|
|
4454
|
-
reservationId: reservation.reservationId,
|
|
4455
|
-
reason: "committed"
|
|
4456
|
-
});
|
|
4457
|
-
});
|
|
4458
|
-
},
|
|
4459
|
-
async getStockStatus(variantId) {
|
|
4460
|
-
const variant = await store.read((tx) => repos.variant.findById(tx, variantId));
|
|
4461
|
-
if (!variant) throw new NotFoundError6("variant", variantId);
|
|
4462
|
-
return {
|
|
4463
|
-
stock: variant.stock,
|
|
4464
|
-
threshold: variant.lowStockThreshold,
|
|
4465
|
-
status: classifyStock(variant.stock, variant.lowStockThreshold)
|
|
4466
|
-
};
|
|
4467
|
-
}
|
|
4468
|
-
};
|
|
4469
|
-
}
|
|
4470
|
-
|
|
4471
|
-
// src/services/checkout-service.ts
|
|
4472
|
-
import { v5 as uuidv5, v7 as uuidv710 } from "uuid";
|
|
4473
|
-
import {
|
|
4474
|
-
CheckoutError,
|
|
4475
|
-
EVT_CART_CONVERTED,
|
|
4476
|
-
EVT_CART_UPDATED as EVT_CART_UPDATED2,
|
|
4477
|
-
EVT_ORDER_PAID as EVT_ORDER_PAID4,
|
|
4478
|
-
EVT_PAYMENT_CAPTURED,
|
|
4479
|
-
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
|
|
4480
|
-
EVT_PAYMENT_INTENT_CREATED as EVT_PAYMENT_INTENT_CREATED2,
|
|
4481
|
-
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
|
|
4482
|
-
NotFoundError as NotFoundError7,
|
|
4483
|
-
OrderConflictError as OrderConflictError2,
|
|
4484
|
-
PaymentError,
|
|
4485
|
-
StatusTransitionError as StatusTransitionError2
|
|
4486
|
-
} from "@nymbalhq/types";
|
|
4487
|
-
var StockUnavailable = class extends Error {
|
|
4488
|
-
constructor(variantId) {
|
|
4489
|
-
super(`stock unavailable for variant ${variantId}`);
|
|
4490
|
-
this.variantId = variantId;
|
|
4491
|
-
}
|
|
4492
|
-
variantId;
|
|
4493
|
-
};
|
|
4494
|
-
var NoLongerPending = class extends Error {
|
|
4495
|
-
};
|
|
4496
|
-
var PROVIDER_CAPTURE = {
|
|
4497
|
-
method: "provider",
|
|
4498
|
-
actor: "system:checkout",
|
|
4499
|
-
note: "payment captured"
|
|
4500
|
-
};
|
|
4501
|
-
var FINALIZE_ACTOR = "system:checkout-finalize";
|
|
4502
|
-
var CANCEL_ACTOR = "system:checkout-cancel";
|
|
4503
|
-
var DUPLICATE_CAPTURE = "duplicate_capture_refunded";
|
|
4504
|
-
var DUPLICATE_CAPTURE_HANDLER = "checkout:duplicate-capture";
|
|
4505
|
-
var CAPTURE_REFUND_NAMESPACE = "49e623d3-5784-4331-80e9-6f951d97f7c0";
|
|
4506
|
-
var SUPERSEDE_ATTEMPTS = 3;
|
|
4507
|
-
var ABANDON_AFTER_MS = 12e4;
|
|
4508
|
-
function outcomeOf(status) {
|
|
4509
|
-
if (status === "succeeded") return "succeeded";
|
|
4510
|
-
if (status === "failed" || status === "cancelled") return "failed";
|
|
4511
|
-
return "requires_action";
|
|
4512
|
-
}
|
|
4513
|
-
function sameLines(order, cart) {
|
|
4514
|
-
if (order.totalMinor !== cart.subtotalMinor || order.currency !== cart.currency) return false;
|
|
4515
|
-
if (order.lineItems.length !== cart.items.length) return false;
|
|
4516
|
-
return cart.items.every((item, i) => {
|
|
4517
|
-
const line = order.lineItems[i];
|
|
4518
|
-
return line?.variantId === item.variantId && line.qty === item.qty && line.unitPriceMinor === item.priceMinor;
|
|
4519
|
-
});
|
|
4520
|
-
}
|
|
4521
|
-
function createCheckoutService(deps) {
|
|
4522
|
-
const { store, repos, publisher, logger, cart, orders: orders4, inventory, payments, currency } = deps;
|
|
4523
|
-
async function cartEmpty(token) {
|
|
4524
|
-
const converted = await store.read((tx) => repos.order.findLastConvertedByCartToken(tx, token));
|
|
4525
|
-
return new CheckoutError(
|
|
4526
|
-
"cart_empty",
|
|
4527
|
-
"Cart has no items",
|
|
4528
|
-
converted ? { context: { orderNumber: converted.orderNumber } } : {}
|
|
4529
|
-
);
|
|
4530
|
-
}
|
|
4531
|
-
async function loadValidCart(token) {
|
|
4532
|
-
const c = await cart.get(token);
|
|
4533
|
-
if (!c) throw new NotFoundError7("cart", token);
|
|
4534
|
-
if (!c.items.length) throw await cartEmpty(token);
|
|
4535
|
-
if (c.currency !== currency) {
|
|
4536
|
-
throw new CheckoutError(
|
|
4537
|
-
"cart_empty",
|
|
4538
|
-
`Cart currency ${c.currency} does not match store currency ${currency}`
|
|
4539
|
-
);
|
|
4540
|
-
}
|
|
4541
|
-
return c;
|
|
4542
|
-
}
|
|
4543
|
-
async function settled(tx, paymentIntentId, order, paid) {
|
|
4544
|
-
if (order === null) return recordOutcome(tx, paymentIntentId, null, "no_order");
|
|
4545
|
-
if (order.captureMethod === "manual" || order.captureMethod === "import") {
|
|
4546
|
-
return refundDuplicateCapture(tx, paymentIntentId, paid, order);
|
|
4547
|
-
}
|
|
4548
|
-
if (order.status === "confirmed") return { orderNumber: order.orderNumber, finalized: true };
|
|
4549
|
-
if (order.status === "cancelled") {
|
|
4550
|
-
if (order.capturedMinor === 0) await refundCancelledCapture(paymentIntentId, paid, order);
|
|
4551
|
-
return recordOutcome(tx, paymentIntentId, order, "order_cancelled_refunded");
|
|
4552
|
-
}
|
|
4553
|
-
return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
|
|
4554
|
-
}
|
|
4555
|
-
async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
|
|
4556
|
-
await publisher.publish(EVT_PAYMENT_FAILED2, {
|
|
4557
|
-
paymentId: paymentIntentId,
|
|
4558
|
-
orderId: order?.id ?? "",
|
|
4559
|
-
reason
|
|
4560
|
-
});
|
|
4561
|
-
if (order !== null) {
|
|
4562
|
-
audit.note("payment.recordOutcome", [{ type: "order", id: order.id }]);
|
|
4563
|
-
await repos.orderHistory.append(tx, {
|
|
4564
|
-
id: uuidv710(),
|
|
4565
|
-
orderId: order.id,
|
|
4566
|
-
fromStatus: order.status,
|
|
4567
|
-
toStatus: order.status,
|
|
4568
|
-
actor: FINALIZE_ACTOR,
|
|
4569
|
-
note: `captured payment not applied: ${reason}${detail === void 0 ? "" : ` (${detail})`}`,
|
|
4570
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
4571
|
-
});
|
|
4572
|
-
}
|
|
4573
|
-
logger.warn({ paymentIntentId, orderId: order?.id, reason }, "captured payment not applied");
|
|
4574
|
-
return { orderNumber: order?.orderNumber ?? null, finalized: false, reason };
|
|
4575
|
-
}
|
|
4576
|
-
async function reservationFor(tx, order, reservationId, index) {
|
|
4577
|
-
const held = await repos.inventoryReservation.findById(tx, reservationId);
|
|
4578
|
-
if (held !== null) return reservationId;
|
|
4579
|
-
const line = order.lineItems[index];
|
|
4580
|
-
if (line === void 0) {
|
|
4581
|
-
throw new CheckoutError(
|
|
4582
|
-
"finalize_failed",
|
|
4583
|
-
`Order ${order.id} has no line for reservation ${reservationId}`
|
|
4584
|
-
);
|
|
4585
|
-
}
|
|
4586
|
-
const retaken = await inventory.tryReserveStock(line.variantId, line.qty, order.id).catch((err) => {
|
|
4587
|
-
if (err instanceof NotFoundError7) return null;
|
|
4588
|
-
throw err;
|
|
4589
|
-
});
|
|
4590
|
-
if (retaken === null) throw new StockUnavailable(line.variantId);
|
|
4591
|
-
return retaken.reservationId;
|
|
4592
|
-
}
|
|
4593
|
-
async function refundCapture(paymentIntentId, paid, currency2, key, context) {
|
|
4594
|
-
try {
|
|
4595
|
-
const answer = await payments.refund(
|
|
4596
|
-
paymentIntentId,
|
|
4597
|
-
paid.amountMinor,
|
|
4598
|
-
PROVIDER_REFUND_REASON,
|
|
4599
|
-
{
|
|
4600
|
-
idempotencyKey: key,
|
|
4601
|
-
currency: currency2
|
|
4602
|
-
}
|
|
4603
|
-
);
|
|
4604
|
-
const settlement = settlementOf(answer, { amountMinor: paid.amountMinor, currency: currency2 });
|
|
4605
|
-
if (settlement.mismatch) {
|
|
4606
|
-
logger.error(
|
|
4607
|
-
{ ...context, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
4608
|
-
"provider refund answer differs from the capture; left pending"
|
|
4609
|
-
);
|
|
4610
|
-
}
|
|
4611
|
-
return settlement;
|
|
4612
|
-
} catch (err) {
|
|
4613
|
-
if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
|
|
4614
|
-
logger.error({ ...context, err }, "provider refused the refund of a capture");
|
|
4615
|
-
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
4616
|
-
}
|
|
4617
|
-
logger.error(
|
|
4618
|
-
{ ...context, err },
|
|
4619
|
-
"capture refund outcome unknown; left pending until reconciled"
|
|
4620
|
-
);
|
|
4621
|
-
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
4622
|
-
}
|
|
4623
|
-
}
|
|
4624
|
-
async function refundCancelledCapture(paymentIntentId, paid, order) {
|
|
4625
|
-
const refundId = uuidv5(`cancelled-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
4626
|
-
const held = await store.transaction(async (tx) => {
|
|
4627
|
-
audit.note("payment.refundCapture", [{ type: "order", id: order.id }]);
|
|
4628
|
-
const locked = await repos.order.lock(tx, order.id);
|
|
4629
|
-
if (locked === null || locked.capturedMinor > 0) return false;
|
|
4630
|
-
const now = /* @__PURE__ */ new Date();
|
|
4631
|
-
await repos.order.recordCapture(tx, order.id, {
|
|
4632
|
-
amountMinor: paid.amountMinor,
|
|
4633
|
-
method: "provider",
|
|
4634
|
-
at: now
|
|
4635
|
-
});
|
|
4636
|
-
await repos.orderRefund.insert(tx, {
|
|
4637
|
-
id: refundId,
|
|
4638
|
-
orderId: order.id,
|
|
4639
|
-
amountMinor: paid.amountMinor,
|
|
4640
|
-
currency: order.currency,
|
|
4641
|
-
providerRefundId: null,
|
|
4642
|
-
status: "pending",
|
|
4643
|
-
reason: "captured for a cancelled order",
|
|
4644
|
-
actor: "system:checkout",
|
|
4645
|
-
createdAt: now
|
|
4646
|
-
});
|
|
4647
|
-
return true;
|
|
4648
|
-
});
|
|
4649
|
-
if (!held) return;
|
|
4650
|
-
const settlement = await refundCapture(paymentIntentId, paid, order.currency, refundId, {
|
|
4651
|
-
orderId: order.id,
|
|
4652
|
-
refundId
|
|
4653
|
-
});
|
|
4654
|
-
if (settlement.status === "pending") return;
|
|
4655
|
-
await store.transaction(async (tx) => {
|
|
4656
|
-
await repos.order.lock(tx, order.id);
|
|
4657
|
-
await repos.orderRefund.settle(tx, refundId, {
|
|
4658
|
-
status: settlement.status,
|
|
4659
|
-
providerRefundId: settlement.providerRefundId
|
|
4660
|
-
});
|
|
4661
|
-
await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
|
|
4662
|
-
if (settlement.status === "succeeded") {
|
|
4663
|
-
await publisher.publish(EVT_PAYMENT_REFUNDED2, {
|
|
4664
|
-
paymentId: paymentIntentId,
|
|
4665
|
-
orderId: order.id,
|
|
4666
|
-
refundId,
|
|
4667
|
-
amountMinor: paid.amountMinor,
|
|
4668
|
-
currency: order.currency
|
|
4669
|
-
});
|
|
4670
|
-
}
|
|
4671
|
-
});
|
|
4672
|
-
}
|
|
4673
|
-
async function refundDuplicateCapture(tx, paymentIntentId, paid, order) {
|
|
4674
|
-
if (await repos.processedEvent.seen(tx, DUPLICATE_CAPTURE_HANDLER, paymentIntentId)) {
|
|
4675
|
-
return { orderNumber: order.orderNumber, finalized: false, reason: DUPLICATE_CAPTURE };
|
|
4676
|
-
}
|
|
4677
|
-
const key = uuidv5(`duplicate-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
4678
|
-
const settlement = await refundCapture(
|
|
4679
|
-
paymentIntentId,
|
|
4680
|
-
paid,
|
|
4681
|
-
paid.currency.toUpperCase(),
|
|
4682
|
-
key,
|
|
4683
|
-
{
|
|
4684
|
-
orderId: order.id,
|
|
4685
|
-
idempotencyKey: key
|
|
4686
|
-
}
|
|
4687
|
-
);
|
|
4688
|
-
if (settlement.status === "pending" && !settlement.mismatch) {
|
|
4689
|
-
throw new CheckoutError(
|
|
4690
|
-
"finalize_failed",
|
|
4691
|
-
`The refund of a second capture of order ${order.orderNumber} has no known outcome`,
|
|
4692
|
-
{ context: { orderNumber: order.orderNumber } }
|
|
4693
|
-
);
|
|
4694
|
-
}
|
|
4695
|
-
await repos.processedEvent.markProcessed(
|
|
4696
|
-
tx,
|
|
4697
|
-
DUPLICATE_CAPTURE_HANDLER,
|
|
4698
|
-
paymentIntentId,
|
|
4699
|
-
/* @__PURE__ */ new Date()
|
|
4700
|
-
);
|
|
4701
|
-
const reason = settlement.status === "succeeded" ? DUPLICATE_CAPTURE : `duplicate_capture_refund_${settlement.status}`;
|
|
4702
|
-
return recordOutcome(
|
|
4703
|
-
tx,
|
|
4704
|
-
paymentIntentId,
|
|
4705
|
-
order,
|
|
4706
|
-
reason,
|
|
4707
|
-
`capture of ${formatMoney(paid.amountMinor, paid.currency)}`
|
|
4708
|
-
);
|
|
4709
|
-
}
|
|
4710
|
-
async function confirm(tx, paymentIntentId, paid, order, capture) {
|
|
4711
|
-
const metadata = order.metadata;
|
|
4712
|
-
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
4713
|
-
audit.note("order.confirm", [{ type: "order", id: order.id }]);
|
|
4714
|
-
for (const [index, reservationId] of reservationIds.entries()) {
|
|
4715
|
-
const reservation = await reservationFor(tx, order, reservationId, index);
|
|
4716
|
-
await inventory.commitReservation(reservation, FINALIZE_ACTOR);
|
|
4717
|
-
}
|
|
4718
|
-
const now = /* @__PURE__ */ new Date();
|
|
4719
|
-
if (!await repos.order.setStatusIf(tx, order.id, "pending", "confirmed", now)) {
|
|
4720
|
-
throw new NoLongerPending();
|
|
4721
|
-
}
|
|
4722
|
-
await repos.order.recordCapture(tx, order.id, {
|
|
4723
|
-
amountMinor: paid.amountMinor,
|
|
4724
|
-
method: capture.method,
|
|
4725
|
-
at: now
|
|
4726
|
-
});
|
|
4727
|
-
await repos.orderHistory.append(tx, {
|
|
4728
|
-
id: uuidv710(),
|
|
4729
|
-
orderId: order.id,
|
|
4730
|
-
fromStatus: "pending",
|
|
4731
|
-
toStatus: "confirmed",
|
|
4732
|
-
actor: capture.actor,
|
|
4733
|
-
note: capture.note,
|
|
4734
|
-
timestamp: now
|
|
4735
|
-
});
|
|
4736
|
-
if (order.customerId) {
|
|
4737
|
-
await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
|
|
4738
|
-
}
|
|
4739
|
-
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
4740
|
-
paymentId: paymentIntentId,
|
|
4741
|
-
orderId: order.id,
|
|
4742
|
-
amountMinor: paid.amountMinor,
|
|
4743
|
-
currency: order.currency
|
|
4744
|
-
});
|
|
4745
|
-
await publisher.publish(EVT_ORDER_PAID4, {
|
|
4746
|
-
orderId: order.id,
|
|
4747
|
-
paymentIntentId,
|
|
4748
|
-
amountMinor: paid.amountMinor,
|
|
4749
|
-
currency: order.currency
|
|
4750
|
-
});
|
|
4751
|
-
const cartToken = metadata.cartToken;
|
|
4752
|
-
if (cartToken) {
|
|
4753
|
-
if (await repos.cart.clearIfLive(tx, cartToken, now)) {
|
|
4754
|
-
await publisher.publish(EVT_CART_UPDATED2, {
|
|
4755
|
-
cartId: cartToken,
|
|
4756
|
-
itemCount: 0,
|
|
4757
|
-
totalMinor: 0
|
|
4758
|
-
});
|
|
4759
|
-
}
|
|
4760
|
-
await publisher.publish(EVT_CART_CONVERTED, {
|
|
4761
|
-
cartId: cartToken,
|
|
4762
|
-
orderId: order.id
|
|
4763
|
-
});
|
|
4764
|
-
}
|
|
4765
|
-
logger.info({ orderId: order.id, orderNumber: order.orderNumber }, "checkout finalized");
|
|
4766
|
-
return { orderNumber: order.orderNumber, finalized: true };
|
|
4767
|
-
}
|
|
4768
|
-
async function cancelDraft(orderId, reason) {
|
|
4769
|
-
await store.transaction(async (tx) => {
|
|
4770
|
-
const order = await repos.order.findById(tx, orderId);
|
|
4771
|
-
if (!order) throw new NotFoundError7("order", orderId);
|
|
4772
|
-
const metadata = order.metadata;
|
|
4773
|
-
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
4774
|
-
for (const rid of reservationIds) {
|
|
4775
|
-
await inventory.releaseReservation(rid, "cancelled");
|
|
4776
|
-
}
|
|
4777
|
-
await orders4.cancel(orderId, reason, CANCEL_ACTOR);
|
|
4778
|
-
});
|
|
4779
|
-
}
|
|
4780
|
-
async function checkStock(tx, cartDoc) {
|
|
4781
|
-
for (const item of cartDoc.items) {
|
|
4782
|
-
const v = await repos.variant.findById(tx, item.variantId);
|
|
4783
|
-
if (!v) {
|
|
4784
|
-
throw new CheckoutError("variant_missing", `Variant missing: ${item.variantId}`);
|
|
4785
|
-
}
|
|
4786
|
-
if (v.stock < item.qty) {
|
|
4787
|
-
throw new CheckoutError(
|
|
4788
|
-
"out_of_stock",
|
|
4789
|
-
`Insufficient stock for ${item.variantName}: available ${v.stock}, requested ${item.qty}`
|
|
4790
|
-
);
|
|
4791
|
-
}
|
|
4792
|
-
}
|
|
4793
|
-
}
|
|
4794
|
-
async function place(tx, input, closed) {
|
|
4795
|
-
const cartDoc = await repos.cart.lock(tx, input.cartToken);
|
|
4796
|
-
if (cartDoc === null) throw new NotFoundError7("cart", input.cartToken);
|
|
4797
|
-
if (!cartDoc.items.length) throw await cartEmpty(input.cartToken);
|
|
4798
|
-
const pending = await repos.order.findPendingByCartToken(tx, input.cartToken);
|
|
4799
|
-
if (pending !== null) {
|
|
4800
|
-
const { paymentIntentId } = pending;
|
|
4801
|
-
if (paymentIntentId === null) {
|
|
4802
|
-
if (Date.now() - Date.parse(pending.createdAt) <= ABANDON_AFTER_MS) {
|
|
4803
|
-
throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
|
|
4804
|
-
}
|
|
4805
|
-
await cancelDraft(pending.id, "abandoned: no payment intent");
|
|
4806
|
-
} else {
|
|
4807
|
-
const reason = closed.get(paymentIntentId);
|
|
4808
|
-
if (reason === void 0) {
|
|
4809
|
-
if (sameLines(pending, cartDoc))
|
|
4810
|
-
return { kind: "existing", order: { ...pending, paymentIntentId } };
|
|
4811
|
-
return { kind: "cancel-first", order: { ...pending, paymentIntentId } };
|
|
4812
|
-
}
|
|
4813
|
-
await cancelDraft(pending.id, reason);
|
|
4814
|
-
}
|
|
4815
|
-
}
|
|
4816
|
-
await checkStock(tx, cartDoc);
|
|
4817
|
-
const lineItems = cartDoc.items.map((item) => ({
|
|
4818
|
-
variantId: item.variantId,
|
|
4819
|
-
productId: item.productId,
|
|
4820
|
-
productName: item.productName,
|
|
4821
|
-
variantName: item.variantName,
|
|
4822
|
-
sku: "",
|
|
4823
|
-
qty: item.qty,
|
|
4824
|
-
unitPriceMinor: item.priceMinor,
|
|
4825
|
-
lineSubtotalMinor: item.priceMinor * item.qty,
|
|
4826
|
-
lineTaxMinor: 0,
|
|
4827
|
-
lineTotalMinor: item.priceMinor * item.qty,
|
|
4828
|
-
imageUrl: item.imageUrl
|
|
4829
|
-
}));
|
|
4830
|
-
const orderId = uuidv710();
|
|
4831
|
-
audit.note("checkout.place", [{ type: "order", id: orderId }]);
|
|
4832
|
-
const correlationId = currentCorrelationId();
|
|
4833
|
-
const reservationIds = [];
|
|
4834
|
-
for (const item of cartDoc.items) {
|
|
4835
|
-
try {
|
|
4836
|
-
const r = await inventory.reserveStock(item.variantId, item.qty, orderId);
|
|
4837
|
-
reservationIds.push(r.reservationId);
|
|
4838
|
-
} catch (err) {
|
|
4839
|
-
if (err instanceof CheckoutError) throw err;
|
|
4840
|
-
throw new CheckoutError("reservation_failed", "Inventory reservation failed", {
|
|
4841
|
-
cause: err
|
|
4842
|
-
});
|
|
4843
|
-
}
|
|
4844
|
-
}
|
|
4845
|
-
const order = await orders4.createFromCheckout({
|
|
4846
|
-
orderId,
|
|
4847
|
-
customerId: input.customerId ?? null,
|
|
4848
|
-
email: input.email,
|
|
4849
|
-
billingAddress: input.billingAddress,
|
|
4850
|
-
shippingAddress: input.shippingAddress,
|
|
4851
|
-
lineItems,
|
|
4852
|
-
subtotalMinor: cartDoc.subtotalMinor,
|
|
4853
|
-
taxTotalMinor: 0,
|
|
4854
|
-
shippingTotalMinor: 0,
|
|
4855
|
-
discountTotalMinor: 0,
|
|
4856
|
-
totalMinor: cartDoc.subtotalMinor,
|
|
4857
|
-
currency: cartDoc.currency,
|
|
4858
|
-
...input.notes !== void 0 && { notes: input.notes },
|
|
4859
|
-
metadata: {
|
|
4860
|
-
cartToken: cartDoc.token,
|
|
4861
|
-
reservationIds,
|
|
4862
|
-
...correlationId !== void 0 && { correlationId }
|
|
4863
|
-
},
|
|
4864
|
-
cartToken: cartDoc.token
|
|
4865
|
-
});
|
|
4866
|
-
return { kind: "placed", order };
|
|
4867
|
-
}
|
|
4868
|
-
async function answerExisting(order) {
|
|
4869
|
-
const paymentIntent = await payments.getPaymentIntent(order.paymentIntentId);
|
|
4870
|
-
if (outcomeOf(paymentIntent.status) === "failed") {
|
|
4871
|
-
return { closed: `payment_${paymentIntent.status}` };
|
|
4872
|
-
}
|
|
4873
|
-
return {
|
|
4874
|
-
orderId: order.id,
|
|
4875
|
-
orderNumber: order.orderNumber,
|
|
4876
|
-
paymentIntent,
|
|
4877
|
-
currency: order.currency,
|
|
4878
|
-
totalMinor: order.totalMinor,
|
|
4879
|
-
orderStatus: order.status,
|
|
4880
|
-
payment: { status: "requires_action" }
|
|
4881
|
-
};
|
|
4882
|
-
}
|
|
4883
|
-
async function cancelIntent(order) {
|
|
4884
|
-
try {
|
|
4885
|
-
await payments.cancelPaymentIntent(order.paymentIntentId);
|
|
4886
|
-
} catch (err) {
|
|
4887
|
-
if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
|
|
4888
|
-
throw new CheckoutError(
|
|
4889
|
-
"payment_in_progress",
|
|
4890
|
-
`The payment for order ${order.orderNumber} is already under way`,
|
|
4891
|
-
{ cause: err, context: { orderNumber: order.orderNumber } }
|
|
4892
|
-
);
|
|
4893
|
-
}
|
|
4894
|
-
}
|
|
4895
|
-
async function pay(input, order) {
|
|
4896
|
-
const params = {
|
|
4897
|
-
amountMinor: order.totalMinor,
|
|
4898
|
-
currency: order.currency,
|
|
4899
|
-
orderRef: order.id,
|
|
4900
|
-
receiptEmail: input.email,
|
|
4901
|
-
metadata: { orderId: order.id, orderNumber: order.orderNumber }
|
|
4902
|
-
};
|
|
4903
|
-
if (input.customerId != null) params.customerId = input.customerId;
|
|
4904
|
-
let intent;
|
|
4905
|
-
try {
|
|
4906
|
-
intent = await payments.createPaymentIntent(params);
|
|
4907
|
-
} catch (err) {
|
|
4908
|
-
await cancelDraft(order.id, "payment intent not created");
|
|
4909
|
-
throw err;
|
|
4910
|
-
}
|
|
4911
|
-
let unconfirmed = null;
|
|
4912
|
-
const answer = await store.transaction(async (tx) => {
|
|
4913
|
-
await repos.cart.lock(tx, input.cartToken);
|
|
4914
|
-
await repos.order.setPaymentIntent(tx, order.id, intent.id, /* @__PURE__ */ new Date());
|
|
4915
|
-
await publisher.publish(EVT_PAYMENT_INTENT_CREATED2, {
|
|
4916
|
-
paymentId: intent.id,
|
|
4917
|
-
orderId: order.id
|
|
4918
|
-
});
|
|
4919
|
-
let payment;
|
|
4920
|
-
const outcome = outcomeOf(intent.status);
|
|
4921
|
-
if (outcome === "succeeded") {
|
|
4922
|
-
const done = await finalize(intent.id, {
|
|
4923
|
-
amountMinor: intent.amountMinor,
|
|
4924
|
-
currency: intent.currency
|
|
4925
|
-
});
|
|
4926
|
-
if (!done.finalized) unconfirmed = done.reason ?? "not_confirmed";
|
|
4927
|
-
payment = unconfirmed === null ? { status: "succeeded" } : { status: "failed", reason: unconfirmed };
|
|
4928
|
-
} else if (outcome === "failed") {
|
|
4929
|
-
const reason = `payment_${intent.status}`;
|
|
4930
|
-
await cancelDraft(order.id, reason);
|
|
4931
|
-
await publisher.publish(EVT_PAYMENT_FAILED2, {
|
|
4932
|
-
paymentId: intent.id,
|
|
4933
|
-
orderId: order.id,
|
|
4934
|
-
reason
|
|
4935
|
-
});
|
|
4936
|
-
payment = { status: "failed", reason };
|
|
4937
|
-
} else {
|
|
4938
|
-
payment = { status: "requires_action" };
|
|
4939
|
-
}
|
|
4940
|
-
const current = await repos.order.findById(tx, order.id);
|
|
4941
|
-
logger.info(
|
|
4942
|
-
{ orderId: order.id, orderNumber: order.orderNumber, payment: payment.status },
|
|
4943
|
-
"checkout started"
|
|
4944
|
-
);
|
|
4945
|
-
return {
|
|
4946
|
-
orderId: order.id,
|
|
4947
|
-
orderNumber: order.orderNumber,
|
|
4948
|
-
paymentIntent: intent,
|
|
4949
|
-
currency: order.currency,
|
|
4950
|
-
totalMinor: order.totalMinor,
|
|
4951
|
-
orderStatus: current?.status ?? order.status,
|
|
4952
|
-
payment
|
|
4953
|
-
};
|
|
4954
|
-
});
|
|
4955
|
-
if (unconfirmed !== null && answer.orderStatus === "pending") {
|
|
4956
|
-
await cancelDraft(order.id, unconfirmed);
|
|
4957
|
-
await refundCancelledCapture(
|
|
4958
|
-
intent.id,
|
|
4959
|
-
{ amountMinor: intent.amountMinor, currency: intent.currency },
|
|
4960
|
-
order
|
|
4961
|
-
);
|
|
4962
|
-
return { ...answer, orderStatus: "cancelled" };
|
|
4963
|
-
}
|
|
4964
|
-
return answer;
|
|
4965
|
-
}
|
|
4966
|
-
async function finalize(paymentIntentId, paid) {
|
|
4967
|
-
return store.transaction(async (tx) => {
|
|
4968
|
-
const order = await repos.order.findByPaymentIntentId(tx, paymentIntentId);
|
|
4969
|
-
return inOrderScope(order, () => finalizeLoaded(tx, paymentIntentId, paid, order));
|
|
4970
|
-
});
|
|
4971
|
-
}
|
|
4972
|
-
async function finalizeLoaded(tx, paymentIntentId, paid, order) {
|
|
4973
|
-
const outcome = (order2, reason) => recordOutcome(tx, paymentIntentId, order2, reason);
|
|
4974
|
-
if (order === null || order.status !== "pending") {
|
|
4975
|
-
return settled(tx, paymentIntentId, order, paid);
|
|
4976
|
-
}
|
|
4977
|
-
if (paid.amountMinor !== order.totalMinor || paid.currency.toUpperCase() !== order.currency.toUpperCase()) {
|
|
4978
|
-
return outcome(
|
|
4979
|
-
order,
|
|
4980
|
-
`amount_mismatch: paid ${paid.amountMinor} ${paid.currency.toUpperCase()}, due ${order.totalMinor} ${order.currency.toUpperCase()}`
|
|
4981
|
-
);
|
|
4982
|
-
}
|
|
4983
|
-
try {
|
|
4984
|
-
return await store.savepoint(
|
|
4985
|
-
() => confirm(tx, paymentIntentId, paid, order, PROVIDER_CAPTURE)
|
|
4986
|
-
);
|
|
4987
|
-
} catch (err) {
|
|
4988
|
-
if (err instanceof StockUnavailable) {
|
|
4989
|
-
const current = await repos.order.findById(tx, order.id);
|
|
4990
|
-
if (current?.status !== "pending") return settled(tx, paymentIntentId, current, paid);
|
|
4991
|
-
return outcome(current, `stock_unavailable: ${err.variantId}`);
|
|
4992
|
-
}
|
|
4993
|
-
if (!(err instanceof NoLongerPending)) throw err;
|
|
4994
|
-
}
|
|
4995
|
-
return settled(tx, paymentIntentId, await repos.order.findById(tx, order.id), paid);
|
|
4996
|
-
}
|
|
4997
|
-
return {
|
|
4998
|
-
async beginCheckout(input) {
|
|
4999
|
-
audit.note("checkout.place");
|
|
5000
|
-
await loadValidCart(input.cartToken);
|
|
5001
|
-
const closed = /* @__PURE__ */ new Map();
|
|
5002
|
-
for (let attempt = 0; ; attempt += 1) {
|
|
5003
|
-
const placement = await store.transaction((tx) => place(tx, input, closed));
|
|
5004
|
-
if (placement.kind === "placed") return pay(input, placement.order);
|
|
5005
|
-
if (placement.kind === "existing") {
|
|
5006
|
-
const answer = await answerExisting(placement.order);
|
|
5007
|
-
if (!("closed" in answer)) return answer;
|
|
5008
|
-
closed.set(placement.order.paymentIntentId, answer.closed);
|
|
5009
|
-
continue;
|
|
5010
|
-
}
|
|
5011
|
-
if (attempt === SUPERSEDE_ATTEMPTS) {
|
|
5012
|
-
throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
|
|
5013
|
-
}
|
|
5014
|
-
await cancelIntent(placement.order);
|
|
5015
|
-
closed.set(placement.order.paymentIntentId, "superseded: the cart changed");
|
|
5016
|
-
}
|
|
5017
|
-
},
|
|
5018
|
-
finalize,
|
|
5019
|
-
async cancel(orderId, reason) {
|
|
5020
|
-
await cancelDraft(orderId, reason);
|
|
5021
|
-
},
|
|
5022
|
-
async markPaid(orderId, actor, note) {
|
|
5023
|
-
audit.note("order.markPaid", [{ type: "order", id: orderId }]);
|
|
5024
|
-
const found = await store.read((tx) => repos.order.findById(tx, orderId));
|
|
5025
|
-
if (!found) throw new NotFoundError7("order", orderId);
|
|
5026
|
-
if (found.status !== "pending") {
|
|
5027
|
-
throw new StatusTransitionError2("order", found.status, "confirmed");
|
|
5028
|
-
}
|
|
5029
|
-
if (found.paymentIntentId) {
|
|
5030
|
-
try {
|
|
5031
|
-
await payments.cancelPaymentIntent(found.paymentIntentId);
|
|
5032
|
-
} catch (err) {
|
|
5033
|
-
if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
|
|
5034
|
-
throw new OrderConflictError2(
|
|
5035
|
-
"order.payment_in_progress",
|
|
5036
|
-
`The payment for order ${found.orderNumber} is under way with the provider`,
|
|
5037
|
-
{ cause: err, context: { orderNumber: found.orderNumber } }
|
|
5038
|
-
);
|
|
5039
|
-
}
|
|
5040
|
-
}
|
|
5041
|
-
return store.transaction(async (tx) => {
|
|
5042
|
-
const order = await repos.order.lock(tx, orderId);
|
|
5043
|
-
if (!order) throw new NotFoundError7("order", orderId);
|
|
5044
|
-
if (order.status !== "pending") {
|
|
5045
|
-
throw new StatusTransitionError2("order", order.status, "confirmed");
|
|
5046
|
-
}
|
|
5047
|
-
const capture = {
|
|
5048
|
-
method: "manual",
|
|
5049
|
-
actor,
|
|
5050
|
-
note: note ? `payment recorded manually: ${note}` : "payment recorded manually"
|
|
5051
|
-
};
|
|
5052
|
-
const paid = { amountMinor: order.totalMinor, currency: order.currency };
|
|
5053
|
-
try {
|
|
5054
|
-
await inOrderScope(order, () => confirm(tx, "", paid, order, capture));
|
|
5055
|
-
} catch (err) {
|
|
5056
|
-
if (!(err instanceof StockUnavailable)) throw err;
|
|
5057
|
-
throw new OrderConflictError2(
|
|
5058
|
-
"order.stock_unavailable",
|
|
5059
|
-
`The stock order ${order.orderNumber} held has gone to another order`,
|
|
5060
|
-
{ context: { variantId: err.variantId } }
|
|
5061
|
-
);
|
|
5062
|
-
}
|
|
5063
|
-
return await repos.order.findById(tx, order.id);
|
|
5064
|
-
});
|
|
5065
|
-
}
|
|
5066
|
-
};
|
|
5067
|
-
}
|
|
5068
|
-
|
|
5069
|
-
// src/services/search-service.ts
|
|
5070
|
-
function createSearchService(deps) {
|
|
5071
|
-
return {
|
|
5072
|
-
async products(query, params) {
|
|
5073
|
-
return deps.adapter.search(query, params);
|
|
5074
|
-
}
|
|
5075
|
-
};
|
|
5076
|
-
}
|
|
5077
|
-
|
|
5078
|
-
// src/services/index.ts
|
|
5079
|
-
function buildServices(deps) {
|
|
5080
|
-
const { config, store, repos, publisher, logger, payments, searchAdapter } = deps;
|
|
5081
|
-
const inventory = createInventoryService({
|
|
5082
|
-
store,
|
|
5083
|
-
repos,
|
|
5084
|
-
publisher,
|
|
5085
|
-
logger: logger.child({ service: "inventory" })
|
|
5086
|
-
});
|
|
5087
|
-
const orders4 = createOrderService({
|
|
5088
|
-
store,
|
|
5089
|
-
repos,
|
|
5090
|
-
publisher,
|
|
5091
|
-
logger: logger.child({ service: "order" }),
|
|
5092
|
-
orderNumberPrefix: config.commerce.orders.numberPrefix,
|
|
5093
|
-
orderNumberStart: config.commerce.orders.numberStart
|
|
5094
|
-
});
|
|
5095
|
-
const cart = createCartService({
|
|
5096
|
-
store,
|
|
5097
|
-
carts: repos.cart,
|
|
5098
|
-
publisher,
|
|
5099
|
-
logger: logger.child({ service: "cart" }),
|
|
5100
|
-
currency: config.store.currency
|
|
5101
|
-
});
|
|
5102
|
-
const checkout = createCheckoutService({
|
|
5103
|
-
store,
|
|
5104
|
-
repos,
|
|
5105
|
-
publisher,
|
|
5106
|
-
logger: logger.child({ service: "checkout" }),
|
|
5107
|
-
cart,
|
|
5108
|
-
orders: orders4,
|
|
5109
|
-
inventory,
|
|
5110
|
-
payments,
|
|
5111
|
-
currency: config.store.currency
|
|
5112
|
-
});
|
|
5113
|
-
return {
|
|
5114
|
-
product: createProductService({
|
|
5115
|
-
store,
|
|
5116
|
-
repos,
|
|
5117
|
-
publisher,
|
|
5118
|
-
logger: logger.child({ service: "product" })
|
|
5119
|
-
}),
|
|
5120
|
-
category: createCategoryService({
|
|
5121
|
-
repos,
|
|
5122
|
-
publisher,
|
|
5123
|
-
logger: logger.child({ service: "category" })
|
|
5124
|
-
}),
|
|
5125
|
-
cart,
|
|
5126
|
-
customer: createCustomerService({
|
|
5127
|
-
repos,
|
|
5128
|
-
publisher,
|
|
5129
|
-
logger: logger.child({ service: "customer" })
|
|
5130
|
-
}),
|
|
5131
|
-
auth: createAuthService({
|
|
5132
|
-
repos,
|
|
5133
|
-
publisher,
|
|
5134
|
-
logger: logger.child({ service: "auth" }),
|
|
5135
|
-
jwtSecret: config.security.auth.jwtSecret,
|
|
5136
|
-
accessTtl: config.security.auth.accessTtl,
|
|
5137
|
-
refreshTtl: config.security.auth.refreshTtl
|
|
5138
|
-
}),
|
|
5139
|
-
order: orders4,
|
|
5140
|
-
inventory,
|
|
5141
|
-
checkout,
|
|
5142
|
-
refund: createRefundService({
|
|
5143
|
-
store,
|
|
5144
|
-
repos,
|
|
5145
|
-
publisher,
|
|
5146
|
-
logger: logger.child({ service: "refund" }),
|
|
5147
|
-
payments
|
|
5148
|
-
}),
|
|
5149
|
-
search: createSearchService({
|
|
5150
|
-
adapter: searchAdapter,
|
|
5151
|
-
logger: logger.child({ service: "search" })
|
|
5152
|
-
})
|
|
5153
|
-
};
|
|
5154
|
-
}
|
|
5155
|
-
|
|
5156
|
-
// src/read-models/index.ts
|
|
5157
|
-
import { errorText } from "@nymbalhq/types";
|
|
5158
|
-
|
|
5159
|
-
// src/read-models/catalogue.ts
|
|
5160
|
-
function snapshotsOf({ repos }) {
|
|
5161
|
-
return async (tx, page) => {
|
|
5162
|
-
const out = [];
|
|
5163
|
-
for (const p of await repos.product.listPage(tx, page)) {
|
|
5164
|
-
out.push(await productSnapshot(tx, repos, p));
|
|
5165
|
-
}
|
|
5166
|
-
return out;
|
|
5167
|
-
};
|
|
5168
|
-
}
|
|
5169
|
-
var catalogue = {
|
|
5170
|
-
name: "catalogue",
|
|
5171
|
-
target: "documents",
|
|
5172
|
-
collections: [CATEGORIES, PRODUCTS, PRODUCTS_BY_CATEGORY],
|
|
5173
|
-
async *rebuild(ctx) {
|
|
5174
|
-
const { config, repos, logger } = ctx.deps;
|
|
5175
|
-
const storeId = config.store.name;
|
|
5176
|
-
const categories3 = /* @__PURE__ */ new Map();
|
|
5177
|
-
for await (const page of ctx.pages("categories", (tx, p) => repos.category.listPage(tx, p))) {
|
|
5178
|
-
for (const c of page) {
|
|
5179
|
-
categories3.set(c.id, c);
|
|
5180
|
-
yield { collection: CATEGORIES, key: c.slug, doc: buildCategoryDoc(c, storeId) };
|
|
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));
|
|
3672
|
+
}
|
|
3673
|
+
return out;
|
|
3674
|
+
};
|
|
3675
|
+
}
|
|
3676
|
+
var catalogue = {
|
|
3677
|
+
name: "catalogue",
|
|
3678
|
+
target: "documents",
|
|
3679
|
+
collections: [CATEGORIES, PRODUCTS, PRODUCTS_BY_CATEGORY],
|
|
3680
|
+
async *rebuild(ctx) {
|
|
3681
|
+
const { config, repos, logger } = ctx.deps;
|
|
3682
|
+
const storeId = config.store.name;
|
|
3683
|
+
const categories3 = /* @__PURE__ */ new Map();
|
|
3684
|
+
for await (const page of ctx.pages("categories", (tx, p) => repos.category.listPage(tx, p))) {
|
|
3685
|
+
for (const c of page) {
|
|
3686
|
+
categories3.set(c.id, c);
|
|
3687
|
+
yield { collection: CATEGORIES, key: c.slug, doc: buildCategoryDoc(c, storeId) };
|
|
5181
3688
|
}
|
|
5182
3689
|
}
|
|
5183
3690
|
const context = { storeId, currency: config.store.currency, logger };
|
|
5184
3691
|
for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
|
|
5185
|
-
for (const
|
|
5186
|
-
yield* productWrites(buildProductDoc(
|
|
3692
|
+
for (const snapshot of page) {
|
|
3693
|
+
yield* productWrites(buildProductDoc(snapshot, categories3, context));
|
|
5187
3694
|
}
|
|
5188
3695
|
}
|
|
5189
3696
|
},
|
|
@@ -5268,8 +3775,8 @@ var search = {
|
|
|
5268
3775
|
collections: [],
|
|
5269
3776
|
async *rebuild(ctx) {
|
|
5270
3777
|
for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
|
|
5271
|
-
for (const
|
|
5272
|
-
const doc = buildSearchDoc(
|
|
3778
|
+
for (const snapshot of page) {
|
|
3779
|
+
const doc = buildSearchDoc(snapshot);
|
|
5273
3780
|
yield { collection: SEARCH_INDEX, key: doc.id, doc };
|
|
5274
3781
|
}
|
|
5275
3782
|
}
|
|
@@ -5280,7 +3787,13 @@ var search = {
|
|
|
5280
3787
|
};
|
|
5281
3788
|
|
|
5282
3789
|
// src/read-models/index.ts
|
|
5283
|
-
var READ_MODELS = [
|
|
3790
|
+
var READ_MODELS = [
|
|
3791
|
+
catalogue,
|
|
3792
|
+
orders3,
|
|
3793
|
+
customers3,
|
|
3794
|
+
search,
|
|
3795
|
+
recentlyViewed
|
|
3796
|
+
];
|
|
5284
3797
|
var READ_MODEL_NAMES = READ_MODELS.map((m) => m.name);
|
|
5285
3798
|
var CATCH_UP_MARGIN_MS = 10 * 6e4;
|
|
5286
3799
|
var DEFAULT_PAGE_SIZE = 200;
|
|
@@ -5311,7 +3824,8 @@ function modelsOf(names) {
|
|
|
5311
3824
|
function contextFor(model, deps) {
|
|
5312
3825
|
const limit = deps.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
5313
3826
|
let page = 0;
|
|
5314
|
-
|
|
3827
|
+
let logReadThrough;
|
|
3828
|
+
const ctx = {
|
|
5315
3829
|
deps,
|
|
5316
3830
|
async *pages(table, read) {
|
|
5317
3831
|
let after;
|
|
@@ -5324,15 +3838,35 @@ function contextFor(model, deps) {
|
|
|
5324
3838
|
if (rows.length < limit) return;
|
|
5325
3839
|
after = rows[rows.length - 1].id;
|
|
5326
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
|
+
}
|
|
5327
3859
|
}
|
|
5328
3860
|
};
|
|
3861
|
+
return { ctx, logReadThrough: () => logReadThrough };
|
|
5329
3862
|
}
|
|
5330
3863
|
async function collect(model, deps) {
|
|
5331
3864
|
const startedAt = Date.now();
|
|
5332
3865
|
const owned = model.target === "search" ? [SEARCH_INDEX] : model.collections;
|
|
5333
3866
|
const writes = new Map(owned.map((c) => [c, /* @__PURE__ */ new Map()]));
|
|
3867
|
+
const { ctx, logReadThrough } = contextFor(model, deps);
|
|
5334
3868
|
try {
|
|
5335
|
-
for await (const w of model.rebuild(
|
|
3869
|
+
for await (const w of model.rebuild(ctx)) {
|
|
5336
3870
|
const into = writes.get(w.collection);
|
|
5337
3871
|
if (into === void 0) throw new Error(`it wrote to ${w.collection}, which it does not own`);
|
|
5338
3872
|
into.set(w.key, w.doc);
|
|
@@ -5340,7 +3874,7 @@ async function collect(model, deps) {
|
|
|
5340
3874
|
} catch (error) {
|
|
5341
3875
|
throw new RebuildError(model.name, error);
|
|
5342
3876
|
}
|
|
5343
|
-
return { model, startedAt, writes };
|
|
3877
|
+
return { model, startedAt, writes, logReadThrough: logReadThrough() };
|
|
5344
3878
|
}
|
|
5345
3879
|
async function* entries(docs) {
|
|
5346
3880
|
yield* docs;
|
|
@@ -5361,11 +3895,10 @@ async function swap({ model, writes }, deps) {
|
|
|
5361
3895
|
await search2.index(docs);
|
|
5362
3896
|
return `${search2.providerName} has no replaceAll: every document was indexed, removals not guaranteed`;
|
|
5363
3897
|
}
|
|
5364
|
-
async function catchUp(model, since, deps) {
|
|
3898
|
+
async function catchUp(model, since, deps, afterSeq = 0) {
|
|
5365
3899
|
const handlers = model.handlers(deps);
|
|
5366
3900
|
const failures = [];
|
|
5367
3901
|
let applied = 0;
|
|
5368
|
-
let afterSeq = 0;
|
|
5369
3902
|
for (; ; ) {
|
|
5370
3903
|
const page = await deps.store.read(
|
|
5371
3904
|
(tx) => deps.repos.eventLog.listForCatchUp(tx, since, { afterSeq, limit: CATCH_UP_PAGE })
|
|
@@ -5401,7 +3934,8 @@ async function rebuild(names, deps) {
|
|
|
5401
3934
|
const { applied, failures } = await catchUp(
|
|
5402
3935
|
c.model,
|
|
5403
3936
|
new Date(c.startedAt - CATCH_UP_MARGIN_MS),
|
|
5404
|
-
deps
|
|
3937
|
+
deps,
|
|
3938
|
+
c.logReadThrough
|
|
5405
3939
|
);
|
|
5406
3940
|
const entry = {
|
|
5407
3941
|
model: c.model.name,
|
|
@@ -5762,7 +4296,8 @@ async function createApp(config, options = {}) {
|
|
|
5762
4296
|
store: platform.commandStore,
|
|
5763
4297
|
eventLog: repos.eventLog,
|
|
5764
4298
|
eventBus: platform.eventBus,
|
|
5765
|
-
logger
|
|
4299
|
+
logger,
|
|
4300
|
+
...options.relay
|
|
5766
4301
|
});
|
|
5767
4302
|
const subscriberBus = deliveringBus(platform.eventBus, relay);
|
|
5768
4303
|
const publisher = createEventPublisher({
|
|
@@ -5784,7 +4319,8 @@ async function createApp(config, options = {}) {
|
|
|
5784
4319
|
publisher,
|
|
5785
4320
|
logger: logger.child({ layer: "service" }),
|
|
5786
4321
|
payments: adapters.payments,
|
|
5787
|
-
searchAdapter: adapters.search
|
|
4322
|
+
searchAdapter: adapters.search,
|
|
4323
|
+
email: adapters.email
|
|
5788
4324
|
});
|
|
5789
4325
|
await registerHandlers({
|
|
5790
4326
|
config,
|
|
@@ -5792,6 +4328,7 @@ async function createApp(config, options = {}) {
|
|
|
5792
4328
|
documentStore: platform.documentStore,
|
|
5793
4329
|
repos,
|
|
5794
4330
|
adapters,
|
|
4331
|
+
alerts: services.alert,
|
|
5795
4332
|
logger
|
|
5796
4333
|
});
|
|
5797
4334
|
await rebuild(READ_MODEL_NAMES, {
|
|
@@ -5834,7 +4371,7 @@ async function createApp(config, options = {}) {
|
|
|
5834
4371
|
relay,
|
|
5835
4372
|
async attachHttp(adapter, options2 = {}) {
|
|
5836
4373
|
await adapters.security.applyMiddleware(adapter, config.security);
|
|
5837
|
-
const { registerAllRoutes: registerAllRoutes2 } = await import("./register-
|
|
4374
|
+
const { registerAllRoutes: registerAllRoutes2 } = await import("./register-N2XGSFUF.js");
|
|
5838
4375
|
registerAllRoutes2({
|
|
5839
4376
|
config,
|
|
5840
4377
|
adapter,
|
|
@@ -5955,26 +4492,6 @@ function compilePathPattern(pattern) {
|
|
|
5955
4492
|
return new RegExp(`^${escaped}$`);
|
|
5956
4493
|
}
|
|
5957
4494
|
|
|
5958
|
-
// src/adapters/ai/native-adapter.ts
|
|
5959
|
-
import { AdapterError as AdapterError3 } from "@nymbalhq/types";
|
|
5960
|
-
function createNativeAiAdapter(_logger) {
|
|
5961
|
-
return {
|
|
5962
|
-
kind: "ai",
|
|
5963
|
-
providerName: "native",
|
|
5964
|
-
capabilities: () => [],
|
|
5965
|
-
producesEvents: [],
|
|
5966
|
-
consumesEvents: [],
|
|
5967
|
-
initialize: noopInitialize,
|
|
5968
|
-
healthCheck: () => okHealth("AI adapter is stubbed \u2014 configure a real provider for v1.0"),
|
|
5969
|
-
async embed() {
|
|
5970
|
-
throw new AdapterError3("not_configured", "AI embedding is not configured in v0.1");
|
|
5971
|
-
},
|
|
5972
|
-
async complete() {
|
|
5973
|
-
throw new AdapterError3("not_configured", "AI completion is not configured in v0.1");
|
|
5974
|
-
}
|
|
5975
|
-
};
|
|
5976
|
-
}
|
|
5977
|
-
|
|
5978
4495
|
// src/diagnose.ts
|
|
5979
4496
|
import { existsSync } from "fs";
|
|
5980
4497
|
import { resolve as resolve3 } from "path";
|
|
@@ -6257,6 +4774,7 @@ async function diagnose(input, options = {}) {
|
|
|
6257
4774
|
primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
|
|
6258
4775
|
}
|
|
6259
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);
|
|
6260
4778
|
for (const close of closers) {
|
|
6261
4779
|
const closed = await within(timeoutMs, close);
|
|
6262
4780
|
if (!closed.ok) logger.debug({ detail: closed.detail }, "diagnose: a connection did not close");
|
|
@@ -6270,22 +4788,47 @@ async function diagnose(input, options = {}) {
|
|
|
6270
4788
|
storeCheck,
|
|
6271
4789
|
migrationsCheck,
|
|
6272
4790
|
...slots,
|
|
6273
|
-
...primitives
|
|
4791
|
+
...primitives,
|
|
4792
|
+
eventsCheck
|
|
6274
4793
|
].map((check) => ({
|
|
6275
4794
|
...check,
|
|
6276
|
-
detail: scrub(secrets.reduce((
|
|
4795
|
+
detail: scrub(secrets.reduce((text2, secret) => text2.split(secret).join("***"), check.detail))
|
|
6277
4796
|
}));
|
|
6278
4797
|
return { checks };
|
|
6279
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
|
+
}
|
|
6280
4823
|
function fromReport(name, what, report) {
|
|
6281
4824
|
return { name, status: report.status, detail: described(what, report.detail) };
|
|
6282
4825
|
}
|
|
6283
4826
|
|
|
6284
4827
|
// src/seed/run.ts
|
|
6285
|
-
import { inArray as
|
|
6286
|
-
import { v7 as
|
|
6287
|
-
import
|
|
6288
|
-
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";
|
|
6289
4832
|
|
|
6290
4833
|
// src/seed/data.ts
|
|
6291
4834
|
var seedCategories = [
|
|
@@ -6335,7 +4878,7 @@ var seedProducts = [
|
|
|
6335
4878
|
{ slug: "accelerate", title: "Accelerate", description: "The science of lean software and DevOps.", priceMinor: 2400, categorySlug: "books", imageUrl: img("accelerate") },
|
|
6336
4879
|
{ slug: "working-effectively-with-legacy-code", title: "Working Effectively with Legacy Code", description: "Michael Feathers on rescuing complex codebases.", priceMinor: 3400, categorySlug: "books", imageUrl: img("legacy-code") }
|
|
6337
4880
|
];
|
|
6338
|
-
var escapeXml = (
|
|
4881
|
+
var escapeXml = (text2) => text2.replace(/[<>&'"]/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
6339
4882
|
function seedImage(product) {
|
|
6340
4883
|
let hash = 0;
|
|
6341
4884
|
for (const char of product.slug) hash = hash * 31 + char.charCodeAt(0) >>> 0;
|
|
@@ -6345,7 +4888,7 @@ function seedImage(product) {
|
|
|
6345
4888
|
}
|
|
6346
4889
|
|
|
6347
4890
|
// src/seed/run.ts
|
|
6348
|
-
var { hashSync } =
|
|
4891
|
+
var { hashSync } = bcrypt;
|
|
6349
4892
|
async function insertVariants(store, rows) {
|
|
6350
4893
|
if (rows.length === 0) return;
|
|
6351
4894
|
const clients = rawClients(store);
|
|
@@ -6402,13 +4945,13 @@ async function demoRowsPresent(store, emails) {
|
|
|
6402
4945
|
const clients = rawClients(store);
|
|
6403
4946
|
if (clients.kind === "sqlite") {
|
|
6404
4947
|
const { categories: categories4, products: products4, customers: customers5 } = sqlite_exports;
|
|
6405
|
-
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;
|
|
6406
4949
|
}
|
|
6407
4950
|
const { categories: categories3, products: products3, customers: customers4 } = postgres_exports;
|
|
6408
4951
|
const [category, product, customer] = await Promise.all([
|
|
6409
|
-
clients.db.select({ id: categories3.id }).from(categories3).where(
|
|
6410
|
-
clients.db.select({ id: products3.id }).from(products3).where(
|
|
6411
|
-
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)
|
|
6412
4955
|
]);
|
|
6413
4956
|
return category.length > 0 || product.length > 0 || customer.length > 0;
|
|
6414
4957
|
}
|
|
@@ -6451,6 +4994,9 @@ async function insertCustomer(store, row) {
|
|
|
6451
4994
|
updatedAt: row.updatedAt
|
|
6452
4995
|
});
|
|
6453
4996
|
}
|
|
4997
|
+
function failedOf2(err) {
|
|
4998
|
+
return err.context?.failed ?? [];
|
|
4999
|
+
}
|
|
6454
5000
|
async function runSeed(deps) {
|
|
6455
5001
|
const { config, commandStore, documentStore, eventBus, logger, version } = deps;
|
|
6456
5002
|
const categoryRepo = createCategoryRepository(commandStore);
|
|
@@ -6469,7 +5015,7 @@ async function runSeed(deps) {
|
|
|
6469
5015
|
}
|
|
6470
5016
|
const now = /* @__PURE__ */ new Date();
|
|
6471
5017
|
const categoryInserts = seedCategories.map((c, i) => ({
|
|
6472
|
-
id:
|
|
5018
|
+
id: uuidv74(),
|
|
6473
5019
|
slug: c.slug,
|
|
6474
5020
|
name: c.name,
|
|
6475
5021
|
description: c.description,
|
|
@@ -6487,7 +5033,7 @@ async function runSeed(deps) {
|
|
|
6487
5033
|
}
|
|
6488
5034
|
}
|
|
6489
5035
|
const productInserts = seedProducts.map((p) => ({
|
|
6490
|
-
id:
|
|
5036
|
+
id: uuidv74(),
|
|
6491
5037
|
slug: p.slug,
|
|
6492
5038
|
name: p.title,
|
|
6493
5039
|
description: p.description,
|
|
@@ -6505,7 +5051,7 @@ async function runSeed(deps) {
|
|
|
6505
5051
|
const variantInserts = productInserts.map((p, i) => {
|
|
6506
5052
|
const seed = seedProducts[i];
|
|
6507
5053
|
return {
|
|
6508
|
-
id:
|
|
5054
|
+
id: uuidv74(),
|
|
6509
5055
|
productId: p.id,
|
|
6510
5056
|
sku: p.slug.toUpperCase().replaceAll("-", "_"),
|
|
6511
5057
|
name: "Default",
|
|
@@ -6525,7 +5071,7 @@ async function runSeed(deps) {
|
|
|
6525
5071
|
});
|
|
6526
5072
|
await insertProductCategories(commandStore, joinRows);
|
|
6527
5073
|
const demoCustomer = {
|
|
6528
|
-
id:
|
|
5074
|
+
id: uuidv74(),
|
|
6529
5075
|
email: demoEmail,
|
|
6530
5076
|
passwordHash: hashSync("nymbal", 10),
|
|
6531
5077
|
firstName: "Demo",
|
|
@@ -6537,7 +5083,7 @@ async function runSeed(deps) {
|
|
|
6537
5083
|
const adminPassword = process.env["NYMBAL_ADMIN_PASSWORD"] ?? "nymbal-admin-dev";
|
|
6538
5084
|
const adminRoles = ["admin"];
|
|
6539
5085
|
const adminCustomer = {
|
|
6540
|
-
id:
|
|
5086
|
+
id: uuidv74(),
|
|
6541
5087
|
email: adminEmail,
|
|
6542
5088
|
passwordHash: hashSync(adminPassword, 10),
|
|
6543
5089
|
firstName: "Admin",
|
|
@@ -6549,7 +5095,7 @@ async function runSeed(deps) {
|
|
|
6549
5095
|
await insertCustomer(commandStore, adminCustomer);
|
|
6550
5096
|
const events3 = [
|
|
6551
5097
|
...categoryInserts.map(
|
|
6552
|
-
(c) => makeEvent(
|
|
5098
|
+
(c) => makeEvent(EVT_CATEGORY_CREATED3, {
|
|
6553
5099
|
category: {
|
|
6554
5100
|
id: c.id,
|
|
6555
5101
|
parentId: c.parentId,
|
|
@@ -6565,7 +5111,7 @@ async function runSeed(deps) {
|
|
|
6565
5111
|
const v = variantInserts[i];
|
|
6566
5112
|
const seed = seedProducts[i];
|
|
6567
5113
|
const cat = categoryBySlug.get(seed.categorySlug);
|
|
6568
|
-
return makeEvent(
|
|
5114
|
+
return makeEvent(EVT_PRODUCT_CREATED3, {
|
|
6569
5115
|
product: {
|
|
6570
5116
|
id: p.id,
|
|
6571
5117
|
slug: p.slug,
|
|
@@ -6602,16 +5148,27 @@ async function runSeed(deps) {
|
|
|
6602
5148
|
}
|
|
6603
5149
|
});
|
|
6604
5150
|
}),
|
|
6605
|
-
makeEvent(
|
|
5151
|
+
makeEvent(EVT_CUSTOMER_CREATED3, {
|
|
6606
5152
|
customerId: demoCustomer.id,
|
|
6607
5153
|
email: demoCustomer.email
|
|
6608
5154
|
}),
|
|
6609
|
-
makeEvent(
|
|
5155
|
+
makeEvent(EVT_CUSTOMER_CREATED3, {
|
|
6610
5156
|
customerId: adminCustomer.id,
|
|
6611
5157
|
email: adminCustomer.email
|
|
6612
5158
|
})
|
|
6613
5159
|
];
|
|
6614
|
-
|
|
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
|
+
}
|
|
6615
5172
|
logger.info({ adminEmail }, "Admin user seeded");
|
|
6616
5173
|
if (!process.env["NYMBAL_ADMIN_EMAIL"]) {
|
|
6617
5174
|
console.log(
|
|
@@ -6708,6 +5265,8 @@ export {
|
|
|
6708
5265
|
buildRepositories,
|
|
6709
5266
|
buildSecurityHeaders,
|
|
6710
5267
|
buildServices,
|
|
5268
|
+
createAlertService,
|
|
5269
|
+
createAlertSubscriptionRepository,
|
|
6711
5270
|
createApp,
|
|
6712
5271
|
createAuditEntryRepository,
|
|
6713
5272
|
createAuthService,
|
|
@@ -6729,7 +5288,6 @@ export {
|
|
|
6729
5288
|
createLocalFsMediaStorage,
|
|
6730
5289
|
createLogger,
|
|
6731
5290
|
createMiddlewareSecurityAdapter,
|
|
6732
|
-
createNativeAiAdapter,
|
|
6733
5291
|
createNativeAnalyticsAdapter,
|
|
6734
5292
|
createNativeEmailAdapter,
|
|
6735
5293
|
createNativeReviewsAdapter,
|
|
@@ -6737,6 +5295,7 @@ export {
|
|
|
6737
5295
|
createNativeShippingAdapter,
|
|
6738
5296
|
createNativeStubPaymentsAdapter,
|
|
6739
5297
|
createNativeTaxAdapter,
|
|
5298
|
+
createOrderAccessKeyRepository,
|
|
6740
5299
|
createOrderHistoryRepository,
|
|
6741
5300
|
createOrderRefundRepository,
|
|
6742
5301
|
createOrderRepository,
|
|
@@ -6747,6 +5306,7 @@ export {
|
|
|
6747
5306
|
createProductCategoryRepository,
|
|
6748
5307
|
createProductRepository2 as createProductRepository,
|
|
6749
5308
|
createProductService,
|
|
5309
|
+
createRecentlyViewedService,
|
|
6750
5310
|
createRefreshTokenRepository,
|
|
6751
5311
|
createRefundService,
|
|
6752
5312
|
createRelay,
|
|
@@ -6760,6 +5320,7 @@ export {
|
|
|
6760
5320
|
decrypt,
|
|
6761
5321
|
diagnose,
|
|
6762
5322
|
diffReadModel,
|
|
5323
|
+
emailDelivers,
|
|
6763
5324
|
encodeSearchCursor,
|
|
6764
5325
|
encrypt,
|
|
6765
5326
|
fillFromSettings,
|
|
@@ -6771,14 +5332,18 @@ export {
|
|
|
6771
5332
|
keyId,
|
|
6772
5333
|
keyProblem,
|
|
6773
5334
|
listAuditEntries,
|
|
5335
|
+
newAlertToken,
|
|
6774
5336
|
newCorrelationId,
|
|
6775
5337
|
openReadModels,
|
|
6776
5338
|
orderPayment,
|
|
5339
|
+
parseDurationToMs,
|
|
6777
5340
|
rawClients,
|
|
6778
5341
|
readSecretsKey,
|
|
6779
5342
|
rebuild,
|
|
6780
5343
|
refreshRefunded,
|
|
6781
5344
|
registerAdminStaticRoute,
|
|
5345
|
+
registerAlertHandler,
|
|
5346
|
+
registerAlertRoutes,
|
|
6782
5347
|
registerAllRoutes,
|
|
6783
5348
|
registerHandlers,
|
|
6784
5349
|
resolvePrimitives,
|