/
cart.js
322 lines (267 loc) · 8.1 KB
/
cart.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
import $ from 'jquery';
import prestashop from 'prestashop';
prestashop.cart = prestashop.cart || {};
prestashop.cart.active_inputs = null;
let spinnerSelector = 'input[name="product-quantity-spin"]';
let hasError = false;
let isUpdateOperation = false;
let errorMsg = '';
/**
* Attach Bootstrap TouchSpin event handlers
*/
function createSpin()
{
$.each($(spinnerSelector), function (index, spinner) {
$(spinner).TouchSpin({
verticalbuttons: true,
verticalupclass: 'material-icons touchspin-up',
verticaldownclass: 'material-icons touchspin-down',
buttondown_class: 'btn btn-touchspin js-touchspin js-increase-product-quantity',
buttonup_class: 'btn btn-touchspin js-touchspin js-decrease-product-quantity',
min: parseInt($(spinner).attr('min'), 10),
max: 1000000
});
});
CheckUpdateQuantityOperations.switchErrorStat();
}
$(document).ready(() => {
const productLineInCartSelector = '.js-cart-line-product-quantity';
const promises = [];
prestashop.on('updateCart', () => {
$('.quickview').modal('hide');
});
prestashop.on('updatedCart', () => {
createSpin();
});
createSpin();
const $body = $('body');
function isTouchSpin(namespace) {
return namespace === 'on.startupspin' || namespace === 'on.startdownspin';
}
function shouldIncreaseProductQuantity(namespace) {
return namespace === 'on.startupspin';
}
function findCartLineProductQuantityInput($target) {
var $input = $target.parents('.bootstrap-touchspin').find(productLineInCartSelector);
if ($input.is(':focus')) {
return null;
}
return $input;
}
function camelize(subject) {
let actionTypeParts = subject.split('-');
let i;
let part;
let camelizedSubject = '';
for (i = 0; i < actionTypeParts.length; i++) {
part = actionTypeParts[i];
if (0 !== i) {
part = part.substring(0, 1).toUpperCase() + part.substring(1);
}
camelizedSubject = camelizedSubject + part;
}
return camelizedSubject;
}
function parseCartAction($target, namespace) {
if (!isTouchSpin(namespace)) {
return {
url: $target.attr('href'),
type: camelize($target.data('link-action'))
}
}
let $input = findCartLineProductQuantityInput($target);
if (!$input) {
return;
}
let cartAction = {};
if (shouldIncreaseProductQuantity(namespace)) {
cartAction = {
url: $input.data('up-url'),
type: 'increaseProductQuantity'
};
} else {
cartAction = {
url: $input.data('down-url'),
type: 'decreaseProductQuantity'
}
}
return cartAction;
}
let abortPreviousRequests = () => {
var promise;
while (promises.length > 0) {
promise = promises.pop();
promise.abort();
}
};
var getTouchSpinInput = ($button) => {
return $($button.parents('.bootstrap-touchspin').find('input'));
};
var handleCartAction = (event) => {
event.preventDefault();
let $target = $(event.currentTarget);
let dataset = event.currentTarget.dataset;
let cartAction = parseCartAction($target, event.namespace);
let requestData = {
ajax: '1',
action: 'update'
};
if (typeof cartAction === 'undefined') {
return;
}
abortPreviousRequests();
$.ajax({
url: cartAction.url,
method: 'POST',
data: requestData,
dataType: 'json',
beforeSend: function (jqXHR) {
promises.push(jqXHR);
}
}).then(function (resp) {
CheckUpdateQuantityOperations.checkUpdateOpertation(resp);
var $quantityInput = getTouchSpinInput($target);
$quantityInput.val(resp.quantity);
// Refresh cart preview
prestashop.emit('updateCart', {
reason: dataset
});
}).fail((resp) => {
prestashop.emit('handleError', {
eventType: 'updateProductInCart',
resp: resp,
cartAction: cartAction.type
});
});
};
$body.on(
'click',
'[data-link-action="delete-from-cart"], [data-link-action="remove-voucher"]',
handleCartAction
);
$body.on('touchspin.on.startdownspin', spinnerSelector, handleCartAction);
$body.on('touchspin.on.startupspin', spinnerSelector, handleCartAction);
function sendUpdateQuantityInCartRequest(updateQuantityInCartUrl, requestData, $target) {
abortPreviousRequests();
return $.ajax({
url: updateQuantityInCartUrl,
method: 'POST',
data: requestData,
dataType: 'json',
beforeSend: function (jqXHR) {
promises.push(jqXHR);
}
}).then(function (resp) {
CheckUpdateQuantityOperations.checkUpdateOpertation(resp);
$target.val(resp.quantity);
var dataset;
if ($target && $target.dataset) {
dataset = $target.dataset;
} else {
dataset = resp;
}
// Refresh cart preview
prestashop.emit('updateCart', {
reason: dataset
});
}).fail((resp) => {
prestashop.emit('handleError', {eventType: 'updateProductQuantityInCart', resp: resp})
});
}
function getRequestData(quantity) {
return {
ajax: '1',
qty: Math.abs(quantity),
action: 'update',
op: getQuantityChangeType(quantity)
}
}
function getQuantityChangeType($quantity) {
return ($quantity > 0) ? 'up' : 'down';
}
function updateProductQuantityInCart(event)
{
const $target = $(event.currentTarget);
const updateQuantityInCartUrl = $target.data('update-url');
const baseValue = $target.attr('value');
// There should be a valid product quantity in cart
const targetValue = $target.val();
if (targetValue != parseInt(targetValue) || targetValue < 0 || isNaN(targetValue)) {
$target.val(baseValue);
return;
}
// There should be a new product quantity in cart
const qty = targetValue - baseValue;
if (qty === 0) {
return;
}
$target.attr('value', targetValue);
sendUpdateQuantityInCartRequest(updateQuantityInCartUrl, getRequestData(qty), $target);
}
$body.on(
'focusout keyup',
productLineInCartSelector,
(event) => {
if (event.type === 'keyup') {
if (event.keyCode === 13) {
updateProductQuantityInCart(event);
}
return false;
}
updateProductQuantityInCart(event);
}
);
$body.on(
'click',
'.js-discount .code',
(event) => {
event.stopPropagation();
const $code = $(event.currentTarget);
const $discountInput = $('[name=discount_name]');
$discountInput.val($code.text());
return false;
}
)
});
const CheckUpdateQuantityOperations = {
'switchErrorStat': () => {
/**
* if errorMsg is not empty or if notifications are shown, we have error to display
* if hasError is true, quantity was not updated : we don't disable checkout button
*/
const $checkoutBtn = $('.checkout a');
if ($("#notifications article.alert-danger").length || ('' !== errorMsg && !hasError)) {
$checkoutBtn.addClass('disabled');
}
if ('' !== errorMsg) {
let strError = ' <article class="alert alert-danger" role="alert" data-alert="danger"><ul><li>' + errorMsg + '</li></ul></article>';
$('#notifications .container').html(strError);
errorMsg = '';
isUpdateOperation = false;
if (hasError) {
// if hasError is true, quantity was not updated : allow checkout
$checkoutBtn.removeClass('disabled');
}
} else if (!hasError && isUpdateOperation) {
hasError = false;
isUpdateOperation = false;
$('#notifications .container').html('');
$checkoutBtn.removeClass('disabled');
}
},
'checkUpdateOpertation': (resp) => {
/**
* resp.hasError can be not defined but resp.errors not empty: quantity is updated but order cannot be placed
* when resp.hasError=true, quantity is not updated
*/
hasError = resp.hasOwnProperty('hasError');
let errors = resp.errors || "";
// 1.7.2.x returns errors as string, 1.7.3.x returns array
if (errors instanceof Array) {
errorMsg = errors.join(" ");
} else {
errorMsg = errors;
}
isUpdateOperation = true;
}
};