@comity/order 0.9.1 → 0.9.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.
Files changed (46) hide show
  1. package/package.json +17 -36
  2. package/dist/cjs/contracts/address-snapshot.js +0 -3
  3. package/dist/cjs/contracts/contact.js +0 -3
  4. package/dist/cjs/contracts/customer-snapshot.js +0 -3
  5. package/dist/cjs/contracts/item.js +0 -3
  6. package/dist/cjs/contracts/order-repository.js +0 -3
  7. package/dist/cjs/contracts/order.js +0 -3
  8. package/dist/cjs/contracts/payment-snapshot.js +0 -3
  9. package/dist/cjs/domain/order-transitions.js +0 -52
  10. package/dist/cjs/entities/order.js +0 -551
  11. package/dist/cjs/errors/index.js +0 -6
  12. package/dist/cjs/errors/order.js +0 -41
  13. package/dist/cjs/index.js +0 -8
  14. package/dist/cjs/repositories/index.js +0 -6
  15. package/dist/cjs/repositories/memory.js +0 -69
  16. package/dist/cjs/value-objects/order-id.js +0 -70
  17. /package/dist/{types/contracts → contracts}/address-snapshot.d.ts +0 -0
  18. /package/dist/{esm/contracts → contracts}/address-snapshot.js +0 -0
  19. /package/dist/{types/contracts → contracts}/contact.d.ts +0 -0
  20. /package/dist/{esm/contracts → contracts}/contact.js +0 -0
  21. /package/dist/{types/contracts → contracts}/customer-snapshot.d.ts +0 -0
  22. /package/dist/{esm/contracts → contracts}/customer-snapshot.js +0 -0
  23. /package/dist/{types/contracts → contracts}/item.d.ts +0 -0
  24. /package/dist/{esm/contracts → contracts}/item.js +0 -0
  25. /package/dist/{types/contracts → contracts}/order-repository.d.ts +0 -0
  26. /package/dist/{esm/contracts → contracts}/order-repository.js +0 -0
  27. /package/dist/{types/contracts → contracts}/order.d.ts +0 -0
  28. /package/dist/{esm/contracts → contracts}/order.js +0 -0
  29. /package/dist/{types/contracts → contracts}/payment-snapshot.d.ts +0 -0
  30. /package/dist/{esm/contracts → contracts}/payment-snapshot.js +0 -0
  31. /package/dist/{types/domain → domain}/order-transitions.d.ts +0 -0
  32. /package/dist/{esm/domain → domain}/order-transitions.js +0 -0
  33. /package/dist/{types/entities → entities}/order.d.ts +0 -0
  34. /package/dist/{esm/entities → entities}/order.js +0 -0
  35. /package/dist/{types/errors → errors}/index.d.ts +0 -0
  36. /package/dist/{esm/errors → errors}/index.js +0 -0
  37. /package/dist/{types/errors → errors}/order.d.ts +0 -0
  38. /package/dist/{esm/errors → errors}/order.js +0 -0
  39. /package/dist/{types/index.d.ts → index.d.ts} +0 -0
  40. /package/dist/{esm/index.js → index.js} +0 -0
  41. /package/dist/{types/repositories → repositories}/index.d.ts +0 -0
  42. /package/dist/{esm/repositories → repositories}/index.js +0 -0
  43. /package/dist/{types/repositories → repositories}/memory.d.ts +0 -0
  44. /package/dist/{esm/repositories → repositories}/memory.js +0 -0
  45. /package/dist/{types/value-objects → value-objects}/order-id.d.ts +0 -0
  46. /package/dist/{esm/value-objects → value-objects}/order-id.js +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@comity/order",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "description": "Order domain contracts for Comity commerce modules.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -29,52 +29,33 @@
29
29
  "typescript"
30
30
  ],
31
31
  "files": [
32
- "./dist",
33
- "!./dist/**/*.map"
32
+ "dist",
33
+ "!dist/**/*.map"
34
34
  ],
