@tallyui/pos 4.1.0 → 5.0.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 +584 -161
- package/dist/index.js +1908 -1077
- package/package.json +7 -6
- package/src/index.ts +17 -10
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +65 -21
- package/src/order/order-drafts.ts +78 -24
- package/src/order/taken-at.ts +5 -0
- package/src/order/types.ts +11 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +2 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +14 -5
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +7 -3
- package/src/pos-order/command.ts +3 -0
- package/src/pos-order/finalize.ts +11 -0
- package/src/pos-order/reopen.ts +11 -2
- package/src/pos-order/schema.ts +7 -2
- package/src/pos-order/types.ts +7 -1
- package/src/print/escpos/bluetooth-sink.ts +114 -0
- package/src/print/escpos/index.ts +4 -0
- package/src/print/escpos/transport.ts +3 -2
- package/src/print/escpos/usb-sink.ts +84 -0
- package/src/print/index.ts +2 -2
- package/src/receipt/build-receipt-data.ts +8 -1
- package/src/receipt/reprint.ts +2 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/template-data.ts +1 -1
- package/src/receipt-template/wcpos/from-orders.ts +5 -1
- package/src/refund/index.ts +1 -0
- package/src/refund/needs-admin-line.ts +6 -0
- package/src/refund/refundable-lines.ts +2 -91
- package/src/refund/send-order-refund.ts +6 -1
- package/src/refund/submit-order-refund.ts +33 -1
- package/src/register/closing.ts +15 -0
- package/src/register/closure-document.ts +13 -5
- package/src/register/closure-figures.ts +83 -0
- package/src/register/document-labels.ts +5 -3
- package/src/register/expected.ts +30 -9
- package/src/register/index.ts +3 -1
- package/src/register/register-adoption.ts +42 -4
- package/src/register/register-document.ts +17 -0
- package/src/register/session-store.ts +48 -12
- package/src/register/use-register-session.ts +53 -20
- package/src/reports/adapters.ts +5 -1
- package/src/reports/index.ts +1 -1
- package/src/reports/sales-figures.ts +33 -6
- package/src/reports/types.ts +3 -1
- package/src/sale/index.ts +1 -1
- package/src/sale/use-sale.ts +321 -135
- package/src/store-orders/index.ts +5 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-orders-in-range.ts +127 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tax/index.ts +1 -0
- package/src/tender/cash-rounding.ts +49 -6
- package/src/tender/index.ts +1 -1
- package/src/tender/payment-legs.ts +5 -0
- package/src/tender/tender-figures.ts +3 -1
- package/src/outbox/types.test-d.ts +0 -27
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.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",
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"src",
|
|
20
20
|
"!src/**/*.test.ts",
|
|
21
21
|
"!src/**/*.test.tsx",
|
|
22
|
+
"!src/**/*.test-d.ts",
|
|
22
23
|
"!src/**/*.test-helper.ts"
|
|
23
24
|
],
|
|
24
25
|
"license": "MIT",
|
|
@@ -34,20 +35,20 @@
|
|
|
34
35
|
"mustache": "^4.2.0"
|
|
35
36
|
},
|
|
36
37
|
"peerDependencies": {
|
|
37
|
-
"@tallyui/core": "^
|
|
38
|
+
"@tallyui/core": "^5.0.0",
|
|
38
39
|
"react": ">=18",
|
|
39
40
|
"rxdb": "~17.5.0",
|
|
40
41
|
"rxjs": ">=7"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
|
-
"@tallyui/core": "
|
|
44
|
+
"@tallyui/core": "5.0.0",
|
|
44
45
|
"@types/react": ">=18",
|
|
45
46
|
"react": "^19.2.4",
|
|
46
47
|
"rxdb": "17.5.0",
|
|
47
48
|
"rxjs": "7.8.2",
|
|
48
|
-
"@tallyui/connector-medusa": "
|
|
49
|
-
"@tallyui/connector-woocommerce": "
|
|
50
|
-
"@tallyui/database": "
|
|
49
|
+
"@tallyui/connector-medusa": "5.0.0",
|
|
50
|
+
"@tallyui/connector-woocommerce": "5.0.0",
|
|
51
|
+
"@tallyui/database": "5.0.0"
|
|
51
52
|
},
|
|
52
53
|
"scripts": {
|
|
53
54
|
"build": "tsup",
|
package/src/index.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type { CurrencyFormat, CurrencyProviderProps } from './currency';
|
|
|
14
14
|
|
|
15
15
|
// Tax
|
|
16
16
|
export { TaxProvider, useTax, taxLogger, taxSettingsForLocation, createTaxContext, saleTaxContexts, taxDerivation } from './tax';
|
|
17
|
-
export { MICROS_PER_MINOR, ratePpmFromPercent, taxMicros, roundMicrosToMinor, computeOrderTax, taxLinesByRate } from './tax';
|
|
17
|
+
export { MICROS_PER_MINOR, ratePpmFromPercent, taxMicros, roundMicrosToMinor, computeOrderTax, taxLinesByRate, taxedLinesFor } from './tax';
|
|
18
18
|
export type { TaxLineInput, OrderTaxTotals, RateTaxLine } from './tax';
|
|
19
19
|
export type { TaxProviderProps } from './tax';
|
|
20
20
|
export type { TaxRateMap, TaxContext, SaleTaxContext } from './tax';
|
|
@@ -50,6 +50,8 @@ export type { Repository } from './repository';
|
|
|
50
50
|
export { createOrderBuilder, createOrderManager, allocateOrderDiscount, taxFiguresForBasket } from './order';
|
|
51
51
|
export { orderDraftSchema, writeOrderDraft, restoreOrderDraft, parkedOrderSummaries$ } from './order';
|
|
52
52
|
export { useParkedSales } from './order';
|
|
53
|
+
export { salesRangeQuery, useStoreOrdersInRange, useStoreRefundsInRange } from './store-orders';
|
|
54
|
+
export type { OrderDownloadProgress, OtherCurrencyRefunds, StoreOrdersInRange, StoreOrdersRangeQuery, StoreRefundsInRange, StoreRefundsRangeQuery } from './store-orders';
|
|
53
55
|
export type { BasketLine } from './order';
|
|
54
56
|
export { couponPricingBasis } from './order';
|
|
55
57
|
export type { OrderBuilder, OrderBuilderOptions, OrderCouponContext, StorePricedCoupon, StorePricedCouponContext } from './order';
|
|
@@ -71,6 +73,7 @@ export type {
|
|
|
71
73
|
DisplayTotals,
|
|
72
74
|
DisplayLine,
|
|
73
75
|
Payment,
|
|
76
|
+
CashRounding,
|
|
74
77
|
CustomerSummary,
|
|
75
78
|
PaymentMethod,
|
|
76
79
|
} from './order';
|
|
@@ -136,17 +139,19 @@ export type {
|
|
|
136
139
|
export {
|
|
137
140
|
PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
|
|
138
141
|
printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
|
|
139
|
-
escpos, encodeEscPos, createEscPosTransport, createEpsonEposSink, createStarWebPrntSink, networkSinkFor,
|
|
142
|
+
escpos, encodeEscPos, createEscPosTransport, createEpsonEposSink, createStarWebPrntSink, networkSinkFor, createWebUsbSink, createWebBluetoothSink,
|
|
143
|
+
BLUETOOTH_PRINT_SERVICES, canOpenDrawer,
|
|
140
144
|
openDrawerJob, ESCPOS_CODE_PAGES, resolvePrinter, templateColumns, renderEscpos, encodeThermalTemplate,
|
|
141
145
|
} from './print';
|
|
142
146
|
export type {
|
|
143
147
|
PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
|
|
144
148
|
PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
|
|
145
|
-
EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions,
|
|
149
|
+
EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, WebUsbDevice, WebUsbSinkOptions,
|
|
150
|
+
WebBluetoothDevice, WebBluetoothSinkOptions, ResolvePrinterOptions, RenderEscposOptions,
|
|
146
151
|
} from './print';
|
|
147
152
|
|
|
148
153
|
// Sale
|
|
149
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, 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';
|
|
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';
|
|
150
155
|
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
|
|
151
156
|
|
|
152
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';
|
|
@@ -155,11 +160,12 @@ export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
|
155
160
|
export { extrasNotSent, type ExtrasNotSent } from './pos-order';
|
|
156
161
|
export { refundDueOf } from './pos-order';
|
|
157
162
|
export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
|
|
158
|
-
export { ADDRESS_CHANGE_REFUSED, 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';
|
|
163
|
+
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';
|
|
159
164
|
export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
|
|
160
165
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
161
166
|
export type { PosOrderCouponLine } from './pos-order/types';
|
|
162
167
|
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger } from './outbox';
|
|
168
|
+
export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX, type NeedsAdminAnswer } from './outbox';
|
|
163
169
|
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
164
170
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
165
171
|
export type { OutboxCounts, OutboxHealth, UseOutboxHealthOptions, UseOutboxHealthResult } from './outbox';
|
|
@@ -167,6 +173,7 @@ export { createBackendNotFound } from './outbox/backend-not-found';
|
|
|
167
173
|
export type { BackendNotFound } from './outbox/backend-not-found';
|
|
168
174
|
export type { HttpTransportOptions, OrderOutboxOptions, OrderOutbox, TransportOutcome, CommandTransport, OrderTransportContext, OutboxState, UseOrderOutboxOptions, UseOrderOutboxResult } from './outbox';
|
|
169
175
|
export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection, refundableLines, priceRefund } from './refund';
|
|
176
|
+
export { refundNeedsAdminLine } from './refund';
|
|
170
177
|
export { sendOrderReopen, isOrderReopenInFlight, isReopenOffered, type OrderReopenOutcome, storeOrderForReopen, ReopenEntryError, REOPEN_REFUSED_STATUSES, type ReopenEntryReason, reopenStoreOrder, REOPENED_NOT_LOADED, STORE_ORDER_OPEN_HERE, type ReopenStoreOrderOutcome } from './reopen';
|
|
171
178
|
export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refund';
|
|
172
179
|
export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, percentOfMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderFigures, runsWholeOrder, tenderVoidSchema, tenderVoidCollection, legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg, splitUnitLines, unitsMinor, unitAllocationsFromLegs, paidUnitsByLine, unpaidUnitsByLine, pickedUnitsMinor } from './tender';
|
|
@@ -185,19 +192,19 @@ export { mintUuid, readRegister, ensureRegister, observeRegister$, getBoundRegis
|
|
|
185
192
|
export type { RegisterHost, RegisterCounters, RegisterBucket, RegisterStore, RegisterDocument } from './register';
|
|
186
193
|
export { RegisterSessionRequiredError, RegisterSessionClosedError, RegisterNeedsUpgradeError, RegisterSessionConflictError, RegisterTakeOverError, isKnownSessionStatus, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, openSessionSelector, requireOpenSession, stampSession, openSession, startCounting, backToSelling, closeSession, recordMovement, voidMovement, writeClosure } from './register';
|
|
187
194
|
export type { RegisterSessionCollection, CashMovementCollection, ClosureCollection } from './register';
|
|
188
|
-
export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows, ENGLISH_CLOSURE_LABELS } from './register';
|
|
189
|
-
export type { Correction, RecordedFigures, ClosureScope } from './register';
|
|
195
|
+
export { deriveSettled, closureFigures, exportCsv, labelKeys, clampClosureScope, selectClosureRows, ENGLISH_CLOSURE_LABELS } from './register';
|
|
196
|
+
export type { Correction, RecordedFigures, ClosureScope, ClosureFigures } from './register';
|
|
190
197
|
export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, TAX_STORE_PAID_NOTE, registerFactsLogger, recordRegisterFact, type ClosureContext, type Actor, type RegisterFact, createClosureContext, formatDecimalMoney, type CreateClosureContextOptions } from './register';
|
|
191
198
|
import { minorToDecimal as registerMinorToDecimal } from './register';
|
|
192
199
|
/** @deprecated Use `minorToMajor(minor, digits)` from `@tallyui/core`, which also rejects an amount that is not a safe integer. */
|
|
193
200
|
export const minorToDecimal: (minor: number, exponent: number) => string = registerMinorToDecimal;
|
|
194
|
-
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
|
|
195
|
-
export { roundedDue, tenderRounding } from './tender';
|
|
201
|
+
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';
|
|
196
203
|
export type { TenderRounding } from './tender';
|
|
197
204
|
export { suggestFloat, type FloatSuggestion } from './register';
|
|
198
205
|
export { switchWarnings, handoverSlip } from './register';
|
|
199
206
|
export type { SwitchKind, SwitchWarning, SwitchWarningInput, SwitchWarnings, HandoverSlipInput, HandoverSlipData } from './register';
|
|
200
207
|
|
|
201
208
|
// Reports
|
|
202
|
-
export { salesFigures, marginOf, comparisonRange, daysOf, inRange, presetRange, DATE_PRESETS, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './reports';
|
|
209
|
+
export { salesFigures, marginOf, medianMinor, comparisonRange, daysOf, inRange, presetRange, DATE_PRESETS, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './reports';
|
|
203
210
|
export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin, Margin, SalesTotals, PaymentRow, GroupRow, TaxRow, DayPoint, SalesFiguresInput, SalesFigures, DatePreset } from './reports';
|
package/src/order/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
2
2
|
import { resolvePrice, woocommerceTax, type woocommerceCoupons, type OrderCreateMeta, type ProductTraits, type ResolvedPrice, type TaxRounding } from '@tallyui/core';
|
|
3
|
-
import type { TaxContext } from '../tax/types';
|
|
3
|
+
import type { TaxContext, WooRate } from '../tax/types';
|
|
4
4
|
import { taxMicros, roundMicrosToMinor, roundedTaxByRate, MICROS_PER_MINOR } from '../tax/exact';
|
|
5
5
|
import { taxLogger } from '../tax/tax-provider';
|
|
6
6
|
import { capturedMinor, canMoveLeg, countsTowardPaid, isInMotion, legStatus, type PaymentLegStatus } from '../tender/payment-legs';
|
|
@@ -15,9 +15,10 @@ import type {
|
|
|
15
15
|
Discount,
|
|
16
16
|
AppliedDiscount,
|
|
17
17
|
Payment,
|
|
18
|
+
CashRounding,
|
|
18
19
|
CustomerSummary,
|
|
19
20
|
AddLineInput,
|
|
20
|
-
ChargeInput, ChargeLine, FeeLine, ShippingLine,
|
|
21
|
+
ChargeInput, ChargeLine, FeeLine, ShippingLine, LineTaxLine,
|
|
21
22
|
} from './types';
|
|
22
23
|
|
|
23
24
|
/** splitLine's refusal: a fixed line discount copied onto every split line would multiply it. */
|
|
@@ -152,6 +153,8 @@ export interface OrderBuilderOptions {
|
|
|
152
153
|
storeOrder?: StoreOrderRef;
|
|
153
154
|
afterClose?: Order['afterClose'];
|
|
154
155
|
couponContext?: OrderCouponContext;
|
|
156
|
+
/** A restored paid draft's parked tax lines by line, fee or shipping id (row 497); held only while one of `legIds` is captured or moving. */
|
|
157
|
+
heldRates?: { legIds: readonly string[]; taxLines: ReadonlyMap<string, readonly LineTaxLine[]> };
|
|
155
158
|
}
|
|
156
159
|
|
|
157
160
|
export interface OrderBuilder {
|
|
@@ -188,8 +191,15 @@ export interface OrderBuilder {
|
|
|
188
191
|
applyLineDiscount(lineId: string, discount: Discount): void;
|
|
189
192
|
applyOrderDiscount(discount: Discount): void;
|
|
190
193
|
removeDiscount(discountId: string): void;
|
|
191
|
-
|
|
192
|
-
|
|
194
|
+
/** ADR-094: `rounding` adds the leg's cash rounding entry with it, so no snapshot shows the leg without it (none when `minor` is 0). */
|
|
195
|
+
addPayment(payment: Omit<Payment, 'id'> & { id?: string }, rounding?: { minor: number }): string;
|
|
196
|
+
/** ADR-094: adds a cash rounding entry against an existing leg; it counts in totalMinor while that leg counts toward paid. */
|
|
197
|
+
addCashRounding(entry: CashRounding): void;
|
|
198
|
+
/**
|
|
199
|
+
* Moves a leg's status; `takenAt` is set on the leg only on a move to captured, and `sessionId` with it (S3: the
|
|
200
|
+
* session that captured the leg), only on a leg that has none yet.
|
|
201
|
+
*/
|
|
202
|
+
setPaymentStatus(paymentId: string, status: PaymentLegStatus, takenAt?: string, sessionId?: string): boolean;
|
|
193
203
|
removePayment(paymentId: string): void;
|
|
194
204
|
setCustomer(customer: CustomerSummary | null): void;
|
|
195
205
|
setNote(note: string): void;
|
|
@@ -209,11 +219,22 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
209
219
|
const currency = options.currency.toUpperCase();
|
|
210
220
|
const orderId = options.id ?? uid();
|
|
211
221
|
const woo = taxContext.rounding?.granularity === 'woocommerce' && taxContext.getTaxRates ? taxContext.rounding : undefined;
|
|
212
|
-
|
|
213
|
-
|
|
222
|
+
// Row 497: a held item's parked tax lines, while a held leg is captured or moving; a void ends the hold at the next build.
|
|
223
|
+
const heldFor = (id: string) => {
|
|
224
|
+
const held = options.heldRates;
|
|
225
|
+
return held?.taxLines.has(id) && payments.some((p) => held.legIds.includes(p.id) && (countsTowardPaid(p) || isInMotion(p)))
|
|
226
|
+
? held.taxLines.get(id) : undefined;
|
|
227
|
+
};
|
|
228
|
+
const toWooRates = (held: readonly LineTaxLine[]): WooRate[] => held.map((t, i) =>
|
|
229
|
+
({ id: t.rateId!, code: t.code ?? '', label: '', rate: (t.ratePpm / 10000).toFixed(4), priority: i, compound: t.compound ?? false, shipping: true }));
|
|
230
|
+
const wooLine = (amount: number, taxClass: string | undefined, inclusive: boolean, untaxed = false, shipping = false, id?: string) => {
|
|
231
|
+
const held = id !== undefined ? heldFor(id) : undefined;
|
|
232
|
+
return woocommerceLine(amount, untaxed ? [] : held ? toWooRates(held) : taxContext.getTaxRates!(taxClass, { shipping }),
|
|
233
|
+
inclusive, currency, woo!.roundAtSubtotal, taxContext.pricesIncludeTax);
|
|
234
|
+
};
|
|
214
235
|
const displayAmount = (line: LineItem, amount: number) => {
|
|
215
236
|
if (!woo || line.taxInclusive === taxContext.pricesIncludeTax) return toDisplayMode(line, amount, taxContext.pricesIncludeTax);
|
|
216
|
-
const item = wooLine(amount, line.taxClass, line.taxInclusive, line.taxStatus === 'none');
|
|
237
|
+
const item = wooLine(amount, line.taxClass, line.taxInclusive, line.taxStatus === 'none', false, line.id);
|
|
217
238
|
return taxContext.pricesIncludeTax ? item.totalMinor : item.netMinor;
|
|
218
239
|
};
|
|
219
240
|
/** A recalculated line's remaining amount in the store's mode: the display's remaining and a percent fee's basis. */
|
|
@@ -225,6 +246,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
225
246
|
let shipping: ShippingLine[] = [];
|
|
226
247
|
let orderDiscounts: AppliedDiscount[] = [];
|
|
227
248
|
let payments: Payment[] = [];
|
|
249
|
+
let cashRoundings: CashRounding[] = [];
|
|
228
250
|
let customer: CustomerSummary | null = null;
|
|
229
251
|
let note = '';
|
|
230
252
|
let meta: OrderCreateMeta[] = [];
|
|
@@ -251,7 +273,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
251
273
|
// Store-priced coupons (#709) come off what the discounts leave, capped there; discountMinor never includes them (v6).
|
|
252
274
|
const netMinor = grossMinor - discountMinor - Math.max(0, Math.min(couponMinor, grossMinor - discountMinor));
|
|
253
275
|
if (woo) return { ...line, discounts: recalcedDiscounts, discountMinor, orderDiscountMinor,
|
|
254
|
-
...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === 'none') };
|
|
276
|
+
...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === 'none', false, line.id) };
|
|
255
277
|
const combinedRate = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
|
|
256
278
|
// Tax in the line's own mode, from its own unit price × quantity: never re-tax a rounded base.
|
|
257
279
|
const inclusiveTax = line.taxInclusive ? taxMicros(netMinor, combinedRate, true) : 0n;
|
|
@@ -313,7 +335,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
313
335
|
const tagged = couponContext && 'kind' in couponContext ? couponContext : undefined;
|
|
314
336
|
const store = tagged?.kind === 'store-priced' ? tagged : undefined, kept = tagged?.kind === 'kept' ? tagged : undefined;
|
|
315
337
|
const replay = woo && couponCodes.length && !tagged ? woocommerceCouponReplay(displaySourceLines, couponCodes,
|
|
316
|
-
couponContext as OrderCouponContext,
|
|
338
|
+
couponContext as OrderCouponContext, (line) => { const held = heldFor(line.id); return held ? toWooRates(held) : taxContext.getTaxRates!(line.taxClass); },
|
|
339
|
+
currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax) : undefined;
|
|
317
340
|
// Kept figures go only on the lines they were parked for, so a line edit never meets them (it goes stale instead).
|
|
318
341
|
const keptOn = kept && couponCodes.length > 0 && payments.some((p) => isLiveLeg(p) && kept.legIds.includes(p.id))
|
|
319
342
|
&& couponPricingBasis({ currency, customer: null, lineItems, discounts: orderDiscounts }) === kept.linesBasis ? kept : undefined;
|
|
@@ -337,7 +360,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
337
360
|
amountMinor: Number((basis * BigInt(Math.round(fee.percent * 10000)) + 500000n) / 1000000n) }));
|
|
338
361
|
}
|
|
339
362
|
|
|
340
|
-
|
|
363
|
+
// Row 497: held charges recalculate on every build, so a hold starts once payments restore and ends at a void.
|
|
364
|
+
if (options.heldRates) fees = fees.map((fee) => fee.percent !== undefined ? fee : { ...fee, ...recalculateCharge(fee.id, fee) });
|
|
365
|
+
if (woo || options.heldRates) shipping =shipping.map((charge) => ({ ...charge, ...recalculateCharge(charge.id, charge, true) }));
|
|
341
366
|
const charges = [...fees, ...shipping];
|
|
342
367
|
const taxedCharges = charges.map((charge) => ({ ...charge, taxInclusive: charge.amountIncludesTax ?? taxContext.pricesIncludeTax,
|
|
343
368
|
taxMicros: charge.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n).toString() }));
|
|
@@ -476,16 +501,19 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
476
501
|
throw new Error(`Display line ${line.lineId} shows ${line.amountMinor}, less than its rows ${rows} and share ${shareMinor} (ADR-063)`);
|
|
477
502
|
}
|
|
478
503
|
}
|
|
504
|
+
// ADR-094: an entry counts while its leg counts toward paid; the subtotal above stays unrounded.
|
|
505
|
+
const live = cashRoundings.filter((e) => payments.some((p) => p.id === e.paymentId && countsTowardPaid(p)));
|
|
506
|
+
const total = totalMinor + live.reduce((sum, e) => sum + e.minor, 0);
|
|
479
507
|
const display = {
|
|
480
|
-
taxInclusive, subtotalMinor: displaySubtotal, discountMinor: displayDiscount, taxMinor, totalMinor,
|
|
508
|
+
taxInclusive, subtotalMinor: displaySubtotal, discountMinor: displayDiscount, taxMinor, totalMinor: total,
|
|
481
509
|
lines: displayLines, orderDiscountMinor: orderDiscountDisplay,
|
|
482
510
|
...(displayCoupons ? { coupons: displayCoupons } : {}),
|
|
483
511
|
...(fees.length ? { fees: displayFees } : {}),
|
|
484
512
|
...(shipping.length ? { shipping: displayShipping } : {}),
|
|
485
513
|
};
|
|
486
514
|
const paidMinor = capturedMinor(payments);
|
|
487
|
-
const balanceDueMinor = Math.max(0,
|
|
488
|
-
const changeDueMinor = Math.max(0, paidMinor -
|
|
515
|
+
const balanceDueMinor = Math.max(0, total - paidMinor);
|
|
516
|
+
const changeDueMinor = Math.max(0, paidMinor - total);
|
|
489
517
|
|
|
490
518
|
const order: Order = {
|
|
491
519
|
id: orderId,
|
|
@@ -498,13 +526,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
498
526
|
...(shipping.length ? { shipping: [...shipping] } : {}),
|
|
499
527
|
discounts: recalcedOrderDiscounts,
|
|
500
528
|
payments: [...payments],
|
|
529
|
+
...(live.length ? { cashRoundings: live.map((e) => ({ ...e })) } : {}),
|
|
501
530
|
customer,
|
|
502
531
|
note,
|
|
503
532
|
...(meta.length ? { meta: meta.map((m) => ({ ...m })) } : {}),
|
|
504
533
|
subtotalMinor,
|
|
505
534
|
discountMinor,
|
|
506
535
|
taxMinor,
|
|
507
|
-
totalMinor,
|
|
536
|
+
totalMinor: total,
|
|
508
537
|
display,
|
|
509
538
|
paidMinor,
|
|
510
539
|
balanceDueMinor,
|
|
@@ -548,15 +577,15 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
548
577
|
// A `none` shipping line is untaxed as WCPOS saves it (its _woocommerce_pos_data meta clears the store's shipping taxes).
|
|
549
578
|
const untaxed = shipping ? taxStatus === 'none' || taxClass === woocommerceTax.NO_SHIPPING_TAX : taxStatus === 'none';
|
|
550
579
|
const line = wooLine(input.amountMinor, taxClass === woocommerceTax.NO_SHIPPING_TAX || (shipping && untaxed) ? undefined : taxClass,
|
|
551
|
-
inclusive, untaxed, shipping);
|
|
580
|
+
inclusive, untaxed, shipping, id);
|
|
552
581
|
return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus, ...mode,
|
|
553
582
|
...(input.storeLineId !== undefined ? { storeLineId: input.storeLineId } : {}),
|
|
554
583
|
...line };
|
|
555
584
|
}
|
|
556
|
-
const code = taxContext.getTaxRateCode?.(input.taxClass);
|
|
585
|
+
const code = taxContext.getTaxRateCode?.(input.taxClass), held = heldFor(id);
|
|
557
586
|
const line = recalculateLine({
|
|
558
587
|
id, productId: id, name: input.name, sku: '', unitPriceMinor: input.amountMinor, quantity: 1,
|
|
559
|
-
taxLines: [{ ...(code !== undefined ? { code } : {}),
|
|
588
|
+
taxLines: held ? held.map(({ code, ratePpm }) => ({ ...(code !== undefined ? { code } : {}), ratePpm, taxMicros: '0' })) : [{ ...(code !== undefined ? { code } : {}),
|
|
560
589
|
ratePpm: taxStatus === 'none' ? 0 : taxContext.getTaxRatePpm(input.taxClass), taxMicros: '0' }],
|
|
561
590
|
discounts: [], discountMinor: 0, orderDiscountMinor: 0, netMinor: 0, taxMicros: '0',
|
|
562
591
|
taxInclusive: inclusive,
|
|
@@ -576,7 +605,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
576
605
|
throw new RangeError('Regular price must be integer minor units >= 0');
|
|
577
606
|
// A rate from the tax class carries the backend's name for it when one is mapped (#287, #288).
|
|
578
607
|
const code = woo || input.taxRates ? undefined : taxContext.getTaxRateCode?.(input.taxClass);
|
|
579
|
-
const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === 'none').taxLines
|
|
608
|
+
const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === 'none', false, input.id).taxLines
|
|
580
609
|
: input.taxStatus === 'none' ? [{ ...(code !== undefined ? { code } : {}), ratePpm: 0 }]
|
|
581
610
|
: input.taxRates ?? [{ ...(code !== undefined ? { code } : {}), ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
|
|
582
611
|
const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
|
|
@@ -809,17 +838,31 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
809
838
|
emit();
|
|
810
839
|
},
|
|
811
840
|
|
|
812
|
-
addPayment(payment) {
|
|
841
|
+
addPayment(payment, rounding) {
|
|
813
842
|
const id = idFor(payment.id);
|
|
814
843
|
payments = [...payments, { ...payment, id }];
|
|
844
|
+
if (rounding && rounding.minor !== 0) cashRoundings = [...cashRoundings, { paymentId: id, minor: rounding.minor }];
|
|
815
845
|
emit();
|
|
816
846
|
return id;
|
|
817
847
|
},
|
|
818
848
|
|
|
819
|
-
|
|
849
|
+
addCashRounding(entry) {
|
|
850
|
+
// One entry per leg: a second entry on a leg is summed into the first, and a sum of 0 removes it.
|
|
851
|
+
const prior = cashRoundings.find((e) => e.paymentId === entry.paymentId);
|
|
852
|
+
if (!prior) cashRoundings = [...cashRoundings, { paymentId: entry.paymentId, minor: entry.minor }];
|
|
853
|
+
else {
|
|
854
|
+
const minor = prior.minor + entry.minor;
|
|
855
|
+
cashRoundings = minor === 0 ? cashRoundings.filter((e) => e !== prior) : cashRoundings.map((e) => (e === prior ? { ...e, minor } : e));
|
|
856
|
+
}
|
|
857
|
+
emit();
|
|
858
|
+
},
|
|
859
|
+
|
|
860
|
+
setPaymentStatus(paymentId, status, takenAt, sessionId) {
|
|
820
861
|
const payment = payments.find((p) => p.id === paymentId);
|
|
821
862
|
if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
|
|
822
|
-
|
|
863
|
+
const stamp = status === 'captured' && takenAt !== undefined
|
|
864
|
+
? { takenAt, ...(sessionId !== undefined && payment.sessionId === undefined ? { sessionId } : {}) } : {};
|
|
865
|
+
payments = payments.map((p) => p.id === paymentId ? { ...p, status, ...stamp } : p);
|
|
823
866
|
emit();
|
|
824
867
|
return true;
|
|
825
868
|
},
|
|
@@ -885,6 +928,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
885
928
|
shipping = [];
|
|
886
929
|
orderDiscounts = [];
|
|
887
930
|
payments = [];
|
|
931
|
+
cashRoundings = [];
|
|
888
932
|
customer = null;
|
|
889
933
|
note = '';
|
|
890
934
|
meta = [];
|
|
@@ -2,9 +2,11 @@ import { map, type Observable } from 'rxjs';
|
|
|
2
2
|
import type { RxCollection, RxJsonSchema } from 'rxdb';
|
|
3
3
|
import type { TaxContext } from '../tax/types';
|
|
4
4
|
import { customerRefusal } from '../pos-order/command';
|
|
5
|
-
import {
|
|
5
|
+
import { tillPayments } from '../pos-order/till-payments';
|
|
6
|
+
import { capturedMinor, countsTowardPaid, isInMotion } from '../tender/payment-legs';
|
|
6
7
|
import { couponPricingBasis, createOrderBuilder, isLiveLeg, type OrderBuilder } from './order-builder';
|
|
7
|
-
import
|
|
8
|
+
import { isTakenAt } from './taken-at';
|
|
9
|
+
import type { CashRounding, Order, Payment } from './types';
|
|
8
10
|
|
|
9
11
|
/** Apps create their drafts collection with this schema. */
|
|
10
12
|
export const orderDraftSchema: RxJsonSchema<{
|
|
@@ -37,15 +39,49 @@ export interface ParkedOrderSummary {
|
|
|
37
39
|
firstItem?: string;
|
|
38
40
|
}
|
|
39
41
|
|
|
42
|
+
/** A draft's saved order; throws on data that is not JSON. */
|
|
43
|
+
const savedDraft = (data: unknown) => JSON.parse(String(data)) as Partial<Order>;
|
|
44
|
+
|
|
40
45
|
function draftExtras(data: unknown): Pick<ParkedOrderSummary, 'paidMinor' | 'balanceDueMinor' | 'firstItem'> {
|
|
41
46
|
try {
|
|
42
|
-
const saved =
|
|
47
|
+
const saved = savedDraft(data);
|
|
43
48
|
return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
|
|
44
49
|
} catch {
|
|
45
50
|
return {}; // an unreadable draft still lists, without these figures
|
|
46
51
|
}
|
|
47
52
|
}
|
|
48
53
|
|
|
54
|
+
/**
|
|
55
|
+
* S3: the till legs a session counts while no stored order counts them: captured, stamped with the session that took
|
|
56
|
+
* them, not reopened (its refused order's, counted there) and not `counted` (an after-close sale's, in a closure already).
|
|
57
|
+
* One rule for a parked draft (`parkedTakenLegs`) and the live sale (`useSale`'s `takenLegs`).
|
|
58
|
+
*/
|
|
59
|
+
export function sessionTakenLegs(payments: readonly Payment[], counted: (leg: Payment) => boolean = () => false): Payment[] {
|
|
60
|
+
return tillPayments(payments).filter((leg) => countsTowardPaid(leg) && !leg.reopened && !counted(leg) && typeof leg.sessionId === 'string');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** S3: a parked draft's taken legs (`sessionTakenLegs`), so their session counts their cash while the sale is parked. Unreadable data has none. */
|
|
64
|
+
export function parkedTakenLegs(data: unknown): Payment[] {
|
|
65
|
+
try {
|
|
66
|
+
const payments = savedDraft(data).payments;
|
|
67
|
+
return Array.isArray(payments) ? sessionTakenLegs(payments) : [];
|
|
68
|
+
} catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** #1281: a parked draft's cash rounding entries on its taken legs (`parkedTakenLegs`), counted with those legs. Unreadable data has none. */
|
|
74
|
+
export function parkedCashRoundings(data: unknown): CashRounding[] {
|
|
75
|
+
try {
|
|
76
|
+
const entries: unknown = savedDraft(data).cashRoundings;
|
|
77
|
+
if (!Array.isArray(entries)) return [];
|
|
78
|
+
const taken = new Set(parkedTakenLegs(data).map((leg) => leg.id));
|
|
79
|
+
return entries.filter((entry): entry is CashRounding => typeof entry?.paymentId === 'string' && Number.isFinite(entry?.minor) && taken.has(entry.paymentId));
|
|
80
|
+
} catch {
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
49
85
|
export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string> {
|
|
50
86
|
await drafts.upsert({
|
|
51
87
|
id: snapshot.id,
|
|
@@ -59,17 +95,26 @@ export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Pr
|
|
|
59
95
|
}
|
|
60
96
|
|
|
61
97
|
/**
|
|
62
|
-
* Rebuilds a saved order on `taxContext`.
|
|
63
|
-
*
|
|
64
|
-
*
|
|
98
|
+
* Rebuilds a saved order on `taxContext`. Outside woo, a line marked taxFromClass re-derives from its class unless
|
|
99
|
+
* `keepTaxRates` is set; every other line (given rates, a draft from before the marker) keeps its stored rates. Fees and
|
|
100
|
+
* shipping, and under woo lines too, re-derive today's rates, except with `keepTaxRates` (row 497): then they hold their
|
|
101
|
+
* parked tax lines (under woo, only those with every rate id), and the hold ends at the next build once no parked leg
|
|
102
|
+
* is still captured or in motion. Granularity must match the draft's. `keepCoupons` puts the saved
|
|
65
103
|
* coupons back as parked, figures and all, while an unlocked leg is live (ADR-077 d3, amended 2026-11-19); otherwise none.
|
|
66
104
|
* Carried coupons always restore their priced amounts against the saved basis, keeping stale figures stale.
|
|
67
105
|
*/
|
|
68
106
|
export function restoreOrderDraft(saved: Order, options: { currency: string; taxContext: TaxContext; keepTaxRates?: boolean; keepCoupons?: boolean }): OrderBuilder {
|
|
69
107
|
const { currency, taxContext } = options;
|
|
108
|
+
const wooNow = taxContext.rounding?.granularity === 'woocommerce' && !!taxContext.getTaxRates;
|
|
109
|
+
const items = [...saved.lineItems, ...saved.fees ?? [], ...saved.shipping ?? []];
|
|
110
|
+
const heldRates = options.keepTaxRates && wooNow === (saved.taxRounding?.granularity === 'woocommerce') ? {
|
|
111
|
+
legIds: (saved.payments ?? []).filter((p) => countsTowardPaid(p) || isInMotion(p)).map((p) => p.id),
|
|
112
|
+
taxLines: new Map(items.filter((i) => !wooNow || i.taxLines.every((t) => t.rateId !== undefined)).map((i) => [i.id, i.taxLines])),
|
|
113
|
+
} : undefined;
|
|
70
114
|
const builder = createOrderBuilder({
|
|
71
115
|
currency,
|
|
72
116
|
taxContext,
|
|
117
|
+
...(heldRates ? { heldRates } : {}),
|
|
73
118
|
id: saved.id,
|
|
74
119
|
...(saved.createdAt ? { createdAt: saved.createdAt } : {}), // #742: with every id below (fees and shipping replay whole)
|
|
75
120
|
...(saved.storeOrder !== undefined ? { storeOrder: saved.storeOrder } : {}),
|
|
@@ -86,6 +131,29 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
86
131
|
}
|
|
87
132
|
if (saved.meta?.length) builder.setMeta(saved.meta);
|
|
88
133
|
|
|
134
|
+
// Payments come first so that a held paid draft's lines are held when they are added (row 497).
|
|
135
|
+
// Restore payments
|
|
136
|
+
for (const payment of saved.payments) {
|
|
137
|
+
builder.addPayment({
|
|
138
|
+
id: payment.id,
|
|
139
|
+
method: payment.method,
|
|
140
|
+
amountMinor: payment.amountMinor,
|
|
141
|
+
tenderedMinor: payment.tenderedMinor,
|
|
142
|
+
changeMinor: payment.changeMinor,
|
|
143
|
+
reference: payment.reference,
|
|
144
|
+
...(payment.status !== undefined ? { status: payment.status } : {}),
|
|
145
|
+
...(payment.storePaymentId !== undefined ? { storePaymentId: payment.storePaymentId } : {}),
|
|
146
|
+
...(payment.locked !== undefined ? { locked: payment.locked } : {}),
|
|
147
|
+
...(payment.reopened !== undefined ? { reopened: payment.reopened } : {}),
|
|
148
|
+
...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
|
|
149
|
+
...(payment.units !== undefined ? { units: payment.units } : {}),
|
|
150
|
+
...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
|
|
151
|
+
...(typeof payment.sessionId === 'string' ? { sessionId: payment.sessionId } : {}),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
for (const entry of saved.cashRoundings ?? []) builder.addCashRounding(entry);
|
|
156
|
+
|
|
89
157
|
// Restore line items and their discounts
|
|
90
158
|
for (const line of saved.lineItems) {
|
|
91
159
|
const rederive = line.taxFromClass === true && !options.keepTaxRates;
|
|
@@ -135,23 +203,6 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
135
203
|
}
|
|
136
204
|
|
|
137
205
|
// Coupons are re-applied by the sale with fresh coupon data (ADR-077 d3), except carried coupons and keepCoupons below.
|
|
138
|
-
// Restore payments
|
|
139
|
-
for (const payment of saved.payments) {
|
|
140
|
-
builder.addPayment({
|
|
141
|
-
id: payment.id,
|
|
142
|
-
method: payment.method,
|
|
143
|
-
amountMinor: payment.amountMinor,
|
|
144
|
-
tenderedMinor: payment.tenderedMinor,
|
|
145
|
-
changeMinor: payment.changeMinor,
|
|
146
|
-
reference: payment.reference,
|
|
147
|
-
...(payment.status !== undefined ? { status: payment.status } : {}),
|
|
148
|
-
...(payment.storePaymentId !== undefined ? { storePaymentId: payment.storePaymentId } : {}),
|
|
149
|
-
...(payment.locked !== undefined ? { locked: payment.locked } : {}),
|
|
150
|
-
...(payment.reopened !== undefined ? { reopened: payment.reopened } : {}),
|
|
151
|
-
...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
|
|
152
|
-
...(payment.units !== undefined ? { units: payment.units } : {}),
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
206
|
if (saved.coupons?.some((c) => c.carried) && !saved.coupons.every((c) => c.carried)) throw new Error('restoreOrderDraft: a draft cannot mix carried and redeemable coupons');
|
|
156
207
|
if (saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried)) {
|
|
157
208
|
builder.setCoupons(saved.coupons.map((c) => c.code), { kind: 'store-priced', carried: true,
|
|
@@ -163,9 +214,12 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
163
214
|
// Kept only with a display row per coupon; a draft parked stale keeps its figures but stays stale (basis '' never matches).
|
|
164
215
|
if (options.keepCoupons && saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length) {
|
|
165
216
|
const restored = builder.getSnapshot();
|
|
217
|
+
// The kept lines carry their parked rates (order-builder keptOn), so the basis must too: a Woo line re-derives today's rate (F5).
|
|
218
|
+
const parkedRates = new Map(saved.lineItems.map((li) => [li.id, li.taxLines]));
|
|
219
|
+
const keptBasis = couponPricingBasis({ ...restored, lineItems: restored.lineItems.map((li) => ({ ...li, taxLines: parkedRates.get(li.id) ?? li.taxLines })) });
|
|
166
220
|
builder.setCoupons(saved.coupons.map((coupon) => coupon.code), { kind: 'kept', coupons: saved.coupons,
|
|
167
221
|
displayRows: saved.display.coupons.map((row) => row.amountMinor), lines: new Map(saved.lineItems.map((li) => [li.id, li])),
|
|
168
|
-
basis: saved.couponPricesStale ? '' :
|
|
222
|
+
basis: saved.couponPricesStale ? '' : keptBasis, linesBasis: couponPricingBasis({ ...restored, customer: null }),
|
|
169
223
|
legIds: saved.payments.filter(isLiveLeg).map((p) => p.id) });
|
|
170
224
|
}
|
|
171
225
|
return builder;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** A stored takenAt must be an instant in toISOString() form (the Front desk's ruling on #1178); any other value is dropped. */
|
|
2
|
+
export function isTakenAt(value: unknown): value is string {
|
|
3
|
+
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
|
|
4
|
+
&& Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
5
|
+
}
|
package/src/order/types.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface Order {
|
|
|
41
41
|
/** TallyUI#709: present (true) only when store-priced coupons are set and couponPricingBasis(order) no longer equals their basis. */
|
|
42
42
|
couponPricesStale?: true;
|
|
43
43
|
payments: Payment[];
|
|
44
|
+
/** ADR-094: a cash leg that settles the sale at a rounded due records the signed difference here, counted in totalMinor; only entries whose leg counts toward paid are built in. Absent when empty. */
|
|
45
|
+
cashRoundings?: CashRounding[];
|
|
44
46
|
customer: CustomerSummary | null;
|
|
45
47
|
note: string;
|
|
46
48
|
/** The sale's order meta, WooCommerce's custom fields (ADR-092 6d). Set with `useSale().setMeta`, parked with the draft,
|
|
@@ -173,6 +175,9 @@ export interface AppliedDiscount extends Discount {
|
|
|
173
175
|
amountMinor: number; // an order discount: its own-mode amount, allocated across the lines
|
|
174
176
|
}
|
|
175
177
|
|
|
178
|
+
/** ADR-094: one cash rounding, the signed minor units its leg (`paymentId`) settled the sale above (+) or below (-) its due. */
|
|
179
|
+
export interface CashRounding { paymentId: string; minor: number }
|
|
180
|
+
|
|
176
181
|
export interface Payment {
|
|
177
182
|
id: string;
|
|
178
183
|
/** The store's payment record id for a leg it already holds */
|
|
@@ -186,14 +191,18 @@ export interface Payment {
|
|
|
186
191
|
methodId?: string;
|
|
187
192
|
/** Absent means captured; only captured legs count toward paidMinor. */
|
|
188
193
|
status?: PaymentLegStatus;
|
|
189
|
-
//
|
|
190
|
-
//
|
|
194
|
+
// A cash leg taken at Take records the amount applied here, with `tenderedMinor` and `changeMinor`. A leg without
|
|
195
|
+
// `tenderedMinor` (from `setTender` or an old draft) records the full amount handed over, and finalize nets it; a reopened leg carries the stored, already netted amount.
|
|
191
196
|
amountMinor: number;
|
|
192
197
|
tenderedMinor?: number;
|
|
193
198
|
changeMinor?: number;
|
|
194
199
|
reference?: string;
|
|
195
200
|
/** The units of each line (`String(line id)`) this leg paid for, set when it was taken with unit picks (#1133). Absent for a leg taken by amount. */
|
|
196
201
|
units?: Readonly<Record<string, number>>;
|
|
202
|
+
/** When the till recorded the leg (an ISO 8601 instant). Absent on store-held legs and on legs from before 4.2. */
|
|
203
|
+
takenAt?: string;
|
|
204
|
+
/** The register session the leg was taken in (money suspect S3): its cash counts there, not in the order's session. */
|
|
205
|
+
sessionId?: string;
|
|
197
206
|
}
|
|
198
207
|
|
|
199
208
|
export interface CustomerSummary {
|