Debian Codegraph @

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

raw symbols SCIP
1 import { _t } from "@web/core/l10n/translation";
2 import { parseFloat } from "@web/views/fields/parsers";
3 import { SelectionPopup } from "@point_of_sale/app/components/popups/selection_popup/selection_popup";
4 import { AlertDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
5 import { NumberPopup } from "@point_of_sale/app/components/popups/number_popup/number_popup";
6 import { ask, makeAwaitable } from "@point_of_sale/app/utils/make_awaitable_dialog";
7 import { enhancedButtons, DECIMAL } from "@point_of_sale/app/components/numpad/numpad";
8 import { patch } from "@web/core/utils/patch";
9 import { PosStore } from "@point_of_sale/app/services/pos_store";
10 import { accountTaxHelpers } from "@account/helpers/account_tax";
11
12 patch(PosStore.prototype, {
13 async onClickSaleOrder(clickedOrderId) {
14 const sale_order = await this._getSaleOrder(clickedOrderId);
15 await this._processSaleOrder(sale_order);
16 },
17 async _processSaleOrder(sale_order) {
18 const currentSaleOrigin = this.getOrder()
19 .getOrderlines()
20 .find((line) => line.sale_order_origin_id)?.sale_order_origin_id;
21 if (currentSaleOrigin?.id) {
22 const linkedSO = await this._getSaleOrder(currentSaleOrigin.id);
23 if (
24 linkedSO.partner_id?.id !== sale_order.partner_id?.id ||
25 linkedSO.partner_invoice_id?.id !== sale_order.partner_invoice_id?.id ||
26 linkedSO.partner_shipping_id?.id !== sale_order.partner_shipping_id?.id
27 ) {
28 this.addNewOrder({
29 partner_id: sale_order.partner_id,
30 });
31 this.notification.add(_t("A new order has been created."));
32 }
33 }
34 if (sale_order.partner_id) {
35 this.getOrder().setPartner(sale_order.partner_id);
36 }
37
38 // Fiscal position should be set after the partner is set
39 // to ensure that the fiscal position is correctly computed
40 // based on sale order.
41 const orderFiscalPos = sale_order.fiscal_position_id;
42 this.getOrder().update({
43 fiscal_position_id: orderFiscalPos,
44 });
45
46 //Add a down payment for transactions that were already done online
47 if (sale_order.amount_paid > 0) {
48 await this.addDownPaymentProductOrderlineToOrder(
49 sale_order,
50 -sale_order.amount_paid,
51 false
52 );
53 }
54 const selectedOption = await makeAwaitable(this.dialog, SelectionPopup, {
55 title: _t("What do you want to do?"),
56 list: [
57 { id: "0", label: _t("Settle the order"), item: "settle" },
58 {
59 id: "1",
60 label: _t("Apply a down payment (percentage)"),
61 item: "dpPercentage",
62 },
63 {
64 id: "2",
65 label: _t("Apply a down payment (fixed amount)"),
66 item: "dpAmount",
67 },
68 ],
69 });
70 if (!selectedOption) {
71 return;
72 }
73 selectedOption == "settle"
74 ? await this.settleSO(sale_order, orderFiscalPos)
75 : await this.downPaymentSO(sale_order, selectedOption == "dpPercentage");
76 this.selectOrderLine(this.getOrder(), this.getOrder().lines.at(-1));
77 },
78 async _getSaleOrder(id) {
79 const result = await this.data.callRelated("sale.order", "load_sale_order_from_pos", [
80 id,
81 this.config.id,
82 ]);
83 return result["sale.order"][0];
84 },
85 async settleSO(sale_order, orderFiscalPos) {
86 if (sale_order.pricelist_id) {
87 this.getOrder().setPricelist(sale_order.pricelist_id);
88 }
89 let useLoadedLots = false;
90 let userWasAskedAboutLoadedLots = false;
91 let previousProductLine = null;
92
93 const converted_lines = await this.data.call("sale.order.line", "read_converted", [
94 sale_order.order_line.map((l) => l.id),
95 ]);
96
97 for (const line of sale_order.order_line) {
98 if (line.display_type === "line_note") {
99 if (previousProductLine) {
100 const previousNote = previousProductLine.customer_note;
101 previousProductLine.customer_note = previousNote
102 ? previousNote + "--" + line.name
103 : line.name;
104 }
105 continue;
106 }
107
108 if (line.is_downpayment) {
109 line.product_id = this.config.down_payment_product_id;
110 }
111
112 const taxes = orderFiscalPos?.getTaxesAfterFiscalPosition(line.tax_ids) || line.tax_ids;
113 const newLineValues = {
114 product_tmpl_id: line.product_id?.product_tmpl_id,
115 product_id: line.product_id,
116 qty: line.product_uom_qty,
117 price_unit: line.price_unit,
118 price_type: "automatic",
119 tax_ids: taxes.map((tax) => ["link", tax]),
120 sale_order_origin_id: sale_order,
121 sale_order_line_id: line,
122 customer_note: line.customer_note,
123 description: line.name,
124 order_id: this.getOrder(),
125 custom_attribute_value_ids: Object.values(
126 line.product_custom_attribute_value_ids || {}
127 ).map((value_line) => [
128 "create",
129 {
130 custom_product_template_attribute_value_id:
131 value_line.custom_product_template_attribute_value_id,
132 custom_value: value_line.custom_value,
133 },
134 ]),
135 };
136 if (line.display_type === "line_section") {
137 continue;
138 }
139 newLineValues.attribute_value_ids = (line.product_custom_attribute_value_ids || []).map(
140 (value_line) => {
141 if (value_line?.custom_product_template_attribute_value_id) {
142 return ["link", value_line.custom_product_template_attribute_value_id];
143 }
144 }
145 );
146 const newLine = await this.addLineToCurrentOrder(newLineValues, {}, false);
147 previousProductLine = newLine;
148
149 const converted_line = converted_lines.find((l) => l.id === line.id);
150 if (
151 newLine.getProduct().tracking !== "none" &&
152 (this.pickingType.use_create_lots || this.pickingType.use_existing_lots) &&
153 converted_line.lot_names.length > 0
154 ) {
155 if (!useLoadedLots && !userWasAskedAboutLoadedLots) {
156 useLoadedLots = await ask(this.dialog, {
157 title: _t("SN/Lots Loading"),
158 body: _t("Do you want to load the SN/Lots linked to the Sales Order?"),
159 });
160 userWasAskedAboutLoadedLots = true;
161 }
162 if (useLoadedLots) {
163 newLine.setPackLotLines({
164 modifiedPackLotLines: [],
165 newPackLotLines: (converted_line.lot_names || []).map((name) => ({
166 lot_name: name,
167 })),
168 });
169 }
170 }
171 newLine.setQuantityFromSOL(converted_line);
172 newLine.setUnitPrice(converted_line.price_unit);
173 newLine.setDiscount(line.discount);
174
175 const lot_splitted_lines = [];
176 const product_unit = line.product_id.uom_id;
177 if (product_unit && !product_unit.is_pos_groupable) {
178 let remaining_quantity = newLine.qty;
179 newLineValues.product_id = newLine.product_id;
180 const priceUnit = newLine.price_unit;
181 newLine.delete();
182 while (!product_unit.isZero(remaining_quantity)) {
183 const splitted_line = this.models["pos.order.line"].create({
184 ...newLineValues,
185 });
186 splitted_line.setQuantity(Math.min(remaining_quantity, 1.0), true);
187 splitted_line.setUnitPrice(priceUnit);
188 splitted_line.setDiscount(line.discount);
189 remaining_quantity -= splitted_line.qty;
190 if (splitted_line.product_id.tracking == "lot") {
191 lot_splitted_lines.push(splitted_line);
192 }
193 }
194 }
195
196 // Order line can only hold one lot, so we need to split the line if there are multiple lots
197 if (
198 line.product_id.tracking == "lot" &&
199 converted_line.lot_names.length > 0 &&
200 useLoadedLots
201 ) {
202 const priceUnit = newLine.price_unit;
203 newLine.delete();
204 let total_lot_quantity = 0;
205 for (const lot of converted_line.lot_names) {
206 let lot_remaining_quantity = converted_line.lot_qty_by_name[lot] || 0;
207 while (lot_splitted_lines.length && lot_remaining_quantity > 0) {
208 const splitted_line = lot_splitted_lines.shift();
209 splitted_line.setPackLotLines({
210 modifiedPackLotLines: [],
211 newPackLotLines: [{ lot_name: lot }],
212 setQuantity: false,
213 });
214 total_lot_quantity += splitted_line.qty;
215 lot_remaining_quantity -= splitted_line.qty;
216 }
217 if (lot_remaining_quantity > 0 && lot_splitted_lines.length == 0) {
218 const splitted_line = this.models["pos.order.line"].create({
219 ...newLineValues,
220 });
221 splitted_line.setQuantity(lot_remaining_quantity, true);
222 splitted_line.setUnitPrice(priceUnit);
223 splitted_line.setDiscount(line.discount);
224 splitted_line.setPackLotLines({
225 modifiedPackLotLines: [],
226 newPackLotLines: [{ lot_name: lot }],
227 setQuantity: false,
228 });
229 total_lot_quantity += lot_remaining_quantity;
230 }
231 }
232 if (total_lot_quantity < newLineValues.qty && lot_splitted_lines.length == 0) {
233 const splitted_line = this.models["pos.order.line"].create({
234 ...newLineValues,
235 });
236 splitted_line.setQuantity(newLineValues.qty - total_lot_quantity, true);
237 splitted_line.setDiscount(line.discount);
238 }
239 }
240 }
241 },
242
243 prepareSoBaseLineForTaxesComputationExtraValues(so, soLine) {
244 const extraValues = { currency_id: so.currency_id || this.company.currency_id };
245 return {
246 ...extraValues,
247 quantity: soLine.product_uom_qty,
248 tax_ids: soLine.tax_ids,
249 partner_id: so.partner_id,
250 product_id: soLine.product_id,
251 extra_tax_data: soLine.extra_tax_data,
252 };
253 },
254
255 async downPaymentSO(saleOrder, isPercentage) {
256 const colorClassMap = {
257 [DECIMAL.value]: "o_colorlist_item_numpad_color_6",
258 Backspace: "o_colorlist_item_numpad_color_1",
259 "+10": "o_colorlist_item_numpad_color_10",
260 "+20": "o_colorlist_item_numpad_color_10",
261 "+50": "o_colorlist_item_numpad_color_10",
262 "-": "o_colorlist_item_numpad_color_3",
263 };
264
265 const payload = await makeAwaitable(this.dialog, NumberPopup, {
266 title: _t("Down Payment"),
267 subtitle: _t("Due balance: %s", this.env.utils.formatCurrency(saleOrder.amount_unpaid)),
268 buttons: enhancedButtons().map((button) => ({
269 ...button,
270 class: `${colorClassMap[button.value] || ""}`,
271 })),
272 confirmButtonLabel: _t("Apply"),
273 formatDisplayedValue: (x) => (isPercentage ? `% ${x}` : x),
274 feedback: (buffer) =>
275 isPercentage && buffer
276 ? `(${this.env.utils.formatCurrency(
277 (saleOrder.amount_unpaid * parseFloat(buffer)) / 100
278 )})`
279 : "",
280 });
281 if (!payload) {
282 return;
283 }
284
285 const amount = parseFloat(payload);
286 await this.addDownPaymentProductOrderlineToOrder(saleOrder, amount, isPercentage);
287 },
288 async loadDownPaymentProduct() {
289 if (!this.config.down_payment_product_id && this.config.raw.down_payment_product_id) {
290 await this.data.read("product.product", [this.config.raw.down_payment_product_id]);
291 }
292 if (!this.config.down_payment_product_id) {
293 this.dialog.add(AlertDialog, {
294 title: _t("No down payment product"),
295 body: _t(
296 "It seems that you didn't configure a down payment product in your point of sale. You can go to your point of sale configuration to choose one."
297 ),
298 });
299 return false;
300 }
301 return true;
302 },
303 async addDownPaymentProductOrderlineToOrder(saleOrder, amount, isPercentage) {
304 const result = await this.loadDownPaymentProduct();
305 if (!result) {
306 return;
307 }
308 const saleOrderLines = saleOrder.order_line.filter((soLine) => !soLine.display_type);
309 const baseLines = [];
310 for (const saleOrderLine of saleOrderLines) {
311 baseLines.push(
312 accountTaxHelpers.prepare_base_line_for_taxes_computation(
313 saleOrderLine,
314 this.prepareSoBaseLineForTaxesComputationExtraValues(saleOrder, saleOrderLine)
315 )
316 );
317 }
318 accountTaxHelpers.add_tax_details_in_base_lines(baseLines, this.company);
319 accountTaxHelpers.round_base_lines_tax_details(baseLines, this.company);
320 if (isPercentage) {
321 const percentage = amount / 100.0;
322 amount = baseLines.length ? saleOrder.amount_unpaid * percentage : 0.0;
323 }
324
325 const downPaymentProduct = this.config.down_payment_product_id;
326 const groupingFunction = (base_line) => ({
327 grouping_key: { product_id: downPaymentProduct },
328 raw_grouping_key: { product_id: downPaymentProduct.id },
329 });
330 const downPaymentBaseLines = accountTaxHelpers.prepare_down_payment_lines(
331 baseLines,
332 this.company,
333 "fixed",
334 amount,
335 {
336 computation_key: "down_payment", // TODO: won't work with multiple down payment on the same order... is it a problem?
337 grouping_function: groupingFunction,
338 }
339 );
340
341 // Update the pos order.
342 for (const baseLine of downPaymentBaseLines) {
343 // Find the sale order lines that are impacted by this down payment line.
344 const taxIds = new Set(baseLine.tax_ids.map((tax) => tax.id));
345 const matchedSaleOrderLines = [];
346 for (const saleOrderLine of saleOrderLines) {
347 // TODO: use '!saleOrderLine.is_down_payment' instead?
348 // TODO: 'product_id' is always set on a SO line, correct?
349 if (
350 !saleOrderLine.product_id ||
351 saleOrderLine.product_id.id === downPaymentProduct.id
352 ) {
353 continue;
354 }
355
356 const saleOrderLineTaxIds = saleOrderLine.tax_ids.map((tax) => tax.id);
357 if (
358 saleOrderLineTaxIds.length === taxIds.size &&
359 saleOrderLineTaxIds.every((taxId) => taxIds.has(taxId))
360 ) {
361 matchedSaleOrderLines.push(saleOrderLine);
362 }
363 }
364
365 this.addLineToCurrentOrder({
366 pos: this,
367 order: saleOrder,
368 product_id: baseLine.product_id,
369 product_tmpl_id: baseLine.product_id.product_tmpl_id,
370 price: baseLine.price_unit,
371 price_unit: baseLine.price_unit,
372 price_type: "automatic",
373 sale_order_origin_id: saleOrder,
374 down_payment_details: matchedSaleOrderLines.map((saleOrderLine) => ({
375 product_name: saleOrderLine.product_id.display_name,
376 product_uom_qty: saleOrderLine.product_uom_qty,
377 price_unit: saleOrderLine.price_unit,
378 total: saleOrderLine.price_total,
379 })),
380 tax_ids: [["link", ...baseLine.tax_ids]],
381 extra_tax_data: accountTaxHelpers.export_base_line_extra_tax_data(baseLine),
382 });
383 }
384 },
385 selectOrderLine(order, line) {
386 super.selectOrderLine(...arguments);
387 if (
388 line &&
389 this.config.down_payment_product_id &&
390 line.product_id.id === this.config.down_payment_product_id.id
391 ) {
392 this.numpadMode = "price";
393 }
394 },
395 setPartnerToCurrentOrder(partner) {
396 if (partner.sale_warn_msg) {
397 this.dialog.add(AlertDialog, {
398 title: _t("Warning for %s", partner.name),
399 body: partner.sale_warn_msg,
400 });
401 }
402 super.setPartnerToCurrentOrder(partner);
403 },
404 addLineToCurrentOrder(vals, opt = {}, configure = true) {
405 if (!vals.product_tmpl_id && vals.product_id) {
406 vals.product_tmpl_id = vals.product_id.product_tmpl_id;
407 }
408
409 const productTemplate = vals.product_tmpl_id;
410 if (productTemplate.sale_line_warn_msg) {
411 this.dialog.add(AlertDialog, {
412 title: _t("Warning for %s", productTemplate.name),
413 body: productTemplate.sale_line_warn_msg,
414 });
415 }
416 return super.addLineToCurrentOrder(vals, opt, configure);
417 },
418 });