[IMP] website_sale: keep the cart quantity up-to-date

This commit updates the cart quantity even if the html page comes from
browser cache, i.e. the user comes back to a previous page with the
browser back method.

task-2741846

closes odoo/odoo#84861

Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
This commit is contained in:
Thibault Libioulle
2022-03-25 12:39:46 +01:00
parent f89fce4501
commit d77e7f9472
2 changed files with 46 additions and 0 deletions
+5
View File
@@ -603,6 +603,11 @@ class WebsiteSale(http.Controller):
assert layout_mode in ('grid', 'list'), "Invalid shop layout mode"
request.session['website_sale_shop_layout_mode'] = layout_mode
@http.route(['/shop/cart/quantity'], type='json', auth="public", methods=['POST'], website=True, csrf=False)
def cart_quantity(self):
cart = request.website.sale_get_order()
return cart and cart.cart_quantity or 0
# ------------------------------------------------------
# Checkout
# ------------------------------------------------------
@@ -21,6 +21,13 @@ publicWidget.registry.websiteSaleCartLink = publicWidget.Widget.extend({
init: function () {
this._super.apply(this, arguments);
this._popoverRPC = null;
this._onVisibilityChange = this._onVisibilityChange.bind(this);
},
/**
* @override
*/
willStart() {
return Promise.all([this._super.apply(this, arguments), this._updateCartQuantityValue()]);
},
/**
* @override
@@ -37,8 +44,17 @@ publicWidget.registry.websiteSaleCartLink = publicWidget.Widget.extend({
placement: 'auto',
template: '<div class="popover mycart-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
});
window.addEventListener('visibilitychange', this._onVisibilityChange);
this._updateCartQuantityText();
return this._super.apply(this, arguments);
},
/**
* @override
*/
destroy() {
window.removeEventListener('visibilitychange', this._onVisibilityChange);
this._super(...arguments);
},
//--------------------------------------------------------------------------
// Handlers
@@ -101,6 +117,31 @@ publicWidget.registry.websiteSaleCartLink = publicWidget.Widget.extend({
});
}
},
/**
* @private
* @param {Event} ev
*/
_onVisibilityChange(ev) {
if (ev.target.visibilityState === 'visible'){
this._updateCartQuantityValue().then(this._updateCartQuantityText.bind(this));
}
},
/**
* @private
*/
_updateCartQuantityValue() {
return this._rpc({route: "/shop/cart/quantity"}).then((cartQty) => {
this.cartQty = cartQty;
});
},
/**
* @private
*/
_updateCartQuantityText() {
if (this.cartQty !== undefined) {
this.el.querySelector('.my_cart_quantity').innerText = this.cartQty;
}
}
});
});