Debian Codegraph @

addons/website_sale/static/src/js/cart_service.js

raw symbols SCIP
1 import {
2 ComboConfiguratorDialog
3 } from '@sale/js/combo_configurator_dialog/combo_configurator_dialog';
4 import { ProductCombo } from '@sale/js/models/product_combo';
5 import {
6 ProductConfiguratorDialog
7 } from '@sale/js/product_configurator_dialog/product_configurator_dialog';
8 import { getSelectedCustomPtav, serializeComboItem } from '@sale/js/sale_utils';
9 import { browser } from '@web/core/browser/browser';
10 import { serializeDateTime } from '@web/core/l10n/dates';
11 import { rpc } from '@web/core/network/rpc';
12 import { registry } from '@web/core/registry';
13 import { redirect } from '@web/core/utils/urls';
14 import { session } from '@web/session';
15
16 const { DateTime } = luxon;
17
18 /**
19 * @typedef {Object} CustomAttributeValues
20 * @property {Number} custom_product_template_attribute_value_id
21 * @property {String} custom_value
22 */
23
24 /**
25 * Manages product addition via the {@link addToCart} function.
26 *
27 * This function handles the process of adding products to the cart, including:
28 * - Opening configurators if needed;
29 * - Updating the cart with the selected products;
30 * - Updating the cart count in the navbar;
31 * - Notifying the customer of successful additions;
32 * - Track the added products.
33 *
34 * Override this class to implement additional checks or
35 * provide relevant information when adding a product to the cart.
36 */
37 export class CartService {
38 static dependencies = ['cartNotificationService', 'dialog'];
39
40 /**
41 * Creates an instance of the service and initializes it using the {@link setup} method.
42 *
43 * The constructor delegates initialization to {@link setup} to handle wiring up dependencies,
44 * setting up methods, and initializing global variables, as constructors themselves cannot be
45 * patched.
46 *
47 * @returns {Object} - The initialized service object returned by {@link setup}.
48 */
49 constructor() {
50 return this.setup(...arguments);
51 }
52
53 /**
54 * Initializes the service wiring up dependencies, setting up methods and initializing global
55 * variables.
56 *
57 * @param {import("@web/env").OdooEnv} _env - The environment object, not used here.
58 * @param {import("services").ServiceFactories} services - An object containing instances of the
59 * required services specified in the {@link dependencies} array.
60 *
61 * @returns {Object} - An object exposing the public methods of the service.
62 */
63 setup(_env, services) {
64 this.cartNotificationService = services.cartNotificationService;
65 this.dialog = services.dialog;
66 this.rpc = rpc; // To be overridable in tests.
67
68 // Only expose `add` in the service registry.
69 return {
70 add: (...args) => this.add(...args)
71 };
72 }
73
74 //--------------------------------------------------------------------------
75 // Methods exposed by the service.
76 //--------------------------------------------------------------------------
77
78 /**
79 * Asynchronously adds a product to the shopping cart.
80 *
81 * @async
82 * @param {Object} product - The product details to add to the cart.
83 * @param {Number} product.productTemplateId - The product template's id, as a
84 * `product.template` id.
85 * @param {Number} [product.productId=undefined] - The product's id, as a `product.product` id.
86 * If not provided, selects the first available product or creates one if any attribute is
87 * dynamic.
88 * @param {Number} [product.quantity=1] - The quantity of the product to add to the cart.
89 * Defaults to 1.
90 * @param {Number} [product.uom_id=undefined] - The product's uom id, as a `uom.uom` id.
91 * If not provided, considers the product default uom.
92 * @param {Number[]} [product.ptavs=[]] - The selected stored attribute(s), as a list of
93 * `product.template.attribute.value` ids.
94 * @param {CustomAttributeValues[]} [product.productCustomAttributeValues=[]] - An
95 * array of objects representing custom attribute values for the product.
96 * @param {Number[]} [product.noVariantAttributeValues=[]] - The selected non-stored
97 * attribute(s), as a list of `product.template.attribute.value` ids.
98 * @param {Boolean} [product.isCombo=false] - Whether the product is part of a combo template.
99 * Defaults to false.
100 * @param {...*} [product.rest] - Locally unused data sent to the controllers.
101 * @param {Object} [options] - Define how to add products to the cart.
102 * @param {Boolean} [options.isBuyNow=false] - Whether the product should be added immediately,
103 * bypassing optional configurations. Defaults to false.
104 * @param {Boolean} [options.redirectToCart=true] - When `isBuyNow` is `true`, whether to
105 * redirect the customer to the cart. Defaults to true.
106 * @param {Boolean} [options.isConfigured=false] - Whether the product is already configured.
107 * Defaults to false.
108 * @param {Boolean} [options.showQuantity=true] - Whether quantity selector should be shown
109 * Defaults to true.
110 * @returns {Number} - The product's quantity added to the cart.
111 */
112 async add({
113 productTemplateId,
114 productId = undefined,
115 quantity = 1,
116 uomId = undefined,
117 ptavs = [],
118 productCustomAttributeValues = [],
119 noVariantAttributeValues = [],
120 isCombo = false,
121 ...rest
122 },
123 {
124 isBuyNow=false,
125 redirectToCart=true,
126 isConfigured=false,
127 showQuantity=true,
128 } = {},
129 ) {
130 if (!productId && ptavs.length) {
131 productId = await this.rpc('/sale/create_product_variant', {
132 product_template_id: productTemplateId,
133 product_template_attribute_value_ids: ptavs.concat(noVariantAttributeValues),
134 })
135 }
136
137 if(isCombo) {
138 const { combos, ...remainingData } = await this.rpc(
139 '/website_sale/combo_configurator/get_data',
140 {
141 product_tmpl_id: productTemplateId,
142 quantity: quantity,
143 // NOTE: no uom for combos on purpose
144 date: serializeDateTime(DateTime.now()),
145 ...rest
146 }
147 );
148 const preselectedComboItems = combos
149 .map(combo => new ProductCombo(combo))
150 .map(combo => combo.preselectedComboItem)
151 .filter(Boolean);
152 // If the combo product is already fully configured (i.e. a combo item has been
153 // preselected for each combo choice), then it can be added to the cart without
154 // opening the combo configurator.
155 if (preselectedComboItems.length === combos.length) {
156 return this._makeRequest({
157 productTemplateId: productTemplateId,
158 productId: productId,
159 quantity: remainingData.quantity,
160 uomId: uomId,
161 linked_products: preselectedComboItems.map(
162 (comboItem) => this._serializeComboItem(
163 comboItem, productTemplateId, remainingData.quantity
164 )
165 ),
166 shouldRedirectToCart: isBuyNow && redirectToCart,
167 ...rest
168 });
169 }
170 // If some combo choices need to be configured, open the combo configurator.
171 return this._openComboConfigurator(
172 productTemplateId,
173 productId,
174 combos.map(combo => new ProductCombo(combo)),
175 remainingData,
176 {
177 isBuyNow: isBuyNow,
178 showQuantity: showQuantity,
179 },
180 rest
181 );
182 }
183
184 if (isBuyNow) {
185 return this._makeRequest({
186 productTemplateId,
187 productId,
188 quantity,
189 uomId,
190 productCustomAttributeValues,
191 noVariantAttributeValues,
192 shouldRedirectToCart: isBuyNow && redirectToCart,
193 ...rest
194 });
195 }
196
197 const shouldShowProductConfigurator = await this.rpc(
198 '/website_sale/should_show_product_configurator',
199 {
200 product_template_id: productTemplateId,
201 ptav_ids: ptavs,
202 is_product_configured: isConfigured,
203 }
204 );
205 if (shouldShowProductConfigurator) {
206 return this._openProductConfigurator(
207 productTemplateId,
208 quantity,
209 uomId,
210 ptavs.concat(noVariantAttributeValues),
211 productCustomAttributeValues,
212 {
213 isBuyNow: isBuyNow,
214 isMainProductConfigurable: !isConfigured,
215 showQuantity: showQuantity,
216 },
217 rest
218 );
219 }
220
221 return this._makeRequest({
222 productTemplateId,
223 productId,
224 quantity,
225 uomId,
226 productCustomAttributeValues,
227 noVariantAttributeValues,
228 shouldRedirectToCart: isBuyNow && redirectToCart,
229 ...rest
230 });
231 }
232
233 //--------------------------------------------------------------------------
234 // Configurators
235 //--------------------------------------------------------------------------
236
237 /**
238 * Opens the combo configurator dialog.
239 *
240 * @private
241 * @param {Number} productTemplateId - The product template id, as a `product.template` id.
242 * @param {Number} productId - The product's id, as a `product.product` id.
243 * @param {ProductCombo[]} combos - The combos of the product.
244 * @param {Object} remainingData - Other data needed to open the combo configurator.
245 * @param {Number} remainingData.currency_id - The currency's id, as a `res.currency` id.
246 * @param {String} remainingData.display_name - The name of the combo.
247 * @param {Number} remainingData.price - The price of the combo.
248 * @param {Number} remainingData.product_tmpl_id - The product template's id, as a
249 * `product.template` id.
250 * @param {Number} remainingData.quantity - The quantity of the combo.
251 * @param {Object} [options] - Define how to add products to the cart.
252 * @param {Boolean} [options.isBuyNow] - Whether the product should be added immediately,
253 * bypassing optional configurations.
254 * @param {Object} [additionalData] - Additional data sent to the controllers.
255 *
256 * @returns {Number} - The product's quantity added to the cart.
257 */
258 async _openComboConfigurator(
259 productTemplateId,
260 productId,
261 combos,
262 remainingData,
263 options,
264 additionalData
265 ) {
266 return await new Promise((resolve) => {
267 this.dialog.add(ComboConfiguratorDialog, {
268 combos: combos,
269 ...remainingData,
270 date: serializeDateTime(DateTime.now()),
271 edit: false,
272 isFrontend: true,
273 options,
274 ...additionalData,
275 save: async (comboProductData, selectedComboItems, options) => {
276 resolve(this._makeRequest({
277 productTemplateId: productTemplateId,
278 productId: productId,
279 quantity: comboProductData.quantity,
280 // NOTE: no uom since not handled in combo configurator
281 linked_products: selectedComboItems.map(
282 (comboItem) => this._serializeComboItem(
283 comboItem, productTemplateId, comboProductData.quantity
284 )
285 ),
286 shouldRedirectToCart: options.goToCart,
287 ...additionalData,
288 }));
289 },
290 discard: () => resolve(0),
291 });
292 });
293 }
294
295 /**
296 * Opens the product configurator dialog.
297 *
298 * @private
299 * @param {Number} productTemplateId - The product template id, as a `product.template` id.
300 * @param {Number} quantity - The quantity to add to the cart.
301 * @param {Number[]} combination - The combination of the product, as a list of
302 * `product.template.attribute.value` ids.
303 * @param {CustomAttributeValues[]} productCustomAttributeValues - An array of objects
304 * representing custom attribute values for the product.
305 * @param {Object} [options] - Define how to add products to the cart.
306 * @param {Boolean} [options.isBuyNow] - Whether the product should be added immediately,
307 * bypassing optional configurations.
308 * @param {Boolean} [options.isMainProductConfigurable] - Whether the product should be
309 * configurable.
310 * @param {Object} [additionalData] - Additional data sent to the controllers.
311 *
312 * @returns {Number} - The product's quantity added to the cart.
313 */
314 async _openProductConfigurator(
315 productTemplateId,
316 quantity,
317 uomId,
318 combination,
319 productCustomAttributeValues,
320 options,
321 additionalData
322 ) {
323 return await new Promise((resolve) => {
324 this.dialog.add(ProductConfiguratorDialog, {
325 productTemplateId: productTemplateId,
326 ptavIds: combination,
327 customPtavs: productCustomAttributeValues.map(customPtav => ({
328 id: customPtav.custom_product_template_attribute_value_id,
329 value: customPtav.custom_value,
330 })),
331 quantity: quantity,
332 productUOMId: uomId,
333 soDate: serializeDateTime(DateTime.now()),
334 edit: false,
335 isFrontend: true,
336 selectedComboItems: [], // optional products for combo aren't supported on ecommerce for now.
337 options,
338 ...additionalData,
339 save: async (mainProduct, optionalProducts, options) => {
340 const product = this._serializeProduct(mainProduct);
341 resolve(this._makeRequest({
342 productTemplateId: product.product_template_id,
343 productId: product.product_id,
344 quantity: product.quantity,
345 uom_id: product.uom_id,
346 productCustomAttributeValues: product.product_custom_attribute_values,
347 noVariantAttributeValues: product.no_variant_attribute_value_ids,
348 linked_products: optionalProducts.map(this._serializeProduct),
349 shouldRedirectToCart: options.goToCart,
350 ...additionalData,
351 }));
352 },
353 discard: () => resolve(0),
354 });
355 });
356 }
357
358 /**
359 * Serialize a product into a format understandable by the server.
360 *
361 * @private
362 * @param {Object} product - The product to serialize.
363 *
364 * @returns {Object} - The serialized product.
365 */
366 _serializeProduct(product) {
367 let serializedProduct = {
368 product_id: product.id,
369 product_template_id: product.product_tmpl_id,
370 parent_product_template_id: product.parent_product_tmpl_id,
371 quantity: product.quantity,
372 uom_id: product.uom.id,
373 }
374
375 if (!product.attribute_lines) {
376 return serializedProduct;
377 }
378
379 // Custom attributes.
380 serializedProduct.product_custom_attribute_values = [];
381 for (const ptal of product.attribute_lines) {
382 const selectedCustomPtav = getSelectedCustomPtav(ptal);
383 if (selectedCustomPtav) {
384 serializedProduct.product_custom_attribute_values.push({
385 custom_product_template_attribute_value_id: selectedCustomPtav.id,
386 custom_value: ptal.customValue ?? '',
387 });
388 }
389 }
390
391 // No variant attributes.
392 serializedProduct.no_variant_attribute_value_ids = product.attribute_lines
393 .filter(ptal => ptal.create_variant === 'no_variant')
394 .flatMap(ptal => ptal.selected_attribute_value_ids);
395
396 return serializedProduct;
397 }
398
399 /**
400 * Serialize a combo item into a format understandable by the server.
401 *
402 * @private
403 * @param {ProductComboItem} comboItem - The combo item to serialize.
404 * @param {Number} parentProductTemplateId - The parent's product template id, as a
405 * `product.template` id.
406 * @param {Number} quantity - The quantity to add to the cart.
407 *
408 * @returns {Object} - The serialized combo item.
409 */
410 _serializeComboItem(comboItem, parentProductTemplateId, quantity) {
411 return {
412 product_template_id: comboItem.product.product_tmpl_id,
413 parent_product_template_id: parentProductTemplateId,
414 quantity: quantity,
415 ...serializeComboItem(comboItem),
416 };
417 }
418
419 //--------------------------------------------------------------------------
420 // Helpers
421 //--------------------------------------------------------------------------
422
423 /**
424 * Make a request to the server to add the product to the cart.
425 *
426 * @async
427 * @private
428 * @param {Object} data - Data containing product(s) to add to the cart and options for adding
429 * them.
430 * @param {Number} data.productTemplateId - The product template's id, as a
431 * `product.template` id.
432 * @param {Number} data.productId - The product's id, as a `product.product` id.
433 * @param {Number} data.uomId - The uom's id, as a `uom.uom` id.
434 * @param {Number} data.quantity - The quantity of the product to add to the cart.
435 * @param {CustomAttributeValues[]} [data.productCustomAttributeValues=[]] - An
436 * array of objects representing custom attribute values for the product.
437 * @param {Number[]} [data.noVariantAttributeValues=[]] - The selected non-stored
438 * attribute(s), as a list of `product.template.attribute.value` ids.
439 * @param {Boolean} [data.shouldRedirectToCart=false] - Whether to redirect the
440 * customer to the cart. Defaults to false.
441 * @param {...*} [data.rest] - Locally unused data sent to the controllers.
442 *
443 * @returns {Number} - The product's quantity in the cart.
444 */
445 async _makeRequest({
446 productTemplateId,
447 productId,
448 quantity,
449 uomId=undefined,
450 productCustomAttributeValues=[],
451 noVariantAttributeValues=[],
452 shouldRedirectToCart=false,
453 ...rest
454 }) {
455 const data = await this.rpc('/shop/cart/add', {
456 product_template_id: productTemplateId,
457 product_id: productId,
458 quantity: quantity,
459 uom_id: uomId,
460 product_custom_attribute_values: productCustomAttributeValues,
461 no_variant_attribute_value_ids: noVariantAttributeValues,
462 ...rest
463 });
464 // TODO should not redirect if errors in data.
465 if (shouldRedirectToCart || session.add_to_cart_action === 'go_to_cart') {
466 redirect('/shop/cart');
467 return data.quantity;
468 }
469 if (data.cart_quantity && (
470 data.cart_quantity !== browser.sessionStorage.getItem('website_sale_cart_quantity')
471 )) {
472 this._updateCartIcon(data.cart_quantity);
473 };
474 this._showCartNotification(data.notification_info);
475 if (data.quantity) {
476 this._trackProducts(data.tracking_info);
477 }
478 return data.quantity;
479 }
480
481 /**
482 * Update the quantity on the cart icon in the navbar.
483 *
484 * @private
485 * @param {Number} cartQuantity - The number of items currently in the cart.
486 *
487 * @returns {void}
488 */
489 _updateCartIcon(cartQuantity) {
490 browser.sessionStorage.setItem('website_sale_cart_quantity', cartQuantity);
491 // Mobile and Desktop elements have to be updated.
492 const cartQuantityElements = document.querySelectorAll('.my_cart_quantity');
493 for(const cartQuantityElement of cartQuantityElements) {
494 if (cartQuantity === 0) {
495 cartQuantityElement.classList.add('d-none');
496 } else {
497 const cartIconElement = document.querySelector('li.o_wsale_my_cart');
498 cartIconElement.classList.remove('d-none');
499 cartQuantityElement.classList.remove('d-none');
500 cartQuantityElement.classList.add('o_mycart_zoom_animation');
501 setTimeout(() => {
502 cartQuantityElement.textContent = cartQuantity;
503 cartQuantityElement.classList.remove('o_mycart_zoom_animation');
504 }, 300);
505 }
506 }
507 }
508
509 /**
510 * Show the notification about the cart.
511 *
512 * @private
513 * @param {Object} props
514 * @param {Object} options
515 *
516 * @returns {void}
517 */
518 _showCartNotification(props, options = {}) {
519 if (props.lines) {
520 this.cartNotificationService.add('', {
521 lines: props.lines,
522 currency_id: props.currency_id,
523 ...options,
524 });
525 }
526 if (props.warning) {
527 this.cartNotificationService.add('', {
528 warning: props.warning,
529 ...options,
530 });
531 }
532 }
533
534 /**
535 * Track the products added to the cart.
536 *
537 * @private
538 * @param {Object[]} trackingInfo - A list of product tracking information.
539 *
540 * @returns {void}
541 */
542 _trackProducts(trackingInfo) {
543 document.querySelector('.oe_website_sale').dispatchEvent(
544 new CustomEvent('add_to_cart_event', {'detail': trackingInfo})
545 );
546 }
547 }
548
549 export const cartService = {
550 dependencies: CartService.dependencies,
551 async: ['add'],
552 start(env, dependencies) {
553 return new CartService(env, dependencies);
554 },
555 }
556
557 registry.category('services').add('cart', cartService);