@tallyui/pos 3.13.0 → 3.14.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 +342 -102
- package/dist/index.js +414 -46
- package/package.json +7 -7
- package/src/app-settings/app-settings.ts +17 -2
- package/src/customer-display/display-link.ts +72 -0
- package/src/customer-display/index.ts +5 -0
- package/src/customer-display/transport.ts +54 -0
- package/src/customer-display/use-customer-display.ts +36 -0
- package/src/index.ts +8 -2
- package/src/print/escpos/code-page.ts +48 -0
- package/src/print/escpos/commands.ts +53 -0
- package/src/print/escpos/encode.ts +127 -0
- package/src/print/escpos/index.ts +7 -0
- package/src/print/escpos/transport.ts +45 -0
- package/src/print/index.ts +2 -0
- package/src/print/types.ts +4 -0
- package/src/register/handover.ts +103 -0
- package/src/register/index.ts +2 -0
- package/src/reports/sales-figures.ts +22 -8
- package/src/sale/in-cart.ts +18 -0
- package/src/sale/index.ts +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.14.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",
|
|
@@ -28,26 +28,26 @@
|
|
|
28
28
|
"directory": "packages/pos"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
+
"@types/mustache": "^4.2.6",
|
|
31
32
|
"@xmldom/xmldom": "0.9.12",
|
|
32
33
|
"dompurify": "^3.4.17",
|
|
33
34
|
"mustache": "^4.2.0"
|
|
34
35
|
},
|
|
35
36
|
"peerDependencies": {
|
|
36
|
-
"@tallyui/core": "^3.
|
|
37
|
+
"@tallyui/core": "^3.14.0",
|
|
37
38
|
"react": ">=18",
|
|
38
39
|
"rxdb": "~17.5.0",
|
|
39
40
|
"rxjs": ">=7"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
|
-
"@tallyui/core": "3.
|
|
43
|
-
"@types/mustache": "^4.2.6",
|
|
43
|
+
"@tallyui/core": "3.14.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": "3.
|
|
49
|
-
"@tallyui/connector-woocommerce": "3.
|
|
50
|
-
"@tallyui/database": "3.
|
|
48
|
+
"@tallyui/connector-medusa": "3.14.0",
|
|
49
|
+
"@tallyui/connector-woocommerce": "3.14.0",
|
|
50
|
+
"@tallyui/database": "3.14.0"
|
|
51
51
|
},
|
|
52
52
|
"scripts": {
|
|
53
53
|
"build": "tsup",
|
|
@@ -22,6 +22,11 @@ export interface AppSettings {
|
|
|
22
22
|
'ui.scale': UiScale;
|
|
23
23
|
/** A font id; `'auto'` follows the theme. Not an enum: the font list lives in the UI layer. */
|
|
24
24
|
'ui.font': string;
|
|
25
|
+
/**
|
|
26
|
+
* The cart's quick-discount keys in percent, for `Cart`'s `quickDiscounts`. v2 keeps them per screen,
|
|
27
|
+
* `pos-cart.quickDiscounts: [5, 10, 15]` (`core/src/screens/main/contexts/ui-settings/initial-settings.json`).
|
|
28
|
+
*/
|
|
29
|
+
'cart.quickDiscounts': readonly number[];
|
|
25
30
|
}
|
|
26
31
|
export type AppSettingKey = keyof AppSettings;
|
|
27
32
|
|
|
@@ -37,11 +42,19 @@ export const APP_SETTING_DEFINITIONS: { [K in AppSettingKey]: AppSettingDefiniti
|
|
|
37
42
|
default: 'auto',
|
|
38
43
|
parse: (value) => typeof value === 'string' && value.length > 0 && value.length <= 64 ? value : undefined,
|
|
39
44
|
},
|
|
45
|
+
'cart.quickDiscounts': {
|
|
46
|
+
default: [5, 10, 15],
|
|
47
|
+
// As v2's `ensureNumberArray`: only real percentages (0 < n <= 100) survive; an empty list is no keys.
|
|
48
|
+
parse: (value) => Array.isArray(value)
|
|
49
|
+
? value.filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0 && n <= 100)
|
|
50
|
+
: undefined,
|
|
51
|
+
},
|
|
40
52
|
};
|
|
41
53
|
export const DEFAULT_APP_SETTINGS: AppSettings = {
|
|
42
54
|
'ui.theme': APP_SETTING_DEFINITIONS['ui.theme'].default,
|
|
43
55
|
'ui.scale': APP_SETTING_DEFINITIONS['ui.scale'].default,
|
|
44
56
|
'ui.font': APP_SETTING_DEFINITIONS['ui.font'].default,
|
|
57
|
+
'cart.quickDiscounts': APP_SETTING_DEFINITIONS['cart.quickDiscounts'].default,
|
|
45
58
|
};
|
|
46
59
|
|
|
47
60
|
/** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
|
|
@@ -86,8 +99,10 @@ export function appSettings$(collection: AppSettingCollection): Observable<AppSe
|
|
|
86
99
|
export async function writeAppSetting<K extends AppSettingKey>(
|
|
87
100
|
collection: AppSettingCollection, key: K, value: AppSettings[K],
|
|
88
101
|
): Promise<void> {
|
|
89
|
-
|
|
102
|
+
// The parsed value is stored, so a list keeps only what a read would keep.
|
|
103
|
+
const parsed = APP_SETTING_DEFINITIONS[key].parse(value);
|
|
104
|
+
if (parsed === undefined) {
|
|
90
105
|
throw new Error(`writeAppSetting: invalid value for ${key}`);
|
|
91
106
|
}
|
|
92
|
-
await collection.upsert({ key, value: JSON.stringify(
|
|
107
|
+
await collection.upsert({ key, value: JSON.stringify(parsed) });
|
|
93
108
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { ReceiptData } from '../receipt/types';
|
|
2
|
+
import { displayCart, makeEnvelope, type DisplayConfig, type DisplayEnvelope, type DisplayPayment } from './protocol';
|
|
3
|
+
import type { DisplayTransport } from './transport';
|
|
4
|
+
|
|
5
|
+
export interface DisplayClock { setTimeout(run: () => void, ms: number): unknown; clearTimeout(handle: unknown): void }
|
|
6
|
+
|
|
7
|
+
const systemClock: DisplayClock = {
|
|
8
|
+
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
9
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export interface DisplayLink {
|
|
13
|
+
/** The order as it stands; null, or no lines, fees or shipping, shows idle. */
|
|
14
|
+
showCart(receipt: ReceiptData | null): void;
|
|
15
|
+
showPayment(receipt: ReceiptData, payment: DisplayPayment): void;
|
|
16
|
+
close(): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The till's side of the customer display. Ported from WCPOS v2 (monorepo main 51e7c43,
|
|
21
|
+
* core/services/customer-display/display-session.ts and service.ts) without the WebRTC: each `display.hello` is
|
|
22
|
+
* answered with `display.config` under the hello's id, then the current state; a completed payment stays up for
|
|
23
|
+
* `config.idle.afterCompleteMs` before `display.idle`, and an empty cart inside that window waits for it.
|
|
24
|
+
*/
|
|
25
|
+
export function createDisplayLink(transport: DisplayTransport, options: { config: DisplayConfig; clock?: DisplayClock }): DisplayLink {
|
|
26
|
+
const { config, clock = systemClock } = options;
|
|
27
|
+
let current: DisplayEnvelope | null = null;
|
|
28
|
+
let lastKey = '';
|
|
29
|
+
let idleTimer: unknown = null;
|
|
30
|
+
const cancelIdle = () => {
|
|
31
|
+
if (idleTimer !== null) clock.clearTimeout(idleTimer);
|
|
32
|
+
idleTimer = null;
|
|
33
|
+
};
|
|
34
|
+
// As v2's lastPublished: the same state twice is sent once.
|
|
35
|
+
const publish = (envelope: DisplayEnvelope) => {
|
|
36
|
+
const key = JSON.stringify([envelope.action, envelope.payload]);
|
|
37
|
+
if (key === lastKey) return;
|
|
38
|
+
lastKey = key;
|
|
39
|
+
current = envelope;
|
|
40
|
+
transport.send(envelope);
|
|
41
|
+
};
|
|
42
|
+
const idle = () => publish(makeEnvelope('display.idle', { reason: 'no_cart' }));
|
|
43
|
+
const unsubscribe = transport.onMessage((envelope) => {
|
|
44
|
+
if (envelope.action !== 'display.hello') return;
|
|
45
|
+
transport.send(makeEnvelope('display.config', { ...config, template: envelope.payload.template }, envelope.id));
|
|
46
|
+
if (current) transport.send(current);
|
|
47
|
+
});
|
|
48
|
+
return {
|
|
49
|
+
showCart(receipt) {
|
|
50
|
+
if (!receipt || receipt.lineItems.length + receipt.fees.length + receipt.shipping.length === 0) {
|
|
51
|
+
if (idleTimer === null) idle();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
cancelIdle();
|
|
55
|
+
publish(makeEnvelope('cart.updated', displayCart(receipt)));
|
|
56
|
+
},
|
|
57
|
+
showPayment(receipt, payment) {
|
|
58
|
+
cancelIdle();
|
|
59
|
+
publish(makeEnvelope('payment.state', { ...displayCart(receipt), ...payment }));
|
|
60
|
+
if (payment.state === 'complete') {
|
|
61
|
+
idleTimer = clock.setTimeout(() => {
|
|
62
|
+
idleTimer = null;
|
|
63
|
+
idle();
|
|
64
|
+
}, config.idle.afterCompleteMs);
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
close() {
|
|
68
|
+
cancelIdle();
|
|
69
|
+
unsubscribe();
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -6,3 +6,8 @@ export type {
|
|
|
6
6
|
export { MAX_MESSAGE_BYTES, messageBytes, encode } from './snapshot';
|
|
7
7
|
export { displayReducer, initialDisplayState } from './display-state';
|
|
8
8
|
export type { DisplayView, DisplayState } from './display-state';
|
|
9
|
+
export { DISPLAY_CHANNEL, createBroadcastDisplayTransport } from './transport';
|
|
10
|
+
export type { DisplayTransport, BroadcastChannelLike } from './transport';
|
|
11
|
+
export { createDisplayLink } from './display-link';
|
|
12
|
+
export type { DisplayLink, DisplayClock } from './display-link';
|
|
13
|
+
export { useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './use-customer-display';
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { decode, type DisplayEnvelope } from './protocol';
|
|
2
|
+
import { encode } from './snapshot';
|
|
3
|
+
|
|
4
|
+
/** How the till and the customer display reach each other. The first is a second window on this device (ADR-084 3). */
|
|
5
|
+
export interface DisplayTransport {
|
|
6
|
+
/** False when the channel refuses (closed); never throws. */
|
|
7
|
+
send(envelope: DisplayEnvelope): boolean;
|
|
8
|
+
/** Decoded messages from the other window; returns the unsubscribe. */
|
|
9
|
+
onMessage(listener: (envelope: DisplayEnvelope) => void): () => void;
|
|
10
|
+
close(): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const DISPLAY_CHANNEL = 'tallyui.customer-display';
|
|
14
|
+
|
|
15
|
+
/** The structural part of BroadcastChannel the transport uses (a test passes a fake). */
|
|
16
|
+
export interface BroadcastChannelLike {
|
|
17
|
+
postMessage(message: unknown): void;
|
|
18
|
+
close(): void;
|
|
19
|
+
onmessage: ((event: MessageEvent) => void) | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A same-origin second window over BroadcastChannel. Whatever arrives is decoded; anything refused is dropped. */
|
|
23
|
+
export function createBroadcastDisplayTransport(
|
|
24
|
+
channelName = DISPLAY_CHANNEL,
|
|
25
|
+
open: (name: string) => BroadcastChannelLike = (name) => new BroadcastChannel(name),
|
|
26
|
+
): DisplayTransport {
|
|
27
|
+
const channel = open(channelName);
|
|
28
|
+
const listeners = new Set<(envelope: DisplayEnvelope) => void>();
|
|
29
|
+
channel.onmessage = (event) => {
|
|
30
|
+
const result = decode(event.data);
|
|
31
|
+
if (result.ok) listeners.forEach((listener) => listener(result.envelope));
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
send(envelope) {
|
|
35
|
+
try {
|
|
36
|
+
channel.postMessage(encode(envelope));
|
|
37
|
+
return true;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
onMessage(listener) {
|
|
43
|
+
listeners.add(listener);
|
|
44
|
+
return () => {
|
|
45
|
+
listeners.delete(listener);
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
close() {
|
|
49
|
+
listeners.clear();
|
|
50
|
+
channel.onmessage = null;
|
|
51
|
+
channel.close();
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { displayReducer, initialDisplayState, type DisplayState } from './display-state';
|
|
3
|
+
import { makeEnvelope, type DisplayTemplate } from './protocol';
|
|
4
|
+
import type { DisplayTransport } from './transport';
|
|
5
|
+
|
|
6
|
+
export const DISPLAY_TEMPLATE: DisplayTemplate = { id: 'default', version: 1 };
|
|
7
|
+
/** The hello is re-sent until a config answers it, so a till opened after the display still finds it. */
|
|
8
|
+
export const HELLO_RETRY_MS = 2000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The customer display's side: says `display.hello`, then shows what the till sends. As v2's display page
|
|
12
|
+
* (Pro packages/display/src/session.ts), nothing is applied before the `display.config` that answers this hello.
|
|
13
|
+
*/
|
|
14
|
+
export function useCustomerDisplay(transport: DisplayTransport | null): DisplayState {
|
|
15
|
+
const [state, setState] = useState(initialDisplayState);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!transport) return;
|
|
18
|
+
const hello = makeEnvelope('display.hello', { template: DISPLAY_TEMPLATE });
|
|
19
|
+
let configured = false;
|
|
20
|
+
const retry = setInterval(() => transport.send(hello), HELLO_RETRY_MS);
|
|
21
|
+
const unsubscribe = transport.onMessage((envelope) => {
|
|
22
|
+
if (!configured) {
|
|
23
|
+
if (envelope.action !== 'display.config' || envelope.id !== hello.id) return;
|
|
24
|
+
configured = true;
|
|
25
|
+
clearInterval(retry);
|
|
26
|
+
}
|
|
27
|
+
setState((previous) => displayReducer(previous, envelope));
|
|
28
|
+
});
|
|
29
|
+
transport.send(hello);
|
|
30
|
+
return () => {
|
|
31
|
+
clearInterval(retry);
|
|
32
|
+
unsubscribe();
|
|
33
|
+
};
|
|
34
|
+
}, [transport]);
|
|
35
|
+
return state;
|
|
36
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -79,6 +79,8 @@ export type { ThermalNode, ReceiptNode, SanitizeHtmlOptions, RenderSanitizeOptio
|
|
|
79
79
|
// Customer display
|
|
80
80
|
export { DISPLAY_PROTOCOL_VERSION, DISPLAY_ACTIONS, makeEnvelope, displayCart, decode as decodeDisplayMessage, encode as encodeDisplayMessage, messageBytes, MAX_MESSAGE_BYTES, displayReducer, initialDisplayState } from './customer-display';
|
|
81
81
|
export type { PaymentPhase, DisplayTemplate, DisplayCart, DisplayPayment, DisplayConfig, DisplayPayloads, DisplayAction, DisplayEnvelope, DecodeRefusal, DecodeResult, DisplayView, DisplayState } from './customer-display';
|
|
82
|
+
export { DISPLAY_CHANNEL, createBroadcastDisplayTransport, createDisplayLink, useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './customer-display';
|
|
83
|
+
export type { DisplayTransport, BroadcastChannelLike, DisplayLink, DisplayClock } from './customer-display';
|
|
82
84
|
|
|
83
85
|
// Product
|
|
84
86
|
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';
|
|
@@ -99,15 +101,17 @@ export type {
|
|
|
99
101
|
export {
|
|
100
102
|
PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
|
|
101
103
|
printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
|
|
104
|
+
escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES,
|
|
102
105
|
} from './print';
|
|
103
106
|
export type {
|
|
104
107
|
PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
|
|
105
108
|
PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
|
|
109
|
+
EscPosBuilder, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions,
|
|
106
110
|
} from './print';
|
|
107
111
|
|
|
108
112
|
// Sale
|
|
109
|
-
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 } from './sale';
|
|
110
|
-
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState } from './sale';
|
|
113
|
+
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';
|
|
114
|
+
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, CartQuantityLine } from './sale';
|
|
111
115
|
|
|
112
116
|
export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
113
117
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
@@ -144,6 +148,8 @@ export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlrea
|
|
|
144
148
|
export { roundedDue, tenderRounding } from './tender';
|
|
145
149
|
export type { TenderRounding } from './tender';
|
|
146
150
|
export { suggestFloat, type FloatSuggestion } from './register';
|
|
151
|
+
export { switchWarnings, handoverSlip } from './register';
|
|
152
|
+
export type { SwitchKind, SwitchWarning, SwitchWarningInput, SwitchWarnings, HandoverSlipInput, HandoverSlipData } from './register';
|
|
147
153
|
|
|
148
154
|
// Reports
|
|
149
155
|
export { salesFigures, marginOf, comparisonRange, daysOf, inRange, presetRange, DATE_PRESETS, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './reports';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Character tables for ESC/POS text. WCPOS v2 (monorepo main) leaves the code page to
|
|
3
|
+
* `@point-of-sale/receipt-printer-encoder`; here two fixed tables cover Latin receipts without a dependency.
|
|
4
|
+
* `high` holds the characters for bytes 0x80-0xFF; `id` is the `ESC t n` table number.
|
|
5
|
+
*/
|
|
6
|
+
export const ESCPOS_CODE_PAGES = {
|
|
7
|
+
cp437: {
|
|
8
|
+
id: 0,
|
|
9
|
+
high: 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀'
|
|
10
|
+
+ 'αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00A0',
|
|
11
|
+
},
|
|
12
|
+
// PC850 with the euro sign at 0xD5.
|
|
13
|
+
cp858: {
|
|
14
|
+
id: 19,
|
|
15
|
+
high: 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤'
|
|
16
|
+
+ 'ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´\u00AD±‗¾¶§÷¸°¨·¹³²■\u00A0',
|
|
17
|
+
},
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export type EscPosCodePageName = keyof typeof ESCPOS_CODE_PAGES;
|
|
21
|
+
export interface EscPosCodePage { id: number; high: string }
|
|
22
|
+
|
|
23
|
+
/** The named page; cp437 (ESC/POS table 0, the usual default) when the name is absent or unknown. */
|
|
24
|
+
export function resolveCodePage(name?: string): EscPosCodePage {
|
|
25
|
+
return ESCPOS_CODE_PAGES[name as EscPosCodePageName] ?? ESCPOS_CODE_PAGES.cp437;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const PRINTABLE_ASCII = /^[\x20-\x7E]$/;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Text the page can print, one character for one, so `length` is the columns it takes. v2's
|
|
32
|
+
* `normalizeThermalText` first (dashes and the minus sign to `-`, curly quotes to ASCII, no-break and thin
|
|
33
|
+
* spaces to a space); then a character the page has stays; `×` becomes `x`; an accented letter outside the
|
|
34
|
+
* page loses its accent (`ź` → `z`); anything else prints as `?`.
|
|
35
|
+
*/
|
|
36
|
+
export function foldText(text: string, page: EscPosCodePage): string {
|
|
37
|
+
const normalized = text
|
|
38
|
+
.replace(/[\u2010-\u2014\u2212]/g, '-')
|
|
39
|
+
.replace(/[\u2018\u2019]/g, "'")
|
|
40
|
+
.replace(/[\u201C\u201D]/g, '"')
|
|
41
|
+
.replace(/[\u00A0\u202F\u2009\u2007]/g, ' ');
|
|
42
|
+
return Array.from(normalized, (char) => {
|
|
43
|
+
if (char === '\n' || PRINTABLE_ASCII.test(char) || page.high.includes(char)) return char;
|
|
44
|
+
if (char === '\u00D7') return 'x';
|
|
45
|
+
const base = char.normalize('NFD').replace(/[\u0300-\u036F]/g, '');
|
|
46
|
+
return PRINTABLE_ASCII.test(base) ? base : '?';
|
|
47
|
+
}).join('');
|
|
48
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small ESC/POS command builder. The command bytes follow WCPOS v2 (monorepo main): `escpos-text.ts`
|
|
3
|
+
* opens every job with `ESC @` then `ESC M 0` (Font A, so the profile's column count holds whatever the
|
|
4
|
+
* printer's memory switch says; v2 gotcha N39), and `render-escpos.ts` `writeCut` cuts with `GS V 0x41|0x42 0`
|
|
5
|
+
* (feed to the cutter, then cut). Text goes through `foldText`, so no multibyte UTF-8 ever reaches the printer.
|
|
6
|
+
*/
|
|
7
|
+
import type { DrawerConnector } from '../../receipt-template/types';
|
|
8
|
+
import { foldText, resolveCodePage, type EscPosCodePage } from './code-page';
|
|
9
|
+
|
|
10
|
+
const ESC = 0x1b;
|
|
11
|
+
const GS = 0x1d;
|
|
12
|
+
|
|
13
|
+
export interface EscPosBuilder {
|
|
14
|
+
/** `ESC @` (reset), then `ESC M 0` (Font A). */
|
|
15
|
+
init(): EscPosBuilder;
|
|
16
|
+
/** `ESC t n`: select the builder's code page. */
|
|
17
|
+
codePage(): EscPosBuilder;
|
|
18
|
+
align(mode: 'left' | 'center' | 'right'): EscPosBuilder;
|
|
19
|
+
bold(on: boolean): EscPosBuilder;
|
|
20
|
+
/** `GS ! n`: character width and height multipliers, 1-8 each. */
|
|
21
|
+
size(width: number, height: number): EscPosBuilder;
|
|
22
|
+
/** Folded to the code page, one byte per character; `\n` is LF. */
|
|
23
|
+
text(value: string): EscPosBuilder;
|
|
24
|
+
/** `ESC d n`: print and feed n lines. */
|
|
25
|
+
feed(lines: number): EscPosBuilder;
|
|
26
|
+
cut(type?: 'full' | 'partial'): EscPosBuilder;
|
|
27
|
+
/** `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
|
+
pulse(connector?: DrawerConnector): EscPosBuilder;
|
|
29
|
+
bytes(): Uint8Array;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function escpos(page: EscPosCodePage = resolveCodePage()): EscPosBuilder {
|
|
33
|
+
const out: number[] = [];
|
|
34
|
+
const clamp = (n: number) => Math.min(8, Math.max(1, Math.round(n))) - 1;
|
|
35
|
+
const builder: EscPosBuilder = {
|
|
36
|
+
init: () => push(ESC, 0x40, ESC, 0x4d, 0),
|
|
37
|
+
codePage: () => push(ESC, 0x74, page.id),
|
|
38
|
+
align: (mode) => push(ESC, 0x61, mode === 'left' ? 0 : mode === 'center' ? 1 : 2),
|
|
39
|
+
bold: (on) => push(ESC, 0x45, on ? 1 : 0),
|
|
40
|
+
size: (width, height) => push(GS, 0x21, (clamp(width) << 4) | clamp(height)),
|
|
41
|
+
text: (value) => push(...Array.from(foldText(value, page), (char) =>
|
|
42
|
+
char.charCodeAt(0) < 0x80 ? char.charCodeAt(0) : 0x80 + page.high.indexOf(char))),
|
|
43
|
+
feed: (lines) => push(ESC, 0x64, Math.min(255, Math.max(0, lines))),
|
|
44
|
+
cut: (type = 'partial') => push(GS, 0x56, type === 'full' ? 0x41 : 0x42, 0),
|
|
45
|
+
pulse: (connector = 'pin2') => push(ESC, 0x70, connector === 'pin5' ? 1 : 0, 25, 250),
|
|
46
|
+
bytes: () => Uint8Array.from(out),
|
|
47
|
+
};
|
|
48
|
+
function push(...bytes: number[]): EscPosBuilder {
|
|
49
|
+
for (const byte of bytes) out.push(byte);
|
|
50
|
+
return builder;
|
|
51
|
+
}
|
|
52
|
+
return builder;
|
|
53
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ReceiptData` to ESC/POS bytes. The strings come from `receiptTemplateData`, so a thermal receipt says what
|
|
3
|
+
* the HTML receipt says, and the layout follows the 58/80 mm template (`receipt-template/default-templates.ts`)
|
|
4
|
+
* and WCPOS v2's thermal template (monorepo main `packages/printer/src/encoder/default-thermal-template.ts`):
|
|
5
|
+
* a name line, then `qty x price` with the amount right-aligned; feed 3, drawer, cut at the end. v2's rows
|
|
6
|
+
* truncate a long cell; here the left part wraps and the amount sits on its last line. Left out: the QR code,
|
|
7
|
+
* barcodes, logos and images (they need a raster path).
|
|
8
|
+
*/
|
|
9
|
+
import { formatMoney, moneyToMajor } from '@tallyui/core';
|
|
10
|
+
import type { ReceiptData } from '../../receipt/types';
|
|
11
|
+
import { receiptTemplateData, type ReceiptTemplateOptions } from '../../receipt-template/template-data';
|
|
12
|
+
import type { DrawerConnector } from '../../receipt-template/types';
|
|
13
|
+
import { foldText, resolveCodePage } from './code-page';
|
|
14
|
+
import { escpos } from './commands';
|
|
15
|
+
|
|
16
|
+
export interface EncodeEscPosOptions extends ReceiptTemplateOptions {
|
|
17
|
+
/** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. */
|
|
18
|
+
columns: number;
|
|
19
|
+
/** `cp437` (the default, also for an unknown name) or `cp858`. */
|
|
20
|
+
codePage?: string;
|
|
21
|
+
/** Default true: a partial cut after the feed. */
|
|
22
|
+
cut?: boolean;
|
|
23
|
+
/** Default false: kick the drawer before the cut. */
|
|
24
|
+
openDrawer?: boolean;
|
|
25
|
+
/** Default `pin2`. */
|
|
26
|
+
drawerConnector?: DrawerConnector;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Breaks at spaces; a word wider than `width` is split. Always at least one line. */
|
|
30
|
+
export function wrapText(text: string, width: number): string[] {
|
|
31
|
+
const lines: string[] = [];
|
|
32
|
+
let line = '';
|
|
33
|
+
for (let word of text.split(' ').filter(Boolean)) {
|
|
34
|
+
while (word.length > width) {
|
|
35
|
+
if (line) lines.push(line);
|
|
36
|
+
line = '';
|
|
37
|
+
lines.push(word.slice(0, width));
|
|
38
|
+
word = word.slice(width);
|
|
39
|
+
}
|
|
40
|
+
if (!line) line = word;
|
|
41
|
+
else if (line.length + 1 + word.length <= width) line += ` ${word}`;
|
|
42
|
+
else {
|
|
43
|
+
lines.push(line);
|
|
44
|
+
line = word;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (line || lines.length === 0) lines.push(line);
|
|
48
|
+
return lines;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function encodeEscPos(receipt: ReceiptData, options: EncodeEscPosOptions): Uint8Array {
|
|
52
|
+
const { columns, cut = true, openDrawer = false, drawerConnector = 'pin2' } = options;
|
|
53
|
+
const page = resolveCodePage(options.codePage);
|
|
54
|
+
const fold = (text: string) => foldText(text, page);
|
|
55
|
+
// v2 format-money.ts: a currency symbol the page cannot print becomes the ISO code.
|
|
56
|
+
const money = options.formatMoney ?? ((minor: number, currency: string) => {
|
|
57
|
+
const formatted = formatMoney({ amount: minor, currency }) ?? '';
|
|
58
|
+
if (!fold(formatted).includes('?')) return formatted;
|
|
59
|
+
return new Intl.NumberFormat(undefined, { style: 'currency', currency, currencyDisplay: 'code' })
|
|
60
|
+
.format(moneyToMajor({ amount: minor, currency }));
|
|
61
|
+
});
|
|
62
|
+
const data = receiptTemplateData(receipt, { ...options, formatMoney: money });
|
|
63
|
+
|
|
64
|
+
const out = escpos(page).init().codePage();
|
|
65
|
+
const print = (lines: string[]) => { for (const line of lines) out.text(`${line}\n`); };
|
|
66
|
+
const block = (text: string, indent = '') => fold(text).split('\n')
|
|
67
|
+
.flatMap((part) => wrapText(part, columns - indent.length).map((line) => indent + line));
|
|
68
|
+
const pair = (left: string, right: string, indent = '') => {
|
|
69
|
+
const amount = fold(right);
|
|
70
|
+
const space = columns - amount.length - 1;
|
|
71
|
+
if (space <= indent.length) {
|
|
72
|
+
print([...block(left, indent), amount.padStart(columns)]);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const lines = wrapText(fold(left), space - indent.length).map((line) => indent + line);
|
|
76
|
+
const last = lines.pop() ?? '';
|
|
77
|
+
print([...lines, last + ' '.repeat(columns - last.length - amount.length) + amount]);
|
|
78
|
+
};
|
|
79
|
+
const rule = (char: string) => print([char.repeat(columns)]);
|
|
80
|
+
|
|
81
|
+
out.align('center').bold(true);
|
|
82
|
+
print(block(data.store.name));
|
|
83
|
+
out.bold(false);
|
|
84
|
+
for (const { line } of data.store.addressLines) print(block(line));
|
|
85
|
+
out.align('left');
|
|
86
|
+
rule('-');
|
|
87
|
+
out.align('center').bold(true);
|
|
88
|
+
print(block(data.document.title));
|
|
89
|
+
out.bold(false);
|
|
90
|
+
if (data.document.isReprint) print(block(`Copy ${data.document.reprintCount}`));
|
|
91
|
+
out.align('left');
|
|
92
|
+
pair('Order', data.order.number);
|
|
93
|
+
pair('Date', data.order.date);
|
|
94
|
+
for (const [label, value] of [['Cashier', data.cashier], ['Register', data.register], ['Customer', data.customer]]) {
|
|
95
|
+
if (value) pair(label, value);
|
|
96
|
+
}
|
|
97
|
+
rule('-');
|
|
98
|
+
for (const line of data.lines) {
|
|
99
|
+
print(block(line.name));
|
|
100
|
+
for (const option of line.options) print(block(option.text, ' '));
|
|
101
|
+
pair(line.detail, line.amount, ' ');
|
|
102
|
+
for (const discount of line.discounts) pair(discount.label, discount.amount, ' ');
|
|
103
|
+
}
|
|
104
|
+
rule('-');
|
|
105
|
+
pair('Subtotal', data.subtotal);
|
|
106
|
+
if (data.lineDiscount) pair('Line discounts', data.lineDiscount);
|
|
107
|
+
if (data.orderDiscount) pair('Order discount', data.orderDiscount);
|
|
108
|
+
for (const charge of [...data.charges, ...data.taxes]) pair(charge.label, charge.amount);
|
|
109
|
+
out.bold(true);
|
|
110
|
+
pair('Total', data.total);
|
|
111
|
+
out.bold(false);
|
|
112
|
+
rule('=');
|
|
113
|
+
for (const payment of data.payments) {
|
|
114
|
+
pair(payment.reference ? `${payment.method} ${payment.reference}` : payment.method, payment.amount);
|
|
115
|
+
}
|
|
116
|
+
if (data.change) pair('Change', data.change);
|
|
117
|
+
if (data.note) {
|
|
118
|
+
out.feed(1);
|
|
119
|
+
print(block(data.note));
|
|
120
|
+
}
|
|
121
|
+
out.feed(1).align('center');
|
|
122
|
+
print(['Thank you']);
|
|
123
|
+
out.align('left').feed(3);
|
|
124
|
+
if (openDrawer) out.pulse(drawerConnector);
|
|
125
|
+
if (cut) out.cut();
|
|
126
|
+
return out.bytes();
|
|
127
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { ESCPOS_CODE_PAGES } from './code-page';
|
|
2
|
+
export { escpos } from './commands';
|
|
3
|
+
export type { EscPosBuilder } from './commands';
|
|
4
|
+
export { encodeEscPos } from './encode';
|
|
5
|
+
export type { EncodeEscPosOptions } from './encode';
|
|
6
|
+
export { createEscPosTransport } from './transport';
|
|
7
|
+
export type { EscPosSink, EscPosTransportOptions } from './transport';
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `PrintTransport` that writes ESC/POS bytes to a sink the app supplies (WebUSB, WebSerial, a TCP socket,
|
|
3
|
+
* Bluetooth). It holds no device code; ADR-084 decision 2 keeps vendor SDKs out of the MIT packages. Run it
|
|
4
|
+
* through `createPrintQueue`, like the system transport, so one printer prints one job at a time.
|
|
5
|
+
*/
|
|
6
|
+
import type { ReceiptTemplateOptions } from '../../receipt-template/template-data';
|
|
7
|
+
import type { PrinterProfile } from '../printer-profiles';
|
|
8
|
+
import { PrintError, type PrintJob, type PrintTransport } from '../types';
|
|
9
|
+
import { encodeEscPos } from './encode';
|
|
10
|
+
|
|
11
|
+
export interface EscPosSink {
|
|
12
|
+
write(bytes: Uint8Array): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EscPosTransportOptions {
|
|
16
|
+
sink: EscPosSink;
|
|
17
|
+
profile: PrinterProfile;
|
|
18
|
+
format?: Pick<ReceiptTemplateOptions, 'formatMoney' | 'formatDate' | 'paymentLabel'>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createEscPosTransport({ sink, profile, format }: EscPosTransportOptions): PrintTransport {
|
|
22
|
+
return {
|
|
23
|
+
name: 'escpos',
|
|
24
|
+
async print(job: PrintJob) {
|
|
25
|
+
if (profile.language !== undefined && profile.language !== 'esc-pos') {
|
|
26
|
+
throw new PrintError('unsupported', `Printer ${profile.name} speaks ${profile.language}, not ESC/POS`);
|
|
27
|
+
}
|
|
28
|
+
// The profile's documented defaults: 42 columns, cut on, drawer off, pin 2.
|
|
29
|
+
const bytes = job.bytes ?? (job.receipt && encodeEscPos(job.receipt, {
|
|
30
|
+
...format,
|
|
31
|
+
columns: profile.columns ?? 42,
|
|
32
|
+
codePage: profile.codePage,
|
|
33
|
+
cut: profile.autoCut ?? true,
|
|
34
|
+
openDrawer: profile.autoOpenDrawer ?? false,
|
|
35
|
+
drawerConnector: profile.drawerConnector ?? 'pin2',
|
|
36
|
+
}));
|
|
37
|
+
if (!bytes) throw new PrintError('unsupported', `ESC/POS prints bytes or a receipt; job ${job.id} has neither`);
|
|
38
|
+
try {
|
|
39
|
+
await sink.write(bytes);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
package/src/print/index.ts
CHANGED
|
@@ -8,3 +8,5 @@ export {
|
|
|
8
8
|
export type { PrinterProfile, PrinterProfileCollection } from './printer-profiles';
|
|
9
9
|
export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
|
|
10
10
|
export type { SystemPrintTransportOptions } from './system-transport';
|
|
11
|
+
export { escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES } from './escpos';
|
|
12
|
+
export type { EscPosBuilder, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions } from './escpos';
|
package/src/print/types.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* `PrinterTransport` has `printRaw(bytes)` and `printHtml(html)`; here one `print(job)` takes a job that
|
|
4
4
|
* carries HTML, bytes or both, and each transport prints what it can.
|
|
5
5
|
*/
|
|
6
|
+
import type { ReceiptData } from '../receipt/types';
|
|
7
|
+
|
|
6
8
|
export type PrintJobKind = 'receipt' | 'report' | 'test';
|
|
7
9
|
|
|
8
10
|
export interface PrintJob {
|
|
@@ -12,6 +14,8 @@ export interface PrintJob {
|
|
|
12
14
|
html?: string;
|
|
13
15
|
/** Pre-encoded printer bytes (ESC/POS and the like), for a raw transport. */
|
|
14
16
|
bytes?: Uint8Array;
|
|
17
|
+
/** The receipt itself, for a transport that lays it out (`createEscPosTransport`). */
|
|
18
|
+
receipt?: ReceiptData;
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
/** `unsupported`: this transport cannot print the job; `unavailable`: the platform has no way to print; `failed`: the print went wrong. */
|