35
- "main": "./dist/cjs/index.js",
36
- "module": "./dist/esm/index.js",
37
- "types": "./dist/types/index.d.ts",
35
+ "main": "./dist/index.js",
36
+ "types": "./dist/index.d.ts",
38
37
  "exports": {
39
38
  ".": {
40
- "import": {
41
- "types": "./dist/types/index.d.ts",
42
- "default": "./dist/esm/index.js"
43
- },
44
- "require": {
45
- "types": "./dist/types/index.d.ts",
46
- "default": "./dist/cjs/index.js"
47
- }
39
+ "types": "./dist/index.d.ts",
40
+ "default": "./dist/index.js"
48
41
  },
49
42
  "./errors": {
50
- "import": {
51
- "types": "./dist/types/errors/index.d.ts",
52
- "default": "./dist/esm/errors/index.js"
53
- },
54
- "require": {
55
- "types": "./dist/types/errors/index.d.ts",
56
- "default": "./dist/cjs/errors/index.js"
57
- }
43
+ "types": "./dist/errors/index.d.ts",
44
+ "default": "./dist/errors/index.js"
58
45
  },
59
46
  "./repositories": {
60
- "import": {
61
- "types": "./dist/types/repositories/index.d.ts",
62
- "default": "./dist/esm/repositories/index.js"
63
- },
64
- "require": {
65
- "types": "./dist/types/repositories/index.d.ts",
66
- "default": "./dist/cjs/repositories/index.js"
67
- }
47
+ "types": "./dist/repositories/index.d.ts",
48
+ "default": "./dist/repositories/index.js"
68
49
  },
69
50
  "./package.json": "./package.json"
70
51
  },
71
52
  "typesVersions": {
72
53
  "*": {
73
54
  "errors": [
74
- "./dist/types/errors/index.d.ts"
55
+ "./dist/errors/index.d.ts"
75
56
  ],
76
57
  "repositories": [
77
- "./dist/types/repositories/index.d.ts"
58
+ "./dist/repositories/index.d.ts"
78
59
  ]
79
60
  }
80
61
  },
@@ -84,12 +65,12 @@
84
65
  },
85
66
  "sideEffects": false,
86
67
  "dependencies": {
87
- "@comity/organization": "0.9.1",
88
- "@comity/pricing": "0.9.1",
89
- "@comity/primitives": "0.9.1"
68
+ "@comity/organization": "0.9.2",
69
+ "@comity/pricing": "0.9.2",
70
+ "@comity/primitives": "0.9.2"
90
71
  },
91
72
  "devDependencies": {
92
- "@types/node": "^24.19.1",
73
+ "@types/node": "^24.19.2",
93
74
  "typescript": "^5.9.3"
94
75
  },
