@classytic/cart 0.1.0 → 0.1.2
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/README.md +1 -10
- package/dist/{cart-event-catalog-BIbi2Q_n.d.mts → cart-event-catalog-BxDJhtTM.d.mts} +1 -1
- package/dist/cart.error-BwWy4RlY.mjs +27 -0
- package/dist/{create-cart-q3CXxPP7.mjs → create-cart-B4l61iKT.mjs} +589 -543
- package/dist/domain/errors/index.d.mts +1 -1
- package/dist/domain/errors/index.mjs +5 -3
- package/dist/domain/events/index.d.mts +2 -2
- package/dist/domain/events/index.mjs +2 -2
- package/dist/domain/index.d.mts +11 -11
- package/dist/domain/index.mjs +11 -10
- package/dist/domain/ports/index.d.mts +2 -2
- package/dist/domain/ports/index.mjs +1 -1
- package/dist/domain/saga/index.d.mts +2 -2
- package/dist/domain/saga/index.mjs +2 -3
- package/dist/engine/index.d.mts +1 -1
- package/dist/engine/index.mjs +1 -1
- package/dist/{errors-CHR9RlbY.mjs → errors-DzR7Pipp.mjs} +27 -27
- package/dist/{index-Doi5uzux.d.mts → index-BFBUk6qT.d.mts} +68 -68
- package/dist/index.d.mts +73 -58
- package/dist/index.mjs +50 -49
- package/dist/{internal-event-bus-IkUfQJxn.d.mts → internal-event-bus-DKcDteh-.d.mts} +109 -84
- package/dist/{line-item.entity-B3M_i-pw.d.mts → kind-registry-C1n47C7h.d.mts} +52 -52
- package/dist/{kind-registry-Ba4PO4WC.mjs → kind-registry-C99h_-8t.mjs} +1 -1
- package/dist/{kind.error-CCjTB6kW.mjs → kind.error-DIaJpdUb.mjs} +2 -27
- package/dist/kinds/index.d.mts +1 -1
- package/dist/kinds/index.mjs +1 -1
- package/dist/{line-kind-Bndo6IS8.d.mts → line-kind-Ck3fVXzG.d.mts} +1 -1
- package/dist/{cart-event-catalog-BOP9aDhL.mjs → outbox-store-CWW8ppxS.mjs} +31 -31
- package/dist/{not-found.error-B6WYnAjX.mjs → price-changed.error-C-wGVcfc.mjs} +23 -47
- package/dist/{idempotency-record.entity-DIFXjN1V.d.mts → reservation.entity-b5cZ1ojx.d.mts} +72 -72
- package/dist/{shipping.bridge-DD4A_O0O.d.mts → shipping.bridge-CmQFTgSE.d.mts} +82 -82
- package/dist/state-transition.error-2fRLh3p0.mjs +26 -0
- package/dist/{saga-step-fn-Cyob38iU.d.mts → state-transitions-X_Eix5Iw.d.mts} +31 -30
- package/dist/state-transitions-e4z3Yhxb.mjs +61 -0
- package/dist/{bundle.kind-BdgnyKZt.d.mts → variant.kind-9P1DXdXu.d.mts} +51 -51
- package/dist/{bundle.kind-DFydSxV_.mjs → variant.kind-DfEh2oku.mjs} +133 -133
- package/package.json +14 -7
- package/dist/saga-steps-B27LI7xp.mjs +0 -27
- package/dist/state-transitions-CpJpZZTK.mjs +0 -21
- /package/dist/{cart-status.vo-2iisZGhb.d.mts → cart-status.vo-CNJw4aaB.d.mts} +0 -0
- /package/dist/{domain-event-DHNkz15G.mjs → domain-event-CIEORKF6.mjs} +0 -0
- /package/dist/{id.port-C3rlDAKP.mjs → id.port-BhbFZJPm.mjs} +0 -0
- /package/dist/{id.port-DPXLrqb2.d.mts → id.port-C7ygWLRU.d.mts} +0 -0
- /package/dist/{index-DEHBdV_z.d.mts → index-2Ag-54t8.d.mts} +0 -0
- /package/dist/{outbox-store-CTWz9pvG.d.mts → outbox-store-CBt9fSYh.d.mts} +0 -0
|
@@ -1,14 +1,102 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import { n as CartEvents, t as createCartEvent } from "./domain-event-
|
|
4
|
-
import { n as cryptoIdPort, r as systemClock } from "./id.port-
|
|
5
|
-
import { t as createKindRegistry } from "./kind-registry-
|
|
6
|
-
import {
|
|
1
|
+
import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "./price-changed.error-C-wGVcfc.mjs";
|
|
2
|
+
import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
|
|
3
|
+
import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
|
|
4
|
+
import { n as cryptoIdPort, r as systemClock } from "./id.port-BhbFZJPm.mjs";
|
|
5
|
+
import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
|
|
6
|
+
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-e4z3Yhxb.mjs";
|
|
7
7
|
import { money } from "@classytic/primitives/money";
|
|
8
8
|
import { matchEventPattern } from "@classytic/primitives/events";
|
|
9
9
|
import mongoose, { Schema } from "mongoose";
|
|
10
10
|
import { resolveTenantConfig } from "@classytic/primitives/tenant";
|
|
11
|
-
import { Repository, customIdPlugin, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
|
|
11
|
+
import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
|
|
12
|
+
//#region src/models/checkout.model.ts
|
|
13
|
+
function createCheckoutModel(connection, opts = {}) {
|
|
14
|
+
const schema = new Schema({
|
|
15
|
+
publicId: {
|
|
16
|
+
type: String,
|
|
17
|
+
required: true,
|
|
18
|
+
unique: true
|
|
19
|
+
},
|
|
20
|
+
draftId: {
|
|
21
|
+
type: Schema.Types.ObjectId,
|
|
22
|
+
required: true
|
|
23
|
+
},
|
|
24
|
+
actorRef: {
|
|
25
|
+
type: String,
|
|
26
|
+
required: true
|
|
27
|
+
},
|
|
28
|
+
actorKind: {
|
|
29
|
+
type: String,
|
|
30
|
+
enum: ["user", "session"],
|
|
31
|
+
required: true
|
|
32
|
+
},
|
|
33
|
+
state: {
|
|
34
|
+
type: String,
|
|
35
|
+
enum: [
|
|
36
|
+
"open",
|
|
37
|
+
"finalized",
|
|
38
|
+
"canceled"
|
|
39
|
+
],
|
|
40
|
+
default: "open"
|
|
41
|
+
},
|
|
42
|
+
flowState: {
|
|
43
|
+
type: Schema.Types.Mixed,
|
|
44
|
+
required: true
|
|
45
|
+
},
|
|
46
|
+
lines: {
|
|
47
|
+
type: [{ type: Schema.Types.Mixed }],
|
|
48
|
+
default: []
|
|
49
|
+
},
|
|
50
|
+
adjustments: {
|
|
51
|
+
type: [{ type: Schema.Types.Mixed }],
|
|
52
|
+
default: []
|
|
53
|
+
},
|
|
54
|
+
currency: {
|
|
55
|
+
type: String,
|
|
56
|
+
required: true,
|
|
57
|
+
length: 3
|
|
58
|
+
},
|
|
59
|
+
pricing: {
|
|
60
|
+
type: Schema.Types.Mixed,
|
|
61
|
+
required: true
|
|
62
|
+
},
|
|
63
|
+
externalRef: {
|
|
64
|
+
type: String,
|
|
65
|
+
default: null
|
|
66
|
+
},
|
|
67
|
+
canceledReason: {
|
|
68
|
+
type: String,
|
|
69
|
+
default: null
|
|
70
|
+
},
|
|
71
|
+
version: {
|
|
72
|
+
type: Number,
|
|
73
|
+
default: 0,
|
|
74
|
+
min: 0
|
|
75
|
+
},
|
|
76
|
+
metadata: {
|
|
77
|
+
type: Schema.Types.Mixed,
|
|
78
|
+
default: null
|
|
79
|
+
},
|
|
80
|
+
privateMetadata: {
|
|
81
|
+
type: Schema.Types.Mixed,
|
|
82
|
+
default: null
|
|
83
|
+
}
|
|
84
|
+
}, {
|
|
85
|
+
timestamps: true,
|
|
86
|
+
minimize: false
|
|
87
|
+
});
|
|
88
|
+
schema.index({ draftId: 1 }, {
|
|
89
|
+
unique: true,
|
|
90
|
+
partialFilterExpression: { state: "open" }
|
|
91
|
+
});
|
|
92
|
+
schema.index({
|
|
93
|
+
draftId: 1,
|
|
94
|
+
state: 1
|
|
95
|
+
});
|
|
96
|
+
const collection = (opts.collectionPrefix ?? "") + "cart_checkouts";
|
|
97
|
+
return connection.model("CartCheckout", schema, collection);
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
12
100
|
//#region src/models/draft.model.ts
|
|
13
101
|
const lineDisplaySubSchema = new Schema({
|
|
14
102
|
name: {
|
|
@@ -195,92 +283,127 @@ function createDraftModel(connection, opts = {}) {
|
|
|
195
283
|
return connection.model("CartDraft", schema, collection);
|
|
196
284
|
}
|
|
197
285
|
//#endregion
|
|
198
|
-
//#region src/models/
|
|
199
|
-
function
|
|
286
|
+
//#region src/models/idempotency.model.ts
|
|
287
|
+
function createIdempotencyModel(connection, opts = {}) {
|
|
200
288
|
const schema = new Schema({
|
|
201
|
-
|
|
289
|
+
cartRef: {
|
|
202
290
|
type: String,
|
|
203
|
-
required: true
|
|
204
|
-
unique: true
|
|
291
|
+
required: true
|
|
205
292
|
},
|
|
206
|
-
|
|
207
|
-
type:
|
|
293
|
+
operation: {
|
|
294
|
+
type: String,
|
|
208
295
|
required: true
|
|
209
296
|
},
|
|
210
297
|
actorRef: {
|
|
211
298
|
type: String,
|
|
212
299
|
required: true
|
|
213
300
|
},
|
|
214
|
-
|
|
301
|
+
idempotencyKey: {
|
|
215
302
|
type: String,
|
|
216
|
-
enum: ["user", "session"],
|
|
217
303
|
required: true
|
|
218
304
|
},
|
|
219
|
-
|
|
305
|
+
status: {
|
|
220
306
|
type: String,
|
|
221
307
|
enum: [
|
|
222
|
-
"
|
|
223
|
-
"
|
|
224
|
-
"
|
|
308
|
+
"in_flight",
|
|
309
|
+
"succeeded",
|
|
310
|
+
"failed"
|
|
225
311
|
],
|
|
226
|
-
default: "
|
|
227
|
-
},
|
|
228
|
-
flowState: {
|
|
229
|
-
type: Schema.Types.Mixed,
|
|
230
|
-
required: true
|
|
231
|
-
},
|
|
232
|
-
lines: {
|
|
233
|
-
type: [{ type: Schema.Types.Mixed }],
|
|
234
|
-
default: []
|
|
235
|
-
},
|
|
236
|
-
adjustments: {
|
|
237
|
-
type: [{ type: Schema.Types.Mixed }],
|
|
238
|
-
default: []
|
|
312
|
+
default: "in_flight"
|
|
239
313
|
},
|
|
240
|
-
|
|
314
|
+
resultKind: {
|
|
241
315
|
type: String,
|
|
242
|
-
|
|
243
|
-
|
|
316
|
+
enum: [
|
|
317
|
+
"inline",
|
|
318
|
+
"pointer",
|
|
319
|
+
null
|
|
320
|
+
],
|
|
321
|
+
default: null
|
|
244
322
|
},
|
|
245
|
-
|
|
323
|
+
resultInline: {
|
|
246
324
|
type: Schema.Types.Mixed,
|
|
247
|
-
required: true
|
|
248
|
-
},
|
|
249
|
-
externalRef: {
|
|
250
|
-
type: String,
|
|
251
325
|
default: null
|
|
252
326
|
},
|
|
253
|
-
|
|
254
|
-
type:
|
|
327
|
+
resultPointer: {
|
|
328
|
+
type: Schema.Types.Mixed,
|
|
255
329
|
default: null
|
|
256
330
|
},
|
|
257
|
-
|
|
258
|
-
type: Number,
|
|
259
|
-
default: 0,
|
|
260
|
-
min: 0
|
|
261
|
-
},
|
|
262
|
-
metadata: {
|
|
331
|
+
error: {
|
|
263
332
|
type: Schema.Types.Mixed,
|
|
264
333
|
default: null
|
|
265
334
|
},
|
|
266
|
-
|
|
267
|
-
type:
|
|
335
|
+
leaseToken: {
|
|
336
|
+
type: String,
|
|
337
|
+
required: true
|
|
338
|
+
},
|
|
339
|
+
leaseExpiresAt: {
|
|
340
|
+
type: Date,
|
|
341
|
+
required: true
|
|
342
|
+
},
|
|
343
|
+
completedAt: {
|
|
344
|
+
type: Date,
|
|
268
345
|
default: null
|
|
269
346
|
}
|
|
270
347
|
}, {
|
|
271
|
-
timestamps:
|
|
348
|
+
timestamps: {
|
|
349
|
+
createdAt: true,
|
|
350
|
+
updatedAt: false
|
|
351
|
+
},
|
|
272
352
|
minimize: false
|
|
273
353
|
});
|
|
274
|
-
schema.index({ draftId: 1 }, {
|
|
275
|
-
unique: true,
|
|
276
|
-
partialFilterExpression: { state: "open" }
|
|
277
|
-
});
|
|
278
354
|
schema.index({
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
355
|
+
cartRef: 1,
|
|
356
|
+
operation: 1,
|
|
357
|
+
actorRef: 1,
|
|
358
|
+
idempotencyKey: 1
|
|
359
|
+
}, { unique: true });
|
|
360
|
+
schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
|
|
361
|
+
const collection = (opts.collectionPrefix ?? "") + "cart_idempotency";
|
|
362
|
+
return connection.model("CartIdempotency", schema, collection);
|
|
363
|
+
}
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region src/models/inject-tenant.ts
|
|
366
|
+
/**
|
|
367
|
+
* Mongoose-specific adapter around `resolveTenantConfig()` from
|
|
368
|
+
* `@classytic/primitives/tenant`. The pure resolution lives in primitives
|
|
369
|
+
* (zero runtime deps) — this file only handles the Mongoose schema
|
|
370
|
+
* mutations (add field, prepend tenant to indexes) that primitives can't
|
|
371
|
+
* own without a mongoose dependency.
|
|
372
|
+
*/
|
|
373
|
+
function resolveCartTenant(input = {}) {
|
|
374
|
+
if (typeof input === "boolean" || input === void 0) return resolveTenantConfig(input);
|
|
375
|
+
if ("tenantFieldType" in input || "multiTenant" in input) {
|
|
376
|
+
const legacy = input;
|
|
377
|
+
return resolveTenantConfig({
|
|
378
|
+
enabled: legacy.multiTenant !== false,
|
|
379
|
+
fieldType: legacy.tenantFieldType ?? "objectId"
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
return resolveTenantConfig(input);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Inject the tenant field into a Mongoose schema, and (when `enabled` +
|
|
386
|
+
* strategy === 'field') prepend it to every existing compound index so
|
|
387
|
+
* queries are index-efficient under multi-tenant scoping.
|
|
388
|
+
*/
|
|
389
|
+
function injectTenantField(schema, tenant) {
|
|
390
|
+
const isFieldStrategy = tenant.strategy === "field";
|
|
391
|
+
const isObjectId = tenant.fieldType === "objectId";
|
|
392
|
+
schema.add({ [tenant.tenantField]: {
|
|
393
|
+
type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
|
|
394
|
+
...tenant.enabled && tenant.required ? { required: true } : {},
|
|
395
|
+
index: true,
|
|
396
|
+
...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
|
|
397
|
+
} });
|
|
398
|
+
if (!tenant.enabled || !isFieldStrategy) return;
|
|
399
|
+
const existingIndexes = schema._indexes;
|
|
400
|
+
if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
|
|
401
|
+
const fields = indexEntry[0];
|
|
402
|
+
if (fields[tenant.tenantField] !== void 0) continue;
|
|
403
|
+
const newFields = { [tenant.tenantField]: 1 };
|
|
404
|
+
for (const [key, val] of Object.entries(fields)) newFields[key] = val;
|
|
405
|
+
indexEntry[0] = newFields;
|
|
406
|
+
}
|
|
284
407
|
}
|
|
285
408
|
//#endregion
|
|
286
409
|
//#region src/models/reservation.model.ts
|
|
@@ -369,129 +492,6 @@ function createReservationModel(connection, opts = {}) {
|
|
|
369
492
|
return connection.model("CartReservation", schema, collection);
|
|
370
493
|
}
|
|
371
494
|
//#endregion
|
|
372
|
-
//#region src/models/idempotency.model.ts
|
|
373
|
-
function createIdempotencyModel(connection, opts = {}) {
|
|
374
|
-
const schema = new Schema({
|
|
375
|
-
cartRef: {
|
|
376
|
-
type: String,
|
|
377
|
-
required: true
|
|
378
|
-
},
|
|
379
|
-
operation: {
|
|
380
|
-
type: String,
|
|
381
|
-
required: true
|
|
382
|
-
},
|
|
383
|
-
actorRef: {
|
|
384
|
-
type: String,
|
|
385
|
-
required: true
|
|
386
|
-
},
|
|
387
|
-
idempotencyKey: {
|
|
388
|
-
type: String,
|
|
389
|
-
required: true
|
|
390
|
-
},
|
|
391
|
-
status: {
|
|
392
|
-
type: String,
|
|
393
|
-
enum: [
|
|
394
|
-
"in_flight",
|
|
395
|
-
"succeeded",
|
|
396
|
-
"failed"
|
|
397
|
-
],
|
|
398
|
-
default: "in_flight"
|
|
399
|
-
},
|
|
400
|
-
resultKind: {
|
|
401
|
-
type: String,
|
|
402
|
-
enum: [
|
|
403
|
-
"inline",
|
|
404
|
-
"pointer",
|
|
405
|
-
null
|
|
406
|
-
],
|
|
407
|
-
default: null
|
|
408
|
-
},
|
|
409
|
-
resultInline: {
|
|
410
|
-
type: Schema.Types.Mixed,
|
|
411
|
-
default: null
|
|
412
|
-
},
|
|
413
|
-
resultPointer: {
|
|
414
|
-
type: Schema.Types.Mixed,
|
|
415
|
-
default: null
|
|
416
|
-
},
|
|
417
|
-
error: {
|
|
418
|
-
type: Schema.Types.Mixed,
|
|
419
|
-
default: null
|
|
420
|
-
},
|
|
421
|
-
leaseToken: {
|
|
422
|
-
type: String,
|
|
423
|
-
required: true
|
|
424
|
-
},
|
|
425
|
-
leaseExpiresAt: {
|
|
426
|
-
type: Date,
|
|
427
|
-
required: true
|
|
428
|
-
},
|
|
429
|
-
completedAt: {
|
|
430
|
-
type: Date,
|
|
431
|
-
default: null
|
|
432
|
-
}
|
|
433
|
-
}, {
|
|
434
|
-
timestamps: {
|
|
435
|
-
createdAt: true,
|
|
436
|
-
updatedAt: false
|
|
437
|
-
},
|
|
438
|
-
minimize: false
|
|
439
|
-
});
|
|
440
|
-
schema.index({
|
|
441
|
-
cartRef: 1,
|
|
442
|
-
operation: 1,
|
|
443
|
-
actorRef: 1,
|
|
444
|
-
idempotencyKey: 1
|
|
445
|
-
}, { unique: true });
|
|
446
|
-
schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
|
|
447
|
-
const collection = (opts.collectionPrefix ?? "") + "cart_idempotency";
|
|
448
|
-
return connection.model("CartIdempotency", schema, collection);
|
|
449
|
-
}
|
|
450
|
-
//#endregion
|
|
451
|
-
//#region src/models/inject-tenant.ts
|
|
452
|
-
/**
|
|
453
|
-
* Mongoose-specific adapter around `resolveTenantConfig()` from
|
|
454
|
-
* `@classytic/primitives/tenant`. The pure resolution lives in primitives
|
|
455
|
-
* (zero runtime deps) — this file only handles the Mongoose schema
|
|
456
|
-
* mutations (add field, prepend tenant to indexes) that primitives can't
|
|
457
|
-
* own without a mongoose dependency.
|
|
458
|
-
*/
|
|
459
|
-
function resolveCartTenant(input = {}) {
|
|
460
|
-
if (typeof input === "boolean" || input === void 0) return resolveTenantConfig(input);
|
|
461
|
-
if ("tenantFieldType" in input || "multiTenant" in input) {
|
|
462
|
-
const legacy = input;
|
|
463
|
-
return resolveTenantConfig({
|
|
464
|
-
enabled: legacy.multiTenant !== false,
|
|
465
|
-
fieldType: legacy.tenantFieldType ?? "objectId"
|
|
466
|
-
});
|
|
467
|
-
}
|
|
468
|
-
return resolveTenantConfig(input);
|
|
469
|
-
}
|
|
470
|
-
/**
|
|
471
|
-
* Inject the tenant field into a Mongoose schema, and (when `enabled` +
|
|
472
|
-
* strategy === 'field') prepend it to every existing compound index so
|
|
473
|
-
* queries are index-efficient under multi-tenant scoping.
|
|
474
|
-
*/
|
|
475
|
-
function injectTenantField(schema, tenant) {
|
|
476
|
-
const isFieldStrategy = tenant.strategy === "field";
|
|
477
|
-
const isObjectId = tenant.fieldType === "objectId";
|
|
478
|
-
schema.add({ [tenant.tenantField]: {
|
|
479
|
-
type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
|
|
480
|
-
...tenant.enabled && tenant.required ? { required: true } : {},
|
|
481
|
-
index: true,
|
|
482
|
-
...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
|
|
483
|
-
} });
|
|
484
|
-
if (!tenant.enabled || !isFieldStrategy) return;
|
|
485
|
-
const existingIndexes = schema._indexes;
|
|
486
|
-
if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
|
|
487
|
-
const fields = indexEntry[0];
|
|
488
|
-
if (fields[tenant.tenantField] !== void 0) continue;
|
|
489
|
-
const newFields = { [tenant.tenantField]: 1 };
|
|
490
|
-
for (const [key, val] of Object.entries(fields)) newFields[key] = val;
|
|
491
|
-
indexEntry[0] = newFields;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
//#endregion
|
|
495
495
|
//#region src/models/index.ts
|
|
496
496
|
const CART_MODEL_NAMES = [
|
|
497
497
|
"CartDraft",
|
|
@@ -558,14 +558,252 @@ var CartEventPublisher = class {
|
|
|
558
558
|
resourceId: options.resourceId,
|
|
559
559
|
userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
|
|
560
560
|
organizationId: ctx.organizationId,
|
|
561
|
-
correlationId: ctx.correlationId,
|
|
562
|
-
aggregate: options.aggregate
|
|
563
|
-
});
|
|
564
|
-
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
565
|
-
else if (ctx.session) throw new Error("CartEventPublisher.emit: ctx.session requires a host-provided outbox for durable event writes");
|
|
566
|
-
if (!ctx.session) await this.events.publish(event);
|
|
561
|
+
correlationId: ctx.correlationId,
|
|
562
|
+
aggregate: options.aggregate
|
|
563
|
+
});
|
|
564
|
+
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
565
|
+
else if (ctx.session) throw new Error("CartEventPublisher.emit: ctx.session requires a host-provided outbox for durable event writes");
|
|
566
|
+
if (!ctx.session) await this.events.publish(event);
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
//#endregion
|
|
570
|
+
//#region src/repositories/checkout.repository.ts
|
|
571
|
+
/**
|
|
572
|
+
* CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
|
|
573
|
+
*
|
|
574
|
+
* All domain logic (createFromDraft with hash interlock, commit, cancel)
|
|
575
|
+
* lives here. Tenant scoping comes from `multiTenantPlugin`; `publicId`
|
|
576
|
+
* comes from `customIdPlugin`. State transitions go through mongokit's
|
|
577
|
+
* `update()` so all hooks fire.
|
|
578
|
+
*/
|
|
579
|
+
var CheckoutRepository = class extends Repository {
|
|
580
|
+
draftRepo;
|
|
581
|
+
clock;
|
|
582
|
+
eventPublisher;
|
|
583
|
+
constructor(model, plugins, deps) {
|
|
584
|
+
super(model, plugins);
|
|
585
|
+
this.draftRepo = deps.draftRepo;
|
|
586
|
+
this.clock = deps.clock;
|
|
587
|
+
this.eventPublisher = deps.eventPublisher;
|
|
588
|
+
}
|
|
589
|
+
async findByPublicId(publicId, ctx) {
|
|
590
|
+
return await this.getByQuery({ publicId }, this.readOptions(ctx));
|
|
591
|
+
}
|
|
592
|
+
async findByDraft(draftId, ctx) {
|
|
593
|
+
return await this.getByQuery({ draftId }, this.readOptions(ctx));
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Find the currently-open checkout for a draft.
|
|
597
|
+
* Used by `createFromDraft` dedup — terminal checkouts (canceled /
|
|
598
|
+
* finalized) are history, they must NOT be returned here or the host
|
|
599
|
+
* would try to commit a canceled snapshot on retry.
|
|
600
|
+
*/
|
|
601
|
+
async findOpenByDraft(draftId, ctx) {
|
|
602
|
+
return await this.getByQuery({
|
|
603
|
+
draftId,
|
|
604
|
+
state: "open"
|
|
605
|
+
}, this.readOptions(ctx));
|
|
606
|
+
}
|
|
607
|
+
async createFromDraft(input, ctx) {
|
|
608
|
+
const draft = await this.draftRepo.findByPublicId(input.draftPublicId, ctx);
|
|
609
|
+
if (!draft) throw new NotFoundError("draft", input.draftPublicId, ctx.organizationId);
|
|
610
|
+
if (draft.status !== "active") throw new Error(`Cannot create checkout from draft in status '${draft.status}'`);
|
|
611
|
+
if (draft.lines.length === 0) throw new Error("Cannot create checkout from an empty draft");
|
|
612
|
+
if (!draft.pricing) throw new Error("Cannot create checkout from a draft with no priced snapshot — call addItem first");
|
|
613
|
+
const draftPricingHash = draft.pricing.pricingHash;
|
|
614
|
+
if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
|
|
615
|
+
const existing = await this.findOpenByDraft(draft._id, ctx);
|
|
616
|
+
if (existing) return existing;
|
|
617
|
+
const nowIso = this.clock.now().toISOString();
|
|
618
|
+
let created;
|
|
619
|
+
try {
|
|
620
|
+
created = await this.create({
|
|
621
|
+
draftId: draft._id,
|
|
622
|
+
actorRef: draft.actorRef,
|
|
623
|
+
actorKind: draft.actorKind,
|
|
624
|
+
state: "open",
|
|
625
|
+
flowState: {
|
|
626
|
+
lastStep: CheckoutStep.CreateCheckout,
|
|
627
|
+
startedAt: nowIso,
|
|
628
|
+
updatedAt: nowIso
|
|
629
|
+
},
|
|
630
|
+
lines: draft.lines,
|
|
631
|
+
adjustments: draft.adjustments,
|
|
632
|
+
currency: draft.currency,
|
|
633
|
+
pricing: draft.pricing,
|
|
634
|
+
externalRef: null,
|
|
635
|
+
canceledReason: null,
|
|
636
|
+
version: 0,
|
|
637
|
+
metadata: null,
|
|
638
|
+
privateMetadata: null
|
|
639
|
+
}, this.writeOptions(ctx));
|
|
640
|
+
} catch (err) {
|
|
641
|
+
if (isDuplicateKeyError(err)) {
|
|
642
|
+
const winner = await this.findOpenByDraft(draft._id, ctx);
|
|
643
|
+
if (winner) return winner;
|
|
644
|
+
}
|
|
645
|
+
throw err;
|
|
646
|
+
}
|
|
647
|
+
const doc = created;
|
|
648
|
+
const pricing = doc.pricing;
|
|
649
|
+
await this.eventPublisher.emit(CartEvents.CHECKOUT_CREATED, {
|
|
650
|
+
checkoutId: doc.publicId,
|
|
651
|
+
draftId: input.draftPublicId,
|
|
652
|
+
grandTotal: pricing.totals?.grandTotal ?? {
|
|
653
|
+
amount: 0,
|
|
654
|
+
currency: doc.currency
|
|
655
|
+
}
|
|
656
|
+
}, ctx, {
|
|
657
|
+
resource: "checkout",
|
|
658
|
+
resourceId: doc.publicId,
|
|
659
|
+
aggregate: {
|
|
660
|
+
type: "checkout",
|
|
661
|
+
id: doc.publicId
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
return doc;
|
|
665
|
+
}
|
|
666
|
+
async commit(input, ctx) {
|
|
667
|
+
const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
|
|
668
|
+
const draft = await this.draftRepo.getById(checkout.draftId, {
|
|
669
|
+
organizationId: ctx.organizationId,
|
|
670
|
+
skipTenant: ctx.skipTenant,
|
|
671
|
+
session: ctx.session,
|
|
672
|
+
lean: true,
|
|
673
|
+
throwOnNotFound: false
|
|
674
|
+
});
|
|
675
|
+
CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "finalized");
|
|
676
|
+
const nowIso = this.clock.now().toISOString();
|
|
677
|
+
const updated = await this.updateWithVersion(checkout._id, checkout.version, {
|
|
678
|
+
state: "finalized",
|
|
679
|
+
externalRef: input.externalRef ?? null,
|
|
680
|
+
flowState: {
|
|
681
|
+
...checkout.flowState,
|
|
682
|
+
lastStep: CheckoutStep.Commit,
|
|
683
|
+
updatedAt: nowIso
|
|
684
|
+
}
|
|
685
|
+
}, ctx);
|
|
686
|
+
await this.draftRepo.markConverted(checkout.draftId, ctx);
|
|
687
|
+
const pricing = updated.pricing;
|
|
688
|
+
await this.eventPublisher.emit(CartEvents.CHECKOUT_COMMITTED, {
|
|
689
|
+
checkoutId: updated.publicId,
|
|
690
|
+
draftId: draft?.publicId ?? String(updated.draftId),
|
|
691
|
+
externalRef: updated.externalRef ?? null,
|
|
692
|
+
grandTotal: pricing.totals?.grandTotal ?? {
|
|
693
|
+
amount: 0,
|
|
694
|
+
currency: updated.currency
|
|
695
|
+
}
|
|
696
|
+
}, ctx, {
|
|
697
|
+
resource: "checkout",
|
|
698
|
+
resourceId: updated.publicId,
|
|
699
|
+
aggregate: {
|
|
700
|
+
type: "checkout",
|
|
701
|
+
id: updated.publicId
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
return updated;
|
|
705
|
+
}
|
|
706
|
+
async cancel(input, ctx) {
|
|
707
|
+
const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
|
|
708
|
+
CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "canceled");
|
|
709
|
+
const nowIso = this.clock.now().toISOString();
|
|
710
|
+
const updated = await this.updateWithVersion(checkout._id, checkout.version, {
|
|
711
|
+
state: "canceled",
|
|
712
|
+
canceledReason: input.reason,
|
|
713
|
+
flowState: {
|
|
714
|
+
...checkout.flowState,
|
|
715
|
+
updatedAt: nowIso
|
|
716
|
+
}
|
|
717
|
+
}, ctx);
|
|
718
|
+
await this.eventPublisher.emit(CartEvents.CHECKOUT_CANCELED, {
|
|
719
|
+
checkoutId: updated.publicId,
|
|
720
|
+
reason: input.reason
|
|
721
|
+
}, ctx, {
|
|
722
|
+
resource: "checkout",
|
|
723
|
+
resourceId: updated.publicId,
|
|
724
|
+
aggregate: {
|
|
725
|
+
type: "checkout",
|
|
726
|
+
id: updated.publicId
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
return updated;
|
|
730
|
+
}
|
|
731
|
+
async updateWithVersion(checkoutId, expectedVersion, updates, ctx) {
|
|
732
|
+
try {
|
|
733
|
+
return await this.update(checkoutId, {
|
|
734
|
+
$set: updates,
|
|
735
|
+
$inc: { version: 1 }
|
|
736
|
+
}, {
|
|
737
|
+
...this.writeOptions(ctx),
|
|
738
|
+
query: { version: expectedVersion },
|
|
739
|
+
throwOnNotFound: true,
|
|
740
|
+
lean: true
|
|
741
|
+
});
|
|
742
|
+
} catch (err) {
|
|
743
|
+
if (isNotFound$2(err)) throw new ConcurrencyError("checkout", expectedVersion, String(checkoutId));
|
|
744
|
+
throw err;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Transition `open` checkouts older than `maxAgeMs` to `canceled` with
|
|
749
|
+
* `canceledReason: 'expired'`. Pure business expiry — host-driven, no
|
|
750
|
+
* TTL.
|
|
751
|
+
*
|
|
752
|
+
* Why this exists: a checkout left in `open` (browser closed before
|
|
753
|
+
* commit/cancel, mobile app crash, network drop after the freeze step)
|
|
754
|
+
* holds the partial-unique slot for that draft. Without expiry, the
|
|
755
|
+
* customer's next attempt collides with their own zombie. Hosts should
|
|
756
|
+
* call this from a periodic job (cron, Streamline, etc.) at whatever
|
|
757
|
+
* cadence matches their checkout completion SLA.
|
|
758
|
+
*
|
|
759
|
+
* Returns the count of rows expired. Caller scopes the operation via
|
|
760
|
+
* `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
|
|
761
|
+
* `skipTenant: true` to expire across the board (only safe for the
|
|
762
|
+
* platform's own background worker, not an end-user request).
|
|
763
|
+
*
|
|
764
|
+
* Does NOT emit `CHECKOUT_CANCELED` events for the expired rows.
|
|
765
|
+
* Expiry is a janitorial action; if hosts need an event for analytics
|
|
766
|
+
* they can subscribe to a downstream tail of the audit trail or wrap
|
|
767
|
+
* this method.
|
|
768
|
+
*/
|
|
769
|
+
async expireStaleOpenCheckouts(maxAgeMs, ctx) {
|
|
770
|
+
if (!Number.isFinite(maxAgeMs) || maxAgeMs <= 0) throw new Error("maxAgeMs must be a positive number of milliseconds");
|
|
771
|
+
const cutoff = new Date(this.clock.now().getTime() - maxAgeMs);
|
|
772
|
+
const result = await this.updateMany({
|
|
773
|
+
state: "open",
|
|
774
|
+
createdAt: { $lt: cutoff }
|
|
775
|
+
}, { $set: {
|
|
776
|
+
state: "canceled",
|
|
777
|
+
canceledReason: "expired",
|
|
778
|
+
updatedAt: this.clock.now()
|
|
779
|
+
} }, this.writeOptions(ctx));
|
|
780
|
+
return { count: result?.modifiedCount ?? result?.matchedCount ?? 0 };
|
|
781
|
+
}
|
|
782
|
+
readOptions(ctx) {
|
|
783
|
+
return {
|
|
784
|
+
organizationId: ctx.organizationId,
|
|
785
|
+
skipTenant: ctx.skipTenant,
|
|
786
|
+
session: ctx.session,
|
|
787
|
+
lean: true,
|
|
788
|
+
throwOnNotFound: false
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
writeOptions(ctx) {
|
|
792
|
+
return {
|
|
793
|
+
organizationId: ctx.organizationId,
|
|
794
|
+
skipTenant: ctx.skipTenant,
|
|
795
|
+
session: ctx.session
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
async requireCheckout(publicId, ctx) {
|
|
799
|
+
const checkout = await this.findByPublicId(publicId, ctx);
|
|
800
|
+
if (!checkout) throw new NotFoundError("checkout", publicId, ctx.organizationId);
|
|
801
|
+
return checkout;
|
|
567
802
|
}
|
|
568
803
|
};
|
|
804
|
+
function isNotFound$2(err) {
|
|
805
|
+
return typeof err === "object" && err !== null && err.status === 404;
|
|
806
|
+
}
|
|
569
807
|
//#endregion
|
|
570
808
|
//#region src/services/pricing.service.ts
|
|
571
809
|
/**
|
|
@@ -1014,7 +1252,7 @@ var DraftRepository = class extends Repository {
|
|
|
1014
1252
|
throwOnNotFound: true
|
|
1015
1253
|
});
|
|
1016
1254
|
} catch (err) {
|
|
1017
|
-
if (isNotFound$
|
|
1255
|
+
if (isNotFound$1(err)) throw new ConcurrencyError("draft", expectedVersion, String(draftId));
|
|
1018
1256
|
throw err;
|
|
1019
1257
|
}
|
|
1020
1258
|
}
|
|
@@ -1053,7 +1291,7 @@ var DraftRepository = class extends Repository {
|
|
|
1053
1291
|
});
|
|
1054
1292
|
return doc;
|
|
1055
1293
|
} catch (err) {
|
|
1056
|
-
if (isNotFound$
|
|
1294
|
+
if (isNotFound$1(err)) return null;
|
|
1057
1295
|
throw err;
|
|
1058
1296
|
}
|
|
1059
1297
|
}
|
|
@@ -1083,267 +1321,8 @@ var DraftRepository = class extends Repository {
|
|
|
1083
1321
|
pricing
|
|
1084
1322
|
}, ctx);
|
|
1085
1323
|
}
|
|
1086
|
-
mergeLines(existing, incoming) {
|
|
1087
|
-
return incoming.reduce((acc, line) => this.mergeLine(acc, { ...line }), [...existing]);
|
|
1088
|
-
}
|
|
1089
|
-
readOptions(ctx) {
|
|
1090
|
-
return {
|
|
1091
|
-
organizationId: ctx.organizationId,
|
|
1092
|
-
skipTenant: ctx.skipTenant,
|
|
1093
|
-
session: ctx.session,
|
|
1094
|
-
lean: true,
|
|
1095
|
-
throwOnNotFound: false
|
|
1096
|
-
};
|
|
1097
|
-
}
|
|
1098
|
-
writeOptions(ctx) {
|
|
1099
|
-
return {
|
|
1100
|
-
organizationId: ctx.organizationId,
|
|
1101
|
-
skipTenant: ctx.skipTenant,
|
|
1102
|
-
session: ctx.session
|
|
1103
|
-
};
|
|
1104
|
-
}
|
|
1105
|
-
async price(lines, currency, ctx, previous) {
|
|
1106
|
-
return runPricing({
|
|
1107
|
-
lines,
|
|
1108
|
-
currency,
|
|
1109
|
-
kinds: this.kinds,
|
|
1110
|
-
bridges: this.bridges,
|
|
1111
|
-
clock: this.clock,
|
|
1112
|
-
ctx,
|
|
1113
|
-
previous
|
|
1114
|
-
});
|
|
1115
|
-
}
|
|
1116
|
-
async requireDraft(publicId, ctx) {
|
|
1117
|
-
const draft = await this.findByPublicId(publicId, ctx);
|
|
1118
|
-
if (!draft) throw new NotFoundError("draft", publicId, ctx.organizationId);
|
|
1119
|
-
return draft;
|
|
1120
|
-
}
|
|
1121
|
-
kindContextFor(ctx) {
|
|
1122
|
-
return {
|
|
1123
|
-
...ctx,
|
|
1124
|
-
bridges: {
|
|
1125
|
-
catalog: this.bridges.catalog,
|
|
1126
|
-
inventory: this.bridges.inventory,
|
|
1127
|
-
promotions: this.bridges.promotions,
|
|
1128
|
-
tax: this.bridges.tax,
|
|
1129
|
-
shipping: this.bridges.shipping
|
|
1130
|
-
}
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
mergeLine(existing, incoming) {
|
|
1134
|
-
const key = this.computeMergeKey(incoming);
|
|
1135
|
-
if (key === null) return [...existing, incoming];
|
|
1136
|
-
const idx = existing.findIndex((l) => this.computeMergeKey(l) === key);
|
|
1137
|
-
if (idx === -1) return [...existing, incoming];
|
|
1138
|
-
const merged = {
|
|
1139
|
-
...existing[idx],
|
|
1140
|
-
quantity: existing[idx].quantity + incoming.quantity
|
|
1141
|
-
};
|
|
1142
|
-
return existing.map((l, i) => i === idx ? merged : l);
|
|
1143
|
-
}
|
|
1144
|
-
/**
|
|
1145
|
-
* Resolve a line's merge key.
|
|
1146
|
-
*
|
|
1147
|
-
* Preferred path: delegate to `LineKind.mergeKey()` — every built-in kind
|
|
1148
|
-
* knows its own payload shape and returns a stable grouping key
|
|
1149
|
-
* (e.g. `variant:${productRef}:${variantSku}` for the variant kind).
|
|
1150
|
-
*
|
|
1151
|
-
* Fallback: for kinds that don't implement `mergeKey()` (older custom
|
|
1152
|
-
* kinds, or unregistered kinds seen on legacy drafts), check for a
|
|
1153
|
-
* `payload.skuRef` field — the shape the repository historically
|
|
1154
|
-
* assumed. This keeps drafts written before this change mergeable.
|
|
1155
|
-
*/
|
|
1156
|
-
computeMergeKey(line) {
|
|
1157
|
-
const kind = this.kinds.tryGet(line.kind);
|
|
1158
|
-
if (kind?.mergeKey) {
|
|
1159
|
-
const lineLike = {
|
|
1160
|
-
lineId: line.lineId,
|
|
1161
|
-
kind: line.kind,
|
|
1162
|
-
quantity: line.quantity,
|
|
1163
|
-
payload: line.payload,
|
|
1164
|
-
currency: this.defaultCurrency,
|
|
1165
|
-
overrideUnitPrice: line.overrideUnitPrice
|
|
1166
|
-
};
|
|
1167
|
-
return kind.mergeKey(lineLike);
|
|
1168
|
-
}
|
|
1169
|
-
const payload = line.payload;
|
|
1170
|
-
if (!payload?.skuRef) return null;
|
|
1171
|
-
return `${line.kind}:${payload.skuRef}`;
|
|
1172
|
-
}
|
|
1173
|
-
};
|
|
1174
|
-
function isNotFound$2(err) {
|
|
1175
|
-
return typeof err === "object" && err !== null && err.status === 404;
|
|
1176
|
-
}
|
|
1177
|
-
function assertPositiveInteger(quantity, kind) {
|
|
1178
|
-
if (!Number.isInteger(quantity) || quantity < 1) throw new KindError(kind, `quantity must be a positive integer, got ${quantity}`);
|
|
1179
|
-
return quantity;
|
|
1180
|
-
}
|
|
1181
|
-
//#endregion
|
|
1182
|
-
//#region src/repositories/checkout.repository.ts
|
|
1183
|
-
/**
|
|
1184
|
-
* CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
|
|
1185
|
-
*
|
|
1186
|
-
* All domain logic (createFromDraft with hash interlock, commit, cancel)
|
|
1187
|
-
* lives here. Tenant scoping comes from `multiTenantPlugin`; `publicId`
|
|
1188
|
-
* comes from `customIdPlugin`. State transitions go through mongokit's
|
|
1189
|
-
* `update()` so all hooks fire.
|
|
1190
|
-
*/
|
|
1191
|
-
var CheckoutRepository = class extends Repository {
|
|
1192
|
-
draftRepo;
|
|
1193
|
-
clock;
|
|
1194
|
-
eventPublisher;
|
|
1195
|
-
constructor(model, plugins, deps) {
|
|
1196
|
-
super(model, plugins);
|
|
1197
|
-
this.draftRepo = deps.draftRepo;
|
|
1198
|
-
this.clock = deps.clock;
|
|
1199
|
-
this.eventPublisher = deps.eventPublisher;
|
|
1200
|
-
}
|
|
1201
|
-
async findByPublicId(publicId, ctx) {
|
|
1202
|
-
return await this.getByQuery({ publicId }, this.readOptions(ctx));
|
|
1203
|
-
}
|
|
1204
|
-
async findByDraft(draftId, ctx) {
|
|
1205
|
-
return await this.getByQuery({ draftId }, this.readOptions(ctx));
|
|
1206
|
-
}
|
|
1207
|
-
/**
|
|
1208
|
-
* Find the currently-open checkout for a draft.
|
|
1209
|
-
* Used by `createFromDraft` dedup — terminal checkouts (canceled /
|
|
1210
|
-
* finalized) are history, they must NOT be returned here or the host
|
|
1211
|
-
* would try to commit a canceled snapshot on retry.
|
|
1212
|
-
*/
|
|
1213
|
-
async findOpenByDraft(draftId, ctx) {
|
|
1214
|
-
return await this.getByQuery({
|
|
1215
|
-
draftId,
|
|
1216
|
-
state: "open"
|
|
1217
|
-
}, this.readOptions(ctx));
|
|
1218
|
-
}
|
|
1219
|
-
async createFromDraft(input, ctx) {
|
|
1220
|
-
const draft = await this.draftRepo.findByPublicId(input.draftPublicId, ctx);
|
|
1221
|
-
if (!draft) throw new NotFoundError("draft", input.draftPublicId, ctx.organizationId);
|
|
1222
|
-
if (draft.status !== "active") throw new Error(`Cannot create checkout from draft in status '${draft.status}'`);
|
|
1223
|
-
if (draft.lines.length === 0) throw new Error("Cannot create checkout from an empty draft");
|
|
1224
|
-
if (!draft.pricing) throw new Error("Cannot create checkout from a draft with no priced snapshot — call addItem first");
|
|
1225
|
-
const draftPricingHash = draft.pricing.pricingHash;
|
|
1226
|
-
if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
|
|
1227
|
-
const existing = await this.findOpenByDraft(draft._id, ctx);
|
|
1228
|
-
if (existing) return existing;
|
|
1229
|
-
const nowIso = this.clock.now().toISOString();
|
|
1230
|
-
const doc = await this.create({
|
|
1231
|
-
draftId: draft._id,
|
|
1232
|
-
actorRef: draft.actorRef,
|
|
1233
|
-
actorKind: draft.actorKind,
|
|
1234
|
-
state: "open",
|
|
1235
|
-
flowState: {
|
|
1236
|
-
lastStep: CheckoutStep.CreateCheckout,
|
|
1237
|
-
startedAt: nowIso,
|
|
1238
|
-
updatedAt: nowIso
|
|
1239
|
-
},
|
|
1240
|
-
lines: draft.lines,
|
|
1241
|
-
adjustments: draft.adjustments,
|
|
1242
|
-
currency: draft.currency,
|
|
1243
|
-
pricing: draft.pricing,
|
|
1244
|
-
externalRef: null,
|
|
1245
|
-
canceledReason: null,
|
|
1246
|
-
version: 0,
|
|
1247
|
-
metadata: null,
|
|
1248
|
-
privateMetadata: null
|
|
1249
|
-
}, this.writeOptions(ctx));
|
|
1250
|
-
const pricing = doc.pricing;
|
|
1251
|
-
await this.eventPublisher.emit(CartEvents.CHECKOUT_CREATED, {
|
|
1252
|
-
checkoutId: doc.publicId,
|
|
1253
|
-
draftId: input.draftPublicId,
|
|
1254
|
-
grandTotal: pricing.totals?.grandTotal ?? {
|
|
1255
|
-
amount: 0,
|
|
1256
|
-
currency: doc.currency
|
|
1257
|
-
}
|
|
1258
|
-
}, ctx, {
|
|
1259
|
-
resource: "checkout",
|
|
1260
|
-
resourceId: doc.publicId,
|
|
1261
|
-
aggregate: {
|
|
1262
|
-
type: "checkout",
|
|
1263
|
-
id: doc.publicId
|
|
1264
|
-
}
|
|
1265
|
-
});
|
|
1266
|
-
return doc;
|
|
1267
|
-
}
|
|
1268
|
-
async commit(input, ctx) {
|
|
1269
|
-
const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
|
|
1270
|
-
const draft = await this.draftRepo.getById(checkout.draftId, {
|
|
1271
|
-
organizationId: ctx.organizationId,
|
|
1272
|
-
skipTenant: ctx.skipTenant,
|
|
1273
|
-
session: ctx.session,
|
|
1274
|
-
lean: true,
|
|
1275
|
-
throwOnNotFound: false
|
|
1276
|
-
});
|
|
1277
|
-
if (checkout.state !== "open") throw new StateTransitionError(checkout.publicId, checkout.state, "finalized");
|
|
1278
|
-
const nowIso = this.clock.now().toISOString();
|
|
1279
|
-
const updated = await this.updateWithVersion(checkout._id, checkout.version, {
|
|
1280
|
-
state: "finalized",
|
|
1281
|
-
externalRef: input.externalRef ?? null,
|
|
1282
|
-
flowState: {
|
|
1283
|
-
...checkout.flowState,
|
|
1284
|
-
lastStep: CheckoutStep.Commit,
|
|
1285
|
-
updatedAt: nowIso
|
|
1286
|
-
}
|
|
1287
|
-
}, ctx);
|
|
1288
|
-
await this.draftRepo.markConverted(checkout.draftId, ctx);
|
|
1289
|
-
const pricing = updated.pricing;
|
|
1290
|
-
await this.eventPublisher.emit(CartEvents.CHECKOUT_COMMITTED, {
|
|
1291
|
-
checkoutId: updated.publicId,
|
|
1292
|
-
draftId: draft?.publicId ?? String(updated.draftId),
|
|
1293
|
-
externalRef: updated.externalRef ?? null,
|
|
1294
|
-
grandTotal: pricing.totals?.grandTotal ?? {
|
|
1295
|
-
amount: 0,
|
|
1296
|
-
currency: updated.currency
|
|
1297
|
-
}
|
|
1298
|
-
}, ctx, {
|
|
1299
|
-
resource: "checkout",
|
|
1300
|
-
resourceId: updated.publicId,
|
|
1301
|
-
aggregate: {
|
|
1302
|
-
type: "checkout",
|
|
1303
|
-
id: updated.publicId
|
|
1304
|
-
}
|
|
1305
|
-
});
|
|
1306
|
-
return updated;
|
|
1307
|
-
}
|
|
1308
|
-
async cancel(input, ctx) {
|
|
1309
|
-
const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
|
|
1310
|
-
if (checkout.state !== "open") throw new StateTransitionError(checkout.publicId, checkout.state, "canceled");
|
|
1311
|
-
const nowIso = this.clock.now().toISOString();
|
|
1312
|
-
const updated = await this.updateWithVersion(checkout._id, checkout.version, {
|
|
1313
|
-
state: "canceled",
|
|
1314
|
-
canceledReason: input.reason,
|
|
1315
|
-
flowState: {
|
|
1316
|
-
...checkout.flowState,
|
|
1317
|
-
updatedAt: nowIso
|
|
1318
|
-
}
|
|
1319
|
-
}, ctx);
|
|
1320
|
-
await this.eventPublisher.emit(CartEvents.CHECKOUT_CANCELED, {
|
|
1321
|
-
checkoutId: updated.publicId,
|
|
1322
|
-
reason: input.reason
|
|
1323
|
-
}, ctx, {
|
|
1324
|
-
resource: "checkout",
|
|
1325
|
-
resourceId: updated.publicId,
|
|
1326
|
-
aggregate: {
|
|
1327
|
-
type: "checkout",
|
|
1328
|
-
id: updated.publicId
|
|
1329
|
-
}
|
|
1330
|
-
});
|
|
1331
|
-
return updated;
|
|
1332
|
-
}
|
|
1333
|
-
async updateWithVersion(checkoutId, expectedVersion, updates, ctx) {
|
|
1334
|
-
try {
|
|
1335
|
-
return await this.update(checkoutId, {
|
|
1336
|
-
$set: updates,
|
|
1337
|
-
$inc: { version: 1 }
|
|
1338
|
-
}, {
|
|
1339
|
-
...this.writeOptions(ctx),
|
|
1340
|
-
query: { version: expectedVersion },
|
|
1341
|
-
lean: true
|
|
1342
|
-
});
|
|
1343
|
-
} catch (err) {
|
|
1344
|
-
if (isNotFound$1(err)) throw new ConcurrencyError("checkout", expectedVersion, String(checkoutId));
|
|
1345
|
-
throw err;
|
|
1346
|
-
}
|
|
1324
|
+
mergeLines(existing, incoming) {
|
|
1325
|
+
return incoming.reduce((acc, line) => this.mergeLine(acc, { ...line }), [...existing]);
|
|
1347
1326
|
}
|
|
1348
1327
|
readOptions(ctx) {
|
|
1349
1328
|
return {
|
|
@@ -1361,103 +1340,82 @@ var CheckoutRepository = class extends Repository {
|
|
|
1361
1340
|
session: ctx.session
|
|
1362
1341
|
};
|
|
1363
1342
|
}
|
|
1364
|
-
async
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
//#region src/repositories/reservation.repository.ts
|
|
1375
|
-
/**
|
|
1376
|
-
* ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
|
|
1377
|
-
*
|
|
1378
|
-
* Tenant scoping is enforced by `multiTenantPlugin`; `publicId` comes from
|
|
1379
|
-
* `customIdPlugin`. The TTL index on `expiresAt` is a backstop — the
|
|
1380
|
-
* sweeper drives the active release loop via `findExpiredHeld`.
|
|
1381
|
-
*/
|
|
1382
|
-
var ReservationRepository = class extends Repository {
|
|
1383
|
-
constructor(model, plugins) {
|
|
1384
|
-
super(model, plugins);
|
|
1385
|
-
}
|
|
1386
|
-
/** All reservations belonging to a checkout. */
|
|
1387
|
-
async findByCheckout(checkoutId, ctx) {
|
|
1388
|
-
return await this.findAll({ checkoutId }, this.readOptions(ctx));
|
|
1389
|
-
}
|
|
1390
|
-
/**
|
|
1391
|
-
* Expired held reservations for the sweeper. Routed through `getAll` so
|
|
1392
|
-
* the multi-tenant plugin scopes the query at POLICY priority.
|
|
1393
|
-
*/
|
|
1394
|
-
async findExpiredHeld(asOf, limit, ctx) {
|
|
1395
|
-
return (await this.getAll({
|
|
1396
|
-
filters: {
|
|
1397
|
-
status: "held",
|
|
1398
|
-
expiresAt: { $lt: asOf }
|
|
1399
|
-
},
|
|
1400
|
-
sort: { expiresAt: 1 },
|
|
1401
|
-
page: 1,
|
|
1402
|
-
limit,
|
|
1403
|
-
countStrategy: "none"
|
|
1404
|
-
}, this.readOptions(ctx))).docs;
|
|
1405
|
-
}
|
|
1406
|
-
/** Atomic transition `held → released` via version check. */
|
|
1407
|
-
async markReleased(reservationId, expectedVersion, reason, ctx) {
|
|
1408
|
-
return this.atomicTransition(reservationId, {
|
|
1409
|
-
$set: {
|
|
1410
|
-
status: "released",
|
|
1411
|
-
releasedAt: /* @__PURE__ */ new Date(),
|
|
1412
|
-
releaseReason: reason
|
|
1413
|
-
},
|
|
1414
|
-
$inc: { version: 1 }
|
|
1415
|
-
}, {
|
|
1416
|
-
version: expectedVersion,
|
|
1417
|
-
status: "held"
|
|
1418
|
-
}, ctx);
|
|
1419
|
-
}
|
|
1420
|
-
/** Atomic transition `held → committed` on saga step 10. */
|
|
1421
|
-
async markCommitted(reservationId, expectedVersion, ctx) {
|
|
1422
|
-
return this.atomicTransition(reservationId, {
|
|
1423
|
-
$set: { status: "committed" },
|
|
1424
|
-
$inc: { version: 1 }
|
|
1425
|
-
}, {
|
|
1426
|
-
version: expectedVersion,
|
|
1427
|
-
status: "held"
|
|
1428
|
-
}, ctx);
|
|
1343
|
+
async price(lines, currency, ctx, previous) {
|
|
1344
|
+
return runPricing({
|
|
1345
|
+
lines,
|
|
1346
|
+
currency,
|
|
1347
|
+
kinds: this.kinds,
|
|
1348
|
+
bridges: this.bridges,
|
|
1349
|
+
clock: this.clock,
|
|
1350
|
+
ctx,
|
|
1351
|
+
previous
|
|
1352
|
+
});
|
|
1429
1353
|
}
|
|
1430
|
-
async
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
query: constraints,
|
|
1435
|
-
lean: true
|
|
1436
|
-
});
|
|
1437
|
-
} catch (err) {
|
|
1438
|
-
if (isNotFound(err)) return null;
|
|
1439
|
-
throw err;
|
|
1440
|
-
}
|
|
1354
|
+
async requireDraft(publicId, ctx) {
|
|
1355
|
+
const draft = await this.findByPublicId(publicId, ctx);
|
|
1356
|
+
if (!draft) throw new NotFoundError("draft", publicId, ctx.organizationId);
|
|
1357
|
+
return draft;
|
|
1441
1358
|
}
|
|
1442
|
-
|
|
1359
|
+
kindContextFor(ctx) {
|
|
1443
1360
|
return {
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1361
|
+
...ctx,
|
|
1362
|
+
bridges: {
|
|
1363
|
+
catalog: this.bridges.catalog,
|
|
1364
|
+
inventory: this.bridges.inventory,
|
|
1365
|
+
promotions: this.bridges.promotions,
|
|
1366
|
+
tax: this.bridges.tax,
|
|
1367
|
+
shipping: this.bridges.shipping
|
|
1368
|
+
}
|
|
1448
1369
|
};
|
|
1449
1370
|
}
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1371
|
+
mergeLine(existing, incoming) {
|
|
1372
|
+
const key = this.computeMergeKey(incoming);
|
|
1373
|
+
if (key === null) return [...existing, incoming];
|
|
1374
|
+
const idx = existing.findIndex((l) => this.computeMergeKey(l) === key);
|
|
1375
|
+
if (idx === -1) return [...existing, incoming];
|
|
1376
|
+
const merged = {
|
|
1377
|
+
...existing[idx],
|
|
1378
|
+
quantity: existing[idx].quantity + incoming.quantity
|
|
1455
1379
|
};
|
|
1380
|
+
return existing.map((l, i) => i === idx ? merged : l);
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Resolve a line's merge key.
|
|
1384
|
+
*
|
|
1385
|
+
* Preferred path: delegate to `LineKind.mergeKey()` — every built-in kind
|
|
1386
|
+
* knows its own payload shape and returns a stable grouping key
|
|
1387
|
+
* (e.g. `variant:${productRef}:${variantSku}` for the variant kind).
|
|
1388
|
+
*
|
|
1389
|
+
* Fallback: for kinds that don't implement `mergeKey()` (older custom
|
|
1390
|
+
* kinds, or unregistered kinds seen on legacy drafts), check for a
|
|
1391
|
+
* `payload.skuRef` field — the shape the repository historically
|
|
1392
|
+
* assumed. This keeps drafts written before this change mergeable.
|
|
1393
|
+
*/
|
|
1394
|
+
computeMergeKey(line) {
|
|
1395
|
+
const kind = this.kinds.tryGet(line.kind);
|
|
1396
|
+
if (kind?.mergeKey) {
|
|
1397
|
+
const lineLike = {
|
|
1398
|
+
lineId: line.lineId,
|
|
1399
|
+
kind: line.kind,
|
|
1400
|
+
quantity: line.quantity,
|
|
1401
|
+
payload: line.payload,
|
|
1402
|
+
currency: this.defaultCurrency,
|
|
1403
|
+
overrideUnitPrice: line.overrideUnitPrice
|
|
1404
|
+
};
|
|
1405
|
+
return kind.mergeKey(lineLike);
|
|
1406
|
+
}
|
|
1407
|
+
const payload = line.payload;
|
|
1408
|
+
if (!payload?.skuRef) return null;
|
|
1409
|
+
return `${line.kind}:${payload.skuRef}`;
|
|
1456
1410
|
}
|
|
1457
1411
|
};
|
|
1458
|
-
function isNotFound(err) {
|
|
1412
|
+
function isNotFound$1(err) {
|
|
1459
1413
|
return typeof err === "object" && err !== null && err.status === 404;
|
|
1460
1414
|
}
|
|
1415
|
+
function assertPositiveInteger(quantity, kind) {
|
|
1416
|
+
if (!Number.isInteger(quantity) || quantity < 1) throw new KindError(kind, `quantity must be a positive integer, got ${quantity}`);
|
|
1417
|
+
return quantity;
|
|
1418
|
+
}
|
|
1461
1419
|
//#endregion
|
|
1462
1420
|
//#region src/repositories/idempotency.repository.ts
|
|
1463
1421
|
/**
|
|
@@ -1506,7 +1464,7 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1506
1464
|
leaseExpiresAt
|
|
1507
1465
|
}], { session }))[0];
|
|
1508
1466
|
} catch (err) {
|
|
1509
|
-
if (isDuplicateKeyError(err)) return null;
|
|
1467
|
+
if (isDuplicateKeyError$1(err)) return null;
|
|
1510
1468
|
throw err;
|
|
1511
1469
|
}
|
|
1512
1470
|
}
|
|
@@ -1572,12 +1530,100 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1572
1530
|
}) ?? null;
|
|
1573
1531
|
}
|
|
1574
1532
|
};
|
|
1575
|
-
function isDuplicateKeyError(err) {
|
|
1533
|
+
function isDuplicateKeyError$1(err) {
|
|
1576
1534
|
if (!err || typeof err !== "object") return false;
|
|
1577
1535
|
const code = err.code;
|
|
1578
1536
|
return code === 11e3 || code === 11001;
|
|
1579
1537
|
}
|
|
1580
1538
|
//#endregion
|
|
1539
|
+
//#region src/repositories/reservation.repository.ts
|
|
1540
|
+
/**
|
|
1541
|
+
* ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
|
|
1542
|
+
*
|
|
1543
|
+
* Tenant scoping is enforced by `multiTenantPlugin`; `publicId` comes from
|
|
1544
|
+
* `customIdPlugin`. The TTL index on `expiresAt` is a backstop — the
|
|
1545
|
+
* sweeper drives the active release loop via `findExpiredHeld`.
|
|
1546
|
+
*/
|
|
1547
|
+
var ReservationRepository = class extends Repository {
|
|
1548
|
+
constructor(model, plugins) {
|
|
1549
|
+
super(model, plugins);
|
|
1550
|
+
}
|
|
1551
|
+
/** All reservations belonging to a checkout. */
|
|
1552
|
+
async findByCheckout(checkoutId, ctx) {
|
|
1553
|
+
return await this.findAll({ checkoutId }, this.readOptions(ctx));
|
|
1554
|
+
}
|
|
1555
|
+
/**
|
|
1556
|
+
* Expired held reservations for the sweeper. Routed through `getAll` so
|
|
1557
|
+
* the multi-tenant plugin scopes the query at POLICY priority.
|
|
1558
|
+
*/
|
|
1559
|
+
async findExpiredHeld(asOf, limit, ctx) {
|
|
1560
|
+
return (await this.getAll({
|
|
1561
|
+
filters: {
|
|
1562
|
+
status: "held",
|
|
1563
|
+
expiresAt: { $lt: asOf }
|
|
1564
|
+
},
|
|
1565
|
+
sort: { expiresAt: 1 },
|
|
1566
|
+
page: 1,
|
|
1567
|
+
limit,
|
|
1568
|
+
countStrategy: "none"
|
|
1569
|
+
}, this.readOptions(ctx))).docs;
|
|
1570
|
+
}
|
|
1571
|
+
/** Atomic transition `held → released` via version check. */
|
|
1572
|
+
async markReleased(reservationId, expectedVersion, reason, ctx) {
|
|
1573
|
+
return this.atomicTransition(reservationId, {
|
|
1574
|
+
$set: {
|
|
1575
|
+
status: "released",
|
|
1576
|
+
releasedAt: /* @__PURE__ */ new Date(),
|
|
1577
|
+
releaseReason: reason
|
|
1578
|
+
},
|
|
1579
|
+
$inc: { version: 1 }
|
|
1580
|
+
}, {
|
|
1581
|
+
version: expectedVersion,
|
|
1582
|
+
status: "held"
|
|
1583
|
+
}, ctx);
|
|
1584
|
+
}
|
|
1585
|
+
/** Atomic transition `held → committed` on saga step 10. */
|
|
1586
|
+
async markCommitted(reservationId, expectedVersion, ctx) {
|
|
1587
|
+
return this.atomicTransition(reservationId, {
|
|
1588
|
+
$set: { status: "committed" },
|
|
1589
|
+
$inc: { version: 1 }
|
|
1590
|
+
}, {
|
|
1591
|
+
version: expectedVersion,
|
|
1592
|
+
status: "held"
|
|
1593
|
+
}, ctx);
|
|
1594
|
+
}
|
|
1595
|
+
async atomicTransition(id, data, constraints, ctx) {
|
|
1596
|
+
try {
|
|
1597
|
+
return await this.update(id, data, {
|
|
1598
|
+
...this.writeOptions(ctx),
|
|
1599
|
+
query: constraints,
|
|
1600
|
+
lean: true
|
|
1601
|
+
});
|
|
1602
|
+
} catch (err) {
|
|
1603
|
+
if (isNotFound(err)) return null;
|
|
1604
|
+
throw err;
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
readOptions(ctx) {
|
|
1608
|
+
return {
|
|
1609
|
+
organizationId: ctx.organizationId,
|
|
1610
|
+
skipTenant: ctx.skipTenant,
|
|
1611
|
+
session: ctx.session,
|
|
1612
|
+
lean: true
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
writeOptions(ctx) {
|
|
1616
|
+
return {
|
|
1617
|
+
organizationId: ctx.organizationId,
|
|
1618
|
+
skipTenant: ctx.skipTenant,
|
|
1619
|
+
session: ctx.session
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
function isNotFound(err) {
|
|
1624
|
+
return typeof err === "object" && err !== null && err.status === 404;
|
|
1625
|
+
}
|
|
1626
|
+
//#endregion
|
|
1581
1627
|
//#region src/repositories/index.ts
|
|
1582
1628
|
function tenantPlugin(fieldType = "objectId") {
|
|
1583
1629
|
return multiTenantPlugin({
|
|
@@ -1748,4 +1794,4 @@ async function createCart(config) {
|
|
|
1748
1794
|
};
|
|
1749
1795
|
}
|
|
1750
1796
|
//#endregion
|
|
1751
|
-
export {
|
|
1797
|
+
export { IdempotencyRepository as a, CheckoutRepository as c, createIdempotencyModel as d, createDraftModel as f, ReservationRepository as i, createCartModels as l, InProcessCartEventBus as n, DraftRepository as o, createCheckoutModel as p, createCartRepositories as r, runPricing as s, createCart as t, createReservationModel as u };
|