Debian Codegraph @

addons/point_of_sale/static/src/app/models/pos_order.js

raw
1 import { registry } from "@web/core/registry";
2 import { _t } from "@web/core/l10n/translation";
3 import { computeComboItems } from "./utils/compute_combo_items";
4 import { localization } from "@web/core/l10n/localization";
5 import { formatDate, serializeDateTime } from "@web/core/l10n/dates";
6 import { PosOrderAccounting } from "./accounting/pos_order_accounting";
7
8 const { DateTime } = luxon;
9
10 export class PosOrder extends PosOrderAccounting {
11 static pythonModel = "pos.order";
12
13 setup(vals) {
14 super.setup(vals);
15
16 if (!this.session_id?.id && (!this.finalized || !this.isSynced)) {
17 this.session_id = this.session;
18 }
19
20 // Data present in python model
21 this.name = vals.name || "/";
22 this.nb_print = vals.nb_print || 0;
23 this.to_invoice = vals.to_invoice || false;
24 this.setShippingDate(vals.shipping_date);
25 this.state = vals.state || "draft";
26
27 if (!vals.last_order_preparation_change) {
28 this.last_order_preparation_change = {
29 lines: {},
30 metadata: {},
31 general_customer_note: "",
32 internal_note: "",
33 sittingMode: 0,
34 };
35 } else {
36 this.last_order_preparation_change =
37 typeof vals.last_order_preparation_change === "object"
38 ? vals.last_order_preparation_change
39 : JSON.parse(vals.last_order_preparation_change);
40 }
41
42 this.general_customer_note = vals.general_customer_note || "";
43 this.internal_note = vals.internal_note || "";
44
45 if (!this.date_order) {
46 this.date_order = DateTime.now();
47 }
48 if (!this.user_id && this.models["res.users"]) {
49 this.user_id = this.user;
50 }
51 }
52
53 initState() {
54 super.initState();
55 // !!Keep all uiState in one object!!
56 this.uiState = {
57 unmerge: {},
58 lastPrints: [],
59 lineToRefund: {},
60 displayed: this.state !== "cancel",
61 booked: false,
62 screen_data: {},
63 selected_orderline_uuid: undefined,
64 selected_paymentline_uuid: undefined,
65 // Pos restaurant specific to most proper way is to override this
66 TipScreen: {
67 inputTipAmount: "",
68 },
69 requiredPartnerDetails: {},
70 };
71 }
72
73 get user() {
74 return this.models["res.users"].getFirst();
75 }
76
77 get company() {
78 return this.config.company_id;
79 }
80
81 get config() {
82 return this.models["pos.config"].getFirst();
83 }
84
85 get currency() {
86 return this.config.currency_id;
87 }
88
89 get pickingType() {
90 return this.models["stock.picking.type"].getFirst();
91 }
92
93 get session() {
94 return this.models["pos.session"].getFirst();
95 }
96
97 get finalized() {
98 return this.state !== "draft";
99 }
100
101 get totalQuantity() {
102 return this.lines.reduce((sum, line) => sum + line.getQuantity(), 0);
103 }
104
105 get isUnsyncedPaid() {
106 return this.finalized && !this.isSynced;
107 }
108
109 get originalSplittedOrder() {
110 return this.models["pos.order"].getBy("uuid", this.uiState.splittedOrderUuid);
111 }
112
113 get presetDate() {
114 return this.preset_time?.toFormat(localization.dateFormat) || "";
115 }
116
117 get isFutureDate() {
118 return this.preset_time?.startOf("day") > DateTime.now().startOf("day");
119 }
120
121 get presetTime() {
122 return this.preset_time && this.preset_time.isValid
123 ? this.preset_time.toFormat("HH:mm")
124 : false;
125 }
126
127 get invoiceName() {
128 return this.account_move?.name || "";
129 }
130
131 get presetDateTime() {
132 return this.preset_time?.isValid
133 ? this.preset_time.hasSame(this.date_order, "day")
134 ? this.preset_time.toFormat(localization.timeFormat)
135 : this.preset_time.toFormat(`${localization.dateFormat} ${localization.timeFormat}`)
136 : false;
137 }
138
139 get isCustomerRequired() {
140 if (this.partner_id) {
141 return false;
142 }
143 const splitPayment = this.payment_ids.some(
144 (payment) => payment.payment_method_id.split_transactions
145 );
146 const invalidPartnerPreset =
147 (this.preset_id?.needsName && !this.floating_order_name) ||
148 this.preset_id?.needsPartner;
149 return invalidPartnerPreset || this.isToInvoice() || Boolean(splitPayment);
150 }
151
152 get presetRequirementsFilled() {
153 const invalidCustomer =
154 (this.preset_id?.needsName && !(this.floating_order_name || this.partner_id)) ||
155 (this.preset_id?.needsPartner && !this.partner_id);
156 const isAddressMissing =
157 this.preset_id?.needsPartner && !(this.partner_id?.street || this.partner_id?.street2);
158 const invalidSlot = this.preset_id?.needsSlot && !this.preset_time;
159
160 if (invalidCustomer || isAddressMissing || invalidSlot) {
161 this.uiState.requiredPartnerDetails = {
162 field: _t(
163 invalidCustomer ? _t("Customer") : isAddressMissing ? _t("Address") : _t("Slot")
164 ),
165 message: invalidCustomer
166 ? _t("Please add a valid customer to the order.")
167 : isAddressMissing
168 ? _t("The selected customer needs an address.")
169 : _t("Please select a time slot before proceeding."),
170 };
171 return false;
172 }
173 return true;
174 }
175
176 get isRefund() {
177 return this.is_refund === true;
178 }
179
180 setPreset(preset) {
181 this.setPricelist(preset.pricelist_id || this.config.pricelist_id);
182 this.fiscal_position_id =
183 preset.fiscal_position_id || this.config.default_fiscal_position_id;
184 this.preset_id = preset;
185 if (preset.is_return) {
186 this.lines.forEach((l) => l.setQuantity(-Math.abs(l.getQuantity()), true));
187 }
188 }
189
190 getCashierName() {
191 return this.user_id?.name?.split(" ").at(0);
192 }
193 canPay() {
194 return this.lines.length;
195 }
196
197 get isBooked() {
198 return Boolean(this.uiState.booked || !this.isEmpty() || this.isSynced);
199 }
200
201 get hasChange() {
202 return this.lines.some((l) => l.uiState.hasChange);
203 }
204 /**
205 * This function is called after the order has been successfully sent to the preparation tool(s).
206 * In the future, this status should be separated between the different preparation tools,
207 * so that if one of them returns an error, it is possible to send the information back to it
208 * without impacting the other tools.
209 */
210 updateLastOrderChange() {
211 const orderlineIdx = [];
212 this.lines.forEach((line) => {
213 orderlineIdx.push(line.preparationKey);
214
215 if (this.last_order_preparation_change.lines[line.preparationKey]) {
216 this.last_order_preparation_change.lines[line.preparationKey] = {
217 ...this.last_order_preparation_change.lines[line.preparationKey],
218 quantity: line.getQuantity(),
219 note: line.getNote(),
220 customer_note: line.getCustomerNote(),
221 };
222 } else {
223 this.last_order_preparation_change.lines[line.preparationKey] = {
224 attribute_value_names: line.attribute_value_ids.map((a) => a.name),
225 uuid: line.uuid,
226 isCombo: Boolean(line?.combo_line_ids?.length),
227 combo_parent_uuid: line?.combo_parent_id?.uuid,
228 product_id: line.getProduct().id,
229 name: line.getFullProductName(),
230 basic_name: line.getProduct().name,
231 display_name: line.getProduct().display_name,
232 note: line.getNote(),
233 quantity: line.getQuantity(),
234 customer_note: line.getCustomerNote(),
235 };
236 }
237 line.setHasChange(false);
238 line.uiState.savedQuantity = line.getQuantity();
239 });
240 // Checks whether an orderline has been deleted from the order since it
241 // was last sent to the preparation tools or updated. If so we delete older changes.
242 for (const [key, change] of Object.entries(this.last_order_preparation_change.lines)) {
243 const orderline = this.models["pos.order.line"].getBy("uuid", change.uuid);
244 const lineNote = orderline?.note;
245 const changeNote = change?.note;
246 if (!orderline || (lineNote && changeNote && changeNote.trim() !== lineNote.trim())) {
247 delete this.last_order_preparation_change.lines[key];
248 }
249 }
250 this.last_order_preparation_change.general_customer_note = this.general_customer_note;
251 this.last_order_preparation_change.internal_note = this.internal_note;
252 this.last_order_preparation_change.sittingMode = this.preset_id?.id || 0;
253 this.last_order_preparation_change.metadata = {
254 serverDate: serializeDateTime(DateTime.now()),
255 };
256 this._markDirty();
257 }
258
259 isEmpty() {
260 return this.lines.length === 0;
261 }
262
263 updateSavedQuantity() {
264 this.lines.forEach((line) => line.updateSavedQuantity());
265 }
266
267 assertEditable() {
268 if (this.finalized) {
269 throw new Error("Finalized Order cannot be modified");
270 }
271 return true;
272 }
273
274 getOrderline(id) {
275 const orderlines = this.lines;
276 for (let i = 0; i < orderlines.length; i++) {
277 if (orderlines[i].id === id) {
278 return orderlines[i];
279 }
280 }
281 return null;
282 }
283
284 getLastOrderline() {
285 const orderlines = this.lines;
286 return this.lines.at(orderlines.length - 1);
287 }
288
289 getTip() {
290 const tip_product = this.config.tip_product_id;
291 const lines = this.lines;
292 if (!tip_product) {
293 return 0;
294 } else {
295 for (const line of lines) {
296 if (line.getProduct() === tip_product) {
297 return line.prices.total_excluded_currency;
298 }
299 }
300 return 0;
301 }
302 }
303
304 setPricelist(pricelist) {
305 this.pricelist_id = pricelist ? pricelist : false;
306
307 const lines_to_recompute = this.getLinesToCompute();
308
309 for (const line of lines_to_recompute) {
310 if (line.isLotTracked()) {
311 const related_lines = [];
312 const price = line.product_id.product_tmpl_id.getPrice(
313 pricelist,
314 line.getQuantity(),
315 line.getPriceExtra(),
316 false,
317 line.product_id,
318 line,
319 related_lines
320 );
321 related_lines.forEach((line) => line.setUnitPrice(price));
322 } else {
323 const newPrice = line.product_id.product_tmpl_id.getPrice(
324 pricelist,
325 line.getQuantity(),
326 line.getPriceExtra(),
327 false,
328 line.product_id
329 );
330 line.setUnitPrice(newPrice);
331 }
332 }
333
334 const attributes_prices = {};
335 const combo_parent_lines = this.lines.filter(
336 (line) => line.price_type === "original" && line.combo_line_ids?.length
337 );
338 for (const pLine of combo_parent_lines) {
339 const { childLineFree, childLineExtra } = this.getFreeAndExtraChildLines(pLine);
340 attributes_prices[pLine.id] = computeComboItems(
341 pLine.product_id,
342 childLineFree,
343 pricelist,
344 this.models["decimal.precision"].getAll(),
345 this.models["product.template.attribute.value"].getAllBy("id"),
346 childLineExtra,
347 this.config_id.currency_id
348 );
349 }
350 const combo_children_lines = this.lines.filter(
351 (line) => line.price_type === "original" && line.combo_parent_id
352 );
353 combo_children_lines.forEach((line) => {
354 const currentItem = attributes_prices[line.combo_parent_id.id].find(
355 (item) => item.combo_item_id.id === line.combo_item_id.id
356 );
357 line.setUnitPrice(currentItem.price_unit);
358 // Removing to be able to have extras that are the same as free products
359 attributes_prices[line.combo_parent_id.id].splice(
360 attributes_prices[line.combo_parent_id.id].indexOf(currentItem),
361 1
362 );
363 });
364 }
365
366 getFreeAndExtraChildLines(pLine) {
367 const childLineFree = [];
368 const childLineExtra = [];
369 const comboRemainingFree = {};
370 for (const cLine of pLine.combo_line_ids) {
371 if (!(cLine.combo_item_id.combo_id.id in comboRemainingFree)) {
372 comboRemainingFree[cLine.combo_item_id.combo_id.id] =
373 cLine.combo_item_id.combo_id.qty_free;
374 }
375 const newQty = comboRemainingFree[cLine.combo_item_id.combo_id.id] - cLine.qty;
376 const baseData = { combo_item_id: cLine.combo_item_id };
377 if (cLine.attribute_value_ids) {
378 baseData.configuration = { attribute_value_ids: cLine.attribute_value_ids };
379 }
380 if (cLine.qty) {
381 if (newQty >= 0) {
382 comboRemainingFree[cLine.combo_item_id.combo_id.id] = newQty;
383 childLineFree.push({ ...baseData, qty: cLine.qty });
384 } else {
385 childLineExtra.push({ ...baseData, qty: cLine.qty });
386 }
387 }
388 }
389 return { childLineFree, childLineExtra };
390 }
391
392 /**
393 * A wrapper around line.delete() that may potentially remove multiple orderlines.
394 * In core pos, it removes the linked combo lines. In other modules, it may remove
395 * other related lines, e.g. multiple reward lines in pos_loyalty module.
396 * @param {Orderline} line
397 * @returns {boolean} true if the line was removed, false otherwise
398 */
399 removeOrderline(line) {
400 const linesToRemove = line.getAllLinesInCombo();
401 for (const lineToRemove of linesToRemove) {
402 if (lineToRemove.refunded_orderline_id?.uuid in this.uiState.lineToRefund) {
403 delete this.uiState.lineToRefund[lineToRemove.refunded_orderline_id.uuid];
404 }
405
406 if (this.assertEditable()) {
407 lineToRemove.delete();
408 }
409 }
410 if (!this.lines.length) {
411 this.general_customer_note = ""; // reset general note on empty order
412 }
413 this.selectOrderline(this.getLastOrderline());
414 return true;
415 }
416
417 isSaleDisallowed(values, options) {
418 return this.isRefund && (!values.qty || values.qty > 0);
419 }
420
421 getSelectedOrderline() {
422 return this.lines.find((line) => line.uuid === this.uiState.selected_orderline_uuid);
423 }
424
425 getSelectedPaymentline() {
426 return this.payment_ids.find(
427 (line) => line.uuid === this.uiState.selected_paymentline_uuid
428 );
429 }
430
431 selectOrderline(line) {
432 if (line) {
433 this.uiState.selected_orderline_uuid = line.uuid;
434 } else {
435 this.uiState.selected_orderline_uuid = undefined;
436 }
437 }
438
439 deselectOrderline() {
440 if (this.uiState.selected_orderline_uuid) {
441 this.uiState.selected_orderline_uuid = undefined;
442 }
443 }
444
445 /* ---- Payment Lines --- */
446 addPaymentline(payment_method) {
447 this.assertEditable();
448 const existingCash = this.payment_ids.find((pl) => pl.payment_method_id.is_cash_count);
449
450 if (this.electronicPaymentInProgress()) {
451 return {
452 status: false,
453 data: _t("There is already an electronic payment in progress."),
454 };
455 }
456
457 if (existingCash && payment_method.is_cash_count) {
458 return { status: false, data: _t("There is already a cash payment line.") };
459 }
460
461 const totalAmountDue = this.getDefaultAmountDueToPayIn(payment_method);
462 const newPaymentLine = this.models["pos.payment"].create({
463 pos_order_id: this,
464 payment_method_id: payment_method,
465 });
466 this.selectPaymentline(newPaymentLine);
467 newPaymentLine.setAmount(totalAmountDue);
468
469 if (
470 (payment_method.payment_terminal && !this.isRefund) ||
471 payment_method.payment_method_type === "qr_code"
472 ) {
473 newPaymentLine.setPaymentStatus("pending");
474 }
475 return { status: true, data: newPaymentLine };
476 }
477
478 getPaymentlineByUuid(uuid) {
479 var lines = this.payment_ids;
480 return lines.find(function (line) {
481 return line.uuid === uuid;
482 });
483 }
484
485 removePaymentline(line) {
486 this.assertEditable();
487
488 if (this.getSelectedPaymentline() === line) {
489 this.selectPaymentline(undefined);
490 }
491
492 line.delete({ backend: true });
493 }
494
495 selectPaymentline(line) {
496 if (line) {
497 this.uiState.selected_paymentline_uuid = line?.uuid;
498 } else {
499 this.uiState.selected_paymentline_uuid = undefined;
500 }
501 }
502
503 electronicPaymentInProgress() {
504 return this.payment_ids.some(function (pl) {
505 if (pl.payment_status) {
506 return !["done", "reversed"].includes(pl.payment_status);
507 } else {
508 return false;
509 }
510 });
511 }
512
513 _getIgnoredProductIdsTotalDiscount() {
514 return [];
515 }
516
517 getTotalDiscount() {
518 const ignored_product_ids = this._getIgnoredProductIdsTotalDiscount();
519 return this.currency.round(
520 this.lines.reduce((sum, orderLine) => {
521 if (!ignored_product_ids.includes(orderLine.product_id.id)) {
522 const data = orderLine.order_id.prices.baseLineByLineUuids[orderLine.uuid];
523 sum += data.tax_details.discount_amount;
524 if (
525 orderLine.displayDiscountPolicy() === "without_discount" &&
526 !(orderLine.price_type === "manual") &&
527 orderLine.discount == 0
528 ) {
529 sum +=
530 (orderLine.displayPriceUnit - orderLine.displayPriceUnitNoDiscount) *
531 orderLine.getQuantity();
532 }
533 }
534 return sum;
535 }, 0)
536 );
537 }
538
539 isPaid() {
540 return this.orderHasZeroRemaining;
541 }
542
543 isRefundInProcess() {
544 return (
545 this.isRefund &&
546 this.payment_ids.some(
547 (pl) => pl.payment_method_id.use_payment_terminal && pl.payment_status !== "done"
548 )
549 );
550 }
551
552 isPaidWithCash() {
553 return !!this.payment_ids.find(function (pl) {
554 return pl.payment_method_id.is_cash_count;
555 });
556 }
557
558 getTotalCost() {
559 return this.lines.reduce(function (sum, orderLine) {
560 return sum + orderLine.getTotalCost();
561 }, 0);
562 }
563
564 /* ---- Invoice --- */
565 setToInvoice(to_invoice) {
566 this.assertEditable();
567 this.to_invoice = to_invoice;
568 }
569
570 isToInvoice() {
571 return this.to_invoice;
572 }
573
574 /* ---- Partner --- */
575 // the partner related to the current order.
576 setPartner(partner) {
577 this.assertEditable();
578 this.partner_id = partner;
579 this.updatePricelistAndFiscalPosition(partner);
580 if (partner.is_company) {
581 this.setToInvoice(true);
582 }
583 }
584
585 getPartner() {
586 return this.partner_id;
587 }
588
589 getPartnerName() {
590 return this.partner_id ? this.partner_id.name : "";
591 }
592
593 getCardHolderName() {
594 const card_payment_line = this.payment_ids.find((pl) => pl.cardholder_name);
595 return card_payment_line ? card_payment_line.cardholder_name : "";
596 }
597
598 /* ---- Screen Status --- */
599 // the order also stores the screen status, as the PoS supports
600 // different active screens per order. This method is used to
601 // store the screen status.
602 setScreenData(value) {
603 this.uiState.screen_data["value"] = value;
604 }
605
606 getCurrentScreenData() {
607 return this.uiState.screen_data["value"] ?? { name: "ProductScreen" };
608 }
609
610 //see setScreenData
611 getScreenData() {
612 const screen = this.uiState?.screen_data["value"];
613 // If no screen data is saved
614 // no payment line -> product screen
615 // with payment line -> payment screen
616 if (!screen) {
617 if (!this.finalized && this.payment_ids.length > 0) {
618 return { name: "PaymentScreen" };
619 } else if (!this.finalized) {
620 return { name: "ProductScreen" };
621 }
622 }
623 if (!this.finalized && this.payment_ids.length > 0) {
624 return { name: "PaymentScreen" };
625 }
626
627 return screen || { name: "" };
628 }
629
630 waitForPushOrder() {
631 return false;
632 }
633
634 updatePricelistAndFiscalPosition(newPartner) {
635 let newPartnerPricelist, newPartnerFiscalPosition;
636 const defaultFiscalPosition = this.models["account.fiscal.position"].find(
637 (position) => position.id === this.config.default_fiscal_position_id?.id
638 );
639
640 if (newPartner) {
641 newPartnerFiscalPosition = newPartner.fiscal_position_id
642 ? this.models["account.fiscal.position"].find(
643 (position) => position.id === newPartner.fiscal_position_id?.id
644 )
645 : defaultFiscalPosition;
646 newPartnerPricelist =
647 this.models["product.pricelist"].find(
648 (pricelist) => pricelist.id === newPartner.property_product_pricelist?.id
649 ) || this.config.pricelist_id;
650 } else {
651 newPartnerFiscalPosition = defaultFiscalPosition;
652 newPartnerPricelist = this.config.pricelist_id;
653 }
654
655 if (!this.config.use_presets || !this.preset_id?.fiscal_position_id) {
656 this.fiscal_position_id = newPartnerFiscalPosition;
657 }
658
659 if (!this.config.use_presets || !this.preset_id?.pricelist_id) {
660 this.setPricelist(newPartnerPricelist);
661 }
662 }
663
664 /* ---- Ship later --- */
665 //FIXME remove this
666 setShippingDate(shippingDate) {
667 this.shipping_date = shippingDate;
668 }
669 //FIXME remove this
670 getShippingDate() {
671 return formatDate(this.shipping_date);
672 }
673
674 getHasRefundLines() {
675 for (const line of this.lines) {
676 if (line.refunded_orderline_id) {
677 return true;
678 }
679 }
680 return false;
681 }
682
683 /**
684 * Returns false if the current order is empty and has no payments.
685 * @returns {boolean}
686 */
687 _isValidEmptyOrder() {
688 if (this.lines.length == 0) {
689 return this.payment_ids.length != 0;
690 } else {
691 return true;
692 }
693 }
694
695 canBeValidated() {
696 return this.isPaid() && this._isValidEmptyOrder() && !this.isCustomerRequired;
697 }
698
699 // NOTE: Overrided in pos_loyalty to put loyalty rewards at this end of array.
700 getOrderlines() {
701 return this.lines;
702 }
703
704 serializeForORM(opts = {}) {
705 const data = super.serializeForORM(opts);
706 if (
707 data.last_order_preparation_change &&
708 typeof data.last_order_preparation_change === "object"
709 ) {
710 data.last_order_preparation_change = JSON.stringify(data.last_order_preparation_change);
711 }
712 return data;
713 }
714
715 get floatingOrderName() {
716 return this.floating_order_name || this.tracking_number.toString() || "";
717 }
718
719 sortBySequenceAndCategory(a, b) {
720 const seqA = a.product_id?.pos_categ_ids[0]?.sequence ?? 0;
721 const seqB = b.product_id?.pos_categ_ids[0]?.sequence ?? 0;
722 const pos_categ_id_A = a.product_id?.pos_categ_ids[0]?.id ?? 0;
723 const pos_categ_id_B = b.product_id?.pos_categ_ids[0]?.id ?? 0;
724
725 if (seqA !== seqB) {
726 return seqA - seqB;
727 }
728 return pos_categ_id_A - pos_categ_id_B;
729 }
730
731 get discountLines() {
732 return this.lines?.filter(
733 (line) => line.product_id.id === this.config.discount_product_id?.id
734 );
735 }
736
737 get globalDiscountPc() {
738 return this.discountLines?.[0]?.extra_tax_data?.discount_percentage || 0;
739 }
740
741 getName() {
742 let name = this.floatingOrderName || "";
743 if (this.isRefund) {
744 name += _t(" (Refund)");
745 }
746 return name;
747 }
748 setGeneralCustomerNote(note) {
749 this.general_customer_note = note || "";
750 }
751 setInternalNote(note) {
752 this.internal_note = note || "";
753 }
754
755 get showChange() {
756 return !this.currency.isZero(this.change) && this.finalized;
757 }
758
759 getLinesToCompute() {
760 return this.lines.filter(
761 (line) =>
762 line.price_type === "original" &&
763 !(line.combo_line_ids?.length || line.combo_parent_id)
764 );
765 }
766 }
767
768 registry.category("pos_available_models").add(PosOrder.pythonModel, PosOrder);