Debian Codegraph @

addons/point_of_sale/static/src/app/services/pos_store.js

raw
1 /* global waitForWebfonts */
2
3 import { Mutex } from "@web/core/utils/concurrency";
4 import { markRaw, reactive } from "@odoo/owl";
5 import { renderToElement } from "@web/core/utils/render";
6 import { registry } from "@web/core/registry";
7 import { AlertDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
8 import {
9 deduceUrl,
10 random5Chars,
11 uuidv4,
12 Counter,
13 orderUsageUTCtoLocalUtil,
14 } from "@point_of_sale/utils";
15 import { HWPrinter } from "@point_of_sale/app/utils/printer/hw_printer";
16 import { ConnectionLostError } from "@web/core/network/rpc";
17 import { OrderReceipt } from "@point_of_sale/app/screens/receipt_screen/receipt/order_receipt";
18 import { _t } from "@web/core/l10n/translation";
19 import { OpeningControlPopup } from "@point_of_sale/app/components/popups/opening_control_popup/opening_control_popup";
20 import { SelectLotPopup } from "@point_of_sale/app/components/popups/select_lot_popup/select_lot_popup";
21 import { ProductConfiguratorPopup } from "@point_of_sale/app/components/popups/product_configurator_popup/product_configurator_popup";
22 import { ComboConfiguratorPopup } from "@point_of_sale/app/components/popups/combo_configurator_popup/combo_configurator_popup";
23 import {
24 makeAwaitable,
25 ask,
26 makeActionAwaitable,
27 } from "@point_of_sale/app/utils/make_awaitable_dialog";
28 import { PartnerList } from "../screens/partner_list/partner_list";
29 import { ScaleScreen } from "../screens/scale_screen/scale_screen";
30 import { computeComboItems } from "../models/utils/compute_combo_items";
31 import { changesToOrder, getOrderChanges } from "../models/utils/order_change";
32 import { QRPopup } from "@point_of_sale/app/components/popups/qr_code_popup/qr_code_popup";
33 import { FormViewDialog } from "@web/views/view_dialogs/form_view_dialog";
34 import { CashMovePopup } from "@point_of_sale/app/components/popups/cash_move_popup/cash_move_popup";
35 import { ClosePosPopup } from "@point_of_sale/app/components/popups/closing_popup/closing_popup";
36 import { SelectionPopup } from "../components/popups/selection_popup/selection_popup";
37 import { user } from "@web/core/user";
38 import { normalize } from "@web/core/l10n/utils";
39 import { WithLazyGetterTrap } from "@point_of_sale/lazy_getter";
40 import { debounce } from "@web/core/utils/timing";
41 import DevicesSynchronisation from "../utils/devices_synchronisation";
42 import { formatDate } from "@web/core/l10n/dates";
43 import { ProductInfoPopup } from "@point_of_sale/app/components/popups/product_info_popup/product_info_popup";
44 import { RetryPrintPopup } from "@point_of_sale/app/components/popups/retry_print_popup/retry_print_popup";
45 import { PresetSlotsPopup } from "@point_of_sale/app/components/popups/preset_slots_popup/preset_slots_popup";
46 import { DebugWidget } from "../utils/debug/debug_widget";
47 import { EpsonPrinter } from "@point_of_sale/app/utils/printer/epson_printer";
48 import OrderPaymentValidation from "../utils/order_payment_validation";
49 import { logPosMessage } from "../utils/pretty_console_log";
50 import { initLNA } from "../utils/init_lna";
51
52 const { DateTime } = luxon;
53 export const CONSOLE_COLOR = "#F5B427";
54
55 export class PosStore extends WithLazyGetterTrap {
56 loadingSkipButtonIsShown = false;
57 mainScreen = { name: null, component: null };
58
59 static serviceDependencies = [
60 "bus_service",
61 "number_buffer",
62 "barcode_reader",
63 "hardware_proxy",
64 "ui",
65 "pos_data",
66 "pos_scale",
67 "dialog",
68 "notification",
69 "printer",
70 "action",
71 "alert",
72 "pos_router",
73 "mail.sound_effects",
74 "iot_longpolling",
75 ];
76 constructor({ traps, env, deps }) {
77 super({ traps });
78 const reactiveSelf = reactive(this);
79 reactiveSelf.ready = reactiveSelf.setup(env, deps).then(() => reactiveSelf);
80 return reactiveSelf;
81 }
82 // use setup instead of constructor because setup can be patched.
83 async setup(
84 env,
85 {
86 number_buffer,
87 hardware_proxy,
88 barcode_reader,
89 ui,
90 dialog,
91 notification,
92 printer,
93 bus_service,
94 pos_data,
95 pos_scale,
96 action,
97 pos_router,
98 alert,
99 iot_longpolling,
100 }
101 ) {
102 this.env = env;
103 this.numberBuffer = number_buffer;
104 this.barcodeReader = barcode_reader;
105 this.ui = ui;
106 this.dialog = dialog;
107 this.printer = printer;
108 this.bus = bus_service;
109 this.data = pos_data;
110 this.action = action;
111 this.alert = alert;
112 this.router = pos_router;
113 this.sound = env.services["mail.sound_effects"];
114 this.notification = notification;
115 this.unwatched = markRaw({});
116 this.pushOrderMutex = new Mutex();
117 this.router.popStateCallback = this.handleUrlParams.bind(this);
118
119 // Object mapping the order's name (which contains the uuid) to it's server_id after
120 // validation (order paid then sent to the backend).
121 this.validated_orders_name_server_id_map = {};
122 this.numpadMode = "quantity";
123 this.mobile_pane = "right";
124 this.ticket_screen_mobile_pane = "left";
125
126 this.loadingOrderState = false; // used to prevent orders fetched to be put in the update set during the reactive change
127 this.screenState = {
128 ticketSCreen: {
129 offsetByDomain: {},
130 totalCount: 0,
131 },
132 partnerList: {
133 offsetBySearch: {},
134 },
135 };
136 // Handle offline mode
137 // All of Set of ids
138 this.pendingOrder = {
139 write: new Set(),
140 delete: new Set(),
141 create: new Set(),
142 };
143
144 this.hardwareProxy = hardware_proxy;
145 this.iotLongpolling = iot_longpolling;
146 this.selectedOrderUuid = null;
147 this.selectedPartner = null;
148 this.selectedCategory = null;
149 this.searchProductWord = "";
150 this.ready = new Promise((resolve) => {
151 this.markReady = resolve;
152 });
153 this.scale = pos_scale;
154
155 this.orderCounter = new Counter(0);
156
157 // FIXME POSREF: the hardwareProxy needs the pos and the pos needs the hardwareProxy. Maybe
158 // the hardware proxy should just be part of the pos service?
159 this.hardwareProxy.pos = this;
160 this.syncingOrders = new Set();
161 await this.initServerData();
162
163 if (this.config.useProxy) {
164 await this.connectToProxy();
165 }
166 this.closeOtherTabs();
167 this.syncAllOrdersDebounced = debounce(this.syncAllOrders, 100);
168 this._searchTriggered = false;
169
170 if (this.env.debug) {
171 registry.category("main_components").add("DebugWidget", {
172 Component: DebugWidget,
173 });
174 }
175
176 window.addEventListener("pos-network-online", () => {
177 // Sync should be done before websocket connection when going online
178 this.syncAllOrdersDebounced();
179 });
180
181 this.lnaState = {
182 type: "pending",
183 message: _t("Checking Local Network Access permission..."),
184 };
185 initLNA(this.notification, (type, message) => {
186 this.lnaState = { type, message };
187 });
188 }
189
190 navigate(routeName, routeParams = {}) {
191 const pageParams = registry.category("pos_pages").get(routeName);
192 const component = pageParams.component;
193
194 if (component.storeOnOrder ?? true) {
195 this.getOrder()?.setScreenData({ name: routeName, props: routeParams });
196 }
197
198 this.router.navigate(routeName, routeParams);
199 return true;
200 }
201
202 navigateToFirstPage() {
203 const page = this.firstPage;
204 this.navigate(page.page, page.params);
205 }
206
207 navigateToOrderScreen(order) {
208 const orderPage = order.getScreenData();
209 const page = orderPage?.name || "ProductScreen";
210 const params = orderPage?.props || {
211 orderUuid: order.uuid,
212 };
213 this.ticket_screen_mobile_pane = "left";
214 this.navigate(page, params);
215 }
216
217 get defaultPage() {
218 return {
219 page: "ProductScreen",
220 params: {
221 orderUuid: this.openOrder.uuid,
222 },
223 };
224 }
225
226 get firstPage() {
227 if (odoo.from_backend) {
228 // Remove from_backend params in the URL but keep the rest
229 const url = new URL(window.location.href);
230 url.searchParams.delete("from_backend");
231 window.history.replaceState({}, "", url);
232
233 if (!this.config.module_pos_hr) {
234 this.setCashier(this.user);
235 }
236 } else {
237 this.resetCashier();
238 }
239
240 return !this.cashier ? { page: "LoginScreen", params: {} } : this.defaultPage;
241 }
242
243 get idleTimeout() {
244 return [
245 {
246 timeout: 300000, // 5 minutes
247 action: () =>
248 this.router.state.current !== "PaymentScreen" && this.navigate("SaverScreen"),
249 },
250 {
251 timeout: 120000, // 2 minutes
252 action: () =>
253 this.router.state.current === "LoginScreen" && this.navigate("SaverScreen"),
254 },
255 ];
256 }
257
258 async reloadData(fullReload = false) {
259 const orders = this.models["pos.order"].getAll();
260 this.device.saveUnusedNumber(orders);
261 await this.data.resetIndexedDB();
262 const url = new URL(window.location.href);
263
264 if (fullReload) {
265 url.searchParams.set("limited_loading", "0");
266 }
267
268 window.location.href = url.href;
269 }
270
271 async showLoginScreen() {
272 this.resetCashier();
273 this.navigate("LoginScreen");
274 this.dialog.closeAll();
275 }
276
277 resetCashier() {
278 this.cashier = false;
279 this._resetConnectedCashier();
280 }
281
282 checkPreviousLoggedCashier() {
283 const savedCashier = this._getConnectedCashier();
284 if (savedCashier) {
285 this.setCashier(savedCashier);
286 }
287 }
288
289 setCashier(user) {
290 if (!user) {
291 return;
292 }
293
294 this.cashier = user;
295 this._storeConnectedCashier(user);
296 }
297
298 _getConnectedCashier() {
299 const cashier_id = Number(sessionStorage.getItem(`connected_cashier_${this.config.id}`));
300 if (cashier_id && this.models["res.users"].get(cashier_id)) {
301 return this.models["res.users"].get(cashier_id);
302 }
303 return false;
304 }
305
306 _storeConnectedCashier(user) {
307 sessionStorage.setItem(`connected_cashier_${this.config.id}`, user.id);
308 }
309
310 _resetConnectedCashier() {
311 sessionStorage.removeItem(`connected_cashier_${this.config.id}`);
312 }
313
314 async initServerData() {
315 await this.processServerData();
316 await this.handleUrlParams();
317 this.data.connectWebSocket("CLOSING_SESSION", this.closingSessionNotification.bind(this));
318 const process = await this.afterProcessServerData();
319
320 if (this.router.state.current !== "LoginScreen" && !this.config.module_pos_hr) {
321 this.setCashier(this.user);
322 }
323
324 const page =
325 this.router.state.current === "LoginScreen"
326 ? this.firstPage
327 : {
328 page: this.router.state.current,
329 params: this.router.state.params,
330 };
331 this.navigate(page.page, page.params);
332 return process;
333 }
334
335 async closingSessionNotification(data) {
336 if (
337 data.device_identifier === this.device.identifier ||
338 this.session.id !== parseInt(data.session_id)
339 ) {
340 return;
341 }
342
343 try {
344 const paidOrderNotSynced = this.models["pos.order"].filter(
345 (order) => order.state === "paid" && !order.isSynced
346 );
347 this.addPendingOrder(paidOrderNotSynced.map((o) => o.id));
348 await this.syncAllOrders({ throw: true });
349
350 this.dialog.add(AlertDialog, {
351 title: _t("Closing Session"),
352 body: _t("The session is being closed by another user. The page will be reloaded."),
353 });
354 } catch {
355 this.dialog.add(AlertDialog, {
356 title: _t("Error"),
357 body: _t(
358 "An error occurred while closing the session. Unsynced orders will be available in the next session. The page will be reloaded."
359 ),
360 });
361 } finally {
362 // All orders saved on the server should be cancelled by the device that closes
363 // the session. If some orders are not cancelled, we need to cancel them here.
364 const orders = this.models["pos.order"].filter((o) => o.isSynced);
365 for (const order of orders) {
366 if (!order.finalized) {
367 order.state = "cancel";
368 }
369 }
370 this.session.state = "closed";
371 }
372
373 setTimeout(() => {
374 window.location.reload();
375 }, 3000);
376 }
377
378 get session() {
379 return this.data.models["pos.session"].get(odoo.pos_session_id);
380 }
381
382 get company() {
383 return this.config.company_id;
384 }
385
386 async processServerData() {
387 // Used to identify the device when several devices are connected to the same POS
388 this.device = this.data.device;
389
390 // These fields should be unique for the pos_config
391 // and should not change during the session, so we can
392 // safely take the first element.this.models
393 this.config = this.data.models["pos.config"].getFirst();
394 this.user = this.data.models["res.users"].getFirst();
395 this.currency = this.config.currency_id;
396 this.pickingType = this.data.models["stock.picking.type"].getFirst();
397 this.models = this.data.models;
398 this.screenState.partnerList.offsetBySearch = {
399 "": this.models["res.partner"].length,
400 };
401
402 const models = Object.keys(this.models);
403 const dynamicModels = this.data.opts.dynamicModels;
404 const staticModels = models.filter((model) => !dynamicModels.includes(model));
405 const deviceSync = new DevicesSynchronisation(dynamicModels, staticModels, this);
406
407 this.deviceSync = deviceSync;
408 this.data.deviceSync = deviceSync;
409
410 await this.deviceSync.readDataFromServer();
411
412 // Check cashier
413 this.checkPreviousLoggedCashier();
414
415 // Add Payment Interface to Payment Method
416 for (const pm of this.models["pos.payment.method"].getAll()) {
417 const PaymentInterface = this.electronic_payment_interfaces[pm.use_payment_terminal];
418 if (PaymentInterface) {
419 pm.payment_terminal = new PaymentInterface(this, pm);
420 }
421 }
422
423 // Create printer with hardware proxy, this will override related model data
424 this.unwatched.printers = [];
425 for (const relPrinter of this.models["pos.printer"].getAll()) {
426 const printer = relPrinter.raw;
427 const HWPrinter = this.createPrinter(printer);
428
429 HWPrinter.config = printer;
430 this.unwatched.printers.push(HWPrinter);
431 }
432 this.config.iface_printers = !!this.unwatched.printers.length;
433
434 this.models["product.pricelist.item"].addEventListener("create", () => {
435 const order = this.getOrder();
436 if (!order) {
437 return;
438 }
439 const currentPricelistId = order.pricelist_id?.id;
440 order.setPricelist(this.models["product.pricelist"].get(currentPricelistId));
441 });
442
443 await this.processProductAttributes();
444 await this.config.cacheReceiptLogo();
445 }
446 cashMove() {
447 this.hardwareProxy.openCashbox(_t("Cash in / out"));
448 return makeAwaitable(this.dialog, CashMovePopup);
449 }
450 async closeSession() {
451 const info = await this.getClosePosInfo();
452
453 if (info) {
454 this.dialog.add(ClosePosPopup, info);
455 }
456 }
457 async processProductAttributes() {
458 const productIds = new Set();
459 const productTmplIds = new Set();
460 const productByTmplId = {};
461
462 for (const product of this.models["product.product"].getAll()) {
463 if (product.product_template_variant_value_ids.length > 0) {
464 productTmplIds.add(product.raw.product_tmpl_id);
465 productIds.add(product.id);
466
467 if (!productByTmplId[product.raw.product_tmpl_id]) {
468 productByTmplId[product.raw.product_tmpl_id] = [];
469 }
470
471 productByTmplId[product.raw.product_tmpl_id].push(product);
472 }
473 }
474
475 if (productIds.size > 0) {
476 try {
477 await this.data.searchRead("product.product", [
478 "&",
479 ["id", "not in", [...productIds]],
480 ["product_tmpl_id", "in", [...productTmplIds]],
481 ]);
482 } catch (error) {
483 logPosMessage(
484 "Store",
485 "processProductAttributes",
486 "Error while fetching product variants",
487 CONSOLE_COLOR,
488 [error]
489 );
490 }
491 }
492
493 for (const product of this.models["product.product"].filter(
494 (p) => !productIds.has(p.id) && p.product_template_variant_value_ids.length > 0
495 )) {
496 productByTmplId[product.raw.product_tmpl_id].push(product);
497 }
498
499 for (const products of Object.values(productByTmplId)) {
500 const nbrProduct = products.length;
501
502 for (let i = 0; i < nbrProduct - 1; i++) {
503 products[i].available_in_pos = false;
504 }
505 }
506
507 this.productAttributesExclusion = this.computeProductAttributesExclusion();
508 }
509
510 computeProductAttributesExclusion(excl = false) {
511 const exclusions = this.productAttributesExclusion || new Map();
512
513 const addExclusion = (key, value) => {
514 if (!exclusions.has(key)) {
515 exclusions.set(key, new Set());
516 }
517 exclusions.get(key).add(value);
518 };
519
520 for (const exclusion of excl ||
521 this.models["product.template.attribute.exclusion"].getAll()) {
522 const ptavId = exclusion.product_template_attribute_value_id.id;
523 for (const { id: valueId } of exclusion.value_ids) {
524 addExclusion(ptavId, valueId);
525 addExclusion(valueId, ptavId);
526 }
527 }
528 return exclusions;
529 }
530
531 doHaveConflictWith(value, selectedValues) {
532 const exclusions = this.productAttributesExclusion.get(value.id);
533 if (!exclusions) {
534 return false;
535 }
536 const selectedValueIds = new Set(selectedValues.map((v) => v.id));
537 for (const exclusionId of exclusions) {
538 if (selectedValueIds.has(exclusionId)) {
539 return true;
540 }
541 }
542 return false;
543 }
544
545 async onDeleteOrder(order) {
546 if (order.getOrderlines().length > 0) {
547 const confirmed = await ask(this.dialog, {
548 title: _t("Existing orderlines"),
549 body: _t(
550 "%s has a total amount of %s, are you sure you want to delete this order?",
551 order.pos_reference,
552 this.env.utils.formatCurrency(order.priceIncl)
553 ),
554 });
555 if (!confirmed) {
556 return false;
557 }
558 }
559 const refundedOrderLines = order.lines
560 .filter((line) => line.refunded_orderline_id?.order_id)
561 .map((line) => ({
562 order: line.refunded_orderline_id.order_id,
563 uuid: line.refunded_orderline_id.uuid,
564 }));
565
566 const orderIsDeleted = await this.deleteOrders([order]);
567 if (!orderIsDeleted) {
568 return false;
569 }
570 order.uiState.displayed = false;
571 // Delete refunded lines linked to the current order
572 for (const refundedLine of refundedOrderLines) {
573 delete refundedLine.order?.uiState?.lineToRefund[refundedLine.uuid];
574 }
575
576 await this.afterOrderDeletion();
577 return true;
578 }
579 async afterOrderDeletion() {
580 if (!this.config.module_pos_restaurant) {
581 this.setOrder(this.getOpenOrders().at(-1) || this.addNewOrder());
582 }
583 }
584
585 async deleteOrders(orders, serverIds = [], ignoreChange = false) {
586 const ordersToDelete = [];
587 const actionPosOrderCancelCall = async (orderIds) => {
588 await this.data.call("pos.order", "action_pos_order_cancel", [orderIds], {
589 context: {
590 device_identifier: this.device.identifier,
591 },
592 });
593 };
594 try {
595 for (const order of orders) {
596 if (order && (await this._onBeforeDeleteOrder(order))) {
597 if (
598 !ignoreChange &&
599 order.isSynced &&
600 Object.keys(order.last_order_preparation_change).length > 0
601 ) {
602 const orderPresetDate = DateTime.fromISO(order.preset_time);
603 const isSame = DateTime.now().hasSame(orderPresetDate, "day");
604 if (!order.preset_time || isSame) {
605 await this.sendOrderInPreparation(order, {
606 cancelled: true,
607 orderDone: true,
608 });
609 }
610 }
611
612 if (order.isSynced) {
613 await actionPosOrderCancelCall([order.id]);
614 }
615 ordersToDelete.push(order);
616 } else {
617 return false;
618 }
619 }
620
621 if (serverIds.length > 0) {
622 await actionPosOrderCancelCall([
623 ...new Set(serverIds.filter((id) => typeof id === "number")),
624 ]);
625 }
626 } finally {
627 // Remove orders locally at the end to avoid reactivity during the async process
628 for (const order of ordersToDelete) {
629 this.removeOrder(order, false);
630 this.removePendingOrder(order);
631 }
632 }
633
634 return true;
635 }
636 /**
637 * Override to do something before deleting the order.
638 * Make sure to return true to proceed on deleting the order.
639 * @param {*} order
640 * @returns {boolean}
641 */
642 async _onBeforeDeleteOrder(order) {
643 return true;
644 }
645
646 /**
647 * This method is used to load new products from the server.
648 * It also load pricelists, attributes and packagings
649 * @param {Array} domain
650 * @param {number} offset
651 * @param {number} limit
652 * @returns {Promise<Object>}
653 */
654 async loadNewProducts(domain, offset = 0, limit = 0) {
655 const result = await this.data.callRelated(
656 "product.template",
657 "load_product_from_pos",
658 [odoo.pos_config_id, domain, offset, limit],
659 {},
660 false
661 );
662 this.productAttributesExclusion = this.computeProductAttributesExclusion(
663 result["product.template.attribute.exclusion"]
664 );
665 return result;
666 }
667
668 async handleUrlParams() {
669 const orderPathUuid = this.router.state.params.orderUuid;
670 const order = this.models["pos.order"].find((order) => order.uuid === orderPathUuid);
671 if (orderPathUuid && !order) {
672 await this.data.loadServerOrders([["uuid", "=", orderPathUuid]]);
673 const order = this.models["pos.order"].find((order) => order.uuid === orderPathUuid);
674 if (order) {
675 this.setOrder(order);
676 } else {
677 const next = this.defaultPage;
678 this.router.navigate(next.page, next.params);
679 }
680 } else {
681 this.setOrder(order);
682 }
683 }
684
685 async afterProcessServerData() {
686 // Adding the not synced paid orders to the pending orders
687 const paidUnsyncedOrderIds = this.models["pos.order"]
688 .filter((order) => order.isUnsyncedPaid)
689 .map((order) => order.id);
690
691 if (paidUnsyncedOrderIds.length > 0) {
692 this.addPendingOrder(paidUnsyncedOrderIds);
693 }
694
695 const openOrders = this.data.models["pos.order"].filter((order) => !order.finalized);
696 await this.syncAllOrders();
697
698 if (!this.config.module_pos_restaurant) {
699 if (this.router.state.params.orderUuid) {
700 this.selectedOrderUuid = this.router.state.params.orderUuid;
701 } else {
702 this.selectedOrderUuid = openOrders.length
703 ? openOrders[openOrders.length - 1].uuid
704 : null;
705 }
706 }
707
708 this.markReady();
709 await this.deviceSync.readDataFromServer();
710
711 if (this.config.other_devices && this.config.epson_printer_ip) {
712 this.hardwareProxy.printer = new EpsonPrinter({ ip: this.config.epson_printer_ip });
713 }
714 }
715
716 get productViewMode() {
717 const viewMode = this.productListView && this.ui.isSmall ? this.productListView : "grid";
718 if (viewMode === "grid") {
719 return "flex-column";
720 } else {
721 return "flex-row-reverse justify-content-between m-1";
722 }
723 }
724 async onProductInfoClick(productTemplate, productProduct = false) {
725 const info = await this.getProductInfo(productTemplate, 1, 0, productProduct);
726 this.dialog.add(ProductInfoPopup, { info: info, productTemplate: productTemplate });
727 }
728 async openConfigurator(pTemplate, opts = {}) {
729 const attrById = this.models["product.attribute"].getAllBy("id");
730 const attributeLines = pTemplate.attribute_line_ids.filter(
731 (attr) => attr.attribute_id?.id in attrById
732 );
733 let attributeLinesValues = attributeLines.map((attr) => attr.product_template_value_ids);
734 if (opts.code || opts.presetVariant) {
735 let product;
736 if (opts.code) {
737 product = this.models["product.product"].getBy("barcode", opts.code.base_code);
738 } else {
739 product = opts.presetVariant;
740 }
741
742 const attrValueIds = new Set(
743 product?.product_template_attribute_value_ids?.map((v) => v.id) || []
744 );
745
746 attributeLinesValues = attributeLinesValues.map((values) =>
747 values[0].attribute_id.create_variant === "no_variant"
748 ? values
749 : values.filter((value) => attrValueIds.has(value.id))
750 );
751 }
752 if (attributeLinesValues.some((values) => values.length > 1 || values[0].is_custom)) {
753 return await makeAwaitable(this.dialog, ProductConfiguratorPopup, {
754 productTemplate: pTemplate,
755 hideAlwaysVariants: opts.hideAlwaysVariants,
756 forceVariantValue: opts.forceVariantValue,
757 line: opts.line,
758 });
759 }
760 return {
761 attribute_value_ids: attributeLinesValues.map((values) => values[0].id),
762 attribute_custom_values: [],
763 price_extra: attributeLinesValues
764 .filter((attr) => attr[0].attribute_id.create_variant !== "always")
765 .reduce((acc, values) => acc + values[0].price_extra, 0),
766 quantity: 1,
767 };
768 }
769 getDefaultSearchDetails() {
770 let field = "RECEIPT_NUMBER";
771 let term = "";
772 if (this.getOrder()?.getPartner()) {
773 field = "PARTNER";
774 term = this.getOrder().getPartner().name;
775 }
776 return {
777 fieldName: field,
778 searchTerm: term,
779 };
780 }
781
782 async setDiscountFromUI(line, val) {
783 for (const comboLine of line.combo_line_ids) {
784 comboLine.setDiscount(val);
785 }
786 line.setDiscount(val);
787 }
788
789 async setTip(tip) {
790 const currentOrder = this.getOrder();
791 const tipProduct = this.config.tip_product_id;
792 let line = currentOrder.lines.find((line) => line.product_id.id === tipProduct.id);
793
794 if (line) {
795 line.setUnitPrice(tip);
796 } else {
797 line = await this.addLineToCurrentOrder(
798 {
799 product_id: tipProduct,
800 price_unit: tip,
801 product_tmpl_id: tipProduct.product_tmpl_id,
802 },
803 {}
804 );
805 }
806
807 currentOrder.is_tipped = true;
808 currentOrder.tip_amount = tip;
809 return line;
810 }
811
812 selectOrderLine(order, line) {
813 order.selectOrderline(line);
814 this.numpadMode = "quantity";
815 }
816 // This method should be called every time a product is added to an order.
817 // The configure parameter is available if the orderline already contains all
818 // the information without having to be calculated. For example, importing a SO.
819 async addLineToCurrentOrder(vals, opts = {}, configure = true) {
820 let order = this.getOrder();
821 if (!order) {
822 order = this.addNewOrder();
823 }
824 order.assertEditable();
825 return await this.addLineToOrder(vals, order, opts, configure);
826 }
827
828 async addLineToOrder(vals, order, opts = {}, configure = true) {
829 let merge = true;
830 order.assertEditable();
831
832 const options = {
833 ...opts,
834 };
835
836 if ("price_unit" in vals) {
837 merge = false;
838 }
839
840 if (typeof vals.product_tmpl_id == "number") {
841 vals.product_tmpl_id = this.data.models["product.template"].get(vals.product_tmpl_id);
842 }
843
844 const productTemplate = vals.product_tmpl_id;
845 const values = {
846 price_type: "price_unit" in vals ? "manual" : "original",
847 price_extra: 0,
848 price_unit: 0,
849 order_id: order,
850 qty: order.preset_id?.is_return ? -1 : 1,
851 tax_ids: productTemplate.taxes_id.map((tax) => ["link", tax]),
852 product_id: productTemplate.product_variant_ids[0],
853 ...vals,
854 };
855
856 // Handle refund constraints
857 if (order.isSaleDisallowed(values, options) && !opts.force) {
858 this.dialog.add(AlertDialog, {
859 title: _t("Oops.."),
860 body: _t("Ensure you validate the refund before taking another order."),
861 });
862 return;
863 }
864
865 let keepGoing = await this.handleConfigurableProduct(
866 values,
867 productTemplate,
868 opts,
869 configure
870 );
871 if (keepGoing === false) {
872 return;
873 }
874
875 keepGoing = await this.handleComboProduct(values, order, configure);
876 if (keepGoing === false) {
877 return;
878 }
879
880 // In the case of a product with tracking enabled, we need to ask the user for the lot/serial number.
881 // It will return an instance of pos.pack.operation.lot
882 // ---
883 // This actions cannot be handled inside pos_order.js or pos_order_line.js
884 const code = opts.code;
885 let pack_lot_ids = {};
886 if (values.product_tmpl_id.isTracked() && (configure || code)) {
887 const packLotLinesToEdit =
888 (!values.product_tmpl_id.isAllowOnlyOneLot() &&
889 this.getOrder()
890 .getOrderlines()
891 .filter((line) => !line.getDiscount())
892 .find((line) => line.product_id.id === values.product_id.id)
893 ?.getPackLotLinesToEdit()) ||
894 [];
895
896 // if the lot information exists in the barcode, we don't need to ask it from the user.
897 if (code && code.type === "lot") {
898 // consider the old and new packlot lines
899 const modifiedPackLotLines = Object.fromEntries(
900 packLotLinesToEdit.filter((item) => item.id).map((item) => [item.id, item.text])
901 );
902 const newPackLotLines = [{ lot_name: code.code }];
903 pack_lot_ids = { modifiedPackLotLines, newPackLotLines };
904 } else {
905 pack_lot_ids = await this.editLots(values.product_id, packLotLinesToEdit);
906 }
907
908 if (!pack_lot_ids) {
909 return;
910 } else {
911 const packLotLine = pack_lot_ids.newPackLotLines;
912 values.pack_lot_ids = packLotLine.map((lot) => ["create", lot]);
913 }
914 }
915
916 // In case of clicking a product with tracking weight enabled a popup will be shown to the user
917 // It will return the weight of the product as quantity
918 // ---
919 // This actions cannot be handled inside pos_order.js or pos_order_line.js
920 if (values.product_tmpl_id.to_weight && this.config.iface_electronic_scale && configure) {
921 if (values.product_tmpl_id.isScaleAvailable) {
922 const decimalAccuracy = this.models["decimal.precision"].find(
923 (dp) => dp.name === "Product Unit"
924 ).digits;
925
926 const overridedValues = {};
927 if (order.pricelist_id) {
928 overridedValues.pricelist = order.pricelist_id;
929 }
930 if (order.fiscal_position_id) {
931 overridedValues.fiscalPosition = order.fiscal_position_id;
932 }
933
934 this.scale.setProduct(
935 values.product_id,
936 decimalAccuracy,
937 values.product_id.getTaxDetails({ overridedValues }).total_included
938 );
939 const weight = await this.weighProduct();
940 if (weight) {
941 values.qty = weight;
942 } else if (weight !== null) {
943 return;
944 }
945 } else {
946 await values.product_tmpl_id._onScaleNotAvailable();
947 }
948 }
949
950 // Handle price unit
951 this.handlePriceUnit(values, order, vals.price_unit);
952
953 const line = this.data.models["pos.order.line"].create({ ...values, order_id: order });
954 line.setOptions(options);
955 this.selectOrderLine(order, line);
956 if (configure) {
957 this.numberBuffer.reset();
958 }
959 let selectedOrderline = order.getSelectedOrderline();
960 if (options.draftPackLotLines && configure) {
961 selectedOrderline.setPackLotLines({
962 ...options.draftPackLotLines,
963 setQuantity: options.quantity === undefined,
964 });
965 }
966
967 // Merge orderline if needed
968 this.tryMergeOrderline(order, line, merge, selectedOrderline);
969
970 selectedOrderline = order.getSelectedOrderline();
971 if (values.product_id.tracking === "lot") {
972 const productTemplate = values.product_id.product_tmpl_id;
973 const related_lines = [];
974 const price = productTemplate.getPrice(
975 order.pricelist_id,
976 values.qty,
977 values.price_extra,
978 false,
979 values.product_id,
980 selectedOrderline,
981 related_lines
982 );
983 related_lines.forEach((line) => line.setUnitPrice(price));
984 }
985
986 if (configure) {
987 this.numberBuffer.reset();
988 }
989
990 if (values.product_id.tracking === "serial") {
991 this.selectedOrder.getSelectedOrderline().setPackLotLines({
992 modifiedPackLotLines: pack_lot_ids.modifiedPackLotLines ?? [],
993 newPackLotLines: pack_lot_ids.newPackLotLines ?? [],
994 setQuantity: true,
995 });
996 }
997
998 if (configure) {
999 this.numberBuffer.reset();
1000 }
1001
1002 return order.getSelectedOrderline();
1003 }
1004
1005 /**
1006 * Try to merge the orderline with another one in the order.
1007 * If no orderline can be merged, select the last orderline.
1008 * If merge is false, do not merge the orderline.
1009 */
1010 tryMergeOrderline(order, line, merge, selectedOrderline) {
1011 selectedOrderline = selectedOrderline || order.getSelectedOrderline();
1012 let to_merge_orderline;
1013 for (const curLine of order.lines) {
1014 if (curLine.id !== line.id) {
1015 if (curLine.canBeMergedWith(line) && merge !== false) {
1016 to_merge_orderline = curLine;
1017 }
1018 }
1019 }
1020
1021 if (to_merge_orderline) {
1022 to_merge_orderline.merge(line);
1023 line.delete();
1024 this.selectOrderLine(order, to_merge_orderline);
1025 } else if (!selectedOrderline) {
1026 this.selectOrderLine(order, order.getLastOrderline());
1027 }
1028 }
1029
1030 /**
1031 * Handle price unit for the order line.
1032 */
1033 handlePriceUnit(values, order, price_unit) {
1034 if (!values.product_tmpl_id.isCombo() && price_unit === undefined) {
1035 values.price_unit = values.product_id.getPrice(
1036 order.pricelist_id,
1037 values.qty,
1038 values.price_extra,
1039 false,
1040 values.product_id
1041 );
1042 }
1043 }
1044
1045 // In case of clicking a combo product a popup will be shown to the user
1046 // It will return the combo prices and the selected products
1047 // ---
1048 // This actions cannot be handled inside pos_order.js or pos_order_line.js
1049 async handleComboProduct(values, order, configure = true, { line } = {}) {
1050 if (values.product_tmpl_id.isCombo() && configure) {
1051 const payload =
1052 values?.payload && Object.keys(values?.payload).length
1053 ? values.payload
1054 : await makeAwaitable(this.dialog, ComboConfiguratorPopup, {
1055 productTemplate: values.product_tmpl_id,
1056 line: line,
1057 });
1058
1059 if (!payload) {
1060 return false;
1061 }
1062
1063 // Product template of combo should not have more than 1 variant.
1064 const [childLineConf, comboExtraLines] = payload;
1065 const comboPrices = computeComboItems(
1066 values.product_tmpl_id.product_variant_ids[0],
1067 childLineConf,
1068 order.pricelist_id,
1069 this.data.models["decimal.precision"].getAll(),
1070 this.data.models["product.template.attribute.value"].getAllBy("id"),
1071 comboExtraLines,
1072 this.currency
1073 );
1074
1075 values.combo_line_ids = comboPrices.map((comboItem) => [
1076 "create",
1077 {
1078 product_id: comboItem.combo_item_id.product_id,
1079 tax_ids: comboItem.combo_item_id.product_id.taxes_id.map((tax) => [
1080 "link",
1081 tax,
1082 ]),
1083 combo_item_id: comboItem.combo_item_id,
1084 price_unit: comboItem.price_unit,
1085 price_type: "original",
1086 order_id: order,
1087 qty: comboItem.qty * values.qty,
1088 attribute_value_ids: comboItem.attribute_value_ids?.map((attr) => [
1089 "link",
1090 attr,
1091 ]),
1092 custom_attribute_value_ids: Object.entries(
1093 comboItem.attribute_custom_values
1094 ).map(([id, cus]) => [
1095 "create",
1096 {
1097 custom_product_template_attribute_value_id:
1098 this.data.models["product.template.attribute.value"].get(id),
1099 custom_value: cus,
1100 },
1101 ]),
1102 },
1103 ]);
1104 }
1105
1106 return true;
1107 }
1108
1109 // In case of configurable product a popup will be shown to the user
1110 // We assign the payload to the current values object.
1111 // ---
1112 // This actions cannot be handled inside pos_order.js or pos_order_line.js
1113 handleConfigurableProduct = async (values, productTemplate, opts = {}, configure = true) => {
1114 if (productTemplate.isConfigurable() && configure) {
1115 const payload =
1116 values?.payload && Object.keys(values?.payload).length
1117 ? values.payload
1118 : await this.openConfigurator(productTemplate, opts);
1119
1120 if (payload) {
1121 // Find candidate based on instantly created variants.
1122 const attributeValues = this.models["product.template.attribute.value"]
1123 .readMany(payload.attribute_value_ids)
1124 .filter((value) => value.attribute_id.create_variant !== "no_variant")
1125 .map((value) => value.id);
1126
1127 let candidate = productTemplate.product_variant_ids.find((variant) => {
1128 const attributeIds = variant.product_template_attribute_value_ids.map(
1129 (value) => value.id
1130 );
1131 return (
1132 attributeValues.every((id) => attributeIds.includes(id)) &&
1133 attributeValues.length
1134 );
1135 });
1136
1137 const isDynamic = productTemplate.attribute_line_ids.some(
1138 (line) => line.attribute_id.create_variant === "dynamic"
1139 );
1140
1141 if (!candidate && isDynamic) {
1142 // Need to create the new product.
1143 const result = await this.data.callRelated(
1144 "product.template",
1145 "create_product_variant_from_pos",
1146 [productTemplate.id, payload.attribute_value_ids, this.config.id]
1147 );
1148 candidate = result["product.product"][0];
1149 }
1150
1151 Object.assign(values, {
1152 attribute_value_ids: payload.attribute_value_ids.map((id) => [
1153 "link",
1154 this.models["product.template.attribute.value"].get(id),
1155 ]),
1156 custom_attribute_value_ids: Object.entries(payload.attribute_custom_values).map(
1157 ([id, cus]) => [
1158 "create",
1159 {
1160 custom_product_template_attribute_value_id:
1161 this.models["product.template.attribute.value"].get(id),
1162 custom_value: cus,
1163 },
1164 ]
1165 ),
1166 price_extra: values.price_extra + payload.price_extra,
1167 qty: payload.qty || values.qty,
1168 product_id: candidate || productTemplate.product_variant_ids[0],
1169 });
1170 } else {
1171 return false;
1172 }
1173 } else if (values.product_id.product_template_variant_value_ids.length > 0) {
1174 // Verify price extra of variant products
1175 const priceExtra = values.product_id.product_template_variant_value_ids
1176 .filter((attr) => attr.attribute_id.create_variant !== "always")
1177 .reduce((acc, attr) => acc + attr.price_extra, 0);
1178
1179 values.price_extra += priceExtra;
1180 if (!values.attribute_value_ids) {
1181 values.attribute_value_ids = [];
1182 }
1183 values.attribute_value_ids = values.attribute_value_ids.concat(
1184 values.product_id.product_template_variant_value_ids.map((attr) => ["link", attr])
1185 );
1186 }
1187 };
1188
1189 createPrinter(config) {
1190 if (config.printer_type === "epson_epos") {
1191 return new EpsonPrinter({ ip: config.epson_printer_ip });
1192 }
1193 const url = deduceUrl(config.proxy_ip || "");
1194 return new HWPrinter({ url });
1195 }
1196 async _loadFonts() {
1197 return new Promise(function (resolve, reject) {
1198 // Waiting for fonts to be loaded to prevent receipt printing
1199 // from printing empty receipt while loading Inconsolata
1200 // ( The font used for the receipt )
1201 waitForWebfonts(["Lato", "Inconsolata"], function () {
1202 resolve();
1203 });
1204 // The JS used to detect font loading is not 100% robust, so
1205 // do not wait more than 5sec
1206 setTimeout(resolve, 5000);
1207 });
1208 }
1209
1210 setSelectedCategory(categoryId) {
1211 if (categoryId === this.selectedCategory?.id) {
1212 if (this.selectedCategory.parent_id) {
1213 this.selectedCategory = this.selectedCategory.parent_id;
1214 } else {
1215 this.selectedCategory = this.models["pos.category"].get(0);
1216 }
1217 } else {
1218 this.selectedCategory = this.models["pos.category"].get(categoryId);
1219 }
1220 }
1221
1222 /**
1223 * Remove the order passed in params from the list of orders
1224 * @param order
1225 */
1226 removeOrder(order, removeFromServer = true) {
1227 if (this.config.isShareable || removeFromServer) {
1228 if (order.isSynced && !order.finalized) {
1229 this.addPendingOrder([order.id], true);
1230 this.syncAllOrdersDebounced();
1231 }
1232 }
1233
1234 if (!order.isSynced && order.finalized) {
1235 this.addPendingOrder([order.id]);
1236 return;
1237 }
1238
1239 this.device.saveUnusedNumber([order]);
1240 return this.data.localDeleteCascade(order);
1241 }
1242
1243 /**
1244 * Return the current cashier (in this case, the user)
1245 * @returns {name: string, id: int, role: string}
1246 */
1247 getCashier() {
1248 if (!this.user.role) {
1249 this.user._role = this.user.raw.role;
1250 }
1251 return this.user;
1252 }
1253 getCashierUserId() {
1254 return this.user?.id;
1255 }
1256 cashierHasPriceControlRights() {
1257 return !this.config.restrict_price_control || this.getCashier()._role == "manager";
1258 }
1259 get showCashMoveButton() {
1260 return Boolean(this.config.cash_control && this.config._has_cash_move_perm);
1261 }
1262 createNewOrder(data = {}) {
1263 const fiscalPosition = this.models["account.fiscal.position"].find(
1264 (fp) => fp.id === this.config.default_fiscal_position_id?.id
1265 );
1266
1267 const order = this.models["pos.order"].create({
1268 session_id: this.session,
1269 company_id: this.company,
1270 config_id: this.config,
1271 picking_type_id: this.pickingType,
1272 user_id: this.user,
1273 access_token: uuidv4(),
1274 ticket_code: random5Chars(),
1275 fiscal_position_id: fiscalPosition,
1276 tracking_number: "",
1277 sequence_number: 0,
1278 pos_reference: "",
1279 ...data,
1280 });
1281
1282 this.setNextOrderRefs(order);
1283 order.setPricelist(this.config.pricelist_id);
1284
1285 if (this.config.use_presets && !data["preset_id"]) {
1286 this.selectPreset(this.config.default_preset_id, order);
1287 }
1288
1289 return order;
1290 }
1291 addNewOrder(data = {}) {
1292 if (this.getOrder()) {
1293 this.getOrder().updateSavedQuantity();
1294 }
1295 const order = this.createOrderIfNeeded(data);
1296 this.selectedOrderUuid = order.uuid;
1297 this.searchProductWord = "";
1298 this.mobile_pane = "right";
1299 return order;
1300 }
1301 createOrderIfNeeded(data) {
1302 return this.createNewOrder(data);
1303 }
1304 setNextOrderRefs(order) {
1305 const deviceIdentifier = this.device.identifier;
1306 const number = `${this.device.useNext()}`.padStart(6, "0");
1307 const configId = this.config.id;
1308 const year2Digits = DateTime.now().year.toString().slice(-2);
1309 const posReference = `${year2Digits}${deviceIdentifier}-${configId}-${number}`;
1310
1311 order.pos_reference = posReference;
1312 order.tracking_number = deviceIdentifier + `${parseInt(number) % 1000}`.padStart(3, "0");
1313 }
1314
1315 selectNextOrder() {
1316 const orders = this.models["pos.order"].filter((order) => !order.finalized);
1317 if (orders.length > 0) {
1318 this.selectedOrderUuid = orders[0].uuid;
1319 } else {
1320 return this.addNewOrder();
1321 }
1322 }
1323 get openOrder() {
1324 return this.models["pos.order"].find((o) => o.state === "draft") || this.addNewOrder();
1325 }
1326 getEmptyOrder() {
1327 const emptyOrders = this.models["pos.order"].filter(
1328 (order) =>
1329 order.isEmpty() &&
1330 !order.finalized &&
1331 order.payment_ids.length === 0 &&
1332 !order.partner_id &&
1333 order.pricelist_id?.id === this.config.pricelist_id?.id &&
1334 order.fiscal_position_id?.id === this.config.default_fiscal_position_id?.id
1335 );
1336 if (emptyOrders.length > 0) {
1337 return emptyOrders[0];
1338 }
1339 return this.addNewOrder();
1340 }
1341
1342 addPendingOrder(orderIds, remove = false) {
1343 if (remove) {
1344 for (const id of orderIds) {
1345 this.pendingOrder["create"].delete(id);
1346 this.pendingOrder["write"].delete(id);
1347 }
1348
1349 this.pendingOrder["delete"].add(...orderIds);
1350 return true;
1351 }
1352
1353 for (const id of orderIds) {
1354 if (typeof id === "number") {
1355 this.pendingOrder["write"].add(id);
1356 } else {
1357 this.pendingOrder["create"].add(id);
1358 }
1359 }
1360
1361 return true;
1362 }
1363
1364 getPendingOrder() {
1365 const orderToCreate = this.models["pos.order"]
1366 .filter(
1367 (order) =>
1368 this.pendingOrder.create.has(order.id) && this.shouldCreatePendingOrder(order)
1369 )
1370 .filter(Boolean);
1371 const orderToUpdate = this.models["pos.order"]
1372 .readMany(Array.from(this.pendingOrder.write))
1373 .filter(Boolean);
1374 const orderToDelete = this.models["pos.order"]
1375 .readMany(Array.from(this.pendingOrder.delete))
1376 .filter(Boolean);
1377
1378 return {
1379 orderToDelete,
1380 orderToCreate,
1381 orderToUpdate,
1382 };
1383 }
1384
1385 shouldCreatePendingOrder(order) {
1386 return (
1387 order.lines.length > 0 ||
1388 order.payment_ids.some((p) => p.payment_method_id.type === "pay_later")
1389 );
1390 }
1391
1392 getOrderIdsToDelete() {
1393 return [...this.pendingOrder.delete];
1394 }
1395
1396 removePendingOrder(order) {
1397 this.pendingOrder["create"].delete(order.id);
1398 this.pendingOrder["write"].delete(order.id);
1399 this.pendingOrder["delete"].delete(order.id);
1400 return true;
1401 }
1402
1403 clearPendingOrder() {
1404 this.pendingOrder = {
1405 create: new Set(),
1406 write: new Set(),
1407 delete: new Set(),
1408 };
1409 }
1410
1411 getSyncAllOrdersContext(orders, options = {}) {
1412 return {
1413 config_id: this.config.id,
1414 device_identifier: this.device.identifier,
1415 ...(options.context || {}),
1416 };
1417 }
1418
1419 async preSyncAllOrders(orders) {
1420 // Prices are computed on the fly on the pos.order and pos.order.line model
1421 // we need to set them before sending the orders to the backend
1422 for (const order of orders) {
1423 order.setOrderPrices();
1424 }
1425 }
1426
1427 postSyncAllOrders(orders) {}
1428 async syncAllOrders(options = {}) {
1429 if (this.data.network.offline) {
1430 if (options.throw) {
1431 throw new ConnectionLostError();
1432 }
1433
1434 return new ConnectionLostError();
1435 }
1436
1437 const { orderToCreate, orderToUpdate } = this.getPendingOrder();
1438 const orderIdsToDelete = this.getOrderIdsToDelete();
1439
1440 let orders = options.orders || [...orderToCreate, ...orderToUpdate];
1441 orders = orders.filter(
1442 (order) => !this.syncingOrders.has(order.uuid) && (order.isDirty() || options.force)
1443 );
1444
1445 // Delete orders first
1446 if (orderIdsToDelete.length > 0) {
1447 await this.deleteOrders([], orderIdsToDelete);
1448 }
1449
1450 // Allow us to force the sync of the orders In the case of
1451 // pos_restaurant is usefull to get unsynced orders
1452 // for a specific table
1453 if (orders.length === 0) {
1454 return;
1455 }
1456
1457 // We are now syncing orders one by one to avoid cancelling all sync
1458 // when one order fails, this also avoid timeout issues with a lot of orders
1459 let errorOccurred = false;
1460 let newSession = false;
1461 const syncedOrders = [];
1462
1463 for (const order of orders) {
1464 const context = this.getSyncAllOrdersContext([order], options);
1465 await this.preSyncAllOrders([order]);
1466 this.syncingOrders.add(order.id);
1467
1468 try {
1469 const serialized = order.serializeForORM();
1470 const data = await this.data.call("pos.order", "sync_from_ui", [[serialized]], {
1471 context,
1472 });
1473 const missingRecords = await this.data.missingRecursive(data);
1474 const newData = this.models.loadConnectedData(missingRecords);
1475
1476 logPosMessage(
1477 "Store",
1478 "syncAllOrders",
1479 `Successfully synced orders (${orders.length})`,
1480 CONSOLE_COLOR,
1481 [newData]
1482 );
1483
1484 for (const line of newData["pos.order.line"]) {
1485 const refundedOrderLine = line.refunded_orderline_id;
1486
1487 if (refundedOrderLine && ["paid", "done"].includes(line.order_id.state)) {
1488 const order = refundedOrderLine.order_id;
1489 if (order) {
1490 delete order.uiState?.lineToRefund[refundedOrderLine.uuid];
1491 }
1492 }
1493 }
1494
1495 await this.postSyncAllOrders(newData["pos.order"]);
1496 this.removePendingOrder(order);
1497 syncedOrders.push(...newData["pos.order"]);
1498 newSession = newSession || data["pos.session"].length > 0;
1499 } catch (error) {
1500 if (options.throw) {
1501 throw error;
1502 }
1503
1504 if (error instanceof ConnectionLostError) {
1505 logPosMessage(
1506 "Store",
1507 "syncAllOrders",
1508 "Offline mode active, order will be synced later",
1509 CONSOLE_COLOR
1510 );
1511 } else {
1512 errorOccurred = true;
1513 }
1514 } finally {
1515 orders.forEach((order) => this.syncingOrders.delete(order.uuid));
1516 }
1517 }
1518
1519 if (errorOccurred) {
1520 // In that case we assume the order data isn't valid anymore, so we
1521 // try to read data from server, to be sure to have the latest state
1522 // the order can be deleted from the server side during the sync_from_ui call
1523 this.deviceSync.readDataFromServer();
1524 }
1525
1526 if (newSession) {
1527 // Replace the original session by the rescue one. And the rescue one will have
1528 // a higher id than the original one since it's the last one created.
1529 const sessions = this.models["pos.session"].sort((a, b) => a.id - b.id);
1530 if (sessions.length > 1) {
1531 const sessionToDelete = sessions.slice(0, -1);
1532 this.models["pos.session"].deleteMany(sessionToDelete);
1533 }
1534 this.models["pos.order"]
1535 .getAll()
1536 .filter((order) => order.state === "draft")
1537 .forEach((order) => (order.session_id = this.session));
1538 }
1539
1540 return syncedOrders;
1541 }
1542
1543 pushSingleOrder(order) {
1544 return this.pushOrderMutex.exec(() => this.syncAllOrders(order));
1545 }
1546
1547 async pay() {
1548 const currentOrder = this.getOrder();
1549
1550 if (!currentOrder.canPay()) {
1551 return;
1552 }
1553
1554 if (
1555 currentOrder.lines.some(
1556 (line) => line.getProduct().tracking !== "none" && !line.hasValidProductLot()
1557 ) &&
1558 (this.pickingType.use_create_lots || this.pickingType.use_existing_lots)
1559 ) {
1560 const confirmed = await ask(this.env.services.dialog, {
1561 title: _t("Some Serial/Lot Numbers are missing"),
1562 body: _t(
1563 "You are trying to sell products with serial/lot numbers, but some of them are not set.\nWould you like to proceed anyway?"
1564 ),
1565 });
1566 if (confirmed) {
1567 this.mobile_pane = "right";
1568 this.navigate("PaymentScreen", {
1569 orderUuid: this.selectedOrderUuid,
1570 });
1571 }
1572 } else {
1573 this.mobile_pane = "right";
1574 this.navigate("PaymentScreen", {
1575 orderUuid: this.selectedOrderUuid,
1576 });
1577 }
1578 }
1579 async getServerOrders() {
1580 await this.syncAllOrders();
1581 return await this.data.loadServerOrders([
1582 ["config_id", "in", [...this.config.raw.trusted_config_ids, this.config.id]],
1583 ["state", "=", "draft"],
1584 ]);
1585 }
1586 async getProductInfo(productTemplate, quantity, priceExtra = 0, productProduct = false) {
1587 const order = this.getOrder();
1588 // check back-end method `get_product_info_pos` to see what it returns
1589 // We do this so it's easier to override the value returned and use it in the component template later
1590 const productInfo = await this.data.call("product.template", "get_product_info_pos", [
1591 [productTemplate?.id],
1592 productTemplate.getPrice(order.pricelist_id, quantity, priceExtra, false),
1593 quantity,
1594 this.config.id,
1595 productProduct?.id,
1596 ]);
1597
1598 const productTaxDetails = productTemplate.getTaxDetails();
1599 const priceWithoutTax = productTaxDetails.total_excluded;
1600 const margin = priceWithoutTax - productTemplate.standard_price;
1601 const orderPriceWithoutTax = order.priceExcl;
1602 const orderCost = order.getTotalCost();
1603 const orderMargin = orderPriceWithoutTax - orderCost;
1604 const orderTaxTotalCurrency = this.env.utils.formatCurrency(
1605 order.prices.taxDetails.order_sign * order.prices.taxDetails.tax_amount_currency
1606 );
1607 const orderPriceWithTaxCurrency = this.env.utils.formatCurrency(
1608 order.prices.taxDetails.order_sign * order.prices.taxDetails.total_amount_currency
1609 );
1610 const taxAmount = this.env.utils.formatCurrency(
1611 productTaxDetails.taxes_data.reduce((sum, d) => sum + d.tax_amount_currency, 0)
1612 );
1613 const taxName = productTemplate.taxes_id.map((t) => t.name)?.join(", ");
1614
1615 const costCurrency = this.env.utils.formatCurrency(productTemplate.standard_price);
1616 const marginCurrency = this.env.utils.formatCurrency(margin);
1617 const marginPercent = priceWithoutTax
1618 ? Math.round((margin / priceWithoutTax) * 10000) / 100
1619 : 0;
1620 const orderPriceWithoutTaxCurrency = this.env.utils.formatCurrency(orderPriceWithoutTax);
1621 const orderCostCurrency = this.env.utils.formatCurrency(orderCost);
1622 const orderMarginCurrency = this.env.utils.formatCurrency(orderMargin);
1623 const orderMarginPercent = orderPriceWithoutTax
1624 ? Math.round((orderMargin / orderPriceWithoutTax) * 10000) / 100
1625 : 0;
1626 return {
1627 costCurrency,
1628 marginCurrency,
1629 marginPercent,
1630 taxAmount,
1631 taxName,
1632 orderPriceWithoutTaxCurrency,
1633 orderCostCurrency,
1634 orderMarginCurrency,
1635 orderMarginPercent,
1636 orderTaxTotalCurrency,
1637 orderPriceWithTaxCurrency,
1638 productInfo,
1639 };
1640 }
1641 async getClosePosInfo() {
1642 return await this.data.call("pos.session", "get_closing_control_data", [[this.session.id]]);
1643 }
1644 // return the current order
1645 getOrder() {
1646 if (!this.selectedOrderUuid) {
1647 return undefined;
1648 }
1649
1650 return this.models["pos.order"].getBy("uuid", this.selectedOrderUuid);
1651 }
1652 get selectedOrder() {
1653 return this.getOrder();
1654 }
1655
1656 // change the current order
1657 setOrder(order) {
1658 if (this.getOrder()) {
1659 this.getOrder().updateSavedQuantity();
1660 }
1661 this.selectedOrderUuid = order?.uuid;
1662 }
1663
1664 // return the list of unpaid orders
1665 getOpenOrders() {
1666 return this.models["pos.order"].filter((o) => !o.finalized);
1667 }
1668
1669 // To be used in the context of closing the POS
1670 // Saves the order locally and try to send it to the backend.
1671 // If there is an error show a popup
1672 async pushOrdersWithClosingPopup(opts = {}) {
1673 try {
1674 await this.syncAllOrders(opts);
1675 return true;
1676 } catch (error) {
1677 logPosMessage(
1678 "Store",
1679 "pushOrdersWithClosingPopup",
1680 "Some orders could not be submitted to the server",
1681 CONSOLE_COLOR,
1682 [error]
1683 );
1684 const reason = this.failed
1685 ? _t(
1686 "Some orders could not be submitted to " +
1687 "the server due to configuration errors. " +
1688 "You can exit the Point of Sale, but do " +
1689 "not close the session before the issue " +
1690 "has been resolved."
1691 )
1692 : _t(
1693 "Some orders could not be submitted to " +
1694 "the server due to internet connection issues. " +
1695 "You can exit the Point of Sale, but do " +
1696 "not close the session before the issue " +
1697 "has been resolved."
1698 );
1699 await ask(this.dialog, {
1700 title: _t("Offline Orders"),
1701 body: reason,
1702 });
1703 return false;
1704 }
1705 }
1706
1707 /**
1708 * @param {str} terminalName
1709 */
1710 getPendingPaymentLine(terminalName) {
1711 for (const order of this.models["pos.order"].getAll()) {
1712 const paymentLine = order.payment_ids.find(
1713 (paymentLine) =>
1714 paymentLine.payment_method_id.use_payment_terminal === terminalName &&
1715 !paymentLine.isDone() &&
1716 paymentLine.getPaymentStatus() !== "retry"
1717 );
1718 if (paymentLine) {
1719 return paymentLine;
1720 }
1721 }
1722 }
1723
1724 get linesToRefund() {
1725 return this.models["pos.order"].reduce((acc, order) => {
1726 acc.push(...Object.values(order.uiState.lineToRefund));
1727 return acc;
1728 }, []);
1729 }
1730
1731 isProductQtyZero(qty) {
1732 const ProductUnit = this.models["decimal.precision"].find(
1733 (dp) => dp.name === "Product Unit"
1734 );
1735 return ProductUnit.isZero(qty);
1736 }
1737
1738 disallowLineQuantityChange() {
1739 return false;
1740 }
1741
1742 restrictLineDiscountChange() {
1743 return false;
1744 }
1745
1746 restrictLinePriceChange() {
1747 return false;
1748 }
1749
1750 switchPane() {
1751 this.mobile_pane = this.mobile_pane === "left" ? "right" : "left";
1752 }
1753 switchPaneTicketScreen() {
1754 this.ticket_screen_mobile_pane =
1755 this.ticket_screen_mobile_pane === "left" ? "right" : "left";
1756 }
1757 async logEmployeeMessage(action, message) {
1758 await this.data.call(
1759 "pos.session",
1760 "log_partner_message",
1761 [this.session.id, this.user.partner_id.id, action, message],
1762 {},
1763 true
1764 );
1765 }
1766 async printReceipt({
1767 basic = false,
1768 order = this.getOrder(),
1769 printBillActionTriggered = false,
1770 } = {}) {
1771 const result = await this.printer.print(
1772 OrderReceipt,
1773 {
1774 order,
1775 basic_receipt: basic,
1776 },
1777 this.printOptions
1778 );
1779 if (!printBillActionTriggered) {
1780 if (result) {
1781 const count = order.nb_print ? order.nb_print + 1 : 1;
1782 if (order.isSynced) {
1783 const wasDirty = order.isDirty();
1784 await this.data.write("pos.order", [order.id], { nb_print: count });
1785 if (!wasDirty) {
1786 order._dirty = false;
1787 }
1788 } else {
1789 order.nb_print = count;
1790 }
1791 }
1792 } else if (!order.nb_print) {
1793 order.nb_print = 0;
1794 }
1795 if (result?.warningCode) {
1796 this.displayPrinterWarning(result, _t("Receipt Printer"));
1797 }
1798 return result;
1799 }
1800 get printOptions() {
1801 return { webPrintFallback: true };
1802 }
1803 getOrderChanges(order = this.getOrder()) {
1804 return getOrderChanges(order, this.config.preparationCategories);
1805 }
1806 changesToOrder(order, skipped = false, orderPreparationCategories, cancelled = false) {
1807 return changesToOrder(order, skipped, orderPreparationCategories, cancelled);
1808 }
1809 async checkPreparationStateAndSentOrderInPreparation(order, opts = {}) {
1810 if (!order.isSynced) {
1811 return this.sendOrderInPreparation(order, opts);
1812 }
1813
1814 const data = await this.data.call("pos.order", "get_preparation_change", [order.id]);
1815 const rawchange = data.last_order_preparation_change || "{}";
1816 const lastChanges = JSON.parse(rawchange);
1817 const lastServerDate = DateTime.fromSQL(lastChanges.metadata?.serverDate).toUTC();
1818 const lastLocalDate = DateTime.fromSQL(
1819 order.last_order_preparation_change?.metadata?.serverDate
1820 ).toUTC();
1821
1822 if (lastServerDate.isValid && lastServerDate.ts != lastLocalDate.ts) {
1823 this.dialog.add(AlertDialog, {
1824 title: _t("Order Outdated"),
1825 body: _t(
1826 "The order has been modified on another device. If you have modified existing " +
1827 "order lines, check that your changes have not been overwritten.\n\n" +
1828 "The order will be sent to the server with the last changes made on this device."
1829 ),
1830 });
1831
1832 // Update before syncing otherwise it will overwrite the last change
1833 order.last_order_preparation_change = lastChanges;
1834 await this.syncAllOrders({ orders: [order] });
1835 return;
1836 }
1837
1838 return this.sendOrderInPreparation(order, opts);
1839 }
1840 // Now the printer should work in PoS without restaurant
1841 async sendOrderInPreparation(order, opts = {}) {
1842 let isPrinted = false;
1843
1844 if (this.config.printerCategories.size && !opts.byPassPrint) {
1845 try {
1846 let reprint = false;
1847 let orderChange = changesToOrder(
1848 order,
1849 this.config.printerCategories,
1850 opts.cancelled
1851 );
1852
1853 const hasChanges =
1854 orderChange.new.length ||
1855 orderChange.cancelled.length ||
1856 orderChange.noteUpdate.length ||
1857 orderChange.internal_note ||
1858 orderChange.general_customer_note;
1859
1860 let shouldPrint = true;
1861 if (!hasChanges) {
1862 if (opts.explicitReprint && order.uiState.lastPrints) {
1863 orderChange = [order.uiState.lastPrints.at(-1)];
1864 reprint = true;
1865 } else {
1866 shouldPrint = false;
1867 }
1868 } else {
1869 order.uiState.lastPrints.push(orderChange);
1870 orderChange = [orderChange];
1871 }
1872
1873 if (reprint && opts.orderDone) {
1874 shouldPrint = false;
1875 }
1876
1877 if (shouldPrint) {
1878 isPrinted = await this.printChanges(order, orderChange, reprint);
1879 }
1880 } catch (e) {
1881 logPosMessage(
1882 "Store",
1883 "sendOrderInPreparation",
1884 "Failed in printing the changes in the order",
1885 CONSOLE_COLOR,
1886 [e]
1887 );
1888 }
1889 }
1890 order.updateLastOrderChange();
1891 // Ensure that other devices are aware of the changes
1892 // Otherwise several devices can print the same changes
1893 // We need to check if a preparation display is configured to avoid unnecessary sync
1894 if (isPrinted && !this.models["pos.prep.display"]?.length) {
1895 await this.syncAllOrders({ orders: [order] });
1896 }
1897 }
1898 async sendOrderInPreparationUpdateLastChange(o, opts) {
1899 if (this.data.network.offline) {
1900 this.data.network.warningTriggered = false;
1901 throw new ConnectionLostError();
1902 }
1903 await this.checkPreparationStateAndSentOrderInPreparation(o, opts);
1904 }
1905
1906 getStrNotes(note) {
1907 if (!note) {
1908 return "";
1909 }
1910 if (Array.isArray(note)) {
1911 return note.map((n) => (typeof n === "string" ? n : n.text)).join(", ");
1912 }
1913 if (typeof note === "string") {
1914 try {
1915 const parsed = JSON.parse(note);
1916 if (Array.isArray(parsed)) {
1917 return parsed.map((n) => (typeof n === "string" ? n : n.text)).join(", ");
1918 }
1919 return note;
1920 } catch (error) {
1921 logPosMessage(
1922 "Store",
1923 "getStrNotes",
1924 "Error while parsing note, not valid JSON",
1925 CONSOLE_COLOR,
1926 [error]
1927 );
1928 return note;
1929 }
1930 }
1931 return "";
1932 }
1933
1934 getOrderData(order, reprint) {
1935 return {
1936 reprint: reprint,
1937 pos_reference: order.getName(),
1938 config_name: order.config_id?.name || order.config.name,
1939 time: DateTime.now().toFormat("HH:mm"),
1940 tracking_number: order.tracking_number,
1941 preset_time: order.presetDateTime,
1942 preset_name: order.preset_id?.name || "",
1943 employee_name: order.employee_id?.name || order.user_id?.name,
1944 internal_note: this.getStrNotes(order.internal_note),
1945 general_customer_note: order.general_customer_note,
1946 changes: {
1947 title: "",
1948 data: [],
1949 },
1950 };
1951 }
1952
1953 generateOrderChange(order, orderChange, categories, reprint = false) {
1954 const isPartOfCombo = (line) =>
1955 line.isCombo ||
1956 line.combo_parent_uuid ||
1957 this.models["product.product"].get(line.product_id).type == "combo";
1958 const comboChanges = orderChange.new.filter(isPartOfCombo);
1959 const normalChanges = orderChange.new.filter((line) => !isPartOfCombo(line));
1960 normalChanges.sort((a, b) => {
1961 const sequenceA = a.pos_categ_sequence;
1962 const sequenceB = b.pos_categ_sequence;
1963 if (sequenceA === 0 && sequenceB === 0) {
1964 return a.pos_categ_id - b.pos_categ_id;
1965 }
1966
1967 return sequenceA - sequenceB;
1968 });
1969 orderChange.new = [...comboChanges, ...normalChanges];
1970
1971 const orderData = this.getOrderData(order, reprint);
1972
1973 const changes = this.filterChangeByCategories(categories, orderChange);
1974 for (const changeItem of [...changes.new, ...changes.cancelled, ...changes.noteUpdate]) {
1975 changeItem.note = this.getStrNotes(changeItem.note || "[]");
1976 }
1977 return { orderData, changes };
1978 }
1979
1980 async generateReceiptsDataToPrint(orderData, changes, orderChange) {
1981 const receiptsData = [];
1982 if (changes.new.length) {
1983 const orderDataNew = { ...orderData };
1984 orderDataNew.changes = {
1985 title: _t("NEW"),
1986 data: changes.new,
1987 };
1988 receiptsData.push(await this.prepareReceiptGroupedData(orderDataNew));
1989 }
1990
1991 if (changes.cancelled.length) {
1992 const orderDataCancelled = { ...orderData };
1993 orderDataCancelled.changes = {
1994 title: _t("CANCELLED"),
1995 data: changes.cancelled,
1996 };
1997 receiptsData.push(await this.prepareReceiptGroupedData(orderDataCancelled));
1998 }
1999
2000 if (changes.noteUpdate.length) {
2001 const orderDataNoteUpdate = { ...orderData };
2002 const { noteUpdateTitle, printNoteUpdateData = true } = orderChange;
2003 orderDataNoteUpdate.changes = {
2004 title: noteUpdateTitle || _t("NOTE UPDATE"),
2005 data: printNoteUpdateData ? changes.noteUpdate : [],
2006 };
2007 receiptsData.push(await this.prepareReceiptGroupedData(orderDataNoteUpdate));
2008 orderData.changes.noteUpdate = [];
2009 }
2010
2011 if (orderChange.internal_note || orderChange.general_customer_note) {
2012 const orderDataNote = { ...orderData };
2013 orderDataNote.changes = { title: "", data: [] };
2014 receiptsData.push(await this.prepareReceiptGroupedData(orderDataNote));
2015 }
2016 return receiptsData;
2017 }
2018
2019 async printChanges(order, orderChange, reprint = false, printers = this.unwatched.printers) {
2020 let isPrinted = false;
2021 const unsuccessfulPrints = [];
2022 const retryPrinters = new Set();
2023
2024 for (const printer of printers) {
2025 for (const change of orderChange) {
2026 const { orderData, changes } = this.generateOrderChange(
2027 order,
2028 change,
2029 printer.config.product_categories_ids,
2030 reprint
2031 );
2032 const receiptsData = await this.generateReceiptsDataToPrint(
2033 orderData,
2034 changes,
2035 change
2036 );
2037 let result = {};
2038 for (const data of receiptsData) {
2039 result = await this.printOrderChanges(data, printer);
2040 if (result.successful) {
2041 isPrinted = true;
2042 }
2043
2044 if (!result.successful) {
2045 retryPrinters.add(printer);
2046 unsuccessfulPrints.push(printer.config.name + ": " + result.message.body);
2047 } else if (result.warningCode) {
2048 this.displayPrinterWarning(result, printer.config.name);
2049 }
2050 }
2051 }
2052 }
2053
2054 // printing errors
2055 if (unsuccessfulPrints.length) {
2056 const failedReceipts = unsuccessfulPrints.join("\n");
2057 this.dialog.add(RetryPrintPopup, {
2058 message: failedReceipts,
2059 canRetry: true,
2060 retry: () => {
2061 this.printChanges(order, orderChange, reprint, retryPrinters);
2062 },
2063 });
2064 }
2065
2066 return isPrinted;
2067 }
2068
2069 async prepareReceiptGroupedData(data) {
2070 const dataChanges = data.changes?.data;
2071 if (dataChanges && dataChanges.some((c) => c.group)) {
2072 const groupedData = dataChanges.reduce((acc, c) => {
2073 const { name = "", index = -1 } = c.group || {};
2074 if (!acc[name]) {
2075 acc[name] = { name, index, data: [] };
2076 }
2077 acc[name].data.push(c);
2078 return acc;
2079 }, {});
2080 data.changes.groupedData = Object.values(groupedData).sort((a, b) => a.index - b.index);
2081 }
2082 return data;
2083 }
2084
2085 async printOrderChanges(data, printer) {
2086 const receipt = renderToElement("point_of_sale.OrderChangeReceipt", {
2087 data: data,
2088 });
2089 return await printer.printReceipt(receipt);
2090 }
2091
2092 filterChangeByCategories(categories, currentOrderChange) {
2093 const matchesCategories = (change) => {
2094 const product = this.models["product.product"].get(change["product_id"]);
2095 const categoryIds = product.parentPosCategIds;
2096 for (const categoryId of categoryIds) {
2097 if (categories.includes(categoryId)) {
2098 return true;
2099 }
2100 }
2101 return false;
2102 };
2103
2104 const filterChanges = (changes) => {
2105 // Combo line uuids to have at least one child line in the given categories
2106 const validComboUuids = new Set(
2107 changes
2108 .filter((change) => change.combo_parent_uuid && matchesCategories(change))
2109 .map((change) => change.combo_parent_uuid)
2110 );
2111 return changes.filter(
2112 (change) =>
2113 (change.isCombo && validComboUuids.has(change.uuid)) ||
2114 (!change.isCombo && matchesCategories(change))
2115 );
2116 };
2117
2118 return {
2119 new: filterChanges(currentOrderChange["new"]),
2120 cancelled: filterChanges(currentOrderChange["cancelled"]),
2121 noteUpdate: filterChanges(currentOrderChange["noteUpdate"]),
2122 };
2123 }
2124
2125 connectToProxy() {
2126 return new Promise((resolve, reject) => {
2127 this.barcodeReader?.disconnectFromProxy();
2128 this.loadingSkipButtonIsShown = true;
2129 this.hardwareProxy.autoConnect({ force_ip: this.config.proxy_ip }).then(
2130 () => {
2131 if (this.config.iface_scan_via_proxy) {
2132 this.barcodeReader?.connectToProxy();
2133 }
2134 resolve();
2135 },
2136 (statusText, url) => {
2137 // this should reject so that it can be captured when we wait for pos.ready
2138 // in the chrome component.
2139 // then, if it got really rejected, we can show the error.
2140 if (statusText == "error" && window.location.protocol == "https:") {
2141 // FIXME POSREF this looks like it's dead code.
2142 reject({
2143 title: _t("HTTPS connection to IoT Box failed"),
2144 body: _t(
2145 "Make sure you are using IoT Box v18.12 or higher. Navigate to %s to accept the certificate of your IoT Box.",
2146 url
2147 ),
2148 popup: "alert",
2149 });
2150 } else {
2151 resolve();
2152 }
2153 }
2154 );
2155 });
2156 }
2157 editPartnerContext(partner) {
2158 return {};
2159 }
2160 /**
2161 * @param {import("@point_of_sale/app/models/res_partner").ResPartner?} partner leave undefined to create a new partner
2162 */
2163 async editPartner(partner) {
2164 const record = await makeActionAwaitable(
2165 this.action,
2166 "point_of_sale.res_partner_action_edit_pos",
2167 {
2168 props: { resId: partner?.id },
2169 additionalContext: this.editPartnerContext(),
2170 }
2171 );
2172 const newPartner = await this.data.read("res.partner", record.config.resIds);
2173 return newPartner[0];
2174 }
2175 /**
2176 * @param {import("@point_of_sale/app/models/product_product").ProductProduct?} product leave undefined to create a new product
2177 */
2178 async editProduct(product) {
2179 const orderContainsProduct = product && this.orderContainsProduct(product);
2180 this.action.doAction(
2181 product
2182 ? "point_of_sale.product_template_action_edit_pos"
2183 : "point_of_sale.product_template_action_add_pos",
2184 {
2185 props: {
2186 resId: product?.id,
2187 onSave: (record) => {
2188 this.data.read("product.template", [record.evalContext.id]);
2189 this.data.searchRead("product.product", [
2190 ["product_tmpl_id", "=", record.evalContext.id],
2191 ]);
2192 this.action.doAction({
2193 type: "ir.actions.act_window_close",
2194 });
2195 },
2196 },
2197 additionalContext: {
2198 taxes_readonly: orderContainsProduct,
2199 },
2200 }
2201 );
2202 }
2203 orderContainsProduct(product) {
2204 const lines = this.getOpenOrders().flatMap((o) => o.lines);
2205 return lines.some((l) => l.product_id.product_tmpl_id.id === product.id);
2206 }
2207 async loadSampleData() {
2208 const [isPosManager, isAdmin] = await Promise.all([
2209 user.hasGroup("point_of_sale.group_pos_manager"),
2210 user.hasGroup("base.group_system"),
2211 ]);
2212
2213 if (!(isPosManager && isAdmin)) {
2214 this.dialog.add(AlertDialog, {
2215 title: _t("Access Denied"),
2216 body: _t("It seems like you don't have enough rights to load data."),
2217 });
2218 return;
2219 }
2220 await this.data.call("pos.config", "load_demo_data", [[this.config.id]]);
2221 await this.reloadData(true);
2222 }
2223 async allowProductCreation() {
2224 return await user.hasGroup("base.group_system");
2225 }
2226 orderDetailsProps(order) {
2227 return {
2228 resModel: "pos.order",
2229 resId: order.id,
2230 context: {
2231 from_frontend: true,
2232 },
2233 onRecordSaved: async (record) => {
2234 await this.data.loadServerOrders([["id", "=", record.evalContext.id]]);
2235 this.action.doAction({
2236 type: "ir.actions.act_window_close",
2237 });
2238 },
2239 };
2240 }
2241 async orderDetails(order) {
2242 this.dialog.add(FormViewDialog, this.orderDetailsProps(order));
2243 }
2244 async closePos() {
2245 this._resetConnectedCashier();
2246 // If pos is not properly loaded, we just go back to /web without
2247 // doing anything in the order data.
2248 if (!this) {
2249 this.redirectToBackend();
2250 }
2251
2252 if (this.session.state === "opening_control") {
2253 const data = await this.data.call("pos.session", "delete_opening_control_session", [
2254 this.session.id,
2255 ]);
2256
2257 if (data.status === "success") {
2258 this.redirectToBackend();
2259 }
2260 }
2261
2262 // If there are orders in the db left unsynced, we try to sync.
2263 const syncSuccess = await this.pushOrdersWithClosingPopup();
2264 if (syncSuccess) {
2265 this.redirectToBackend();
2266 }
2267 }
2268 async selectPricelist(pricelist) {
2269 await this.getOrder().setPricelist(pricelist);
2270 }
2271 async openPresetTiming(order = this.getOrder()) {
2272 const data = await makeAwaitable(this.dialog, PresetSlotsPopup);
2273 if (data) {
2274 if (order.preset_id.id != data.presetId) {
2275 await this.selectPreset(this.models["pos.preset"].get(data.presetId));
2276 }
2277
2278 order.preset_time = data.slot.datetime;
2279 if (data.slot.datetime > DateTime.now()) {
2280 this.addPendingOrder([order.id]);
2281 await this.syncAllOrders({ orders: [order] });
2282 }
2283 }
2284 }
2285 async handleSelectNamePreset(order) {
2286 if (!order.partner_id) {
2287 const partner = await this.selectPartner();
2288 if (!partner) {
2289 return;
2290 }
2291 }
2292 }
2293 async selectPreset(preset = false, order = this.getOrder()) {
2294 if (!preset) {
2295 const selectionList = this.models["pos.preset"].map((preset) => ({
2296 id: preset.id,
2297 label: preset.name,
2298 isSelected: order.preset_id && preset.id === order.preset_id.id,
2299 item: preset,
2300 }));
2301
2302 preset = await makeAwaitable(this.dialog, SelectionPopup, {
2303 title: _t("Select preset"),
2304 list: selectionList,
2305 size: "md",
2306 });
2307 }
2308
2309 if (preset) {
2310 order.setPreset(preset);
2311
2312 if (preset.needsPartner) {
2313 const partner = order.partner_id || (await this.selectPartner(order));
2314 if (!partner) {
2315 return;
2316 }
2317 if (!(partner.street || partner.street2)) {
2318 this.notification.add(_t("Customer address is required"), { type: "warning" });
2319 await this.editPartner(partner);
2320 if (!(partner.street || partner.street2)) {
2321 return;
2322 }
2323 }
2324 }
2325
2326 if (preset.identification === "name") {
2327 await this.handleSelectNamePreset(order);
2328 }
2329
2330 if (preset.use_timing && !order.preset_time) {
2331 await this.openPresetTiming(order);
2332 if (!order.preset_time) {
2333 await this.syncPresetSlotAvaibility(preset);
2334 order.preset_time = preset.nextSlot?.datetime || false;
2335 }
2336 } else if (!preset.use_timing) {
2337 order.preset_time = false;
2338 }
2339 }
2340 }
2341 orderUsageUTCtoLocal(data) {
2342 return orderUsageUTCtoLocalUtil(data);
2343 }
2344 async syncPresetSlotAvaibility(preset) {
2345 try {
2346 const result = await this.data.call("pos.preset", "get_available_slots", [preset.id]);
2347 const localUsage = this.orderUsageUTCtoLocal(result.usage_utc);
2348 preset.computeAvailabilities(localUsage);
2349 } catch {
2350 // Compute locally if the server is not reachable
2351 preset.computeAvailabilities();
2352 }
2353 }
2354 // There for override to do something before adding partner to current order from partner list
2355 setPartnerToCurrentOrder(partner) {
2356 this.getOrder().setPartner(partner);
2357 }
2358 async selectPartner(currentOrder = this.getOrder()) {
2359 // FIXME, find order to refund when we are in the ticketscreen.
2360 if (!currentOrder) {
2361 return false;
2362 }
2363 const currentPartner = currentOrder.getPartner();
2364 if (currentPartner && currentOrder.getHasRefundLines()) {
2365 this.dialog.add(AlertDialog, {
2366 title: _t("Can't change customer"),
2367 body: _t(
2368 "This order already has refund lines for %s. We can't change the customer associated to it. Create a new order for the new customer.",
2369 currentPartner.name
2370 ),
2371 });
2372 return currentPartner;
2373 }
2374 const payload = await makeAwaitable(this.dialog, PartnerList, {
2375 partner: currentPartner,
2376 });
2377
2378 this.setPartnerToCurrentOrder(payload || false);
2379
2380 return payload;
2381 }
2382 async editLotsRefund(line) {
2383 const product = line.getProduct();
2384 const packLotLinesToEdit = line.pack_lot_ids.map((p) => ({
2385 id: p.id,
2386 text: p.lot_name,
2387 }));
2388 const alreadyRefundedLots = line.refunded_orderline_id.refund_orderline_ids
2389 .filter((item) => !["cancel", "draft"].includes(item.order_id.state))
2390 .flatMap((item) => item.pack_lot_ids)
2391 .map((p) => p.lot_name);
2392 const options = line.refunded_orderline_id.pack_lot_ids
2393 .map((p) => ({ id: p.id, name: p.lot_name, product_qty: line.qty }))
2394 .filter((lot) => !alreadyRefundedLots.includes(lot.name));
2395 const payload = await makeAwaitable(this.dialog, SelectLotPopup, {
2396 title: _t("Lot/Serial number(s) required for"),
2397 name: product.display_name,
2398 isSingleItem: product.isAllowOnlyOneLot(),
2399 array: packLotLinesToEdit,
2400 options: options,
2401 customInput: false,
2402 uniqueValues: product.tracking === "serial",
2403 isLotNameUsed: () => false,
2404 });
2405 if (payload) {
2406 const modifiedPackLotLines = {};
2407 const newPackLotLines = [];
2408 for (const item of payload) {
2409 if (item.id) {
2410 modifiedPackLotLines[item.id] = item.text;
2411 } else {
2412 newPackLotLines.push({ lot_name: item.text });
2413 }
2414 }
2415 return { modifiedPackLotLines, newPackLotLines };
2416 } else {
2417 return null;
2418 }
2419 }
2420
2421 async editLots(product, packLotLinesToEdit) {
2422 const isAllowOnlyOneLot = product.isAllowOnlyOneLot();
2423 let canCreateLots = this.pickingType.use_create_lots || !this.pickingType.use_existing_lots;
2424
2425 let existingLots = [];
2426 try {
2427 existingLots = await this.data.call("pos.order.line", "get_existing_lots", [
2428 this.company.id,
2429 this.config.id,
2430 product.id,
2431 ]);
2432 if (!canCreateLots && (!existingLots || existingLots.length === 0)) {
2433 this.dialog.add(AlertDialog, {
2434 title: _t("No existing serial/lot number"),
2435 body: _t(
2436 "There is no serial/lot number for the selected product, and their creation is not allowed from the Point of Sale app."
2437 ),
2438 });
2439 return null;
2440 }
2441 } catch (ex) {
2442 logPosMessage("Store", "editLots", "Collecting existing lots failed", CONSOLE_COLOR, [
2443 ex,
2444 ]);
2445 const confirmed = await ask(this.dialog, {
2446 title: _t("Server communication problem"),
2447 body: _t(
2448 "The existing serial/lot numbers could not be retrieved. \nContinue without checking the validity of serial/lot numbers ?"
2449 ),
2450 confirmLabel: _t("Yes"),
2451 cancelLabel: _t("No"),
2452 });
2453 if (!confirmed) {
2454 return null;
2455 }
2456 canCreateLots = true;
2457 }
2458
2459 const usedLotsQty = this.models["pos.pack.operation.lot"]
2460 .filter(
2461 (lot) =>
2462 lot.pos_order_line_id?.product_id?.id === product.id &&
2463 lot.pos_order_line_id?.order_id?.state === "draft"
2464 )
2465 .reduce((acc, lot) => {
2466 if (!acc[lot.lot_name]) {
2467 acc[lot.lot_name] = { total: 0, currentOrderCount: 0 };
2468 }
2469 acc[lot.lot_name].total += lot.pos_order_line_id?.qty || 0;
2470
2471 if (lot.pos_order_line_id?.order_id?.id === this.selectedOrder.id) {
2472 acc[lot.lot_name].currentOrderCount += lot.pos_order_line_id?.qty || 0;
2473 }
2474 return acc;
2475 }, {});
2476
2477 // Remove lot/serial names that are already used in draft orders
2478 existingLots = existingLots.filter(
2479 (lot) => lot.product_qty > (usedLotsQty[lot.name]?.total || 0)
2480 );
2481
2482 // Check if the input lot/serial name is already used in another order
2483 const isLotNameUsed = (itemValue) => {
2484 const totalQty = existingLots.find((lt) => lt.name == itemValue)?.product_qty || 0;
2485 const usedQty = usedLotsQty[itemValue]
2486 ? usedLotsQty[itemValue].total - usedLotsQty[itemValue].currentOrderCount
2487 : 0;
2488 return usedQty ? usedQty >= totalQty : false;
2489 };
2490
2491 const existingLotsName = existingLots.map((l) => l.name);
2492 if (!packLotLinesToEdit.length && existingLotsName.length === 1) {
2493 // If there's only one existing lot/serial number, automatically assign it to the order line
2494 return { newPackLotLines: [{ lot_name: existingLotsName[0] }] };
2495 }
2496 const payload = await makeAwaitable(this.dialog, SelectLotPopup, {
2497 title: _t("Lot/Serial number(s) required for"),
2498 name: product.display_name,
2499 isSingleItem: isAllowOnlyOneLot,
2500 array: packLotLinesToEdit,
2501 options: existingLots,
2502 customInput: canCreateLots,
2503 uniqueValues: product.tracking === "serial",
2504 isLotNameUsed: isLotNameUsed,
2505 });
2506 if (payload) {
2507 // Segregate the old and new packlot lines
2508 const modifiedPackLotLines = Object.fromEntries(
2509 payload.filter((item) => item.id).map((item) => [item.id, item.text])
2510 );
2511 const newPackLotLines = payload
2512 .filter((item) => !item.id)
2513 .map((item) => ({ lot_name: item.text }));
2514
2515 return { modifiedPackLotLines, newPackLotLines };
2516 } else {
2517 return null;
2518 }
2519 }
2520
2521 openOpeningControl() {
2522 if (this.shouldShowOpeningControl()) {
2523 this.dialog.add(
2524 OpeningControlPopup,
2525 {},
2526 {
2527 onClose: () => {
2528 if (
2529 this.session.state !== "opened" &&
2530 this.router.state.current === "ProductScreen"
2531 ) {
2532 this.closePos();
2533 }
2534 },
2535 }
2536 );
2537 }
2538 }
2539 shouldShowOpeningControl() {
2540 return this.session.state == "opening_control";
2541 }
2542
2543 /**
2544 * Close other tabs that contain the same pos session.
2545 */
2546 closeOtherTabs() {
2547 localStorage["message"] = "";
2548 localStorage["message"] = JSON.stringify({
2549 message: "close_tabs",
2550 session: this.session.id,
2551 });
2552
2553 window.addEventListener(
2554 "storage",
2555 (event) => {
2556 if (event.key === "message" && event.newValue) {
2557 const msg = JSON.parse(event.newValue);
2558 if (msg.message === "close_tabs" && msg.session == this.session.id) {
2559 logPosMessage(
2560 "Store",
2561 "editLots",
2562 "POS / Session opened in another window. EXITING POS",
2563 CONSOLE_COLOR
2564 );
2565 this.closePos();
2566 }
2567 }
2568 },
2569 false
2570 );
2571 }
2572
2573 showBackButton() {
2574 return (
2575 this.ui.isSmall &&
2576 this.numpadMode !== "table" &&
2577 (this.router.state.current !== "ProductScreen" || this.mobile_pane === "left")
2578 );
2579 }
2580 async onClickBackButton() {
2581 if (this.router.state.current === "TicketScreen") {
2582 if (this.ticket_screen_mobile_pane == "left") {
2583 const next = this.defaultPage;
2584 this.navigate(next.page, next.params);
2585 } else {
2586 this.ticket_screen_mobile_pane = "left";
2587 }
2588 } else if (
2589 this.mobile_pane == "left" ||
2590 ["PaymentScreen", "ActionScreen"].includes(this.router.state.current)
2591 ) {
2592 if (this.router.state.current === "ProductScreen") {
2593 this.getOrder().deselectOrderline();
2594 }
2595
2596 this.mobile_pane = this.router.state.current === "PaymentScreen" ? "left" : "right";
2597 this.navigate("ProductScreen", {
2598 orderUuid: this.getOrder().uuid,
2599 });
2600 }
2601 }
2602
2603 showSearchButton() {
2604 if (this.router.state.current === "ProductScreen") {
2605 return this.ui.isSmall ? this.mobile_pane === "right" : true;
2606 }
2607 return false;
2608 }
2609
2610 async showQR(payment) {
2611 let qr;
2612 try {
2613 qr = await this.data.call("pos.payment.method", "get_qr_code", [
2614 [payment.payment_method_id.id],
2615 payment.amount,
2616 payment.pos_order_id.name + " " + payment.pos_order_id.tracking_number,
2617 "",
2618 this.currency.id,
2619 payment.pos_order_id.partner_id?.id,
2620 ]);
2621 } catch (error) {
2622 qr = payment.payment_method_id.default_qr;
2623 if (!qr) {
2624 let message;
2625 if (error instanceof ConnectionLostError) {
2626 message = _t(
2627 "Connection to the server has been lost. Please check your internet connection."
2628 );
2629 } else {
2630 message = error.data.message;
2631 }
2632 this.env.services.dialog.add(AlertDialog, {
2633 title: _t("Failure to generate Payment QR Code"),
2634 body: message,
2635 });
2636 return false;
2637 }
2638 }
2639 payment.qrPaymentData = {
2640 name: payment.payment_method_id.name,
2641 amount: this.env.utils.formatCurrency(payment.amount),
2642 qrCode: qr,
2643 };
2644 return await ask(
2645 this.env.services.dialog,
2646 {
2647 title: payment.name,
2648 line: payment,
2649 order: payment.pos_order_id,
2650 qrCode: qr,
2651 },
2652 {},
2653 QRPopup
2654 ).then((result) => {
2655 payment.qrPaymentData = null;
2656 return result;
2657 });
2658 }
2659
2660 redirectToBackend() {
2661 window.location = "/odoo/action-point_of_sale.action_client_pos_menu";
2662 }
2663
2664 getExcludedProductIds() {
2665 return [
2666 this.config.tip_product_id?.product_tmpl_id?.id,
2667 ...this.config._pos_special_products_ids.map(
2668 (id) => this.models["product.product"].get(id)?.product_tmpl_id?.id
2669 ),
2670 ].filter(Boolean);
2671 }
2672
2673 areAllProductsSpecial(products) {
2674 const specialDisplayProductIds = this.config._pos_special_display_products_ids || [];
2675 return (
2676 specialDisplayProductIds.length >= products.length &&
2677 products.every((product) => specialDisplayProductIds.includes(product.id))
2678 );
2679 }
2680
2681 get productsToDisplay() {
2682 const searchWord = this.searchProductWord.trim();
2683 const allProducts = this.models["product.template"].getAll();
2684 let list = [];
2685 const isSearchByWord = searchWord !== "";
2686
2687 if (isSearchByWord) {
2688 if (!this._searchTriggered) {
2689 this.setSelectedCategory(0);
2690 this._searchTriggered = true;
2691 }
2692 list = this.getProductsBySearchWord(
2693 searchWord,
2694 this.selectedCategory?.id ? this.selectedCategory.associatedProducts : allProducts
2695 );
2696 } else {
2697 this._searchTriggered = false;
2698 if (this.selectedCategory?.id) {
2699 list = this.selectedCategory.associatedProducts;
2700 } else {
2701 list = allProducts;
2702 }
2703 }
2704
2705 if (!list || list.length === 0) {
2706 return [];
2707 }
2708
2709 const filteredList = [];
2710 const excludedProductIds = new Set(this.getExcludedProductIds());
2711 const availableCateg = new Set(
2712 (this.config.iface_available_categ_ids || []).map((c) => c.id)
2713 );
2714
2715 for (const p of list) {
2716 if (filteredList.length >= 100) {
2717 break;
2718 }
2719
2720 if (excludedProductIds.has(p.id) || !p.canBeDisplayed) {
2721 continue;
2722 }
2723
2724 if (
2725 availableCateg.size &&
2726 !this.config._pos_special_display_products_ids?.includes(p.id) &&
2727 !p.pos_categ_ids.some((c) => availableCateg.has(c.id))
2728 ) {
2729 continue;
2730 }
2731
2732 filteredList.push(p);
2733 }
2734
2735 if (
2736 !isSearchByWord &&
2737 !this.selectedCategory?.id &&
2738 this.areAllProductsSpecial(filteredList)
2739 ) {
2740 return [];
2741 }
2742
2743 return isSearchByWord
2744 ? filteredList.sort((a, b) => b.is_favorite - a.is_favorite)
2745 : filteredList.sort((a, b) => {
2746 if (b.is_favorite !== a.is_favorite) {
2747 return b.is_favorite - a.is_favorite;
2748 } else if (a.pos_sequence !== b.pos_sequence) {
2749 return a.pos_sequence - b.pos_sequence;
2750 }
2751 return a.name.localeCompare(b.name);
2752 });
2753 }
2754
2755 get productToDisplayByCateg() {
2756 const sortedProducts = this.productsToDisplay;
2757 if (!this.config.iface_group_by_categ) {
2758 return sortedProducts.length ? [["0", sortedProducts]] : [];
2759 } else {
2760 const groupedByCategory = {};
2761 const selectedCategories = this.selectedCategory
2762 ? this.selectedCategory.getAllChildren().map((c) => c.id)
2763 : false;
2764 for (const product of sortedProducts) {
2765 if (product.pos_categ_ids.length === 0) {
2766 // Only display product without category if we don't have a category selected
2767 if (selectedCategories) {
2768 continue;
2769 }
2770 if (!groupedByCategory[0]) {
2771 groupedByCategory[0] = [];
2772 }
2773 groupedByCategory[0].push(product);
2774 continue;
2775 }
2776 const productCategories = product.pos_categ_ids.map((c) => c.id);
2777 for (const categId of productCategories) {
2778 if (selectedCategories && !selectedCategories.includes(categId)) {
2779 continue;
2780 }
2781 if (!groupedByCategory[categId]) {
2782 groupedByCategory[categId] = [];
2783 }
2784 groupedByCategory[categId].push(product);
2785 }
2786 }
2787 const res = Object.entries(groupedByCategory).sort(([a], [b]) => {
2788 // None category goes last
2789 const aNoneCategory = a === "0";
2790 const bNoneCategory = b === "0";
2791 if (aNoneCategory && bNoneCategory) {
2792 return 0;
2793 }
2794 if (aNoneCategory) {
2795 return 1;
2796 }
2797 if (bNoneCategory) {
2798 return -1;
2799 }
2800
2801 const catA = this.models["pos.category"].get(a);
2802 const catB = this.models["pos.category"].get(b);
2803
2804 const isRootA = !catA.parent_id;
2805 const isRootB = !catB.parent_id;
2806
2807 return isRootA !== isRootB ? (isRootA ? -1 : 1) : catA.sequence - catB.sequence;
2808 });
2809 return res;
2810 }
2811 }
2812
2813 getProductsBySearchWord(searchWord, products) {
2814 const query = normalize(searchWord);
2815 const matches = [];
2816
2817 for (const product of products) {
2818 const searchStr = product.searchString;
2819
2820 if (searchStr.includes(query)) {
2821 const normName = product.normalizedName;
2822 matches.push({
2823 product: product,
2824 index: normName.indexOf(query),
2825 name: normName,
2826 });
2827 }
2828 }
2829
2830 matches.sort(
2831 (a, b) =>
2832 (a.index === -1) - (b.index === -1) ||
2833 a.index - b.index ||
2834 (a.name == b.name ? 0 : a.name > b.name ? 1 : -1)
2835 );
2836
2837 return matches.map((m) => m.product);
2838 }
2839 getPaymentMethodFmtAmount(pm, order) {
2840 const amount = order.getDefaultAmountDueToPayIn(pm);
2841 const fmtAmount = this.env.utils.formatCurrency(amount, true);
2842
2843 if (!this.currency.isPositive(amount) || !this.config.cash_rounding) {
2844 return;
2845 }
2846 if (!this.config.only_round_cash_method || pm.type === "cash") {
2847 return fmtAmount;
2848 }
2849 }
2850 getDate(date) {
2851 const todayTs = DateTime.now().startOf("day").ts;
2852 if (date.toLocal().startOf("day").ts === todayTs) {
2853 return _t("Today");
2854 } else {
2855 return formatDate(date);
2856 }
2857 }
2858 getTime(date) {
2859 return date.toFormat("hh:mm");
2860 }
2861
2862 orderDone(order) {
2863 order.setScreenData({ name: "" });
2864 if (!this.config.module_pos_restaurant) {
2865 this.selectedOrderUuid = this.getEmptyOrder().uuid;
2866 }
2867 this.searchProductWord = "";
2868 const nextPage = this.defaultPage;
2869 this.navigate(nextPage.page, nextPage.params);
2870 }
2871
2872 displayPrinterWarning(printResult, printerName) {
2873 let notification;
2874 if (printResult.warningCode === "ROLL_PAPER_HAS_ALMOST_RUN_OUT") {
2875 notification = _t("%s almost runs out of paper.", printerName);
2876 }
2877 if (notification) {
2878 this.notification.add(notification, {
2879 type: "warning",
2880 });
2881 }
2882 }
2883
2884 async isSessionDeleted() {
2885 return (
2886 (await this.data.orm.searchCount("pos.session", [["id", "=", this.session.id]])) === 0
2887 );
2888 }
2889
2890 weighProduct() {
2891 return makeAwaitable(this.env.services.dialog, ScaleScreen);
2892 }
2893
2894 async validateOrderFast(paymentMethod) {
2895 const validation = new OrderPaymentValidation({
2896 pos: this,
2897 orderUuid: this.getOrder().uuid,
2898 fastPaymentMethod: paymentMethod,
2899 });
2900 await validation.validateOrder(false);
2901 }
2902
2903 clickSaveOrder() {
2904 this.syncAllOrders({ orders: [this.getOrder()] });
2905 this.notification.add(_t("Order saved for later"), { type: "success" });
2906 this.setOrder(this.getEmptyOrder());
2907 this.mobile_pane = "right";
2908 }
2909
2910 get showSaveOrderButton() {
2911 return this.config.raw.trusted_config_ids.length > 0;
2912 }
2913
2914 canEditPayment(order) {
2915 return order.nb_print === 0;
2916 }
2917 }
2918
2919 PosStore.prototype.electronic_payment_interfaces = {};
2920
2921 /**
2922 * Call this function to map your PaymentInterface implementation to
2923 * the use_payment_terminal field. When the POS loads it will take
2924 * care of instantiating your interface and setting it on the right
2925 * payment methods.
2926 *
2927 * @param {string} use_payment_terminal - value used in the
2928 * use_payment_terminal selection field
2929 *
2930 * @param {Object} ImplementedPaymentInterface - implemented
2931 * PaymentInterface
2932 */
2933 export function register_payment_method(use_payment_terminal, ImplementedPaymentInterface) {
2934 PosStore.prototype.electronic_payment_interfaces[use_payment_terminal] =
2935 ImplementedPaymentInterface;
2936 }
2937
2938 export const posService = {
2939 dependencies: PosStore.serviceDependencies,
2940 async start(env, deps) {
2941 return new PosStore({ traps: {}, env, deps }).ready;
2942 },
2943 };
2944
2945 registry.category("services").add("pos", posService);