| 1 |
import { waitImages } from "@point_of_sale/utils"; |
| 2 |
|
| 3 |
import { Reactive } from "@web/core/utils/reactive"; |
| 4 |
import { logPosMessage } from "../utils/pretty_console_log"; |
| 5 |
|
| 6 |
export const printerService = { |
| 7 |
dependencies: ["renderer"], |
| 8 |
start(env, { renderer }) { |
| 9 |
return new PrinterService(env, { renderer }); |
| 10 |
}, |
| 11 |
}; |
| 12 |
export class PrinterService extends Reactive { |
| 13 |
constructor(...args) { |
| 14 |
super(...args); |
| 15 |
this.setup(...args); |
| 16 |
} |
| 17 |
setup(env, { renderer }) { |
| 18 |
this.renderer = renderer; |
| 19 |
this.device = null; |
| 20 |
this.state = { isPrinting: false }; |
| 21 |
} |
| 22 |
setPrinter(newDevice) { |
| 23 |
this.device = newDevice; |
| 24 |
} |
| 25 |
printWeb(el) { |
| 26 |
this.renderer.whenMounted({ |
| 27 |
el, |
| 28 |
callback: async (el) => { |
| 29 |
await waitImages(el); |
| 30 |
window.print(el); |
| 31 |
}, |
| 32 |
}); |
| 33 |
return true; |
| 34 |
} |
| 35 |
async printHtml(el, { webPrintFallback = false } = {}) { |
| 36 |
if (!this.device) { |
| 37 |
return webPrintFallback && this.printWeb(el); |
| 38 |
} |
| 39 |
const printResult = await this.device.printReceipt(el); |
| 40 |
if (printResult.successful) { |
| 41 |
return printResult; |
| 42 |
} |
| 43 |
throw { |
| 44 |
title: printResult.message.title || "Error", |
| 45 |
body: printResult.message.body, |
| 46 |
canRetry: printResult.canRetry, |
| 47 |
errorCode: printResult.errorCode, |
| 48 |
}; |
| 49 |
} |
| 50 |
async print(component, props, options = {}) { |
| 51 |
if (!this.device && !options?.webPrintFallback) { |
| 52 |
logPosMessage( |
| 53 |
"PrinterService", |
| 54 |
"print", |
| 55 |
"No printer device available and webPrintFallback is not enabled" |
| 56 |
); |
| 57 |
return; |
| 58 |
} |
| 59 |
this.state.isPrinting = true; |
| 60 |
const el = await this.renderer.toHtml(component, props); |
| 61 |
try { |
| 62 |
await waitImages(el); |
| 63 |
} catch (e) { |
| 64 |
logPosMessage( |
| 65 |
"PrinterService", |
| 66 |
"print", |
| 67 |
"Images could not be loaded correctly", |
| 68 |
false, |
| 69 |
[e] |
| 70 |
); |
| 71 |
} |
| 72 |
try { |
| 73 |
return await this.printHtml(el, options); |
| 74 |
} finally { |
| 75 |
this.state.isPrinting = false; |
| 76 |
} |
| 77 |
} |
| 78 |
is = () => Boolean(this.device?.printReceipt); |
| 79 |
} |