@tallyui/pos 5.0.0 → 5.2.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 +209 -12
- package/dist/index.js +437 -55
- package/package.json +6 -6
- package/src/index.ts +5 -4
- package/src/order/types.ts +1 -1
- package/src/outbox/index.ts +1 -0
- package/src/outbox/order-outbox.ts +13 -6
- package/src/outbox/store-settlement.ts +206 -0
- package/src/outbox/use-order-outbox.ts +65 -1
- package/src/pos-order/attention-handled.ts +2 -0
- package/src/pos-order/command.ts +47 -24
- package/src/pos-order/finalize.ts +13 -8
- package/src/pos-order/index.ts +4 -1
- package/src/pos-order/needs-attention.ts +24 -7
- package/src/pos-order/reopen.ts +2 -2
- package/src/pos-order/schema.ts +27 -2
- package/src/pos-order/store-order-left.ts +21 -0
- package/src/pos-order/store-settlement.ts +75 -0
- package/src/pos-order/till-payments.ts +17 -0
- package/src/pos-order/types.ts +26 -0
- package/src/receipt/build-receipt-data.ts +2 -2
- package/src/receipt/reprint.ts +2 -2
- package/src/register/expected.ts +9 -8
- package/src/register/session-store.ts +7 -6
- package/src/reports/adapters.ts +2 -2
- package/src/sale/use-sale.ts +13 -6
- package/src/tax/taxed-lines.ts +8 -0
- package/src/tender/cash-rounding.ts +17 -9
- package/src/tender/index.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.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",
|
|
@@ -35,20 +35,20 @@
|
|
|
35
35
|
"mustache": "^4.2.0"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@tallyui/core": "^5.
|
|
38
|
+
"@tallyui/core": "^5.2.0",
|
|
39
39
|
"react": ">=18",
|
|
40
40
|
"rxdb": "~17.5.0",
|
|
41
41
|
"rxjs": ">=7"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@tallyui/core": "5.
|
|
44
|
+
"@tallyui/core": "5.2.0",
|
|
45
45
|
"@types/react": ">=18",
|
|
46
46
|
"react": "^19.2.4",
|
|
47
47
|
"rxdb": "17.5.0",
|
|
48
48
|
"rxjs": "7.8.2",
|
|
49
|
-
"@tallyui/connector-medusa": "5.
|
|
50
|
-
"@tallyui/connector-woocommerce": "5.
|
|
51
|
-
"@tallyui/database": "5.
|
|
49
|
+
"@tallyui/connector-medusa": "5.2.0",
|
|
50
|
+
"@tallyui/connector-woocommerce": "5.2.0",
|
|
51
|
+
"@tallyui/database": "5.2.0"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"build": "tsup",
|
package/src/index.ts
CHANGED
|
@@ -154,17 +154,18 @@ export type {
|
|
|
154
154
|
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, REGISTER_CLOSING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_CARD_IN_PROGRESS, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
|
|
155
155
|
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
|
|
156
156
|
|
|
157
|
-
export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
157
|
+
export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, storeOrderLeft, canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, settledOnStore, TILL_SESSION_CLOSED, unrecordedLegs, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
158
158
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
159
159
|
export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
160
|
+
export { settledAwayOnStore, tillPayments } from './pos-order';
|
|
160
161
|
export { extrasNotSent, type ExtrasNotSent } from './pos-order';
|
|
161
162
|
export { refundDueOf } from './pos-order';
|
|
162
163
|
export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
|
|
163
164
|
export { ADDRESS_CHANGE_REFUSED, NOTHING_DUE, NOTHING_TO_ROUND_AGAINST, CASH_NOT_PAYABLE, CASH_WAITS_FOR_PAYMENT, CASH_PICK_LIMIT, CASH_SETTLE_LIMIT, CASH_PICK_ENTRIES_MAX, VOID_LATER_CASH_FIRST, PAYMENT_TAKEN, CUSTOMER_RETAX_REFUSED, LINE_EDIT_REFUSED, META_CHANGE_REFUSED, META_INVALID, RESTORE_STALE, TAX_IDS_CHANGE_REFUSED, TAX_IDS_INVALID, type SaleRemoval } from './sale/use-sale';
|
|
164
165
|
export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
|
|
165
|
-
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
166
|
+
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, PosOrderStoreSettlement, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
166
167
|
export type { PosOrderCouponLine } from './pos-order/types';
|
|
167
|
-
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger } from './outbox';
|
|
168
|
+
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger, cancelOnStore, payRestOnStore, reverseOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './outbox';
|
|
168
169
|
export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX, type NeedsAdminAnswer } from './outbox';
|
|
169
170
|
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
170
171
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
@@ -199,7 +200,7 @@ import { minorToDecimal as registerMinorToDecimal } from './register';
|
|
|
199
200
|
/** @deprecated Use `minorToMajor(minor, digits)` from `@tallyui/core`, which also rejects an amount that is not a safe integer. */
|
|
200
201
|
export const minorToDecimal: (minor: number, exponent: number) => string = registerMinorToDecimal;
|
|
201
202
|
export { useRegisterSession, RegisterTenderInProgressError, RegisterSaleSavingError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
|
|
202
|
-
export { cashVoidRefusal, type CashVoidRefusal, nearestPayableCash, roundedPickTarget, remainderEntriesMinor, roundedDue, tenderRounding } from './tender';
|
|
203
|
+
export { cashVoidRefusal, type CashVoidRefusal, nearestPayableCash, roundedPickTarget, remainderEntriesMinor, writeOffLeg, roundedDue, tenderRounding } from './tender';
|
|
203
204
|
export type { TenderRounding } from './tender';
|
|
204
205
|
export { suggestFloat, type FloatSuggestion } from './register';
|
|
205
206
|
export { switchWarnings, handoverSlip } from './register';
|
package/src/order/types.ts
CHANGED
|
@@ -142,7 +142,7 @@ export interface ChargeLine {
|
|
|
142
142
|
amountMinor: number; // integer >= 0, as entered, in the charge's own mode (amountIncludesTax, else the order's; ADR-075)
|
|
143
143
|
taxClass?: string;
|
|
144
144
|
taxStatus: 'taxable' | 'none';
|
|
145
|
-
/** The cashier's mode for this charge (v2 "Amount includes tax"); absent means the order's. Never stored on a finalized order
|
|
145
|
+
/** The cashier's mode for this charge (v2 "Amount includes tax"); absent means the order's. Never stored on a finalized order; a `chargeTaxMode` store keeps it in the stored charge's `entered`. */
|
|
146
146
|
amountIncludesTax?: boolean;
|
|
147
147
|
/** A fee's percentage of the cart (v2 Add Fee "%"): the builder sets `amountMinor` to it on every build. Fees only. Never stored on a finalized order. */
|
|
148
148
|
percent?: number;
|
package/src/outbox/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { createHttpCommandTransport } from './http-transport';
|
|
2
2
|
export type { HttpTransportOptions } from './http-transport';
|
|
3
3
|
export { createOrderOutbox, isRequeueable, isRequeueableOrder } from './order-outbox';
|
|
4
|
+
export { cancelOnStore, payRestOnStore, reverseOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './store-settlement';
|
|
4
5
|
export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
|
|
5
6
|
export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
|
|
6
7
|
export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
|
|
@@ -3,7 +3,7 @@ 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
5
|
import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
|
|
6
|
-
import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
6
|
+
import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, settledOnStore, storeOrderLeft, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
7
7
|
import { freezeSentForm } from '../pos-order/finalize';
|
|
8
8
|
import { countFresh, readFresh } from '../rxdb';
|
|
9
9
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
@@ -26,8 +26,10 @@ export function isRequeueable(code: string | undefined): boolean {
|
|
|
26
26
|
* Whether `requeue()` will send this order again. A rejected order: its code is requeueable, except that a reopened
|
|
27
27
|
* sale (`storeOrderId`) refused with `reopen_required` or `revision_conflict` needs a fresh reopen, not a resend
|
|
28
28
|
* (ADR-090 gate 5). A pending order the outbox could not build as an update (`UPDATE_UNSENDABLE`): yes, it is tried again.
|
|
29
|
+
* An order with a `storeSettlement` (#1101): never; the till is settling its store order instead.
|
|
29
30
|
*/
|
|
30
|
-
export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error'>): boolean {
|
|
31
|
+
export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'storeSettlement'>): boolean {
|
|
32
|
+
if (order.storeSettlement !== undefined) return false;
|
|
31
33
|
return order.syncStatus === 'pending' ? order.error?.code === UPDATE_UNSENDABLE
|
|
32
34
|
: order.syncStatus === 'rejected' && isRequeueable(order.error?.code)
|
|
33
35
|
&& !(order.storeOrderId !== undefined && ['reopen_required', 'revision_conflict'].includes(order.error?.code ?? ''));
|
|
@@ -78,7 +80,8 @@ export interface OrderOutbox {
|
|
|
78
80
|
* Orders isRequeueableOrder refuses are left alone. Resolves to the number requeued. */
|
|
79
81
|
requeue(orderIds?: string[]): Promise<number>;
|
|
80
82
|
/** Removes the rejected order `orderId` from the collection, after any running flush ends. Resolves to true when
|
|
81
|
-
* removed; false, with nothing changed, when the id is unknown
|
|
83
|
+
* removed; false, with nothing changed, when the id is unknown, the order is not rejected, or the store created its
|
|
84
|
+
* order before refusing it (`storeOrderLeft`, #1101). */
|
|
82
85
|
discard(orderId: string): Promise<boolean>;
|
|
83
86
|
/** Watches for pending orders and sends them. */
|
|
84
87
|
start(): void;
|
|
@@ -216,7 +219,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
216
219
|
const refused = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
|
|
217
220
|
const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
|
|
218
221
|
const replaced = replacedOrderIds([...refused, ...successors]);
|
|
219
|
-
|
|
222
|
+
// A refused sale whose store order is settled on the store (#1101) no longer counts.
|
|
223
|
+
const rejected = refused.filter((order) => !replaced.has(order.id) && !settledOnStore(order)).length;
|
|
220
224
|
state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
|
|
221
225
|
}
|
|
222
226
|
|
|
@@ -584,7 +588,9 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
584
588
|
delete data.sentVersion;
|
|
585
589
|
delete data.downgradedFrom;
|
|
586
590
|
// The server ledger stored the rejection under the old id; replaying it returns that rejection.
|
|
587
|
-
//
|
|
591
|
+
// The create push keys on the order's id (the transport's recordId is clientOrderId), which a requeue leaves
|
|
592
|
+
// unchanged; so the resend of a row whose order the store created (storeOrderLeft, #1101) carries that order's
|
|
593
|
+
// clientOrderId again.
|
|
588
594
|
data.commandId = uuidv7();
|
|
589
595
|
data.updatedAt = new Date(now()).toISOString();
|
|
590
596
|
return data;
|
|
@@ -605,7 +611,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
605
611
|
// requeue that won the race leaves its pending order in place.
|
|
606
612
|
await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
607
613
|
// The modifier runs again on a write conflict, so it decides on each run.
|
|
608
|
-
|
|
614
|
+
// A refused sale whose order the store created (storeOrderLeft, #1101) stays: the till settles that order instead.
|
|
615
|
+
commandId = data.syncStatus === 'rejected' && storeOrderLeft(data) === undefined ? data.commandId : undefined;
|
|
609
616
|
if (commandId === undefined) return data;
|
|
610
617
|
data._deleted = true;
|
|
611
618
|
return data;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import type { SettleCancelRequest, SettleOutcome, SettlePayment, SettlePayRequest, SettlePayResult, SettleReverseRequest, SettleReverseResult } from '@tallyui/core';
|
|
2
|
+
import type { RxCollection } from 'rxdb';
|
|
3
|
+
import { outboxLogger } from './logger';
|
|
4
|
+
import { canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, storeOrderLeft, TILL_SESSION_CLOSED, tillPayments, unrecordedLegs, uuidv7, type PosOrder, type PosOrderStoreSettlement } from '../pos-order';
|
|
5
|
+
|
|
6
|
+
const inOpenSession = (order: PosOrder, open: string | undefined) => open !== undefined && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === open);
|
|
7
|
+
function markClosed<T extends PosOrder>(data: T, kind: 'cancel' | 'reverse', at: string, attemptId?: string): T {
|
|
8
|
+
const stored = data.storeSettlement;
|
|
9
|
+
if (stored?.kind === kind && stored.state === 'sending' && (attemptId === undefined || stored.attemptId === attemptId)) {
|
|
10
|
+
data.storeSettlement = { kind, state: 'refused', code: TILL_SESSION_CLOSED, attemptId: stored.attemptId, at, ...(kind === 'reverse' && stored.legs && { legs: stored.legs }) };
|
|
11
|
+
data.updatedAt = at;
|
|
12
|
+
}
|
|
13
|
+
return data;
|
|
14
|
+
}
|
|
15
|
+
async function closedAtLanding(deps: Pick<CancelOnStoreDeps, 'orders' | 'openSessionId'>, kind: 'cancel' | 'reverse', orderId: string, attemptId: string, outcome: SettleOutcome, stamp: () => string) {
|
|
16
|
+
const open = await deps.openSessionId!(), order = await deps.orders.findOne(orderId).exec();
|
|
17
|
+
if (!order || inOpenSession(order, open)) return false;
|
|
18
|
+
await order.incrementalModify((data) => markClosed(data, kind, stamp(), attemptId));
|
|
19
|
+
outboxLogger.warn('The store answered after the till session closed; a manager must settle the order', { orderId, outcome: outcome.kind });
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Store the void command ids before sending; only the same sending attempt can receive the outcome. */
|
|
24
|
+
export async function reverseOnStore(deps: { orders: RxCollection<PosOrder>; reverse(request: SettleReverseRequest): Promise<SettleReverseResult>; now?: () => Date; openSessionId?: CancelOnStoreDeps['openSessionId'] },
|
|
25
|
+
orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
|
|
26
|
+
const stamp = () => (deps.now?.() ?? new Date()).toISOString();
|
|
27
|
+
let request: SettleReverseRequest | undefined;
|
|
28
|
+
const open = deps.openSessionId && await deps.openSessionId();
|
|
29
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
30
|
+
request = undefined;
|
|
31
|
+
if (data._deleted || !canReverseOnStore(data)) return data;
|
|
32
|
+
if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, 'reverse', stamp());
|
|
33
|
+
const stored = data.storeSettlement?.kind === 'reverse' ? data.storeSettlement : undefined;
|
|
34
|
+
const again = stored?.state === 'sending' ? stored : undefined;
|
|
35
|
+
if (again && !again.legs?.length) return data;
|
|
36
|
+
const attemptId = again?.attemptId ?? uuidv7();
|
|
37
|
+
const legs = again?.legs ?? recordedLegs(data).map(({ id }) => stored?.legs?.find((leg) => leg.paymentId === id && leg.done)
|
|
38
|
+
?? { paymentId: id, commandId: uuidv7() });
|
|
39
|
+
const requestLegs = [];
|
|
40
|
+
for (const { paymentId, commandId } of legs) {
|
|
41
|
+
const payment = data.payments.find(({ id }) => id === paymentId);
|
|
42
|
+
if (!payment) return data;
|
|
43
|
+
requestLegs.push({ paymentId, commandId, amountMinor: payment.amountMinor });
|
|
44
|
+
}
|
|
45
|
+
const at = stamp();
|
|
46
|
+
data.storeSettlement = { kind: 'reverse', state: 'sending', attemptId, at, legs };
|
|
47
|
+
data.updatedAt = at;
|
|
48
|
+
request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId, legs: requestLegs };
|
|
49
|
+
return data;
|
|
50
|
+
});
|
|
51
|
+
if (!request) return { kind: 'not_offered' };
|
|
52
|
+
const sent: SettleReverseRequest = request;
|
|
53
|
+
const { outcome, voided } = await deps.reverse(sent);
|
|
54
|
+
if (deps.openSessionId && await closedAtLanding(deps, 'reverse', orderId, sent.attemptId, outcome, stamp)) return { kind: 'not_offered' };
|
|
55
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
56
|
+
const stored = data.storeSettlement;
|
|
57
|
+
if (stored?.kind !== 'reverse' || stored.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
|
|
58
|
+
const legs = (stored.legs ?? []).map((leg) => voided.includes(leg.paymentId) ? { ...leg, done: true } : leg);
|
|
59
|
+
if (outcome.kind === 'retry' && legs.every((leg, index) => leg.done === stored.legs?.[index]?.done)) return data;
|
|
60
|
+
const at = stamp(), base = { kind: 'reverse' as const, attemptId: sent.attemptId, at, legs };
|
|
61
|
+
data.storeSettlement = outcome.kind === 'retry' ? { ...stored, legs }
|
|
62
|
+
: outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
|
|
63
|
+
: outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
|
|
64
|
+
: outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message } : { ...base, state: 'gone' };
|
|
65
|
+
if (outcome.kind !== 'retry') data.updatedAt = at;
|
|
66
|
+
return data;
|
|
67
|
+
});
|
|
68
|
+
return outcome;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface CancelOnStoreDeps {
|
|
72
|
+
orders: RxCollection<PosOrder>;
|
|
73
|
+
/** The connector's cancel, bound to the open store (`RefusedOrderSettlement.cancel`). */
|
|
74
|
+
cancel(request: SettleCancelRequest): Promise<SettleOutcome>;
|
|
75
|
+
/** The open register session's id. When given, the store's answer counts only while the session that took every till payment is still open. */
|
|
76
|
+
openSessionId?: () => string | undefined | Promise<string | undefined>;
|
|
77
|
+
now?: () => Date;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Cancels on the store the order a refused sale left behind (#1101), when `canCancelOnStore` allows it on the stored
|
|
82
|
+
* row; otherwise resolves to `not_offered` and never calls `cancel`. It first stores the attempt as `sending` (keeping
|
|
83
|
+
* the stored `attemptId` of a cancel still `sending`, so a repeat is the same attempt), and only once that write has
|
|
84
|
+
* resolved calls `cancel`. The outcome is written only while the stored settlement is still this attempt's `sending`
|
|
85
|
+
* one; `retry` writes nothing, and a rejected `cancel` leaves the row `sending` and rejects with the same error.
|
|
86
|
+
* `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed. pos_orders is till-local, never
|
|
87
|
+
* pulled from a store, so these writes break no replication rule.
|
|
88
|
+
*/
|
|
89
|
+
export async function cancelOnStore(deps: CancelOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
|
|
90
|
+
const stamp = () => (deps.now?.() ?? new Date()).toISOString();
|
|
91
|
+
let request: SettleCancelRequest | undefined;
|
|
92
|
+
const open = deps.openSessionId && await deps.openSessionId();
|
|
93
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
94
|
+
// The modifier runs again on a write conflict, so it decides on the stored state each run.
|
|
95
|
+
request = undefined;
|
|
96
|
+
if (data._deleted || !canCancelOnStore(data)) return data;
|
|
97
|
+
if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, 'cancel', stamp());
|
|
98
|
+
const stored = data.storeSettlement;
|
|
99
|
+
const attemptId = stored?.kind === 'cancel' && stored.state === 'sending' ? stored.attemptId : uuidv7();
|
|
100
|
+
const at = stamp();
|
|
101
|
+
data.storeSettlement = { kind: 'cancel', state: 'sending', attemptId, at };
|
|
102
|
+
data.updatedAt = at;
|
|
103
|
+
request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId };
|
|
104
|
+
return data;
|
|
105
|
+
});
|
|
106
|
+
if (!request) return { kind: 'not_offered' };
|
|
107
|
+
const sent: SettleCancelRequest = request;
|
|
108
|
+
const outcome = await deps.cancel(sent);
|
|
109
|
+
if (deps.openSessionId && await closedAtLanding(deps, 'cancel', orderId, sent.attemptId, outcome, stamp)) return { kind: 'not_offered' };
|
|
110
|
+
if (outcome.kind === 'retry') {
|
|
111
|
+
outboxLogger.info('Cancelling the store order got no definite answer; it stays sending', { orderId, reason: outcome.reason });
|
|
112
|
+
return outcome;
|
|
113
|
+
}
|
|
114
|
+
if (outcome.kind === 'refused') outboxLogger.warn('The store refused to cancel the order', { orderId, code: outcome.code, message: outcome.message });
|
|
115
|
+
if (outcome.kind === 'changed') {
|
|
116
|
+
outboxLogger.warn('The store order changed; nothing was cancelled', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
|
|
117
|
+
}
|
|
118
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
119
|
+
const stored = data.storeSettlement;
|
|
120
|
+
// A newer attempt, or an answer already written, wins over this one.
|
|
121
|
+
if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
|
|
122
|
+
const at = stamp();
|
|
123
|
+
const base = { kind: 'cancel' as const, attemptId: sent.attemptId, at };
|
|
124
|
+
const settled: PosOrderStoreSettlement = outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
|
|
125
|
+
: outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
|
|
126
|
+
: outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
|
|
127
|
+
: { ...base, state: 'gone' };
|
|
128
|
+
data.storeSettlement = settled;
|
|
129
|
+
data.updatedAt = at;
|
|
130
|
+
return data;
|
|
131
|
+
});
|
|
132
|
+
return outcome;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface PayRestOnStoreDeps {
|
|
136
|
+
orders: RxCollection<PosOrder>;
|
|
137
|
+
/** The connector's pay, bound to the open store (`RefusedOrderSettlement.pay`). */
|
|
138
|
+
pay(request: SettlePayRequest): Promise<SettlePayResult>;
|
|
139
|
+
now?: () => Date;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
type StoredPayment = NonNullable<PosOrderStoreSettlement['payments']>[number];
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Records on the store the legs of a refused sale its part-paid store order is missing (#1101 slice 3), when
|
|
146
|
+
* `canPayRestOnStore` allows it on the stored row; otherwise resolves to `not_offered` and never calls `pay`. No money is
|
|
147
|
+
* taken: each leg of `unrecordedLegs` is sent under a new id (method, amount, and `tenderedMinor` for cash only, never
|
|
148
|
+
* the change), except that a stored pay with one payment per leg keeps its ids, amounts and `done` flags, so the store
|
|
149
|
+
* skips a leg it already holds. It first stores the attempt as `sending` with those ids (a pay still `sending` also keeps
|
|
150
|
+
* its `attemptId`, so a repeat is the same attempt; any other mints a new one), and only once that write has resolved
|
|
151
|
+
* calls `pay`. The answer is written only while the stored settlement is still this attempt's `sending` one: every id in
|
|
152
|
+
* `recorded` is marked `done` whatever the outcome, `retry` keeps `sending`, and a rejected `pay` leaves the row
|
|
153
|
+
* `sending` and rejects with the same error.
|
|
154
|
+
* `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed.
|
|
155
|
+
*/
|
|
156
|
+
export async function payRestOnStore(deps: PayRestOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
|
|
157
|
+
const stamp = () => (deps.now?.() ?? new Date()).toISOString();
|
|
158
|
+
let request: SettlePayRequest | undefined;
|
|
159
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
160
|
+
// The modifier runs again on a write conflict, so it decides on the stored state each run.
|
|
161
|
+
request = undefined;
|
|
162
|
+
if (data._deleted || !canPayRestOnStore(data)) return data;
|
|
163
|
+
const stored = data.storeSettlement;
|
|
164
|
+
const legs = unrecordedLegs(data);
|
|
165
|
+
const again = stored?.kind === 'pay' && stored.payments?.length === legs.length ? stored : undefined;
|
|
166
|
+
const attemptId = again?.state === 'sending' ? again.attemptId : uuidv7();
|
|
167
|
+
const payments: StoredPayment[] = again?.payments ?? legs.map((leg) => ({
|
|
168
|
+
id: uuidv7(), method: leg.method, amountMinor: leg.amountMinor,
|
|
169
|
+
...(leg.method === 'cash' && leg.tenderedMinor !== undefined ? { tenderedMinor: leg.tenderedMinor } : {}),
|
|
170
|
+
}));
|
|
171
|
+
const at = stamp();
|
|
172
|
+
data.storeSettlement = { kind: 'pay', state: 'sending', attemptId, at, payments };
|
|
173
|
+
data.updatedAt = at;
|
|
174
|
+
request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId, currency: data.currency,
|
|
175
|
+
payments: payments.map(({ done: _done, ...payment }) => payment as SettlePayment) };
|
|
176
|
+
return data;
|
|
177
|
+
});
|
|
178
|
+
if (!request) return { kind: 'not_offered' };
|
|
179
|
+
const sent: SettlePayRequest = request;
|
|
180
|
+
const { outcome, recorded } = await deps.pay(sent);
|
|
181
|
+
if (outcome.kind === 'retry') {
|
|
182
|
+
outboxLogger.info('Recording the rest on the store got no definite answer; it stays sending', { orderId, reason: outcome.reason, recorded: recorded.length });
|
|
183
|
+
}
|
|
184
|
+
if (outcome.kind === 'refused') outboxLogger.warn('The store refused to record the rest of the order', { orderId, code: outcome.code, message: outcome.message });
|
|
185
|
+
if (outcome.kind === 'changed') {
|
|
186
|
+
outboxLogger.warn('The store order changed; nothing more was recorded', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
|
|
187
|
+
}
|
|
188
|
+
const done = new Set(recorded);
|
|
189
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
190
|
+
const stored = data.storeSettlement;
|
|
191
|
+
// A newer attempt, or an answer already written, wins over this one.
|
|
192
|
+
if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
|
|
193
|
+
const payments = (stored.payments ?? []).map((payment) => (done.has(payment.id) ? { ...payment, done: true } : payment));
|
|
194
|
+
if (outcome.kind === 'retry' && payments.every((payment, index) => payment.done === stored.payments?.[index]?.done)) return data;
|
|
195
|
+
const at = stamp();
|
|
196
|
+
const base = { kind: 'pay' as const, attemptId: sent.attemptId, at, payments };
|
|
197
|
+
data.storeSettlement = outcome.kind === 'retry' ? { ...stored, payments }
|
|
198
|
+
: outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
|
|
199
|
+
: outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
|
|
200
|
+
: outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
|
|
201
|
+
: { ...base, state: 'gone' };
|
|
202
|
+
data.updatedAt = outcome.kind === 'retry' ? data.updatedAt : at;
|
|
203
|
+
return data;
|
|
204
|
+
});
|
|
205
|
+
return outcome;
|
|
206
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type { OrderCreateEnvelope, OrderUpdateEnvelope } from '@tallyui/core';
|
|
1
|
+
import type { OrderCreateEnvelope, OrderUpdateEnvelope, SettleCancelRequest, SettleOutcome, SettlePayRequest, SettlePayResult, SettleReverseRequest, SettleReverseResult } from '@tallyui/core';
|
|
2
2
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
3
3
|
import type { RxCollection, RxError } from 'rxdb';
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
5
5
|
import { OrderContentMismatchError, sameSale, type PosOrder } from '../pos-order';
|
|
6
6
|
import { watchFresh } from '../rxdb';
|
|
7
7
|
import { createOrderOutbox, refreshOutboxState } from './order-outbox';
|
|
8
|
+
import { cancelOnStore as cancelStoreOrder, payRestOnStore as payStoreRest, reverseOnStore } from './store-settlement';
|
|
8
9
|
import type { CommandTransport, OutboxState } from './types';
|
|
9
10
|
|
|
10
11
|
const idle: OutboxState = { pending: 0, sending: false };
|
|
@@ -12,6 +13,8 @@ const noneStuck: readonly string[] = [];
|
|
|
12
13
|
export { outboxLogger } from './logger';
|
|
13
14
|
|
|
14
15
|
export interface UseOrderOutboxOptions {
|
|
16
|
+
/** The open register session's id. Without it, `cancelOnStore` and `reverseOnStore` resolve to `not_offered`. */
|
|
17
|
+
openSessionId?: () => string | undefined;
|
|
15
18
|
/** Which order store to use (medusapos: the backend's base URL); `null` means no store. A change reopens. */
|
|
16
19
|
storeKey: string | null;
|
|
17
20
|
/** Opens the order store for `storeKey`; `close()` is called when the key or device id changes, or on unmount. */
|
|
@@ -28,6 +31,13 @@ export interface UseOrderOutboxOptions {
|
|
|
28
31
|
onBusy?(busy: boolean): void;
|
|
29
32
|
/** Called when `open` rejects, even if the key has changed since (medusapos: reports storage worker failures). */
|
|
30
33
|
onOpenError?(error: unknown): void;
|
|
34
|
+
/** The settlement of a refused sale's store order (#1101) for `storeKey`: the connector's `cancel` and `pay`, bound to
|
|
35
|
+
* that store. Read on each call, for the open store. */
|
|
36
|
+
storeSettlement?(storeKey: string): {
|
|
37
|
+
cancel?(request: SettleCancelRequest): Promise<SettleOutcome>;
|
|
38
|
+
pay?(request: SettlePayRequest): Promise<SettlePayResult>;
|
|
39
|
+
reverse?(request: SettleReverseRequest): Promise<SettleReverseResult>;
|
|
40
|
+
} | undefined;
|
|
31
41
|
}
|
|
32
42
|
|
|
33
43
|
export interface UseOrderOutboxResult {
|
|
@@ -56,6 +66,20 @@ export interface UseOrderOutboxResult {
|
|
|
56
66
|
requeue(orderIds?: string[]): Promise<number>;
|
|
57
67
|
/** Removes one rejected order (see `OrderOutbox.discard`); resolves to false before the current store is ready. */
|
|
58
68
|
discard(orderId: string): Promise<boolean>;
|
|
69
|
+
/**
|
|
70
|
+
* Cancels on the store the order a refused sale left behind (`cancelOnStore`, #1101), with the `cancel` of
|
|
71
|
+
* `storeSettlement` for the open store, then recounts the outbox state, whether the cancel resolved or rejected.
|
|
72
|
+
* Resolves to `not_offered` before the current store is ready, or when there is no `storeSettlement` or no `cancel`.
|
|
73
|
+
*/
|
|
74
|
+
cancelOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
|
|
75
|
+
/**
|
|
76
|
+
* Records on the store the till's legs a refused sale's part-paid store order is missing (`payRestOnStore`, #1101
|
|
77
|
+
* slice 3), with the `pay` of `storeSettlement` for the open store, then recounts the outbox state, whether the pay
|
|
78
|
+
* resolved or rejected. Resolves to `not_offered` before the current store is ready, or when there is no
|
|
79
|
+
* `storeSettlement` or no `pay`.
|
|
80
|
+
*/
|
|
81
|
+
payRestOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
|
|
82
|
+
reverseOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
|
|
59
83
|
/**
|
|
60
84
|
* The count of `record()` calls not yet settled (resolved or rejected). An app holds sign-out
|
|
61
85
|
* (closing the store) while this is above 0, because a close that lands under a write stuck in
|
|
@@ -135,6 +159,46 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
|
|
|
135
159
|
const opened = current.current;
|
|
136
160
|
return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
|
|
137
161
|
},
|
|
162
|
+
async cancelOnStore(orderId) {
|
|
163
|
+
if (!latest.current.openSessionId) return { kind: 'not_offered' };
|
|
164
|
+
const opened = current.current;
|
|
165
|
+
if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
|
|
166
|
+
const settlement = latest.current.storeSettlement?.(opened.storeKey);
|
|
167
|
+
const cancel = settlement?.cancel?.bind(settlement);
|
|
168
|
+
if (!cancel) return { kind: 'not_offered' };
|
|
169
|
+
try {
|
|
170
|
+
return await cancelStoreOrder({ orders: opened.orders, cancel, openSessionId: () => latest.current.openSessionId?.() }, orderId);
|
|
171
|
+
} finally {
|
|
172
|
+
// A settled row leaves state.rejected: publish it before resolving.
|
|
173
|
+
try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
async payRestOnStore(orderId) {
|
|
177
|
+
const opened = current.current;
|
|
178
|
+
if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
|
|
179
|
+
const settlement = latest.current.storeSettlement?.(opened.storeKey);
|
|
180
|
+
const pay = settlement?.pay?.bind(settlement);
|
|
181
|
+
if (!pay) return { kind: 'not_offered' };
|
|
182
|
+
try {
|
|
183
|
+
return await payStoreRest({ orders: opened.orders, pay }, orderId);
|
|
184
|
+
} finally {
|
|
185
|
+
// A settled row leaves state.rejected: publish it before resolving.
|
|
186
|
+
try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
async reverseOnStore(orderId) {
|
|
190
|
+
if (!latest.current.openSessionId) return { kind: 'not_offered' };
|
|
191
|
+
const opened = current.current;
|
|
192
|
+
if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
|
|
193
|
+
const settlement = latest.current.storeSettlement?.(opened.storeKey);
|
|
194
|
+
const reverse = settlement?.reverse?.bind(settlement);
|
|
195
|
+
if (!reverse) return { kind: 'not_offered' };
|
|
196
|
+
try {
|
|
197
|
+
return await reverseOnStore({ orders: opened.orders, reverse, openSessionId: () => latest.current.openSessionId?.() }, orderId);
|
|
198
|
+
} finally {
|
|
199
|
+
try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
|
|
200
|
+
}
|
|
201
|
+
},
|
|
138
202
|
savesInFlight: savesInFlightCount,
|
|
139
203
|
stuckCommandIds,
|
|
140
204
|
async record(posOrder) {
|
|
@@ -5,6 +5,8 @@ import type { PosOrder } from './types';
|
|
|
5
5
|
* Marks the order `orderId` handled for its current `commandId`, so `needsAttention` leaves it out until a requeue
|
|
6
6
|
* mints a new one (ADR-092 6f, tally-woo 03). Resolves to true when the order is stamped (or already was, for this
|
|
7
7
|
* commandId); false, with nothing changed, when the id is unknown or the order is pending (still the outbox's to settle).
|
|
8
|
+
* The stamp does not hide a refused sale whose order the store created (`storeOrderLeft`, #1101): it is still written
|
|
9
|
+
* and the call still resolves to true, but `needsAttention` keeps that sale.
|
|
8
10
|
*/
|
|
9
11
|
export async function markAttentionHandled(orders: RxCollection<PosOrder>, orderId: string, now?: () => Date): Promise<boolean> {
|
|
10
12
|
const doc = await orders.findOne(orderId).exec();
|
package/src/pos-order/command.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { ORDER_META_KEY_MAX, ORDER_META_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_TAX_IDS_MAX } from '@tallyui/core';
|
|
2
2
|
import type { OrderCreateEnvelope, OrderCreateMeta, OrderCreatePayload, OrderCreateTaxId, OrderUpdateEnvelope, OrderUpdatePayload } from '@tallyui/core';
|
|
3
3
|
import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
|
|
4
|
-
import { woocommerceChargeTaxMinor } from '../order/woocommerce-tax';
|
|
4
|
+
import { woocommerceChargeTaxMinor, woocommerceLine } from '../order/woocommerce-tax';
|
|
5
|
+
import type { LineTaxLine } from '../order/types';
|
|
5
6
|
import type { PosOrder, PosOrderLine } from './types';
|
|
6
7
|
|
|
7
8
|
/** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
|
|
@@ -82,12 +83,22 @@ export const editedSku = (line: PosOrderLine) => !line.custom && line.catalogueS
|
|
|
82
83
|
/**
|
|
83
84
|
* Version 4 (#286): a line's discount made tax-exclusive. An exclusive line's is unchanged; an inclusive line's
|
|
84
85
|
* gross discount D on its amount A becomes `net(A) − net(A − D)`, exact in millionths, rounded half away from zero.
|
|
85
|
-
*
|
|
86
|
+
* A Woo-rounded line with a coupon or a compound rate takes both nets from `woocommerceLine` at its stored rates (#1342):
|
|
87
|
+
* its stored taxLines are after the coupon. Otherwise tax comes from stored taxLines after D, recomputed before a
|
|
88
|
+
* store-priced coupon, and from `taxMicros` before D.
|
|
86
89
|
*/
|
|
87
|
-
function netDiscountMinor(line: PosOrderLine,
|
|
88
|
-
if (!(line.taxInclusive ?? pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
|
|
89
|
-
const
|
|
90
|
+
function netDiscountMinor(line: PosOrderLine, order: Pick<PosOrder, 'pricesIncludeTax' | 'taxRounding' | 'coupons' | 'currency'>): number {
|
|
91
|
+
if (!(line.taxInclusive ?? order.pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
|
|
92
|
+
const woocommerce = order.taxRounding?.granularity === 'woocommerce', stored: readonly LineTaxLine[] = line.taxLines;
|
|
90
93
|
const afterDiscount = line.unitPriceMinor * line.quantity - line.discountMinor;
|
|
94
|
+
if (woocommerce && (order.coupons?.length || stored.some((tax) => tax.compound))) {
|
|
95
|
+
const rates = stored.map((tax, i) => ({ id: i, code: tax.code ?? '', label: '', rate: (tax.ratePpm / 10000).toFixed(4),
|
|
96
|
+
priority: i, compound: tax.compound ?? false, shipping: true }));
|
|
97
|
+
// Only netMicros is read: the net before any coupon, which roundAtSubtotal does not change.
|
|
98
|
+
const net = (minor: number) => BigInt(woocommerceLine(minor, rates, true, order.currency, false).netMicros);
|
|
99
|
+
return roundMicrosToMinor(net(line.unitPriceMinor * line.quantity) - net(afterDiscount));
|
|
100
|
+
}
|
|
101
|
+
const ratePpm = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
|
|
91
102
|
// A store-priced coupon leaves stored taxLines after the coupon; the line discount needs tax before it.
|
|
92
103
|
const taxAfter = !woocommerce && line.netMinor < afterDiscount ? taxMicros(afterDiscount, ratePpm, true)
|
|
93
104
|
: line.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n);
|
|
@@ -120,9 +131,17 @@ function wireNote(note: string | undefined): string | undefined {
|
|
|
120
131
|
return newline === -1 ? undefined : note.slice(newline + 1) || undefined;
|
|
121
132
|
}
|
|
122
133
|
|
|
134
|
+
/** #1341 (ADR-075/076): in Woo rounding a charge goes on the wire at its display row, found by id (the server checks the
|
|
135
|
+
* two are equal); with no such row it goes at its stored amount. Any other rounding sends the stored amount. */
|
|
136
|
+
function wireChargeMinor(order: PosOrder, charge: { id: string; amountMinor: number }, rows?: readonly { id: string; amountMinor: number }[]): number {
|
|
137
|
+
if (order.taxRounding?.granularity !== 'woocommerce') return charge.amountMinor;
|
|
138
|
+
return rows?.find(({ id }) => id === charge.id)?.amountMinor ?? charge.amountMinor;
|
|
139
|
+
}
|
|
140
|
+
|
|
123
141
|
/**
|
|
124
142
|
* Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
|
|
125
|
-
* an order is byte-identical,
|
|
143
|
+
* an order is byte-identical, except that a Woo-rounded order with charge display rows sends each charge at its row
|
|
144
|
+
* (`wireChargeMinor`, #1341) and everything else as stored:
|
|
126
145
|
* `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
|
|
127
146
|
* ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
|
|
128
147
|
* A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
|
|
@@ -184,7 +203,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
|
|
|
184
203
|
const withTaxAddress = version === 8 || (version >= 9 && taxAddress !== undefined);
|
|
185
204
|
const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
|
|
186
205
|
const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : undefined;
|
|
187
|
-
const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order
|
|
206
|
+
const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order) : line.discountMinor);
|
|
188
207
|
for (const coupon of carried) {
|
|
189
208
|
if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
|
|
190
209
|
for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
|
|
@@ -214,23 +233,27 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
|
|
|
214
233
|
...(base === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
|
|
215
234
|
...(base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
|
|
216
235
|
})),
|
|
217
|
-
...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) =>
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
:
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
?
|
|
232
|
-
:
|
|
233
|
-
|
|
236
|
+
...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => {
|
|
237
|
+
const sent = fee.entered?.sent === true ? fee.entered : undefined;
|
|
238
|
+
return { clientFeeId: fee.id, name: fee.name, amountMinor: sent?.amountMinor ?? wireChargeMinor(order, fee, order.display?.fees),
|
|
239
|
+
...(sent ? { amountIncludesTax: sent.amountIncludesTax } : {}), taxStatus: fee.taxStatus,
|
|
240
|
+
...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
|
|
241
|
+
// #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
|
|
242
|
+
taxMinor: order.taxRounding?.granularity === 'woocommerce'
|
|
243
|
+
? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
|
|
244
|
+
: roundMicrosToMinor(BigInt(fee.taxMicros)) };
|
|
245
|
+
}) } : {}),
|
|
246
|
+
...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => {
|
|
247
|
+
const sent = charge.entered?.sent === true ? charge.entered : undefined;
|
|
248
|
+
return { clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
|
|
249
|
+
amountMinor: sent?.amountMinor ?? wireChargeMinor(order, charge, order.display?.shipping),
|
|
250
|
+
...(sent ? { amountIncludesTax: sent.amountIncludesTax } : {}), taxStatus: charge.taxStatus,
|
|
251
|
+
...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
|
|
252
|
+
// #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
|
|
253
|
+
taxMinor: order.taxRounding?.granularity === 'woocommerce'
|
|
254
|
+
? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
|
|
255
|
+
: roundMicrosToMinor(BigInt(charge.taxMicros)) };
|
|
256
|
+
}) } : {}),
|
|
234
257
|
...(base === 6 && redeemable.length ? { coupons: redeemable.map(({ code, couponId, discountMinor, discountTaxMinor, lines }) => ({
|
|
235
258
|
code, couponId, discountMinor, discountTaxMinor,
|
|
236
259
|
...(version >= 9 ? { lines: lines!.map(({ lineId, discountMinor, discountTaxMinor }) =>
|