-
Notifications
You must be signed in to change notification settings - Fork 5
/
order.es6
261 lines (225 loc) · 7.39 KB
/
order.es6
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
(() => {
const DOM = {
$fancybox: $('.fancybox'),
$formErrorText: $('.js-form-error-text'),
$order: $('.js-order-contain'),
$yandexFormWrapper: $('#yandex-form-wrapper'),
yandexForm: '#yandex-form',
productRows: '.div-table-row',
submit: '#submit-order',
fullForm: '#order-form-full',
productCount: '.js-prod-count',
productPrice: '.js-product-price',
remove: '.js-remove',
paymentOptions: 'input[name=payment_type]',
defaultPaymentOptions: 'input[for=id_payment_type_0]',
orderForm: {
name: '#id_name',
phone: '#id_phone',
email: '#id_email',
city: '#id_city',
},
};
const config = {
autocomplete: {
types: ['(cities)'],
componentRestrictions: {
country: 'ru',
},
},
sePayments: ['cash', 'cashless'],
paymentKey: 'payment',
};
const init = () => {
pluginsInit();
setUpListeners();
fillSavedInputs();
restoreSelectedPayment();
};
function pluginsInit() {
cityAutocomplete();
}
function setUpListeners() {
mediator.subscribe(
'onCartUpdate', renderTable, fillSavedInputs,
touchSpinReinit, restoreSelectedPayment, cityAutocomplete,
);
$(DOM.fullForm).submit(() => mediator.publish('onOrderSend', [getProductsData()]));
/**
* Bind events to parent's elements, because of dynamic elements.
*/
DOM.$order.on('click', DOM.submit, submitOrder);
DOM.$order.on('click', DOM.remove, event => removeProduct(getElAttr(event, 'productId'), getElAttr(event, 'productCount')));
DOM.$order.on('change', DOM.productCount, helpers.debounce(changeProductCount, 250));
DOM.$order.on('keyup', 'input', event => storeInput($(event.target)));
}
function getProductsData() {
return $(DOM.productRows).map((_, el) => {
const $el = $(el);
return {
name: $el.find('.js-product-link').text(),
quantity: $el.find(DOM.productCount).val(),
price: parseInt($el.find(DOM.productPrice).attr('productPrice'), 10),
};
}).get();
}
/**
* Return element's attribute value by attr name.
*/
function getElAttr(event, attrName) {
return event.currentTarget.getAttribute(attrName);
}
/**
* Init google cities autocomplete.
*/
function cityAutocomplete() {
const cityField = document.getElementById('id_city');
if (!cityField) return;
const autocompleteItem = new google.maps.places.Autocomplete(cityField, config.autocomplete);
google.maps.event.addListener(autocompleteItem, 'place_changed', () => {
storeInput($(DOM.orderForm.city));
});
}
/**
* Reinit touchspin plugin cause of dynamic DOM.
*/
function touchSpinReinit() {
$(DOM.productCount).TouchSpin(configs.plugins.touchspin);
}
/**
* Fill inputs, which have saved to localstorage value.
* Runs on page load, and on every cart's update.
*/
function fillSavedInputs() {
const getFieldByName = name => $(`#id_${name}`);
for (const fieldName in DOM.orderForm) { // Ignore ESLintBear (no-restricted-syntax)
if ({}.hasOwnProperty.call(DOM.orderForm, fieldName)) {
const $field = getFieldByName(fieldName);
const savedValue = localStorage.getItem(fieldName);
if ($field && savedValue) {
$field.val(savedValue);
}
}
}
}
/**
* Select saved payment if there is one.
*/
function restoreSelectedPayment() {
const savedPayment = localStorage.getItem(config.paymentKey);
if (savedPayment) {
const isSelected = $option => $option.val() === savedPayment;
$(DOM.paymentOptions).each((_, el) => {
$(el).attr('checked', isSelected($(el)));
});
} else {
$(DOM.defaultPaymentOptions).attr('checked', true);
}
}
/**
* Remove Product from Cart.
*/
function removeProduct(productId, count) {
server.removeFromCart(productId)
.then((data) => {
mediator.publish('onCartUpdate', data);
mediator.publish('onProductRemove', [productId, count]);
});
}
/**
* Handle Product's count change in Cart with delay.
*/
function changeProductCount(event) {
const productId = getElAttr(event, 'productId');
const countDiff = event.target.value - getElAttr(event, 'productLastCount');
const data = {
id: productId,
quantity: Math.abs(countDiff),
};
server.changeInCart(productId, event.target.value)
.then((newData) => {
mediator.publish('onCartUpdate', newData);
mediator.publish(countDiff > 0 ? 'onProductAdd' : 'onProductRemove', [data]);
});
}
/**
* Return name (which is value) of a selected payment option.
*/
const getSelectedPayment = () => $(`${DOM.paymentOptions}:checked`).val();
/**
* Return hash with customer's info from form.
*/
const getOrderInfo = () => {
const orderInfo = {
payment_type: getSelectedPayment(),
};
$.each(DOM.orderForm, (name, field) => {
orderInfo[name] = $(field).val();
});
return orderInfo;
};
/**
* Return true if form has valid phone & email.
*/
function isValid(customerInfo) {
return helpers.isPhoneValid(customerInfo.phone) &&
helpers.isEmailValid(customerInfo.email);
}
function renderYandexForm(formData) {
const formHtml = `
<form action="${formData.yandex_kassa_link}" method="POST" id="yandex-form">
<input type="text" name="shopId" value="${formData.shopId}">
<input type="text" name="scid" value="${formData.scid}">
<input type="text" name="shopSuccessURL" value="${formData.shopSuccessURL}">
<input type="text" name="shopFailURL" value="${formData.shopFailURL}">
<input type="text" name="cps_phone" value="${formData.cps_phone}">
<input type="text" name="cps_email" value="${formData.cps_email}">
<input type="text" name="sum" value="${formData.sum}">
<input type="text" name="customerNumber" value="${formData.customerNumber}">
<input type="text" name="orderNumber" value="${formData.orderNumber}">
<input type="text" name="paymentType" value="${formData.paymentType}">
</form>
`;
DOM.$yandexFormWrapper.append($(formHtml));
}
/**
* Before submit:
* 1. Validate user's email and phone.
* 2. Define payment type, if it is Yandex order make request and wait response with form.
* 3. Submit this form.
*/
function submitOrder(event) {
event.preventDefault();
const orderInfo = getOrderInfo();
if (!isValid(orderInfo)) {
DOM.$formErrorText.removeClass('hidden').addClass('shake animated');
return;
}
// disable button to prevent user's multiple clicks;
helpers.setDisabledState($(DOM.submit));
const isYandex = () => !config.sePayments.includes(getSelectedPayment());
if (isYandex()) {
// @todo #473:30m Test order redirect to ya.kassa
server.sendYandexOrder(orderInfo)
.then(formData => renderYandexForm(formData))
// setTimeout to wait "onOrderSend" handling
.then(() => setTimeout(() => $(DOM.yandexForm).submit(), 100));
} else {
setTimeout(() => $(DOM.fullForm).submit(), 100);
}
}
/**
* Store inputted value into LocalStorage.
*/
function storeInput(target) {
localStorage.setItem(target.attr('name'), target.val());
}
/**
* Render table and form.
* Fill in saved form data after.
*/
function renderTable(_, data) {
DOM.$order.html(data.table);
}
init();
})();