@tallyui/pos 4.2.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 +465 -162
- package/dist/index.js +1752 -1104
- package/package.json +7 -6
- package/src/index.ts +12 -9
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +64 -22
- package/src/order/order-drafts.ts +77 -25
- package/src/order/types.ts +9 -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 +9 -0
- package/src/pos-order/reopen.ts +9 -2
- package/src/pos-order/schema.ts +5 -2
- package/src/pos-order/types.ts +5 -1
- 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 +313 -134
- package/src/store-orders/index.ts +3 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- 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/src/print/escpos/sinks.test-d.ts +0 -77
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
|
@@ -50,8 +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 { useStoreOrdersInRange } from './store-orders';
|
|
54
|
-
export type { OrderDownloadProgress, StoreOrdersInRange, StoreOrdersRangeQuery } from './store-orders';
|
|
53
|
+
export { salesRangeQuery, useStoreOrdersInRange, useStoreRefundsInRange } from './store-orders';
|
|
54
|
+
export type { OrderDownloadProgress, OtherCurrencyRefunds, StoreOrdersInRange, StoreOrdersRangeQuery, StoreRefundsInRange, StoreRefundsRangeQuery } from './store-orders';
|
|
55
55
|
export type { BasketLine } from './order';
|
|
56
56
|
export { couponPricingBasis } from './order';
|
|
57
57
|
export type { OrderBuilder, OrderBuilderOptions, OrderCouponContext, StorePricedCoupon, StorePricedCouponContext } from './order';
|
|
@@ -73,6 +73,7 @@ export type {
|
|
|
73
73
|
DisplayTotals,
|
|
74
74
|
DisplayLine,
|
|
75
75
|
Payment,
|
|
76
|
+
CashRounding,
|
|
76
77
|
CustomerSummary,
|
|
77
78
|
PaymentMethod,
|
|
78
79
|
} from './order';
|
|
@@ -150,7 +151,7 @@ export type {
|
|
|
150
151
|
} from './print';
|
|
151
152
|
|
|
152
153
|
// Sale
|
|
153
|
-
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';
|
|
154
155
|
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
|
|
155
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';
|
|
@@ -159,11 +160,12 @@ export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
|
159
160
|
export { extrasNotSent, type ExtrasNotSent } from './pos-order';
|
|
160
161
|
export { refundDueOf } from './pos-order';
|
|
161
162
|
export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
|
|
162
|
-
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';
|
|
163
164
|
export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
|
|
164
165
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
165
166
|
export type { PosOrderCouponLine } from './pos-order/types';
|
|
166
167
|
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger } from './outbox';
|
|
168
|
+
export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX, type NeedsAdminAnswer } from './outbox';
|
|
167
169
|
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
168
170
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
169
171
|
export type { OutboxCounts, OutboxHealth, UseOutboxHealthOptions, UseOutboxHealthResult } from './outbox';
|
|
@@ -171,6 +173,7 @@ export { createBackendNotFound } from './outbox/backend-not-found';
|
|
|
171
173
|
export type { BackendNotFound } from './outbox/backend-not-found';
|
|
172
174
|
export type { HttpTransportOptions, OrderOutboxOptions, OrderOutbox, TransportOutcome, CommandTransport, OrderTransportContext, OutboxState, UseOrderOutboxOptions, UseOrderOutboxResult } from './outbox';
|
|
173
175
|
export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection, refundableLines, priceRefund } from './refund';
|
|
176
|
+
export { refundNeedsAdminLine } from './refund';
|
|
174
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';
|
|
175
178
|
export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refund';
|
|
176
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';
|
|
@@ -189,19 +192,19 @@ export { mintUuid, readRegister, ensureRegister, observeRegister$, getBoundRegis
|
|
|
189
192
|
export type { RegisterHost, RegisterCounters, RegisterBucket, RegisterStore, RegisterDocument } from './register';
|
|
190
193
|
export { RegisterSessionRequiredError, RegisterSessionClosedError, RegisterNeedsUpgradeError, RegisterSessionConflictError, RegisterTakeOverError, isKnownSessionStatus, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, openSessionSelector, requireOpenSession, stampSession, openSession, startCounting, backToSelling, closeSession, recordMovement, voidMovement, writeClosure } from './register';
|
|
191
194
|
export type { RegisterSessionCollection, CashMovementCollection, ClosureCollection } from './register';
|
|
192
|
-
export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows, ENGLISH_CLOSURE_LABELS } from './register';
|
|
193
|
-
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';
|
|
194
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';
|
|
195
198
|
import { minorToDecimal as registerMinorToDecimal } from './register';
|
|
196
199
|
/** @deprecated Use `minorToMajor(minor, digits)` from `@tallyui/core`, which also rejects an amount that is not a safe integer. */
|
|
197
200
|
export const minorToDecimal: (minor: number, exponent: number) => string = registerMinorToDecimal;
|
|
198
|
-
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
|
|
199
|
-
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';
|
|
200
203
|
export type { TenderRounding } from './tender';
|
|
201
204
|
export { suggestFloat, type FloatSuggestion } from './register';
|
|
202
205
|
export { switchWarnings, handoverSlip } from './register';
|
|
203
206
|
export type { SwitchKind, SwitchWarning, SwitchWarningInput, SwitchWarnings, HandoverSlipInput, HandoverSlipData } from './register';
|
|
204
207
|
|
|
205
208
|
// Reports
|
|
206
|
-
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';
|
|
207
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,9 +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
|
-
|
|
193
|
-
|
|
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;
|
|
194
203
|
removePayment(paymentId: string): void;
|
|
195
204
|
setCustomer(customer: CustomerSummary | null): void;
|
|
196
205
|
setNote(note: string): void;
|
|
@@ -210,11 +219,22 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
210
219
|
const currency = options.currency.toUpperCase();
|
|
211
220
|
const orderId = options.id ?? uid();
|
|
212
221
|
const woo = taxContext.rounding?.granularity === 'woocommerce' && taxContext.getTaxRates ? taxContext.rounding : undefined;
|
|
213
|
-
|
|
214
|
-
|
|
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
|
+
};
|
|
215
235
|
const displayAmount = (line: LineItem, amount: number) => {
|
|
216
236
|
if (!woo || line.taxInclusive === taxContext.pricesIncludeTax) return toDisplayMode(line, amount, taxContext.pricesIncludeTax);
|
|
217
|
-
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);
|
|
218
238
|
return taxContext.pricesIncludeTax ? item.totalMinor : item.netMinor;
|
|
219
239
|
};
|
|
220
240
|
/** A recalculated line's remaining amount in the store's mode: the display's remaining and a percent fee's basis. */
|
|
@@ -226,6 +246,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
226
246
|
let shipping: ShippingLine[] = [];
|
|
227
247
|
let orderDiscounts: AppliedDiscount[] = [];
|
|
228
248
|
let payments: Payment[] = [];
|
|
249
|
+
let cashRoundings: CashRounding[] = [];
|
|
229
250
|
let customer: CustomerSummary | null = null;
|
|
230
251
|
let note = '';
|
|
231
252
|
let meta: OrderCreateMeta[] = [];
|
|
@@ -252,7 +273,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
252
273
|
// Store-priced coupons (#709) come off what the discounts leave, capped there; discountMinor never includes them (v6).
|
|
253
274
|
const netMinor = grossMinor - discountMinor - Math.max(0, Math.min(couponMinor, grossMinor - discountMinor));
|
|
254
275
|
if (woo) return { ...line, discounts: recalcedDiscounts, discountMinor, orderDiscountMinor,
|
|
255
|
-
...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === 'none') };
|
|
276
|
+
...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === 'none', false, line.id) };
|
|
256
277
|
const combinedRate = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
|
|
257
278
|
// Tax in the line's own mode, from its own unit price × quantity: never re-tax a rounded base.
|
|
258
279
|
const inclusiveTax = line.taxInclusive ? taxMicros(netMinor, combinedRate, true) : 0n;
|
|
@@ -314,7 +335,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
314
335
|
const tagged = couponContext && 'kind' in couponContext ? couponContext : undefined;
|
|
315
336
|
const store = tagged?.kind === 'store-priced' ? tagged : undefined, kept = tagged?.kind === 'kept' ? tagged : undefined;
|
|
316
337
|
const replay = woo && couponCodes.length && !tagged ? woocommerceCouponReplay(displaySourceLines, couponCodes,
|
|
317
|
-
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;
|
|
318
340
|
// Kept figures go only on the lines they were parked for, so a line edit never meets them (it goes stale instead).
|
|
319
341
|
const keptOn = kept && couponCodes.length > 0 && payments.some((p) => isLiveLeg(p) && kept.legIds.includes(p.id))
|
|
320
342
|
&& couponPricingBasis({ currency, customer: null, lineItems, discounts: orderDiscounts }) === kept.linesBasis ? kept : undefined;
|
|
@@ -338,7 +360,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
338
360
|
amountMinor: Number((basis * BigInt(Math.round(fee.percent * 10000)) + 500000n) / 1000000n) }));
|
|
339
361
|
}
|
|
340
362
|
|
|
341
|
-
|
|
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) }));
|
|
342
366
|
const charges = [...fees, ...shipping];
|
|
343
367
|
const taxedCharges = charges.map((charge) => ({ ...charge, taxInclusive: charge.amountIncludesTax ?? taxContext.pricesIncludeTax,
|
|
344
368
|
taxMicros: charge.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n).toString() }));
|
|
@@ -477,16 +501,19 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
477
501
|
throw new Error(`Display line ${line.lineId} shows ${line.amountMinor}, less than its rows ${rows} and share ${shareMinor} (ADR-063)`);
|
|
478
502
|
}
|
|
479
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);
|
|
480
507
|
const display = {
|
|
481
|
-
taxInclusive, subtotalMinor: displaySubtotal, discountMinor: displayDiscount, taxMinor, totalMinor,
|
|
508
|
+
taxInclusive, subtotalMinor: displaySubtotal, discountMinor: displayDiscount, taxMinor, totalMinor: total,
|
|
482
509
|
lines: displayLines, orderDiscountMinor: orderDiscountDisplay,
|
|
483
510
|
...(displayCoupons ? { coupons: displayCoupons } : {}),
|
|
484
511
|
...(fees.length ? { fees: displayFees } : {}),
|
|
485
512
|
...(shipping.length ? { shipping: displayShipping } : {}),
|
|
486
513
|
};
|
|
487
514
|
const paidMinor = capturedMinor(payments);
|
|
488
|
-
const balanceDueMinor = Math.max(0,
|
|
489
|
-
const changeDueMinor = Math.max(0, paidMinor -
|
|
515
|
+
const balanceDueMinor = Math.max(0, total - paidMinor);
|
|
516
|
+
const changeDueMinor = Math.max(0, paidMinor - total);
|
|
490
517
|
|
|
491
518
|
const order: Order = {
|
|
492
519
|
id: orderId,
|
|
@@ -499,13 +526,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
499
526
|
...(shipping.length ? { shipping: [...shipping] } : {}),
|
|
500
527
|
discounts: recalcedOrderDiscounts,
|
|
501
528
|
payments: [...payments],
|
|
529
|
+
...(live.length ? { cashRoundings: live.map((e) => ({ ...e })) } : {}),
|
|
502
530
|
customer,
|
|
503
531
|
note,
|
|
504
532
|
...(meta.length ? { meta: meta.map((m) => ({ ...m })) } : {}),
|
|
505
533
|
subtotalMinor,
|
|
506
534
|
discountMinor,
|
|
507
535
|
taxMinor,
|
|
508
|
-
totalMinor,
|
|
536
|
+
totalMinor: total,
|
|
509
537
|
display,
|
|
510
538
|
paidMinor,
|
|
511
539
|
balanceDueMinor,
|
|
@@ -549,15 +577,15 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
549
577
|
// A `none` shipping line is untaxed as WCPOS saves it (its _woocommerce_pos_data meta clears the store's shipping taxes).
|
|
550
578
|
const untaxed = shipping ? taxStatus === 'none' || taxClass === woocommerceTax.NO_SHIPPING_TAX : taxStatus === 'none';
|
|
551
579
|
const line = wooLine(input.amountMinor, taxClass === woocommerceTax.NO_SHIPPING_TAX || (shipping && untaxed) ? undefined : taxClass,
|
|
552
|
-
inclusive, untaxed, shipping);
|
|
580
|
+
inclusive, untaxed, shipping, id);
|
|
553
581
|
return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus, ...mode,
|
|
554
582
|
...(input.storeLineId !== undefined ? { storeLineId: input.storeLineId } : {}),
|
|
555
583
|
...line };
|
|
556
584
|
}
|
|
557
|
-
const code = taxContext.getTaxRateCode?.(input.taxClass);
|
|
585
|
+
const code = taxContext.getTaxRateCode?.(input.taxClass), held = heldFor(id);
|
|
558
586
|
const line = recalculateLine({
|
|
559
587
|
id, productId: id, name: input.name, sku: '', unitPriceMinor: input.amountMinor, quantity: 1,
|
|
560
|
-
taxLines: [{ ...(code !== undefined ? { code } : {}),
|
|
588
|
+
taxLines: held ? held.map(({ code, ratePpm }) => ({ ...(code !== undefined ? { code } : {}), ratePpm, taxMicros: '0' })) : [{ ...(code !== undefined ? { code } : {}),
|
|
561
589
|
ratePpm: taxStatus === 'none' ? 0 : taxContext.getTaxRatePpm(input.taxClass), taxMicros: '0' }],
|
|
562
590
|
discounts: [], discountMinor: 0, orderDiscountMinor: 0, netMinor: 0, taxMicros: '0',
|
|
563
591
|
taxInclusive: inclusive,
|
|
@@ -577,7 +605,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
577
605
|
throw new RangeError('Regular price must be integer minor units >= 0');
|
|
578
606
|
// A rate from the tax class carries the backend's name for it when one is mapped (#287, #288).
|
|
579
607
|
const code = woo || input.taxRates ? undefined : taxContext.getTaxRateCode?.(input.taxClass);
|
|
580
|
-
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
|
|
581
609
|
: input.taxStatus === 'none' ? [{ ...(code !== undefined ? { code } : {}), ratePpm: 0 }]
|
|
582
610
|
: input.taxRates ?? [{ ...(code !== undefined ? { code } : {}), ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
|
|
583
611
|
const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
|
|
@@ -810,17 +838,30 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
810
838
|
emit();
|
|
811
839
|
},
|
|
812
840
|
|
|
813
|
-
addPayment(payment) {
|
|
841
|
+
addPayment(payment, rounding) {
|
|
814
842
|
const id = idFor(payment.id);
|
|
815
843
|
payments = [...payments, { ...payment, id }];
|
|
844
|
+
if (rounding && rounding.minor !== 0) cashRoundings = [...cashRoundings, { paymentId: id, minor: rounding.minor }];
|
|
816
845
|
emit();
|
|
817
846
|
return id;
|
|
818
847
|
},
|
|
819
848
|
|
|
820
|
-
|
|
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) {
|
|
821
861
|
const payment = payments.find((p) => p.id === paymentId);
|
|
822
862
|
if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
|
|
823
|
-
const stamp = status === 'captured' && takenAt !== undefined
|
|
863
|
+
const stamp = status === 'captured' && takenAt !== undefined
|
|
864
|
+
? { takenAt, ...(sessionId !== undefined && payment.sessionId === undefined ? { sessionId } : {}) } : {};
|
|
824
865
|
payments = payments.map((p) => p.id === paymentId ? { ...p, status, ...stamp } : p);
|
|
825
866
|
emit();
|
|
826
867
|
return true;
|
|
@@ -887,6 +928,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
887
928
|
shipping = [];
|
|
888
929
|
orderDiscounts = [];
|
|
889
930
|
payments = [];
|
|
931
|
+
cashRoundings = [];
|
|
890
932
|
customer = null;
|
|
891
933
|
note = '';
|
|
892
934
|
meta = [];
|
|
@@ -2,10 +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
8
|
import { isTakenAt } from './taken-at';
|
|
8
|
-
import type { Order } from './types';
|
|
9
|
+
import type { CashRounding, Order, Payment } from './types';
|
|
9
10
|
|
|
10
11
|
/** Apps create their drafts collection with this schema. */
|
|
11
12
|
export const orderDraftSchema: RxJsonSchema<{
|
|
@@ -38,15 +39,49 @@ export interface ParkedOrderSummary {
|
|
|
38
39
|
firstItem?: string;
|
|
39
40
|
}
|
|
40
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
|
+
|
|
41
45
|
function draftExtras(data: unknown): Pick<ParkedOrderSummary, 'paidMinor' | 'balanceDueMinor' | 'firstItem'> {
|
|
42
46
|
try {
|
|
43
|
-
const saved =
|
|
47
|
+
const saved = savedDraft(data);
|
|
44
48
|
return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
|
|
45
49
|
} catch {
|
|
46
50
|
return {}; // an unreadable draft still lists, without these figures
|
|
47
51
|
}
|
|
48
52
|
}
|
|
49
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
|
+
|
|
50
85
|
export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string> {
|
|
51
86
|
await drafts.upsert({
|
|
52
87
|
id: snapshot.id,
|
|
@@ -60,17 +95,26 @@ export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Pr
|
|
|
60
95
|
}
|
|
61
96
|
|
|
62
97
|
/**
|
|
63
|
-
* Rebuilds a saved order on `taxContext`.
|
|
64
|
-
*
|
|
65
|
-
*
|
|
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
|
|
66
103
|
* coupons back as parked, figures and all, while an unlocked leg is live (ADR-077 d3, amended 2026-11-19); otherwise none.
|
|
67
104
|
* Carried coupons always restore their priced amounts against the saved basis, keeping stale figures stale.
|
|
68
105
|
*/
|
|
69
106
|
export function restoreOrderDraft(saved: Order, options: { currency: string; taxContext: TaxContext; keepTaxRates?: boolean; keepCoupons?: boolean }): OrderBuilder {
|
|
70
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;
|
|
71
114
|
const builder = createOrderBuilder({
|
|
72
115
|
currency,
|
|
73
116
|
taxContext,
|
|
117
|
+
...(heldRates ? { heldRates } : {}),
|
|
74
118
|
id: saved.id,
|
|
75
119
|
...(saved.createdAt ? { createdAt: saved.createdAt } : {}), // #742: with every id below (fees and shipping replay whole)
|
|
76
120
|
...(saved.storeOrder !== undefined ? { storeOrder: saved.storeOrder } : {}),
|
|
@@ -87,6 +131,29 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
87
131
|
}
|
|
88
132
|
if (saved.meta?.length) builder.setMeta(saved.meta);
|
|
89
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
|
+
|
|
90
157
|
// Restore line items and their discounts
|
|
91
158
|
for (const line of saved.lineItems) {
|
|
92
159
|
const rederive = line.taxFromClass === true && !options.keepTaxRates;
|
|
@@ -136,24 +203,6 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
136
203
|
}
|
|
137
204
|
|
|
138
205
|
// Coupons are re-applied by the sale with fresh coupon data (ADR-077 d3), except carried coupons and keepCoupons below.
|
|
139
|
-
// Restore payments
|
|
140
|
-
for (const payment of saved.payments) {
|
|
141
|
-
builder.addPayment({
|
|
142
|
-
id: payment.id,
|
|
143
|
-
method: payment.method,
|
|
144
|
-
amountMinor: payment.amountMinor,
|
|
145
|
-
tenderedMinor: payment.tenderedMinor,
|
|
146
|
-
changeMinor: payment.changeMinor,
|
|
147
|
-
reference: payment.reference,
|
|
148
|
-
...(payment.status !== undefined ? { status: payment.status } : {}),
|
|
149
|
-
...(payment.storePaymentId !== undefined ? { storePaymentId: payment.storePaymentId } : {}),
|
|
150
|
-
...(payment.locked !== undefined ? { locked: payment.locked } : {}),
|
|
151
|
-
...(payment.reopened !== undefined ? { reopened: payment.reopened } : {}),
|
|
152
|
-
...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
|
|
153
|
-
...(payment.units !== undefined ? { units: payment.units } : {}),
|
|
154
|
-
...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
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');
|
|
158
207
|
if (saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried)) {
|
|
159
208
|
builder.setCoupons(saved.coupons.map((c) => c.code), { kind: 'store-priced', carried: true,
|
|
@@ -165,9 +214,12 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
165
214
|
// Kept only with a display row per coupon; a draft parked stale keeps its figures but stays stale (basis '' never matches).
|
|
166
215
|
if (options.keepCoupons && saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length) {
|
|
167
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 })) });
|
|
168
220
|
builder.setCoupons(saved.coupons.map((coupon) => coupon.code), { kind: 'kept', coupons: saved.coupons,
|
|
169
221
|
displayRows: saved.display.coupons.map((row) => row.amountMinor), lines: new Map(saved.lineItems.map((li) => [li.id, li])),
|
|
170
|
-
basis: saved.couponPricesStale ? '' :
|
|
222
|
+
basis: saved.couponPricesStale ? '' : keptBasis, linesBasis: couponPricingBasis({ ...restored, customer: null }),
|
|
171
223
|
legIds: saved.payments.filter(isLiveLeg).map((p) => p.id) });
|
|
172
224
|
}
|
|
173
225
|
return builder;
|
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,8 +191,8 @@ 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;
|
|
@@ -196,6 +201,8 @@ export interface Payment {
|
|
|
196
201
|
units?: Readonly<Record<string, number>>;
|
|
197
202
|
/** When the till recorded the leg (an ISO 8601 instant). Absent on store-held legs and on legs from before 4.2. */
|
|
198
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;
|
|
199
206
|
}
|
|
200
207
|
|
|
201
208
|
export interface CustomerSummary {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { minorUnitDigits, woocommerceTax, woocommerceCoupons } from '@tallyui/core';
|
|
2
|
-
import type {
|
|
2
|
+
import type { WooRate } from '../tax/types';
|
|
3
3
|
import { roundMicrosToMinor } from '../tax/exact';
|
|
4
4
|
import type { RateTaxLine } from '../tax/exact';
|
|
5
5
|
import type { ChargeLine, LineItem, LineTaxLine, OrderCoupon } from './types';
|
|
@@ -34,13 +34,13 @@ function lineAmounts(net: number, taxes: { total: number }[], taxLines: LineTaxL
|
|
|
34
34
|
taxMicros: taxLines.reduce((sum, rate) => sum + BigInt(rate.taxMicros), 0n).toString() };
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
/** Replays coupons on the
|
|
37
|
+
/** Replays coupons on the discounted net lines at per-line rates (a held line's parked rates, else today's); integer money only leaves (ADR-076). */
|
|
38
38
|
export function woocommerceCouponReplay(lines: readonly LineItem[], codes: readonly string[], context: OrderCouponContext,
|
|
39
|
-
|
|
39
|
+
ratesFor: (line: LineItem) => readonly WooRate[], currency: string, roundAtSubtotal: boolean,
|
|
40
40
|
pricesIncludeTax: boolean): { lines: LineItem[]; coupons: OrderCoupon[] } {
|
|
41
41
|
const dp = minorUnitDigits(currency), factor = 10 ** dp;
|
|
42
42
|
const inputLines = lines.filter((line) => line.unitPriceMinor >= 0);
|
|
43
|
-
const lineItems: woocommerceCoupons.LineItemInput[] = inputLines.map((line) => {
|
|
43
|
+
const lineItems: woocommerceCoupons.LineItemInput[] = inputLines.map((line, index) => {
|
|
44
44
|
const productId = Number(line.productId), variationId = Number(line.variantId);
|
|
45
45
|
const net = (Number(line.netMicros) / (factor * 1e6)).toFixed(6);
|
|
46
46
|
const taxes = line.taxLines.map((tax) => {
|
|
@@ -51,22 +51,19 @@ export function woocommerceCouponReplay(lines: readonly LineItem[], codes: reado
|
|
|
51
51
|
return {
|
|
52
52
|
product_id: !line.custom && Number.isSafeInteger(productId) && productId >= 0 ? productId : 0,
|
|
53
53
|
...(Number.isSafeInteger(variationId) && variationId >= 0 ? { variation_id: variationId } : {}),
|
|
54
|
-
quantity: line.quantity, tax_class: line
|
|
54
|
+
quantity: line.quantity, tax_class: `line-${index}`,
|
|
55
55
|
...(line.taxStatus === 'none' ? { tax_status: 'none' } : {}),
|
|
56
56
|
subtotal: net, total: net, taxes, subtotal_tax: tax, total_tax: tax,
|
|
57
57
|
};
|
|
58
58
|
});
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
taxRates.set(JSON.stringify([rate.id, taxClass]), { id: rate.id, rate: rate.rate, compound: rate.compound,
|
|
63
|
-
order: rate.priority, priority: rate.priority, class: taxClass });
|
|
64
|
-
}
|
|
59
|
+
// Row 498: rates are keyed per line, so a held line's coupon re-prices at its parked rate beside a fresh line of the same class.
|
|
60
|
+
const taxRates = inputLines.flatMap((line, index) => ratesFor(line).map((rate) => ({ id: rate.id, rate: rate.rate,
|
|
61
|
+
compound: rate.compound, order: rate.priority, priority: rate.priority, class: `line-${index}` })));
|
|
65
62
|
const result = woocommerceCoupons.recalculateCoupons({
|
|
66
63
|
lineItems, couponLines: codes.map((code) => ({ code })),
|
|
67
64
|
couponConfigs: new Map(codes.map((code) => [code, context.configs.get(code)!])),
|
|
68
65
|
pricesIncludeTax, calcDiscountsSequentially: context.calcDiscountsSequentially,
|
|
69
|
-
productCategories: new Map(context.productCategories), taxRates
|
|
66
|
+
productCategories: new Map(context.productCategories), taxRates,
|
|
70
67
|
taxRoundAtSubtotal: roundAtSubtotal, dp,
|
|
71
68
|
});
|
|
72
69
|
let index = 0;
|