@tallyui/pos 4.0.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "4.0.1",
3
+ "version": "4.2.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -34,20 +34,20 @@
34
34
  "mustache": "^4.2.0"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tallyui/core": "^4.0.1",
37
+ "@tallyui/core": "^4.2.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "4.0.1",
43
+ "@tallyui/core": "4.2.0",
44
44
  "@types/react": ">=18",
45
45
  "react": "^19.2.4",
46
46
  "rxdb": "17.5.0",
47
47
  "rxjs": "7.8.2",
48
- "@tallyui/connector-medusa": "4.0.1",
49
- "@tallyui/connector-woocommerce": "4.0.1",
50
- "@tallyui/database": "4.0.1"
48
+ "@tallyui/connector-medusa": "4.2.0",
49
+ "@tallyui/connector-woocommerce": "4.2.0",
50
+ "@tallyui/database": "4.2.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
package/src/index.ts CHANGED
@@ -14,7 +14,7 @@ export type { CurrencyFormat, CurrencyProviderProps } from './currency';
14
14
 
15
15
  // Tax
16
16
  export { TaxProvider, useTax, taxLogger, taxSettingsForLocation, createTaxContext, saleTaxContexts, taxDerivation } from './tax';
17
- export { MICROS_PER_MINOR, ratePpmFromPercent, taxMicros, roundMicrosToMinor, computeOrderTax, taxLinesByRate } from './tax';
17
+ export { MICROS_PER_MINOR, ratePpmFromPercent, taxMicros, roundMicrosToMinor, computeOrderTax, taxLinesByRate, taxedLinesFor } from './tax';
18
18
  export type { TaxLineInput, OrderTaxTotals, RateTaxLine } from './tax';
19
19
  export type { TaxProviderProps } from './tax';
20
20
  export type { TaxRateMap, TaxContext, SaleTaxContext } from './tax';
@@ -50,6 +50,8 @@ export type { Repository } from './repository';
50
50
  export { createOrderBuilder, createOrderManager, allocateOrderDiscount, taxFiguresForBasket } from './order';
51
51
  export { orderDraftSchema, writeOrderDraft, restoreOrderDraft, parkedOrderSummaries$ } from './order';
52
52
  export { useParkedSales } from './order';
53
+ export { useStoreOrdersInRange } from './store-orders';
54
+ export type { OrderDownloadProgress, StoreOrdersInRange, StoreOrdersRangeQuery } from './store-orders';
53
55
  export type { BasketLine } from './order';
54
56
  export { couponPricingBasis } from './order';
55
57
  export type { OrderBuilder, OrderBuilderOptions, OrderCouponContext, StorePricedCoupon, StorePricedCouponContext } from './order';
@@ -136,13 +138,15 @@ export type {
136
138
  export {
137
139
  PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
138
140
  printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
139
- escpos, encodeEscPos, createEscPosTransport, createEpsonEposSink, createStarWebPrntSink, networkSinkFor, canOpenDrawer,
141
+ escpos, encodeEscPos, createEscPosTransport, createEpsonEposSink, createStarWebPrntSink, networkSinkFor, createWebUsbSink, createWebBluetoothSink,
142
+ BLUETOOTH_PRINT_SERVICES, canOpenDrawer,
140
143
  openDrawerJob, ESCPOS_CODE_PAGES, resolvePrinter, templateColumns, renderEscpos, encodeThermalTemplate,
141
144
  } from './print';
142
145
  export type {
143
146
  PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
144
147
  PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
145
- EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, ResolvePrinterOptions, RenderEscposOptions,
148
+ EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, WebUsbDevice, WebUsbSinkOptions,
149
+ WebBluetoothDevice, WebBluetoothSinkOptions, ResolvePrinterOptions, RenderEscposOptions,
146
150
  } from './print';
147
151
 
148
152
  // Sale
@@ -189,7 +189,8 @@ export interface OrderBuilder {
189
189
  applyOrderDiscount(discount: Discount): void;
190
190
  removeDiscount(discountId: string): void;
191
191
  addPayment(payment: Omit<Payment, 'id'> & { id?: string }): string;
192
- setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
192
+ /** Moves a leg's status; `takenAt` is set on the leg only on a move to captured. */
193
+ setPaymentStatus(paymentId: string, status: PaymentLegStatus, takenAt?: string): boolean;
193
194
  removePayment(paymentId: string): void;
194
195
  setCustomer(customer: CustomerSummary | null): void;
195
196
  setNote(note: string): void;
@@ -816,10 +817,11 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
816
817
  return id;
817
818
  },
818
819
 
819
- setPaymentStatus(paymentId, status) {
820
+ setPaymentStatus(paymentId, status, takenAt) {
820
821
  const payment = payments.find((p) => p.id === paymentId);
821
822
  if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
822
- payments = payments.map((p) => p.id === paymentId ? { ...p, status } : p);
823
+ const stamp = status === 'captured' && takenAt !== undefined ? { takenAt } : {};
824
+ payments = payments.map((p) => p.id === paymentId ? { ...p, status, ...stamp } : p);
823
825
  emit();
824
826
  return true;
825
827
  },
@@ -4,6 +4,7 @@ import type { TaxContext } from '../tax/types';
4
4
  import { customerRefusal } from '../pos-order/command';
5
5
  import { capturedMinor } from '../tender/payment-legs';
6
6
  import { couponPricingBasis, createOrderBuilder, isLiveLeg, type OrderBuilder } from './order-builder';
7
+ import { isTakenAt } from './taken-at';
7
8
  import type { Order } from './types';
8
9
 
9
10
  /** Apps create their drafts collection with this schema. */
@@ -150,6 +151,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
150
151
  ...(payment.reopened !== undefined ? { reopened: payment.reopened } : {}),
151
152
  ...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
152
153
  ...(payment.units !== undefined ? { units: payment.units } : {}),
154
+ ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
153
155
  });
154
156
  }
155
157
  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');
@@ -0,0 +1,5 @@
1
+ /** A stored takenAt must be an instant in toISOString() form (the Front desk's ruling on #1178); any other value is dropped. */
2
+ export function isTakenAt(value: unknown): value is string {
3
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
4
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
5
+ }
@@ -194,6 +194,8 @@ export interface Payment {
194
194
  reference?: string;
195
195
  /** The units of each line (`String(line id)`) this leg paid for, set when it was taken with unit picks (#1133). Absent for a leg taken by amount. */
196
196
  units?: Readonly<Record<string, number>>;
197
+ /** When the till recorded the leg (an ISO 8601 instant). Absent on store-held legs and on legs from before 4.2. */
198
+ takenAt?: string;
197
199
  }
198
200
 
199
201
  export interface CustomerSummary {
@@ -2,6 +2,7 @@ import { minorUnitDigits, ORDER_LINE_SKU_MAX, ORDER_META_KEY_MAX, ORDER_NOTE_MAX
2
2
  type woocommerceTax } from '@tallyui/core';
3
3
  import { chargeOrderModeMinor } from '../order/order-builder';
4
4
  import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
5
+ import { isTakenAt } from '../order/taken-at';
5
6
  import type { ChargeLine, Order, SentOrder } from '../order/types';
6
7
  import { legStatus } from '../tender/payment-legs';
7
8
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
@@ -304,6 +305,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
304
305
  ...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor } : {}),
305
306
  ...(payment.changeMinor !== undefined ? { changeMinor: payment.changeMinor } : {}),
306
307
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
308
+ ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
307
309
  }));
308
310
  // A warning naming a payment the order no longer has is dropped and logged, never thrown: this runs at sale completion.
309
311
  const localWarnings = options.localWarnings?.flatMap((warning): PosOrderLocalWarning[] => {
@@ -2,6 +2,7 @@ import type { ServerCapabilities } from '@tallyui/core';
2
2
  import type { RxCollection } from 'rxdb';
3
3
  import { couponPricingBasis, createOrderBuilder, type StorePricedCoupon } from '../order/order-builder';
4
4
  import { writeOrderDraft } from '../order/order-drafts';
5
+ import { isTakenAt } from '../order/taken-at';
5
6
  import type { Order } from '../order/types';
6
7
  import { readSession, type ClosureCollection, type RegisterSessionCollection } from '../register/session-store';
7
8
  import { readFresh } from '../rxdb';
@@ -128,6 +129,7 @@ export async function reopenRefusedOrder(orderId: string, deps: {
128
129
  ...(afterClose ? { id: payment.id } : {}), method: payment.method, amountMinor: payment.amountMinor, reopened: true,
129
130
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
130
131
  ...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
132
+ ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
131
133
  });
132
134
  if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
133
135
  builder.setCustomer({ id: order.customer.id, name: order.customer.name,
@@ -38,6 +38,7 @@ import type { PosOrder } from './types';
38
38
  * Version 17 lets sentVersion and downgradedFrom be 11 (order.create version 11, ADR-086 d2 amended 2026-11-19), and changes nothing else. Its migration is the identity. It is one-way like version 16.
39
39
  * Version 18 adds the customer's `taxIds`, the order's `meta`, a line's `catalogueSku` and `attentionHandledFor` (ADR-092), and lets sentVersion and downgradedFrom be 12 (order.create version 12), and changes nothing else. Its migration is the identity. It is one-way like version 17.
40
40
  * Version 19 adds a store-priced coupon's `carried` flag and its lines' `amountMinor` (a coupon the store refused at send, carried at the amount charged), and the order's `countedInClosureOf`, and changes nothing else. Its migration is the identity. It is one-way like version 18.
41
+ * Version 20 adds a payment's optional `takenAt`, the instant the till recorded the leg; identity migration, one-way like version 19.
41
42
  */
42
43
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
43
44
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -47,7 +48,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
47
48
  } } as const;
48
49
 
49
50
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
50
- version: 19, primaryKey: 'id', type: 'object', additionalProperties: false,
51
+ version: 20, primaryKey: 'id', type: 'object', additionalProperties: false,
51
52
  properties: {
52
53
  id: { type: 'string', maxLength: 36 },
53
54
  saleId: { type: 'string', maxLength: 36 },
@@ -127,6 +128,7 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
127
128
  methodId: { type: 'string', minLength: 1, maxLength: 64 },
128
129
  storePaymentId: { type: 'string', minLength: 1, maxLength: 64 },
129
130
  amountMinor: { type: 'integer' }, tenderedMinor: { type: 'integer' }, changeMinor: { type: 'integer' }, reference: { type: 'string' },
131
+ takenAt: { type: 'string', maxLength: 40 },
130
132
  }, required: ['id', 'method', 'amountMinor'],
131
133
  } },
132
134
  customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
@@ -218,5 +220,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
218
220
  // it means no older sale is ever re-rounded (#287).
219
221
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
220
222
  return { schema: posOrderSchema,
221
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity } };
223
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity } };
222
224
  }
@@ -74,6 +74,8 @@ export interface PosOrderPayment {
74
74
  tenderedMinor?: number;
75
75
  changeMinor?: number;
76
76
  reference?: string;
77
+ /** When the till recorded the leg (`Payment.takenAt`); absent on store-held and older legs. */
78
+ takenAt?: string;
77
79
  }
78
80
 
79
81
  export interface PosOrder {
@@ -0,0 +1,114 @@
1
+ /**
2
+ * A Web Bluetooth sink for `createEscPosTransport`. The app supplies the `BluetoothDevice` from
3
+ * `navigator.bluetooth.requestDevice` (which needs a user gesture), with `BLUETOOTH_PRINT_SERVICES` in
4
+ * `optionalServices` so the sink may reach them, and keeps it between jobs. The sink holds no vendor code (ADR-084
5
+ * decision 2). It connects GATT if it is not connected and never disconnects: the app decides when to. The sink sets
6
+ * no timeout on a write.
7
+ */
8
+ import { PrintError } from '../types';
9
+ import type { EscPosSink } from './transport';
10
+
11
+ // Each print profile's GATT service and its write characteristic, in probe order. Source: WCPOS v2
12
+ // packages/printer/src/transport/ble-profiles.ts (found on a Netum NT-1809).
13
+ const PRINT_PROFILES = [
14
+ ['000018f0-0000-1000-8000-00805f9b34fb', '00002af1-0000-1000-8000-00805f9b34fb'],
15
+ ['0000ff00-0000-1000-8000-00805f9b34fb', '0000ff02-0000-1000-8000-00805f9b34fb'],
16
+ ['49535343-fe7d-4ae5-8fa9-9fafd205e455', '49535343-8841-43f4-a8d4-ecbe34729bb3'],
17
+ ['e7810a71-73ae-499d-8c15-faa9aef0c3f2', 'bef8d6c9-9c21-4c9e-b632-bd58c1009f9f'],
18
+ ] as const;
19
+
20
+ /** The print services the sink probes, in order. The app passes them to `requestDevice` as `optionalServices`. */
21
+ export const BLUETOOTH_PRINT_SERVICES: readonly string[] = PRINT_PROFILES.map(([service]) => service);
22
+
23
+ interface WebBluetoothCharacteristic {
24
+ readonly properties: { readonly write: boolean; readonly writeWithoutResponse: boolean };
25
+ writeValueWithResponse(value: Uint8Array<ArrayBuffer>): Promise<void>;
26
+ writeValueWithoutResponse(value: Uint8Array<ArrayBuffer>): Promise<void>;
27
+ }
28
+
29
+ interface WebBluetoothGattService {
30
+ getCharacteristic(characteristic: string): Promise<WebBluetoothCharacteristic>;
31
+ }
32
+
33
+ interface WebBluetoothGattServer {
34
+ readonly connected: boolean;
35
+ connect(): Promise<unknown>;
36
+ getPrimaryService(service: string): Promise<WebBluetoothGattService>;
37
+ }
38
+
39
+ /** Shaped on the DOM `BluetoothDevice`; e2e/web/webbluetooth-sink.spec.ts checks these member names in Chromium. */
40
+ export interface WebBluetoothDevice {
41
+ readonly name?: string | null;
42
+ readonly gatt?: WebBluetoothGattServer | null;
43
+ }
44
+
45
+ export interface WebBluetoothSinkOptions {
46
+ device: WebBluetoothDevice;
47
+ /** Bytes per GATT write: a positive integer, default 20. */
48
+ chunkSize?: number;
49
+ }
50
+
51
+ // v2's chunk size: 20 bytes is the payload of one write at BLE's default ATT MTU of 23 (3 bytes go to the header).
52
+ const BLE_CHUNK_SIZE = 20;
53
+ // v2's pause between chunks, found on a Netum NT-1809; the sink paces writes itself.
54
+ const BLE_CHUNK_PAUSE_MS = 20;
55
+ // v2's settle, found on a Netum NT-1809: the sink gives the printer 300 ms after the last chunk before resolving.
56
+ const BLE_SETTLE_MS = 300;
57
+
58
+ const pause = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * The first known print profile's characteristic that takes writes; each probe that rejects moves on to the next. A
62
+ * characteristic with `writeWithoutResponse` but not `write` is skipped, because the last chunk always goes with
63
+ * response.
64
+ */
65
+ async function printCharacteristic(gatt: WebBluetoothGattServer) {
66
+ for (const [service, characteristic] of PRINT_PROFILES) {
67
+ try {
68
+ const found = await (await gatt.getPrimaryService(service)).getCharacteristic(characteristic);
69
+ if (found.properties.write) return found;
70
+ } catch {
71
+ // The device lacks this service or characteristic: try the next profile.
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export function createWebBluetoothSink({ device, chunkSize = BLE_CHUNK_SIZE }: WebBluetoothSinkOptions): EscPosSink {
78
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
79
+ const name = () => device.name || 'Bluetooth printer';
80
+ async function step<T>(label: string, run: () => Promise<T>): Promise<T> {
81
+ try {
82
+ return await run();
83
+ } catch (error) {
84
+ throw new PrintError('failed', `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
85
+ }
86
+ }
87
+ return {
88
+ async write(bytes) {
89
+ const { gatt } = device;
90
+ if (!gatt) throw new PrintError('unsupported', `${name()} has no GATT server to print to`);
91
+ // Read the link and probe on every write, so a write after the link drops reconnects and finds the service again.
92
+ if (!gatt.connected) await step('connect', () => gatt.connect());
93
+ const target = await printCharacteristic(gatt);
94
+ if (!target && !gatt.connected) {
95
+ throw new PrintError('failed', `${name()}: the link dropped while finding the print service; nothing was written`);
96
+ }
97
+ if (!target) {
98
+ throw new PrintError('unsupported', `${name()}: no known print service was found; nothing was written; is BLUETOOTH_PRINT_SERVICES in optionalServices?`);
99
+ }
100
+ for (let i = 0; i < bytes.length; i += chunkSize) {
101
+ // slice, not subarray: each write gets its own ArrayBuffer-backed copy.
102
+ const chunk = bytes.slice(i, i + chunkSize);
103
+ const last = i + chunkSize >= bytes.length;
104
+ const chunkLabel = `chunk ${i / chunkSize + 1}`;
105
+ if (last || !target.properties.writeWithoutResponse) {
106
+ await step(`writeValueWithResponse (${chunkLabel})`, () => target.writeValueWithResponse(chunk));
107
+ } else {
108
+ await step(`writeValueWithoutResponse (${chunkLabel})`, () => target.writeValueWithoutResponse(chunk));
109
+ }
110
+ await pause(last ? BLE_SETTLE_MS : BLE_CHUNK_PAUSE_MS);
111
+ }
112
+ },
113
+ };
114
+ }
@@ -7,6 +7,10 @@ export { createEscPosTransport } from './transport';
7
7
  export type { EscPosSink, EscPosTransportOptions } from './transport';
8
8
  export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor } from './network-sinks';
9
9
  export type { NetworkSinkOptions } from './network-sinks';
10
+ export { createWebUsbSink } from './usb-sink';
11
+ export type { WebUsbDevice, WebUsbSinkOptions } from './usb-sink';
12
+ export { BLUETOOTH_PRINT_SERVICES, createWebBluetoothSink } from './bluetooth-sink';
13
+ export type { WebBluetoothDevice, WebBluetoothSinkOptions } from './bluetooth-sink';
10
14
  export { canOpenDrawer, openDrawerJob } from './drawer';
11
15
  export { renderEscpos, encodeThermalTemplate } from './render-escpos';
12
16
  export type { RenderEscposOptions } from './render-escpos';
@@ -0,0 +1,77 @@
1
+ import { describe, expectTypeOf, it } from 'vitest';
2
+ import type { WebBluetoothDevice } from './bluetooth-sink';
3
+ import type { WebUsbDevice } from './usb-sink';
4
+
5
+ // These are written from the WebUSB and Web Bluetooth IDL, because TypeScript's DOM lib has neither. FrozenArray is readonly.
6
+ // The `Missing` parameter covers the IDL's `null` and DefinitelyTyped's `undefined`.
7
+ type USBDirection = 'in' | 'out';
8
+ declare class USBEndpoint { readonly endpointNumber: number; readonly direction: USBDirection; readonly type: 'bulk' | 'interrupt' | 'isochronous'; readonly packetSize: number; }
9
+ declare class USBAlternateInterface { readonly alternateSetting: number; readonly interfaceClass: number; readonly interfaceSubclass: number; readonly interfaceProtocol: number; readonly interfaceName?: string | null; readonly endpoints: readonly USBEndpoint[]; }
10
+ declare class USBInterface { readonly interfaceNumber: number; readonly alternate: USBAlternateInterface; readonly alternates: readonly USBAlternateInterface[]; readonly claimed: boolean; }
11
+ declare class USBConfiguration { readonly configurationValue: number; readonly interfaces: readonly USBInterface[]; }
12
+ declare class USBOutTransferResult { readonly bytesWritten: number; readonly status: 'ok' | 'stall' | 'babble'; }
13
+ declare class USBDevice<Missing extends null | undefined> {
14
+ readonly productName: string | Missing;
15
+ readonly configuration: USBConfiguration | Missing;
16
+ readonly opened: boolean;
17
+ open(): Promise<void>;
18
+ selectConfiguration(configurationValue: number): Promise<void>;
19
+ claimInterface(interfaceNumber: number): Promise<void>;
20
+ clearHalt(direction: USBDirection, endpointNumber: number): Promise<void>;
21
+ transferOut(endpointNumber: number, data: BufferSource): Promise<USBOutTransferResult>;
22
+ }
23
+
24
+ declare class BluetoothCharacteristicProperties {
25
+ readonly broadcast: boolean; readonly read: boolean; readonly writeWithoutResponse: boolean; readonly write: boolean;
26
+ readonly notify: boolean; readonly indicate: boolean; readonly authenticatedSignedWrites: boolean;
27
+ readonly reliableWrite: boolean; readonly writableAuxiliaries: boolean;
28
+ }
29
+ declare class BluetoothRemoteGATTCharacteristic extends EventTarget {
30
+ readonly service: BluetoothRemoteGATTService; readonly uuid: string;
31
+ readonly properties: BluetoothCharacteristicProperties; readonly value?: DataView;
32
+ readValue(): Promise<DataView>;
33
+ writeValue(value: BufferSource): Promise<void>;
34
+ writeValueWithResponse(value: BufferSource): Promise<void>;
35
+ writeValueWithoutResponse(value: BufferSource): Promise<void>;
36
+ }
37
+ declare class BluetoothRemoteGATTService extends EventTarget {
38
+ readonly uuid: string; readonly isPrimary: boolean;
39
+ getCharacteristic(characteristic: number | string): Promise<BluetoothRemoteGATTCharacteristic>;
40
+ getCharacteristics(characteristic?: number | string): Promise<BluetoothRemoteGATTCharacteristic[]>;
41
+ }
42
+ declare class BluetoothRemoteGATTServer {
43
+ readonly connected: boolean;
44
+ connect(): Promise<BluetoothRemoteGATTServer>;
45
+ disconnect(): void;
46
+ getPrimaryService(service: number | string): Promise<BluetoothRemoteGATTService>;
47
+ getPrimaryServices(service?: number | string): Promise<BluetoothRemoteGATTService[]>;
48
+ }
49
+ declare class BluetoothDevice<Missing extends null | undefined> extends EventTarget {
50
+ readonly id: string;
51
+ readonly name: string | Missing;
52
+ readonly gatt: BluetoothRemoteGATTServer | Missing;
53
+ }
54
+
55
+ type SinkGatt = NonNullable<WebBluetoothDevice['gatt']>;
56
+ type SinkService = Awaited<ReturnType<SinkGatt['getPrimaryService']>>;
57
+ type SinkCharacteristic = Awaited<ReturnType<SinkService['getCharacteristic']>>;
58
+
59
+ describe('ESC/POS sink device types', () => {
60
+ it('a WebUSB device with null fields fits WebUsbDevice', () => expectTypeOf<USBDevice<null>>().toExtend<WebUsbDevice>());
61
+ it('a WebUSB device with undefined fields fits WebUsbDevice', () => expectTypeOf<USBDevice<undefined>>().toExtend<WebUsbDevice>());
62
+ it('a Web Bluetooth device with null fields fits WebBluetoothDevice', () => expectTypeOf<BluetoothDevice<null>>().toExtend<WebBluetoothDevice>());
63
+ it('a Web Bluetooth device with undefined fields fits WebBluetoothDevice', () => expectTypeOf<BluetoothDevice<undefined>>().toExtend<WebBluetoothDevice>());
64
+ });
65
+
66
+ describe('ESC/POS sink calls fit the real device methods', () => {
67
+ it('open', () => expectTypeOf<Parameters<WebUsbDevice['open']>>().toExtend<Parameters<USBDevice<null>['open']>>());
68
+ it('selectConfiguration', () => expectTypeOf<Parameters<WebUsbDevice['selectConfiguration']>>().toExtend<Parameters<USBDevice<null>['selectConfiguration']>>());
69
+ it('claimInterface', () => expectTypeOf<Parameters<WebUsbDevice['claimInterface']>>().toExtend<Parameters<USBDevice<null>['claimInterface']>>());
70
+ it('clearHalt', () => expectTypeOf<Parameters<WebUsbDevice['clearHalt']>>().toExtend<Parameters<USBDevice<null>['clearHalt']>>());
71
+ it('transferOut', () => expectTypeOf<Parameters<WebUsbDevice['transferOut']>>().toExtend<Parameters<USBDevice<null>['transferOut']>>());
72
+ it('connect', () => expectTypeOf<Parameters<SinkGatt['connect']>>().toExtend<Parameters<BluetoothRemoteGATTServer['connect']>>());
73
+ it('getPrimaryService', () => expectTypeOf<Parameters<SinkGatt['getPrimaryService']>>().toExtend<Parameters<BluetoothRemoteGATTServer['getPrimaryService']>>());
74
+ it('getCharacteristic', () => expectTypeOf<Parameters<SinkService['getCharacteristic']>>().toExtend<Parameters<BluetoothRemoteGATTService['getCharacteristic']>>());
75
+ it('writeValueWithResponse', () => expectTypeOf<Parameters<SinkCharacteristic['writeValueWithResponse']>>().toExtend<Parameters<BluetoothRemoteGATTCharacteristic['writeValueWithResponse']>>());
76
+ it('writeValueWithoutResponse', () => expectTypeOf<Parameters<SinkCharacteristic['writeValueWithoutResponse']>>().toExtend<Parameters<BluetoothRemoteGATTCharacteristic['writeValueWithoutResponse']>>());
77
+ });
@@ -6,9 +6,10 @@
6
6
  */
7
7
  import type { ReceiptTemplateOptions } from '../../receipt-template/template-data';
8
8
  import type { PrinterProfile } from '../printer-profiles';
9
- import { PrintError, type PrintJob, type PrintTransport } from '../types';
9
+ import { PrintError, toPrintError, type PrintJob, type PrintTransport } from '../types';
10
10
  import { encodeEscPos } from './encode';
11
11
 
12
+ /** Where the ESC/POS bytes go. A `write` that rejects with a `PrintError` keeps its code (`unsupported` for a device it cannot print to); any other rejection is a `failed` PrintError. */
12
13
  export interface EscPosSink {
13
14
  write(bytes: Uint8Array): Promise<void>;
14
15
  }
@@ -39,7 +40,7 @@ export function createEscPosTransport({ sink, profile, format }: EscPosTransport
39
40
  try {
40
41
  await sink.write(bytes);
41
42
  } catch (error) {
42
- throw new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
43
+ throw toPrintError(error);
43
44
  }
44
45
  },
45
46
  };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A WebUSB sink for `createEscPosTransport`. The app supplies the `USBDevice` from `navigator.usb.requestDevice` (which
3
+ * needs a user gesture) or `navigator.usb.getDevices`, and keeps it between jobs. The sink holds no vendor code
4
+ * (ADR-084 decision 2) and never closes the device: the app releases it when it is done. The sink sets no timeout on a
5
+ * transfer.
6
+ */
7
+ import { PrintError } from '../types';
8
+ import type { EscPosSink } from './transport';
9
+
10
+ interface WebUsbEndpoint { readonly endpointNumber: number; readonly direction: 'in' | 'out'; readonly type: 'bulk' | 'interrupt' | 'isochronous' }
11
+
12
+ /** Shaped on the DOM `USBDevice`; e2e/web/webusb-sink.spec.ts checks these member names in Chromium. */
13
+ export interface WebUsbDevice {
14
+ readonly opened: boolean;
15
+ readonly configuration?: {
16
+ readonly interfaces: readonly {
17
+ readonly interfaceNumber: number;
18
+ readonly claimed: boolean;
19
+ readonly alternate: { readonly interfaceClass: number; readonly endpoints: readonly WebUsbEndpoint[] };
20
+ }[];
21
+ } | null;
22
+ readonly productName?: string | null;
23
+ open(): Promise<void>;
24
+ selectConfiguration(configurationValue: number): Promise<void>;
25
+ claimInterface(interfaceNumber: number): Promise<void>;
26
+ clearHalt(direction: 'in' | 'out', endpointNumber: number): Promise<void>;
27
+ transferOut(endpointNumber: number, data: Uint8Array<ArrayBuffer>): Promise<{ status: 'ok' | 'stall' | 'babble'; bytesWritten: number }>;
28
+ }
29
+
30
+ export interface WebUsbSinkOptions {
31
+ device: WebUsbDevice;
32
+ /** Bytes per `transferOut`: a positive integer, default 4096. */
33
+ chunkSize?: number;
34
+ }
35
+
36
+ // Keeps a single transfer bounded; it is not a pacing control (each transfer is awaited, so the device sets the pace).
37
+ const USB_CHUNK_SIZE = 4096;
38
+
39
+ // The USB printer class code (bInterfaceClass 7).
40
+ const USB_PRINTER_CLASS = 7;
41
+
42
+ /**
43
+ * The interface to print to, and its bulk OUT endpoint's number: the first printer-class interface with a bulk OUT
44
+ * endpoint, or, when there is none, the first interface of any class with a bulk OUT endpoint.
45
+ */
46
+ function bulkOut(device: WebUsbDevice) {
47
+ const candidates = (device.configuration?.interfaces ?? []).flatMap((usbInterface) => {
48
+ const endpoint = usbInterface.alternate.endpoints.find(({ direction, type }) => direction === 'out' && type === 'bulk');
49
+ return endpoint ? [{ usbInterface, endpointNumber: endpoint.endpointNumber }] : [];
50
+ });
51
+ return candidates.find(({ usbInterface }) => usbInterface.alternate.interfaceClass === USB_PRINTER_CLASS) ?? candidates[0] ?? null;
52
+ }
53
+
54
+ export function createWebUsbSink({ device, chunkSize = USB_CHUNK_SIZE }: WebUsbSinkOptions): EscPosSink {
55
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
56
+ const name = () => device.productName || 'USB printer';
57
+ async function step<T>(label: string, run: () => Promise<T>): Promise<T> {
58
+ try {
59
+ return await run();
60
+ } catch (error) {
61
+ throw new PrintError('failed', `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
62
+ }
63
+ }
64
+ return {
65
+ async write(bytes) {
66
+ // Read the device's state on every write, so a write after the app reopens the device works.
67
+ if (!device.opened) await step('open', () => device.open());
68
+ if (device.configuration == null) await step('selectConfiguration(1)', () => device.selectConfiguration(1));
69
+ const target = bulkOut(device);
70
+ if (!target) throw new PrintError('unsupported', `${name()} has no bulk OUT endpoint to print to`);
71
+ const { usbInterface: { interfaceNumber, claimed }, endpointNumber } = target;
72
+ if (!claimed) await step(`claimInterface(${interfaceNumber})`, () => device.claimInterface(interfaceNumber));
73
+ for (let i = 0; i < bytes.length; i += chunkSize) {
74
+ // slice, not subarray: each transfer gets its own ArrayBuffer-backed copy.
75
+ const chunk = bytes.slice(i, i + chunkSize);
76
+ const result = await step(`transferOut(${endpointNumber})`, () => device.transferOut(endpointNumber, chunk));
77
+ if (result.status === 'ok') continue;
78
+ // A stalled endpoint stays halted until cleared, so clear it for the next job; this job still fails.
79
+ if (result.status === 'stall') await device.clearHalt('out', endpointNumber).catch(() => undefined);
80
+ throw new PrintError('failed', `${name()}: transferOut(${endpointNumber}) ended with status ${result.status}`);
81
+ }
82
+ },
83
+ };
84
+ }
@@ -11,5 +11,5 @@ export type { ResolvePrinterOptions } from './resolve-printer';
11
11
  export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
12
12
  export type { SystemPrintTransportOptions } from './system-transport';
13
13
  export { escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES, renderEscpos, encodeThermalTemplate } from './escpos';
14
- export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor, canOpenDrawer, openDrawerJob } from './escpos';
15
- export type { EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, RenderEscposOptions } from './escpos';
14
+ export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor, createWebUsbSink, createWebBluetoothSink, BLUETOOTH_PRINT_SERVICES, canOpenDrawer, openDrawerJob } from './escpos';
15
+ export type { EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, WebUsbDevice, WebUsbSinkOptions, WebBluetoothDevice, WebBluetoothSinkOptions, RenderEscposOptions } from './escpos';
@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
2
2
  import type { RxCollection } from 'rxdb';
3
3
  import type { CustomerAddress, CustomerTaxId, ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
4
4
  import { ORDER_META_KEY_MAX, ORDER_META_MAX, paymentMethodOf } from '@tallyui/core';
5
- import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
5
+ import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion, legStatus } from '../tender/payment-legs';
6
6
  import { heldUnitsByLine, unpaidUnitsByLine } from '../tender/split-units';
7
7
  import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type ChargeLine, type LineItem, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
8
8
  import { STORE_ORDER_REBUILD_REFUSALS } from '../order/from-store-order';
@@ -393,17 +393,20 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
393
393
  }
394
394
  }, []);
395
395
 
396
- function addOne(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; changeMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured' }): string {
396
+ function addOne(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; changeMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured' }, stamp: boolean): string {
397
397
  // A terminal reference finalize would refuse is dropped as it's entered, never the payment (the money is
398
398
  // taken): the tender applies without it, with a message that doesn't block complete() and a
399
399
  // localWarnings entry on the stored order naming the payment whose reference was dropped.
400
400
  const reason = referenceReason(tender.reference);
401
401
  const dropped = reason && (reason === 'nul' ? 'it contains a NUL character' : `it is over ${PAYLOAD_STRING_MAX} characters`);
402
- const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor,
402
+ // addTender stamps a leg that enters captured; setTender's pre-filled leg waits for complete(), a pending one for capture.
403
+ // Stamped here, never in addPayment, which the restore paths call too.
404
+ const takenAt = stamp && legStatus({ status: tender.status }) === 'captured' ? { takenAt: new Date().toISOString() } : {};
405
+ const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor, ...takenAt,
403
406
  ...(tender.tenderedMinor !== undefined ? { tenderedMinor: tender.tenderedMinor } : {}),
404
407
  ...(tender.changeMinor !== undefined ? { changeMinor: tender.changeMinor } : {}),
405
408
  ...(tender.units !== undefined ? { units: tender.units } : {}),
406
- ...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : tender;
409
+ ...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : { ...tender, ...takenAt };
407
410
  const builder = builderNow.current;
408
411
  const { units, ...payment } = kept;
409
412
  const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) });
@@ -434,7 +437,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
434
437
  for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
435
438
  droppedReferences.current.clear();
436
439
  setError(null);
437
- if (tender) addOne(tender);
440
+ if (tender) addOne(tender, false);
438
441
  }
439
442
 
440
443
  /** addTender, voidTender and removeTender changed the tenders: a stale error goes, a dropped-reference message stays. */
@@ -871,17 +874,17 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
871
874
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
872
875
  if (due <= 0) return null;
873
876
  clearStaleError(); // before addOne, which sets its own message for a dropped reference
874
- return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
877
+ return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) }, true);
875
878
  }
876
879
  clearStaleError();
877
- return addOne({ ...tender, ...(tender.tenderedMinor !== undefined ? { changeMinor: tender.tenderedMinor - tender.amountMinor } : {}) });
880
+ return addOne({ ...tender, ...(tender.tenderedMinor !== undefined ? { changeMinor: tender.tenderedMinor - tender.amountMinor } : {}) }, true);
878
881
  },
879
882
  setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
880
883
  if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; }
881
884
  if (locked()) return false;
882
885
  const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
883
886
  if (payment && countedLeg(payment)) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return false; }
884
- const changed = builderNow.current.setPaymentStatus(paymentId, status);
887
+ const changed = builderNow.current.setPaymentStatus(paymentId, status, status === 'captured' ? new Date().toISOString() : undefined);
885
888
  // With no live leg left, the sale can change again: SALE_HAS_PAYMENT goes, any other error stays.
886
889
  if (changed && status === 'failed' && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
887
890
  return changed;
@@ -945,7 +948,11 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
945
948
  if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
946
949
  if (couponsUnpriced()) { setSaving(false); setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING); return; }
947
950
  // Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
948
- const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
951
+ // A leg with no takenAt yet (setTender's pre-filled one) was taken now; store and reopened legs keep what they have.
952
+ // Only this copy is stamped, never the builder, so a retry (pending.current) keeps this attempt's instant.
953
+ const completedAt = new Date().toISOString();
954
+ const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid)
955
+ .map((payment) => payment.takenAt === undefined && !payment.locked && !payment.reopened ? { ...payment, takenAt: completedAt } : payment) };
949
956
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
950
957
  .map((payment) => ({ code: 'payment_reference_dropped' as const, paymentId: payment.id }));
951
958
  let posOrder: PosOrder;
@@ -0,0 +1,2 @@
1
+ export { useStoreOrdersInRange } from './use-store-orders-in-range';
2
+ export type { OrderDownloadProgress, StoreOrdersInRange, StoreOrdersRangeQuery } from './use-store-orders-in-range';