Debian Codegraph @

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

raw
1 import { registry } from "@web/core/registry";
2 import { constructFullProductName, constructAttributeString } from "@point_of_sale/utils";
3 import { parseFloat } from "@web/views/fields/parsers";
4 import { formatFloat } from "@web/core/utils/numbers";
5 import { _t } from "@web/core/l10n/translation";
6 import { localization as l10n } from "@web/core/l10n/localization";
7 import { PosOrderlineAccounting } from "./accounting/pos_order_line_accounting";
8
9 export class PosOrderline extends PosOrderlineAccounting {
10 static pythonModel = "pos.order.line";
11
12 setup(vals) {
13 super.setup(vals);
14 if (!this.product_id) {
15 this.delete();
16 return;
17 }
18 this.setFullProductName();
19 }
20
21 initState() {
22 super.initState();
23 // Data that are not saved in the backend
24 this.uiState = {
25 hasChange: true,
26 savedQuantity: 0,
27 oldQty: this.qty,
28 };
29 }
30
31 setFullProductName() {
32 this.full_product_name = constructFullProductName(this);
33 }
34
35 setOptions(options) {
36 if (options.uiState) {
37 this.uiState = { ...this.uiState, ...options.uiState };
38 }
39
40 if (options.code) {
41 const code = options.code;
42 const blockMerge = ["weight", "quantity", "discount"];
43 const product_packaging_by_barcode = this.models["product.uom"].getAllBy("barcode");
44 const uom_by_id = this.models["uom.uom"].getAllBy("id");
45
46 if (blockMerge.includes(code.type)) {
47 this.setQuantity(code.value);
48 } else if (code.type === "price") {
49 this.setUnitPrice(code.value);
50 this.price_type = "manual";
51 }
52
53 if (product_packaging_by_barcode[code.code]) {
54 this.setQuantity(
55 uom_by_id[product_packaging_by_barcode[code.code].uom_id.id].factor /
56 this.product_id.product_tmpl_id.uom_id.factor
57 );
58 }
59 }
60
61 this.setUnitPrice(this.price_unit);
62 }
63
64 get preparationKey() {
65 return this.uuid;
66 }
67
68 get quantityStr() {
69 let unitPart = "";
70 let decimalPart = "";
71 const unit = this.product_id.uom_id;
72 const decimalPoint = l10n.decimalPoint;
73
74 if (unit) {
75 if (unit.rounding) {
76 const ProductUnit = this.models["decimal.precision"].find(
77 (dp) => dp.name === "Product Unit"
78 );
79
80 if (this.qty % 1 === 0) {
81 unitPart = this.qty.toFixed(0);
82 } else {
83 const formatted = formatFloat(this.qty, { digits: [69, ProductUnit.digits] });
84 const parts = formatted.split(decimalPoint);
85 unitPart = parts[0];
86 decimalPart = parts[1] || "";
87 }
88 } else {
89 unitPart = this.qty.toFixed(0);
90 }
91 } else {
92 unitPart = "" + this.qty;
93 }
94 return {
95 qtyStr: unitPart + (decimalPart ? decimalPoint + decimalPart : ""),
96 unitPart: unitPart,
97 decimalPoint: decimalPoint,
98 decimalPart: decimalPart,
99 };
100 }
101
102 get company() {
103 return this.config.company_id;
104 }
105
106 get config() {
107 return this.models["pos.config"].getFirst();
108 }
109
110 get session() {
111 return this.models["pos.session"].getFirst();
112 }
113
114 get currency() {
115 return this.order_id.currency;
116 }
117
118 get pickingType() {
119 return this.models["stock.picking.type"].getFirst();
120 }
121
122 get selectedComboIds() {
123 const allLines = this.getAllLinesInCombo();
124 return allLines.reduce((acc, line) => {
125 if (!line.combo_item_id) {
126 return acc;
127 }
128
129 acc[line.combo_item_id.combo_id.id] = line.combo_item_id.id;
130 return acc;
131 }, {});
132 }
133
134 get selectedAttributes() {
135 return this.attribute_value_ids.reduce((acc, attrValue) => {
136 const customValue =
137 this.custom_attribute_value_ids.find(
138 (c) => c.custom_product_template_attribute_value_id.id === attrValue.id
139 )?.custom_value || "";
140
141 if (attrValue.attribute_id.display_type === "multi") {
142 if (!acc[attrValue.attribute_id.id]) {
143 acc[attrValue.attribute_id.id] = { selected: [], custom_value: customValue };
144 }
145 acc[attrValue.attribute_id.id].selected.push(attrValue);
146 } else {
147 acc[attrValue.attribute_id.id] = { selected: attrValue, custom_value: customValue };
148 }
149 return acc;
150 }, {});
151 }
152
153 // To be overrided
154 getDisplayClasses() {
155 return {};
156 }
157
158 getPackLotLinesToEdit(isAllowOnlyOneLot) {
159 const currentPackLotLines = this.pack_lot_ids;
160 let nExtraLines = Math.abs(this.qty) - currentPackLotLines.length;
161 nExtraLines = Math.ceil(nExtraLines);
162 nExtraLines = nExtraLines > 0 ? nExtraLines : 1;
163 const tempLines = currentPackLotLines
164 .map((lotLine) => ({
165 id: lotLine.id,
166 text: lotLine.lot_name,
167 }))
168 .concat(
169 Array.from(Array(nExtraLines)).map((_) => ({
170 text: "",
171 }))
172 );
173 return isAllowOnlyOneLot ? [tempLines[0]] : tempLines;
174 }
175
176 // What if a number different from 1 (or -1) is specified
177 // to an orderline that has product tracked by lot? Lot tracking (based
178 // on the current implementation) requires that 1 item per orderline is
179 // allowed.
180 async editPackLotLines(editedPackLotLines) {
181 if (!editedPackLotLines) {
182 return;
183 }
184 this.setPackLotLines(editedPackLotLines);
185 this.order_id.selectOrderline(this);
186 }
187
188 setPackLotLines({ modifiedPackLotLines, newPackLotLines, setQuantity = true }) {
189 const lotLinesToRemove = [];
190
191 for (const lotLine of this.pack_lot_ids) {
192 const modifiedLotName = modifiedPackLotLines[lotLine.id];
193 if (modifiedLotName) {
194 lotLine.lot_name = modifiedLotName;
195 } else {
196 lotLinesToRemove.push(lotLine);
197 }
198 }
199
200 // Remove those that needed to be removed.
201 for (const lotLine of lotLinesToRemove) {
202 lotLine.delete();
203 }
204
205 for (const newLotLine of newPackLotLines) {
206 this.models["pos.pack.operation.lot"].create({
207 lot_name: newLotLine.lot_name,
208 pos_order_line_id: this,
209 });
210 }
211
212 // Set the qty of the line based on number of pack lots.
213 if (!this.product_id.to_weight && setQuantity) {
214 this.setQuantityByLot();
215 }
216 }
217
218 setDiscount(discount) {
219 const parsed_discount =
220 typeof discount === "number"
221 ? discount
222 : isNaN(parseFloat(discount))
223 ? 0
224 : parseFloat("" + discount);
225
226 const disc = Math.min(Math.max(parsed_discount || 0, 0), 100);
227 this.discount = disc;
228 }
229
230 // sets the qty of the product. The qty will be rounded according to the
231 // product's unity of measure properties. Quantities greater than zero will not get
232 // rounded to zero
233 setQuantity(quantity, keep_price) {
234 this.uiState.oldQty = this.qty;
235 if (this.order_id.preset_id?.is_return) {
236 quantity = -Math.abs(quantity);
237 }
238
239 this.order_id.assertEditable();
240 const quant =
241 typeof quantity === "number" ? quantity : parseFloat("" + (quantity ? quantity : 0));
242
243 const allLineToRefundUuids = this.models["pos.order"].reduce((acc, order) => {
244 Object.assign(acc, order.uiState.lineToRefund);
245 return acc;
246 }, {});
247
248 if (this.refunded_orderline_id?.uuid in allLineToRefundUuids) {
249 const refundDetails = allLineToRefundUuids[this.refunded_orderline_id.uuid];
250 const maxQtyToRefund = refundDetails.line.qty - refundDetails.line.refundedQty;
251 if (quant > 0) {
252 return {
253 title: _t("Positive quantity not allowed"),
254 body: _t(
255 "Only a negative quantity is allowed for this refund line. Click on +/- to modify the quantity to be refunded."
256 ),
257 };
258 } else if (quant == 0) {
259 refundDetails.qty = 0;
260 } else if (-quant <= maxQtyToRefund) {
261 refundDetails.qty = -quant;
262 } else {
263 return {
264 title: _t("Greater than allowed"),
265 body: _t(
266 "The requested quantity to be refunded is higher than the refundable quantity."
267 ),
268 };
269 }
270 }
271
272 const rounder =
273 this.product_id.uom_id ||
274 this.models["decimal.precision"].find((dp) => dp.name === "Product Unit");
275
276 this.qty = rounder.round(quant);
277
278 // just like in sale.order changing the qty will recompute the unit price
279 if (!keep_price && this.price_type === "original") {
280 const productTemplate = this.product_id.product_tmpl_id;
281 if (this.isLotTracked()) {
282 const related_lines = [];
283 const price = productTemplate.getPrice(
284 this.order_id.pricelist_id,
285 this.getQuantity(),
286 this.getPriceExtra(),
287 false,
288 this.product_id,
289 this,
290 related_lines
291 );
292 related_lines.forEach((line) => line.setUnitPrice(price));
293 } else {
294 this.setUnitPrice(
295 productTemplate.getPrice(
296 this.order_id.pricelist_id,
297 this.getQuantity(),
298 this.getPriceExtra(),
299 false,
300 this.product_id
301 )
302 );
303 }
304 }
305 for (const comboLine of this.combo_line_ids) {
306 // If each combo contains 2 qty of a product, we wanna keep this ratio after setting the new quantity on the parent product.
307 comboLine.setQuantity((comboLine.qty / this.uiState.oldQty || 1) * quantity, true);
308 }
309 return true;
310 }
311
312 setQuantityByLot() {
313 var valid_lots_quantity = this.getValidLots().length;
314 if (this.qty < 0) {
315 valid_lots_quantity = -valid_lots_quantity;
316 }
317 this.setQuantity(valid_lots_quantity);
318 }
319
320 hasValidProductLot() {
321 if (this.pack_lot_ids.length > 0) {
322 return true;
323 }
324
325 const valid_product_lot = this.getValidLots();
326 const lotsRequired = this.product_id.tracking == "serial" ? Math.abs(this.qty) : 1;
327 return lotsRequired === valid_product_lot.length;
328 }
329
330 canBeMergedWith(orderline) {
331 const ProductPrice = this.models["decimal.precision"].find(
332 (dp) => dp.name === "Product Price"
333 );
334 const price = ProductPrice.round(this.price_unit || 0);
335 const product = orderline.getProduct();
336 const order_line_price = product.getPrice(
337 orderline.order_id.pricelist_id,
338 this.getQuantity(),
339 0,
340 false,
341 product
342 );
343
344 const isSameCustomerNote =
345 (Boolean(orderline.getCustomerNote()) === false &&
346 Boolean(this.getCustomerNote()) === false) ||
347 orderline.getCustomerNote() === this.getCustomerNote();
348
349 // only orderlines of the same product can be merged
350 return (
351 orderline.getNote() === this.getNote() &&
352 this.getProduct().id === orderline.getProduct().id &&
353 this.isPosGroupable() &&
354 this.getDiscount() === orderline.getDiscount() &&
355 this.price_type === orderline.price_type &&
356 this.currency.isZero(
357 this.currency.round(price) -
358 this.currency.round(order_line_price) -
359 orderline.getPriceExtra()
360 ) &&
361 !this.isLotTracked() &&
362 this.full_product_name === orderline.full_product_name &&
363 isSameCustomerNote &&
364 !this.refunded_orderline_id &&
365 !orderline.isPartOfCombo()
366 );
367 }
368
369 isLotTracked() {
370 return (
371 this.product_id.tracking === "lot" &&
372 (this.pickingType.use_create_lots || this.pickingType.use_existing_lots)
373 );
374 }
375
376 isPosGroupable() {
377 const unit_groupable = this.product_id.uom_id
378 ? this.product_id.uom_id.is_pos_groupable
379 : false;
380 return unit_groupable && !this.isPartOfCombo();
381 }
382
383 merge(orderline) {
384 this.order_id.assertEditable();
385 this.setQuantity(this.getQuantity() + orderline.getQuantity());
386 this.update({
387 pack_lot_ids: [["link", ...orderline.pack_lot_ids]],
388 });
389 }
390
391 setUnitPrice(price) {
392 const ProductPrice = this.models["decimal.precision"].find(
393 (dp) => dp.name === "Product Price"
394 );
395 const parsed_price = !isNaN(price)
396 ? price
397 : isNaN(parseFloat(price))
398 ? 0
399 : parseFloat("" + price);
400 this.price_unit = ProductPrice.round(parsed_price || 0);
401 }
402
403 displayDiscountPolicy() {
404 // Sales dropped `discount_policy`, and we only show discount if applied pricelist rule
405 // is a percentage discount. However we don't have that information in pos
406 // so this is heuristic used to imitate the same behavior.
407 if (
408 this.order_id.pricelist_id &&
409 this.order_id.pricelist_id.item_ids
410 .map((rule) => rule.compute_price)
411 .includes("percentage")
412 ) {
413 return "without_discount";
414 }
415 return "with_discount";
416 }
417
418 setCustomerNote(note) {
419 this.customer_note = note || "";
420 }
421
422 getCustomerNote() {
423 return this.customer_note || "";
424 }
425
426 getTotalCost() {
427 return this.product_id.standard_price * this.qty;
428 }
429
430 isTipLine() {
431 const tipProduct = this.config.tip_product_id;
432 return tipProduct && this.product_id.id === tipProduct.id;
433 }
434
435 getAllLinesInCombo() {
436 if (this.combo_parent_id) {
437 // having a `combo_parent_id` means that we are not
438 // at the root node of the combo tree.
439 // Thus, we first navigate to the root
440 return this.combo_parent_id.getAllLinesInCombo();
441 }
442 const lines = [];
443 const stack = [this];
444 while (stack.length) {
445 const n = stack.pop();
446 lines.push(n);
447 if (n.combo_line_ids) {
448 stack.push(...n.combo_line_ids);
449 }
450 }
451 return lines;
452 }
453
454 isPartOfCombo() {
455 return Boolean(this.combo_parent_id || this.combo_line_ids?.length);
456 }
457
458 get packLotLines() {
459 return this.pack_lot_ids.map(
460 (l) =>
461 `${l.pos_order_line_id.product_id.tracking == "lot" ? "Lot Number" : "SN"} ${
462 l.lot_name
463 }`
464 );
465 }
466
467 getDiscount() {
468 return this.discount || 0;
469 }
470
471 // FIXME all below should be removed
472 getValidLots() {
473 return this.pack_lot_ids.filter((item) => item.lot_name);
474 }
475 // FIXME what is the use of this ?
476 updateSavedQuantity() {
477 this.uiState.savedQuantity = this.qty;
478 }
479 getPriceExtra() {
480 return this.price_extra;
481 }
482 getNote() {
483 return this.note || "[]";
484 }
485 setNote(note) {
486 this.note = note || "[]";
487 }
488 setHasChange(isChange) {
489 this.uiState.hasChange = isChange;
490 }
491 getDiscountStr() {
492 return this.discount ? this.discount.toString() : "";
493 }
494 getQuantity() {
495 return this.qty;
496 }
497 getQuantityStr() {
498 return this.quantityStr;
499 }
500 getUnit() {
501 return this.product_id.uom_id;
502 }
503 // return the product of this orderline
504 getProduct() {
505 return this.product_id;
506 }
507 getFullProductName() {
508 return this.full_product_name || this.product_id.display_name;
509 }
510 get orderDisplayProductName() {
511 return {
512 name: this.product_id?.name,
513 attributeString: constructAttributeString(this),
514 };
515 }
516 isSelected() {
517 return this.order_id?.uiState?.selected_orderline_uuid === this.uuid;
518 }
519 get canBeRemoved() {
520 return this.product_id.uom_id.isZero(this.qty);
521 }
522 get refundedQty() {
523 return (
524 this.refund_orderline_ids?.reduce(
525 (acc, line) => (line.order_id.state !== "cancel" ? acc - line.qty : acc),
526 0
527 ) || 0
528 );
529 }
530 }
531
532 registry.category("pos_available_models").add(PosOrderline.pythonModel, PosOrderline);