@tallyui/pos 3.9.1 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +283 -139
- package/dist/index.js +709 -266
- package/package.json +6 -6
- package/src/index.ts +5 -4
- package/src/order/order-builder.ts +27 -10
- package/src/order/order-drafts.ts +3 -3
- package/src/order/types.ts +4 -0
- package/src/order/woocommerce-tax.ts +1 -1
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +14 -6
- package/src/pos-order/__fixtures__/order-create-v6.json +96 -0
- package/src/pos-order/command.ts +19 -7
- package/src/pos-order/finalize.ts +6 -0
- package/src/pos-order/index.ts +3 -1
- package/src/pos-order/needs-attention.ts +4 -0
- package/src/pos-order/reopen.ts +94 -0
- package/src/pos-order/reopened.ts +12 -0
- package/src/pos-order/schema.ts +17 -4
- package/src/pos-order/types.ts +18 -2
- package/src/refund/send-order-refund.ts +1 -1
- package/src/register/session-store.ts +4 -2
- package/src/register/use-register-session.ts +6 -4
- package/src/sale/cart.ts +5 -2
- package/src/sale/discount-codes.ts +34 -0
- package/src/sale/index.ts +3 -0
- package/src/sale/use-sale.ts +78 -2
- package/src/sale/woocommerce/coupon-refetch.ts +40 -0
- package/src/sale/woocommerce/coupon-source.ts +55 -0
- package/src/sale/woocommerce/coupons.ts +41 -0
- package/src/sale/woocommerce/discount-codes.ts +40 -0
- package/src/sale/woocommerce/index.ts +5 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.10.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -28,20 +28,20 @@
|
|
|
28
28
|
"directory": "packages/pos"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@tallyui/core": "^3.
|
|
31
|
+
"@tallyui/core": "^3.10.0",
|
|
32
32
|
"react": ">=18",
|
|
33
33
|
"rxdb": "~17.5.0",
|
|
34
34
|
"rxjs": ">=7"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
|
-
"@tallyui/core": "3.
|
|
37
|
+
"@tallyui/core": "3.10.0",
|
|
38
38
|
"@types/react": ">=18",
|
|
39
39
|
"react": "^19.2.4",
|
|
40
40
|
"rxdb": "17.5.0",
|
|
41
41
|
"rxjs": "7.8.2",
|
|
42
|
-
"@tallyui/connector-medusa": "3.
|
|
43
|
-
"@tallyui/connector-woocommerce": "3.
|
|
44
|
-
"@tallyui/database": "3.
|
|
42
|
+
"@tallyui/connector-medusa": "3.10.0",
|
|
43
|
+
"@tallyui/connector-woocommerce": "3.10.0",
|
|
44
|
+
"@tallyui/database": "3.10.0"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "tsup",
|
package/src/index.ts
CHANGED
|
@@ -59,12 +59,13 @@ export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, Rece
|
|
|
59
59
|
export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory } from './product';
|
|
60
60
|
|
|
61
61
|
// Sale
|
|
62
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel } from './sale';
|
|
63
|
-
export type { SaleStage, CatalogueEntry } from './sale';
|
|
62
|
+
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED } from './sale';
|
|
63
|
+
export type { SaleStage, CatalogueEntry, SaleDiscountCodes, SaleDiscountState } from './sale';
|
|
64
64
|
|
|
65
|
-
export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, sameSale, OrderContentMismatchError } from './pos-order';
|
|
65
|
+
export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
66
|
+
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
66
67
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions } from './pos-order';
|
|
67
|
-
export { createHttpCommandTransport, createOrderOutbox, useOrderOutbox, outboxLogger } from './outbox';
|
|
68
|
+
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, useOrderOutbox, outboxLogger } from './outbox';
|
|
68
69
|
export { createRegisterOutbox, useRegisterOutbox } from './outbox';
|
|
69
70
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
70
71
|
export { createBackendNotFound } from './outbox/backend-not-found';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
2
|
-
import { resolvePrice, woocommerceTax, type woocommerceCoupons, type ProductTraits, type TaxRounding } from '@tallyui/core';
|
|
2
|
+
import { resolvePrice, woocommerceTax, type woocommerceCoupons, type ProductTraits, type ResolvedPrice, type TaxRounding } from '@tallyui/core';
|
|
3
3
|
import type { TaxContext } from '../tax/types';
|
|
4
4
|
import { taxMicros, roundMicrosToMinor, roundedTaxByRate } from '../tax/exact';
|
|
5
5
|
import { taxLogger } from '../tax/tax-provider';
|
|
@@ -62,8 +62,14 @@ export function assertDisplayResidue(residue: number, convertedLines: number, co
|
|
|
62
62
|
if (Math.abs(residue) > bound) throw new Error(`Display residue ${residue} exceeds its bound of ${bound} (ADR-063)`);
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
/** The regular unit price to store with a catalogue line (ADR-077 d3): the base price when on sale, else the price charged. */
|
|
66
|
+
export function regularUnitPriceMinor(resolved: ResolvedPrice): number | undefined {
|
|
67
|
+
return resolved.was === undefined ? resolved.current.amount : resolved.was.taxInclusive === resolved.current.taxInclusive ? resolved.was.amount : undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
65
70
|
export interface OrderCouponContext {
|
|
66
71
|
configs: ReadonlyMap<string, woocommerceCoupons.CouponDiscountConfig>;
|
|
72
|
+
couponIds: ReadonlyMap<string, string>; // lower-case code to the connector's coupon id
|
|
67
73
|
productCategories: ReadonlyMap<number, { id: number }[]>;
|
|
68
74
|
calcDiscountsSequentially: boolean;
|
|
69
75
|
}
|
|
@@ -96,14 +102,15 @@ export interface OrderBuilder {
|
|
|
96
102
|
removePayment(paymentId: string): void;
|
|
97
103
|
setCustomer(customer: CustomerSummary | null): void;
|
|
98
104
|
setNote(note: string): void;
|
|
99
|
-
/** Replaces the coupon codes with their trimmed, lower-case, deduplicated list. */
|
|
100
|
-
setCoupons(codes: readonly string[]): void;
|
|
105
|
+
/** Replaces the coupon codes with their trimmed, lower-case, deduplicated list; a given context replaces the builder's coupon context. */
|
|
106
|
+
setCoupons(codes: readonly string[], context?: OrderCouponContext): void;
|
|
101
107
|
clear(): void;
|
|
102
108
|
getSnapshot(): Order;
|
|
103
109
|
}
|
|
104
110
|
|
|
105
111
|
export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
106
|
-
const { taxContext
|
|
112
|
+
const { taxContext } = options;
|
|
113
|
+
let { couponContext } = options;
|
|
107
114
|
const currency = options.currency.toUpperCase();
|
|
108
115
|
const orderId = options.id ?? uid();
|
|
109
116
|
const woo = taxContext.rounding?.granularity === 'woocommerce' && taxContext.getTaxRates ? taxContext.rounding : undefined;
|
|
@@ -360,6 +367,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
360
367
|
if (unitPrice.currency !== currency) throw new RangeError('Line currency must match ' + currency);
|
|
361
368
|
if (!Number.isInteger(unitPrice.amount)) throw new RangeError('Price must be integer minor units');
|
|
362
369
|
if (!Number.isInteger(quantity) || quantity < 1) throw new RangeError('Quantity must be an integer >= 1');
|
|
370
|
+
if (input.regularUnitPriceMinor !== undefined && (!Number.isInteger(input.regularUnitPriceMinor) || input.regularUnitPriceMinor < 0))
|
|
371
|
+
throw new RangeError('Regular price must be integer minor units >= 0');
|
|
363
372
|
// A rate from the tax class carries the backend's name for it when one is mapped (#287, #288).
|
|
364
373
|
const code = woo || input.taxRates ? undefined : taxContext.getTaxRateCode?.(input.taxClass);
|
|
365
374
|
const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === 'none').taxLines
|
|
@@ -370,6 +379,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
370
379
|
const existing = lineItems.find(
|
|
371
380
|
(li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive
|
|
372
381
|
&& (!woo || li.taxClass === input.taxClass && (li.taxStatus === 'none') === (input.taxStatus === 'none'))
|
|
382
|
+
&& li.regularUnitPriceMinor === input.regularUnitPriceMinor
|
|
373
383
|
&& li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length
|
|
374
384
|
&& li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm),
|
|
375
385
|
);
|
|
@@ -394,6 +404,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
394
404
|
sku: input.sku ?? '',
|
|
395
405
|
imageUrl: input.imageUrl,
|
|
396
406
|
unitPriceMinor: unitPrice.amount,
|
|
407
|
+
...(input.regularUnitPriceMinor !== undefined && !input.custom ? { regularUnitPriceMinor: input.regularUnitPriceMinor } : {}),
|
|
397
408
|
quantity,
|
|
398
409
|
taxLines: taxRates.map((tax) => ({ ...tax, taxMicros: '0' })),
|
|
399
410
|
discounts: [],
|
|
@@ -458,8 +469,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
458
469
|
? traits.getVariants(doc, { currency }).find((variant) => variant.id === opts.variantId) : undefined;
|
|
459
470
|
if (opts?.variantId !== undefined && traits.getVariants && !variant)
|
|
460
471
|
throw new Error(`Unknown variant ${opts.variantId} for product ${productId}`);
|
|
461
|
-
const
|
|
462
|
-
if (!
|
|
472
|
+
const resolved = resolvePrice(variant ? variant.prices : traits.getPrices(doc, { currency }), currency);
|
|
473
|
+
if (!resolved) throw new Error('No price in ' + currency + ' for product ' + productId);
|
|
474
|
+
const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
|
|
463
475
|
return addLine({
|
|
464
476
|
productId,
|
|
465
477
|
variantId: opts?.variantId,
|
|
@@ -467,6 +479,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
467
479
|
sku: variant?.sku ?? traits.getSku(doc),
|
|
468
480
|
imageUrl: traits.getImageUrl(doc),
|
|
469
481
|
unitPrice,
|
|
482
|
+
...(regularPrice !== undefined ? { regularUnitPriceMinor: regularPrice } : {}),
|
|
470
483
|
quantity: opts?.quantity,
|
|
471
484
|
taxClass: traits.getTaxClass?.(doc, opts?.variantId),
|
|
472
485
|
...(traits.getTaxStatus?.(doc, opts?.variantId) === 'none' ? { taxStatus: 'none' as const } : {}),
|
|
@@ -558,15 +571,19 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
558
571
|
emit();
|
|
559
572
|
},
|
|
560
573
|
|
|
561
|
-
setCoupons(codes) {
|
|
574
|
+
setCoupons(codes, context) {
|
|
575
|
+
const nextContext = context ?? couponContext;
|
|
562
576
|
const normalized = [...new Set(codes.map((code) => code.trim().toLowerCase()))];
|
|
563
|
-
if (normalized.length && !
|
|
577
|
+
if (normalized.length && !nextContext) throw new Error('Coupon context is required');
|
|
564
578
|
for (const code of normalized) {
|
|
565
|
-
const config =
|
|
579
|
+
const config = nextContext!.configs.get(code);
|
|
566
580
|
if (!config) throw new RangeError(`Unknown coupon ${code}`);
|
|
567
|
-
//
|
|
581
|
+
// The engine needs the regular price as WCPOS pos_data to find sale lines, which would also reset manual price cuts; lifting this waits (ADR-077 d3).
|
|
568
582
|
if (config.exclude_sale_items) throw new RangeError(`Coupon ${code} excludes sale items`);
|
|
583
|
+
const couponId = nextContext!.couponIds.get(code);
|
|
584
|
+
if (couponId === undefined || couponId === '') throw new RangeError(`Coupon ${code} has no id`);
|
|
569
585
|
}
|
|
586
|
+
if (context) couponContext = context;
|
|
570
587
|
couponCodes = normalized;
|
|
571
588
|
emit();
|
|
572
589
|
},
|
|
@@ -33,11 +33,9 @@ export interface ParkedOrderSummary {
|
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string> {
|
|
36
|
-
// Coupons are not persisted until ADR-077 step (d2).
|
|
37
|
-
const { coupons: _coupons, ...draft } = snapshot;
|
|
38
36
|
await drafts.upsert({
|
|
39
37
|
id: snapshot.id,
|
|
40
|
-
data: JSON.stringify(
|
|
38
|
+
data: JSON.stringify(snapshot),
|
|
41
39
|
customerName: snapshot.customer?.name ?? '',
|
|
42
40
|
itemCount: snapshot.lineItems.length,
|
|
43
41
|
total: snapshot.totalMinor,
|
|
@@ -75,6 +73,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
75
73
|
sku: line.sku,
|
|
76
74
|
imageUrl: line.imageUrl,
|
|
77
75
|
unitPrice: { amount: line.unitPriceMinor, currency, taxInclusive: line.taxInclusive },
|
|
76
|
+
...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
78
77
|
quantity: line.quantity,
|
|
79
78
|
taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
|
|
80
79
|
});
|
|
@@ -101,6 +100,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
101
100
|
});
|
|
102
101
|
}
|
|
103
102
|
|
|
103
|
+
// Coupons are re-applied by the sale with fresh coupon data (ADR-077 d3), never restored from the draft.
|
|
104
104
|
// Restore payments
|
|
105
105
|
for (const payment of saved.payments) {
|
|
106
106
|
builder.addPayment({
|
package/src/order/types.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { Money, TaxRounding } from '@tallyui/core';
|
|
|
2
2
|
|
|
3
3
|
export interface OrderCoupon {
|
|
4
4
|
code: string; // lower-case code
|
|
5
|
+
couponId: string; // the connector's coupon id, as a string
|
|
5
6
|
discountMinor: number; // WooCommerce coupon discount, ex tax, in integer minor units
|
|
6
7
|
discountTaxMinor: number; // its tax, in integer minor units
|
|
7
8
|
}
|
|
@@ -77,6 +78,8 @@ export interface LineItem {
|
|
|
77
78
|
sku: string;
|
|
78
79
|
imageUrl?: string;
|
|
79
80
|
unitPriceMinor: number; // as sold, integer
|
|
81
|
+
/** The catalogue's regular unit price, in the line's own tax mode like unitPriceMinor; absent on custom lines (ADR-077 d3). */
|
|
82
|
+
regularUnitPriceMinor?: number;
|
|
80
83
|
quantity: number; // integer >= 1
|
|
81
84
|
taxLines: LineTaxLine[]; // stacked rates on the same net base (ADR-040)
|
|
82
85
|
discounts: AppliedDiscount[];
|
|
@@ -158,6 +161,7 @@ export interface AddLineInput {
|
|
|
158
161
|
sku?: string;
|
|
159
162
|
imageUrl?: string;
|
|
160
163
|
unitPrice: Money & { taxInclusive?: boolean }; // currency must equal the order currency; taxInclusive wins over the order's pricesIncludeTax
|
|
164
|
+
regularUnitPriceMinor?: number; // the catalogue's regular unit price, integer minor units in unitPrice's tax mode (ADR-077 d3)
|
|
161
165
|
quantity?: number; // default 1
|
|
162
166
|
taxRates?: Array<{ code?: string; ratePpm: number }>; // default: [{ ratePpm: taxContext's rate for taxClass }]
|
|
163
167
|
taxClass?: string; // the product's tax class (ProductTraits.getTaxClass); ignored when taxRates is given
|
|
@@ -77,7 +77,7 @@ export function woocommerceCouponReplay(lines: readonly LineItem[], codes: reado
|
|
|
77
77
|
const taxLines = line.taxLines.map((tax, index) => ({ ...tax, taxMicros: String(Math.round(taxes[index].total * factor * 1e6)) }));
|
|
78
78
|
return { ...line, ...lineAmounts(Number(item.total), taxes, taxLines, dp, roundAtSubtotal, pricesIncludeTax) };
|
|
79
79
|
}),
|
|
80
|
-
coupons: result.couponLines.map((coupon, index) => ({ code: codes[index],
|
|
80
|
+
coupons: result.couponLines.map((coupon, index) => ({ code: codes[index], couponId: context.couponIds.get(codes[index])!,
|
|
81
81
|
discountMinor: Math.round(woocommerceTax.roundHalfUp(Number(coupon.discount), dp) * factor),
|
|
82
82
|
discountTaxMinor: Math.round(woocommerceTax.roundHalfUp(Number(coupon.discount_tax), dp) * factor) })),
|
|
83
83
|
};
|
package/src/outbox/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { createHttpCommandTransport } from './http-transport';
|
|
2
2
|
export type { HttpTransportOptions } from './http-transport';
|
|
3
|
-
export { createOrderOutbox } from './order-outbox';
|
|
3
|
+
export { createOrderOutbox, isRequeueable } from './order-outbox';
|
|
4
4
|
export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
|
|
5
5
|
export { createRegisterOutbox } from './register-outbox';
|
|
6
6
|
export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
|
|
@@ -2,7 +2,7 @@ import type { OrderCreateEnvelope } from '@tallyui/core';
|
|
|
2
2
|
import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
|
|
3
3
|
import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
5
|
-
import { toOrderCreateEnvelope, UnsupportedOrderVersionError, uuidv7, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
5
|
+
import { toOrderCreateEnvelope, UnsupportedOrderVersionError, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
6
6
|
import { freezeSentForm } from '../pos-order/finalize';
|
|
7
7
|
import { countFresh, readFresh } from '../rxdb';
|
|
8
8
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
@@ -13,7 +13,12 @@ const AUTH_FAILURES_BEFORE_PROMPT = 3;
|
|
|
13
13
|
|
|
14
14
|
// Rejections that may hide an order the server already created: resending under a new
|
|
15
15
|
// command id could duplicate it, so requeue() leaves these for manual reconciliation.
|
|
16
|
-
const NOT_REQUEUEABLE = new Set(['idempotency_mismatch']);
|
|
16
|
+
const NOT_REQUEUEABLE = new Set(['idempotency_mismatch', 'coupon_invalid', 'total_mismatch']);
|
|
17
|
+
|
|
18
|
+
/** Whether the outbox resends a rejection with this code. */
|
|
19
|
+
export function isRequeueable(code: string | undefined): boolean {
|
|
20
|
+
return !NOT_REQUEUEABLE.has(code ?? '');
|
|
21
|
+
}
|
|
17
22
|
|
|
18
23
|
// The store's message in the refusal log is cut to this many characters, the cap connectors use for a foreign 426 message.
|
|
19
24
|
const REFUSAL_LOG_MESSAGE_MAX = 200;
|
|
@@ -180,7 +185,10 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
180
185
|
// Retiring them is a separate decision.
|
|
181
186
|
async function updateState(patch: Partial<OutboxState> = {}) {
|
|
182
187
|
const pending = await countFresh(collection, { syncStatus: 'pending' });
|
|
183
|
-
const
|
|
188
|
+
const refused = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
|
|
189
|
+
const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
|
|
190
|
+
const replaced = replacedOrderIds([...refused, ...successors]);
|
|
191
|
+
const rejected = refused.filter((order) => !replaced.has(order.id)).length;
|
|
184
192
|
state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
|
|
185
193
|
}
|
|
186
194
|
|
|
@@ -279,7 +287,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
279
287
|
} catch (cause) {
|
|
280
288
|
// Content that cannot downgrade goes at its required version: the server's refusal rejects it.
|
|
281
289
|
if (!(cause instanceof UnsupportedOrderVersionError)) throw cause;
|
|
282
|
-
envelope = toOrderCreateEnvelope(frozen, deviceId, attempt, { maxVersion: cause.needed
|
|
290
|
+
envelope = toOrderCreateEnvelope(frozen, deviceId, attempt, { maxVersion: cause.needed >= 5 ? cause.needed : 3 });
|
|
283
291
|
}
|
|
284
292
|
// Bounds apply when frozen: persist older tills' sent forms before sending (Front desk, 2026-09-29). A first
|
|
285
293
|
// send's version is stored, awaited, before the batch request leaves, so a crash in between keeps it.
|
|
@@ -459,14 +467,14 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
459
467
|
async requeue(orderIds) {
|
|
460
468
|
const orders = (await readFresh(collection, { selector: { syncStatus: 'rejected',
|
|
461
469
|
...(orderIds ? { id: { $in: orderIds } } : {}) } }))
|
|
462
|
-
.filter((order) =>
|
|
470
|
+
.filter((order) => isRequeueable(order.error?.code));
|
|
463
471
|
let count = 0;
|
|
464
472
|
for (const order of orders) {
|
|
465
473
|
const oldCommandId = order.commandId;
|
|
466
474
|
let changed = false;
|
|
467
475
|
// The modifier sees the stored state, even when findOne's cached result is stale.
|
|
468
476
|
await (await collection.findOne(order.id).exec())?.incrementalModify((data) => {
|
|
469
|
-
changed = data.syncStatus === 'rejected' &&
|
|
477
|
+
changed = data.syncStatus === 'rejected' && isRequeueable(data.error?.code);
|
|
470
478
|
if (!changed) return data;
|
|
471
479
|
data.syncStatus = 'pending';
|
|
472
480
|
delete data.error;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "019f6d2e-7800-7000-8000-000000000005",
|
|
3
|
+
"type": "order.create",
|
|
4
|
+
"version": 6,
|
|
5
|
+
"createdAt": "2026-10-07T10:00:00.000Z",
|
|
6
|
+
"deviceId": "device_golden",
|
|
7
|
+
"attempt": 1,
|
|
8
|
+
"payload": {
|
|
9
|
+
"clientOrderId": "019f6d2e-7800-7000-8000-000000000001",
|
|
10
|
+
"createdAt": "2026-10-07T10:00:00.000Z",
|
|
11
|
+
"currency": "GBP",
|
|
12
|
+
"pricesIncludeTax": false,
|
|
13
|
+
"lines": [
|
|
14
|
+
{
|
|
15
|
+
"clientLineId": "019f6d2e-7800-7000-8000-000000000002",
|
|
16
|
+
"variantId": "1",
|
|
17
|
+
"title": "Item",
|
|
18
|
+
"quantity": 1,
|
|
19
|
+
"unitPriceMinor": 800,
|
|
20
|
+
"regularUnitPriceMinor": 1000,
|
|
21
|
+
"attributes": {
|
|
22
|
+
"Size": "L",
|
|
23
|
+
"Colour": "Red"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"clientLineId": "019f6d2e-7800-7000-8000-000000000003",
|
|
28
|
+
"variantId": "2",
|
|
29
|
+
"title": "Item 2",
|
|
30
|
+
"quantity": 1,
|
|
31
|
+
"unitPriceMinor": 500,
|
|
32
|
+
"regularUnitPriceMinor": 500
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"coupons": [
|
|
36
|
+
{
|
|
37
|
+
"code": "ten",
|
|
38
|
+
"couponId": "303",
|
|
39
|
+
"discountMinor": 130,
|
|
40
|
+
"discountTaxMinor": 26
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
"payments": [
|
|
44
|
+
{
|
|
45
|
+
"clientPaymentId": "019f6d2e-7800-7000-8000-000000000004",
|
|
46
|
+
"method": "cash",
|
|
47
|
+
"amountMinor": 1404,
|
|
48
|
+
"tenderedMinor": 1404,
|
|
49
|
+
"changeMinor": 0
|
|
50
|
+
}
|
|
51
|
+
],
|
|
52
|
+
"subtotalMinor": 1170,
|
|
53
|
+
"taxMinor": 234,
|
|
54
|
+
"totalMinor": 1404,
|
|
55
|
+
"display": {
|
|
56
|
+
"currency": "GBP",
|
|
57
|
+
"exponent": 2,
|
|
58
|
+
"taxInclusive": false,
|
|
59
|
+
"subtotalMinor": 1300,
|
|
60
|
+
"discountMinor": 130,
|
|
61
|
+
"taxMinor": 234,
|
|
62
|
+
"totalMinor": 1404,
|
|
63
|
+
"lines": [
|
|
64
|
+
{
|
|
65
|
+
"clientLineId": "019f6d2e-7800-7000-8000-000000000002",
|
|
66
|
+
"amountMinor": 800,
|
|
67
|
+
"discounts": []
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"clientLineId": "019f6d2e-7800-7000-8000-000000000003",
|
|
71
|
+
"amountMinor": 500,
|
|
72
|
+
"discounts": []
|
|
73
|
+
}
|
|
74
|
+
],
|
|
75
|
+
"orderDiscountMinor": 0,
|
|
76
|
+
"coupons": [
|
|
77
|
+
{
|
|
78
|
+
"code": "ten",
|
|
79
|
+
"amountMinor": 130
|
|
80
|
+
}
|
|
81
|
+
]
|
|
82
|
+
},
|
|
83
|
+
"taxByRate": [
|
|
84
|
+
{
|
|
85
|
+
"ratePpm": 200000,
|
|
86
|
+
"code": "VAT",
|
|
87
|
+
"netMinor": 1170,
|
|
88
|
+
"taxMinor": 234,
|
|
89
|
+
"grossMinor": 1404
|
|
90
|
+
}
|
|
91
|
+
],
|
|
92
|
+
"customer": null,
|
|
93
|
+
"registerId": "register_golden",
|
|
94
|
+
"cashierRef": "cashier_golden"
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/pos-order/command.ts
CHANGED
|
@@ -2,6 +2,9 @@ import type { OrderCreateEnvelope } from '@tallyui/core';
|
|
|
2
2
|
import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
|
|
3
3
|
import type { PosOrder, PosOrderLine } from './types';
|
|
4
4
|
|
|
5
|
+
/** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
|
|
6
|
+
export const ORDER_CREATE_MAX_VERSION = 6 as const;
|
|
7
|
+
|
|
5
8
|
export class UnsupportedOrderVersionError extends Error {
|
|
6
9
|
readonly code = 'UNSUPPORTED_ORDER_VERSION';
|
|
7
10
|
constructor(readonly needed: number, readonly supported: number) {
|
|
@@ -55,9 +58,10 @@ function netDiscountMinor(line: PosOrderLine, pricesIncludeTax: boolean): number
|
|
|
55
58
|
|
|
56
59
|
/**
|
|
57
60
|
* The order.create version an order's stored content makes: 3 with ADR-065's figures, else 2 when its lines are
|
|
58
|
-
* discounted (ADR-062), else 1; fees, shipping or custom lines need 5. Also used by pos_orders v5's migration.
|
|
61
|
+
* discounted (ADR-062), else 1; fees, shipping or custom lines need 5; coupons need 6. Also used by pos_orders v5's migration.
|
|
59
62
|
*/
|
|
60
|
-
export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | 'lines' | 'fees' | 'shipping'>): 1 | 2 | 3 | 5 {
|
|
63
|
+
export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | 'lines' | 'fees' | 'shipping' | 'coupons'>): 1 | 2 | 3 | 5 | 6 {
|
|
64
|
+
if (order.coupons?.length) return 6;
|
|
61
65
|
if (order.fees?.length || order.shipping?.length || order.lines.some((line) => line.custom)) return 5;
|
|
62
66
|
return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
|
|
63
67
|
}
|
|
@@ -68,6 +72,7 @@ export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | '
|
|
|
68
72
|
* `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
|
|
69
73
|
* ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
|
|
70
74
|
* A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
|
|
75
|
+
* Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
|
|
71
76
|
*/
|
|
72
77
|
export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt = 1,
|
|
73
78
|
options?: { maxVersion?: number }): OrderCreateEnvelope {
|
|
@@ -75,6 +80,7 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
|
|
|
75
80
|
const content = contentVersion(order);
|
|
76
81
|
const cap = options?.maxVersion === undefined ? order.sentVersion : Math.min(options.maxVersion, order.sentVersion ?? options.maxVersion);
|
|
77
82
|
if (content === 5 && cap !== undefined && cap < 5) throw new UnsupportedOrderVersionError(5, cap);
|
|
83
|
+
if (content === 6 && cap !== undefined && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
|
|
78
84
|
if (grossMinor > 0 && cap !== undefined && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
|
|
79
85
|
// Version 4 only when the cap allows it (the server advertises 4, and no sentVersion holds the order lower).
|
|
80
86
|
const version = (content === 3 && cap !== undefined && cap >= 4 ? 4
|
|
@@ -87,7 +93,7 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
|
|
|
87
93
|
// These are the pre-#222 customerId and sessionId checks, kept byte-exact so stored orders resend older tills' bytes; don't replace with sendable.
|
|
88
94
|
const customerId = typeof id === 'string' && id.length > 0 && id.length <= 64 ? id : undefined;
|
|
89
95
|
const sessionId = order.sessionId ?? order.lateSessionId;
|
|
90
|
-
const { fees: _fees, shipping: _shipping, ...storedDisplay } = { ...order.display! };
|
|
96
|
+
const { fees: _fees, shipping: _shipping, coupons: _coupons, ...storedDisplay } = { ...order.display! };
|
|
91
97
|
return {
|
|
92
98
|
id: order.commandId, type: 'order.create', version, createdAt: order.createdAt, deviceId, attempt,
|
|
93
99
|
payload: {
|
|
@@ -97,16 +103,21 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
|
|
|
97
103
|
quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
|
|
98
104
|
...(line.taxInclusive !== undefined ? { taxInclusive: line.taxInclusive } : {}),
|
|
99
105
|
...(lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}),
|
|
106
|
+
...(version === 6 && line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
107
|
+
...(version === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
|
|
100
108
|
})),
|
|
101
|
-
...(version
|
|
109
|
+
...(version >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
|
|
102
110
|
clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
|
|
103
111
|
...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(fee.taxMicros)),
|
|
104
112
|
})) } : {}),
|
|
105
|
-
...(version
|
|
113
|
+
...(version >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
|
|
106
114
|
clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
|
|
107
115
|
amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
|
|
108
116
|
...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros)),
|
|
109
117
|
})) } : {}),
|
|
118
|
+
...(version === 6 ? { coupons: order.coupons!.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
|
|
119
|
+
code, couponId, discountMinor, discountTaxMinor,
|
|
120
|
+
})) } : {}),
|
|
110
121
|
payments: order.payments.map((payment) => ({
|
|
111
122
|
clientPaymentId: payment.id, method: payment.method, amountMinor: payment.amountMinor,
|
|
112
123
|
...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor } : {}),
|
|
@@ -120,8 +131,9 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
|
|
|
120
131
|
display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
|
|
121
132
|
clientLineId: lineId, amountMinor, discounts,
|
|
122
133
|
})),
|
|
123
|
-
...(version
|
|
124
|
-
...(version
|
|
134
|
+
...(version >= 5 && order.display!.fees ? { fees: order.display!.fees.map(({ id, amountMinor }) => ({ clientFeeId: id, amountMinor })) } : {}),
|
|
135
|
+
...(version >= 5 && order.display!.shipping ? { shipping: order.display!.shipping.map(({ id, amountMinor }) => ({ clientShippingId: id, amountMinor })) } : {}),
|
|
136
|
+
...(version === 6 && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
|
|
125
137
|
},
|
|
126
138
|
taxByRate: order.taxByRate!.map(({ ratePpm, code, netMinor, amountMinor, grossMinor }) => ({
|
|
127
139
|
ratePpm, ...(code !== undefined ? { code } : {}), netMinor, taxMinor: amountMinor, grossMinor,
|
|
@@ -116,6 +116,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
116
116
|
&& (options.capabilities?.orderCreate ?? 1) < 5) {
|
|
117
117
|
throw new Error("finalize: fees, shipping and custom lines need the store to accept order.create version 5; update the store's TallyUI plugin");
|
|
118
118
|
}
|
|
119
|
+
if (order.coupons?.length && (options.capabilities?.orderCreate ?? 1) < 6) {
|
|
120
|
+
throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
|
|
121
|
+
}
|
|
119
122
|
if (!order.lineItems.length) throw new Error('finalize: no lines');
|
|
120
123
|
// Defence in depth: the builder already clamps every discount to >= 0, so this should never fire.
|
|
121
124
|
if (order.discountMinor < 0
|
|
@@ -165,6 +168,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
165
168
|
...(line.taxClass !== undefined ? { taxClass: line.taxClass } : {}), taxStatus: line.taxStatus ?? 'taxable' } } : {}),
|
|
166
169
|
...(line.taxStatus !== undefined ? { taxStatus: line.taxStatus } : {}),
|
|
167
170
|
name: line.name, sku: line.sku, quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
|
|
171
|
+
...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
168
172
|
discountMinor: line.discountMinor, netMinor: line.netMinor,
|
|
169
173
|
...(order.taxRounding?.granularity === 'woocommerce' ? { netMicros: line.netMicros } : {}),
|
|
170
174
|
taxLines: line.taxLines.map((tax) => ({ ...tax })),
|
|
@@ -242,6 +246,8 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
242
246
|
...(fees?.length ? { fees } : {}), ...(shipping?.length ? { shipping } : {}),
|
|
243
247
|
subtotalMinor: order.subtotalMinor, discountMinor: order.discountMinor,
|
|
244
248
|
taxMinor: order.taxMinor, totalMinor: order.totalMinor, taxRounding,
|
|
249
|
+
...(order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) =>
|
|
250
|
+
({ code, couponId, discountMinor, discountTaxMinor })) } : {}),
|
|
245
251
|
...(display && taxByRate ? { display, taxByRate } : {}),
|
|
246
252
|
customer: order.customer ? { id: order.customer.id, name: order.customer.name,
|
|
247
253
|
...(order.customer.email !== undefined ? { email: order.customer.email } : {}) } : null,
|
package/src/pos-order/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { PosOrderSyncStatus, PosOrderLine, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder } from './types';
|
|
1
|
+
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder } from './types';
|
|
2
2
|
export { uuidv7 } from './uuidv7';
|
|
3
3
|
export { finalizeOrder } from './finalize';
|
|
4
4
|
export type { FinalizeOptions } from './finalize';
|
|
@@ -7,4 +7,6 @@ export { posOrderSchema, posOrderCollection } from './schema';
|
|
|
7
7
|
export { addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger } from './open';
|
|
8
8
|
export { getDeviceId } from './device-id';
|
|
9
9
|
export { needsAttention } from './needs-attention';
|
|
10
|
+
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
|
|
11
|
+
export { isReopened, replacedOrderIds } from './reopened';
|
|
10
12
|
export { sameSale, OrderContentMismatchError } from './same-sale';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { knownWarnings } from '@tallyui/core';
|
|
2
|
+
import { replacedOrderIds } from './reopened';
|
|
2
3
|
import type { PosOrder } from './types';
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -7,11 +8,14 @@ import type { PosOrder } from './types';
|
|
|
7
8
|
* `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
|
|
8
9
|
* A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
|
|
9
10
|
* `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
|
|
11
|
+
* A refused order is left out once its finalized successor is in `orders`.
|
|
10
12
|
*/
|
|
11
13
|
export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
|
|
14
|
+
const replaced = replacedOrderIds(orders);
|
|
12
15
|
return orders.filter((order) => order.syncStatus === 'rejected'
|
|
13
16
|
|| (order.localWarnings?.length ?? 0) > 0
|
|
14
17
|
|| (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
|
|
15
18
|
|| (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
|
|
19
|
+
.filter((order) => !replaced.has(order.id))
|
|
16
20
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
17
21
|
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { RxCollection } from 'rxdb';
|
|
2
|
+
import { createOrderBuilder } from '../order/order-builder';
|
|
3
|
+
import { writeOrderDraft } from '../order/order-drafts';
|
|
4
|
+
import { readSession, type RegisterSessionCollection } from '../register/session-store';
|
|
5
|
+
import { readFresh } from '../rxdb';
|
|
6
|
+
import type { TaxContext } from '../tax/types';
|
|
7
|
+
import { customerRefusal } from './command';
|
|
8
|
+
import type { PosOrder } from './types';
|
|
9
|
+
|
|
10
|
+
export const REOPENABLE_CODES: readonly string[] = ['coupon_invalid', 'total_mismatch'];
|
|
11
|
+
export type ReopenRefusal = 'not_found' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed';
|
|
12
|
+
export class ReopenRefusedOrderError extends Error {
|
|
13
|
+
constructor(readonly orderId: string, readonly reason: ReopenRefusal) {
|
|
14
|
+
super(`Cannot reopen order ${orderId}: ${reason}`);
|
|
15
|
+
this.name = 'ReopenRefusedOrderError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function reopenRefusedOrder(orderId: string, deps: {
|
|
20
|
+
orders: RxCollection<PosOrder>;
|
|
21
|
+
drafts: RxCollection;
|
|
22
|
+
sessions: RegisterSessionCollection;
|
|
23
|
+
taxContext: TaxContext;
|
|
24
|
+
/** The product's tax class from the catalogue (ProductTraits.getTaxClass); undefined falls back to 'standard'. */
|
|
25
|
+
taxClassOf?: (productId: string, variantId?: string) => string | undefined;
|
|
26
|
+
now?: () => Date;
|
|
27
|
+
}): Promise<string> {
|
|
28
|
+
const [order] = await readFresh(deps.orders, { selector: { id: orderId } });
|
|
29
|
+
if (!order) throw new ReopenRefusedOrderError(orderId, 'not_found');
|
|
30
|
+
if (order.syncStatus !== 'rejected') throw new ReopenRefusedOrderError(orderId, 'not_rejected');
|
|
31
|
+
if (!REOPENABLE_CODES.includes(order.error?.code ?? '')) throw new ReopenRefusedOrderError(orderId, 'code_not_reopenable');
|
|
32
|
+
const successors = await readFresh(deps.orders, { selector: { saleId: orderId } });
|
|
33
|
+
if (successors.some((successor) => successor.id !== orderId)) throw new ReopenRefusedOrderError(orderId, 'already_replaced');
|
|
34
|
+
if (order.sessionId) {
|
|
35
|
+
const session = await readSession(deps.sessions, order.sessionId);
|
|
36
|
+
if (!session || session.status !== 'open') throw new ReopenRefusedOrderError(orderId, 'session_closed');
|
|
37
|
+
}
|
|
38
|
+
if (!await deps.drafts.findOne(orderId).exec()) {
|
|
39
|
+
const builder = createOrderBuilder({ currency: order.currency, taxContext: deps.taxContext, id: order.id });
|
|
40
|
+
const converted = order.lines.some((line) => line.taxInclusive !== undefined && line.taxInclusive !== order.pricesIncludeTax);
|
|
41
|
+
const display = order.display && !converted ? order.display : undefined;
|
|
42
|
+
for (const [i, line] of order.lines.entries()) {
|
|
43
|
+
const lineId = builder.addLine({
|
|
44
|
+
productId: line.productId, variantId: line.variantId, name: line.name, sku: line.sku,
|
|
45
|
+
unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
|
|
46
|
+
...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
47
|
+
quantity: line.quantity,
|
|
48
|
+
taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
|
|
49
|
+
...(line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus }
|
|
50
|
+
: { taxClass: deps.taxClassOf?.(line.productId, line.variantId) ?? 'standard', taxStatus: line.taxStatus }),
|
|
51
|
+
});
|
|
52
|
+
if (display) {
|
|
53
|
+
for (const row of display.lines[i].discounts) builder.applyLineDiscount(lineId, {
|
|
54
|
+
type: 'fixed', value: row.amountMinor, ...(row.label !== undefined ? { label: row.label } : {}),
|
|
55
|
+
});
|
|
56
|
+
} else if (line.discountMinor > 0) {
|
|
57
|
+
builder.applyLineDiscount(lineId, { type: 'fixed', value: line.discountMinor, label: 'Discount' });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (display && display.orderDiscountMinor > 0) {
|
|
61
|
+
builder.applyOrderDiscount({ type: 'fixed', value: display.orderDiscountMinor, label: 'Discount' });
|
|
62
|
+
}
|
|
63
|
+
for (const fee of order.fees ?? []) builder.addFee({
|
|
64
|
+
name: fee.name, amountMinor: fee.amountMinor,
|
|
65
|
+
...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
|
|
66
|
+
...(fee.taxStatus !== undefined ? { taxStatus: fee.taxStatus } : {}),
|
|
67
|
+
});
|
|
68
|
+
for (const shipping of order.shipping ?? []) builder.addShipping({
|
|
69
|
+
name: shipping.name, amountMinor: shipping.amountMinor,
|
|
70
|
+
...(shipping.taxClass !== undefined ? { taxClass: shipping.taxClass } : {}),
|
|
71
|
+
...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
|
|
72
|
+
...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
|
|
73
|
+
});
|
|
74
|
+
for (const payment of order.payments) builder.addPayment({
|
|
75
|
+
method: payment.method, amountMinor: payment.amountMinor,
|
|
76
|
+
...(payment.reference !== undefined ? { reference: payment.reference } : {}),
|
|
77
|
+
});
|
|
78
|
+
if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
|
|
79
|
+
builder.setCustomer({ id: order.customer.id, name: order.customer.name,
|
|
80
|
+
...(order.customer.email !== undefined ? { email: order.customer.email } : {}) });
|
|
81
|
+
}
|
|
82
|
+
const prefix = `Refused by the store: ${order.error!.message}`;
|
|
83
|
+
builder.setNote(prefix + (order.note ? '\n' + order.note : ''));
|
|
84
|
+
await writeOrderDraft(deps.drafts, builder.getSnapshot());
|
|
85
|
+
}
|
|
86
|
+
const document = await deps.orders.findOne(orderId).exec();
|
|
87
|
+
await document!.incrementalModify((data) => {
|
|
88
|
+
if (data.syncStatus === 'rejected' && !data.reopenedAt) {
|
|
89
|
+
data.reopenedAt = data.updatedAt = (deps.now?.() ?? new Date()).toISOString();
|
|
90
|
+
}
|
|
91
|
+
return data;
|
|
92
|
+
});
|
|
93
|
+
return orderId;
|
|
94
|
+
}
|