@tallyui/pos 3.18.0 → 3.20.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 +3202 -1721
- package/dist/index.js +3871 -677
- package/package.json +6 -6
- package/src/customer-display/display-client.ts +341 -0
- package/src/customer-display/index.ts +20 -0
- package/src/customer-display/sale-display.ts +115 -0
- package/src/customer-display/snapshot-fallback.ts +138 -0
- package/src/customer-display/till-display-service.ts +304 -0
- package/src/customer-display/till-pairing.ts +177 -0
- package/src/customer-display/use-display-client.ts +25 -0
- package/src/customer-display/use-sale-display.ts +28 -0
- package/src/customer-display/use-till-pairing.ts +35 -0
- package/src/customer-display/webrtc/index.ts +5 -0
- package/src/customer-display/webrtc/peer-link.ts +222 -0
- package/src/index.ts +36 -10
- package/src/order/index.ts +2 -1
- package/src/order/order-builder.ts +104 -16
- package/src/order/types.ts +10 -4
- package/src/payment-driver/index.ts +1 -1
- package/src/payment-driver/registry.ts +23 -0
- package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
- package/src/pos-order/command.ts +27 -9
- package/src/pos-order/finalize.ts +30 -2
- package/src/pos-order/schema.ts +16 -5
- package/src/pos-order/types.ts +7 -4
- package/src/receipt/reprint.ts +3 -10
- package/src/receipt/woo-gross.ts +16 -0
- package/src/receipt-template/index.ts +8 -0
- package/src/receipt-template/render-store-template.ts +51 -0
- package/src/receipt-template/wcpos/build.ts +320 -0
- package/src/receipt-template/wcpos/context.ts +29 -0
- package/src/receipt-template/wcpos/format.ts +153 -0
- package/src/receipt-template/wcpos/from-orders.ts +203 -0
- package/src/receipt-template/wcpos/index.ts +11 -0
- package/src/receipt-template/wcpos/money.ts +42 -0
- package/src/receipt-template/wcpos/types.ts +350 -0
- package/src/register/expected.ts +60 -0
- package/src/register/index.ts +2 -2
- package/src/register/use-register-session.ts +8 -4
- package/src/sale/discount-codes.ts +7 -2
- package/src/sale/index.ts +9 -2
- package/src/sale/order-filters-query.ts +59 -0
- package/src/sale/store-priced-discount-codes.ts +52 -0
- package/src/sale/use-sale.ts +157 -16
- package/src/sale/variant-match.ts +44 -0
- package/src/scanner/camera-scan.ts +113 -0
- package/src/scanner/capabilities.ts +22 -0
- package/src/scanner/chooser-cancel.ts +8 -0
- package/src/scanner/device-identity.ts +84 -0
- package/src/scanner/device-scanner.ts +62 -0
- package/src/scanner/hid-pos-decoder.ts +60 -0
- package/src/scanner/hid-scanner.ts +171 -0
- package/src/scanner/index.ts +27 -0
- package/src/scanner/scan-dedup.ts +48 -0
- package/src/scanner/scan-events.ts +75 -0
- package/src/scanner/scan-hub-context.tsx +124 -0
- package/src/scanner/scan-session.ts +4 -0
- package/src/scanner/scanner-profiles.ts +96 -0
- package/src/scanner/serial-line-decoder.ts +58 -0
- package/src/scanner/serial-scanner.ts +227 -0
- package/src/scanner/use-barcode-scanner.ts +23 -5
- package/src/scanner/use-camera-scan.ts +57 -0
- package/src/scanner/wedge-detector.ts +28 -6
- package/src/store-settings/use-store-settings.ts +23 -5
- package/src/tax/index.ts +6 -0
- package/src/tax/location-rates.ts +46 -0
- package/src/tax/sale-tax-contexts.ts +40 -0
- package/src/tax/tax-context.ts +37 -0
- package/src/tax/tax-derivation.ts +99 -0
- package/src/tax/tax-provider.tsx +4 -31
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import type { IceServer, SignalMessage } from '@tallyui/core';
|
|
2
|
+
import { decode, type DisplayEnvelope } from '../protocol';
|
|
3
|
+
import { encode } from '../snapshot';
|
|
4
|
+
import { DISPLAY_CHANNEL, type DisplayTransport } from '../transport';
|
|
5
|
+
|
|
6
|
+
/** How the link sends and receives WebRTC signalling; U4 binds it to the connector's signal mailbox. */
|
|
7
|
+
export interface SignalPort {
|
|
8
|
+
send(message: SignalMessage): void;
|
|
9
|
+
onSignal(listener: (message: SignalMessage) => void): () => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type PeerLinkState = 'connecting' | 'open' | 'closed';
|
|
13
|
+
|
|
14
|
+
export interface PeerLink extends DisplayTransport {
|
|
15
|
+
readonly state: PeerLinkState;
|
|
16
|
+
/** Called on every state change; returns the unsubscribe. */
|
|
17
|
+
onStateChange(listener: (state: PeerLinkState) => void): () => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* An event-handler slot whose argument is checked both ways, as DOM handlers are, so the browser's own
|
|
22
|
+
* RTCPeerConnection (whose handlers take its richer event types) fits the structural interfaces below.
|
|
23
|
+
*/
|
|
24
|
+
type Handler<E> = { bivariance(event: E): void }['bivariance'] | null;
|
|
25
|
+
|
|
26
|
+
export interface SessionDescriptionLike { type?: 'offer' | 'answer' | 'pranswer' | 'rollback'; sdp?: string }
|
|
27
|
+
|
|
28
|
+
/** The structural part of RTCDataChannel the link uses. */
|
|
29
|
+
export interface RTCDataChannelLike {
|
|
30
|
+
readonly readyState: string;
|
|
31
|
+
send(data: string): void;
|
|
32
|
+
close(): void;
|
|
33
|
+
onopen: Handler<unknown>;
|
|
34
|
+
onclose: Handler<unknown>;
|
|
35
|
+
onmessage: Handler<{ data: unknown }>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The structural part of RTCPeerConnection the link uses; a test passes a fake, and a native till passes its own. */
|
|
39
|
+
export interface RTCPeerConnectionLike {
|
|
40
|
+
readonly connectionState: string;
|
|
41
|
+
createDataChannel(label: string, init: { ordered: boolean }): RTCDataChannelLike;
|
|
42
|
+
createOffer(): Promise<SessionDescriptionLike>;
|
|
43
|
+
createAnswer(): Promise<SessionDescriptionLike>;
|
|
44
|
+
setLocalDescription(description: SessionDescriptionLike): Promise<void>;
|
|
45
|
+
setRemoteDescription(description: SessionDescriptionLike): Promise<void>;
|
|
46
|
+
addIceCandidate(candidate: object): Promise<void>;
|
|
47
|
+
close(): void;
|
|
48
|
+
onicecandidate: Handler<{ candidate: { toJSON?(): unknown } | null }>;
|
|
49
|
+
ondatachannel: Handler<{ channel: RTCDataChannelLike }>;
|
|
50
|
+
onconnectionstatechange: Handler<unknown>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type PeerFactory = (config: { iceServers: IceServer[] }) => RTCPeerConnectionLike;
|
|
54
|
+
|
|
55
|
+
export interface PeerLinkOptions {
|
|
56
|
+
signal: SignalPort;
|
|
57
|
+
iceServers: IceServer[];
|
|
58
|
+
createPeer?: PeerFactory;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const browserPeer: PeerFactory = (config) => new RTCPeerConnection(config);
|
|
62
|
+
|
|
63
|
+
/** A signal payload as an object, or undefined when it is not JSON or not an object, so a bad signal is ignored. */
|
|
64
|
+
function parsePayload(payload: unknown): object | undefined {
|
|
65
|
+
if (typeof payload !== 'string') return undefined;
|
|
66
|
+
try {
|
|
67
|
+
const value: unknown = JSON.parse(payload);
|
|
68
|
+
return typeof value === 'object' && value !== null ? value : undefined;
|
|
69
|
+
} catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function createPeerLink(role: 'till' | 'display', { signal, iceServers, createPeer = browserPeer }: PeerLinkOptions): PeerLink {
|
|
75
|
+
const peer = createPeer({ iceServers });
|
|
76
|
+
const messageListeners = new Set<(envelope: DisplayEnvelope) => void>();
|
|
77
|
+
const stateListeners = new Set<(state: PeerLinkState) => void>();
|
|
78
|
+
let state: PeerLinkState = 'connecting';
|
|
79
|
+
let channel: RTCDataChannelLike | null = null;
|
|
80
|
+
let described = false;
|
|
81
|
+
let remoteSet = false;
|
|
82
|
+
// The browser refuses a candidate before the remote description, and the mailbox may deliver one first.
|
|
83
|
+
const earlyIce: object[] = [];
|
|
84
|
+
// Every peer call runs in arrival order, one at a time, so a candidate is never applied before its description.
|
|
85
|
+
let chain = Promise.resolve();
|
|
86
|
+
|
|
87
|
+
const setState = (next: PeerLinkState) => {
|
|
88
|
+
if (state === 'closed' || state === next) return;
|
|
89
|
+
state = next;
|
|
90
|
+
stateListeners.forEach((listener) => listener(next));
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const shutdown = () => {
|
|
94
|
+
if (state === 'closed') return;
|
|
95
|
+
setState('closed');
|
|
96
|
+
unsubscribe();
|
|
97
|
+
messageListeners.clear();
|
|
98
|
+
stateListeners.clear();
|
|
99
|
+
peer.onicecandidate = peer.ondatachannel = peer.onconnectionstatechange = null;
|
|
100
|
+
if (channel) channel.onopen = channel.onclose = channel.onmessage = null;
|
|
101
|
+
for (const closable of [channel, peer]) {
|
|
102
|
+
try {
|
|
103
|
+
closable?.close();
|
|
104
|
+
} catch {
|
|
105
|
+
// Already closed: nothing is left to release.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Queues a peer call; a rejection closes the link rather than escaping as an unhandled rejection. */
|
|
111
|
+
const step = (work: () => Promise<unknown>) => {
|
|
112
|
+
chain = chain.then(async () => {
|
|
113
|
+
if (state !== 'closed') await work();
|
|
114
|
+
}).catch(shutdown);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const sendSignal = (message: SignalMessage) => {
|
|
118
|
+
if (state === 'closed') return;
|
|
119
|
+
try {
|
|
120
|
+
signal.send(message);
|
|
121
|
+
} catch {
|
|
122
|
+
shutdown();
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const attach = (next: RTCDataChannelLike) => {
|
|
127
|
+
channel = next;
|
|
128
|
+
next.onopen = () => setState('open');
|
|
129
|
+
next.onclose = shutdown;
|
|
130
|
+
next.onmessage = (event) => {
|
|
131
|
+
const result = decode(event.data);
|
|
132
|
+
if (result.ok) messageListeners.forEach((listener) => listener(result.envelope));
|
|
133
|
+
};
|
|
134
|
+
if (next.readyState === 'open') setState('open');
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
peer.onicecandidate = (event) => {
|
|
138
|
+
const { candidate } = event;
|
|
139
|
+
if (!candidate) return;
|
|
140
|
+
sendSignal({ type: 'ice', payload: JSON.stringify(candidate.toJSON ? candidate.toJSON() : candidate) });
|
|
141
|
+
};
|
|
142
|
+
peer.onconnectionstatechange = () => {
|
|
143
|
+
if (peer.connectionState === 'failed' || peer.connectionState === 'closed') shutdown();
|
|
144
|
+
};
|
|
145
|
+
if (role === 'display') {
|
|
146
|
+
peer.ondatachannel = (event) => {
|
|
147
|
+
if (!channel) attach(event.channel);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const expected = role === 'till' ? 'answer' : 'offer';
|
|
152
|
+
const unsubscribe = signal.onSignal((message) => {
|
|
153
|
+
if (state === 'closed') return;
|
|
154
|
+
const payload = parsePayload(message?.payload);
|
|
155
|
+
if (!payload) return;
|
|
156
|
+
if (message.type === 'ice') {
|
|
157
|
+
if (remoteSet) step(() => peer.addIceCandidate(payload));
|
|
158
|
+
else earlyIce.push(payload);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// Only the first description counts: a second offer or answer is a replay, never a renegotiation.
|
|
162
|
+
if (message.type !== expected || described) return;
|
|
163
|
+
described = true;
|
|
164
|
+
step(async () => {
|
|
165
|
+
await peer.setRemoteDescription(payload as SessionDescriptionLike);
|
|
166
|
+
remoteSet = true;
|
|
167
|
+
for (const candidate of earlyIce.splice(0)) await peer.addIceCandidate(candidate);
|
|
168
|
+
if (role === 'display') {
|
|
169
|
+
const answer = await peer.createAnswer();
|
|
170
|
+
await peer.setLocalDescription(answer);
|
|
171
|
+
sendSignal({ type: 'answer', payload: JSON.stringify(answer) });
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
if (role === 'till') {
|
|
177
|
+
step(async () => {
|
|
178
|
+
attach(peer.createDataChannel(DISPLAY_CHANNEL, { ordered: true }));
|
|
179
|
+
const offer = await peer.createOffer();
|
|
180
|
+
await peer.setLocalDescription(offer);
|
|
181
|
+
sendSignal({ type: 'offer', payload: JSON.stringify(offer) });
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
get state() {
|
|
187
|
+
return state;
|
|
188
|
+
},
|
|
189
|
+
send(envelope) {
|
|
190
|
+
if (channel?.readyState !== 'open') return false;
|
|
191
|
+
try {
|
|
192
|
+
channel.send(encode(envelope));
|
|
193
|
+
return true;
|
|
194
|
+
} catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
onMessage(listener) {
|
|
199
|
+
messageListeners.add(listener);
|
|
200
|
+
return () => {
|
|
201
|
+
messageListeners.delete(listener);
|
|
202
|
+
};
|
|
203
|
+
},
|
|
204
|
+
onStateChange(listener) {
|
|
205
|
+
stateListeners.add(listener);
|
|
206
|
+
return () => {
|
|
207
|
+
stateListeners.delete(listener);
|
|
208
|
+
};
|
|
209
|
+
},
|
|
210
|
+
close: shutdown,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The till's end (the offerer): it opens the one ordered display channel and sends the offer (ADR-085 d1). */
|
|
215
|
+
export function createTillPeerLink(options: PeerLinkOptions): PeerLink {
|
|
216
|
+
return createPeerLink('till', options);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A display's end (the answerer): it answers the first offer and takes the till's channel. */
|
|
220
|
+
export function createDisplayPeerLink(options: PeerLinkOptions): PeerLink {
|
|
221
|
+
return createPeerLink('display', options);
|
|
222
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -13,11 +13,12 @@ export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './curre
|
|
|
13
13
|
export type { CurrencyFormat, CurrencyProviderProps } from './currency';
|
|
14
14
|
|
|
15
15
|
// Tax
|
|
16
|
-
export { TaxProvider, useTax, taxLogger } from './tax';
|
|
16
|
+
export { TaxProvider, useTax, taxLogger, taxSettingsForLocation, createTaxContext, saleTaxContexts, taxDerivation } from './tax';
|
|
17
17
|
export { MICROS_PER_MINOR, ratePpmFromPercent, taxMicros, roundMicrosToMinor, computeOrderTax, taxLinesByRate } from './tax';
|
|
18
18
|
export type { TaxLineInput, OrderTaxTotals, RateTaxLine } from './tax';
|
|
19
19
|
export type { TaxProviderProps } from './tax';
|
|
20
|
-
export type { TaxRateMap, TaxContext } from './tax';
|
|
20
|
+
export type { TaxRateMap, TaxContext, SaleTaxContext } from './tax';
|
|
21
|
+
export type { TaxDerivation, TaxDerivationClass, TaxDerivationRate, TaxRateWhy, SaleTaxLocation } from './tax';
|
|
21
22
|
|
|
22
23
|
// Store settings
|
|
23
24
|
export { resolveStoreSettings, useStoreSettings, withPricingContext, taxProviderProps } from './store-settings';
|
|
@@ -48,7 +49,8 @@ export { createOrderBuilder, createOrderManager, allocateOrderDiscount, taxFigur
|
|
|
48
49
|
export { orderDraftSchema, writeOrderDraft, restoreOrderDraft, parkedOrderSummaries$ } from './order';
|
|
49
50
|
export { useParkedSales } from './order';
|
|
50
51
|
export type { BasketLine } from './order';
|
|
51
|
-
export
|
|
52
|
+
export { couponPricingBasis } from './order';
|
|
53
|
+
export type { OrderBuilder, OrderBuilderOptions, OrderCouponContext, StorePricedCoupon, StorePricedCouponContext } from './order';
|
|
52
54
|
export type { OrderManager, OrderManagerOptions, ParkedOrderSummary } from './order';
|
|
53
55
|
export type {
|
|
54
56
|
Order,
|
|
@@ -77,22 +79,44 @@ export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, Rece
|
|
|
77
79
|
// Receipt templates
|
|
78
80
|
export { parseXml, renderHtml, sanitizeHtml, renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview, receiptTemplateData, DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS, renderReceiptHtml } from './receipt-template';
|
|
79
81
|
export type { ThermalNode, ReceiptNode, SanitizeHtmlOptions, RenderSanitizeOptions, ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions, ReceiptPaper, RenderReceiptOptions } from './receipt-template';
|
|
82
|
+
export { wcposReceiptData, formatWcposReceiptData, formatWcposMoney, WCPOS_DEFAULT_I18N, WCPOS_TAX_ID_LABELS } from './receipt-template';
|
|
83
|
+
export { wcposSourceFromSentOrder, wcposSourceFromPosOrder, wcposSourceFromStoreOrder, wcposReceiptContext, renderStoreReceiptTemplate } from './receipt-template';
|
|
84
|
+
export type { PrintableSale, StoreTemplateContext } from './receipt-template';
|
|
85
|
+
export type { FormatWcposReceiptOptions, WcposMoneyOptions, WcposReceiptSource, WcposReceiptStore, WcposReceiptOptions, WcposReceiptData, WcposReceiptView, WcposTaxId, WcposReceiptDate, WcposReceiptLine, WcposLineView } from './receipt-template';
|
|
80
86
|
|
|
81
87
|
// Customer display
|
|
82
88
|
export { DISPLAY_PROTOCOL_VERSION, DISPLAY_ACTIONS, makeEnvelope, displayCart, decode as decodeDisplayMessage, encode as encodeDisplayMessage, messageBytes, MAX_MESSAGE_BYTES, displayReducer, initialDisplayState } from './customer-display';
|
|
83
89
|
export type { PaymentPhase, DisplayTemplate, DisplayCart, DisplayPayment, DisplayConfig, DisplayPayloads, DisplayAction, DisplayEnvelope, DecodeRefusal, DecodeResult, DisplayView, DisplayState } from './customer-display';
|
|
84
90
|
export { DISPLAY_CHANNEL, createBroadcastDisplayTransport, createDisplayLink, useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './customer-display';
|
|
85
91
|
export type { DisplayTransport, BroadcastChannelLike, DisplayLink, DisplayClock } from './customer-display';
|
|
92
|
+
export { createSaleDisplayPublisher, derivePaymentEvent, useSaleDisplay } from './customer-display';
|
|
93
|
+
export type { SaleDisplayOptions, SaleDisplayInput, SaleDisplayPublisher } from './customer-display';
|
|
94
|
+
export { createTillPeerLink, createDisplayPeerLink } from './customer-display';
|
|
95
|
+
export type { SignalPort, PeerLink, PeerLinkState, PeerLinkOptions, PeerFactory, RTCPeerConnectionLike, RTCDataChannelLike, SessionDescriptionLike } from './customer-display';
|
|
96
|
+
export { createDisplayClient, COLLECT_POLL_MS, DISPLAY_SIGNAL_POLL_MS, OPEN_SIGNAL_POLL_MS, SNAPSHOT_POLL_MS, useDisplayClient } from './customer-display';
|
|
97
|
+
export type { DisplayClient, DisplayClientOptions, DisplayClientPhase, DisplayClientError, DisplayTokenStore, DisplayClientView } from './customer-display';
|
|
98
|
+
export { createTillDisplayService, SIGNAL_POLL_MS, LIST_POLL_MS, CONNECT_TIMEOUT_MS, createSnapshotSender, SNAPSHOT_MIN_INTERVAL_MS, SNAPSHOT_RESEND_MS, SNAPSHOT_LIFETIME_MS } from './customer-display';
|
|
99
|
+
export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayEntry, ServiceClock, SnapshotSender, SnapshotSenderOptions, SnapshotBody } from './customer-display';
|
|
100
|
+
export { createTillPairing, PENDING_POLL_MS, useTillPairing, useTillDisplays } from './customer-display';
|
|
101
|
+
export type { TillPairing, TillPairingOptions, PairingPhase, PairingError, TillPairingView, TillDisplaysView } from './customer-display';
|
|
86
102
|
|
|
87
103
|
// Product
|
|
88
104
|
export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory } from './product';
|
|
89
105
|
|
|
90
106
|
// Scanner
|
|
91
|
-
export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner } from './scanner';
|
|
92
|
-
export
|
|
107
|
+
export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner, SCANNER_DEVICE_KEY_MAX_LENGTH, normalizeUuid, isCanonicalUuid, scannerDeviceKey, scannerTransport, createSerialLineDecoder, decodeHidPosReport, isWebSerialSupported, isWebHidSupported, isChooserCancel, SCANNER_PROFILES_COLLECTION, scannerProfileSchema, scannerProfileCollection, addScannerProfileCollection, scannerProfiles$, readScannerProfiles, saveScannerProfile, removeScannerProfile, createScanHub, createScanBus, inertScanHub, dedupeScans, SCAN_DEDUP_WINDOW_MS } from './scanner';
|
|
108
|
+
export { scannerProfileStore, createDeviceScannerStateCell, createSerialScanner, serialPortIdentity, DEFAULT_SERIAL_BAUD_RATE, STANDARD_SPP_SERVICE_CLASS_ID } from './scanner';
|
|
109
|
+
export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector, ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession, UseBarcodeScannerOptions, ScannerConnectionType, ScannerIdentity, ScannerTransport, SerialLineDecoderOptions, SerialLineDecoder, HidPosDecodeOptions, HidPosResult, ScannerProfile, ScannerProfileCollection, ScanSourceKind, ScanSource, ScanEvent, ScanBus, ScanHub, WedgeScanMeta } from './scanner';
|
|
110
|
+
export type { ScannerProfileStore, DeviceScannerSettings, DeviceScannerState, DeviceScannerErrorPhase, DeviceScannerErrorHandler, DeviceScannerStateCell, DeviceScanner, SerialPortInfoLike, SerialPortLike, SerialLike, SerialScannerOptions } from './scanner';
|
|
111
|
+
export { createHidScanner, HID_POS_USAGE_PAGE } from './scanner';
|
|
112
|
+
export type { HidInputReportEventLike, HidDeviceLike, HidLike, HidScannerOptions } from './scanner';
|
|
113
|
+
export { ScanHubProvider, useScanHub, useDeviceScanControls, inertDeviceScanControls, scanTimeOf } from './scanner';
|
|
114
|
+
export type { DeviceScanControl, DeviceScanControls, ScanHubProviderProps } from './scanner';
|
|
115
|
+
export { CAMERA_BARCODE_TYPES, DETECTOR_FORMATS, detectorFormatToSymbology, nativeBarcodeDetector, DEFAULT_DECODE_INTERVAL_MS, DECODER_ERROR_THRESHOLD, startDecodeLoop, cameraErrorStatus, CAMERA_CONSTRAINTS, useCameraScan } from './scanner';
|
|
116
|
+
export type { DetectedBarcode, CameraDecoder, ViewfinderStatus, DecodeLoopOptions, UseCameraScanOptions, CameraScan } from './scanner';
|
|
93
117
|
|
|
94
118
|
// Payment drivers
|
|
95
|
-
export { createPaymentDriverRegistry, driverForMethod, createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './payment-driver';
|
|
119
|
+
export { createPaymentDriverRegistry, driverForMethod, methodDrivers, methodForProvider, createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './payment-driver';
|
|
96
120
|
export type {
|
|
97
121
|
DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
|
|
98
122
|
CollectOutcome, CollectResult, DriverStatusSource, PaymentDriver, PaymentDriverRegistry,
|
|
@@ -112,12 +136,14 @@ export type {
|
|
|
112
136
|
} from './print';
|
|
113
137
|
|
|
114
138
|
// Sale
|
|
115
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, cartQuantities } from './sale';
|
|
116
|
-
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, CartQuantityLine } from './sale';
|
|
139
|
+
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
|
|
140
|
+
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
|
|
117
141
|
|
|
118
142
|
export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
119
143
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
120
144
|
export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
145
|
+
export { TAX_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
|
|
146
|
+
export { CUSTOMER_RETAX_REFUSED } from './sale/use-sale';
|
|
121
147
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions } from './pos-order';
|
|
122
148
|
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, useOrderOutbox, outboxLogger } from './outbox';
|
|
123
149
|
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
@@ -132,8 +158,8 @@ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, chang
|
|
|
132
158
|
export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid, PaymentLegStatus } from './tender';
|
|
133
159
|
|
|
134
160
|
// Register
|
|
135
|
-
export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
|
|
136
|
-
export type { MovementType, LedgerRow, Movement } from './register';
|
|
161
|
+
export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, deriveDrawerTerms, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
|
|
162
|
+
export type { MovementType, LedgerRow, Movement, DrawerTerm, DrawerTerms } from './register';
|
|
137
163
|
export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './register';
|
|
138
164
|
export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './register';
|
|
139
165
|
export type { RegisterSession, CashMovement, Closure } from './register';
|
package/src/order/index.ts
CHANGED
|
@@ -2,7 +2,8 @@ export { createOrderBuilder } from './order-builder';
|
|
|
2
2
|
export { taxFiguresForBasket } from './tax-figures';
|
|
3
3
|
export type { BasketLine } from './tax-figures';
|
|
4
4
|
export { allocateOrderDiscount } from './allocate-order-discount';
|
|
5
|
-
export
|
|
5
|
+
export { couponPricingBasis } from './order-builder';
|
|
6
|
+
export type { OrderBuilder, OrderBuilderOptions, OrderCouponContext, StorePricedCoupon, StorePricedCouponContext } from './order-builder';
|
|
6
7
|
export { createOrderManager } from './order-manager';
|
|
7
8
|
export { orderDraftSchema, writeOrderDraft, restoreOrderDraft, parkedOrderSummaries$ } from './order-drafts';
|
|
8
9
|
export { useParkedSales } from './use-parked-sales';
|
|
@@ -17,6 +17,9 @@ import type {
|
|
|
17
17
|
ChargeInput, ChargeLine, FeeLine, ShippingLine,
|
|
18
18
|
} from './types';
|
|
19
19
|
|
|
20
|
+
/** splitLine's refusal: a fixed line discount copied onto every split line would multiply it. */
|
|
21
|
+
export const SPLIT_FIXED_DISCOUNT = 'Remove the line’s fixed discount before splitting it';
|
|
22
|
+
|
|
20
23
|
/** Tax contexts already warned that per_rate_group_items fell back to per_order for inclusive lines (#287). */
|
|
21
24
|
const perRateGroupWarned = new WeakSet<TaxContext>();
|
|
22
25
|
|
|
@@ -81,6 +84,29 @@ export interface OrderCouponContext {
|
|
|
81
84
|
calcDiscountsSequentially: boolean;
|
|
82
85
|
}
|
|
83
86
|
|
|
87
|
+
/** One code's amounts as the store priced them (TallyUI#709): per line, in that line's own tax mode. */
|
|
88
|
+
export interface StorePricedCoupon {
|
|
89
|
+
couponId: string; // the store's id for the code, non-empty
|
|
90
|
+
lines: ReadonlyArray<{ lineId: string; amountMinor: number }>; // safe integers >= 0, each lineId at most once
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Coupons priced by the store (TallyUI#709): the till applies the amounts and never computes a coupon's value. */
|
|
94
|
+
export interface StorePricedCouponContext {
|
|
95
|
+
kind: 'store-priced';
|
|
96
|
+
priced: ReadonlyMap<string, StorePricedCoupon>; // lower-case code to its priced amounts
|
|
97
|
+
/** couponPricingBasis(order) of the order the store priced. */
|
|
98
|
+
basis: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** What a store-priced coupon's amounts depend on (TallyUI#709). A price is good only while this is unchanged. */
|
|
102
|
+
export function couponPricingBasis(order: Order): string {
|
|
103
|
+
// Inputs only, never a computed figure, so applying or removing coupons can't change it.
|
|
104
|
+
return JSON.stringify([order.currency, order.customer?.id ?? null,
|
|
105
|
+
order.lineItems.map((li) => [li.id, li.productId, li.variantId ?? null, li.quantity, li.unitPriceMinor, li.taxInclusive,
|
|
106
|
+
li.taxClass ?? null, li.taxStatus ?? null, li.discounts.map((d) => [d.type, d.value])]),
|
|
107
|
+
order.discounts.map((d) => [d.type, d.value])]);
|
|
108
|
+
}
|
|
109
|
+
|
|
84
110
|
export interface OrderBuilderOptions {
|
|
85
111
|
currency: string;
|
|
86
112
|
taxContext: TaxContext;
|
|
@@ -99,6 +125,12 @@ export interface OrderBuilder {
|
|
|
99
125
|
updateShipping(id: string, patch: Partial<ChargeInput & { methodId?: string }>): void;
|
|
100
126
|
removeShipping(id: string): void;
|
|
101
127
|
updateQuantity(lineId: string, quantity: number): void;
|
|
128
|
+
/**
|
|
129
|
+
* Splits a line of quantity N into N lines of quantity 1 (v2's cart Split): the line keeps its id at quantity 1 and
|
|
130
|
+
* N − 1 copies with fresh ids, and fresh discount ids, follow it. Returns the new lines' ids; `[]`, emitting nothing,
|
|
131
|
+
* for quantity 1 or an unknown line. Throws a RangeError (SPLIT_FIXED_DISCOUNT) for a line with a fixed discount.
|
|
132
|
+
*/
|
|
133
|
+
splitLine(lineId: string): string[];
|
|
102
134
|
/** Sets a line's unit price (a till price edit), in minor units of the order's currency and the line's own tax mode; its discounts and tax are recomputed. */
|
|
103
135
|
setUnitPrice(lineId: string, amountMinor: number): void;
|
|
104
136
|
removeItem(lineId: string): void;
|
|
@@ -111,14 +143,14 @@ export interface OrderBuilder {
|
|
|
111
143
|
setCustomer(customer: CustomerSummary | null): void;
|
|
112
144
|
setNote(note: string): void;
|
|
113
145
|
/** Replaces the coupon codes with their trimmed, lower-case, deduplicated list; a given context replaces the builder's coupon context. */
|
|
114
|
-
setCoupons(codes: readonly string[], context?: OrderCouponContext): void;
|
|
146
|
+
setCoupons(codes: readonly string[], context?: OrderCouponContext | StorePricedCouponContext): void;
|
|
115
147
|
clear(): void;
|
|
116
148
|
getSnapshot(): Order;
|
|
117
149
|
}
|
|
118
150
|
|
|
119
151
|
export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
120
152
|
const { taxContext } = options;
|
|
121
|
-
let
|
|
153
|
+
let couponContext: OrderCouponContext | StorePricedCouponContext | undefined = options.couponContext;
|
|
122
154
|
const currency = options.currency.toUpperCase();
|
|
123
155
|
const orderId = options.id ?? uid();
|
|
124
156
|
const woo = taxContext.rounding?.granularity === 'woocommerce' && taxContext.getTaxRates ? taxContext.rounding : undefined;
|
|
@@ -143,7 +175,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
143
175
|
const subject = new BehaviorSubject<Order>(buildOrder());
|
|
144
176
|
|
|
145
177
|
/** Stored lines carry no order share; buildOrder recalculates each with its allocated share (ADR-062). */
|
|
146
|
-
function recalculateLine(line: LineItem, orderDiscountMinor = 0): LineItem {
|
|
178
|
+
function recalculateLine(line: LineItem, orderDiscountMinor = 0, couponMinor = 0): LineItem {
|
|
147
179
|
const grossMinor = line.unitPriceMinor * line.quantity;
|
|
148
180
|
|
|
149
181
|
// Each amount is what that discount actually removed, capped at what's left, matching buildOrder's order-discount path (ADR-062).
|
|
@@ -157,7 +189,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
157
189
|
// The order share never exceeds what the line discounts leave (allocateOrderDiscount's bound).
|
|
158
190
|
const lineDiscountMinor = Math.min(grossMinor, recalcedDiscounts.reduce((sum, d) => sum + d.amountMinor, 0));
|
|
159
191
|
const discountMinor = lineDiscountMinor + orderDiscountMinor;
|
|
160
|
-
|
|
192
|
+
// Store-priced coupons (#709) come off what the discounts leave, capped there; discountMinor never includes them (v6).
|
|
193
|
+
const netMinor = grossMinor - discountMinor - Math.max(0, Math.min(couponMinor, grossMinor - discountMinor));
|
|
161
194
|
if (woo) return { ...line, discounts: recalcedDiscounts, discountMinor, orderDiscountMinor,
|
|
162
195
|
...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === 'none') };
|
|
163
196
|
const combinedRate = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
|
|
@@ -212,17 +245,40 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
212
245
|
});
|
|
213
246
|
const shares = allocateOrderDiscount(lineAmounts, recalcedOrderDiscounts.reduce((sum, d) => sum + d.amountMinor, 0));
|
|
214
247
|
const displaySourceLines = lineItems.map((li, index) => recalculateLine(li, shares[index]));
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
248
|
+
const store = couponContext && 'kind' in couponContext ? couponContext : undefined;
|
|
249
|
+
const replay = woo && couponCodes.length && !store ? woocommerceCouponReplay(displaySourceLines, couponCodes,
|
|
250
|
+
couponContext as OrderCouponContext, taxContext.getTaxRates!, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax) : undefined;
|
|
251
|
+
let lines = replay?.lines ?? displaySourceLines;
|
|
218
252
|
|
|
219
253
|
if (woo) shipping = shipping.map((charge) => ({ ...charge, ...recalculateCharge(charge.id, charge, true) }));
|
|
220
|
-
const wooTotals = woo ? woocommerceTotals(lines, fees, shipping, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax) : undefined;
|
|
221
|
-
const { subtotalMinor } = wooTotals ?? sumLines(lines, taxContext.rounding);
|
|
222
254
|
const charges = [...fees, ...shipping];
|
|
223
|
-
const
|
|
224
|
-
taxMicros: charge.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n).toString() }))
|
|
225
|
-
const
|
|
255
|
+
const taxedCharges = charges.map((charge) => ({ ...charge, taxInclusive: taxContext.pricesIncludeTax,
|
|
256
|
+
taxMicros: charge.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n).toString() }));
|
|
257
|
+
const settle = (items: LineItem[]) => woo ? woocommerceTotals(items, fees, shipping, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax)
|
|
258
|
+
: { ...sumLines([...items, ...taxedCharges], taxContext.rounding), subtotalMinor: sumLines(items, taxContext.rounding).subtotalMinor };
|
|
259
|
+
let totals = settle(lines);
|
|
260
|
+
let coupons = replay?.coupons;
|
|
261
|
+
const displayBasis = (t: typeof totals) => taxContext.pricesIncludeTax ? t.totalMinor : t.totalMinor - t.taxMinor;
|
|
262
|
+
const storeDisplayRows: number[] = [];
|
|
263
|
+
if (store && couponCodes.length) {
|
|
264
|
+
// #709: each code's amounts come off its lines in code order; its figures are what it took off the settlement
|
|
265
|
+
// totals, so they telescope: Σ discountMinor = S₀ − S and Σ discountTaxMinor = T₀ − T exactly.
|
|
266
|
+
const taken = new Map<string, number>();
|
|
267
|
+
coupons = couponCodes.map((code) => {
|
|
268
|
+
const priced = store.priced.get(code);
|
|
269
|
+
for (const { lineId, amountMinor } of priced?.lines ?? []) taken.set(lineId, (taken.get(lineId) ?? 0) + amountMinor);
|
|
270
|
+
lines = lineItems.map((li, index) => taken.has(li.id) ? recalculateLine(li, shares[index], taken.get(li.id)) : displaySourceLines[index]);
|
|
271
|
+
const before = totals;
|
|
272
|
+
totals = settle(lines);
|
|
273
|
+
storeDisplayRows.push(displayBasis(before) - displayBasis(totals));
|
|
274
|
+
// A settlement subtotal is a difference of separately rounded sums (lines total less order-rounded tax), so a
|
|
275
|
+
// rounding cent could in principle move it against a coupon; a coupon never shows as raising the price.
|
|
276
|
+
return { code, couponId: priced?.couponId ?? '', discountMinor: Math.max(0, before.subtotalMinor - totals.subtotalMinor),
|
|
277
|
+
discountTaxMinor: Math.max(0, before.taxMinor - totals.taxMinor) };
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
const { subtotalMinor, taxMinor, totalMinor } = totals;
|
|
281
|
+
const taxedLines = [...lines, ...taxedCharges];
|
|
226
282
|
if (taxContext.rounding?.granularity === 'per_rate_group_items' && taxedLines.some((li) => li.taxInclusive) && !perRateGroupWarned.has(taxContext)) {
|
|
227
283
|
perRateGroupWarned.add(taxContext);
|
|
228
284
|
taxLogger.warn('per_rate_group_items with inclusive lines: using per_order figures until the display has a rounding row (#287, #310)');
|
|
@@ -249,8 +305,10 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
249
305
|
});
|
|
250
306
|
const displayLines = figures.map((f) => f.line);
|
|
251
307
|
const orderDiscountDisplay = figures.reduce((sum, f) => sum + f.shareMinor, 0);
|
|
252
|
-
|
|
253
|
-
|
|
308
|
+
// A store-priced row (#709) is the drop it caused in the figure the display subtotal is derived from: the
|
|
309
|
+
// order-rounded tax over lines and charges can put discountMinor + discountTaxMinor a cent off it, and the display must add up.
|
|
310
|
+
const displayCoupons = coupons?.map(({ code, discountMinor, discountTaxMinor }, k) =>
|
|
311
|
+
({ code, amountMinor: store ? storeDisplayRows[k] : discountMinor + (taxInclusive ? discountTaxMinor : 0) }));
|
|
254
312
|
const displayDiscount = displayLines.reduce(
|
|
255
313
|
(sum, line) => line.discounts.reduce((lineSum, d) => lineSum + d.amountMinor, sum), orderDiscountDisplay)
|
|
256
314
|
+ (displayCoupons?.reduce((sum, row) => sum + row.amountMinor, 0) ?? 0);
|
|
@@ -288,6 +346,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
288
346
|
// Checked here, not only in tests: every figure >= 0, and no line shows less than its own rows and share (lines
|
|
289
347
|
// with a non-negative gross; a return line's negative amount is its own).
|
|
290
348
|
if (displayDiscount < 0) throw new Error(`Display discount ${displayDiscount} is negative (ADR-063)`);
|
|
349
|
+
const negativeCoupon = displayCoupons?.find((row) => row.amountMinor < 0);
|
|
350
|
+
if (negativeCoupon) throw new Error(`Display coupon ${negativeCoupon.code} is negative (ADR-063)`);
|
|
291
351
|
for (const { line, shareMinor, returned } of figures) {
|
|
292
352
|
if (returned && line.discounts.length > 0) throw new Error(`Return line ${line.lineId} shows discount rows (ADR-063)`);
|
|
293
353
|
if (returned || woo) continue;
|
|
@@ -307,11 +367,11 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
307
367
|
const balanceDueMinor = Math.max(0, totalMinor - paidMinor);
|
|
308
368
|
const changeDueMinor = Math.max(0, paidMinor - totalMinor);
|
|
309
369
|
|
|
310
|
-
|
|
370
|
+
const order: Order = {
|
|
311
371
|
id: orderId,
|
|
312
372
|
status: 'draft',
|
|
313
373
|
lineItems: lines,
|
|
314
|
-
...(
|
|
374
|
+
...(coupons ? { coupons } : {}),
|
|
315
375
|
...(fees.length ? { fees: [...fees] } : {}),
|
|
316
376
|
...(shipping.length ? { shipping: [...shipping] } : {}),
|
|
317
377
|
discounts: recalcedOrderDiscounts,
|
|
@@ -332,6 +392,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
332
392
|
createdAt: now,
|
|
333
393
|
updatedAt: new Date().toISOString(),
|
|
334
394
|
};
|
|
395
|
+
// #709: the store's amounts still apply while stale, so the cart shows the last known prices; finalize refuses it.
|
|
396
|
+
if (store && couponCodes.length && couponPricingBasis(order) !== store.basis) order.couponPricesStale = true;
|
|
397
|
+
return order;
|
|
335
398
|
}
|
|
336
399
|
|
|
337
400
|
function emit() {
|
|
@@ -508,6 +571,19 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
508
571
|
emit();
|
|
509
572
|
},
|
|
510
573
|
|
|
574
|
+
splitLine(lineId) {
|
|
575
|
+
const index = lineItems.findIndex((li) => li.id === lineId);
|
|
576
|
+
const source = lineItems[index];
|
|
577
|
+
if (!source || source.quantity <= 1) return [];
|
|
578
|
+
if (source.discounts.some((d) => d.type === 'fixed')) throw new RangeError(SPLIT_FIXED_DISCOUNT);
|
|
579
|
+
// Not through addLine, whose merge would fold the copies back into one line.
|
|
580
|
+
const copies = Array.from({ length: source.quantity - 1 }, () =>
|
|
581
|
+
recalculateLine({ ...source, id: uid(), quantity: 1, discounts: source.discounts.map((d) => ({ ...d, id: uid() })) }));
|
|
582
|
+
lineItems = [...lineItems.slice(0, index), recalculateLine({ ...source, quantity: 1 }), ...copies, ...lineItems.slice(index + 1)];
|
|
583
|
+
emit();
|
|
584
|
+
return copies.map((li) => li.id);
|
|
585
|
+
},
|
|
586
|
+
|
|
511
587
|
setUnitPrice(lineId, amountMinor) {
|
|
512
588
|
if (!Number.isInteger(amountMinor)) throw new RangeError('Price must be integer minor units');
|
|
513
589
|
if (amountMinor < 0) throw new RangeError('Price must be >= 0');
|
|
@@ -594,6 +670,17 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
594
670
|
const normalized = [...new Set(codes.map((code) => code.trim().toLowerCase()))];
|
|
595
671
|
if (normalized.length && !nextContext) throw new Error('Coupon context is required');
|
|
596
672
|
for (const code of normalized) {
|
|
673
|
+
if (nextContext && 'kind' in nextContext) {
|
|
674
|
+
const priced = nextContext.priced.get(code);
|
|
675
|
+
if (!priced) throw new RangeError(`Unknown coupon ${code}`);
|
|
676
|
+
if (!priced.couponId) throw new RangeError(`Coupon ${code} has no id`);
|
|
677
|
+
const ids = priced.lines.map((line) => line.lineId);
|
|
678
|
+
if (new Set(ids).size !== ids.length || priced.lines.some((line) => !Number.isSafeInteger(line.amountMinor) || line.amountMinor < 0))
|
|
679
|
+
throw new RangeError(`Coupon ${code} has an invalid amount`);
|
|
680
|
+
if (ids.some((id) => !lineItems.some((li) => li.id === id && li.unitPriceMinor >= 0)))
|
|
681
|
+
throw new RangeError(`Coupon ${code} prices a line not on the sale`);
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
597
684
|
const config = nextContext!.configs.get(code);
|
|
598
685
|
if (!config) throw new RangeError(`Unknown coupon ${code}`);
|
|
599
686
|
// The engine needs the regular price as WCPOS pos_data to find sale lines, which would also reset manual price cuts; lifting this waits (ADR-077 d3).
|
|
@@ -615,6 +702,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
615
702
|
customer = null;
|
|
616
703
|
note = '';
|
|
617
704
|
couponCodes = [];
|
|
705
|
+
if (couponContext && 'kind' in couponContext) couponContext = undefined;
|
|
618
706
|
emit();
|
|
619
707
|
},
|
|
620
708
|
|
package/src/order/types.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type { Money, TaxRounding } from '@tallyui/core';
|
|
1
|
+
import type { CustomerAddress, Money, TaxRounding } from '@tallyui/core';
|
|
2
2
|
import type { PaymentLegStatus } from '../tender/payment-legs';
|
|
3
3
|
|
|
4
4
|
export interface OrderCoupon {
|
|
5
5
|
code: string; // lower-case code
|
|
6
6
|
couponId: string; // the connector's coupon id, as a string
|
|
7
|
-
discountMinor: number; //
|
|
7
|
+
discountMinor: number; // the coupon's discount (WooCommerce's replay, or the store's own prices, #709), ex tax, in integer minor units
|
|
8
8
|
discountTaxMinor: number; // its tax, in integer minor units
|
|
9
9
|
}
|
|
10
10
|
|
|
@@ -15,8 +15,10 @@ export interface Order {
|
|
|
15
15
|
fees?: FeeLine[];
|
|
16
16
|
shipping?: ShippingLine[];
|
|
17
17
|
discounts: AppliedDiscount[];
|
|
18
|
-
/** Present only
|
|
18
|
+
/** Present only when coupons are set, by WooCommerce's replay or at the store's prices (#709); discountMinor excludes coupons, which are carried here. */
|
|
19
19
|
coupons?: OrderCoupon[];
|
|
20
|
+
/** TallyUI#709: present (true) only when store-priced coupons are set and couponPricingBasis(order) no longer equals their basis. */
|
|
21
|
+
couponPricesStale?: true;
|
|
20
22
|
payments: Payment[];
|
|
21
23
|
customer: CustomerSummary | null;
|
|
22
24
|
note: string;
|
|
@@ -90,7 +92,7 @@ export interface LineItem {
|
|
|
90
92
|
discounts: AppliedDiscount[];
|
|
91
93
|
discountMinor: number; // line discounts + orderDiscountMinor, in the line's own mode
|
|
92
94
|
orderDiscountMinor: number; // this line's allocated share of the order discounts (ADR-062)
|
|
93
|
-
netMinor: number; // unitPriceMinor × quantity − discountMinor; under WooCommerce, the rounded exclusive net
|
|
95
|
+
netMinor: number; // unitPriceMinor × quantity − discountMinor − any coupons; under WooCommerce, the rounded exclusive net
|
|
94
96
|
taxMicros: string; // Σ taxLines[].taxMicros, decimal string of a bigint
|
|
95
97
|
taxInclusive: boolean; // the price's own tax mode; the order's when the price has none
|
|
96
98
|
/** Set only when the price's tax mode differs from the order's; named price mode → order mode. */
|
|
@@ -150,6 +152,10 @@ export interface CustomerSummary {
|
|
|
150
152
|
id: string;
|
|
151
153
|
name: string;
|
|
152
154
|
email?: string;
|
|
155
|
+
/** A picked customer's addresses (a `Customer` carries them): kept on the open sale for its tax location, and sent at
|
|
156
|
+
* order.create 8 when the sale was taxed on one of them (#722). */
|
|
157
|
+
billing?: CustomerAddress;
|
|
158
|
+
shipping?: CustomerAddress;
|
|
153
159
|
}
|
|
154
160
|
|
|
155
161
|
export interface PaymentMethod {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createPaymentDriverRegistry, driverForMethod } from './registry';
|
|
1
|
+
export { createPaymentDriverRegistry, driverForMethod, methodDrivers, methodForProvider } from './registry';
|
|
2
2
|
export { createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './simulated-driver';
|
|
3
3
|
export type {
|
|
4
4
|
DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
|
|
@@ -37,3 +37,26 @@ export function driverForMethod(
|
|
|
37
37
|
): PaymentDriver | undefined {
|
|
38
38
|
return method?.capture.mode === 'device' ? registry.get(method.capture.provider) : undefined;
|
|
39
39
|
}
|
|
40
|
+
|
|
41
|
+
/** The first of `methods` a driver for `provider` takes on a device: primary `capture.mode === 'device'` and
|
|
42
|
+
* `capture.provider === provider` (WCPOS v2 apps/main/lib/payment-drivers.ts `deviceMethod`). Null when none. */
|
|
43
|
+
export function methodForProvider(
|
|
44
|
+
methods: readonly PaymentMethodDescriptor[],
|
|
45
|
+
provider: string,
|
|
46
|
+
): PaymentMethodDescriptor | null {
|
|
47
|
+
return methods.find((method) => method.capture.mode === 'device' && method.capture.provider === provider) ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Each method's id mapped to the registered driver that takes it (`driverForMethod`), for the methods that have one,
|
|
51
|
+
* in `methods` order. */
|
|
52
|
+
export function methodDrivers(
|
|
53
|
+
registry: PaymentDriverRegistry,
|
|
54
|
+
methods: readonly PaymentMethodDescriptor[],
|
|
55
|
+
): ReadonlyMap<string, PaymentDriver> {
|
|
56
|
+
const drivers = new Map<string, PaymentDriver>();
|
|
57
|
+
for (const method of methods) {
|
|
58
|
+
const driver = driverForMethod(registry, method);
|
|
59
|
+
if (driver && !drivers.has(method.id)) drivers.set(method.id, driver);
|
|
60
|
+
}
|
|
61
|
+
return drivers;
|
|
62
|
+
}
|