@tallyui/pos 3.12.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 +1844 -359
- package/dist/index.js +4620 -2211
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +108 -0
- package/src/app-settings/index.ts +8 -0
- package/src/app-settings/use-app-settings.ts +23 -0
- package/src/cashier/can.ts +12 -0
- package/src/cashier/index.ts +2 -0
- package/src/cashier/use-cashier.ts +81 -0
- package/src/csv/csv.ts +33 -0
- package/src/csv/index.ts +2 -0
- package/src/customer-display/display-link.ts +72 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +13 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/customer-display/transport.ts +54 -0
- package/src/customer-display/use-customer-display.ts +36 -0
- package/src/index.ts +73 -10
- package/src/order/order-builder.ts +11 -1
- package/src/order/order-drafts.ts +16 -0
- package/src/order/types.ts +6 -3
- package/src/outbox/index.ts +5 -1
- package/src/outbox/outbox-health.ts +40 -0
- package/src/outbox/register-outbox.ts +59 -6
- package/src/outbox/safe-error.ts +11 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-outbox-health.ts +22 -0
- package/src/outbox/use-register-outbox.ts +6 -0
- package/src/payment-driver/index.ts +8 -0
- package/src/payment-driver/registry.ts +39 -0
- package/src/payment-driver/simulated-driver.ts +104 -0
- package/src/payment-driver/types.ts +73 -0
- package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
- package/src/pos-order/command.ts +36 -16
- package/src/pos-order/finalize.ts +7 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +3 -2
- package/src/pos-order/schema.ts +5 -4
- package/src/pos-order/types.ts +3 -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 +12 -0
- package/src/print/print-queue.ts +67 -0
- package/src/print/printer-profiles.ts +71 -0
- package/src/print/system-transport.ts +101 -0
- package/src/print/types.ts +44 -0
- package/src/receipt/reprint.ts +2 -1
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/default-templates.ts +78 -0
- package/src/receipt-template/index.ts +15 -0
- package/src/receipt-template/parse-xml.ts +175 -0
- package/src/receipt-template/render-html.ts +152 -0
- package/src/receipt-template/render-receipt.ts +19 -0
- package/src/receipt-template/render-template.ts +35 -0
- package/src/receipt-template/sanitize-html.ts +146 -0
- package/src/receipt-template/template-data.ts +97 -0
- package/src/receipt-template/types.ts +49 -0
- package/src/refund/index.ts +2 -0
- package/src/refund/refundable-lines.ts +91 -0
- package/src/register/export-csv.ts +24 -35
- package/src/register/float-suggestion.ts +22 -0
- package/src/register/handover.ts +103 -0
- package/src/register/index.ts +10 -3
- package/src/register/register-adoption.ts +71 -2
- package/src/register/register-commands.ts +7 -4
- package/src/register/register-count.helpers.ts +4 -0
- package/src/register/session-store.ts +4 -1
- package/src/register/use-register-session.ts +112 -28
- package/src/reports/adapters.ts +67 -0
- package/src/reports/index.ts +5 -0
- package/src/reports/presets.ts +27 -0
- package/src/reports/sales-figures.ts +187 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/in-cart.ts +18 -0
- package/src/sale/index.ts +5 -1
- package/src/sale/open-sales.ts +40 -0
- package/src/sale/use-sale.ts +72 -8
- package/src/scanner/index.ts +6 -0
- package/src/scanner/scan-session.ts +84 -0
- package/src/scanner/use-barcode-scanner.ts +61 -0
- package/src/scanner/wedge-detector.ts +137 -0
- package/src/tender/cash-rounding.ts +74 -0
- package/src/tender/index.ts +4 -0
- package/src/tender/payment-legs.ts +48 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { PrintError, toPrintError } from './types';
|
|
2
|
+
export type { PrintJob, PrintJobKind, PrintErrorCode, PrintTransport } from './types';
|
|
3
|
+
export { createPrintQueue, SYSTEM_PRINTER_ID } from './print-queue';
|
|
4
|
+
export type { PrintQueue, PrintQueueOptions, PrintQueueState } from './print-queue';
|
|
5
|
+
export {
|
|
6
|
+
PRINTER_PROFILES_COLLECTION, printerProfileSchema, printerProfileCollection, addPrinterProfileCollection,
|
|
7
|
+
} from './printer-profiles';
|
|
8
|
+
export type { PrinterProfile, PrinterProfileCollection } from './printer-profiles';
|
|
9
|
+
export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
|
|
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';
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One serial queue per printer id. Ported from WCPOS v2 `packages/printer/src/printer-service.ts` (monorepo
|
|
3
|
+
* main), which keeps a `PQueue({ concurrency: 1 })` per profile because one shared queue let a stalled printer
|
|
4
|
+
* stall the till (its gotcha N44). Here a promise chain per printer id does the same without p-queue.
|
|
5
|
+
*/
|
|
6
|
+
import { toPrintError, type PrintJob, type PrintTransport } from './types';
|
|
7
|
+
|
|
8
|
+
/** v2's queue id for the OS print dialog, which is one shared resource on the device. */
|
|
9
|
+
export const SYSTEM_PRINTER_ID = 'system';
|
|
10
|
+
|
|
11
|
+
export interface PrintQueueState {
|
|
12
|
+
printerId: string;
|
|
13
|
+
/** The id of the job printing now, or null. */
|
|
14
|
+
running: string | null;
|
|
15
|
+
/** Ids of the jobs waiting, in the order they will print. */
|
|
16
|
+
queued: string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PrintQueueOptions {
|
|
20
|
+
transportFor: (printerId: string) => PrintTransport | Promise<PrintTransport>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface PrintQueue {
|
|
24
|
+
/** Resolves when this job has printed; rejects with a `PrintError`. A failure never holds up the next job. */
|
|
25
|
+
print(printerId: string, job: PrintJob): Promise<void>;
|
|
26
|
+
state(printerId: string): PrintQueueState;
|
|
27
|
+
subscribe(listener: (state: PrintQueueState) => void): () => void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createPrintQueue({ transportFor }: PrintQueueOptions): PrintQueue {
|
|
31
|
+
const tails = new Map<string, Promise<void>>();
|
|
32
|
+
const states = new Map<string, PrintQueueState>();
|
|
33
|
+
const listeners = new Set<(state: PrintQueueState) => void>();
|
|
34
|
+
|
|
35
|
+
const state = (printerId: string): PrintQueueState => states.get(printerId) ?? { printerId, running: null, queued: [] };
|
|
36
|
+
const update = (printerId: string, change: (current: PrintQueueState) => PrintQueueState) => {
|
|
37
|
+
const next = change(state(printerId));
|
|
38
|
+
states.set(printerId, next);
|
|
39
|
+
for (const listener of listeners) listener(next);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const run = async (printerId: string, job: PrintJob) => {
|
|
43
|
+
// Jobs start in enqueue order, so the starting job is the head of `queued`.
|
|
44
|
+
update(printerId, ({ queued }) => ({ printerId, running: job.id, queued: queued.slice(1) }));
|
|
45
|
+
try {
|
|
46
|
+
await (await transportFor(printerId)).print(job);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw toPrintError(error);
|
|
49
|
+
} finally {
|
|
50
|
+
update(printerId, (current) => ({ ...current, running: null }));
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
print(printerId, job) {
|
|
56
|
+
update(printerId, (current) => ({ ...current, queued: [...current.queued, job.id] }));
|
|
57
|
+
const result = (tails.get(printerId) ?? Promise.resolve()).then(() => run(printerId, job));
|
|
58
|
+
tails.set(printerId, result.catch(() => undefined));
|
|
59
|
+
return result;
|
|
60
|
+
},
|
|
61
|
+
state: (printerId) => ({ ...state(printerId) }),
|
|
62
|
+
subscribe(listener) {
|
|
63
|
+
listeners.add(listener);
|
|
64
|
+
return () => { listeners.delete(listener); };
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Printers set up on this device. Local only, never replicated; the app adds the collection as
|
|
3
|
+
* `printer_profiles`. Ported from WCPOS v2 `packages/database/src/collections/schemas/printer-profiles.ts`
|
|
4
|
+
* (monorepo main, version 0, device-local). Left out: v2's cloud fields (`cloudPrinterId`, `cloudProvider`,
|
|
5
|
+
* `connectionType: 'cloud'`; vendor services stay out of the MIT packages, ADR-084 decision 2), its vendor-SDK and
|
|
6
|
+
* encoder-library hints (`nativeInterfaceType`, `printerModel`), `emitEscPrintMode` and `fullReceiptRaster`.
|
|
7
|
+
* v2's schema defaults are kept as comments, not schema `default`s; a reader treats a missing field as its default.
|
|
8
|
+
*/
|
|
9
|
+
import type { RxCollection, RxDatabase, RxJsonSchema } from 'rxdb';
|
|
10
|
+
|
|
11
|
+
export const PRINTER_PROFILES_COLLECTION = 'printer_profiles';
|
|
12
|
+
|
|
13
|
+
export interface PrinterProfile {
|
|
14
|
+
id: string;
|
|
15
|
+
/** User-assigned, e.g. "Front counter". */
|
|
16
|
+
name: string;
|
|
17
|
+
connectionType: 'system' | 'network' | 'bluetooth' | 'usb';
|
|
18
|
+
/** Default `generic`. */
|
|
19
|
+
vendor?: 'epson' | 'star' | 'generic';
|
|
20
|
+
/** IP address, Bluetooth address or USB path. */
|
|
21
|
+
address?: string;
|
|
22
|
+
/** Default 9100. */
|
|
23
|
+
port?: number;
|
|
24
|
+
/** Default `esc-pos`. */
|
|
25
|
+
language?: 'esc-pos' | 'star-prnt' | 'star-line';
|
|
26
|
+
/** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. Default 42. */
|
|
27
|
+
columns?: number;
|
|
28
|
+
/** The encoder's code page name, e.g. `cp437`; absent lets the encoder choose. */
|
|
29
|
+
codePage?: string;
|
|
30
|
+
/** Default true. */
|
|
31
|
+
autoCut?: boolean;
|
|
32
|
+
/** Default false. */
|
|
33
|
+
autoOpenDrawer?: boolean;
|
|
34
|
+
/** Default `pin2` (drawer 1). */
|
|
35
|
+
drawerConnector?: 'pin2' | 'pin5';
|
|
36
|
+
isDefault?: boolean;
|
|
37
|
+
/** A platform printer (the print dialog) that cannot be deleted. */
|
|
38
|
+
isBuiltIn?: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const printerProfileSchema: RxJsonSchema<PrinterProfile> = {
|
|
42
|
+
title: 'Printer profiles', version: 0, primaryKey: 'id', type: 'object', additionalProperties: false,
|
|
43
|
+
properties: {
|
|
44
|
+
id: { type: 'string', maxLength: 36 },
|
|
45
|
+
name: { type: 'string' },
|
|
46
|
+
connectionType: { type: 'string', enum: ['system', 'network', 'bluetooth', 'usb'] },
|
|
47
|
+
vendor: { type: 'string', enum: ['epson', 'star', 'generic'] },
|
|
48
|
+
address: { type: 'string' },
|
|
49
|
+
port: { type: 'integer' },
|
|
50
|
+
language: { type: 'string', enum: ['esc-pos', 'star-prnt', 'star-line'] },
|
|
51
|
+
columns: { type: 'integer' },
|
|
52
|
+
codePage: { type: 'string' },
|
|
53
|
+
autoCut: { type: 'boolean' },
|
|
54
|
+
autoOpenDrawer: { type: 'boolean' },
|
|
55
|
+
drawerConnector: { type: 'string', enum: ['pin2', 'pin5'] },
|
|
56
|
+
isDefault: { type: 'boolean' },
|
|
57
|
+
isBuiltIn: { type: 'boolean' },
|
|
58
|
+
},
|
|
59
|
+
required: ['id', 'name', 'connectionType'],
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export function printerProfileCollection(): { readonly schema: RxJsonSchema<PrinterProfile> } {
|
|
63
|
+
return { schema: printerProfileSchema } as const;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type PrinterProfileCollection = RxCollection<PrinterProfile>;
|
|
67
|
+
|
|
68
|
+
export async function addPrinterProfileCollection(db: RxDatabase): Promise<PrinterProfileCollection> {
|
|
69
|
+
const added = await db.addCollections({ [PRINTER_PROFILES_COLLECTION]: printerProfileCollection() });
|
|
70
|
+
return added[PRINTER_PROFILES_COLLECTION] as PrinterProfileCollection;
|
|
71
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prints rendered HTML through the platform print dialog. Ported from WCPOS v2 (monorepo main)
|
|
3
|
+
* `packages/printer/src/transport/system-print-adapter.web.ts` (hidden iframe, `print()`, `afterprint`) and
|
|
4
|
+
* `system-print-adapter.ts` (native, `expo-print`). On native the app injects `printHtml` (for example
|
|
5
|
+
* `(html) => Print.printAsync({ html })`), so this package takes no native dependency.
|
|
6
|
+
*/
|
|
7
|
+
import { PrintError, type PrintJob, type PrintTransport } from './types';
|
|
8
|
+
|
|
9
|
+
/** v2's waits: let the frame render, give images 5 s, and settle after 60 s if `afterprint` never fires. */
|
|
10
|
+
export const SYSTEM_PRINT_TIMING = { renderDelayMs: 500, imageTimeoutMs: 5_000, afterPrintTimeoutMs: 60_000, removeDelayMs: 1_000 };
|
|
11
|
+
type SystemPrintTiming = typeof SYSTEM_PRINT_TIMING;
|
|
12
|
+
|
|
13
|
+
const FRAME_ID = 'tallyui-print-frame';
|
|
14
|
+
|
|
15
|
+
export interface SystemPrintTransportOptions {
|
|
16
|
+
/** Native: prints HTML through the OS dialog. When given, the iframe path is not used. */
|
|
17
|
+
printHtml?: (html: string) => Promise<void>;
|
|
18
|
+
/** Web: the document to print from; defaults to `globalThis.document`. */
|
|
19
|
+
document?: Document;
|
|
20
|
+
timing?: Partial<SystemPrintTiming>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function imagesSettled(doc: Document, timeoutMs: number): Promise<void> {
|
|
24
|
+
const pending = Array.from(doc.images).filter((image) => !image.complete);
|
|
25
|
+
if (pending.length === 0) return Promise.resolve();
|
|
26
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
27
|
+
return Promise.race([
|
|
28
|
+
Promise.all(pending.map((image) => new Promise<void>((resolve) => {
|
|
29
|
+
image.addEventListener('load', () => resolve(), { once: true });
|
|
30
|
+
image.addEventListener('error', () => resolve(), { once: true });
|
|
31
|
+
}))).then(() => undefined),
|
|
32
|
+
new Promise<void>((resolve) => { timer = setTimeout(resolve, timeoutMs); }),
|
|
33
|
+
]).finally(() => clearTimeout(timer));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function printInFrame(doc: Document, html: string, timing: SystemPrintTiming): Promise<void> {
|
|
37
|
+
return new Promise<void>((resolve, reject) => {
|
|
38
|
+
doc.getElementById(FRAME_ID)?.remove();
|
|
39
|
+
const iframe = doc.createElement('iframe');
|
|
40
|
+
iframe.id = FRAME_ID;
|
|
41
|
+
Object.assign(iframe.style, { position: 'absolute', top: '-10000px', left: '-10000px', width: '0', height: '0' });
|
|
42
|
+
doc.body.appendChild(iframe);
|
|
43
|
+
const frameDoc = iframe.contentDocument;
|
|
44
|
+
const win = iframe.contentWindow;
|
|
45
|
+
if (!frameDoc || !win) {
|
|
46
|
+
iframe.remove();
|
|
47
|
+
reject(new PrintError('unavailable', 'The print frame has no document'));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
frameDoc.open();
|
|
51
|
+
frameDoc.write(html);
|
|
52
|
+
frameDoc.close();
|
|
53
|
+
|
|
54
|
+
setTimeout(() => {
|
|
55
|
+
void imagesSettled(frameDoc, timing.imageTimeoutMs).then(() => {
|
|
56
|
+
let settled = false;
|
|
57
|
+
const settle = (error?: unknown) => {
|
|
58
|
+
if (settled) return;
|
|
59
|
+
settled = true;
|
|
60
|
+
clearTimeout(fallback);
|
|
61
|
+
win.removeEventListener('afterprint', onAfterPrint);
|
|
62
|
+
// Removed later so the browser can finish spooling; the captured ref never removes a newer job's frame.
|
|
63
|
+
setTimeout(() => iframe.remove(), timing.removeDelayMs);
|
|
64
|
+
if (error === undefined) resolve();
|
|
65
|
+
else reject(new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error }));
|
|
66
|
+
};
|
|
67
|
+
const onAfterPrint = () => settle();
|
|
68
|
+
const fallback = setTimeout(onAfterPrint, timing.afterPrintTimeoutMs);
|
|
69
|
+
win.addEventListener('afterprint', onAfterPrint, { once: true });
|
|
70
|
+
try {
|
|
71
|
+
win.focus();
|
|
72
|
+
win.print();
|
|
73
|
+
} catch (error) {
|
|
74
|
+
settle(error);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}, timing.renderDelayMs);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createSystemPrintTransport(options: SystemPrintTransportOptions = {}): PrintTransport {
|
|
82
|
+
const timing = { ...SYSTEM_PRINT_TIMING, ...options.timing };
|
|
83
|
+
const { printHtml } = options;
|
|
84
|
+
return {
|
|
85
|
+
name: printHtml ? 'system-print-native' : 'system-print-web',
|
|
86
|
+
async print(job: PrintJob) {
|
|
87
|
+
if (job.html === undefined) throw new PrintError('unsupported', `The system dialog prints HTML; job ${job.id} has none`);
|
|
88
|
+
if (printHtml) {
|
|
89
|
+
try {
|
|
90
|
+
await printHtml(job.html);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
throw new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const doc = options.document ?? globalThis.document;
|
|
97
|
+
if (!doc?.body) throw new PrintError('unavailable', 'No document to print from');
|
|
98
|
+
await printInFrame(doc, job.html, timing);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The printing seam. Ported from WCPOS v2 `packages/printer/src/types.ts` (monorepo main): v2's
|
|
3
|
+
* `PrinterTransport` has `printRaw(bytes)` and `printHtml(html)`; here one `print(job)` takes a job that
|
|
4
|
+
* carries HTML, bytes or both, and each transport prints what it can.
|
|
5
|
+
*/
|
|
6
|
+
import type { ReceiptData } from '../receipt/types';
|
|
7
|
+
|
|
8
|
+
export type PrintJobKind = 'receipt' | 'report' | 'test';
|
|
9
|
+
|
|
10
|
+
export interface PrintJob {
|
|
11
|
+
id: string;
|
|
12
|
+
kind: PrintJobKind;
|
|
13
|
+
/** Rendered HTML, for the system dialog (see `renderReceiptHtml`). */
|
|
14
|
+
html?: string;
|
|
15
|
+
/** Pre-encoded printer bytes (ESC/POS and the like), for a raw transport. */
|
|
16
|
+
bytes?: Uint8Array;
|
|
17
|
+
/** The receipt itself, for a transport that lays it out (`createEscPosTransport`). */
|
|
18
|
+
receipt?: ReceiptData;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `unsupported`: this transport cannot print the job; `unavailable`: the platform has no way to print; `failed`: the print went wrong. */
|
|
22
|
+
export type PrintErrorCode = 'unsupported' | 'unavailable' | 'failed';
|
|
23
|
+
|
|
24
|
+
export class PrintError extends Error {
|
|
25
|
+
readonly code: PrintErrorCode;
|
|
26
|
+
constructor(code: PrintErrorCode, message: string, options?: { cause?: unknown }) {
|
|
27
|
+
super(message, options);
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.name = 'PrintError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function toPrintError(error: unknown): PrintError {
|
|
34
|
+
if (error instanceof PrintError) return error;
|
|
35
|
+
return new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface PrintTransport {
|
|
39
|
+
/** For logs, e.g. `system-print-web`. */
|
|
40
|
+
readonly name: string;
|
|
41
|
+
/** Resolves once the job is handed to the printer or dialog; rejects with a `PrintError`. */
|
|
42
|
+
print(job: PrintJob): Promise<void>;
|
|
43
|
+
disconnect?(): Promise<void>;
|
|
44
|
+
}
|
package/src/receipt/reprint.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { minorUnitDigits, woocommerceTax, type StoreOrder } from '@tallyui/core';
|
|
2
|
+
import { noteDelivery } from '../pos-order/note-delivery';
|
|
2
3
|
import type { PosOrder } from '../pos-order/types';
|
|
3
4
|
import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
|
|
4
5
|
import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
|
|
@@ -99,7 +100,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
|
|
|
99
100
|
},
|
|
100
101
|
payments: order.payments.map((p) => ({ method: p.method, amountMinor: p.tenderedMinor ?? p.amountMinor, reference: p.reference })),
|
|
101
102
|
changeDueMinor: sum(order.payments.map((p) => p.changeMinor ?? 0)),
|
|
102
|
-
footer: { note: order.note || undefined, barcode: order.id },
|
|
103
|
+
footer: { note: order.note || undefined, ...(noteDelivery(order) === 'not_sent' ? { noteNotSent: true as const } : {}), barcode: order.id },
|
|
103
104
|
currency: order.currency,
|
|
104
105
|
};
|
|
105
106
|
}
|
package/src/receipt/types.ts
CHANGED
|
@@ -58,6 +58,8 @@ export interface ReceiptData {
|
|
|
58
58
|
changeDueMinor: number;
|
|
59
59
|
footer: {
|
|
60
60
|
note?: string;
|
|
61
|
+
/** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
|
|
62
|
+
noteNotSent?: true;
|
|
61
63
|
barcode?: string;
|
|
62
64
|
};
|
|
63
65
|
currency: string;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export type ReceiptPaper = '58mm' | '80mm';
|
|
2
|
+
/** Characters per line (v2 encode-receipt.ts:18). */
|
|
3
|
+
export const PAPER_COLUMNS: Record<ReceiptPaper, number> = { '58mm': 32, '80mm': 48 };
|
|
4
|
+
export const DEFAULT_RECEIPT_TEMPLATES: Record<ReceiptPaper, string> = {
|
|
5
|
+
'58mm': receiptTemplate(32, 10, 12),
|
|
6
|
+
'80mm': receiptTemplate(48, 12, 14),
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
function receiptTemplate(columns: number, labelWidth: number, amountWidth: number): string {
|
|
10
|
+
return `<receipt paper-width="${columns}">
|
|
11
|
+
<align mode="center">
|
|
12
|
+
<bold><text>{{store.name}}</text></bold>
|
|
13
|
+
{{#store.addressLines}}
|
|
14
|
+
<text>{{line}}</text>
|
|
15
|
+
{{/store.addressLines}}
|
|
16
|
+
</align>
|
|
17
|
+
<line />
|
|
18
|
+
<align mode="center"><bold><text>{{document.title}}</text></bold></align>
|
|
19
|
+
{{#document.isReprint}}
|
|
20
|
+
<align mode="center"><text>Copy {{document.reprintCount}}</text></align>
|
|
21
|
+
{{/document.isReprint}}
|
|
22
|
+
<row><col width="${labelWidth}">Order</col><col width="*" align="right">{{order.number}}</col></row>
|
|
23
|
+
<row><col width="${labelWidth}">Date</col><col width="*" align="right">{{order.date}}</col></row>
|
|
24
|
+
{{#cashier}}
|
|
25
|
+
<row><col width="${labelWidth}">Cashier</col><col width="*" align="right">{{cashier}}</col></row>
|
|
26
|
+
{{/cashier}}
|
|
27
|
+
{{#register}}
|
|
28
|
+
<row><col width="${labelWidth}">Register</col><col width="*" align="right">{{register}}</col></row>
|
|
29
|
+
{{/register}}
|
|
30
|
+
{{#customer}}
|
|
31
|
+
<row><col width="${labelWidth}">Customer</col><col width="*" align="right">{{customer}}</col></row>
|
|
32
|
+
{{/customer}}
|
|
33
|
+
<line style="dashed" />
|
|
34
|
+
{{#lines}}
|
|
35
|
+
<text>{{name}}</text>
|
|
36
|
+
{{#options}}
|
|
37
|
+
<text> {{text}}</text>
|
|
38
|
+
{{/options}}
|
|
39
|
+
<row><col width="*"> {{detail}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
|
|
40
|
+
{{#discounts}}
|
|
41
|
+
<row><col width="*"> {{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
|
|
42
|
+
{{/discounts}}
|
|
43
|
+
{{/lines}}
|
|
44
|
+
<line style="dashed" />
|
|
45
|
+
<row><col width="*">Subtotal</col><col width="${amountWidth}" align="right">{{subtotal}}</col></row>
|
|
46
|
+
{{#lineDiscount}}
|
|
47
|
+
<row><col width="*">Line discounts</col><col width="${amountWidth}" align="right">{{lineDiscount}}</col></row>
|
|
48
|
+
{{/lineDiscount}}
|
|
49
|
+
{{#orderDiscount}}
|
|
50
|
+
<row><col width="*">Order discount</col><col width="${amountWidth}" align="right">{{orderDiscount}}</col></row>
|
|
51
|
+
{{/orderDiscount}}
|
|
52
|
+
{{#charges}}
|
|
53
|
+
<row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
|
|
54
|
+
{{/charges}}
|
|
55
|
+
{{#taxes}}
|
|
56
|
+
<row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
|
|
57
|
+
{{/taxes}}
|
|
58
|
+
<bold><row><col width="*">Total</col><col width="${amountWidth}" align="right">{{total}}</col></row></bold>
|
|
59
|
+
<line />
|
|
60
|
+
{{#payments}}
|
|
61
|
+
<row><col width="*">{{method}}{{#reference}} {{reference}}{{/reference}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
|
|
62
|
+
{{/payments}}
|
|
63
|
+
{{#change}}
|
|
64
|
+
<row><col width="*">Change</col><col width="${amountWidth}" align="right">{{change}}</col></row>
|
|
65
|
+
{{/change}}
|
|
66
|
+
{{#note}}
|
|
67
|
+
<feed lines="1" />
|
|
68
|
+
<text>{{note}}</text>
|
|
69
|
+
{{/note}}
|
|
70
|
+
<feed lines="1" />
|
|
71
|
+
<align mode="center"><text>Thank you</text></align>
|
|
72
|
+
{{#qrPayload}}
|
|
73
|
+
<align mode="center"><qrcode size="4">{{qrPayload}}</qrcode></align>
|
|
74
|
+
{{/qrPayload}}
|
|
75
|
+
<feed lines="3" />
|
|
76
|
+
<cut />
|
|
77
|
+
</receipt>`;
|
|
78
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { parseXml } from './parse-xml';
|
|
2
|
+
export { renderHtml } from './render-html';
|
|
3
|
+
export { sanitizeHtml } from './sanitize-html';
|
|
4
|
+
export { renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview } from './render-template';
|
|
5
|
+
export { receiptTemplateData } from './template-data';
|
|
6
|
+
export { DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS } from './default-templates';
|
|
7
|
+
export { renderReceiptHtml } from './render-receipt';
|
|
8
|
+
export type { ThermalNode, ReceiptNode } from './types';
|
|
9
|
+
export type { SanitizeHtmlOptions } from './sanitize-html';
|
|
10
|
+
export type { RenderSanitizeOptions } from './render-template';
|
|
11
|
+
export type {
|
|
12
|
+
ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions,
|
|
13
|
+
} from './template-data';
|
|
14
|
+
export type { ReceiptPaper } from './default-templates';
|
|
15
|
+
export type { RenderReceiptOptions } from './render-receipt';
|