@nabasolution/commerce 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,852 @@
1
+ import { createId, DEFAULT_TENANT, isValidTenantId, NabaError, normalizeTenantId, roundHalfUp, validatePhone, validatePostalCode } from "@nabasolution/core";
2
+ import { json } from "@nabasolution/runtime";
3
+ const DEFAULT_PRODUCTS = [
4
+ {
5
+ id: "prod_tshirt",
6
+ sku: "NX-TSHIRT",
7
+ name: "NABA Signature T-Shirt",
8
+ description: "Heavyweight organic cotton tee with the NABA mark.",
9
+ price: { amount: 129900, currency: "BDT" }
10
+ },
11
+ {
12
+ id: "prod_hoodie",
13
+ sku: "NX-HOODIE",
14
+ name: "NABA Build Hoodie",
15
+ description: "Brushed-fleece hoodie for long build sessions.",
16
+ price: { amount: 249900, currency: "BDT" }
17
+ },
18
+ {
19
+ id: "prod_cap",
20
+ sku: "NX-CAP",
21
+ name: "NABA Founder Cap",
22
+ description: "Low-profile cap with embroidered wordmark.",
23
+ price: { amount: 89900, currency: "BDT" }
24
+ }
25
+ ];
26
+ export const COMMERCE_SNAPSHOT_VERSION = 2;
27
+ export const COMMERCE_STATE_KEY = "commerce";
28
+ class CommerceServiceImpl {
29
+ country;
30
+ products;
31
+ shippingProviders;
32
+ orders = new Map();
33
+ idempotency = new Map();
34
+ taxEngine;
35
+ inventory;
36
+ payments;
37
+ events;
38
+ accounting;
39
+ persistHook;
40
+ constructor(options) {
41
+ this.country = options.country;
42
+ this.taxEngine = options.taxEngine;
43
+ const seeds = options.seedProducts ?? DEFAULT_PRODUCTS;
44
+ if (seeds.length === 0) {
45
+ throw new NabaError("NO_PRODUCTS", "At least one product seed is required");
46
+ }
47
+ this.products = new Map();
48
+ for (const seed of seeds) {
49
+ if (seed.price.currency !== options.country.currency) {
50
+ throw new NabaError("CURRENCY_MISMATCH", `Product ${seed.id} uses ${seed.price.currency} but country currency is ${options.country.currency}`);
51
+ }
52
+ if (!Number.isInteger(seed.price.amount) || seed.price.amount <= 0) {
53
+ throw new NabaError("INVALID_PRICE", `Product ${seed.id} has an invalid price`);
54
+ }
55
+ this.products.set(seed.id, { ...seed, description: seed.description ?? "" });
56
+ }
57
+ this.shippingProviders = new Map((options.shippingProviders ?? []).map((provider) => [provider.id, provider]));
58
+ }
59
+ bind(inventory, payments, events, accounting) {
60
+ this.inventory = inventory;
61
+ this.payments = payments;
62
+ this.events = events;
63
+ this.accounting = accounting;
64
+ }
65
+ listProducts(tenantId) {
66
+ const tenant = normalizeTenantId(tenantId);
67
+ return [...this.products.values()].map((product) => ({
68
+ ...product,
69
+ price: { ...product.price },
70
+ stock: this.requireInventory().available(product.sku, tenant)
71
+ }));
72
+ }
73
+ listOrders(tenantId) {
74
+ const tenant = normalizeTenantId(tenantId);
75
+ return [...this.orders.values()]
76
+ .filter((order) => order.tenantId === tenant)
77
+ .map(cloneOrder);
78
+ }
79
+ getOrder(id, tenantId) {
80
+ const order = this.scopedOrder(id, tenantId);
81
+ return order ? cloneOrder(order) : undefined;
82
+ }
83
+ async quote(items, shippingProviderId, region, tenantId) {
84
+ const tenant = normalizeTenantId(tenantId);
85
+ const inventory = this.requireInventory();
86
+ const lines = this.validateItems(items);
87
+ let subtotal = 0;
88
+ const quoteLines = [];
89
+ for (const line of lines) {
90
+ const product = this.requireProduct(line.productId);
91
+ const available = inventory.available(product.sku, tenant);
92
+ if (available < line.quantity) {
93
+ throw new NabaError("INSUFFICIENT_STOCK", `Only ${available} unit(s) of ${product.name} available`, { status: 409, details: { productId: product.id, available, requested: line.quantity } });
94
+ }
95
+ const lineTotal = product.price.amount * line.quantity;
96
+ subtotal += lineTotal;
97
+ quoteLines.push({
98
+ productId: product.id,
99
+ sku: product.sku,
100
+ name: product.name,
101
+ quantity: line.quantity,
102
+ unitPrice: { ...product.price },
103
+ lineTotal: { amount: lineTotal, currency: this.country.currency },
104
+ ...(product.taxCategory ? { taxCategory: product.taxCategory } : {})
105
+ });
106
+ }
107
+ const provider = this.resolveShippingProvider(shippingProviderId);
108
+ const shippingAmount = provider
109
+ ? (await provider.quote({
110
+ country: this.country.code,
111
+ subtotal: { amount: subtotal, currency: this.country.currency }
112
+ })).amount
113
+ : { amount: 0, currency: this.country.currency };
114
+ if (shippingAmount.currency !== this.country.currency) {
115
+ throw new NabaError("CURRENCY_MISMATCH", "Shipping quote currency does not match country");
116
+ }
117
+ if (!Number.isInteger(shippingAmount.amount) || shippingAmount.amount < 0) {
118
+ throw new NabaError("INVALID_SHIPPING_QUOTE", "Shipping quote must be a non-negative integer");
119
+ }
120
+ const tax = await this.calculateTaxGroups(quoteLines, region);
121
+ const total = tax.inclusive
122
+ ? subtotal + shippingAmount.amount
123
+ : subtotal + tax.taxAmount + shippingAmount.amount;
124
+ return {
125
+ items: quoteLines,
126
+ subtotal: { amount: subtotal, currency: this.country.currency },
127
+ tax: { amount: tax.taxAmount, currency: this.country.currency },
128
+ shipping: { amount: shippingAmount.amount, currency: this.country.currency },
129
+ total: { amount: total, currency: this.country.currency },
130
+ currency: this.country.currency,
131
+ taxRate: tax.taxRate,
132
+ taxJurisdiction: tax.taxJurisdiction
133
+ };
134
+ }
135
+ async checkout(input) {
136
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
137
+ throw new NabaError("VALIDATION_ERROR", "Request body must be a JSON object", {
138
+ status: 400
139
+ });
140
+ }
141
+ const tenant = normalizeTenantId(input.tenantId);
142
+ const inventory = this.requireInventory();
143
+ const payments = this.requirePayments();
144
+ const idempotencyKey = typeof input.idempotencyKey === "string" ? input.idempotencyKey.trim() : "";
145
+ if (idempotencyKey.length > 0 && (idempotencyKey.length < 8 || idempotencyKey.length > 128)) {
146
+ throw new NabaError("VALIDATION_ERROR", "idempotencyKey must be between 8 and 128 characters", { status: 400 });
147
+ }
148
+ if (idempotencyKey) {
149
+ const existing = this.idempotencyFor(tenant).get(idempotencyKey);
150
+ if (existing) {
151
+ const existingOrder = this.scopedOrder(existing.orderId, tenant);
152
+ const existingPayment = payments.get(existing.paymentId, tenant);
153
+ if (existingOrder && existingPayment) {
154
+ return { order: cloneOrder(existingOrder), payment: existingPayment };
155
+ }
156
+ }
157
+ }
158
+ const items = this.validateItems(input.items ?? []);
159
+ const customer = this.validateCustomer(input.customer ?? {});
160
+ if (!input.paymentProvider) {
161
+ throw new NabaError("VALIDATION_ERROR", "paymentProvider is required", { status: 400 });
162
+ }
163
+ const quote = await this.quote(items, input.shippingProvider, customer.region, tenant);
164
+ const orderId = createId("ord");
165
+ const reservation = inventory.reserve(quote.items.map((item) => ({ sku: item.sku, quantity: item.quantity })), orderId, tenant);
166
+ const now = new Date().toISOString();
167
+ const order = {
168
+ id: orderId,
169
+ tenantId: tenant,
170
+ status: "pending_payment",
171
+ customer,
172
+ items: quote.items,
173
+ totals: quote,
174
+ reservationId: reservation.id,
175
+ createdAt: now,
176
+ updatedAt: now
177
+ };
178
+ this.orders.set(order.id, order);
179
+ try {
180
+ const payment = await payments.create({
181
+ orderId: order.id,
182
+ amount: quote.total,
183
+ provider: input.paymentProvider,
184
+ customer: { name: customer.name, phone: customer.phone, email: customer.email },
185
+ tenantId: tenant
186
+ });
187
+ order.paymentId = payment.id;
188
+ order.updatedAt = new Date().toISOString();
189
+ if (idempotencyKey) {
190
+ this.idempotencyFor(tenant).set(idempotencyKey, {
191
+ orderId: order.id,
192
+ paymentId: payment.id
193
+ });
194
+ }
195
+ this.emit("order.created", {
196
+ orderId: order.id,
197
+ customerId: customer.phone,
198
+ customer,
199
+ totals: quote,
200
+ itemCount: quote.items.reduce((sum, item) => sum + item.quantity, 0),
201
+ paymentId: payment.id
202
+ }, tenant);
203
+ await this.persist();
204
+ return {
205
+ order: cloneOrder(order),
206
+ payment
207
+ };
208
+ }
209
+ catch (error) {
210
+ inventory.release(reservation.id, tenant);
211
+ order.status = "cancelled";
212
+ order.updatedAt = new Date().toISOString();
213
+ await this.persist();
214
+ throw error;
215
+ }
216
+ }
217
+ async verifyPayment(paymentId, tenantId) {
218
+ const tenant = normalizeTenantId(tenantId);
219
+ const payments = this.requirePayments();
220
+ const inventory = this.requireInventory();
221
+ const existing = payments.get(paymentId, tenant);
222
+ if (!existing) {
223
+ throw new NabaError("PAYMENT_NOT_FOUND", `Payment ${paymentId} not found`, { status: 404 });
224
+ }
225
+ const order = this.scopedOrder(existing.orderId, tenant);
226
+ if (!order) {
227
+ throw new NabaError("ORDER_NOT_FOUND", `Order for payment ${paymentId} not found`, {
228
+ status: 404
229
+ });
230
+ }
231
+ if (order.status === "cancelled") {
232
+ throw new NabaError("ORDER_CANCELLED", "Cannot verify payment for a cancelled order", {
233
+ status: 409
234
+ });
235
+ }
236
+ let payment;
237
+ try {
238
+ payment = await payments.verify(paymentId, tenant);
239
+ }
240
+ catch (error) {
241
+ if (order.status === "pending_payment") {
242
+ if (order.reservationId)
243
+ inventory.release(order.reservationId, tenant);
244
+ order.status = "cancelled";
245
+ order.updatedAt = new Date().toISOString();
246
+ this.emit("order.cancelled", {
247
+ orderId: order.id,
248
+ reason: "payment_failed",
249
+ totals: order.totals
250
+ }, tenant);
251
+ await this.persist();
252
+ }
253
+ throw error;
254
+ }
255
+ if (order.status === "pending_payment") {
256
+ await this.confirmFromPayment(payment.id, tenant);
257
+ }
258
+ await this.events?.drain();
259
+ await this.persist();
260
+ const journalId = this.findJournal(order.id, tenant);
261
+ return {
262
+ payment,
263
+ order: cloneOrder(order),
264
+ accounting: { journalId }
265
+ };
266
+ }
267
+ async confirmFromPayment(paymentId, tenantId) {
268
+ const tenant = normalizeTenantId(tenantId);
269
+ const payments = this.requirePayments();
270
+ const payment = payments.get(paymentId, tenant);
271
+ if (!payment)
272
+ return undefined;
273
+ const order = this.scopedOrder(payment.orderId, tenant);
274
+ if (!order)
275
+ return undefined;
276
+ if (order.status !== "pending_payment")
277
+ return cloneOrder(order);
278
+ const inventory = this.requireInventory();
279
+ if (order.reservationId)
280
+ inventory.commit(order.reservationId, tenant);
281
+ order.status = "confirmed";
282
+ order.updatedAt = new Date().toISOString();
283
+ this.emit("order.confirmed", {
284
+ orderId: order.id,
285
+ paymentId: payment.id,
286
+ totals: order.totals,
287
+ customer: order.customer,
288
+ items: order.items
289
+ }, tenant);
290
+ await this.events?.drain();
291
+ await this.persist();
292
+ return cloneOrder(order);
293
+ }
294
+ async cancelFromFailedPayment(paymentId, tenantId) {
295
+ const tenant = normalizeTenantId(tenantId);
296
+ const payment = this.requirePayments().get(paymentId, tenant);
297
+ if (!payment)
298
+ return undefined;
299
+ const order = this.scopedOrder(payment.orderId, tenant);
300
+ if (!order || order.status !== "pending_payment")
301
+ return order;
302
+ const inventory = this.requireInventory();
303
+ if (order.reservationId)
304
+ inventory.release(order.reservationId, tenant);
305
+ order.status = "cancelled";
306
+ order.updatedAt = new Date().toISOString();
307
+ this.emit("order.cancelled", {
308
+ orderId: order.id,
309
+ reason: "payment_failed",
310
+ totals: order.totals
311
+ }, tenant);
312
+ await this.events?.drain();
313
+ await this.persist();
314
+ return cloneOrder(order);
315
+ }
316
+ async cancelOrder(orderId, tenantId) {
317
+ const tenant = normalizeTenantId(tenantId);
318
+ const order = this.scopedOrder(orderId, tenant);
319
+ if (!order) {
320
+ throw new NabaError("ORDER_NOT_FOUND", `Order ${orderId} not found`, { status: 404 });
321
+ }
322
+ if (order.status === "cancelled")
323
+ return cloneOrder(order);
324
+ const inventory = this.requireInventory();
325
+ if (order.status === "pending_payment") {
326
+ if (order.reservationId)
327
+ inventory.release(order.reservationId, tenant);
328
+ }
329
+ else {
330
+ if (order.paymentId && this.payments) {
331
+ try {
332
+ await this.payments.refund(order.paymentId, undefined, tenant);
333
+ }
334
+ catch (error) {
335
+ throw new NabaError("REFUND_FAILED", "The payment could not be refunded; the order was not cancelled", {
336
+ status: 502,
337
+ details: {
338
+ orderId: order.id,
339
+ paymentId: order.paymentId,
340
+ cause: error instanceof Error ? error.message : String(error)
341
+ }
342
+ });
343
+ }
344
+ }
345
+ for (const item of order.items) {
346
+ inventory.restock(item.sku, item.quantity, tenant);
347
+ }
348
+ }
349
+ order.status = "cancelled";
350
+ order.updatedAt = new Date().toISOString();
351
+ this.emit("order.cancelled", {
352
+ orderId: order.id,
353
+ reason: "customer_request",
354
+ totals: order.totals
355
+ }, tenant);
356
+ await this.events?.drain();
357
+ await this.persist();
358
+ return cloneOrder(order);
359
+ }
360
+ setPersistence(hook) {
361
+ this.persistHook = hook;
362
+ }
363
+ /** Capture durable state: orders and scoped idempotency keys. */
364
+ snapshot() {
365
+ const tenants = {};
366
+ for (const order of this.orders.values()) {
367
+ const state = (tenants[order.tenantId] ??= { orders: [], idempotency: {} });
368
+ state.orders.push(cloneOrder(order));
369
+ }
370
+ for (const [tenant, keys] of this.idempotency) {
371
+ const state = (tenants[tenant] ??= { orders: [], idempotency: {} });
372
+ for (const [key, value] of keys) {
373
+ state.idempotency[key] = { orderId: value.orderId, paymentId: value.paymentId };
374
+ }
375
+ }
376
+ return { version: COMMERCE_SNAPSHOT_VERSION, tenants };
377
+ }
378
+ restore(snapshot) {
379
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
380
+ throw corruptSnapshot("expected an object");
381
+ }
382
+ const version = snapshot.version;
383
+ if (version === 1) {
384
+ const legacy = snapshot;
385
+ if (!Array.isArray(legacy.orders))
386
+ throw corruptSnapshot("orders must be an array");
387
+ this.replaceState(new Map([
388
+ [
389
+ DEFAULT_TENANT,
390
+ this.parseTenant(DEFAULT_TENANT, legacy.orders, legacy.idempotency ?? {})
391
+ ]
392
+ ]));
393
+ return;
394
+ }
395
+ if (version !== COMMERCE_SNAPSHOT_VERSION) {
396
+ throw new NabaError("STORE_VERSION_UNSUPPORTED", `Commerce snapshot version ${String(version)} is not supported`, {
397
+ status: 500,
398
+ details: { found: version, supported: COMMERCE_SNAPSHOT_VERSION }
399
+ });
400
+ }
401
+ const data = snapshot;
402
+ if (!isPlainObject(data.tenants))
403
+ throw corruptSnapshot("tenants must be an object");
404
+ const tenants = new Map();
405
+ for (const [tenant, raw] of Object.entries(data.tenants)) {
406
+ if (!isValidTenantId(tenant))
407
+ throw corruptSnapshot(`invalid tenant key "${tenant}"`);
408
+ if (!raw ||
409
+ typeof raw !== "object" ||
410
+ !Array.isArray(raw.orders) ||
411
+ !isPlainObject(raw.idempotency)) {
412
+ throw corruptSnapshot(`invalid state for tenant "${tenant}"`);
413
+ }
414
+ tenants.set(tenant, this.parseTenant(tenant, raw.orders, raw.idempotency));
415
+ }
416
+ this.replaceState(tenants);
417
+ }
418
+ parseTenant(tenant, orders, idempotency) {
419
+ const parsed = new Map();
420
+ for (const raw of orders) {
421
+ const order = this.parseOrder(raw, tenant);
422
+ if (parsed.has(order.id))
423
+ throw corruptSnapshot(`duplicate order ${order.id}`);
424
+ parsed.set(order.id, order);
425
+ }
426
+ const keys = new Map();
427
+ for (const [key, value] of Object.entries(idempotency ?? {})) {
428
+ if (!value ||
429
+ typeof value.orderId !== "string" ||
430
+ typeof value.paymentId !== "string" ||
431
+ !parsed.has(value.orderId)) {
432
+ throw corruptSnapshot("invalid idempotency record");
433
+ }
434
+ keys.set(key, { orderId: value.orderId, paymentId: value.paymentId });
435
+ }
436
+ return { orders: [...parsed.values()], idempotency: keys };
437
+ }
438
+ parseOrder(raw, tenant) {
439
+ const order = raw;
440
+ if (!order ||
441
+ typeof order.id !== "string" ||
442
+ (order.tenantId !== undefined && order.tenantId !== tenant) ||
443
+ !["pending_payment", "confirmed", "cancelled"].includes(order.status) ||
444
+ !Array.isArray(order.items) ||
445
+ !order.customer ||
446
+ typeof order.customer !== "object" ||
447
+ !order.totals ||
448
+ !Array.isArray(order.totals.items) ||
449
+ typeof order.totals.currency !== "string" ||
450
+ !Number.isInteger(order.totals.total?.amount) ||
451
+ !Number.isInteger(order.totals.subtotal?.amount) ||
452
+ !Number.isInteger(order.totals.tax?.amount) ||
453
+ !Number.isInteger(order.totals.shipping?.amount)) {
454
+ throw corruptSnapshot("invalid order record");
455
+ }
456
+ return cloneOrder({ ...order, tenantId: tenant });
457
+ }
458
+ replaceState(tenants) {
459
+ this.orders.clear();
460
+ this.idempotency.clear();
461
+ for (const [tenant, state] of tenants) {
462
+ for (const order of state.orders) {
463
+ if (order.tenantId !== tenant)
464
+ throw corruptSnapshot("order tenant mismatch");
465
+ this.orders.set(order.id, order);
466
+ }
467
+ this.idempotency.set(tenant, state.idempotency);
468
+ }
469
+ }
470
+ idempotencyFor(tenant) {
471
+ let keys = this.idempotency.get(tenant);
472
+ if (!keys) {
473
+ keys = new Map();
474
+ this.idempotency.set(tenant, keys);
475
+ }
476
+ return keys;
477
+ }
478
+ scopedOrder(id, tenantId) {
479
+ const tenant = normalizeTenantId(tenantId);
480
+ const order = this.orders.get(id);
481
+ return order && order.tenantId === tenant ? order : undefined;
482
+ }
483
+ async persist() {
484
+ await this.persistHook?.(this.snapshot());
485
+ }
486
+ findJournal(orderId, tenantId) {
487
+ return (this.accounting
488
+ ?.list(normalizeTenantId(tenantId))
489
+ .find((entry) => entry.reference === orderId)?.id ?? null);
490
+ }
491
+ validateItems(items) {
492
+ if (!Array.isArray(items) || items.length === 0) {
493
+ throw new NabaError("VALIDATION_ERROR", "At least one cart item is required", { status: 400 });
494
+ }
495
+ if (items.length > 50) {
496
+ throw new NabaError("VALIDATION_ERROR", "Too many cart lines", { status: 400 });
497
+ }
498
+ const merged = new Map();
499
+ for (const item of items) {
500
+ if (!item || typeof item.productId !== "string" || !item.productId) {
501
+ throw new NabaError("VALIDATION_ERROR", "Each item requires a productId", { status: 400 });
502
+ }
503
+ if (!Number.isInteger(item.quantity) || item.quantity <= 0 || item.quantity > 100) {
504
+ throw new NabaError("VALIDATION_ERROR", "Quantity must be an integer between 1 and 100", {
505
+ status: 400
506
+ });
507
+ }
508
+ this.requireProduct(item.productId);
509
+ merged.set(item.productId, (merged.get(item.productId) ?? 0) + item.quantity);
510
+ }
511
+ return [...merged].map(([productId, quantity]) => ({ productId, quantity }));
512
+ }
513
+ validateCustomer(customer) {
514
+ const name = String(customer.name ?? "").trim();
515
+ const phone = String(customer.phone ?? "").trim();
516
+ const address = String(customer.address ?? "").trim();
517
+ const postalCode = String(customer.postalCode ?? "").trim();
518
+ const email = customer.email ? String(customer.email).trim() : undefined;
519
+ const region = this.normalizeRegion(customer.region);
520
+ if (name.length < 2) {
521
+ throw new NabaError("VALIDATION_ERROR", "Customer name is required", { status: 400 });
522
+ }
523
+ if (!validatePhone(this.country.code, phone)) {
524
+ throw new NabaError("VALIDATION_ERROR", `A valid ${this.country.name} phone number is required (${this.country.phonePrefix})`, { status: 400, details: { field: "phone" } });
525
+ }
526
+ if (address.length < 5) {
527
+ throw new NabaError("VALIDATION_ERROR", "A delivery address is required", { status: 400 });
528
+ }
529
+ if (!validatePostalCode(this.country.code, postalCode)) {
530
+ throw new NabaError("VALIDATION_ERROR", `A valid ${this.country.name} postal code is required`, { status: 400, details: { field: "postalCode", example: this.country.postalCode.example } });
531
+ }
532
+ if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
533
+ throw new NabaError("VALIDATION_ERROR", "Email address is invalid", { status: 400 });
534
+ }
535
+ return { name, phone, address, postalCode, ...(email ? { email } : {}), ...(region ? { region } : {}) };
536
+ }
537
+ normalizeRegion(region) {
538
+ if (region === undefined || region === null)
539
+ return undefined;
540
+ if (typeof region !== "string") {
541
+ throw new NabaError("VALIDATION_ERROR", "region must be a string", { status: 400 });
542
+ }
543
+ const trimmed = region.trim().toUpperCase();
544
+ if (!trimmed)
545
+ return undefined;
546
+ if (!/^[A-Z0-9-]{1,16}$/.test(trimmed)) {
547
+ throw new NabaError("VALIDATION_ERROR", "region must be 1-16 letters, digits or hyphens", {
548
+ status: 400,
549
+ details: { field: "region" }
550
+ });
551
+ }
552
+ return trimmed;
553
+ }
554
+ /**
555
+ * Tax comes from the injected engine when present (country + region aware),
556
+ * otherwise from the country definition. All amounts stay in integer minor
557
+ * units and are rounded exactly once.
558
+ */
559
+ async calculateTaxGroups(lines, region) {
560
+ const subtotal = lines.reduce((sum, line) => sum + line.lineTotal.amount, 0);
561
+ if (!this.taxEngine)
562
+ return this.calculateTax(subtotal, region);
563
+ const groups = new Map();
564
+ for (const line of lines) {
565
+ const key = line.taxCategory ?? "";
566
+ groups.set(key, (groups.get(key) ?? 0) + line.lineTotal.amount);
567
+ }
568
+ let taxAmount = 0;
569
+ let inclusive = false;
570
+ let jurisdiction = "";
571
+ let weighted = 0;
572
+ for (const [category, amount] of groups) {
573
+ const result = await this.calculateTax(amount, region, category || undefined);
574
+ taxAmount += result.taxAmount;
575
+ weighted += result.taxRate * amount;
576
+ inclusive = result.inclusive;
577
+ if (!jurisdiction)
578
+ jurisdiction = result.taxJurisdiction;
579
+ }
580
+ return {
581
+ taxAmount,
582
+ taxRate: subtotal > 0 ? weighted / subtotal : 0,
583
+ taxJurisdiction: jurisdiction || (this.normalizeRegion(region) ? `${this.country.code}-${this.normalizeRegion(region)}` : this.country.code),
584
+ inclusive
585
+ };
586
+ }
587
+ async calculateTax(subtotal, region, category) {
588
+ const normalizedRegion = this.normalizeRegion(region);
589
+ if (!this.taxEngine) {
590
+ const rate = this.country.tax.rate;
591
+ const inclusive = this.country.tax.inclusive === true;
592
+ const taxAmount = roundHalfUp(inclusive ? subtotal - subtotal / (1 + rate) : subtotal * rate);
593
+ return {
594
+ taxAmount,
595
+ taxRate: rate,
596
+ taxJurisdiction: normalizedRegion
597
+ ? `${this.country.code}-${normalizedRegion}`
598
+ : this.country.code,
599
+ inclusive
600
+ };
601
+ }
602
+ let result;
603
+ try {
604
+ result = await this.taxEngine.calculate({
605
+ country: this.country,
606
+ subtotal: { amount: subtotal, currency: this.country.currency },
607
+ ...(normalizedRegion ? { region: normalizedRegion } : {}),
608
+ ...(category ? { category } : {})
609
+ });
610
+ }
611
+ catch (error) {
612
+ if (error instanceof NabaError)
613
+ throw error;
614
+ throw new NabaError("TAX_ENGINE_ERROR", "Tax calculation failed", {
615
+ status: 500,
616
+ details: { cause: error instanceof Error ? error.message : String(error) }
617
+ });
618
+ }
619
+ if (!result ||
620
+ !Number.isInteger(result.tax?.amount) ||
621
+ result.tax.amount < 0 ||
622
+ result.tax.currency !== this.country.currency ||
623
+ typeof result.rate !== "number" ||
624
+ !Number.isFinite(result.rate)) {
625
+ throw new NabaError("TAX_ENGINE_INVALID", "Tax engine returned an invalid result", {
626
+ status: 500
627
+ });
628
+ }
629
+ return {
630
+ taxAmount: result.tax.amount,
631
+ taxRate: result.rate,
632
+ taxJurisdiction: result.jurisdiction ||
633
+ (normalizedRegion ? `${this.country.code}-${normalizedRegion}` : this.country.code),
634
+ inclusive: result.inclusive === true
635
+ };
636
+ }
637
+ resolveShippingProvider(id) {
638
+ if (id) {
639
+ const provider = this.shippingProviders.get(id);
640
+ if (!provider) {
641
+ throw new NabaError("PROVIDER_NOT_FOUND", `Unknown shipping provider ${id}`, {
642
+ status: 400
643
+ });
644
+ }
645
+ if (!supportsCountry(provider.countries, this.country.code)) {
646
+ throw new NabaError("PROVIDER_COUNTRY_MISMATCH", `${provider.label} does not serve ${this.country.code}`, { status: 400 });
647
+ }
648
+ return provider;
649
+ }
650
+ return [...this.shippingProviders.values()].find((provider) => supportsCountry(provider.countries, this.country.code));
651
+ }
652
+ requireProduct(id) {
653
+ const product = this.products.get(id);
654
+ if (!product) {
655
+ throw new NabaError("PRODUCT_NOT_FOUND", `Product ${id} not found`, { status: 404 });
656
+ }
657
+ return product;
658
+ }
659
+ requireInventory() {
660
+ if (!this.inventory) {
661
+ throw new NabaError("MODULE_NOT_READY", "Inventory module is not registered", { status: 500 });
662
+ }
663
+ return this.inventory;
664
+ }
665
+ requirePayments() {
666
+ if (!this.payments) {
667
+ throw new NabaError("MODULE_NOT_READY", "Payment module is not registered", { status: 500 });
668
+ }
669
+ return this.payments;
670
+ }
671
+ emit(type, data, tenantId) {
672
+ this.events?.publish(type, data, normalizeTenantId(tenantId));
673
+ }
674
+ }
675
+ export function createCommerceModule(options) {
676
+ const service = new CommerceServiceImpl(options);
677
+ const store = options.store;
678
+ return {
679
+ name: "commerce",
680
+ version: "0.1.0",
681
+ service,
682
+ async register(context) {
683
+ if (store) {
684
+ await store.init();
685
+ const snapshot = await store.load(COMMERCE_STATE_KEY);
686
+ if (snapshot !== undefined)
687
+ service.restore(snapshot);
688
+ service.setPersistence((next) => store.save(COMMERCE_STATE_KEY, next));
689
+ }
690
+ const inventory = context.services.tryGet("inventory");
691
+ if (!inventory) {
692
+ throw new NabaError("MODULE_NOT_READY", "Commerce requires the inventory module");
693
+ }
694
+ const payments = context.services.tryGet("payments");
695
+ if (!payments) {
696
+ throw new NabaError("MODULE_NOT_READY", "Commerce requires the payment module");
697
+ }
698
+ const accounting = context.services.tryGet("accounting");
699
+ service.bind(inventory, payments, {
700
+ publish: (type, data, tenantId) => {
701
+ context.events.publish({
702
+ id: createId("evt"),
703
+ type,
704
+ version: 1,
705
+ tenantId: normalizeTenantId(tenantId),
706
+ occurredAt: new Date().toISOString(),
707
+ source: "commerce",
708
+ correlationId: String(data.orderId ?? "commerce"),
709
+ data
710
+ });
711
+ },
712
+ drain: () => context.events.drain()
713
+ }, accounting);
714
+ context.services.set("commerce", service);
715
+ context.events.subscribe("payment.succeeded", async (event) => {
716
+ const data = event.data;
717
+ if (typeof data.paymentId !== "string")
718
+ return;
719
+ await service.confirmFromPayment(data.paymentId, event.tenantId);
720
+ });
721
+ context.events.subscribe("payment.failed", async (event) => {
722
+ const data = event.data;
723
+ if (typeof data.paymentId !== "string")
724
+ return;
725
+ await service.cancelFromFailedPayment(data.paymentId, event.tenantId);
726
+ });
727
+ context.addRoute({
728
+ method: "GET",
729
+ path: "/api/catalog",
730
+ handler: (ctx) => json({ products: service.listProducts(ctx.tenantId ?? DEFAULT_TENANT) })
731
+ });
732
+ context.addRoute({
733
+ method: "GET",
734
+ path: "/api/products/:id",
735
+ handler: (ctx) => {
736
+ const product = service
737
+ .listProducts(ctx.tenantId ?? DEFAULT_TENANT)
738
+ .find((candidate) => candidate.id === ctx.params.id);
739
+ if (!product) {
740
+ throw new NabaError("PRODUCT_NOT_FOUND", "Product not found", { status: 404 });
741
+ }
742
+ return json({ product });
743
+ }
744
+ });
745
+ context.addRoute({
746
+ method: "POST",
747
+ path: "/api/cart/quote",
748
+ handler: async (ctx) => {
749
+ const body = await ctx.json();
750
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
751
+ throw new NabaError("VALIDATION_ERROR", "Request body must be a JSON object", {
752
+ status: 400
753
+ });
754
+ }
755
+ const quote = await service.quote(body.items ?? [], body.shippingProvider, body.region, ctx.tenantId ?? DEFAULT_TENANT);
756
+ return json(quote);
757
+ }
758
+ });
759
+ context.addRoute({
760
+ method: "POST",
761
+ path: "/api/checkout",
762
+ handler: async (ctx) => {
763
+ const body = await ctx.json();
764
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
765
+ throw new NabaError("VALIDATION_ERROR", "Request body must be a JSON object", {
766
+ status: 400
767
+ });
768
+ }
769
+ // The runtime-derived tenant always wins over a body-supplied value.
770
+ const result = await service.checkout({
771
+ ...body,
772
+ tenantId: ctx.tenantId ?? DEFAULT_TENANT
773
+ });
774
+ return json(result, { status: 201 });
775
+ }
776
+ });
777
+ context.addRoute({
778
+ method: "POST",
779
+ path: "/api/payments/:id/verify",
780
+ handler: async (ctx) => {
781
+ const result = await service.verifyPayment(ctx.params.id ?? "", ctx.tenantId ?? DEFAULT_TENANT);
782
+ return json(result);
783
+ }
784
+ });
785
+ context.addRoute({
786
+ method: "POST",
787
+ path: "/api/orders/:id/cancel",
788
+ handler: async (ctx) => {
789
+ const order = await service.cancelOrder(ctx.params.id ?? "", ctx.tenantId ?? DEFAULT_TENANT);
790
+ return json({ order });
791
+ }
792
+ });
793
+ context.addRoute({
794
+ method: "GET",
795
+ path: "/api/orders",
796
+ handler: (ctx) => json({ orders: service.listOrders(ctx.tenantId ?? DEFAULT_TENANT) })
797
+ });
798
+ context.addRoute({
799
+ method: "GET",
800
+ path: "/api/orders/:id",
801
+ handler: (ctx) => {
802
+ const order = service.getOrder(ctx.params.id ?? "", ctx.tenantId ?? DEFAULT_TENANT);
803
+ if (!order) {
804
+ throw new NabaError("ORDER_NOT_FOUND", "Order not found", { status: 404 });
805
+ }
806
+ return json({ order });
807
+ }
808
+ });
809
+ },
810
+ async stop() {
811
+ if (store)
812
+ await store.flush();
813
+ }
814
+ };
815
+ }
816
+ function cloneOrder(order) {
817
+ return {
818
+ ...order,
819
+ customer: { ...order.customer },
820
+ items: order.items.map((item) => ({
821
+ ...item,
822
+ unitPrice: { ...item.unitPrice },
823
+ lineTotal: { ...item.lineTotal }
824
+ })),
825
+ totals: {
826
+ items: order.totals.items.map((item) => ({
827
+ ...item,
828
+ unitPrice: { ...item.unitPrice },
829
+ lineTotal: { ...item.lineTotal }
830
+ })),
831
+ subtotal: { ...order.totals.subtotal },
832
+ tax: { ...order.totals.tax },
833
+ shipping: { ...order.totals.shipping },
834
+ total: { ...order.totals.total },
835
+ currency: order.totals.currency,
836
+ taxRate: order.totals.taxRate,
837
+ taxJurisdiction: order.totals.taxJurisdiction
838
+ }
839
+ };
840
+ }
841
+ function supportsCountry(countries, code) {
842
+ return countries.includes("*") || countries.includes(code);
843
+ }
844
+ function isPlainObject(value) {
845
+ return typeof value === "object" && value !== null && !Array.isArray(value);
846
+ }
847
+ function corruptSnapshot(reason) {
848
+ return new NabaError("STORE_CORRUPT", `Commerce snapshot is corrupt: ${reason}`, {
849
+ status: 500
850
+ });
851
+ }
852
+ //# sourceMappingURL=index.js.map