-
Notifications
You must be signed in to change notification settings - Fork 23.2k
/
models.js
2810 lines (2687 loc) · 102 KB
/
models.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @odoo-module */
import { constructFullProductName, random5Chars, uuidv4, qrCodeSrc } from "@point_of_sale/utils";
// FIXME POSREF - unify use of native parseFloat and web's parseFloat. We probably don't need the native version.
import { parseFloat as oParseFloat } from "@web/views/fields/parsers";
import {
formatDate,
formatDateTime,
serializeDateTime,
deserializeDate,
deserializeDateTime,
} from "@web/core/l10n/dates";
import {
formatFloat,
roundDecimals as round_di,
roundPrecision as round_pr,
floatIsZero,
} from "@web/core/utils/numbers";
import { ErrorPopup } from "@point_of_sale/app/errors/popups/error_popup";
import { ProductConfiguratorPopup } from "@point_of_sale/app/store/product_configurator_popup/product_configurator_popup";
import { ComboConfiguratorPopup } from "./combo_configurator_popup/combo_configurator_popup";
import { ConfirmPopup } from "@point_of_sale/app/utils/confirm_popup/confirm_popup";
import { _t } from "@web/core/l10n/translation";
import { renderToElement } from "@web/core/utils/render";
import { ProductCustomAttribute } from "./models/product_custom_attribute";
import { omit } from "@web/core/utils/objects";
const { DateTime } = luxon;
/**
* If optimization is needed, then we should implement this
* using a Balanced Binary Tree to behave like an Object and an Array.
* But behaving like Object (indexed by cid) might not be
* needed. Let's see how it turns out.
*/
export class PosCollection extends Array {
getByCID(cid) {
return this.find((item) => item.cid == cid);
}
add(item) {
this.push(item);
}
remove(item) {
const index = this.findIndex((_item) => item.cid == _item.cid);
if (index < 0) {
return index;
}
this.splice(index, 1);
return index;
}
reset() {
this.length = 0;
}
at(index) {
return this[index];
}
}
let nextId = 0;
class PosModel {
/**
* Create an object with cid. If no cid is in the defaultObj,
* cid is computed based on its id. Override _getCID if you
* don't want this default calculation of cid.
* @param {Object?} defaultObj its props copied to this instance.
*/
constructor() {
this.setup(...arguments);
}
// To be used by Model patches to patch constructor
setup(defaultObj) {
defaultObj = defaultObj || {};
if (!defaultObj.cid) {
defaultObj.cid = this._getCID(defaultObj);
}
Object.assign(this, defaultObj);
}
/**
* Default cid getter. Used as local identity of this object.
* @param {Object} obj
*/
_getCID(obj) {
if (obj.id) {
if (typeof obj.id == "string") {
return obj.id;
} else if (typeof obj.id == "number") {
return `c${obj.id}`;
}
}
return `c${nextId++}`;
}
}
export class Product extends PosModel {
constructor(obj) {
super(obj);
this.parent_category_ids = [];
let category = this.categ.parent;
while (category) {
this.parent_category_ids.push(category.id);
category = category.parent;
}
}
isAllowOnlyOneLot() {
const productUnit = this.get_unit();
return this.tracking === "lot" || !productUnit || !productUnit.is_pos_groupable;
}
/**
* @returns {string}
*/
getImageUrl() {
return (
(this.image_128 &&
`/web/image?model=product.product&field=image_128&id=${this.id}&unique=${this.write_date}`) ||
""
);
}
isTracked() {
return (
["serial", "lot"].includes(this.tracking) &&
(this.pos.picking_type.use_create_lots || this.pos.picking_type.use_existing_lots)
);
}
get_unit() {
var unit_id = this.uom_id;
if (!unit_id) {
return undefined;
}
unit_id = unit_id[0];
if (!this.pos) {
return undefined;
}
return this.pos.units_by_id[unit_id];
}
async _onScaleNotAvailable() {}
get isScaleAvailable() {
return true;
}
getFormattedUnitPrice() {
const formattedUnitPrice = this.env.utils.formatCurrency(this.get_display_price());
if (this.to_weight) {
return `${formattedUnitPrice}/${this.get_unit().name}`;
} else {
return formattedUnitPrice;
}
}
async openConfigurator({ initQuantity = 1 }) {
const attributes = this.attribute_line_ids
.map((id) => this.pos.attributes_by_ptal_id[id])
.filter((attr) => attr !== undefined);
return await this.env.services.popup.add(ProductConfiguratorPopup, {
product: this,
attributes: attributes,
quantity: initQuantity,
});
}
isConfigurable() {
return this.attribute_line_ids.some((id) => id in this.pos.attributes_by_ptal_id);
}
async getAddProductOptions(code) {
let price_extra = 0.0;
let draftPackLotLines, packLotLinesToEdit, attribute_value_ids;
let quantity = 1;
let comboLines = [];
let attribute_custom_values = {};
if (code && this.pos.db.product_packaging_by_barcode[code.code]) {
quantity = this.pos.db.product_packaging_by_barcode[code.code].qty;
}
if (this.isConfigurable()) {
const { confirmed, payload } = await this.openConfigurator({ initQuantity: quantity });
if (confirmed) {
attribute_value_ids = payload.attribute_value_ids;
attribute_custom_values = payload.attribute_custom_values;
price_extra += payload.price_extra;
quantity = payload.quantity;
} else {
return;
}
}
if (this.combo_ids.length) {
const { confirmed, payload } = await this.env.services.popup.add(
ComboConfiguratorPopup,
{ product: this, keepBehind: true }
);
if (!confirmed) {
return;
}
comboLines = payload;
}
// Gather lot information if required.
if (this.isTracked()) {
packLotLinesToEdit =
(!this.isAllowOnlyOneLot() &&
this.pos.selectedOrder
.get_orderlines()
.filter((line) => !line.get_discount())
.find((line) => line.product.id === this.id)
?.getPackLotLinesToEdit()) ||
[];
// if the lot information exists in the barcode, we don't need to ask it from the user.
if (code && code.type === "lot") {
// consider the old and new packlot lines
const modifiedPackLotLines = Object.fromEntries(
packLotLinesToEdit.filter((item) => item.id).map((item) => [item.id, item.text])
);
const newPackLotLines = [{ lot_name: code.code }];
draftPackLotLines = { modifiedPackLotLines, newPackLotLines };
} else {
draftPackLotLines = await this.pos.getEditedPackLotLines(
this.isAllowOnlyOneLot(),
packLotLinesToEdit,
this.display_name
);
}
if (!draftPackLotLines) {
return;
}
}
// Take the weight if necessary.
if (this.to_weight && this.pos.config.iface_electronic_scale) {
// Show the ScaleScreen to weigh the product.
if (this.isScaleAvailable) {
const product = this;
const { confirmed, payload } = await this.env.services.pos.showTempScreen(
"ScaleScreen",
{
product,
}
);
if (confirmed) {
quantity = payload.weight;
} else {
// do not add the product;
return;
}
} else {
await this._onScaleNotAvailable();
}
}
return {
draftPackLotLines,
quantity,
attribute_custom_values,
price_extra,
comboLines,
attribute_value_ids,
};
}
isPricelistItemUsable(item, date) {
const categories = this.parent_category_ids.concat(this.categ.id);
return (
(!item.categ_id || categories.includes(item.categ_id[0])) &&
(!item.date_start || deserializeDate(item.date_start) <= date) &&
(!item.date_end || deserializeDate(item.date_end) >= date)
);
}
// Port of _get_product_price on product.pricelist.
//
// Anything related to UOM can be ignored, the POS will always use
// the default UOM set on the product and the user cannot change
// it.
//
// Pricelist items do not have to be sorted. All
// product.pricelist.item records are loaded with a search_read
// and were automatically sorted based on their _order by the
// ORM. After that they are added in this order to the pricelists.
get_price(pricelist, quantity, price_extra = 0, recurring = false) {
const date = DateTime.now();
// In case of nested pricelists, it is necessary that all pricelists are made available in
// the POS. Display a basic alert to the user in the case where there is a pricelist item
// but we can't load the base pricelist to get the price when calling this method again.
// As this method is also call without pricelist available in the POS, we can't just check
// the absence of pricelist.
if (recurring && !pricelist) {
alert(
_t(
"An error occurred when loading product prices. " +
"Make sure all pricelists are available in the POS."
)
);
}
const rules = !pricelist
? []
: (this.applicablePricelistItems[pricelist.id] || []).filter((item) =>
this.isPricelistItemUsable(item, date)
);
let price = this.lst_price + (price_extra || 0);
const rule = rules.find((rule) => !rule.min_quantity || quantity >= rule.min_quantity);
if (!rule) {
return price;
}
if (rule.base === "pricelist") {
const base_pricelist = this.pos.pricelists.find(
(pricelist) => pricelist.id === rule.base_pricelist_id[0]
);
if (base_pricelist) {
price = this.get_price(base_pricelist, quantity, 0, true);
}
} else if (rule.base === "standard_price") {
price = this.standard_price;
}
if (rule.compute_price === "fixed") {
price = rule.fixed_price;
} else if (rule.compute_price === "percentage") {
price = price - price * (rule.percent_price / 100);
} else {
var price_limit = price;
price -= price * (rule.price_discount / 100);
if (rule.price_round) {
price = round_pr(price, rule.price_round);
}
if (rule.price_surcharge) {
price += rule.price_surcharge;
}
if (rule.price_min_margin) {
price = Math.max(price, price_limit + rule.price_min_margin);
}
if (rule.price_max_margin) {
price = Math.min(price, price_limit + rule.price_max_margin);
}
}
// This return value has to be rounded with round_di before
// being used further. Note that this cannot happen here,
// because it would cause inconsistencies with the backend for
// pricelist that have base == 'pricelist'.
return price;
}
get_display_price({
pricelist = this.pos.getDefaultPricelist(),
quantity = 1,
price = this.get_price(pricelist, quantity),
iface_tax_included = this.pos.config.iface_tax_included,
} = {}) {
const order = this.pos.get_order();
const taxes = this.pos.get_taxes_after_fp(this.taxes_id, order && order.fiscal_position);
const currentTaxes = this.pos.getTaxesByIds(this.taxes_id);
const priceAfterFp = this.pos.computePriceAfterFp(price, currentTaxes);
const allPrices = this.pos.compute_all(taxes, priceAfterFp, 1, this.pos.currency.rounding);
if (iface_tax_included === "total") {
return allPrices.total_included;
} else {
return allPrices.total_excluded;
}
}
}
var orderline_id = 1;
// An orderline represent one element of the content of a customer's shopping cart.
// An orderline contains a product, its quantity, its price, discount. etc.
// An Order contains zero or more Orderlines.
export class Orderline extends PosModel {
setup(_defaultObj, options) {
super.setup(...arguments);
this.pos = options.pos;
this.order = options.order;
this.price_type = options.price_type;
this.uuid = this.uuid || uuidv4();
this.price_type = options.price_type || "original";
if (options.json) {
try {
this.init_from_JSON(options.json);
} catch {
console.error(
"ERROR: attempting to recover product ID",
options.json.product_id[0],
"not available in the point of sale. Correct the product or clean the browser cache."
);
}
return;
}
this.product = options.product;
this.tax_ids = options.tax_ids;
this.set_product_lot(this.product);
options.quantity ? this.set_quantity(options.quantity) : this.set_quantity(1);
this.discount = 0;
this.note = "";
this.custom_attribute_value_ids = [];
this.hasChange = false;
this.skipChange = false;
this.discountStr = "0";
this.selected = false;
this.price_extra = 0;
this.full_product_name = "";
this.id = orderline_id++;
this.customerNote = this.customerNote || "";
this.saved_quantity = 0;
if (options.price) {
this.set_unit_price(options.price);
} else {
this.set_unit_price(this.product.get_price(this.order.pricelist, this.get_quantity()));
}
}
init_from_JSON(json) {
this.product = this.pos.db.get_product_by_id(json.product_id);
this.set_product_lot(this.product);
this.price = json.price_unit;
this.price_type = json.price_type || "original";
this.set_discount(json.discount);
this.set_quantity(json.qty, "do not recompute unit price");
this.attribute_value_ids = json.attribute_value_ids || [];
this.set_price_extra(json.price_extra);
this.custom_attribute_value_ids = json.custom_attribute_value_ids.map((attr) => {
if (attr.length > 0) {
attr = attr[2];
}
return new ProductCustomAttribute(attr);
});
this.set_full_product_name();
this.id = json.server_id || json.id || orderline_id++;
orderline_id = Math.max(this.id + 1, orderline_id);
var pack_lot_lines = json.pack_lot_ids;
for (var i = 0; i < pack_lot_lines.length; i++) {
var packlotline = pack_lot_lines[i][2];
var pack_lot_line = new Packlotline(
{ env: this.env },
{ json: { ...packlotline, order_line: this } }
);
this.pack_lot_lines.add(pack_lot_line);
}
this.tax_ids = json.tax_ids && json.tax_ids.length !== 0 ? json.tax_ids[0][2] : undefined;
this.set_customer_note(json.customer_note);
this.refunded_qty = json.refunded_qty;
this.refunded_orderline_id = json.refunded_orderline_id;
this.saved_quantity = json.qty;
this.uuid = json.uuid;
this.skipChange = json.skip_change;
this.combo_line_ids = json.combo_line_ids;
this.combo_parent_id = json.combo_parent_id;
this.comboLine = this.pos.db.combo_line_by_id[json.combo_line_id];
}
clone() {
var orderline = new Orderline(
{ env: this.env },
{
pos: this.pos,
order: this.order,
product: this.product,
price: this.price,
}
);
orderline.order = null;
orderline.custom_attribute_value_ids = this.custom_attribute_value_ids;
orderline.quantity = this.quantity;
orderline.quantityStr = this.quantityStr;
orderline.discount = this.discount;
orderline.price = this.price;
orderline.selected = false;
orderline.price_type = this.price_type;
orderline.customerNote = this.customerNote;
return orderline;
}
getDisplayClasses() {
return {};
}
getPackLotLinesToEdit(isAllowOnlyOneLot) {
const currentPackLotLines = this.pack_lot_lines;
let nExtraLines = Math.abs(this.quantity) - currentPackLotLines.length;
nExtraLines = Math.ceil(nExtraLines);
nExtraLines = nExtraLines > 0 ? nExtraLines : 1;
const tempLines = currentPackLotLines
.map((lotLine) => ({
id: lotLine.cid,
text: lotLine.lot_name,
}))
.concat(
Array.from(Array(nExtraLines)).map((_) => ({
text: "",
}))
);
return isAllowOnlyOneLot ? [tempLines[0]] : tempLines;
}
// What if a number different from 1 (or -1) is specified
// to an orderline that has product tracked by lot? Lot tracking (based
// on the current implementation) requires that 1 item per orderline is
// allowed.
async editPackLotLines() {
const isAllowOnlyOneLot = this.product.isAllowOnlyOneLot();
const editedPackLotLines = await this.pos.getEditedPackLotLines(
isAllowOnlyOneLot,
this.getPackLotLinesToEdit(isAllowOnlyOneLot),
this.product.display_name
);
if (!editedPackLotLines) {
return;
}
this.setPackLotLines(editedPackLotLines);
this.order.select_orderline(this);
}
/**
* @param { modifiedPackLotLines, newPackLotLines }
* @param {Object} modifiedPackLotLines key-value pair of String (the cid) & String (the new lot_name)
* @param {Array} newPackLotLines array of { lot_name: String }
*/
setPackLotLines({ modifiedPackLotLines, newPackLotLines, setQuantity = true }) {
// Set the new values for modified lot lines.
const lotLinesToRemove = [];
for (const lotLine of this.pack_lot_lines) {
const modifiedLotName = modifiedPackLotLines[lotLine.cid];
if (modifiedLotName) {
lotLine.lot_name = modifiedLotName;
} else {
// We should not call lotLine.remove() here because
// we don't want to mutate the array while looping thru it.
lotLinesToRemove.push(lotLine);
}
}
// Remove those that needed to be removed.
for (const lotLine of lotLinesToRemove) {
this.pack_lot_lines.remove(lotLine);
}
// Create new pack lot lines.
let newPackLotLine;
for (const newLotLine of newPackLotLines) {
newPackLotLine = new Packlotline({ env: this.env }, { order_line: this });
newPackLotLine.lot_name = newLotLine.lot_name;
this.pack_lot_lines.add(newPackLotLine);
}
// Set the quantity of the line based on number of pack lots.
if (!this.product.to_weight && setQuantity) {
this.set_quantity_by_lot();
}
}
set_product_lot(product) {
this.has_product_lot = product.tracking !== "none";
this.pack_lot_lines = this.has_product_lot && new PosCollection();
}
getNote() {
return this.note;
}
setNote(note) {
this.note = note;
}
setHasChange(isChange) {
this.hasChange = isChange;
}
// sets a discount [0,100]%
set_discount(discount) {
var parsed_discount =
typeof discount === "number"
? discount
: isNaN(parseFloat(discount))
? 0
: oParseFloat("" + discount);
var disc = Math.min(Math.max(parsed_discount || 0, 0), 100);
this.discount = disc;
this.discountStr = "" + disc;
}
// returns the discount [0,100]%
get_discount() {
return this.discount;
}
get_discount_str() {
return this.discountStr;
}
set_price_extra(price_extra) {
this.price_extra = parseFloat(price_extra) || 0.0;
}
set_full_product_name() {
this.full_product_name = this.product.display_name;
}
get_price_extra() {
return this.price_extra;
}
updateSavedQuantity() {
this.saved_quantity = this.quantity;
}
// sets the quantity of the product. The quantity will be rounded according to the
// product's unity of measure properties. Quantities greater than zero will not get
// rounded to zero
// Return true if successfully set the quantity, otherwise, return false.
set_quantity(quantity, keep_price) {
this.order.assert_editable();
var quant =
typeof quantity === "number" ? quantity : oParseFloat("" + (quantity ? quantity : 0));
if (this.refunded_orderline_id in this.pos.toRefundLines) {
const toRefundDetail = this.pos.toRefundLines[this.refunded_orderline_id];
const maxQtyToRefund =
toRefundDetail.orderline.qty - toRefundDetail.orderline.refundedQty;
if (quant > 0) {
this.env.services.popup.add(ErrorPopup, {
title: _t("Positive quantity not allowed"),
body: _t(
"Only a negative quantity is allowed for this refund line. Click on +/- to modify the quantity to be refunded."
),
});
return false;
} else if (quant == 0) {
toRefundDetail.qty = 0;
} else if (-quant <= maxQtyToRefund) {
toRefundDetail.qty = -quant;
} else {
this.env.services.popup.add(ErrorPopup, {
title: _t("Greater than allowed"),
body: _t(
"The requested quantity to be refunded is higher than the refundable quantity of %s.",
this.env.utils.formatProductQty(maxQtyToRefund)
),
});
return false;
}
}
var unit = this.get_unit();
if (unit) {
if (unit.rounding) {
var decimals = this.pos.dp["Product Unit of Measure"];
var rounding = Math.max(unit.rounding, Math.pow(10, -decimals));
this.quantity = round_pr(quant, rounding);
this.quantityStr = formatFloat(this.quantity, {
digits: [69, decimals],
});
} else {
this.quantity = round_pr(quant, 1);
this.quantityStr = this.quantity.toFixed(0);
}
} else {
this.quantity = quant;
this.quantityStr = "" + this.quantity;
}
// just like in sale.order changing the quantity will recompute the unit price
if (!keep_price && this.price_type === "original") {
this.set_unit_price(
this.product.get_price(
this.order.pricelist,
this.get_quantity(),
this.get_price_extra()
)
);
this.order.fix_tax_included_price(this);
}
return true;
}
// return the quantity of product
get_quantity() {
return this.quantity;
}
get_quantity_str() {
return this.quantityStr;
}
get_quantity_str_with_unit() {
if (this.is_pos_groupable()) {
return this.quantityStr + " " + this.get_unit().name;
} else {
return this.quantityStr;
}
}
get_lot_lines() {
return this.pack_lot_lines && this.pack_lot_lines;
}
get_required_number_of_lots() {
var lots_required = 1;
if (this.product.tracking == "serial") {
lots_required = Math.abs(this.quantity);
}
return lots_required;
}
get_valid_lots() {
return this.pack_lot_lines.filter((item) => {
return item.lot_name;
});
}
set_quantity_by_lot() {
var valid_lots_quantity = this.get_valid_lots().length;
if (this.quantity < 0) {
valid_lots_quantity = -valid_lots_quantity;
}
this.set_quantity(valid_lots_quantity);
}
has_valid_product_lot() {
if (!this.has_product_lot) {
return true;
}
var valid_product_lot = this.get_valid_lots();
return this.get_required_number_of_lots() === valid_product_lot.length;
}
// return the unit of measure of the product
get_unit() {
return this.product.get_unit();
}
// return the product of this orderline
get_product() {
return this.product;
}
get_full_product_name() {
return this.full_product_name || this.product.display_name;
}
/**
* Return the full product name with variant details.
*
* e.g. Desk Organiser product with variant:
* - Size: S
* - Fabric: Plastic
*
* -> "Desk Organiser (S, Plastic)"
* @returns {string}
*/
get_full_product_name_with_variant() {
return constructFullProductName(
this,
this.pos.db.attribute_value_by_id,
this.product.display_name
);
}
// selects or deselects this orderline
set_selected(selected) {
this.selected = selected;
// this trigger also triggers the change event of the collection.
}
// returns true if this orderline is selected
is_selected() {
return this.selected;
}
// when we add an new orderline we want to merge it with the last line to see reduce the number of items
// in the orderline. This returns true if it makes sense to merge the two
can_be_merged_with(orderline) {
var price = parseFloat(
round_di(this.price || 0, this.pos.dp["Product Price"]).toFixed(
this.pos.dp["Product Price"]
)
);
var order_line_price = orderline
.get_product()
.get_price(orderline.order.pricelist, this.get_quantity());
order_line_price = round_di(
orderline.compute_fixed_price(order_line_price),
this.pos.currency.decimal_places
);
let hasSameAttributes = Object.keys(Object(orderline.attribute_value_ids)).length === Object.keys(Object(this.attribute_value_ids)).length;
if(hasSameAttributes && Object(orderline.attribute_value_ids)?.length && Object(this.attribute_value_ids)?.length) {
hasSameAttributes = orderline.attribute_value_ids.every((value, index) => value === this.attribute_value_ids[index]);
}
return (
!this.skipChange &&
orderline.getNote() === this.getNote() &&
this.get_product().id === orderline.get_product().id &&
this.get_unit() &&
this.is_pos_groupable() &&
// don't merge discounted orderlines
this.get_discount() === 0 &&
floatIsZero(
price - order_line_price - orderline.get_price_extra(),
this.pos.currency.decimal_places
) &&
!(
this.product.tracking === "lot" &&
(this.pos.picking_type.use_create_lots || this.pos.picking_type.use_existing_lots)
) &&
this.full_product_name === orderline.full_product_name &&
orderline.get_customer_note() === this.get_customer_note() &&
!this.refunded_orderline_id &&
!this.isPartOfCombo() &&
!orderline.isPartOfCombo() &&
hasSameAttributes
);
}
is_pos_groupable() {
return this.get_unit()?.is_pos_groupable && !this.isPartOfCombo();
}
merge(orderline) {
this.order.assert_editable();
this.set_quantity(this.get_quantity() + orderline.get_quantity());
}
export_as_JSON() {
var pack_lot_ids = [];
if (this.has_product_lot) {
this.pack_lot_lines.forEach((item) => {
return pack_lot_ids.push([0, 0, item.export_as_JSON()]);
});
}
return {
uuid: this.uuid,
skip_change: this.skipChange,
custom_attribute_value_ids: this.custom_attribute_value_ids.map((attr) => [0, 0, attr]),
qty: this.get_quantity(),
price_unit: this.get_unit_price(),
price_subtotal: this.get_price_without_tax(),
price_subtotal_incl: this.get_price_with_tax(),
discount: this.get_discount(),
product_id: this.get_product().id,
tax_ids: [[6, false, this.get_applicable_taxes().map((tax) => tax.id)]],
id: this.id,
pack_lot_ids: pack_lot_ids,
attribute_value_ids: this.attribute_value_ids || [],
full_product_name: this.get_full_product_name(),
price_extra: this.get_price_extra(),
customer_note: this.get_customer_note(),
refunded_orderline_id: this.refunded_orderline_id,
price_type: this.price_type,
combo_line_ids: this.comboLines?.map((line) => line.id || line.cid),
combo_parent_id: this.comboParent?.id || this.comboParent?.cid,
combo_line_id: this.comboLine?.id,
};
}
// changes the base price of the product for this orderline
set_unit_price(price) {
this.order.assert_editable();
var parsed_price = !isNaN(price)
? price
: isNaN(parseFloat(price))
? 0
: oParseFloat("" + price);
this.price = round_di(parsed_price || 0, this.pos.dp["Product Price"]);
}
get_unit_price() {
var digits = this.pos.dp["Product Price"];
// round and truncate to mimic _symbol_set behavior
return parseFloat(round_di(this.price || 0, digits).toFixed(digits));
}
get_unit_display_price() {
if (this.pos.config.iface_tax_included === "total") {
return this.get_all_prices(1).priceWithTax;
} else {
return this.get_all_prices(1).priceWithoutTax;
}
}
/**
* This is the price that will appear as striked through.
* @returns {number | false}
*/
get_old_unit_display_price() {
return (
this.display_discount_policy() === "without_discount" &&
this.env.utils.roundCurrency(this.get_unit_display_price()) <
this.env.utils.roundCurrency(this.get_taxed_lst_unit_price()) &&
this.get_taxed_lst_unit_price()
);
}
getUnitDisplayPriceBeforeDiscount() {
if (this.pos.config.iface_tax_included === "total") {
return this.get_all_prices(1).priceWithTaxBeforeDiscount;
} else {
return this.get_all_prices(1).priceWithoutTaxBeforeDiscount;
}
}
get_base_price() {
var rounding = this.pos.currency.rounding;
return round_pr(
this.get_unit_price() * this.get_quantity() * (1 - this.get_discount() / 100),
rounding
);
}
get_display_price_one() {
var rounding = this.pos.currency.rounding;
var price_unit = this.get_unit_price();
if (this.pos.config.iface_tax_included !== "total") {
return round_pr(price_unit * (1.0 - this.get_discount() / 100.0), rounding);
} else {
var product = this.get_product();
var taxes_ids = this.tax_ids || product.taxes_id;
var product_taxes = this.pos.get_taxes_after_fp(taxes_ids, this.order.fiscal_position);
var all_taxes = this.compute_all(
product_taxes,
price_unit,
1,
this.pos.currency.rounding
);
return round_pr(all_taxes.total_included * (1 - this.get_discount() / 100), rounding);
}
}
get_display_price() {
if (this.pos.config.iface_tax_included === "total") {
return this.get_price_with_tax();
} else {
return this.get_price_without_tax();
}
}
get_taxed_lst_unit_price() {
const lstPrice = this.compute_fixed_price(this.get_lst_price());
const product = this.get_product();
const taxesIds = product.taxes_id;
const productTaxes = this.pos.get_taxes_after_fp(taxesIds, this.order.fiscal_position);
const unitPrices = this.compute_all(productTaxes, lstPrice, 1, this.pos.currency.rounding);
if (this.pos.config.iface_tax_included === "total") {
return unitPrices.total_included;
} else {
return unitPrices.total_excluded;
}
}
get_price_without_tax() {
return this.get_all_prices().priceWithoutTax;
}
get_price_with_tax() {
return this.get_all_prices().priceWithTax;
}
get_price_with_tax_before_discount() {
return this.get_all_prices().priceWithTaxBeforeDiscount;
}
get_tax() {
return this.get_all_prices().tax;
}
get_applicable_taxes() {
var i;
// Shenaningans because we need
// to keep the taxes ordering.
var ptaxes_ids = this.tax_ids || this.get_product().taxes_id;
var ptaxes_set = {};
for (i = 0; i < ptaxes_ids.length; i++) {
ptaxes_set[ptaxes_ids[i]] = true;
}
var taxes = [];
for (i = 0; i < this.pos.taxes.length; i++) {
if (ptaxes_set[this.pos.taxes[i].id]) {
taxes.push(this.pos.taxes[i]);
}
}
return taxes;
}
get_tax_details() {
return this.get_all_prices().taxDetails;
}
get_taxes() {
var taxes_ids = this.tax_ids || this.get_product().taxes_id;
return this.pos.getTaxesByIds(taxes_ids);
}
/**
* Calculate the amount of taxes of a specific Orderline, that are included in the price.
* @returns {Number} the total amount of price included taxes
*/
get_total_taxes_included_in_price() {
const productTaxes = this._getProductTaxesAfterFiscalPosition();
const taxDetails = this.get_tax_details();
return productTaxes
.filter((tax) => tax.price_include)
.reduce((sum, tax) => sum + taxDetails[tax.id].amount, 0);
}
_map_tax_fiscal_position(tax, order = false) {
return this.pos._map_tax_fiscal_position(tax, order);
}
/**
* Mirror JS method of:
* _compute_amount in addons/account/models/account.py
*/
_compute_all(tax, base_amount, quantity, price_exclude) {
return this.pos._compute_all(tax, base_amount, quantity, price_exclude);
}
/**
* Mirror JS method of:
* compute_all in addons/account/models/account.py
*
* Read comments in the python side method for more details about each sub-methods.
*/
compute_all(taxes, price_unit, quantity, currency_rounding, handle_price_include = true) {
return this.pos.compute_all(
taxes,
price_unit,
quantity,
currency_rounding,
handle_price_include
);
}
/**
* Calculates the taxes for a product, and converts the taxes based on the fiscal position of the order.
*
* @returns {Object} The calculated product taxes after filtering and fiscal position conversion.
*/
_getProductTaxesAfterFiscalPosition() {
const product = this.get_product();
let taxesIds = this.tax_ids || product.taxes_id;
taxesIds = taxesIds.filter((t) => t in this.pos.taxes_by_id);
return this.pos.get_taxes_after_fp(taxesIds, this.order.fiscal_position);
}
get_all_prices(qty = this.get_quantity()) {
var price_unit = this.get_unit_price() * (1.0 - this.get_discount() / 100.0);
var taxtotal = 0;
var product = this.get_product();
var taxes_ids = this.tax_ids || product.taxes_id;
taxes_ids = taxes_ids.filter((t) => t in this.pos.taxes_by_id);
var taxdetail = {};
var product_taxes = this.pos.get_taxes_after_fp(taxes_ids, this.order.fiscal_position);
var all_taxes = this.compute_all(