95
76
  "scripts": {
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=address-snapshot.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=contact.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=customer-snapshot.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=item.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=order-repository.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=order.js.map
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=payment-snapshot.js.map
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.canTransition = canTransition;
4
- exports.transitionOrderStatus = transitionOrderStatus;
5
- const result_1 = require("@comity/primitives/result");
6
- const order_js_1 = require("../errors/order.js");
7
- /**
8
- * Legal transitions for each order status.
9
- *
10
- * - `draft` → `pending` (submit)
11
- * - `pending` → `confirmed` (confirm)
12
- * - `confirmed` → `fulfilled` (fulfill)
13
- * - `draft | pending | confirmed` → `cancelled` (cancel)
14
- *
15
- * `fulfilled` and `cancelled` are terminal: no transition is legal from them.
16
- */
17
- const TRANSITIONS = {
18
- draft: ["pending", "cancelled"],
19
- pending: ["confirmed", "cancelled"],
20
- confirmed: ["fulfilled", "cancelled"],
21
- fulfilled: [],
22
- cancelled: [],
23
- };
24
- /**
25
- * Checks whether a status transition is legal.
26
- *
27
- * @param from - Source status.
28
- * @param to - Target status.
29
- *
30
- * @returns True if the transition is allowed, false otherwise.
31
- */
32
- function canTransition(from, to) {
33
- return TRANSITIONS[from].includes(to);
34
- }
35
- /**
36
- * Applies a status transition.
37
- *
38
- * @param from - Source status.
39
- * @param to - Target status.
40
- *
41
- * @returns The target status, or an `invalid_status_transition` error when the
42
- * transition is not allowed.
43
- */
44
- function transitionOrderStatus(from, to) {
45
- if (!canTransition(from, to)) {
46
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_status_transition", {
47
- details: { from, to },
48
- }));
49
- }
50
- return (0, result_1.success)(to);
51
- }
52
- //# sourceMappingURL=order-transitions.js.map
@@ -1,551 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Order = void 0;
4
- const result_1 = require("@comity/primitives/result");
5
- const time_1 = require("@comity/primitives/time");
6
- const order_transitions_js_1 = require("../domain/order-transitions.js");
7
- const order_js_1 = require("../errors/order.js");
8
- /**
9
- * Returns a defensive copy of a product snapshot so later mutations of the
10
- * input cannot leak into the order.
11
- *
12
- * @param snapshot - The product snapshot to copy.
13
- *
14
- * @returns A defensive copy of the snapshot.
15
- */
16
- function copyProductSnapshot(snapshot) {
17
- /**
18
- * Returns a defensive copy of a variant snapshot.
19
- *
20
- * @param variant - The variant snapshot to copy.
21
- *
22
- * @returns A defensive copy of the variant.
23
- */
24
- const copyVariant = (variant) => ({
25
- ...variant,
26
- ...(variant.attributes !== undefined
27
- ? { attributes: variant.attributes.map((attribute) => ({ ...attribute })) }
28
- : {}),
29
- ...(variant.options !== undefined
30
- ? { options: variant.options.map((option) => ({ ...option })) }
31
- : {}),
32
- });
33
- return {
34
- ...snapshot,
35
- ...(snapshot.attributes !== undefined
36
- ? { attributes: snapshot.attributes.map((attribute) => ({ ...attribute })) }
37
- : {}),
38
- ...(snapshot.options !== undefined
39
- ? { options: snapshot.options.map((option) => ({ ...option })) }
40
- : {}),
41
- ...(snapshot.variant !== undefined ? { variant: copyVariant(snapshot.variant) } : {}),
42
- ...(snapshot.metadata !== undefined ? { metadata: { ...snapshot.metadata } } : {}),
43
- };
44
- }
45
- /**
46
- * Returns a defensive copy of an order item so later mutations of the input
47
- * cannot leak into the order.
48
- *
49
- * @param item - The order item to copy.
50
- *
51
- * @returns A defensive copy of the item.
52
- */
53
- function copyOrderItem(item) {
54
- return {
55
- ...item,
56
- product: copyProductSnapshot(item.product),
57
- ...(item.meta !== undefined ? { meta: { ...item.meta } } : {}),
58
- };
59
- }
60
- /**
61
- * Returns whether a quantity is a valid order item quantity: an integer
62
- * greater than or equal to 1.
63
- *
64
- * @param quantity - The quantity to validate.
65
- *
66
- * @returns `true` when the quantity is a positive integer, otherwise `false`.
67
- */
68
- function isValidItemQuantity(quantity) {
69
- return Number.isInteger(quantity) && quantity >= 1;
70
- }
71
- /**
72
- * Returns a defensive copy of a contact so later mutations of the input cannot
73
- * leak into the order.
74
- *
75
- * @param contact - The contact to copy.
76
- *
77
- * @returns A defensive copy of the contact.
78
- */
79
- function copyContact(contact) {
80
- return { ...contact };
81
- }
82
- /**
83
- * Returns a defensive copy of the buyer fact so later mutations of the input
84
- * cannot leak into the order.
85
- *
86
- * @param customer - The customer fact to copy.
87
- *
88
- * @returns A defensive copy of the customer fact.
89
- */
90
- function copyCustomerSnapshot(customer) {
91
- return {
92
- ...customer,
93
- ...(customer.contacts !== undefined
94
- ? { contacts: customer.contacts.map((contact) => copyContact(contact)) }
95
- : {}),
96
- };
97
- }
98
- /**
99
- * Returns a defensive copy of an address fact so later mutations of the input
100
- * cannot leak into the order.
101
- *
102
- * @param address - The address fact to copy.
103
- *
104
- * @returns A defensive copy of the address fact.
105
- */
106
- function copyAddressSnapshot(address) {
107
- return {
108
- ...address,
109
- lines: [...address.lines],
110
- };
111
- }
112
- /**
113
- * Returns whether a stored address fact and a replacement destination are
114
- * structurally identical.
115
- *
116
- * @param address - The address fact stored on the order.
117
- * @param destination - The replacement destination to compare against.
118
- *
119
- * @returns `true` when every field matches, otherwise `false`.
120
- */
121
- function isSameShippingDestination(address, destination) {
122
- return (address.addressId === destination.addressId &&
123
- address.lines.length === destination.lines.length &&
124
- address.lines.every((line, index) => line === destination.lines[index]) &&
125
- address.city === destination.city &&
126
- address.administrativeArea === destination.administrativeArea &&
127
- address.postalCode === destination.postalCode &&
128
- address.countryCode === destination.countryCode &&
129
- address.capturedAt.epochMilliseconds === destination.capturedAt.epochMilliseconds);
130
- }
131
- /**
132
- * Represents an order entity in the system.
133
- *
134
- * @remark
135
- * An order is a lifecycle aggregate: it owns its status transitions, its line
136
- * items, the applied pricing result, and its historical facts (buyer,
137
- * addresses, payment). It does not validate coupons, does not know promotion
138
- * rules, and does not orchestrate external services — those concerns belong
139
- * to `@comity/pricing`, other Core Modules, and application/domain services.
140
- */
141
- class Order {
142
- #id;
143
- #status;
144
- #items;
145
- #price;
146
- #channelId;
147
- #customer;
148
- #addresses;
149
- #payments;
150
- #meta;
151
- #createdAt;
152
- #updatedAt;
153
- /**
154
- * @param fields - The fields used to create or hydrate the order.
155
- * @param id - The unique identifier of the order, supplied by the caller.
156
- * The Order never generates its own aggregate ID; hydration preserves the
157
- * persisted ID verbatim.
158
- */
159
- constructor(fields, id) {
160
- this.#id = id;
161
- this.#status = fields.status ?? "draft";
162
- this.#items = fields.items.map(copyOrderItem);
163
- this.#price = fields.price;
164
- this.#channelId = fields.channelId;
165
- this.#customer =
166
- fields.customer !== undefined ? copyCustomerSnapshot(fields.customer) : undefined;
167
- this.#addresses =
168
- fields.addresses !== undefined
169
- ? fields.addresses.map((address) => copyAddressSnapshot(address))
170
- : undefined;
171
- this.#payments =
172
- fields.payments !== undefined
173
- ? fields.payments.map((payment) => ({ ...payment }))
174
- : undefined;
175
- this.#meta = fields.meta ? { ...fields.meta } : undefined;
176
- this.#createdAt = fields.createdAt ?? time_1.Instant.now();
177
- this.#updatedAt = fields.updatedAt ?? this.#createdAt;
178
- }
179
- /**
180
- * @returns The unique identifier of the order.
181
- */
182
- get id() {
183
- return this.#id;
184
- }
185
- /**
186
- * @returns The commercial channel through which the order was placed.
187
- */
188
- get channelId() {
189
- return this.#channelId;
190
- }
191
- /**
192
- * @returns The lifecycle status of the order.
193
- */
194
- get status() {
195
- return this.#status;
196
- }
197
- /**
198
- * @returns The order items.
199
- */
200
- get items() {
201
- return this.#items.map(copyOrderItem);
202
- }
203
- /**
204
- * @returns The order price.
205
- */
206
- get price() {
207
- return this.#price;
208
- }
209
- /**
210
- * @returns The historical buyer fact, if captured.
211
- */
212
- get customer() {
213
- return this.#customer !== undefined
214
- ? {
215
- ...this.#customer,
216
- ...(this.#customer.contacts !== undefined
217
- ? { contacts: this.#customer.contacts.map((contact) => ({ ...contact })) }
218
- : {}),
219
- }
220
- : undefined;
221
- }
222
- /**
223
- * @returns The historical address facts, if captured.
224
- */
225
- get addresses() {
226
- return this.#addresses !== undefined
227
- ? this.#addresses.map((address) => ({ ...address, lines: [...address.lines] }))
228
- : undefined;
229
- }
230
- /**
231
- * @returns The historical payment facts, if attached.
232
- */
233
- get payments() {
234
- return this.#payments?.map((payment) => ({ ...payment }));
235
- }
236
- /**
237
- * @returns The custom metadata of the order, if any.
238
- */
239
- get meta() {
240
- return this.#meta ? { ...this.#meta } : undefined;
241
- }
242
- /**
243
- * @returns The timestamp when the order was created.
244
- */
245
- get createdAt() {
246
- return this.#createdAt;
247
- }
248
- /**
249
- * @returns The timestamp when the order was last updated.
250
- */
251
- get updatedAt() {
252
- return this.#updatedAt;
253
- }
254
- /**
255
- * Updates the applied pricing result and metadata.
256
- *
257
- * Status transitions are performed through the domain methods; items are
258
- * mutated through `setItems`/`addItem`/`removeItem`/`updateItemQuantity`.
259
- *
260
- * @param changes - The changes to apply to the order.
261
- */
262
- update(changes) {
263
- if (changes.price !== undefined) {
264
- this.#price = changes.price;
265
- }
266
- if (changes.meta !== undefined) {
267
- this.#meta = { ...changes.meta };
268
- }
269
- this.#updatedAt = time_1.Instant.now();
270
- }
271
- /**
272
- * Appends a historical payment fact to the order.
273
- *
274
- * A payment may be processed after the order is created, so the outcome is
275
- * recorded through a dedicated method rather than the generic update path.
276
- * This records a historical fact only: it performs no payment logic, knows
277
- * no payment module, and does not coordinate, authorize, or capture.
278
- *
279
- * @param snapshot - The payment fact to record.
280
- */
281
- attachPayment(snapshot) {
282
- this.#payments = [...(this.#payments ?? []), { ...snapshot }];
283
- this.#updatedAt = time_1.Instant.now();
284
- }
285
- /**
286
- * Replaces the shipping destination of the order.
287
- *
288
- * Allowed only while the order is `draft | pending`; in later statuses the
289
- * shipping destination is immutable (ADR-018). The order must hold exactly
290
- * one shipping address fact; a missing or ambiguous one is an error rather
291
- * than a guess. A structurally identical destination is a successful no-op
292
- * that leaves timestamps untouched. The operation never reaches the generic
293
- * `update()` path, never touches billing, customer, item, price, or payment
294
- * facts, and records no history: the aggregate retains only the current
295
- * shipping destination.
296
- *
297
- * @param destination - The replacement shipping destination. The address
298
- * role is owned by this operation and is always stored as `"shipping"`.
299
- *
300
- * @returns A result indicating the success or failure of the change.
301
- */
302
- changeShippingDestination(destination) {
303
- if (this.#status !== "draft" && this.#status !== "pending") {
304
- return (0, result_1.failure)(new order_js_1.OrderError("shipping_destination_immutable", {
305
- details: {
306
- orderId: this.#id.toString(),
307
- },
308
- }));
309
- }
310
- const addresses = this.#addresses;
311
- const shipping = (addresses ?? []).filter((address) => address.role === "shipping");
312
- const current = shipping.length === 1 ? shipping[0] : undefined;
313
- if (current === undefined || addresses === undefined) {
314
- return (0, result_1.failure)(new order_js_1.OrderError("ambiguous_shipping_destination", {
315
- details: {
316
- orderId: this.#id.toString(),
317
- },
318
- }));
319
- }
320
- if (isSameShippingDestination(current, destination)) {
321
- return (0, result_1.success)(undefined);
322
- }
323
- this.#addresses = addresses.map((address) => address.role === "shipping"
324
- ? copyAddressSnapshot({ ...destination, role: "shipping" })
325
- : address);
326
- this.#updatedAt = time_1.Instant.now();
327
- return (0, result_1.success)(undefined);
328
- }
329
- /**
330
- * Replaces the entire item collection with the supplied one (ADR-030).
331
- *
332
- * The supplied collection is the complete desired collection: items omitted
333
- * from it are removed, and no merging, appending, or quantity aggregation
334
- * occurs. The supplied order is the resulting order and an empty collection
335
- * is valid. Every entry is validated before any state changes — quantity
336
- * (integer `>= 1`) first, then ID uniqueness against the IDs already seen —
337
- * and the first violation rejects the whole operation, leaving the aggregate
338
- * unchanged. Every successful replacement refreshes `updatedAt`, including
339
- * identical replacements. Supplied item IDs are preserved verbatim and
340
- * caller-owned data is defensively copied. Item mutation is not status-gated.
341
- *
342
- * @param items - The complete desired item collection.
343
- *
344
- * @returns A result indicating the success or failure of the replacement.
345
- */
346
- setItems(items) {
347
- const seen = new Set();
348
- for (const item of items) {
349
- if (!isValidItemQuantity(item.quantity)) {
350
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_quantity", {
351
- details: {
352
- orderId: this.#id.toString(),
353
- itemId: item.id,
354
- field: "quantity",
355
- },
356
- }));
357
- }
358
- if (seen.has(item.id)) {
359
- return (0, result_1.failure)(new order_js_1.OrderError("duplicate_item_id", {
360
- details: {
361
- orderId: this.#id.toString(),
362
- itemId: item.id,
363
- },
364
- }));
365
- }
366
- seen.add(item.id);
367
- }
368
- this.#items = items.map(copyOrderItem);
369
- this.#updatedAt = time_1.Instant.now();
370
- return (0, result_1.success)(undefined);
371
- }
372
- /**
373
- * Appends one item occurrence to the order.
374
- *
375
- * The occurrence ID is supplied by the caller in the input: the Order never
376
- * mints occurrence IDs itself. The ID must be unique within the order —
377
- * appending an already-used ID is rejected so the `setItems` duplicate-ID
378
- * invariant cannot be bypassed through this path. Validation runs before
379
- * any mutation — quantity (integer `>= 1`) first, then ID uniqueness — and
380
- * failures leave the aggregate unchanged. A successful append refreshes
381
- * `updatedAt`. Occurrence IDs carry no product meaning: identical
382
- * product/configuration data may coexist under distinct IDs.
383
- *
384
- * @param input - The item data to add, including the caller-assigned
385
- * occurrence ID.
386
- *
387
- * @returns The created item copy, an `invalid_quantity` error when the
388
- * quantity is not a positive integer, or a `duplicate_item_id` error when
389
- * the ID is already used within the order.
390
- */
391
- addItem(input) {
392
- if (!isValidItemQuantity(input.quantity)) {
393
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_quantity", {
394
- details: {
395
- orderId: this.#id.toString(),
396
- itemId: input.id,
397
- field: "quantity",
398
- },
399
- }));
400
- }
401
- if (this.#items.some((existing) => existing.id === input.id)) {
402
- return (0, result_1.failure)(new order_js_1.OrderError("duplicate_item_id", {
403
- details: {
404
- orderId: this.#id.toString(),
405
- itemId: input.id,
406
- },
407
- }));
408
- }
409
- const item = {
410
- id: input.id,
411
- product: copyProductSnapshot(input.product),
412
- quantity: input.quantity,
413
- price: input.price,
414
- };
415
- this.#items.push(item);
416
- this.#updatedAt = time_1.Instant.now();
417
- return (0, result_1.success)(copyOrderItem(item));
418
- }
419
- /**
420
- * Removes an item from the order.
421
- *
422
- * @param itemId - The order item ID.
423
- *
424
- * @returns A result indicating the success or failure of the removal.
425
- */
426
- removeItem(itemId) {
427
- const index = this.#items.findIndex((item) => item.id === itemId);
428
- if (index === -1) {
429
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_item", {
430
- details: {
431
- orderId: this.#id.toString(),
432
- itemId,
433
- },
434
- }));
435
- }
436
- this.#items.splice(index, 1);
437
- this.#updatedAt = time_1.Instant.now();
438
- return (0, result_1.success)(undefined);
439
- }
440
- /**
441
- * Updates the quantity of an order item.
442
- *
443
- * @param itemId - The order item ID.
444
- * @param quantity - The new quantity.
445
- *
446
- * @returns A result indicating the success or failure of the update.
447
- */
448
- updateItemQuantity(itemId, quantity) {
449
- if (!isValidItemQuantity(quantity)) {
450
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_quantity", {
451
- details: {
452
- orderId: this.#id.toString(),
453
- itemId,
454
- field: "quantity",
455
- },
456
- }));
457
- }
458
- const index = this.#items.findIndex((candidate) => candidate.id === itemId);
459
- if (index === -1) {
460
- return (0, result_1.failure)(new order_js_1.OrderError("invalid_item", {
461
- details: {
462
- orderId: this.#id.toString(),
463
- itemId,
464
- },
465
- }));
466
- }
467
- const current = this.#items[index];
468
- if (current !== undefined) {
469
- this.#items[index] = { ...current, quantity };
470
- this.#updatedAt = time_1.Instant.now();
471
- }
472
- return (0, result_1.success)(undefined);
473
- }
474
- /**
475
- * Submits the order: `draft` → `pending`.
476
- *
477
- * @returns A result indicating the success or failure of the transition.
478
- */
479
- submit() {
480
- return this.#transition("pending");
481
- }
482
- /**
483
- * Confirms the order: `pending` → `confirmed`.
484
- *
485
- * @returns A result indicating the success or failure of the transition.
486
- */
487
- confirm() {
488
- return this.#transition("confirmed");
489
- }
490
- /**
491
- * Fulfills the order: `confirmed` → `fulfilled`.
492
- *
493
- * @returns A result indicating the success or failure of the transition.
494
- */
495
- fulfill() {
496
- return this.#transition("fulfilled");
497
- }
498
- /**
499
- * Cancels the order: `draft | pending | confirmed` → `cancelled`.
500
- *
501
- * @returns A result indicating the success or failure of the transition.
502
- */
503
- cancel() {
504
- return this.#transition("cancelled");
505
- }
506
- /**
507
- * Creates a snapshot of the current state of the order.
508
- *
509
- * @returns A snapshot representing the current state of the order.
510
- */
511
- snapshot() {
512
- return {
513
- id: this.#id,
514
- status: this.#status,
515
- items: this.#items.map(copyOrderItem),
516
- price: this.#price,
517
- channelId: this.#channelId,
518
- ...(this.#customer !== undefined ? { customer: copyCustomerSnapshot(this.#customer) } : {}),
519
- ...(this.#addresses !== undefined
520
- ? { addresses: this.#addresses.map((address) => copyAddressSnapshot(address)) }
521
- : {}),
522
- ...(this.#payments !== undefined
523
- ? {
524
- payments: this.#payments.map((payment) => ({ ...payment })),
525
- }
526
- : {}),
527
- ...(this.#meta !== undefined ? { meta: { ...this.#meta } } : {}),
528
- createdAt: this.#createdAt,
529
- updatedAt: this.#updatedAt,
530
- capturedAt: time_1.Instant.now(),
531
- };
532
- }
533
- /**
534
- * Applies a lifecycle transition through the centralized transition rules.
535
- *
536
- * @param to - The target status.
537
- *
538
- * @returns A result indicating the success or failure of the transition.
539
- */
540
- #transition(to) {
541
- const result = (0, order_transitions_js_1.transitionOrderStatus)(this.#status, to);
542
- if (!result.success) {
543
- return result;
544
- }
545
- this.#status = to;
546
- this.#updatedAt = time_1.Instant.now();
547
- return (0, result_1.success)(undefined);
548
- }
549
- }
550
- exports.Order = Order;
551
- //# sourceMappingURL=order.js.map
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OrderError = void 0;
4
- var order_js_1 = require("./order.js");
5
- Object.defineProperty(exports, "OrderError", { enumerable: true, get: function () { return order_js_1.OrderError; } });
6
- //# sourceMappingURL=index.js.map
@@ -1,41 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OrderError = void 0;
4
- const errors_1 = require("@comity/primitives/errors");
5
- const REASON_MESSAGES = {
6
- invalid_quantity: "Invalid order item quantity",
7
- invalid_item: "Order item not found",
8
- invalid_status_transition: "Invalid order status transition",
9
- shipping_destination_immutable: "Shipping destination cannot be changed in the current order status",
10
- ambiguous_shipping_destination: "Order must contain exactly one shipping destination",
11
- duplicate_item_id: "Duplicate order item identifier",
12
- };
13
- const REASON_HTTP_STATUS = {
14
- invalid_quantity: 400,
15
- invalid_item: 400,
16
- invalid_status_transition: 409,
17
- shipping_destination_immutable: 409,
18
- ambiguous_shipping_destination: 409,
19
- duplicate_item_id: 400,
20
- };
21
- /**
22
- * Order operation error with typed reasons.
23
- */
24
- class OrderError extends errors_1.BaseError {
25
- /** Error code. */
26
- code;
27
- /**
28
- * @param reason - The reason for the order error.
29
- * @param meta - Additional metadata for the error.
30
- */
31
- constructor(reason, meta) {
32
- super(REASON_MESSAGES[reason], {
33
- httpStatus: REASON_HTTP_STATUS[reason],
34
- ...meta,
35
- reason,
36
- });
37
- this.code = `order:${reason}`;
38
- }
39
- }
40
- exports.OrderError = OrderError;
41
- //# sourceMappingURL=order.js.map
package/dist/cjs/index.js DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OrderId = exports.Order = void 0;
4
- var order_js_1 = require("./entities/order.js");
5
- Object.defineProperty(exports, "Order", { enumerable: true, get: function () { return order_js_1.Order; } });
6
- var order_id_js_1 = require("./value-objects/order-id.js");
7
- Object.defineProperty(exports, "OrderId", { enumerable: true, get: function () { return order_id_js_1.OrderId; } });
8
- //# sourceMappingURL=index.js.map
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemoryOrderRepository = void 0;
4
- var memory_js_1 = require("./memory.js");
5
- Object.defineProperty(exports, "MemoryOrderRepository", { enumerable: true, get: function () { return memory_js_1.MemoryOrderRepository; } });
6
- //# sourceMappingURL=index.js.map
@@ -1,69 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemoryOrderRepository = void 0;
4
- const result_1 = require("@comity/primitives/result");
5
- /**
6
- * In-memory implementation of `OrderRepository` for testing and development purposes.
7
- *
8
- * Note: This implementation is not suitable for production use as it does not persist
9
- * sessions and is not shared across multiple instances of the application.
10
- */
11
- class MemoryOrderRepository {
12
- /** Internal storage keyed by tenant + order ID */
13
- #orders = new Map();
14
- #makeKey(tenant, id) {
15
- return `${tenant.toString()}\u0000${id.toString()}`;
16
- }
17
- /**
18
- * @inheritdoc
19
- */
20
- async getById(id, ctx) {
21
- const order = this.#orders.get(this.#makeKey(ctx.tenant, id));
22
- if (!order) {
23
- return (0, result_1.success)(null);
24
- }
25
- return (0, result_1.success)(order);
26
- }
27
- /**
28
- * @inheritdoc
29
- */
30
- async save(order, ctx) {
31
- this.#orders.set(this.#makeKey(ctx.tenant, order.id), order);
32
- return (0, result_1.success)(undefined);
33
- }
34
- /**
35
- * @inheritdoc
36
- */
37
- async search(criteria, ctx) {
38
- const tenantPrefix = `${ctx.tenant.toString()}\u0000`;
39
- const all = [...this.#orders.entries()]
40
- .filter(([key]) => key.startsWith(tenantPrefix))
41
- .map(([, order]) => order);
42
- let filtered = all;
43
- if (criteria?.status !== undefined) {
44
- filtered = filtered.filter((o) => o.status === criteria.status);
45
- }
46
- const limit = criteria?.limit ?? filtered.length;
47
- const offset = criteria?.offset ?? 0;
48
- const items = filtered.slice(offset, offset + limit).map((o) => ({
49
- id: o.id,
50
- status: o.status,
51
- createdAt: o.createdAt,
52
- updatedAt: o.updatedAt,
53
- items: o.items,
54
- price: o.price,
55
- channelId: o.channelId,
56
- ...(o.customer !== undefined ? { customer: o.customer } : {}),
57
- ...(o.addresses !== undefined ? { addresses: o.addresses } : {}),
58
- ...(o.payments !== undefined ? { payments: o.payments } : {}),
59
- ...(o.meta !== undefined ? { meta: o.meta } : {}),
60
- }));
61
- const total = filtered.length;
62
- return (0, result_1.success)({
63
- items,
64
- total,
65
- });
66
- }
67
- }
68
- exports.MemoryOrderRepository = MemoryOrderRepository;
69
- //# sourceMappingURL=memory.js.map
@@ -1,70 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OrderId = void 0;
4
- const result_1 = require("@comity/primitives/result");
5
- const errors_1 = require("@comity/primitives/errors");
6
- /**
7
- * OrderId is a value object that represents the unique identifier of an order.
8
- *
9
- * @remarks
10
- * OrderId is globally unique. The current implementation generates UUIDs.
11
- * The repository uses a composite key of `TenantId + OrderId` as its physical
12
- * storage namespace, but the OrderId itself is globally unique and not scoped
13
- * to a tenant.
14
- */
15
- class OrderId {
16
- #value;
17
- /**
18
- * Creates an OrderId from an identifier string.
19
- *
20
- * The Value Object is always created in a valid state; an empty or
21
- * whitespace-only value yields an `empty` failure instead of throwing.
22
- *
23
- * @param value - The value of the order ID.
24
- *
25
- * @returns The OrderId, or an `empty` error when the value is empty or
26
- * whitespace-only.
27
- */
28
- static create(value) {
29
- if (value.trim().length === 0) {
30
- return (0, result_1.failure)(new errors_1.InvalidIdentifierError("empty", {
31
- details: { kind: "OrderId" },
32
- }));
33
- }
34
- return (0, result_1.success)(new OrderId(value));
35
- }
36
- /**
37
- * @param value - The value of the order ID.
38
- */
39
- constructor(value) {
40
- this.#value = value;
41
- }
42
- /**
43
- * Returns the underlying string value of the order ID.
44
- *
45
- * @returns The underlying identifier.
46
- */
47
- get value() {
48
- return this.#value;
49
- }
50
- /**
51
- * Checks if this OrderId is equal to another OrderId.
52
- *
53
- * @param other - The other OrderId to compare with.
54
- *
55
- * @returns True if the OrderIds are equal, false otherwise.
56
- */
57
- equals(other) {
58
- return this.#value === other.toString();
59
- }
60
- /**
61
- * Returns a string representation of the order ID.
62
- *
63
- * @returns The string representation of the order ID.
64
- */
65
- toString() {
66
- return this.#value;
67
- }
68
- }
69
- exports.OrderId = OrderId;
70
- //# sourceMappingURL=order-id.js.map
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes