@tallyui/pos 3.20.0 → 4.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 +1005 -110
- package/dist/index.js +3156 -907
- package/package.json +6 -6
- package/src/app-settings/app-settings.ts +77 -0
- package/src/app-settings/index.ts +2 -0
- package/src/currency/currency-provider.tsx +5 -7
- package/src/currency/index.ts +1 -1
- package/src/customer/customer-patch.ts +70 -0
- package/src/customer-display/display-client.ts +11 -17
- package/src/customer-display/display-link.ts +10 -5
- package/src/customer-display/index.ts +3 -1
- package/src/customer-display/protocol.ts +1 -1
- package/src/customer-display/sale-display.ts +6 -8
- package/src/customer-display/snapshot-fallback.ts +14 -1
- package/src/customer-display/till-device.ts +62 -0
- package/src/customer-display/till-display-service.ts +44 -42
- package/src/customer-display/till-pairing.ts +20 -23
- package/src/customer-display/use-customer-display.ts +2 -1
- package/src/customer-display/use-till-pairing.ts +4 -4
- package/src/index.ts +37 -18
- package/src/order/allocate-order-discount.ts +5 -17
- package/src/order/apportion.ts +29 -0
- package/src/order/from-store-order.ts +115 -0
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +239 -52
- package/src/order/order-drafts.ts +45 -6
- package/src/order/order-manager.ts +2 -1
- package/src/order/tax-ids.ts +27 -0
- package/src/order/types.ts +59 -5
- package/src/order/woocommerce-tax.ts +9 -0
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +138 -43
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/retry-delay.ts +8 -0
- package/src/outbox/use-order-outbox.ts +8 -2
- package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
- package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
- package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
- package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
- package/src/pos-order/attention-handled.ts +24 -0
- package/src/pos-order/command.ts +132 -12
- package/src/pos-order/extras-delivery.ts +14 -0
- package/src/pos-order/finalize.ts +138 -29
- package/src/pos-order/index.ts +7 -3
- package/src/pos-order/money-divergence.ts +19 -0
- package/src/pos-order/needs-attention.ts +9 -1
- package/src/pos-order/refund-due.ts +35 -0
- package/src/pos-order/reopen.ts +96 -12
- package/src/pos-order/schema.ts +35 -10
- package/src/pos-order/till-payments.ts +4 -0
- package/src/pos-order/types.ts +44 -5
- package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
- package/src/print/escpos/commands.ts +79 -0
- package/src/print/escpos/drawer.ts +25 -0
- package/src/print/escpos/encode.ts +1 -0
- package/src/print/escpos/index.ts +6 -1
- package/src/print/escpos/network-sinks.ts +130 -0
- package/src/print/escpos/render-escpos.ts +155 -0
- package/src/print/escpos/transport.ts +2 -1
- package/src/print/index.ts +5 -2
- package/src/print/resolve-printer.ts +46 -0
- package/src/print/types.ts +1 -1
- package/src/product/index.ts +2 -0
- package/src/product/terms.ts +42 -0
- package/src/product/tile-fields.ts +27 -0
- package/src/receipt/build-receipt-data.ts +12 -7
- package/src/receipt/carried-rows.ts +29 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +14 -8
- package/src/receipt/types.ts +3 -1
- package/src/receipt-template/default-templates.ts +3 -0
- package/src/receipt-template/template-data.ts +3 -0
- package/src/receipt-template/wcpos/build.ts +1 -0
- package/src/receipt-template/wcpos/format.ts +2 -2
- package/src/receipt-template/wcpos/from-orders.ts +6 -2
- package/src/receipt-template/wcpos/types.ts +5 -1
- package/src/register/closure-document.ts +42 -4
- package/src/register/closure-rows.ts +3 -2
- package/src/register/document-labels.ts +25 -0
- package/src/register/expected.ts +49 -10
- package/src/register/index.ts +5 -5
- package/src/register/money.ts +23 -0
- package/src/register/register-adoption.ts +6 -5
- package/src/register/register-commands.ts +4 -3
- package/src/register/schemas.ts +11 -3
- package/src/register/session-store.ts +44 -23
- package/src/register/settled-figures.ts +5 -19
- package/src/register/use-register-session.ts +18 -19
- package/src/reopen/index.ts +3 -0
- package/src/reopen/reopen-entry.ts +48 -0
- package/src/reopen/reopen-store-order.ts +78 -0
- package/src/reopen/send-order-reopen.ts +61 -0
- package/src/reports/adapters.ts +15 -7
- package/src/reports/sales-figures.ts +15 -1
- package/src/reports/types.ts +2 -0
- package/src/sale/cart.ts +4 -2
- package/src/sale/index.ts +1 -1
- package/src/sale/open-sales.ts +3 -0
- package/src/sale/use-sale.ts +388 -83
- package/src/sale/woocommerce/coupon-refetch.ts +1 -0
- package/src/sale/woocommerce/coupon-source.ts +4 -4
- package/src/sale/woocommerce/coupons.ts +6 -0
- package/src/sale/woocommerce/discount-codes.ts +1 -6
- package/src/scanner/analyze-trace.ts +86 -0
- package/src/scanner/device-scanner.ts +57 -0
- package/src/scanner/hid-scanner.ts +14 -41
- package/src/scanner/index.ts +2 -0
- package/src/scanner/serial-scanner.ts +15 -42
- package/src/scanner/use-barcode-scanner.ts +107 -5
- package/src/scanner/wedge-detector.ts +33 -15
- package/src/tax/exact.ts +1 -13
- package/src/tax/taxed-lines.ts +26 -0
- package/src/tender/index.ts +6 -1
- package/src/tender/split-units.ts +109 -0
- package/src/tender/tender-figures.ts +114 -0
- package/src/tender/tender-state.ts +105 -17
- package/src/currency/format-money-with.ts +0 -45
package/src/pos-order/schema.ts
CHANGED
|
@@ -25,14 +25,21 @@ import type { PosOrder } from './types';
|
|
|
25
25
|
* Its migration is the identity. It is one-way like version 7.
|
|
26
26
|
* Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
|
|
27
27
|
* and `regularUnitPriceMinor` (ADR-077 d2), and `reopenedAt`: when a refused order was reopened as a parked sale (ADR-077 d4b), and lets `sentVersion` and `downgradedFrom` be 6 (order.create version 6, ADR-077 d4), and changes nothing else.
|
|
28
|
-
* `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them
|
|
28
|
+
* `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them when its base payload is version 6 (wire versions 6 to 9).
|
|
29
29
|
* Its migration is the identity. It is one-way like version 8.
|
|
30
30
|
* Version 10 adds a line's `anyAttributes` (#495 c/d) and changes nothing else. Its migration is the identity. It is one-way like version 9.
|
|
31
31
|
* Version 11 lets `sentVersion` and `downgradedFrom` be 7 (order.create version 7, ADR-083), and changes nothing else. Its migration is the identity. It is one-way like version 10.
|
|
32
32
|
* Version 12 adds the order's `taxAddress` and the customer's `billing` and `shipping` (#722), and lets `sentVersion` and
|
|
33
33
|
* `downgradedFrom` be 8 (order.create version 8), and changes nothing else. Its migration is the identity. It is one-way like version 11.
|
|
34
|
+
* Version 13 adds a store-priced coupon's `lines` (#790) and lets `sentVersion` and `downgradedFrom` be 9 (order.create version 9), and changes nothing else. Its migration is the identity. It is one-way like version 12.
|
|
35
|
+
* Version 14 adds a reopened sale's store ids (ADR-090 decision 5): the order's `storeOrderId` and `baseRevision`, a line's, fee's and shipping line's `storeLineId`, and a payment's `storePaymentId`, and changes nothing else. Its migration is the identity. It is one-way like version 13.
|
|
36
|
+
* Version 15 lets `baseRevision` be 128 characters (a store revision is an opaque token; WooCommerce's is 71) and adds `refundDueMinor`, what the store owes back on a reopened sale paid beyond its new total (ADR-090), and changes nothing else. Its migration is the identity. It is one-way like version 14.
|
|
37
|
+
* Version 16 adds a payment's optional methodId (ruling A, 2026-11-18) and lets sentVersion and downgradedFrom be 10 (order.create version 10), and changes nothing else. Its migration is the identity. It is one-way like version 15.
|
|
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
|
+
* 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
|
+
* 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.
|
|
34
41
|
*/
|
|
35
|
-
/** A customer's address on an order
|
|
42
|
+
/** A customer's address on an order (#722, OrderAddress): ten optional strings. */
|
|
36
43
|
const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
|
|
37
44
|
firstName: { type: 'string' }, lastName: { type: 'string' }, company: { type: 'string' }, address1: { type: 'string' },
|
|
38
45
|
address2: { type: 'string' }, city: { type: 'string' }, state: { type: 'string' }, postcode: { type: 'string' },
|
|
@@ -40,28 +47,41 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
|
|
|
40
47
|
} } as const;
|
|
41
48
|
|
|
42
49
|
export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
43
|
-
version:
|
|
50
|
+
version: 19, primaryKey: 'id', type: 'object', additionalProperties: false,
|
|
44
51
|
properties: {
|
|
45
52
|
id: { type: 'string', maxLength: 36 },
|
|
46
53
|
saleId: { type: 'string', maxLength: 36 },
|
|
54
|
+
storeOrderId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
55
|
+
baseRevision: { type: 'string', minLength: 1, maxLength: 128 },
|
|
47
56
|
commandId: { type: 'string', maxLength: 36 },
|
|
48
57
|
createdAt: { type: 'string', maxLength: 40 },
|
|
49
58
|
updatedAt: { type: 'string' },
|
|
50
59
|
reopenedAt: { type: 'string', maxLength: 40 },
|
|
60
|
+
attentionHandledFor: { type: 'string', maxLength: 36 },
|
|
51
61
|
currency: { type: 'string' },
|
|
52
62
|
pricesIncludeTax: { type: 'boolean' },
|
|
53
63
|
subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' },
|
|
54
|
-
taxMinor: { type: 'integer' }, totalMinor: { type: 'integer' },
|
|
64
|
+
taxMinor: { type: 'integer' }, totalMinor: { type: 'integer' }, refundDueMinor: { type: 'integer', minimum: 0 },
|
|
55
65
|
syncStatus: { type: 'string', enum: ['pending', 'applied', 'rejected'], maxLength: 10 },
|
|
56
|
-
note: { type: 'string' },
|
|
66
|
+
note: { type: 'string' }, meta: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
67
|
+
key: { type: 'string' }, value: { type: 'string' } }, required: ['key', 'value'] } },
|
|
68
|
+
registerId: { type: 'string' }, sessionId: { type: 'string', maxLength: 36 }, cashierRef: { type: 'string' },
|
|
69
|
+
countedInClosureOf: { type: 'string', maxLength: 36 },
|
|
57
70
|
coupons: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
58
71
|
code: { type: 'string', minLength: 1, maxLength: 255 }, couponId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
59
72
|
discountMinor: { type: 'integer', minimum: 0 }, discountTaxMinor: { type: 'integer', minimum: 0 },
|
|
73
|
+
carried: { type: 'boolean', enum: [true] },
|
|
74
|
+
lines: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
75
|
+
lineId: { type: 'string', minLength: 1, maxLength: 36 }, discountMinor: { type: 'integer', minimum: 0 },
|
|
76
|
+
discountTaxMinor: { type: 'integer', minimum: 0 },
|
|
77
|
+
amountMinor: { type: 'integer', minimum: 0 },
|
|
78
|
+
}, required: ['lineId', 'discountMinor', 'discountTaxMinor'] } },
|
|
60
79
|
}, required: ['code', 'couponId', 'discountMinor', 'discountTaxMinor'] } },
|
|
61
80
|
lines: { type: 'array', items: {
|
|
62
81
|
type: 'object', properties: {
|
|
63
82
|
id: { type: 'string', maxLength: 36 }, productId: { type: 'string' }, variantId: { type: 'string' },
|
|
64
|
-
|
|
83
|
+
storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
84
|
+
name: { type: 'string' }, sku: { type: 'string' }, catalogueSku: { type: 'string' }, quantity: { type: 'integer' },
|
|
65
85
|
taxStatus: { type: 'string', enum: ['taxable', 'none'] },
|
|
66
86
|
custom: { type: 'object', additionalProperties: false, properties: {
|
|
67
87
|
name: { type: 'string', minLength: 1, maxLength: 255 }, sku: { type: 'string', maxLength: 64 },
|
|
@@ -80,6 +100,7 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
|
80
100
|
required: ['id', 'productId', 'name', 'sku', 'quantity', 'unitPriceMinor', 'discountMinor', 'netMinor', 'taxLines'],
|
|
81
101
|
} },
|
|
82
102
|
fees: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
103
|
+
storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
83
104
|
id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
|
|
84
105
|
amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
|
|
85
106
|
taxStatus: { type: 'string', enum: ['taxable', 'none'] }, netMinor: { type: 'integer' }, taxMicros: { type: 'string' },
|
|
@@ -90,6 +111,7 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
|
90
111
|
}, required: ['ratePpm', 'taxMicros'] } },
|
|
91
112
|
}, required: ['id', 'name', 'amountMinor', 'taxStatus', 'taxLines', 'netMinor', 'taxMicros'] } },
|
|
92
113
|
shipping: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
114
|
+
storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
93
115
|
id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
|
|
94
116
|
methodId: { type: 'string', maxLength: 64 }, amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
|
|
95
117
|
taxStatus: { type: 'string', enum: ['taxable', 'none'] }, netMinor: { type: 'integer' }, taxMicros: { type: 'string' },
|
|
@@ -102,11 +124,14 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
|
102
124
|
payments: { type: 'array', items: {
|
|
103
125
|
type: 'object', properties: {
|
|
104
126
|
id: { type: 'string', maxLength: 36 }, method: { type: 'string', enum: ['cash', 'external'] },
|
|
127
|
+
methodId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
128
|
+
storePaymentId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
105
129
|
amountMinor: { type: 'integer' }, tenderedMinor: { type: 'integer' }, changeMinor: { type: 'integer' }, reference: { type: 'string' },
|
|
106
130
|
}, required: ['id', 'method', 'amountMinor'],
|
|
107
131
|
} },
|
|
108
132
|
customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
|
|
109
|
-
billing: orderAddressSchema, shipping: orderAddressSchema
|
|
133
|
+
billing: orderAddressSchema, shipping: orderAddressSchema, taxIds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
134
|
+
type: { type: 'string' }, value: { type: 'string' }, country: { type: 'string' }, label: { type: 'string' } }, required: ['type', 'value'] } } } },
|
|
110
135
|
taxAddress: { type: 'string', enum: ['billing', 'shipping'] },
|
|
111
136
|
serverRefs: { type: 'object', properties: {
|
|
112
137
|
orderId: { type: 'string' }, displayId: { type: 'string' }, totalMinor: { type: 'integer' },
|
|
@@ -128,8 +153,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
|
128
153
|
roundAtSubtotal: { type: 'boolean' },
|
|
129
154
|
mode: { type: 'string', enum: ['half_away_from_zero', 'half_up'] },
|
|
130
155
|
}, required: ['granularity'] },
|
|
131
|
-
sentVersion: { type: 'integer', minimum: 1, maximum:
|
|
132
|
-
downgradedFrom: { type: 'integer', minimum: 1, maximum:
|
|
156
|
+
sentVersion: { type: 'integer', minimum: 1, maximum: 12 },
|
|
157
|
+
downgradedFrom: { type: 'integer', minimum: 1, maximum: 12 },
|
|
133
158
|
// The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
|
|
134
159
|
display: { type: 'object', additionalProperties: false, properties: {
|
|
135
160
|
currency: { type: 'string' }, exponent: { type: 'integer' }, taxInclusive: { type: 'boolean' },
|
|
@@ -193,5 +218,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
|
|
|
193
218
|
// it means no older sale is ever re-rounded (#287).
|
|
194
219
|
const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
|
|
195
220
|
return { schema: posOrderSchema,
|
|
196
|
-
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 } };
|
|
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 } };
|
|
197
222
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The payments this till took: a locked store payment (storePaymentId set) is the store's earlier money (ADR-090 gate 11). */
|
|
2
|
+
export function tillPayments<P extends { storePaymentId?: string }>(payments: readonly P[]): P[] {
|
|
3
|
+
return payments.filter((payment) => payment.storePaymentId === undefined);
|
|
4
|
+
}
|
package/src/pos-order/types.ts
CHANGED
|
@@ -21,16 +21,31 @@ export interface PosOrderCoupon {
|
|
|
21
21
|
couponId: string; // the connector's coupon id, as a string
|
|
22
22
|
discountMinor: number; // the coupon's discount, ex tax, in integer minor units
|
|
23
23
|
discountTaxMinor: number; // its tax, in integer minor units
|
|
24
|
+
carried?: true;
|
|
25
|
+
/** Present only on a store-priced coupon (#790), in stored `lines` order, with no zero entries unless a carried amountMinor is non-zero;
|
|
26
|
+
* absent on WooCommerce replay coupons and on every order stored before schema 13. */
|
|
27
|
+
lines?: PosOrderCouponLine[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface PosOrderCouponLine {
|
|
31
|
+
lineId: string; // the stored line's id
|
|
32
|
+
discountMinor: number; // tax-exclusive, integer minor units
|
|
33
|
+
discountTaxMinor: number; // integer minor units
|
|
34
|
+
amountMinor?: number;
|
|
24
35
|
}
|
|
25
36
|
|
|
26
37
|
export interface PosOrderLine {
|
|
27
38
|
id: string;
|
|
39
|
+
/** The store's id of a kept line (ADR-090); absent on a line added at the till. */
|
|
40
|
+
storeLineId?: string;
|
|
28
41
|
productId: string;
|
|
29
42
|
variantId?: string;
|
|
30
43
|
custom?: OrderCreateLine['custom'];
|
|
31
44
|
taxStatus?: 'taxable' | 'none';
|
|
32
45
|
name: string;
|
|
33
46
|
sku: string;
|
|
47
|
+
/** The SKU the line was added with, recorded only when the cashier edits the line's `sku` (pos_orders v18, ADR-092); absent means `sku` is the catalogue's. */
|
|
48
|
+
catalogueSku?: string;
|
|
34
49
|
quantity: number;
|
|
35
50
|
unitPriceMinor: number;
|
|
36
51
|
/** The chosen variation attributes, name to value (pos_orders v9, #495). */
|
|
@@ -50,7 +65,11 @@ export interface PosOrderLine {
|
|
|
50
65
|
|
|
51
66
|
export interface PosOrderPayment {
|
|
52
67
|
id: string;
|
|
68
|
+
/** The store's id of a payment already on the order (ADR-090): a captured leg, never re-taken. Sent as `order.update`'s `paymentId`. */
|
|
69
|
+
storePaymentId?: string;
|
|
53
70
|
method: PaymentMethodKind;
|
|
71
|
+
/** The payment method's own id on the platform, kept for labels and takings (`legMethodId`); `method` decides cash. */
|
|
72
|
+
methodId?: string;
|
|
54
73
|
amountMinor: number;
|
|
55
74
|
tenderedMinor?: number;
|
|
56
75
|
changeMinor?: number;
|
|
@@ -61,31 +80,49 @@ export interface PosOrder {
|
|
|
61
80
|
id: string;
|
|
62
81
|
/** The sale order's id (the builder's), set by finalizeOrder (pos_orders v7, ADR-072): support traceability from a draft or preview to this stored order. Never sent, never printed. */
|
|
63
82
|
saleId?: string;
|
|
83
|
+
/** The store order this sale reopened (ADR-090); the outbox sends such a row as `order.update`, never `order.create`. */
|
|
84
|
+
storeOrderId?: string;
|
|
85
|
+
/** The store's revision of that order as the reopen left it (ADR-090). */
|
|
86
|
+
baseRevision?: string;
|
|
64
87
|
createdAt: string;
|
|
65
88
|
currency: string;
|
|
66
89
|
pricesIncludeTax: boolean;
|
|
67
90
|
lines: PosOrderLine[];
|
|
68
91
|
/** pos_orders v9, ADR-077 d2; present only on a sale with coupons */
|
|
69
92
|
coupons?: PosOrderCoupon[];
|
|
70
|
-
fees?: FeeLine
|
|
71
|
-
|
|
93
|
+
fees?: Array<FeeLine & {
|
|
94
|
+
/** The store's id of a kept fee or shipping line, in the same id space as lines (ADR-090). */
|
|
95
|
+
storeLineId?: string;
|
|
96
|
+
}>;
|
|
97
|
+
shipping?: Array<ShippingLine & {
|
|
98
|
+
/** The store's id of a kept fee or shipping line, in the same id space as lines (ADR-090). */
|
|
99
|
+
storeLineId?: string;
|
|
100
|
+
}>;
|
|
72
101
|
subtotalMinor: number;
|
|
73
102
|
discountMinor: number;
|
|
74
103
|
taxMinor: number;
|
|
75
104
|
totalMinor: number;
|
|
105
|
+
/** What the store owes back on a reopened sale whose locked payments exceed its new total, in minor units (pos_orders v15, ADR-090). `finalizeOrder` writes it on every reopened sale, 0 when nothing is due; absent on a till sale. */
|
|
106
|
+
refundDueMinor?: number;
|
|
76
107
|
payments: PosOrderPayment[];
|
|
77
108
|
/** `billing` and `shipping` (#722) are frozen copies of the customer's addresses, stored only with `taxAddress`. */
|
|
78
|
-
customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress
|
|
109
|
+
customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress;
|
|
110
|
+
/** The sale's tax ids (pos_orders v18, ADR-092), sent at order.create 12; `label` is kept on the till and is not sent. */
|
|
111
|
+
taxIds?: Array<{ type: string; value: string; country?: string; label?: string }> } | null;
|
|
79
112
|
/** The customer address the sale was taxed on (#722), sent as order.create 8's `taxAddress`; absent: the store's base. */
|
|
80
113
|
taxAddress?: 'billing' | 'shipping';
|
|
81
114
|
/** The sale's note; sent as order.create version 7's `note` (ADR-083), cut to ORDER_NOTE_MAX when frozen. */
|
|
82
115
|
note?: string;
|
|
116
|
+
/** The order's custom fields (pos_orders v18, ADR-092), sent at order.create 12 in this order. */
|
|
117
|
+
meta?: Array<{ key: string; value: string }>;
|
|
83
118
|
registerId?: string;
|
|
84
119
|
/**
|
|
85
120
|
* The register session the sale was taken in (ADR-032): its closure counts this order.
|
|
86
121
|
* Sent at `order.create` version 3 as the payload's `sessionId` (the stamped or late session, one field).
|
|
87
122
|
*/
|
|
88
123
|
sessionId?: string;
|
|
124
|
+
/** The closed session whose closure already counted this sale: set by finalize on an after-close reopen (ADR-077), which then joins no session. */
|
|
125
|
+
countedInClosureOf?: string;
|
|
89
126
|
/**
|
|
90
127
|
* Set only by `useSale`'s late-sale path (ADR-032): the session the sale was taken for, which
|
|
91
128
|
* refused the stamp after the money was taken. Such an order has no `sessionId`, so no closure
|
|
@@ -96,9 +133,9 @@ export interface PosOrder {
|
|
|
96
133
|
* The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
|
|
97
134
|
* send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
|
|
98
135
|
*/
|
|
99
|
-
sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
|
136
|
+
sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
|
|
100
137
|
/** The version first tried, before the downgrade (the order's audit). */
|
|
101
|
-
downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
|
138
|
+
downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
|
|
102
139
|
/** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
|
|
103
140
|
display?: DisplayTotals & { currency: string; exponent: number };
|
|
104
141
|
/** ADR-065: tax by rate, named as `taxLinesByRate` names them (`amountMinor` is the tax). */
|
|
@@ -119,4 +156,6 @@ export interface PosOrder {
|
|
|
119
156
|
updatedAt: string;
|
|
120
157
|
/** When the till reopened this refused order as a parked sale (ADR-077 d4b). Needs attention hides it, and it stays as the record of the refusal. */
|
|
121
158
|
reopenedAt?: string;
|
|
159
|
+
/** The commandId whose refusal the cashier marked handled (tally-woo 03, ADR-092 6f); the logic comes in a later PR. */
|
|
160
|
+
attentionHandledFor?: string;
|
|
122
161
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
<receipt paper-width="48">
|
|
2
|
+
<align mode="center">
|
|
3
|
+
<size width="2" height="2"><bold><text>Corner Cafe</text></bold></size>
|
|
4
|
+
<text>12 High Street, Leeds</text>
|
|
5
|
+
</align>
|
|
6
|
+
<line />
|
|
7
|
+
<text>Plain <bold>bold</bold>, <underline>under</underline>, <invert>inv</invert> end</text>
|
|
8
|
+
<text> Oat milk, extra hot, no foam, in a takeaway cup</text>
|
|
9
|
+
<align mode="right"><text>Right side</text></align>
|
|
10
|
+
<row><col width="10">Order</col><col width="*" align="right">#1001</col></row>
|
|
11
|
+
<line style="dashed" />
|
|
12
|
+
<text>Flat White</text>
|
|
13
|
+
<row><col width="*"> 2 × 3.50</col><col width="12" align="right">7.00</col></row>
|
|
14
|
+
<row><col width="*"> Loyalty discount for regular customers</col><col width="12" align="right">−1.00</col></row>
|
|
15
|
+
<line style="dotted" />
|
|
16
|
+
<bold><row><col width="10">Total</col><col width="*" align="right">6.00</col></row></bold>
|
|
17
|
+
<line style="double" />
|
|
18
|
+
<row><col width="6">Cash</col><col width="*">tendered</col><col width="12" align="right">10.00</col></row>
|
|
19
|
+
<feed lines="2" />
|
|
20
|
+
<image src="https://example.invalid/logo.png" width="200" />
|
|
21
|
+
<text>Note one
|
|
22
|
+
Note two</text>
|
|
23
|
+
<align mode="center">
|
|
24
|
+
<text>Thanks again</text>
|
|
25
|
+
<barcode type="code128" height="50">ORDER-1001</barcode>
|
|
26
|
+
<barcode type="ean13">4006381333932</barcode>
|
|
27
|
+
<barcode type="upca">012345678905</barcode>
|
|
28
|
+
<qrcode size="4">https://example.invalid/r/1001</qrcode>
|
|
29
|
+
</align>
|
|
30
|
+
<feed lines="3" />
|
|
31
|
+
<drawer />
|
|
32
|
+
<cut />
|
|
33
|
+
</receipt>
|
|
@@ -3,12 +3,36 @@
|
|
|
3
3
|
* opens every job with `ESC @` then `ESC M 0` (Font A, so the profile's column count holds whatever the
|
|
4
4
|
* printer's memory switch says; v2 gotcha N39), and `render-escpos.ts` `writeCut` cuts with `GS V 0x41|0x42 0`
|
|
5
5
|
* (feed to the cutter, then cut). Text goes through `foldText`, so no multibyte UTF-8 ever reaches the printer.
|
|
6
|
+
* The `underline`, `invert`, `barcode` and `qrcode` bytes follow `@point-of-sale/receipt-printer-encoder` 4.0.1,
|
|
7
|
+
* as read on 19 Nov 2026, except two TallyUI choices: the `GS h`, `GS w`, `GS H` order before a barcode, and
|
|
8
|
+
* sending a computed check digit for a 12-digit EAN-13.
|
|
6
9
|
*/
|
|
7
10
|
import type { DrawerConnector } from '../../receipt-template/types';
|
|
8
11
|
import { foldText, resolveCodePage, type EscPosCodePage } from './code-page';
|
|
9
12
|
|
|
10
13
|
const ESC = 0x1b;
|
|
11
14
|
const GS = 0x1d;
|
|
15
|
+
const HRI = { none: 0, above: 1, below: 2, both: 3 } as const;
|
|
16
|
+
const QR_LEVEL = { l: 0x30, m: 0x31, q: 0x32, h: 0x33 } as const;
|
|
17
|
+
/** QR's numeric-mode capacity, the longest value any QR symbol can hold. */
|
|
18
|
+
const QR_MAX_LENGTH = 7089;
|
|
19
|
+
|
|
20
|
+
export interface EscPosBarcodeOptions {
|
|
21
|
+
/** `GS h n`, dots. Default 60; rounded and clamped to 1-255. */
|
|
22
|
+
height?: number;
|
|
23
|
+
/** Module width 1-3; `GS w (width + 1)`. Default 2; rounded and clamped to 1-3. */
|
|
24
|
+
width?: number;
|
|
25
|
+
/** `GS H n`: where the human-readable digits print. Default 'none'. */
|
|
26
|
+
hri?: 'none' | 'above' | 'below' | 'both';
|
|
27
|
+
}
|
|
28
|
+
export interface EscPosQrOptions {
|
|
29
|
+
/** Default 2. */
|
|
30
|
+
model?: 1 | 2;
|
|
31
|
+
/** Module size; default 6; rounded and clamped to 1-8. */
|
|
32
|
+
size?: number;
|
|
33
|
+
/** Error correction; default 'm'. */
|
|
34
|
+
errorLevel?: 'l' | 'm' | 'q' | 'h';
|
|
35
|
+
}
|
|
12
36
|
|
|
13
37
|
export interface EscPosBuilder {
|
|
14
38
|
/** `ESC @` (reset), then `ESC M 0` (Font A). */
|
|
@@ -26,9 +50,47 @@ export interface EscPosBuilder {
|
|
|
26
50
|
cut(type?: 'full' | 'partial'): EscPosBuilder;
|
|
27
51
|
/** `ESC p m 25 250`: a drawer kick, on 50 ms and off 500 ms; m 0 for pin 2, 1 for pin 5. */
|
|
28
52
|
pulse(connector?: DrawerConnector): EscPosBuilder;
|
|
53
|
+
/** `ESC - 1` on, `ESC - 0` off. */
|
|
54
|
+
underline(on: boolean): EscPosBuilder;
|
|
55
|
+
/** `GS B 1` on, `GS B 0` off (reverse print). */
|
|
56
|
+
invert(on: boolean): EscPosBuilder;
|
|
57
|
+
/** `GS h`, `GS w`, `GS H`, then `GS k 0x49 n data` (code128) or `GS k 0x02 d1…d13 NUL` (ean13); RangeError first. */
|
|
58
|
+
barcode(value: string, symbology: 'code128' | 'ean13', options?: EscPosBarcodeOptions): EscPosBuilder;
|
|
59
|
+
/** `GS ( k` model, size, error level, store (`31 50 30 data`) and print (`31 51 30`); RangeError first. */
|
|
60
|
+
qrcode(value: string, options?: EscPosQrOptions): EscPosBuilder;
|
|
29
61
|
bytes(): Uint8Array;
|
|
30
62
|
}
|
|
31
63
|
|
|
64
|
+
const fit = (n: number, max: number) => Math.min(max, Math.max(1, Math.round(n)));
|
|
65
|
+
const codes = (value: string) => Array.from(value, (char) => char.charCodeAt(0));
|
|
66
|
+
|
|
67
|
+
/** The `GS k` bytes for a barcode value. Throws a RangeError when it cannot be encoded. */
|
|
68
|
+
function barcodeSymbol(value: string, symbology: 'code128' | 'ean13'): number[] {
|
|
69
|
+
if (symbology === 'ean13') {
|
|
70
|
+
if (!/^\d{12,13}$/.test(value)) throw new RangeError('ean13: value must be 12 or 13 digits');
|
|
71
|
+
let sum = 0;
|
|
72
|
+
for (let i = 0; i < 12; i++) sum += Number(value[i]) * (i % 2 === 0 ? 1 : 3);
|
|
73
|
+
const check = (10 - (sum % 10)) % 10;
|
|
74
|
+
if (value.length === 13 && Number(value[12]) !== check) throw new RangeError('ean13: wrong check digit');
|
|
75
|
+
return [GS, 0x6b, 0x02, ...codes(value.slice(0, 12) + check), 0];
|
|
76
|
+
}
|
|
77
|
+
if (!/^[\x20-\x7e]+$/.test(value)) throw new RangeError('code128: value must be non-empty printable ASCII');
|
|
78
|
+
const selected = /^\{[ABC]/.test(value);
|
|
79
|
+
if ((selected ? value.slice(2) : value).includes('{')) throw new RangeError('code128: { only in a leading {A, {B or {C');
|
|
80
|
+
const data = selected ? value : '{B' + value;
|
|
81
|
+
if (data.length > 255) throw new RangeError('code128: data longer than 255 bytes');
|
|
82
|
+
return [GS, 0x6b, 0x49, data.length, ...codes(data)];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One byte per character (ISO-8859-1). Throws a RangeError when the value cannot be encoded. */
|
|
86
|
+
function qrData(value: string): number[] {
|
|
87
|
+
if (value === '') throw new RangeError('qrcode: value is empty');
|
|
88
|
+
const data = codes(value);
|
|
89
|
+
if (data.some((code) => code > 0xff)) throw new RangeError('qrcode: character above 0xFF');
|
|
90
|
+
if (data.length > QR_MAX_LENGTH) throw new RangeError(`qrcode: longer than ${QR_MAX_LENGTH} characters`);
|
|
91
|
+
return data;
|
|
92
|
+
}
|
|
93
|
+
|
|
32
94
|
export function escpos(page: EscPosCodePage = resolveCodePage()): EscPosBuilder {
|
|
33
95
|
const out: number[] = [];
|
|
34
96
|
const clamp = (n: number) => Math.min(8, Math.max(1, Math.round(n))) - 1;
|
|
@@ -43,6 +105,23 @@ export function escpos(page: EscPosCodePage = resolveCodePage()): EscPosBuilder
|
|
|
43
105
|
feed: (lines) => push(ESC, 0x64, Math.min(255, Math.max(0, lines))),
|
|
44
106
|
cut: (type = 'partial') => push(GS, 0x56, type === 'full' ? 0x41 : 0x42, 0),
|
|
45
107
|
pulse: (connector = 'pin2') => push(ESC, 0x70, connector === 'pin5' ? 1 : 0, 25, 250),
|
|
108
|
+
underline: (on) => push(ESC, 0x2d, on ? 1 : 0),
|
|
109
|
+
invert: (on) => push(GS, 0x42, on ? 1 : 0),
|
|
110
|
+
barcode: (value, symbology, { height = 60, width = 2, hri = 'none' } = {}) => {
|
|
111
|
+
const symbol = barcodeSymbol(value, symbology);
|
|
112
|
+
return push(GS, 0x68, fit(height, 255), GS, 0x77, fit(width, 3) + 1, GS, 0x48, HRI[hri], ...symbol);
|
|
113
|
+
},
|
|
114
|
+
qrcode: (value, { model = 2, size = 6, errorLevel = 'm' } = {}) => {
|
|
115
|
+
const data = qrData(value);
|
|
116
|
+
const stored = data.length + 3;
|
|
117
|
+
return push(
|
|
118
|
+
GS, 0x28, 0x6b, 4, 0, 0x31, 0x41, model === 1 ? 0x31 : 0x32, 0,
|
|
119
|
+
GS, 0x28, 0x6b, 3, 0, 0x31, 0x43, fit(size, 8),
|
|
120
|
+
GS, 0x28, 0x6b, 3, 0, 0x31, 0x45, QR_LEVEL[errorLevel],
|
|
121
|
+
GS, 0x28, 0x6b, stored & 0xff, stored >> 8, 0x31, 0x50, 0x30, ...data,
|
|
122
|
+
GS, 0x28, 0x6b, 3, 0, 0x31, 0x51, 0x30,
|
|
123
|
+
);
|
|
124
|
+
},
|
|
46
125
|
bytes: () => Uint8Array.from(out),
|
|
47
126
|
};
|
|
48
127
|
function push(...bytes: number[]): EscPosBuilder {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A standalone cash-drawer kick, ported from WCPOS v2 `packages/printer/src/printer-service.ts`
|
|
3
|
+
* (`encodeEscposDrawerKick`, `openDrawer`) and `capabilities.ts` (`canOpenDrawer`), monorepo main.
|
|
4
|
+
*/
|
|
5
|
+
import type { PrinterProfile } from '../printer-profiles';
|
|
6
|
+
import { PrintError, type PrintJob } from '../types';
|
|
7
|
+
import { escpos } from './commands';
|
|
8
|
+
|
|
9
|
+
/** Whether a standalone drawer kick can go to this printer (v2 capabilities.ts canOpenDrawer). */
|
|
10
|
+
export function canOpenDrawer(profile: PrinterProfile | undefined): boolean {
|
|
11
|
+
if (!profile || profile.connectionType === 'system') return false;
|
|
12
|
+
// A profile with no language speaks ESC/POS, as `createEscPosTransport` treats it.
|
|
13
|
+
return profile.language === undefined || profile.language === 'esc-pos';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The drawer-kick job for `profile`, to run through the printer's queue and `createEscPosTransport`. */
|
|
17
|
+
export function openDrawerJob(profile: PrinterProfile, id: string): PrintJob {
|
|
18
|
+
if (!canOpenDrawer(profile)) throw new PrintError('unsupported', `Printer ${profile.name} cannot open a cash drawer`);
|
|
19
|
+
const connector = profile.drawerConnector ?? 'pin2';
|
|
20
|
+
// Epson gets the real-time kick (DLE DC4), which fires while busy; many clones ignore it, so others get ESC p.
|
|
21
|
+
const bytes = profile.vendor === 'epson'
|
|
22
|
+
? Uint8Array.from([0x10, 0x14, 0x01, connector === 'pin5' ? 1 : 0, 0x03])
|
|
23
|
+
: escpos().pulse(connector).bytes();
|
|
24
|
+
return { id, kind: 'drawer', bytes };
|
|
25
|
+
}
|
|
@@ -114,6 +114,7 @@ export function encodeEscPos(receipt: ReceiptData, options: EncodeEscPosOptions)
|
|
|
114
114
|
pair(payment.reference ? `${payment.method} ${payment.reference}` : payment.method, payment.amount);
|
|
115
115
|
}
|
|
116
116
|
if (data.change) pair('Change', data.change);
|
|
117
|
+
if (data.refundDue) pair('Refund due', data.refundDue);
|
|
117
118
|
if (data.note) {
|
|
118
119
|
out.feed(1);
|
|
119
120
|
print(block(data.note));
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
export { ESCPOS_CODE_PAGES } from './code-page';
|
|
2
2
|
export { escpos } from './commands';
|
|
3
|
-
export type { EscPosBuilder } from './commands';
|
|
3
|
+
export type { EscPosBarcodeOptions, EscPosBuilder, EscPosQrOptions } from './commands';
|
|
4
4
|
export { encodeEscPos } from './encode';
|
|
5
5
|
export type { EncodeEscPosOptions } from './encode';
|
|
6
6
|
export { createEscPosTransport } from './transport';
|
|
7
7
|
export type { EscPosSink, EscPosTransportOptions } from './transport';
|
|
8
|
+
export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor } from './network-sinks';
|
|
9
|
+
export type { NetworkSinkOptions } from './network-sinks';
|
|
10
|
+
export { canOpenDrawer, openDrawerJob } from './drawer';
|
|
11
|
+
export { renderEscpos, encodeThermalTemplate } from './render-escpos';
|
|
12
|
+
export type { RenderEscposOptions } from './render-escpos';
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web sinks for `createEscPosTransport`. A browser cannot open a raw 9100 socket, so a network Epson printer takes the
|
|
3
|
+
* bytes over ePOS-Print and a Star printer over WebPRNT: plain HTTP, no vendor SDK (ADR-084 decision 2). Ported from
|
|
4
|
+
* WCPOS v2 `packages/printer/src/transport` (monorepo main).
|
|
5
|
+
*/
|
|
6
|
+
import type { PrinterProfile } from '../printer-profiles';
|
|
7
|
+
import { PrintError } from '../types';
|
|
8
|
+
import type { EscPosSink } from './transport';
|
|
9
|
+
|
|
10
|
+
export interface NetworkSinkOptions {
|
|
11
|
+
/** IP address or hostname. */
|
|
12
|
+
address: string;
|
|
13
|
+
/** The profile's port. Unset or 9100 (the raw-socket default) picks the vendor's web port. */
|
|
14
|
+
port?: number;
|
|
15
|
+
/** The till page is https. Default: `globalThis.location?.protocol === 'https:'`. */
|
|
16
|
+
https?: boolean;
|
|
17
|
+
/** Abort the request after this long. Default: 15_000 for ePOS, 30_000 for WebPRNT (v2's figures). */
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
/** Default `globalThis.fetch`. */
|
|
20
|
+
fetch?: typeof fetch;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const pageIsHttps = () => globalThis.location?.protocol === 'https:';
|
|
24
|
+
|
|
25
|
+
// v2 epson-epos-protocol.ts:4 buildEposXml.
|
|
26
|
+
function buildEposXml(innerXml: string): string {
|
|
27
|
+
return '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'
|
|
28
|
+
+ `<s:Body><epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">${innerXml}</epos-print>`
|
|
29
|
+
+ '</s:Body></s:Envelope>';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// v2 epson-epos-protocol.ts:17 parseEposResponse.
|
|
33
|
+
function parseEposResponse(body: string): { success: boolean; code: string } {
|
|
34
|
+
const response = body.match(/<(?:[A-Za-z_][\w.-]*:)?response\b[^>]*>/i)?.[0];
|
|
35
|
+
if (!response) throw new PrintError('failed', 'Unexpected Epson ePOS response from printer');
|
|
36
|
+
const attribute = (name: string) => response.match(new RegExp(`\\b${name}\\s*=\\s*(["'])(.*?)\\1`, 'i'))?.[2] ?? '';
|
|
37
|
+
const success = attribute('success');
|
|
38
|
+
return { success: success === 'true' || success === '1', code: attribute('code') };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// v2 epson-epos-protocol.ts:35 commandFromBytes: lowercase hex, two digits a byte.
|
|
42
|
+
function commandFromBytes(bytes: Uint8Array): string {
|
|
43
|
+
return `<command>${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}</command>`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// v2 star-webprnt-adapter.ts:118 uint8ArrayToBase64: btoa over 8 KiB chunks.
|
|
47
|
+
function toBase64(bytes: Uint8Array): string {
|
|
48
|
+
const chunks: string[] = [];
|
|
49
|
+
for (let i = 0; i < bytes.length; i += 8192) chunks.push(String.fromCharCode(...bytes.subarray(i, i + 8192)));
|
|
50
|
+
return btoa(chunks.join(''));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// v2 utils/local-fetch.ts:29 withTargetAddressSpace: mark a plain-http LAN request for Local Network Access; skip
|
|
54
|
+
// loopback, where a 'local' mark that mismatches the address space fails the request.
|
|
55
|
+
function withTargetAddressSpace(url: string, init: RequestInit): RequestInit {
|
|
56
|
+
const { protocol, hostname } = new URL(url);
|
|
57
|
+
const loopback = hostname === 'localhost' || hostname === '::1' || hostname === '[::1]' || hostname.startsWith('127.');
|
|
58
|
+
return protocol !== 'http:' || loopback ? init : { ...init, targetAddressSpace: 'local' } as RequestInit;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// v2 epson-epos-adapter.ts:81-112: POST, abort after the timeout, always clear the timer.
|
|
62
|
+
async function post(label: string, url: string, init: RequestInit, timeoutMs: number, fetchFn = globalThis.fetch) {
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
65
|
+
try {
|
|
66
|
+
return await fetchFn(url, withTargetAddressSpace(url, { ...init, method: 'POST', signal: controller.signal }));
|
|
67
|
+
} catch (error) {
|
|
68
|
+
const within = controller.signal.aborted ? ` within ${timeoutMs} ms` : '';
|
|
69
|
+
throw new PrintError('failed', `${label} printer at ${url} did not answer${within}`, { cause: error });
|
|
70
|
+
} finally {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createEpsonEposSink(options: NetworkSinkOptions & { deviceId?: string }): EscPosSink {
|
|
76
|
+
const { address, port, https = pageIsHttps(), timeoutMs = 15_000, fetch: fetchFn, deviceId } = options;
|
|
77
|
+
// v2 network-adapter.web.ts:30 maps the raw-socket 9100 to ePOS's port; epson-epos-adapter.ts:45 picks the scheme.
|
|
78
|
+
const webPort = port === undefined || port === 9100 ? (https ? 8043 : 8008) : port;
|
|
79
|
+
const scheme = webPort === 8043 || webPort === 443 ? 'https' : 'http';
|
|
80
|
+
const url = `${scheme}://${address}:${webPort}/cgi-bin/epos/service.cgi`
|
|
81
|
+
+ `?devid=${encodeURIComponent(deviceId ?? 'local_printer')}&timeout=10000`;
|
|
82
|
+
return {
|
|
83
|
+
async write(bytes) {
|
|
84
|
+
// v2 epson-epos-adapter.ts:86-122: the SOAP headers, then the reply's success and code.
|
|
85
|
+
const headers = {
|
|
86
|
+
'Content-Type': 'text/xml; charset=utf-8', 'If-Modified-Since': 'Thu, 01 Jan 1970 00:00:00 GMT', SOAPAction: '""',
|
|
87
|
+
};
|
|
88
|
+
const response = await post('Epson ePOS', url, { headers, body: buildEposXml(commandFromBytes(bytes)) }, timeoutMs, fetchFn);
|
|
89
|
+
if (!response.ok) throw new PrintError('failed', `Epson ePOS HTTP ${response.status}`);
|
|
90
|
+
const { success, code } = parseEposResponse(await response.text());
|
|
91
|
+
if (!success) throw new PrintError('failed', `Epson print failed (code: ${code || 'unknown'})`);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createStarWebPrntSink(options: NetworkSinkOptions & { cut?: boolean }): EscPosSink {
|
|
97
|
+
const { address, port, https = pageIsHttps(), timeoutMs = 30_000, fetch: fetchFn, cut = false } = options;
|
|
98
|
+
// v2 network-adapter.web.ts:78-91 resolveStarWebPrntUrl: 9100 maps to 80 or 443; only 443 is https.
|
|
99
|
+
const webPort = port === undefined || port === 9100 ? (https ? 443 : 80) : port;
|
|
100
|
+
const url = `${webPort === 443 ? 'https' : 'http'}://${address}:${webPort}/StarWebPRNT/SendMessage`;
|
|
101
|
+
return {
|
|
102
|
+
async write(bytes) {
|
|
103
|
+
// v2 star-webprnt-adapter.ts:41-54. No <cutpaper> by default: encodeEscPos already writes the profile's cut.
|
|
104
|
+
const body = [
|
|
105
|
+
'<?xml version="1.0" encoding="utf-8"?>',
|
|
106
|
+
'<StarWebPrint xmlns="http://schema.starwebprnt.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">',
|
|
107
|
+
' <SendMessage>', ' <Request>', ' <initialize />', ` <rawData>${toBase64(bytes)}</rawData>`,
|
|
108
|
+
cut ? ' <cutpaper feed="true" />' : '', ' </Request>', ' </SendMessage>', '</StarWebPrint>',
|
|
109
|
+
].filter(Boolean).join('\n');
|
|
110
|
+
const init = { headers: { 'Content-Type': 'text/xml; charset=utf-8' }, body };
|
|
111
|
+
const response = await post('Star WebPRNT', url, init, timeoutMs, fetchFn);
|
|
112
|
+
// v2 star-webprnt-adapter.ts:87-99: a reply with no <Status> counts as printed.
|
|
113
|
+
if (!response.ok) throw new PrintError('failed', `Star WebPRNT request failed (HTTP ${response.status})`);
|
|
114
|
+
const status = (await response.text()).match(/<Status>(\w+)<\/Status>/)?.[1];
|
|
115
|
+
if (status !== undefined && status !== 'Normal') throw new PrintError('failed', `Star printer reported status: ${status}`);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The web sink for a network Epson or Star profile; null for system, usb, bluetooth, a generic vendor or no address. */
|
|
121
|
+
export function networkSinkFor(
|
|
122
|
+
profile: PrinterProfile, options: Pick<NetworkSinkOptions, 'https' | 'timeoutMs' | 'fetch'> = {},
|
|
123
|
+
): EscPosSink | null {
|
|
124
|
+
// v2 network-adapter.web.ts:24-45: Epson and Star only; any other vendor has no web protocol.
|
|
125
|
+
const { connectionType, vendor, address, port } = profile;
|
|
126
|
+
if (connectionType !== 'network' || !address) return null;
|
|
127
|
+
if (vendor === 'epson') return createEpsonEposSink({ address, port, ...options });
|
|
128
|
+
if (vendor === 'star') return createStarWebPrntSink({ address, port, ...options });
|
|
129
|
+
return null;
|
|
130
|
+
}
|