generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcalculate-shipping.js
508 lines (484 loc) · 16.2 KB
/
calculate-shipping.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
const axios = require('axios')
const ecomUtils = require('@ecomplus/utils')
const { getBestPackage } = require('../../../lib/kangu/util')
exports.post = ({ appSdk }, req, res) => {
/**
* Treat `params` and (optionally) `application` from request body to properly mount the `response`.
* JSON Schema reference for Calculate Shipping module objects:
* `params`: https://apx-mods.e-com.plus/api/v1/calculate_shipping/schema.json?store_id=100
* `response`: https://apx-mods.e-com.plus/api/v1/calculate_shipping/response_schema.json?store_id=100
*
* Examples in published apps:
* https://github.com/ecomplus/app-mandabem/blob/master/functions/routes/ecom/modules/calculate-shipping.js
* https://github.com/ecomplus/app-kangu/blob/master/functions/routes/ecom/modules/calculate-shipping.js
* https://github.com/ecomplus/app-jadlog/blob/master/functions/routes/ecom/modules/calculate-shipping.js
*/
const { params, application } = req.body
const { storeId } = req
// setup basic required response object
const response = {
shipping_services: []
}
// merge all app options configured by merchant
const appData = Object.assign({}, application.data, application.hidden_data)
let shippingRules
if (Array.isArray(appData.shipping_rules) && appData.shipping_rules.length) {
shippingRules = appData.shipping_rules
} else {
shippingRules = []
}
const token = appData.kangu_token
const disableShippingRules = appData.unavailable_for
if (!token) {
// must have configured kangu doc number and token
return res.status(409).send({
error: 'CALCULATE_AUTH_ERR',
message: 'Token or document unset on app hidden data (merchant must configure the app)'
})
}
const ordernar = appData.ordernar ? appData.ordernar : 'preco'
if (appData.free_shipping_from_value >= 0) {
response.free_shipping_from_value = appData.free_shipping_from_value
}
const destinationZip = params.to ? params.to.zip.replace(/\D/g, '') : ''
const matchService = (service, name) => {
const fields = ['service_name', 'service_code']
for (let i = 0; i < fields.length; i++) {
if (service[fields[i]]) {
return service[fields[i]].trim().toUpperCase() === name.toUpperCase()
}
}
return true
}
const checkZipCode = rule => {
// validate rule zip range
if (destinationZip && rule.zip_range) {
const { min, max } = rule.zip_range
return Boolean((!min || destinationZip >= min) && (!max || destinationZip <= max))
}
return true
}
const completeAddress = address => {
const { logradouro, numero, complemento, bairro, cidade, distancia } = address
let lineAddress
if (logradouro) {
lineAddress = logradouro
if (numero) {
lineAddress += ', ' + numero
}
if (complemento) {
lineAddress += ' - ' + complemento
}
if (bairro) {
lineAddress += ', ' + bairro
}
if (cidade) {
lineAddress += ', ' + cidade
}
if (logradouro) {
lineAddress += ' - ' + distancia + 'm'
}
} else {
lineAddress = ''
}
return lineAddress
}
let originZip, warehouseCode, docNumber, postingDeadline
let from = appData.from
let isWareHouse = false
if (params.from) {
from = params.from
originZip = params.from.zip
} else if (Array.isArray(appData.warehouses) && appData.warehouses.length) {
for (let i = 0; i < appData.warehouses.length; i++) {
const warehouse = appData.warehouses[i]
if (warehouse && warehouse.zip && checkZipCode(warehouse)) {
const { code } = warehouse
if (!code) {
continue
}
if (
params.items &&
params.items.find(({ quantity, inventory }) => inventory && Object.keys(inventory).length && !(inventory[code] >= quantity))
) {
// item not available on current warehouse
continue
}
originZip = warehouse.zip
isWareHouse = true
if (warehouse.posting_deadline) {
postingDeadline = warehouse.posting_deadline
}
if (warehouse && warehouse.street) {
;['zip', 'street', 'number', 'complement', 'borough', 'city', 'province_code'].forEach(prop => {
if (warehouse[prop]) {
from[prop] = warehouse[prop]
}
})
}
if (warehouse.doc) {
docNumber = warehouse.doc
}
warehouseCode = code
}
}
}
if (!originZip) {
originZip = appData.zip
}
originZip = typeof originZip === 'string' ? originZip.replace(/\D/g, '') : ''
// search for configured free shipping rule
if (Array.isArray(appData.free_shipping_rules)) {
for (let i = 0; i < appData.free_shipping_rules.length; i++) {
const rule = appData.free_shipping_rules[i]
if (rule && checkZipCode(rule)) {
if (!rule.min_amount) {
response.free_shipping_from_value = 0
break
} else if (!(response.free_shipping_from_value <= rule.min_amount)) {
response.free_shipping_from_value = rule.min_amount
}
}
}
}
if (!params.to) {
// just a free shipping preview with no shipping address received
// respond only with free shipping option
res.send(response)
return
}
/* DO THE STUFF HERE TO FILL RESPONSE OBJECT WITH SHIPPING SERVICES */
if (!originZip) {
// must have configured origin zip code to continue
return res.status(409).send({
error: 'CALCULATE_ERR',
message: 'Zip code is unset on app hidden data (merchant must configure the app)'
})
}
if (params.items) {
let pkgKgWeight = 0
let pkgM3Vol = 0
let cartSubtotal = 0
const produtos = []
params.items.forEach((item) => {
const { quantity, dimensions, weight } = item
cartSubtotal += (quantity * ecomUtils.price(item))
let kgWeight = 0
let cubicWeight = 0
if (weight && weight.value) {
switch (weight.unit) {
case 'g':
kgWeight = weight.value / 1000
break
case 'mg':
kgWeight = weight.value / 1000000
break
default:
kgWeight = weight.value
}
}
const cmDimensions = {
height: 5,
width: 10,
length: 10
}
if (dimensions) {
for (const side in dimensions) {
const dimension = dimensions[side]
if (dimension?.value) {
switch (dimension.unit) {
case 'm':
cmDimensions[side] = dimension.value * 100
break
case 'mm':
cmDimensions[side] = dimension.value / 10
break
default:
cmDimensions[side] = dimension.value
}
}
}
let m3 = 1
for (const side in cmDimensions) {
if (cmDimensions[side]) {
m3 *= (cmDimensions[side] / 100)
}
}
if (m3 !== 1) {
pkgM3Vol += (quantity * m3)
// 167 kg/m³
cubicWeight = m3 * 167
}
}
if (kgWeight > 0) {
const unitFinalWeight = cubicWeight < 0.5 || kgWeight > cubicWeight
? kgWeight
: cubicWeight
pkgKgWeight += (quantity * unitFinalWeight)
}
produtos.push({
peso: kgWeight || 0.5,
altura: cmDimensions.height,
largura: cmDimensions.width,
comprimento: cmDimensions.length,
valor: ecomUtils.price(item),
quantidade: quantity
})
})
const body = {
cepOrigem: originZip,
cepDestino: destinationZip,
origem: 'E-Com Plus',
servicos: [
'E',
'X',
'R',
'M'
],
ordernar
}
if (appData.use_kubic_weight || appData.use_cubic_weight) {
body.produtos = [{
peso: pkgKgWeight || 0.5,
altura: 36,
largura: 70,
comprimento: 36,
...getBestPackage(pkgM3Vol),
valor: cartSubtotal,
quantidade: 1
}]
} else {
body.produtos = produtos
}
// send POST request to kangu REST API
return axios.post(
'https://portal.kangu.com.br/tms/transporte/simular',
body,
{
headers: {
token,
accept: 'application/json',
'Content-Type': 'application/json'
},
timeout: 10000
}
).then(({ data, status }) => {
let result
if (typeof data === 'string') {
try {
result = JSON.parse(data)
} catch (e) {
console.log('> kangu invalid JSON response', data)
return res.status(409).send({
error: 'CALCULATE_INVALID_RES',
message: data
})
}
} else {
result = data
}
if (result && Number(status) === 200 && Array.isArray(result)) {
let lowestPriceShipping
result.forEach(kanguService => {
let disableShipping = false
// check if service is not disabled
if (Array.isArray(disableShippingRules) && disableShippingRules.length) {
for (let i = 0; i < disableShippingRules.length; i++) {
if (
disableShippingRules[i] &&
disableShippingRules[i].zip_range &&
checkZipCode(disableShippingRules[i]) &&
disableShippingRules[i].service_name
) {
const unavailable = disableShippingRules[i]
if (
matchService(unavailable, (kanguService.transp_nome || kanguService.descricao))
) {
disableShipping = true
}
}
}
}
if (!disableShipping) {
// parse to E-Com Plus shipping line object
const serviceCode = String(kanguService.servico)
const price = kanguService.vlrFrete
const kanguPickup = Array.isArray(kanguService.pontosRetira)
? kanguService.pontosRetira[0]
: false
const postDeadline = isWareHouse && postingDeadline
? postingDeadline
: appData.posting_deadline
// push shipping service object to response
const shippingLine = {
from: {
...params.from,
...appData.from,
...from,
zip: originZip
},
to: params.to,
price,
total_price: price,
discount: 0,
delivery_time: {
days: parseInt(kanguService.prazoEnt, 10),
working_days: true
},
delivery_instructions: kanguPickup
? `${kanguPickup.nome} - ${completeAddress(kanguPickup.endereco)}`
: undefined,
posting_deadline: {
days: 3,
...postDeadline
},
package: {
weight: {
value: pkgKgWeight,
unit: 'kg'
}
},
warehouse_code: warehouseCode,
custom_fields: [
{
field: 'kangu_reference',
value: kanguPickup
? String(kanguPickup.referencia)
: String(kanguService.referencia)
},
{
field: 'nfe_required',
value: kanguService.nf_obrig === 'N' ? 'false' : 'true'
}
],
flags: ['kangu-ws', `kangu-${serviceCode}`.substr(0, 20)]
}
if (!lowestPriceShipping || lowestPriceShipping.price > price) {
lowestPriceShipping = shippingLine
}
// check for default configured additional/discount price
if (appData.additional_price) {
if (appData.additional_price > 0) {
shippingLine.other_additionals = [{
tag: 'additional_price',
label: 'Adicional padrão',
price: appData.additional_price
}]
} else {
// negative additional price to apply discount
shippingLine.discount -= appData.additional_price
}
// update total price
shippingLine.total_price += appData.additional_price
}
// search for discount by shipping rule
const shippingName = kanguService.transp_nome || kanguService.descricao
if (Array.isArray(shippingRules)) {
for (let i = 0; i < shippingRules.length; i++) {
const rule = shippingRules[i]
if (
rule &&
matchService(rule, shippingName) &&
checkZipCode(rule) &&
!(rule.min_amount > params.subtotal)
) {
// valid shipping rule
if (rule.discount && rule.service_name) {
let discountValue = rule.discount.value
if (rule.discount.percentage) {
discountValue *= (shippingLine.total_price / 100)
}
shippingLine.discount += discountValue
shippingLine.total_price -= discountValue
if (shippingLine.total_price < 0) {
shippingLine.total_price = 0
}
break
}
}
}
}
let label = shippingName
if (appData.services && Array.isArray(appData.services) && appData.services.length) {
const service = appData.services.find(service => {
return service && matchService(service, label)
})
if (service && service.label) {
label = service.label
}
}
const serviceCodeName = shippingName.replaceAll(' ', '_').toLowerCase()
response.shipping_services.push({
label,
carrier: 'kangu',
carrier_doc_number: isWareHouse && docNumber
? docNumber
: typeof kanguService.cnpjTransp === 'string'
? kanguService.cnpjTransp.replace(/\D/g, '').substr(0, 19)
: undefined,
service_name: serviceCode || kanguService.descricao,
service_code: serviceCodeName.substring(0, 70),
shipping_line: shippingLine
})
}
})
if (lowestPriceShipping) {
const { price } = lowestPriceShipping
const discount = typeof response.free_shipping_from_value === 'number' &&
response.free_shipping_from_value <= cartSubtotal
? price
: 0
if (discount) {
lowestPriceShipping.total_price = price - discount
lowestPriceShipping.discount = discount
}
}
res.send(response)
} else {
// console.log(data)
const err = new Error('Invalid Kangu calculate response', storeId, JSON.stringify(body))
err.response = { data, status }
throw err
}
})
.catch(err => {
let { message, response } = err
console.log('>> Kangu message error', message)
console.log('>> Kangu response error', response)
if (response && response.data) {
// try to handle kangu error response
const { data } = response
let result
if (typeof data === 'string') {
try {
result = JSON.parse(data)
} catch (e) {
}
} else {
result = data
}
if (result && result.data) {
// kangu error message
return res.status(409).send({
error: 'CALCULATE_FAILED',
message: result.data
})
}
message = `${message} (${response.status})`
} else {
console.error(err)
}
console.log('error', err)
return res.status(409).send({
error: 'CALCULATE_ERR',
message
})
})
} else {
res.status(400).send({
error: 'CALCULATE_EMPTY_CART',
message: 'Cannot calculate shipping without cart items'
})
}
res.send(response)
}