@crmcom/self-service-sdk 3.0.0-build.5 → 3.0.0-build.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dataUtil.js DELETED
@@ -1,2269 +0,0 @@
1
- import contacts from "./contacts";
2
- import community from "./community";
3
- import payment from "./payment";
4
- import orders from "./orders";
5
- import config from "./config";
6
- import { httpUtil } from "./httpUtil";
7
- import { logger } from './logger';
8
- import { cache, order_key } from "../../utils/cache";
9
-
10
- export const dataUtil = {
11
- getCurrentTier,
12
- getImageByUsageType,
13
- getProductImageByUsageType,
14
- getLCSName,
15
- getLineItems,
16
- groupedByCategory,
17
- getDeliveryItem,
18
- covertListToString,
19
- getProductPrice,
20
- validateFulfilment,
21
- getTotalCartQuantity,
22
- getTotalCartAmount,
23
- validateComponents,
24
- getTotalBaseItems,
25
- filterContactPreferencesByType,
26
- checkAllowPaymentMethod,
27
- checkAllowOrderByContact,
28
- groupedVariantByAttributes,
29
- findProductByVariantAttributes,
30
- getTotalPerProduct,
31
- getTotalAmountItem,
32
- sortByCardPrimary,
33
- createItemToReorder,
34
- getOrderSummary,
35
- getProductImageBySize,
36
- createEsitmateCartItems,
37
- getImageByUsageTypePortal,
38
- sortPrice,
39
- groupServicesByMonth,
40
- groupBillingPeriod,
41
- getRemainingService,
42
- getCartItemsValid,
43
- getImageByUsageTypeSmallSize,
44
- groupBillingPeriodv2,
45
- groupServicesByMonthv2,
46
- getOfferTypeProgress,
47
- compareMerchants,
48
- calculatePriceByRate,
49
- getBillingPeriod,
50
- checkContactWallet,
51
- sortShortcuts,
52
- getBalanceByType,
53
- groupMyCommunities,
54
- getJoinedCommunities,
55
- getServiceMRR,
56
- getTotalSubscriptionAndService,
57
- getQueueIdByMethod,
58
- checkOrderModalMarketPlace,
59
- onLoadCards,
60
- onLoadA2A,
61
- getConditionNearestExpiry,
62
- sumConditionsByNearestExpiry,
63
- getNextBillingDate,
64
- checkAllowUseAccountFundAmount,
65
- checkAllowUseWalletFundAmount,
66
- getPaymentMethodInfo,
67
- getOrderSummaryV2,
68
- createItemsWithComponents,
69
- getCustomerAddressForOrder,
70
- onGetCurrentAdress,
71
- onInitOrder,
72
- getFulfillmentStoreDetail,
73
- groupRecommendedProductsByCategory,
74
- initDefaultDirectSale,
75
- groupMyCommunitiesByGroup,
76
- getStoreIds,
77
- getEstimationIds
78
- };
79
- export const usage_type = {
80
- offers: 'IMAGE',
81
- offers_merchant: 'APP_LOGO',
82
- offer_detail: 'IMAGE',
83
- offer_detail_merchant: 'APP_LOGO',
84
- offer_map: 'IMAGE',
85
- offer_map_merchant: 'APP_LOGO',
86
- offer_order: 'IMAGE',
87
- product_item: 'IMAGE',
88
- product_detail: 'IMAGE',
89
- refer_friend: 'MARKETING',
90
- catalog: 'IMAGE',
91
- business_logo: 'BUSINESS_APP_LOGO',
92
- wallet_image: "WALLET_IMAGE",
93
- landing_page_bg: "LANDING_PAGE_IMAGE",
94
- delivery_image: "DELIVERY_IMAGE",
95
- pickup_image: "PICKUP_IMAGE",
96
- direct_sale_image: "DIRECT_SALE_IMAGE",
97
- APP_LOGO: "APP_LOGO",
98
- merchants_image: 'APP_LOGO',
99
- carousel_image: 'CAROUSEL',
100
- carousel_image: 'CAROUSEL',
101
- profile_image: 'AVATAR',
102
- promotions: "IMAGE",
103
- app_loader_image: "APP_LOADER_IMAGE",
104
- mobile_background_image: "MOBILE_BACKGROUND_IMAGE",
105
- }
106
-
107
- export const preferences_type = {
108
- order: "ORDERS",
109
- rewards: "REWARDS"
110
- }
111
-
112
- function getCurrentTier(reward_tier) {
113
- var period_value_units = reward_tier && reward_tier.period_value_units ? reward_tier.period_value_units : 0;
114
- var points_needed = reward_tier && reward_tier.maintain_tier && reward_tier.maintain_tier.points_needed ? reward_tier.maintain_tier.points_needed : 0;
115
- var collected_by = reward_tier && reward_tier.maintain_tier && reward_tier.maintain_tier.collected_by ? reward_tier.maintain_tier.collected_by : 0;
116
- var remain_name = reward_tier && reward_tier.name ? reward_tier.name : "";
117
- var progress = reward_tier && reward_tier.progress ? reward_tier.progress : null;
118
- var isProgress = false;
119
- if (progress) {
120
- points_needed = progress && progress.points_needed ? progress.points_needed : 0;
121
- collected_by = progress && progress.collected_by ? progress.collected_by : 0;
122
- remain_name = progress && progress.name ? progress.name : "";
123
- isProgress = true;
124
- }
125
- var percentage = (period_value_units * 100) / (points_needed + period_value_units);
126
- if (isNaN(percentage))
127
- percentage = 0
128
- return {
129
- current_name: reward_tier && reward_tier.name ? reward_tier.name : "",
130
- current_color: reward_tier && reward_tier.colour ? reward_tier.colour : "",
131
- period_value_units: period_value_units,
132
- collected_by: collected_by ? formatDateToDDMMYYYYFrEpoch(collected_by, true) : "",
133
- points_needed: points_needed,
134
- remain_name: remain_name,
135
- percentage : percentage,
136
- isProgress: isProgress,
137
- tier_image: reward_tier.creatives ? reward_tier.creatives[0] : null,
138
- }
139
- }
140
-
141
-
142
- function getImageByUsageType(creatives, type, ignoreType) {
143
- let imageSources = [];
144
- let creative = null;
145
- if (!creatives || creatives.length == 0)
146
- return [];
147
- var isExitType = false;
148
- if (type) {
149
- creatives.forEach(element => {
150
- if (element.usage_type && element.usage_type.toLowerCase() === type.toLowerCase()) {
151
- creative = element;
152
- isExitType = true;
153
- }
154
- });
155
- } else {
156
- if (ignoreType) {
157
- creative = creatives[0];
158
- }
159
- }
160
- if (creative) {
161
- let media = creative.media;
162
- if (media && media.length > 0) {
163
- media.forEach(m => {
164
- if (m.width > 50 && m.height > 50) {
165
- imageSources.push({
166
- uri: m.url,
167
- width: m.width,
168
- height: m.height
169
- })
170
- }
171
- });
172
- } else {
173
- imageSources.push({
174
- uri: creative.url,
175
- width: creative.width,
176
- height: creative.height
177
- })
178
- }
179
- }
180
- return imageSources;
181
- }
182
-
183
- function getImageByUsageTypeSmallSize(creatives, type, ignoreFirstElement) {
184
- let imageSources = [];
185
- let creative = null;
186
- if (!creatives || creatives.length == 0)
187
- return [];
188
- var isExitType = false;
189
- if (type) {
190
- creatives.forEach(element => {
191
- if (element.usage_type && element.usage_type.toLowerCase() === type.toLowerCase()) {
192
- creative = element;
193
- isExitType = true;
194
- }
195
- });
196
- }
197
- // if (!isExitType && !ignoreFirstElement) {
198
- // creative = creatives[0];
199
- // }
200
- //console.log("AAAAAAAAAA creative = ", creative);
201
- if (creative) {
202
- let media = creative.media;
203
- if (media && media.length > 0) {
204
- imageSources.push({
205
- uri: media[0].url,
206
- width: media[0].width,
207
- height: media[0].height
208
- })
209
- } else {
210
- imageSources.push({
211
- uri: creative.url,
212
- width: creative.width,
213
- height: creative.height
214
- })
215
- }
216
- }
217
- //console.log("AAAAAAAAAA");
218
- //console.log("AAAAAAAAAA");
219
- //console.log("AAAAAAAAAA");
220
- //console.log("AAAAAAAAAA");
221
- //console.log("AAAAAAAAAA imageSources:",imageSources);
222
- return imageSources;
223
- }
224
-
225
- function getImageByUsageTypePortal(creatives, type, ignoreFirstElement) {
226
- let imageSources = [];
227
- let creative = null;
228
- if (!creatives || creatives.length == 0)
229
- return [];
230
- var isExitType = false;
231
- if (type) {
232
- creatives.forEach(element => {
233
- if (element.usage_type && element.usage_type.toLowerCase() === type.toLowerCase()) {
234
- creative = element;
235
- isExitType = true;
236
- }
237
- });
238
- }
239
- if (!isExitType && !ignoreFirstElement) {
240
- creative = creatives[0];
241
- }
242
- if (creative) {
243
- let media = creative.media;
244
- if (media && media.length > 0) {
245
- media.forEach(m => {
246
- if (m.width > 50 && m.height > 50) {
247
- imageSources.push({
248
- url: m.url,
249
- width: m.width,
250
- height: m.height
251
- })
252
- }
253
- });
254
- } else {
255
- imageSources.push({
256
- url: creative.url,
257
- width: creative.width,
258
- height: creative.height
259
- })
260
- }
261
- }
262
- return imageSources.length > 0 ? imageSources[0] : null;
263
- }
264
-
265
-
266
- function getProductImageByUsageType(creatives) {
267
- if (!creatives || creatives.length == 0)
268
- return null;
269
- var isExitType = false;
270
- var image = null;
271
- creatives.forEach(element => {
272
- if (element.usage_type && element.usage_type.toLowerCase() === usage_type.product_detail.toLowerCase()) {
273
- image = element;
274
- isExitType = true;
275
- }
276
- });
277
- if (!isExitType) {
278
- var isExitNextType = false;
279
- creatives.forEach(element => {
280
- if (element.usage_type && element.usage_type.toLowerCase() === usage_type.product_item.toLowerCase()) {
281
- image = element;
282
- isExitNextType = true;
283
- }
284
- });
285
- if (!isExitNextType) {
286
- image = creatives[0]
287
- }
288
- }
289
- if (image && image.url)
290
- return image;
291
- return null;
292
- }
293
-
294
- function getLCSName(code) {
295
- var name = code ? code : "";
296
- if (code === 'IN_PROGRESS')
297
- name = 'In Progress'
298
- else if (code === 'CANCELLED')
299
- name = 'Cancelled'
300
- else if (code === 'NEW')
301
- name = 'New'
302
- else if (code === 'COMPLETED')
303
- name = 'Completed'
304
- else if (code === 'CANCELLED')
305
- name = 'Cancelled'
306
- else if (code === 'PENDING')
307
- name = 'Pending'
308
- return name;
309
- }
310
-
311
- /////////////Order
312
- function getLineItems(cart) {
313
- var lineItems = [];
314
- cart = [...cart]
315
- cart.forEach(p => {
316
- let element = { ...p };
317
- var item = {
318
- id: element.id,
319
- quantity: element.quantity,
320
- price: element.price,
321
- tax_model: 'TAX_INCLUSIVE',
322
- notes: element.notes ? element.notes : null
323
- }
324
- var components = []
325
- let _components = element.components ? [...element.components] : []
326
- if (_components.length > 0) {
327
- _components.forEach(c => {
328
- var component = {
329
- id: c.id,
330
- quantity: c.quantity,
331
- tax_model: 'TAX_INCLUSIVE'
332
- }
333
- if (element.price_selected && (element.classification == "TERMED_SERVICE" || element.classification == "ONE_TIME_SERVICE")) {
334
- if (c.pricing && c.pricing.length > 0) {
335
- component.price_terms_id = c.pricing[0].id;
336
- }
337
- }
338
- components.push(component);
339
- });
340
- }
341
- if (components.length > 0) {
342
- item.components = components
343
- }
344
- if (element.price_selected && (element.classification == "TERMED_SERVICE" || element.classification == "ONE_TIME_SERVICE")) {
345
- item.price_terms_id = element.price_selected.id;
346
- }
347
- lineItems.push(item);
348
- });
349
- return lineItems;
350
- }
351
-
352
- function getTotalBaseItems(cart) {
353
- var total = 0;
354
- cart.forEach(element => {
355
- total = total + element.totalAmount;
356
- });
357
- return total;
358
- }
359
-
360
- function groupedByCategory(order_items, allCategories, categorySelected, subCategory) {
361
- var items = order_items.reduce((acc, curr) => {
362
- var categories = curr.categories ? curr.categories : [];
363
- for (let i = 0; i < categories.length; i++) {
364
- let category = categories[i];
365
- if ((subCategory && category.id === subCategory) || !subCategory || subCategory == 'All') {
366
- var isExist = checkCategoryIsExist(category, allCategories, categorySelected);
367
- if (isExist) {
368
- const itemExists = acc.find(item => category && category.id === item.category_id)
369
- if (itemExists) {
370
- itemExists.products.push(curr);
371
- } else {
372
- acc.push({ category_id: category.id, category_name: category.name, products: [curr] })
373
- }
374
- }
375
- }
376
- }
377
- return acc;
378
- }, []);
379
- return items;
380
- }
381
-
382
- function checkCategoryIsExist(category, allCategories, categorySelected) {
383
- var isExist = false;
384
- if (allCategories.length > 0) {
385
- var cat = allCategories.filter(c => {
386
- if (categorySelected)
387
- return c.id == category.id && c.parent && c.parent.id === categorySelected.id;
388
- else
389
- return c.id == category.id
390
- })
391
- if (cat && cat.length > 0) {
392
- isExist = true;
393
- }
394
- }
395
- return isExist;
396
- }
397
-
398
- function getDeliveryItem(items) {
399
- var deleveryItem = null;
400
- if (items && items.length > 0) {
401
- var item = items.filter(line => {
402
- return line.product.name && line.product.name.toLowerCase().includes('delivery')
403
- })
404
- if (item && item.length > 0) {
405
- deleveryItem = item[0];
406
- }
407
- }
408
- return deleveryItem;
409
- }
410
-
411
- function covertListToString(list, key) {
412
- var componentStr = '';
413
- list.forEach(item => {
414
- componentStr = componentStr + item[key] + ", ";
415
- });
416
- if (componentStr) {
417
- componentStr = componentStr.substr(0, componentStr.length - 2);
418
- }
419
- return componentStr;
420
- }
421
-
422
- function getProductPrice(pricing) {
423
- if (pricing && pricing.length > 0) {
424
- pricing = pricing.sort(sortPrice);
425
- }
426
- var amount = 0;
427
- if (pricing && pricing.length > 0) {
428
- amount = pricing[0].price;
429
- }
430
- return amount;
431
- }
432
- function getBillingPeriod(pricing) {
433
- if (pricing && pricing.length > 0) {
434
- pricing = pricing.sort(sortPrice);
435
- }
436
- var billing_period = {};
437
- if (pricing && pricing.length > 0) {
438
- billing_period.duration = pricing[0].price_terms && pricing[0].price_terms[0].billing_period ? pricing[0].price_terms[0].billing_period.duration : null;
439
- billing_period.uot = pricing[0].price_terms && pricing[0].price_terms[0].billing_period ? pricing[0].price_terms[0].billing_period.uot : null;
440
- }
441
- return billing_period;
442
- }
443
-
444
- export function getProductPricePrimary(pricing) {
445
- let pricePrimary = null;
446
- if (pricing && pricing.length > 0) {
447
- pricing = pricing.sort(sortPrice);
448
- }
449
- if (pricing && pricing.length > 0) {
450
- pricePrimary = pricing[0];
451
- }
452
- return pricePrimary;
453
- }
454
- function sortPrice(n1, n2) {
455
- if (n1.price > n2.price) {
456
- return 1;
457
- } else if (n1.price < n2.price) {
458
- return -1
459
- } else {
460
- return 0;
461
- }
462
- }
463
- function validateFulfilment(fulfilled_by) {
464
- var acceptToChangeFulfilled = false;
465
- if (fulfilled_by.length === 1) {
466
- acceptToChangeFulfilled = false;
467
- } else {
468
- // return true;
469
- //disable temporarily as Sozos requested on 02/09/2020 to be able to test iPham
470
- var isNoParentOrg = false;
471
- fulfilled_by.forEach(element => {
472
- if (!element.parent_organisation) {
473
- isNoParentOrg = true;
474
- }
475
- });
476
- if (isNoParentOrg) {
477
- acceptToChangeFulfilled = true;
478
- } else {
479
- acceptToChangeFulfilled = false;
480
- }
481
- }
482
- logger.debug("acceptToChangeFulfilled:", acceptToChangeFulfilled);
483
- return acceptToChangeFulfilled;
484
- }
485
-
486
- function getTotalCartQuantity(carts) {
487
- var total = 0;
488
- carts.forEach(cart => {
489
- total = total + cart.quantity
490
- });
491
- return total;
492
- }
493
-
494
- function getTotalCartAmount(carts) {
495
- var total = 0;
496
- carts.forEach(cart => {
497
- total = total + cart.totalAmount
498
- });
499
- return Math.round(total * 100) / 100;
500
- }
501
-
502
- function validateComponents(components, componentsSelected) {
503
- var componentRequireSelected = [];
504
- for (let i = 0; i < components.length; i++) {
505
- var component = components[i];
506
- var minimum = component.mandatory ? (component.minimum_quantity ? component.minimum_quantity : 1) : 0;
507
- if (minimum > 0) {
508
- var selected = componentsSelected.filter(c => {
509
- return c.id === component.id || c.item_id == component.item_id
510
- })
511
- if (selected.length == 0) {
512
- componentRequireSelected.push(component);
513
- }
514
- }
515
- }
516
- return componentRequireSelected;
517
- }
518
-
519
- function filterContactPreferencesByType(data, type) {
520
- var filterData = [];
521
- if (data && data.length > 0) {
522
- filterData = data.filter(item => {
523
- return item.type == type;
524
- })
525
- }
526
- if (filterData.length > 0) {
527
- return filterData[0]
528
- }
529
- return null;
530
- }
531
-
532
- function checkAllowPaymentMethod(type, methods_allow) {
533
- var isAllow = false;
534
- if (methods_allow && methods_allow.length > 0) {
535
- methods_allow.forEach(element => {
536
- if (element.payment_method_type && element.payment_method_type == type) {
537
- isAllow = true;
538
- }
539
- });
540
- }
541
- return isAllow;
542
- }
543
-
544
- async function checkAllowOrderByContact(agreement_countries,contact) {
545
- try {
546
- if(cache.getIsGuest()){
547
- return true;
548
- }
549
-
550
- if(!contact)
551
- {
552
- let result = await contacts.getContact();
553
- if (result.code == 'OK') {
554
- contact = result.data;
555
- }
556
- }
557
- if (contact.country_of_agreement)
558
- {
559
- if (agreement_countries.length == 0) {
560
- return false;
561
- } else {
562
- var countrySupport = agreement_countries.filter(e => {
563
- return e.country == contact.country_of_agreement;
564
- })
565
- if (countrySupport && countrySupport.length > 0) {
566
- return true;
567
- } else {
568
- return false;
569
- }
570
- }
571
- } else {
572
- return false;
573
- }
574
-
575
- } catch (error) {
576
- return false;
577
- }
578
-
579
- }
580
-
581
- function groupedVariantByAttributes(variants) {
582
- var items = variants.reduce((acc, curr) => {
583
- var variant_attributes = curr.characteristics ? curr.characteristics : [];
584
- for (var i = 0; i < variant_attributes.length; i++) {
585
- var attributes = { ...variant_attributes[i] };
586
- const itemExists = acc.find(item => attributes.key == item.key)
587
- if (itemExists) {
588
- const variantExit = itemExists.variations.find(item => item.value == variant_attributes[i].value)
589
- if (!variantExit || variantExit.length == 0) {
590
- var variant = { value: variant_attributes[i].value, ...createVariantObject(curr) };
591
- itemExists.variations.push(variant);
592
- }
593
- } else {
594
- var variant = { value: variant_attributes[i].value, ...createVariantObject(curr) }
595
- acc.push({ key: variant_attributes[i].key, label: variant_attributes[i].label, variations: [variant] })
596
- }
597
- }
598
- return acc;
599
- }, []);
600
- return items;
601
- }
602
-
603
- function createVariantObject(variation) {
604
- var element = {};
605
- element.composition = variation.composition;
606
- element.creatives = variation.creatives;
607
- element.id = variation.id;
608
- element.pricing = variation.pricing;
609
- element.price = getProductPrice(variation.pricing);
610
- element.sku = variation.sku;
611
- element.type = variation.type;
612
- return element;
613
- }
614
-
615
- function findProductByVariantAttributes(variations, variantSelected) {
616
- let variants = variations;
617
- variantSelected.forEach(selected => {
618
- variants = filterVariant(variants, selected);
619
- });
620
- return variants
621
- }
622
-
623
- function filterVariant(variants, variantSelected) {
624
- let _variations = variants.filter(variant => {
625
- var variant_attributes = variant.characteristics;
626
- if (variant_attributes && variant_attributes.length > 0) {
627
- let existingAttr = variant_attributes.filter(v => {
628
- return v.key == variantSelected.key && v.value == variantSelected.value
629
- })
630
- if (existingAttr.length > 0) {
631
- return variant;
632
- }
633
- }
634
- })
635
- return _variations;
636
- }
637
-
638
- function getTotalPerProduct(product, isPortal) {
639
- if (product) {
640
- var total = product.price;
641
- if (isPortal) {
642
- total = product.cost_before_discount;
643
- }
644
- if (product.components) {
645
- product.components.forEach(element => {
646
- total = total + element.price;
647
- });
648
- }
649
- if (isPortal) {
650
- total = total * product.quantity
651
- }
652
- return total;
653
- } return 0;
654
- }
655
- function getTotalAmountItem(product) {
656
- var total = product.cost ? product.cost : 0;
657
- var quantity = product.quantity ? product.quantity : 0;
658
- let componentAmount = 0;
659
- if (product.components) {
660
- product.components.forEach(element => {
661
- componentAmount = componentAmount + element.price;
662
- });
663
- componentAmount = componentAmount * 2;
664
- }
665
- return total + componentAmount;
666
- }
667
- function sortByCardPrimary(n1, n2) {
668
- if (n1.is_primary)
669
- return -1;
670
- else if (n2.is_primary)
671
- return 1;
672
- else return 0;
673
- }
674
-
675
- function createItemToReorder(item, isPortal) {
676
- let product = item.product
677
- let product_key = newGUID();
678
- var components = product && product.components ? product.components : null;
679
- var variant_attributes = product && product.variant_attributes ? product.variant_attributes : null;
680
- var productToBeAdded = {
681
- id: product.id,
682
- default_product_id: product.id,
683
- key: product_key,
684
- name: product.name,
685
- description: product.description,
686
- variant_selected: variant_attributes,
687
- components: components,
688
- quantity: item.quantity,
689
- totalAmount: getTotalPerProduct(product, isPortal),
690
- price: product.price,
691
- creatives: product.creatives,
692
- notes: item.notes ? item.notes : null
693
- }
694
- return productToBeAdded;
695
- }
696
-
697
- function getOrderSummary(estimate_order_result, isUseWalletFund, request_amount_from_wallet_funds, isValidAmountWalletFund, isUseAccountFund, paymentMethod) {
698
- var invoice_estimate = estimate_order_result ? estimate_order_result.invoice_estimate : null;
699
- let billing_estimate = estimate_order_result && estimate_order_result.service_delivery_estimate && estimate_order_result.service_delivery_estimate.length > 0 ? estimate_order_result.service_delivery_estimate[0].billing_estimate : null;
700
- let service_invoice_estimate = billing_estimate && billing_estimate.invoicing && billing_estimate.invoicing.length > 0 ? billing_estimate.invoicing[0] : null;
701
- let accountFundAmount = 0;
702
- var wallet_funds_amount = invoice_estimate && invoice_estimate.wallet_funds_amount ? invoice_estimate.wallet_funds_amount : 0;
703
- var wallet_funds_amount_service = service_invoice_estimate && service_invoice_estimate.wallet_funds_amount ? service_invoice_estimate.wallet_funds_amount : 0;
704
- let pay_at_next_bill = null;
705
- if (isValidAmountWalletFund && request_amount_from_wallet_funds) {
706
- wallet_funds_amount = Number(request_amount_from_wallet_funds);
707
- }
708
- if (isUseAccountFund) {
709
- if (invoice_estimate) {
710
- accountFundAmount = invoice_estimate.account_credit ? invoice_estimate.account_credit : 0;
711
- }
712
- if (service_invoice_estimate) {
713
- accountFundAmount = service_invoice_estimate.account_funds ? service_invoice_estimate.account_funds : 0;
714
- }
715
- }
716
- if (accountFundAmount < 0) {
717
- accountFundAmount = 0;
718
- }
719
- let subTotal = invoice_estimate ? invoice_estimate.total_price : 0;
720
- let totalAmount = invoice_estimate ? invoice_estimate.total : 0;
721
- let total_discount_amount = invoice_estimate ? invoice_estimate.discount_incl_tax : 0;
722
- let amountDue = invoice_estimate ? invoice_estimate.amount_due : 0;
723
- if (service_invoice_estimate) {
724
- // subTotal = subTotal + (service_invoice_estimate.total_price ? service_invoice_estimate.total_price : 0);
725
- // total_discount_amount = total_discount_amount + (service_invoice_estimate.total_discount_incl_tax ? service_invoice_estimate.total_discount_incl_tax : 0)
726
- // amountDue = amountDue + (service_invoice_estimate.amount_due ? service_invoice_estimate.amount_due : 0)
727
- // if (accountFundAmount) {
728
- // subTotal = subTotal - accountFundAmount;
729
- // if (subTotal < 0) {
730
- // subTotal = 0;
731
- // }
732
- // }
733
- pay_at_next_bill = { ...service_invoice_estimate }
734
- }
735
- if (accountFundAmount > 0) {
736
- if (accountFundAmount <= totalAmount) {
737
- amountDue = totalAmount - accountFundAmount;
738
- } else {
739
- accountFundAmount = totalAmount;
740
- amountDue = 0;
741
- wallet_funds_amount = 0;
742
- }
743
- if (amountDue > 0 && paymentMethod && paymentMethod != 'CRM_WALLET') {
744
- if (wallet_funds_amount >= amountDue) {
745
- wallet_funds_amount = amountDue;
746
- amountDue = amountDue - wallet_funds_amount;
747
- } else {
748
- amountDue = amountDue - wallet_funds_amount;
749
- }
750
- }
751
- }
752
- let pay_upfront = null;
753
- if (invoice_estimate) {
754
- pay_upfront = {
755
- subTotalAmount: subTotal,
756
- wallet_funds_amount: wallet_funds_amount,
757
- amountDue: amountDue < 0 ? 0 : amountDue,
758
- total_discount_amount: total_discount_amount,
759
- accountFundAmount: accountFundAmount,
760
- totalAmount: totalAmount,
761
- }
762
- }
763
- return {
764
- subTotalAmount: subTotal,
765
- totalAmount: totalAmount,
766
- wallet_funds_amount: wallet_funds_amount + wallet_funds_amount_service,
767
- amountDue: amountDue < 0 ? 0 : amountDue,
768
- total_discount_amount: total_discount_amount,
769
- accountFundAmount: accountFundAmount,
770
- pay_at_next_bill: pay_at_next_bill,
771
- pay_upfront: pay_upfront
772
- }
773
- }
774
-
775
-
776
- function getProductImageBySize(creatives, size, type) {
777
- let imageObject = null;
778
- if (!type) {
779
- type = usage_type.product_item;
780
- }
781
- if (!creatives || creatives.length == 0)
782
- return null;
783
- let imageEixstByType = creatives.filter(c => {
784
- return c.usage_type && c.usage_type.toLowerCase() == type.toLowerCase();
785
- })
786
- if (!imageEixstByType || imageEixstByType.length == 0) {
787
- if (type == usage_type.product_item) {
788
- type = usage_type.product_detail;
789
- } else {
790
- type = usage_type.product_item;
791
- }
792
- imageEixstByType = creatives.filter(c => {
793
- return c.usage_type && c.usage_type.toLowerCase() == type.toLowerCase();
794
- })
795
- }
796
- if (imageEixstByType && imageEixstByType.length > 0) {
797
- let media = imageEixstByType[0].media;
798
- if (media && media.length > 0) {
799
- if (size == 'large') {
800
- imageObject = media[media.length - 1];
801
- } else {
802
- imageObject = media[0];
803
- }
804
- } else {
805
- imageObject = imageEixstByType[0];
806
- }
807
- }
808
- return imageObject;
809
- }
810
-
811
- function createEsitmateCartItems(estimateResult, localCartsData,isMultimerchant) {
812
- let physicalGoodLineItems = estimateResult.invoice_estimate ? estimateResult.invoice_estimate.items : [];
813
- let invalidItems = estimateResult.invalid_products ? estimateResult.invalid_products : [];
814
- let service_delivery_estimate = estimateResult.service_delivery_estimate && estimateResult.service_delivery_estimate.length > 0 ? estimateResult.service_delivery_estimate[0].billing_estimate : null;
815
- let serviceLineItems = service_delivery_estimate && service_delivery_estimate.invoicing && service_delivery_estimate.invoicing.length > 0 ? service_delivery_estimate.invoicing[0].line_items : [];
816
- let cartItems = [];
817
- //find the order through estimateResult for each item in localCartsData
818
- let estimateResultsOrders= estimateResult.orders ? estimateResult.orders : [];
819
- if (localCartsData && localCartsData.length > 0 &&isMultimerchant) {
820
- for(let item of localCartsData)
821
- {
822
- let order= estimateResultsOrders.find(order => order.invoice_estimate&&
823
- order.invoice_estimate.items && order.invoice_estimate.items.length>0 &&
824
- order.invoice_estimate.items.find(o => o.product.id== item.id));
825
-
826
- if(order)
827
- {
828
- item.order=order;
829
- }
830
-
831
- }
832
- }
833
- let localCartsDataValid = getCartItemsValid(localCartsData, invalidItems);
834
-
835
- let estimateMainPGProducts = getMainProducts(physicalGoodLineItems);
836
- let estimateMainServices = getMainProducts(serviceLineItems);
837
- let estimatePGComponents = getComponentsProduct(physicalGoodLineItems);
838
- let estimateServiceComponents = getComponentsProduct(serviceLineItems);
839
-
840
- localCartsDataValid.forEach(cart => {
841
- let isService = cart.classification == "TERMED_SERVICE" || cart.classification == "ONE_TIME_SERVICE";
842
- let products = null;
843
- if (isService) {
844
- products = estimateMainServices.filter(p => {
845
- return p.product.id == cart.id
846
- })
847
- } else {
848
- products = estimateMainPGProducts.filter(p => {
849
- return p.product.id == cart.id
850
- })
851
- }
852
-
853
- if (products && products.length > 0) {
854
- let subTotalAmount = products[0].pricing;
855
- cart = { ...cart, price: subTotalAmount }
856
- }
857
- let componentsSelected = [];
858
- if (cart.components && cart.components.length > 0) {
859
- cart.components.forEach(component => {
860
- let components = [];
861
- if (isService) {
862
- components = estimateServiceComponents.filter(c => {
863
- return c.product.id == component.id && cart.id == c.bundle_product.id
864
- })
865
- } else {
866
- components = estimatePGComponents.filter(c => {
867
- return c.product.id == component.id && cart.id == c.bundle_product.id
868
- })
869
- }
870
- if (components && components.length > 0) {
871
- let subTotalAmount = components[0].pricing;
872
- component = { ...component, price: subTotalAmount };
873
- }
874
- componentsSelected.push(component);
875
- });
876
- cart.components = componentsSelected;
877
- }
878
- cartItems.push(cart);
879
- });
880
- return cartItems;
881
- }
882
- function getCartItemsValid(carts, invalid_products) {
883
- let localCartsDataValid = []
884
- carts.forEach(p => {
885
- var isValid = true;
886
- invalid_products.forEach(ip => {
887
- if ((ip.product.id == p.default_product_id || ip.product.id == p.id) ) {
888
- p.in_stock = ip.in_stock;
889
- p.initial_quantity = p.quantity;
890
- if(ip.in_stock!=null && ip.in_stock < p.quantity)
891
- {
892
- p.quantity = ip.in_stock;
893
- }
894
- }
895
- });
896
- if (isValid) {
897
- localCartsDataValid.push(p);
898
- }
899
- })
900
- return localCartsDataValid;
901
- }
902
- function getMainProducts(estimate_line_items) {
903
- let products = estimate_line_items.filter(item => {
904
- return !item.bundle_product;
905
- })
906
- return products;
907
- }
908
-
909
- function getComponentsProduct(estimate_line_items) {
910
- let products = estimate_line_items.filter(item => {
911
- return item.bundle_product && item.bundle_product.id;
912
- })
913
- return products;
914
- }
915
-
916
- function groupServicesByMonth(services) {
917
- let newService = {};
918
- if (services.length > 0) {
919
- services.forEach(element => {
920
- let service = element.service;
921
- if (service.price && service.price.billing_period && service.price.billing_period.uot == 'MONTH') {
922
- let duration = service.price.billing_period.duration;
923
- let servicePeriod = newService[duration] ? newService[duration] : [];
924
- servicePeriod.push(element);
925
- newService[duration] = servicePeriod;
926
- }
927
- });
928
- }
929
- return newService;
930
- }
931
-
932
- function groupServicesByMonthv2(services, currentPeriod) {
933
- let newService = [];
934
- if (services && services.length > 0 && currentPeriod) {
935
- services.forEach(element => {
936
- let service = element;
937
- let billing_period = service.price ? service.price.billing_period : null;
938
- if (billing_period) {
939
- if (currentPeriod.uot == billing_period.uot && currentPeriod.duration == billing_period.duration) {
940
- newService.push(element);
941
- }
942
- }
943
- });
944
- }
945
- return newService;
946
- }
947
-
948
- function groupBillingPeriod(services) {
949
- let period = [];
950
- if (services.length > 0) {
951
- services.forEach(element => {
952
- let service = element.service;
953
- if (service.price && service.price.billing_period && service.price.billing_period.uot == 'MONTH') {
954
- if (service.price.billing_period.duration) {
955
- let periodExis = period.filter(p => {
956
- return p == service.price.billing_period.duration
957
- })
958
- if (!periodExis || periodExis.length == 0) {
959
- period.push(service.price.billing_period.duration)
960
- }
961
- }
962
- }
963
- });
964
- }
965
- return period;
966
- }
967
-
968
- function groupBillingPeriodv2(services) {
969
- let period = [];
970
- if (services.length > 0) {
971
- services.forEach(element => {
972
- let billing_period = element.price ? element.price.billing_period : null;
973
- let oneTime = element.product && element.product.classification && element.product.classification == "ONE_TIME_SERVICE";
974
- if (billing_period) {
975
- let uot = billing_period.uot;
976
- let duration = billing_period.duration;
977
- let periodExist = period.filter(p => {
978
- return p.uot == uot && p.duration == duration;
979
- })
980
- if (!periodExist || periodExist.length == 0) {
981
- period.push({
982
- uot: uot,
983
- duration: duration,
984
- oneTime: oneTime
985
- })
986
- }
987
- }
988
- });
989
- }
990
- return period;
991
- }
992
-
993
- function getRemainingService(services) {
994
- let totalData = 0;
995
- let totalRemaining = 0;
996
- services.forEach(service => {
997
- const products_allowance = service.products_allowance ? service.products_allowance : [];
998
- let productWifi = products_allowance.filter(p => {
999
- return p.name.toLowerCase() == "Wifi".toLowerCase();
1000
- })
1001
- if (productWifi && productWifi.length > 0) {
1002
- totalData = totalData + (productWifi[0] && productWifi[0].remaining_usage ? productWifi[0].remaining_usage.per_transaction : 0);
1003
- totalRemaining = totalRemaining + (productWifi[0] && productWifi[0].remaining_usage ? productWifi[0].remaining_usage.per_day : 0);
1004
- }
1005
- });
1006
- return ({
1007
- totalData: totalData,
1008
- totalRemaining: totalRemaining
1009
- })
1010
- }
1011
-
1012
- function getOfferTypeProgress(item) {
1013
- const isAchievement = item.type === "ACHIEVEMENT";
1014
- const perfType = item.performance_data?.type;
1015
- const isShowProgress =
1016
- item.performance_enabled &&
1017
- item.performance_data &&
1018
- (
1019
- isAchievement ||
1020
- perfType === 'PRODUCT' ||
1021
- perfType === 'AMOUNT' ||
1022
- (isAchievement && perfType === 'EVENT') // 👈 force progress for ACHIEVEMENT + EVENT
1023
- );
1024
-
1025
- const isShowEntry =
1026
- item.performance_enabled &&
1027
- item.performance_data &&
1028
- perfType === 'EVENT' &&
1029
- !isAchievement; // 👈 only entries when NOT achievement
1030
-
1031
- return ({
1032
- isShowProgress: isShowProgress,
1033
- isShowEntry: isShowEntry,
1034
- current_entries: item.performance_data ? item.performance_data.current : 0,
1035
- percentage_progress: item.performance_data ? item.performance_data.progress : 0,
1036
- })
1037
- }
1038
-
1039
- function compareMerchants(fulfillments, orgNetworks) {
1040
- let merchants = [];
1041
- if (fulfillments && fulfillments.length > 0 && orgNetworks && orgNetworks.length > 0) {
1042
- for (let i = 0; i < fulfillments.length; i++) {
1043
- const fulfillment = fulfillments[i];
1044
- let existingMerchant = orgNetworks.filter(x => x.id === fulfillment.id);
1045
- if (existingMerchant && existingMerchant.length > 0) merchants.push(fulfillment);
1046
- }
1047
- }
1048
- return merchants;
1049
-
1050
- }
1051
-
1052
- function calculatePriceByRate({ quantity, default_price, pricing }) {
1053
- let price = default_price * quantity;
1054
- if (pricing && pricing.length > 0) {
1055
- let mode = pricing[0].rate_model;
1056
- let tiers = pricing[0].tiers
1057
- if (mode == 'STAIRSTEP') {
1058
- price = calculateStairstepMode(quantity, tiers);
1059
- } else if (mode == 'TIERED') {
1060
- price = calculateTieredMode(quantity, tiers);
1061
- } else if (mode == 'VOLUME') {
1062
- price = calculateVolumnMode(quantity, tiers);
1063
- }
1064
- }
1065
- return price;
1066
- }
1067
-
1068
- function calculateTieredMode(quantity, tiers) {
1069
- let price = 0;
1070
- let index = 0;
1071
- for (let i = 0; i < tiers.length; i++) {
1072
- let lower_tier = tiers[i].lower_tier;
1073
- let upper_tier = tiers[i].upper_tier;
1074
- if ((upper_tier && quantity >= lower_tier && quantity <= upper_tier) || (!upper_tier && quantity >= lower_tier)) {
1075
- price = tiers[i].price;
1076
- index = i;
1077
- break;
1078
- }
1079
- }
1080
- if (index > 0) {
1081
- let prevPrice = 0;
1082
- let tierQuantity = quantity;
1083
- for (let j = 0; j < index; j++) {
1084
- tierQuantity = quantity - tiers[j].upper_tier;
1085
- let currentTierPrice = tiers[j].price ? tiers[j].price : 0;
1086
- let currentTierQuantity = tiers[j].upper_tier ? (tiers[j].upper_tier - tiers[j].lower_tier + 1) : (quantity - tiers[j].lower_tier + 1);
1087
- prevPrice = prevPrice + (currentTierQuantity * currentTierPrice);
1088
- }
1089
- if (tierQuantity < 0) {
1090
- tierQuantity = 1;
1091
- }
1092
- price = (price * tierQuantity) + prevPrice;
1093
- } else {
1094
- price = price * quantity
1095
- }
1096
- return price;
1097
- }
1098
-
1099
- function calculateVolumnMode(quantity, tiers) {
1100
- let price = 0;
1101
- for (let i = 0; i < tiers.length; i++) {
1102
- let lower_tier = tiers[i].lower_tier;
1103
- let upper_tier = tiers[i].upper_tier;
1104
- if ((upper_tier && quantity >= lower_tier && quantity <= upper_tier) || (!upper_tier && quantity >= lower_tier)) {
1105
- price = tiers[i].price * quantity;
1106
- break;
1107
- }
1108
- }
1109
- return price;
1110
- }
1111
-
1112
- function calculateStairstepMode(quantity, tiers) {
1113
- let price = 0;
1114
- for (let i = 0; i < tiers.length; i++) {
1115
- let lower_tier = tiers[i].lower_tier;
1116
- let upper_tier = tiers[i].upper_tier;
1117
- if ((upper_tier && quantity >= lower_tier && quantity <= upper_tier) || (!upper_tier && quantity >= lower_tier)) {
1118
- price = tiers[i].price;
1119
- break;
1120
- }
1121
- }
1122
- return price;
1123
- }
1124
-
1125
- async function checkContactWallet(contact) {
1126
- let isAlreadyWallet = false;
1127
- try {
1128
- if(!contact)
1129
- {
1130
-
1131
- const result = await contacts.getContact();
1132
- if (result.code == 'OK') {
1133
- isAlreadyWallet = result.data.wallet && result.data.wallet.id ? true : false;
1134
- }
1135
- }
1136
- else {
1137
- isAlreadyWallet = contact.wallet && contact.wallet.id ? true : false;
1138
-
1139
- }
1140
- } catch (error) {
1141
- }
1142
-
1143
- return isAlreadyWallet;
1144
- }
1145
-
1146
- function sortShortcuts(n1, n2) {
1147
- if (n1.sort_order > n2.sort_order) {
1148
- return 1;
1149
- } else if (n1.sort_order < n2.sort_order) {
1150
- return -1
1151
- } else {
1152
- return 0;
1153
- }
1154
- }
1155
-
1156
- function getBalanceByType(balances, isBusiness, currencyCode) {
1157
- let balance = {
1158
- open: 0,
1159
- commerce: 0,
1160
- total: 0
1161
- };
1162
- let type = isBusiness ? "BUSINESS" : "CRM";
1163
- if (balances) {
1164
- let balanceByType = balances.filter(b => {
1165
- return b.type == type
1166
- })
1167
- if (balanceByType && balanceByType.length > 0) {
1168
- if(balanceByType.length == 1){
1169
- balance = balanceByType[0];
1170
- }
1171
- else if (currencyCode!=null) {
1172
- balance = balanceByType.filter(b => {
1173
- return b.currency_code == currencyCode
1174
- })
1175
- }
1176
- }
1177
- }
1178
- return balance;
1179
- }
1180
-
1181
- async function getJoinedCommunities(joinedCommunityIds) {
1182
- let joinedCommunities = [];
1183
- const contactId = httpUtil.getSession().sub;
1184
- for (let i = 0; i < joinedCommunityIds.length; i++) {
1185
- let joinedCommunity = joinedCommunityIds[i];
1186
- joinedCommunity.name = joinedCommunityIds[i].community_owner ? joinedCommunityIds[i].community_owner.first_name : ""
1187
- var result = await community.getListCommunityPeople({}, joinedCommunity.community_owner.id);
1188
- if (result.code == 'OK') {
1189
- let content = result.data.content ? result.data.content : [];
1190
- content.forEach(c => {
1191
- if (c.contact.id == contactId) {
1192
- c.is_me = true;
1193
- } else {
1194
- c.is_me = false;
1195
- }
1196
- });
1197
- joinedCommunity.total_member = content.length;
1198
- joinedCommunity.peoples = content
1199
- joinedCommunities.push(joinedCommunity);
1200
- }
1201
- }
1202
- return joinedCommunities;
1203
- }
1204
-
1205
- function groupMyCommunities(communities) {
1206
- var items = communities.reduce((acc, curr) => {
1207
- const itemExists = acc.find(item => curr.relation && curr.relation.id === item.relation_id)
1208
- if (itemExists) {
1209
- itemExists.peoples.push(curr);
1210
- } else {
1211
- acc.push({ relation_id: curr.relation.id, relation_name: curr.relation.name, peoples: [curr] })
1212
- }
1213
- return acc;
1214
- }, []);
1215
- return items;
1216
- }
1217
-
1218
- function groupMyCommunitiesByGroup(communities) {
1219
- var items = communities.reduce((acc, curr) => {
1220
- let itemExists = acc.find(item => curr.group === item.group)
1221
- if (itemExists) {
1222
- itemExists.peoples.push(curr);
1223
- } else if(curr.group) {
1224
- acc.push({ group: curr.group, peoples: [curr] })
1225
- } else {
1226
- let itemExists1 = acc.find(item => curr.relation && curr.relation.id === item.relation_id)
1227
- if (itemExists1) {
1228
- itemExists1.peoples.push(curr);
1229
- } else {
1230
- acc.push({ relation_id: curr.relation.id, relation_name: curr.relation.name, peoples: [curr] })
1231
- }
1232
- }
1233
- return acc;
1234
- }, []);
1235
- return items;
1236
- }
1237
-
1238
- function getServiceMRR(services) {
1239
- let mrrService = null;
1240
- if (services && services.length > 0) {
1241
- if (services.length == 1) {
1242
- mrrService = {
1243
- product_name: services[0].product.name
1244
- }
1245
- } else {
1246
- let priceGreatest = 0;
1247
- services.forEach(service => {
1248
- let price = service.price ? service.price.price : 0;
1249
- let billingPeriod = service.subscription && service.subscription.terms && service.subscription.terms.billing_period ? service.subscription.terms.billing_period.duration : 0;
1250
- let _priceGreatest = price / billingPeriod;
1251
- if (_priceGreatest > priceGreatest) {
1252
- priceGreatest = _priceGreatest;
1253
- mrrService = {
1254
- product_name: service.product.name
1255
- }
1256
- }
1257
- });
1258
- }
1259
- }
1260
- return mrrService;
1261
- }
1262
-
1263
- function getTotalSubscriptionAndService(services) {
1264
- let total_subscription = 0;
1265
- let total_service = 0;
1266
- if (services && services.length > 0) {
1267
- var subscriptions = services.reduce((acc, curr) => {
1268
- const itemExists = acc.find(item => curr.subscription && curr.subscription.id === item.subscription_id)
1269
- if (itemExists) {
1270
- itemExists.services.push(curr);
1271
- } else {
1272
- acc.push({ subscription_id: curr.subscription ? curr.subscription.id : null, services: [curr] })
1273
- }
1274
- return acc;
1275
- }, []);
1276
- subscriptions.forEach(sub => {
1277
- total_subscription = sub.subscription_id ? total_subscription + 1 : total_subscription;
1278
- total_service = total_service + sub.services.length;
1279
- });
1280
- }
1281
- return { total_subscription, total_service };
1282
-
1283
- }
1284
-
1285
- function getQueueIdByMethod(appConfig, method) {
1286
- let queueId = null;
1287
- const orderConfig = appConfig.features.contact ? appConfig.features.contact.order : null;
1288
- if (orderConfig && orderConfig.is_supported) {
1289
- queueId = orderConfig[method.toLowerCase()] ? orderConfig[method.toLowerCase()].queue_id : null;
1290
- }
1291
- return queueId;
1292
- }
1293
-
1294
- function checkOrderModalMarketPlace(appConfig) {
1295
- let isMarketPlace = false;
1296
- const orderConfig = appConfig.features.contact ? appConfig.features.contact.order : null;
1297
- if (orderConfig && orderConfig.model && orderConfig.model == "MARKETPLACE") {
1298
- isMarketPlace = true;
1299
- }
1300
- return isMarketPlace;
1301
- }
1302
-
1303
- async function onLoadAllCardsInfo(payment_method_types, gateway) {
1304
- let _isPaymentWithCard = false;
1305
- let cards = [];
1306
- let primaryCard = null;
1307
- let _isPaymentWithA2A = false;
1308
- let a2a = [];
1309
- let primaryA2A = null;
1310
- if (!payment_method_types) {
1311
- payment_method_types = []
1312
- }
1313
- try {
1314
- var result = await payment.getListPaymentMethods();
1315
- if (result.code == 'OK') {
1316
- cards = result.data && result.data.content ? result.data.content : [];
1317
- if (cards.length > 0) {
1318
- cards = cards.filter(card => {
1319
- let gatewayToken = card.card && card.card.gateway_token && card.card.gateway_token.length > 0 ? card.card.gateway_token[0] : null;
1320
- if (gatewayToken && gatewayToken.gateway && gateway)
1321
- return card.payment_method_type == 'CARD' && gatewayToken && gatewayToken.gateway === gateway
1322
- else return card.payment_method_type == 'CARD'
1323
- });
1324
- let cardPrimary = cards.filter(card => {
1325
- return card.is_primary
1326
- })
1327
- if (cardPrimary && cardPrimary.length > 0) {
1328
- primaryCard = cardPrimary[0];
1329
- } else {
1330
- primaryCard = cards[0];
1331
- }
1332
-
1333
- let isCard = payment_method_types.filter((method) => {
1334
- return method === 'CARD'
1335
- })
1336
- if (isCard && isCard.length && isCard.length > 0) {
1337
- _isPaymentWithCard = true;
1338
- }
1339
- }
1340
-
1341
- a2a = result.data && result.data.content ? result.data.content : [];
1342
- if (a2a.length > 0) {
1343
- a2a = a2a.filter(a2aSignle => {
1344
- let gatewayToken = a2aSignle.a2a && a2aSignle.a2a.gateway_token && a2aSignle.a2a.gateway_token.length > 0 ? a2aSignle.a2a.gateway_token[0] : null;
1345
- if (gatewayToken && gatewayToken.gateway && gateway)
1346
- return a2aSignle.payment_method_type == 'A2A' && gatewayToken && gatewayToken.gateway === gateway
1347
- else return a2aSignle.payment_method_type == 'A2A'
1348
- });
1349
-
1350
- let a2aPrimary = a2a.filter(a2aSingle => {
1351
- return a2aSingle.is_primary
1352
- })
1353
- if (a2aPrimary && a2aPrimary.length > 0) {
1354
- primaryA2A = a2aPrimary[0];
1355
- } else {
1356
- primaryA2A = a2a[0];
1357
- }
1358
-
1359
- let isA2A = payment_method_types.filter((method) => {
1360
- return method === 'A2A'
1361
- })
1362
- if (isA2A && isA2A.length && isA2A.length > 0) {
1363
- _isPaymentWithA2A = true;
1364
- }
1365
- }
1366
- }
1367
- } catch (error) {
1368
- logger.error("load my order exception:", error);
1369
- }
1370
- return {
1371
- isPaymentWithCard: _isPaymentWithCard,
1372
- cards: cards,
1373
- primary_card: primaryCard,
1374
- isPaymentWithA2A: _isPaymentWithA2A,
1375
- a2a: a2a,
1376
- primary_a2a: primaryA2A
1377
- }
1378
- }
1379
-
1380
- async function onLoadCards(payment_method_types, gateway) {
1381
- let _isPaymentWithCard = false;
1382
- let cards = [];
1383
- let primaryCard = null;
1384
- if (!payment_method_types) {
1385
- payment_method_types = []
1386
- }
1387
- try {
1388
- var result = await payment.getListPaymentMethods();
1389
- if (result.code == 'OK') {
1390
- cards = result.data && result.data.content ? result.data.content : [];
1391
- if (cards.length > 0) {
1392
- cards = cards.filter(card => {
1393
- let gatewayToken = card.card && card.card.gateway_token && card.card.gateway_token.length > 0 ? card.card.gateway_token[0] : null;
1394
- if (gatewayToken && gatewayToken.gateway && gateway)
1395
- return card.payment_method_type == 'CARD' && gatewayToken && gatewayToken.gateway === gateway
1396
- else return card.payment_method_type == 'CARD'
1397
- });
1398
- let cardPrimary = cards.filter(card => {
1399
- return card.is_primary
1400
- })
1401
- if (cardPrimary && cardPrimary.length > 0) {
1402
- primaryCard = cardPrimary[0];
1403
- } else {
1404
- primaryCard = cards[0];
1405
- }
1406
-
1407
- let isCard = payment_method_types.filter((method) => {
1408
- return method === 'CARD'
1409
- })
1410
- if (isCard && isCard.length && isCard.length > 0) {
1411
- _isPaymentWithCard = true;
1412
- }
1413
- }
1414
- }
1415
- } catch (error) {
1416
- logger.error("load my order exception:", error);
1417
- }
1418
- return {
1419
- isPaymentWithCard: _isPaymentWithCard,
1420
- cards: cards,
1421
- primary_card: primaryCard
1422
- }
1423
-
1424
- }
1425
-
1426
- async function onLoadA2A(payment_method_types, gateway) {
1427
- let _isPaymentWithA2A = false;
1428
- let a2a = [];
1429
- let primaryA2A = null;
1430
- if (!payment_method_types) {
1431
- payment_method_types = []
1432
- }
1433
- try {
1434
- var result = await payment.getListPaymentMethods();
1435
- if (result.code == 'OK') {
1436
- a2a = result.data && result.data.content ? result.data.content : [];
1437
- if (a2a.length > 0) {
1438
- a2a = a2a.filter(a2aSignle => {
1439
- let gatewayToken = a2aSignle.a2a && a2aSignle.a2a.gateway_token && a2aSignle.a2a.gateway_token.length > 0 ? a2aSignle.a2a.gateway_token[0] : null;
1440
- if (gatewayToken && gatewayToken.gateway && gateway)
1441
- return a2aSignle.payment_method_type == 'A2A' && gatewayToken && gatewayToken.gateway === gateway
1442
- else return a2aSignle.payment_method_type == 'A2A'
1443
- });
1444
-
1445
- let a2aPrimary = a2a.filter(a2aSingle => {
1446
- return a2aSingle.is_primary
1447
- })
1448
- if (a2aPrimary && a2aPrimary.length > 0) {
1449
- primaryA2A = a2aPrimary[0];
1450
- } else {
1451
- primaryA2A = a2a[0];
1452
- }
1453
-
1454
- let isA2A = payment_method_types.filter((method) => {
1455
- return method === 'A2A'
1456
- })
1457
- if (isA2A && isA2A.length && isA2A.length > 0) {
1458
- _isPaymentWithA2A = true;
1459
- }
1460
- }
1461
- }
1462
- } catch (error) {
1463
- logger.error("load my order exception:", error);
1464
- }
1465
- return {
1466
- isPaymentWithA2A: _isPaymentWithA2A,
1467
- a2a: a2a,
1468
- primary_a2a: primaryA2A
1469
- }
1470
-
1471
- }
1472
-
1473
- function getConditionNearestExpiry(condition) {
1474
- if (condition.expiration) {
1475
- if (condition.expiration.zero_to_thirty) {
1476
- return {
1477
- amount: condition.expiration.zero_to_thirty.toFixed(2),
1478
- days: "0-30"
1479
- }
1480
- } else if (condition.expiration.thirty_to_sixty) {
1481
- return {
1482
- amount: condition.expiration.thirty_to_sixty.toFixed(2),
1483
- days: "30-60"
1484
- }
1485
- } else if (condition.expiration.sixty_to_ninety) {
1486
- return {
1487
- amount: condition.expiration.sixty_to_ninety.toFixed(2),
1488
- days: "60-90"
1489
- }
1490
- } else if (condition.expiration.ninety_plus) {
1491
- return {
1492
- amount: condition.expiration.ninety_plus.toFixed(2),
1493
- days: "90+",
1494
- isOver: true
1495
- }
1496
- }
1497
- }
1498
- return null
1499
- }
1500
-
1501
- function sumConditionsByNearestExpiry(conditions) {
1502
- const totals = {
1503
- "0-30": 0,
1504
- "30-60": 0,
1505
- "60-90": 0,
1506
- "90+": 0
1507
- };
1508
-
1509
- conditions.forEach(condition => {
1510
- if (condition.expiration) {
1511
- if (condition.expiration.zero_to_thirty) {
1512
- totals["0-30"] += condition.expiration.zero_to_thirty;
1513
- }
1514
- if (condition.expiration.thirty_to_sixty) {
1515
- totals["30-60"] += condition.expiration.thirty_to_sixty;
1516
- }
1517
- if (condition.expiration.sixty_to_ninety) {
1518
- totals["60-90"] += condition.expiration.sixty_to_ninety;
1519
- }
1520
- if (condition.expiration.ninety_plus) {
1521
- totals["90+"] += condition.expiration.ninety_plus;
1522
- }
1523
- }
1524
- });
1525
-
1526
- const priorityOrder = ["0-30", "30-60", "60-90", "90+"];
1527
-
1528
- for (const period of priorityOrder) {
1529
- if (totals[period] > 0) {
1530
- return {
1531
- amount: totals[period].toFixed(2),
1532
- days: period,
1533
- isOver: period === "90+"
1534
- };
1535
- }
1536
- }
1537
-
1538
- return null;
1539
- }
1540
-
1541
-
1542
-
1543
- function getNextBillingDate(subscriptions) {
1544
- let billing_info = {
1545
- bill_up_date: null,
1546
- next_billing_date: null,
1547
- next_payment_date: null,
1548
- one_time_services: null,
1549
- }
1550
- let billed_to = null;
1551
- if (subscriptions && subscriptions.length > 0) {
1552
- let currentDateTime = new Date().getTime() / 1000;
1553
- for (let i = 0; i < subscriptions.length; i++) {
1554
- let sub = subscriptions[i];
1555
- if (sub.billing && sub.billing.billed_to > currentDateTime) {
1556
- billed_to = sub.billing.billed_to;
1557
- break;
1558
- }
1559
- }
1560
- }
1561
- if (billed_to) {
1562
- billing_info = {
1563
- bill_up_date: billed_to,
1564
- next_billing_date: billed_to,
1565
- next_payment_date: billed_to,
1566
- one_time_services: billed_to,
1567
- }
1568
- } else {
1569
- let billing = subscriptions && subscriptions.length > 0 ? subscriptions[0].billing : null
1570
- billing_info = {
1571
- bill_up_date: billing ? billing.billed_to : null,
1572
- next_billing_date: billing ? billing.billed_to : null,
1573
- next_payment_date: billing ? billing.billed_to : null,
1574
- one_time_services: billing ? billing.billed_to : null,
1575
- }
1576
- }
1577
- return billing_info;
1578
- }
1579
-
1580
- function checkAllowUseAccountFundAmount(appConfig, estimate_order_result) {
1581
- let isUseAccountFund = appConfig && appConfig.features && appConfig.features.contact && appConfig.features.contact.order && appConfig.features.contact.order.use_account_funds;
1582
- let availableAccountFund = 0;
1583
- if (isUseAccountFund) {
1584
- var invoice_estimate = estimate_order_result ? estimate_order_result.invoice_estimate : null;
1585
- let billing_estimate = estimate_order_result && estimate_order_result.service_delivery_estimate && estimate_order_result.service_delivery_estimate.length > 0 ? estimate_order_result.service_delivery_estimate[0].billing_estimate : null;
1586
- let service_invoice_estimate = billing_estimate && billing_estimate.invoicing && billing_estimate.invoicing.length > 0 ? billing_estimate.invoicing[0] : null;
1587
- isUseAccountFund = (invoice_estimate && invoice_estimate.account_credit && invoice_estimate.account_credit > 0) || (service_invoice_estimate && service_invoice_estimate.account_funds && service_invoice_estimate.account_funds > 0)
1588
- availableAccountFund = invoice_estimate && invoice_estimate.account_credit ? invoice_estimate.account_credit : 0;
1589
- if (!availableAccountFund) {
1590
- availableAccountFund = service_invoice_estimate && service_invoice_estimate.account_funds ? service_invoice_estimate.account_funds : 0
1591
- }
1592
- }
1593
- return {
1594
- is_allow_account_fund: isUseAccountFund,
1595
- available_account_fund: availableAccountFund
1596
- }
1597
- }
1598
-
1599
- function checkAllowUseWalletFundAmount(appConfig) {
1600
- let isUseWalletFund = appConfig && appConfig.features && appConfig.features.contact && appConfig.features.contact.order && appConfig.features.contact.order.use_wallet_funds && appConfig.features.contact.order.use_wallet_funds.is_supported;
1601
- return isUseWalletFund
1602
- }
1603
-
1604
- async function getPaymentMethodInfo(payment_method_types) {
1605
- let is_support_crm_wallet = payment_method_types.length > 0 && payment_method_types.includes("CRM_WALLET");
1606
- let is_support_card = payment_method_types.length > 0 && payment_method_types.includes("CARD");;
1607
- let is_support_cash = payment_method_types.length > 0 && payment_method_types.includes("CASH");;
1608
- let is_support_a2a = payment_method_types.length > 0 && payment_method_types.includes("A2A");;
1609
- let default_payment_method = null;
1610
- //created in order for payment methods to be called once and not twice for cards & a2a
1611
- let allCardsInfoResult = await onLoadAllCardsInfo(payment_method_types);
1612
- //let cardResult = await onLoadCards(payment_method_types);
1613
- //let a2aResult = await onLoadA2A(payment_method_types);
1614
- if (is_support_crm_wallet) {
1615
- default_payment_method = 'CRM_WALLET'
1616
- } else if (is_support_card) {
1617
- default_payment_method = 'CARD'
1618
- } else if (is_support_cash) {
1619
- default_payment_method = 'CASH'
1620
- } else if (is_support_a2a) {
1621
- default_payment_method = 'A2A'
1622
- }
1623
- return {
1624
- is_support_crm_wallet,
1625
- is_support_card,
1626
- is_support_cash,
1627
- is_support_a2a,
1628
- default_payment_method,
1629
- primary_a2a : allCardsInfoResult.primary_a2a,
1630
- primary_card: allCardsInfoResult.primary_card,
1631
- cards: allCardsInfoResult.cards,
1632
- a2a: allCardsInfoResult.a2a,
1633
- }
1634
- }
1635
-
1636
-
1637
- function getOrderSummaryV2(estimate_order_result, isUseWalletFund, isUseAccountFund, paymentMethod,isMultimerchant=null) {
1638
- if(isMultimerchant && estimate_order_result && estimate_order_result.orders && estimate_order_result.orders.length > 0)
1639
- {
1640
- let orders= estimate_order_result.orders;
1641
- let ordersSummary = [];
1642
- let finalSubTotal=0,finalWalletFundsAmount=0, finalAmountDue=0, finalTotalDiscountAmount=0, finalAccountFundAmount=0, finalTotalAmount=0;
1643
- let finalPayAtNextBill = [],finalPayAtFront = {
1644
- subTotalAmount: 0,
1645
- wallet_funds_amount: 0,
1646
- amountDue: 0,
1647
- total_discount_amount: 0,
1648
- accountFundAmount: 0,
1649
- totalAmount: 0
1650
-
1651
- };
1652
-
1653
- for (let order of orders) {
1654
- var invoice_estimate = order ? order.invoice_estimate : null;
1655
- let billing_estimate = order && order.service_delivery_estimate && order.service_delivery_estimate.length > 0 ? order.service_delivery_estimate[0].billing_estimate : null;
1656
- let service_invoice_estimate = billing_estimate && billing_estimate.invoicing && billing_estimate.invoicing.length > 0 ? billing_estimate.invoicing[0] : null;
1657
- let accountFundAmount = 0;
1658
- var wallet_funds_amount = invoice_estimate && invoice_estimate.wallet_funds_amount ? invoice_estimate.wallet_funds_amount : 0;
1659
- var wallet_funds_amount_service = service_invoice_estimate && service_invoice_estimate.wallet_funds_amount ? service_invoice_estimate.wallet_funds_amount : 0;
1660
- let pay_at_next_bill = null;
1661
- if (invoice_estimate) {
1662
- accountFundAmount = invoice_estimate.account_credit ? invoice_estimate.account_credit : 0;
1663
- }
1664
- if (service_invoice_estimate) {
1665
- accountFundAmount = service_invoice_estimate.account_funds ? service_invoice_estimate.account_funds : 0;
1666
- }
1667
- if (accountFundAmount < 0) {
1668
- accountFundAmount = 0;
1669
- }
1670
- let subTotal = invoice_estimate ? invoice_estimate.total_price : 0;
1671
- let totalAmount = invoice_estimate ? invoice_estimate.total : 0;
1672
- let total_discount_amount = invoice_estimate ? invoice_estimate.discount_incl_tax : 0;
1673
- let amountDue = invoice_estimate ? invoice_estimate.amount_due : 0;
1674
- if (service_invoice_estimate) {
1675
- pay_at_next_bill = { ...service_invoice_estimate }
1676
- finalPayAtNextBill.push(pay_at_next_bill);
1677
- }
1678
- if (!isUseWalletFund) {
1679
- amountDue = totalAmount;
1680
- }
1681
- if (isUseAccountFund) {
1682
- if (accountFundAmount <= amountDue) {
1683
- amountDue = amountDue - accountFundAmount;
1684
- } else {
1685
- accountFundAmount = amountDue;
1686
- amountDue = 0;
1687
- }
1688
- }
1689
- let pay_upfront = null;
1690
- amountDue = amountDue > 0 ? Math.round(amountDue * 100) / 100 : 0;
1691
- if (invoice_estimate) {
1692
- pay_upfront = {
1693
- subTotalAmount: subTotal,
1694
- wallet_funds_amount: wallet_funds_amount,
1695
- amountDue: amountDue,
1696
- total_discount_amount: total_discount_amount,
1697
- accountFundAmount: accountFundAmount,
1698
- totalAmount: totalAmount,
1699
- }
1700
- finalPayAtFront.subTotalAmount=finalPayAtFront.subTotalAmount+subTotal;
1701
- finalPayAtFront.wallet_funds_amount=finalPayAtFront.wallet_funds_amount+wallet_funds_amount;
1702
- finalPayAtFront.amountDue=finalPayAtFront.amountDue+amountDue;
1703
- finalPayAtFront.total_discount_amount=finalPayAtFront.total_discount_amount+total_discount_amount;
1704
- finalPayAtFront.accountFundAmount=finalPayAtFront.accountFundAmount+accountFundAmount;
1705
- finalPayAtFront.totalAmount=finalPayAtFront.totalAmount+totalAmount;
1706
-
1707
- }
1708
- finalSubTotal=finalSubTotal+subTotal;
1709
- finalWalletFundsAmount=finalWalletFundsAmount+wallet_funds_amount+wallet_funds_amount_service;
1710
- finalAmountDue=finalAmountDue+amountDue;
1711
- finalTotalDiscountAmount=finalTotalDiscountAmount+total_discount_amount;
1712
- finalAccountFundAmount=finalAccountFundAmount+accountFundAmount;
1713
- finalTotalAmount=finalTotalAmount+totalAmount;
1714
- ordersSummary.push({
1715
- id:order.id,
1716
- subTotalAmount: subTotal,
1717
- totalAmount: totalAmount,
1718
- wallet_funds_amount: wallet_funds_amount + wallet_funds_amount_service,
1719
- amountDue: amountDue,
1720
- total_discount_amount: total_discount_amount,
1721
- accountFundAmount: accountFundAmount,
1722
- pay_at_next_bill: pay_at_next_bill,
1723
- pay_upfront: pay_upfront
1724
- });
1725
-
1726
- }
1727
-
1728
- return {
1729
- ordersSummary:ordersSummary,
1730
- subTotalAmount: finalSubTotal,
1731
- totalAmount: finalTotalAmount,
1732
- wallet_funds_amount: finalWalletFundsAmount,
1733
- amountDue: finalAmountDue,
1734
- total_discount_amount: finalTotalDiscountAmount,
1735
- accountFundAmount: finalAccountFundAmount,
1736
- pay_at_next_bill: finalPayAtNextBill.length===0?null: finalPayAtNextBill,
1737
- pay_upfront: finalPayAtFront
1738
- }
1739
- }
1740
- else
1741
- {
1742
- var invoice_estimate = estimate_order_result ? estimate_order_result.invoice_estimate : null;
1743
- let billing_estimate = estimate_order_result && estimate_order_result.service_delivery_estimate && estimate_order_result.service_delivery_estimate.length > 0 ? estimate_order_result.service_delivery_estimate[0].billing_estimate : null;
1744
- let service_invoice_estimate = billing_estimate && billing_estimate.invoicing && billing_estimate.invoicing.length > 0 ? billing_estimate.invoicing[0] : null;
1745
- let accountFundAmount = 0;
1746
- var wallet_funds_amount = invoice_estimate && invoice_estimate.wallet_funds_amount ? invoice_estimate.wallet_funds_amount : 0;
1747
- var wallet_funds_amount_service = service_invoice_estimate && service_invoice_estimate.wallet_funds_amount ? service_invoice_estimate.wallet_funds_amount : 0;
1748
- let pay_at_next_bill = null;
1749
- if (invoice_estimate) {
1750
- accountFundAmount = invoice_estimate.account_credit ? invoice_estimate.account_credit : 0;
1751
- }
1752
- if (service_invoice_estimate) {
1753
- accountFundAmount = service_invoice_estimate.account_funds ? service_invoice_estimate.account_funds : 0;
1754
- }
1755
- if (accountFundAmount < 0) {
1756
- accountFundAmount = 0;
1757
- }
1758
- let subTotal = invoice_estimate ? invoice_estimate.total_price : 0;
1759
- let totalAmount = invoice_estimate ? invoice_estimate.total : 0;
1760
- let total_discount_amount = invoice_estimate ? invoice_estimate.discount_incl_tax : 0;
1761
- let amountDue = invoice_estimate ? invoice_estimate.amount_due : 0;
1762
- if (service_invoice_estimate) {
1763
- pay_at_next_bill = { ...service_invoice_estimate }
1764
- }
1765
- if (!isUseWalletFund) {
1766
- amountDue = totalAmount;
1767
- }
1768
- if (isUseAccountFund) {
1769
- if (accountFundAmount <= amountDue) {
1770
- amountDue = amountDue - accountFundAmount;
1771
- } else {
1772
- accountFundAmount = amountDue;
1773
- amountDue = 0;
1774
- }
1775
- }
1776
- let pay_upfront = null;
1777
- amountDue = amountDue > 0 ? Math.round(amountDue * 100) / 100 : 0;
1778
- if (invoice_estimate) {
1779
- pay_upfront = {
1780
- subTotalAmount: subTotal,
1781
- wallet_funds_amount: wallet_funds_amount,
1782
- amountDue: amountDue,
1783
- total_discount_amount: total_discount_amount,
1784
- accountFundAmount: accountFundAmount,
1785
- totalAmount: totalAmount,
1786
- }
1787
- }
1788
- return {
1789
- subTotalAmount: subTotal,
1790
- totalAmount: totalAmount,
1791
- wallet_funds_amount: wallet_funds_amount + wallet_funds_amount_service,
1792
- amountDue: amountDue,
1793
- total_discount_amount: total_discount_amount,
1794
- accountFundAmount: accountFundAmount,
1795
- pay_at_next_bill: pay_at_next_bill,
1796
- pay_upfront: pay_upfront
1797
- }
1798
- }
1799
-
1800
-
1801
- }
1802
-
1803
-
1804
- function createItemsWithComponents(items) {
1805
- let _items = [];
1806
- if (items && items.length > 0) {
1807
- let mainProducts = items.filter(item => {
1808
- return item.product && !item.product.bundled_item
1809
- })
1810
- if (mainProducts.length > 0) {
1811
- mainProducts.forEach(p => {
1812
- let mainProduct = { ...p };
1813
- let product = { ...mainProduct.product };
1814
- let bundleProducts = items.filter(item => {
1815
- let bundled_item_product = item.product && item.product.bundled_item ? item.product.bundled_item : null;
1816
- return bundled_item_product && bundled_item_product.id == mainProduct.id;
1817
- })
1818
- if (bundleProducts && bundleProducts.length > 0) {
1819
- product.components = createObjComponent(bundleProducts);
1820
- mainProduct.product = product;
1821
- }
1822
- _items.push(mainProduct);
1823
- });
1824
- }
1825
- }
1826
- return _items;
1827
- }
1828
-
1829
- function createObjComponent(components) {
1830
- let _components = [];
1831
- components.forEach(element => {
1832
- let object = { ...element.product };
1833
- object.price = element.sub_total;
1834
- object.quantity = element.quantity;
1835
- _components.push(object);
1836
- });
1837
- return _components
1838
- }
1839
-
1840
- const onLoadMyOrder = async () => {
1841
- let _lastOrder = null;
1842
- if(!cache.getLastOrder()){
1843
- try {
1844
- var result = await orders.getMyOrders({ size: 1, page: 1 });
1845
- if (result.code === 'OK') {
1846
- _lastOrder = result.data.content && result.data.content.length > 0 ? result.data.content[0] : null;
1847
- cache.setLastOrder(_lastOrder);
1848
- }
1849
- } catch (error) {
1850
- logger.error("load my order exception:", error);
1851
- }
1852
- }
1853
- else{
1854
- _lastOrder = cache.getCacheByKey(order_key.last_order);
1855
- }
1856
- return _lastOrder;
1857
- }
1858
-
1859
- async function getFulfillmentStoreDetail({
1860
- supply_method, fulfilled_by_id, customer_address, location
1861
- } = {}) {
1862
- let _stores = [];
1863
- try {
1864
- var body = {
1865
- supply_method: supply_method
1866
- }
1867
- if (supply_method == 'PICK_UP' && fulfilled_by_id) {
1868
- body.requested_organisation_id = fulfilled_by_id
1869
- }
1870
- if (supply_method == 'PICK_UP' && location) {
1871
- body.lat_lot = location.lat + ":" + location.lon;
1872
- }
1873
- if (customer_address && customer_address.id) {
1874
- body.address_id = customer_address.id;
1875
- } else if (customer_address && customer_address.lat && customer_address.lon) {
1876
- body.lat_lot = customer_address.lat + ":" + customer_address.lon;
1877
- body.postal_code = customer_address.postal_code;
1878
- }
1879
- var result = await orders.estimateOrderFulfillment(body);
1880
- if (result.code == 'OK') {
1881
- _stores = result.data.fulfilled_by ? result.data.fulfilled_by : [];
1882
- }
1883
-
1884
- cache.setStores(_stores)
1885
- } catch (error) {
1886
- logger.error("initDirectSaleOrder exception:", error);
1887
- }
1888
- let store = _stores.length > 0 ? _stores[0] : null;
1889
- return store;
1890
- }
1891
-
1892
- async function initDefaultDirectSale(fulfilled_by_id) {
1893
- let initOrder = null;
1894
-
1895
- let params = {
1896
- supply_method: 'DIRECT_SALE',
1897
- }
1898
-
1899
- if(fulfilled_by_id){
1900
- params.fulfilled_by_id = fulfilled_by_id;
1901
- }
1902
-
1903
- let fulfilled_by = await getFulfillmentStoreDetail(params);
1904
- initOrder = {
1905
- supply_method: 'DIRECT_SALE',
1906
- fulfilled_by: fulfilled_by,
1907
- }
1908
- return initOrder;
1909
- }
1910
-
1911
- const initDefaultDelivery = async (currentLocation, fulfilled_by_id) => {
1912
- let initOrder = null;
1913
- let result = await getCustomerAddressForOrder({ location: currentLocation });
1914
- let customerAddress = result.customer_address;
1915
-
1916
- let params = {
1917
- supply_method: 'DELIVERY',
1918
- customer_address: customerAddress,
1919
- location: currentLocation
1920
- }
1921
-
1922
- if(fulfilled_by_id){
1923
- params.fulfilled_by_id = fulfilled_by_id;
1924
- }
1925
- if (customerAddress) {
1926
- let fulfilled_by = await getFulfillmentStoreDetail(params);
1927
- initOrder = {
1928
- supply_method: 'DELIVERY',
1929
- fulfilled_by: fulfilled_by,
1930
- customer_address: customerAddress
1931
- }
1932
- }
1933
- return initOrder;
1934
- }
1935
-
1936
- const initDefaultPickup = async (currentLocation, fulfilled_by_id) => {
1937
- let initOrder = null;
1938
- let result = await getCustomerAddressForOrder({ location: currentLocation });
1939
-
1940
- let customerAddress = result.customer_address;
1941
- let location = currentLocation;
1942
- if (!location && customerAddress) {
1943
- location = {
1944
- lat: customerAddress.lat,
1945
- lon: customerAddress.lon,
1946
- }
1947
- }
1948
- let params = {
1949
- supply_method: 'PICK_UP',
1950
- }
1951
- if(fulfilled_by_id){
1952
- params.fulfilled_by_id = fulfilled_by_id;
1953
- }
1954
- if(location) params.location = currentLocation;
1955
- let fulfilled_by = await getFulfillmentStoreDetail(params);
1956
- initOrder = {
1957
- supply_method: 'PICK_UP',
1958
- fulfilled_by: fulfilled_by,
1959
- }
1960
- return initOrder;
1961
- }
1962
-
1963
- const initDefaultOrderMethod = async (currentLocation, defaultOrderMethod, fulfilledById) => {
1964
- let initOrder = null;
1965
- if (defaultOrderMethod && defaultOrderMethod == 'PICK_UP') {
1966
- initOrder = await initDefaultPickup(currentLocation, fulfilledById)
1967
- } else if (defaultOrderMethod && defaultOrderMethod == 'DELIVERY') {
1968
- initOrder = await initDefaultDelivery(currentLocation, fulfilledById)
1969
- } else if (defaultOrderMethod && defaultOrderMethod == 'DIRECT_SALE') {
1970
- initOrder = await initDefaultDirectSale(fulfilledById);
1971
- }
1972
- return initOrder;
1973
- }
1974
-
1975
- async function onInitOrder({ location, appConfig, skipLastOrder = false, supplyMethod, merchantId } = {}) {
1976
- let initOrder = null;
1977
- try {
1978
- let supportDelivery = appConfig.features.contact.order && appConfig.features.contact.order.delivery && appConfig.features.contact.order.delivery.is_supported;
1979
- let supportPickUp = appConfig.features.contact.order && appConfig.features.contact.order.pick_up && appConfig.features.contact.order.pick_up.is_supported;
1980
- let supportDirectSale = appConfig.features.contact.order && appConfig.features.contact.order.direct_sale && appConfig.features.contact.order.direct_sale.is_supported;
1981
- const lastOrder = await onLoadMyOrder();
1982
- let defaultOrderMethod = supplyMethod ? supplyMethod : 'DELIVERY';
1983
- if (!supportDelivery) {
1984
- defaultOrderMethod = supportPickUp ? 'PICK_UP' : (supportDirectSale ? 'DIRECT_SALE' : null);
1985
- }
1986
- if (lastOrder && !skipLastOrder) {
1987
- if (lastOrder.supply_method == 'DIRECT_SALE' && supportDirectSale) {
1988
- initOrder = await initDefaultDirectSale();
1989
- } else {
1990
- let customer_address = null;
1991
- if (lastOrder.supply_method == 'DELIVERY' && supportDelivery) {
1992
- const orderDetailResult = await orders.getOrder(lastOrder.id);
1993
- if (orderDetailResult.code == 'OK') {
1994
- customer_address = orderDetailResult.data.address
1995
- }
1996
-
1997
- if(!customer_address){
1998
- let result = await getCustomerAddressForOrder({ location: location });
1999
- if(result && result.customer_address)
2000
- {
2001
- customer_address = result.customer_address;
2002
- }
2003
- }
2004
-
2005
- if(customer_address)
2006
- {
2007
- let fulfilled_by = await getFulfillmentStoreDetail({
2008
- supply_method: lastOrder.supply_method,
2009
- fulfilled_by_id: lastOrder.fulfilled_by.id,
2010
- customer_address: customer_address,
2011
- location: location
2012
- });
2013
- initOrder = {
2014
- supply_method: lastOrder.supply_method,
2015
- fulfilled_by: fulfilled_by ? fulfilled_by : lastOrder.fulfilled_by,
2016
- customer_address: customer_address
2017
- }
2018
- } else {
2019
- initOrder = await initDefaultOrderMethod(location, defaultOrderMethod);
2020
- }
2021
- } else {
2022
- if (supportPickUp) {
2023
- if (location && location.lat && location.lon && lastOrder.fulfilled_by && lastOrder.fulfilled_by.id) {
2024
- let fulfilled_by = await getFulfillmentStoreDetail({
2025
- supply_method: 'PICK_UP',
2026
- fulfilled_by_id: lastOrder.fulfilled_by.id,
2027
- customer_address: customer_address,
2028
- location: location
2029
- });
2030
- if(fulfilled_by && fulfilled_by.id){
2031
- initOrder = {
2032
- supply_method: 'PICK_UP',
2033
- fulfilled_by: fulfilled_by ? fulfilled_by : null,
2034
- customer_address: customer_address
2035
- }
2036
- }
2037
- else{
2038
- initOrder = await initDefaultOrderMethod(location, defaultOrderMethod);
2039
- }
2040
- } else {
2041
- initOrder = await initDefaultOrderMethod(location, defaultOrderMethod);
2042
- }
2043
- } else {
2044
- initOrder = await initDefaultOrderMethod(location, defaultOrderMethod);
2045
- }
2046
- }
2047
-
2048
- }
2049
-
2050
- } else {
2051
- initOrder = await initDefaultOrderMethod(location, defaultOrderMethod, merchantId);
2052
- }
2053
- } catch (ex) {
2054
- logger.error("onInitDefaultOrder:", ex);
2055
- }
2056
- return initOrder;
2057
- }
2058
-
2059
- async function getCustomerAddressForOrder({ lat, lon, location } = {}) {
2060
- let addressResult = await onLoadAddress();
2061
- let customerAddress = addressResult.customer_address;
2062
- if (!customerAddress) {
2063
- customerAddress = await onGetCurrentAdress({ lat: lat, lon: lon, location: location });
2064
- }
2065
- return ({ addresses: addressResult.addresses, customer_address: customerAddress })
2066
- }
2067
-
2068
- async function onLoadAddress() {
2069
- var customerAddress = null;
2070
- var _addresses = []
2071
- try {
2072
- var result = await contacts.getContactAddresses();
2073
- if (result.code === 'OK') {
2074
- _addresses = result.data && result.data.content ? result.data.content : [];
2075
- cache.setContactAddresses(_addresses);
2076
- let filterPrimaryAddresses = _addresses.filter(a => {
2077
- return a.is_primary
2078
- })
2079
- if (filterPrimaryAddresses && filterPrimaryAddresses.length > 0) {
2080
- customerAddress = filterPrimaryAddresses[0];
2081
- } else {
2082
- customerAddress = _addresses[0];
2083
- }
2084
- }
2085
- } catch (error) {
2086
- logger.error("load contact error:", error);
2087
- }
2088
- return ({ addresses: _addresses, customer_address: customerAddress })
2089
- }
2090
-
2091
- async function onGetCurrentAdress({ lat, lon, location } = {}) {
2092
- let _currentAddress = null;
2093
- let latlng = null;
2094
- if (lat && lon) {
2095
- latlng = lat + ',' + lon;
2096
- } else {
2097
- if (location) {
2098
- latlng = location.lat + ',' + location.lon
2099
- }
2100
- }
2101
-
2102
- if(!cache.getCurrentLocation())
2103
- {
2104
- if (latlng) {
2105
- try {
2106
- var result = await config.getAddress({ latlng: latlng });
2107
- if (result.code == 'OK') {
2108
- if (result.data) {
2109
- _currentAddress = result.data;
2110
- cache.setCurrentLocation(_currentAddress);
2111
- }
2112
- }
2113
- } catch (error) {
2114
- logger.error("initDeliveryOrder find address exception:", error);
2115
- }
2116
- }
2117
- }
2118
- else{
2119
- _currentAddress = cache.getCurrentLocation();
2120
- }
2121
-
2122
- return _currentAddress;
2123
- }
2124
-
2125
- function groupRecommendedProductsByCategory(data) {
2126
- var items = data.reduce((acc, curr) => {
2127
- let itemExists = acc.find(item => curr.category && curr.category.type === item.category_type)
2128
- if (itemExists) {
2129
- if (curr.category.products && curr.category.products.length > 0) {
2130
- itemExists.categories.push({
2131
- category_name: curr.category.name,
2132
- category_id: curr.category.id,
2133
- products: curr.category.products
2134
- })
2135
- }
2136
- } else {
2137
- if (curr.category.products && curr.category.products.length > 0) {
2138
- acc.push({
2139
- category_type: curr.category.type,
2140
- categories: [{
2141
- category_name: curr.category.name,
2142
- category_id: curr.category.id,
2143
- products: curr.category.products
2144
- }]
2145
- })
2146
- }
2147
- }
2148
- return acc;
2149
- }, []);
2150
-
2151
- items = items.map(i => {
2152
- let newObj = { ...i };
2153
- if (newObj.category_type == 'REWARD_OFFER_PROMOTION') {
2154
- newObj.position = 0
2155
- }
2156
- else if (newObj.category_type == 'BEST_SELLING') {
2157
- newObj.position = 1
2158
- } else {
2159
- newObj.position = 3
2160
- }
2161
- return newObj;
2162
- })
2163
- return items;
2164
- }
2165
-
2166
- function getStoreIds() {
2167
- let stores= cache.getStores();
2168
- if(!stores || stores.length === 0) return [];
2169
- let storeIds = ''
2170
- stores.forEach(store => {
2171
- if(store && store.id) {
2172
- storeIds+=store.id + ',';
2173
- }
2174
- });
2175
- storeIds = storeIds.substring(0, storeIds.length - 1);
2176
- return storeIds;
2177
- }
2178
-
2179
- function getEstimationIds(estimate_order_result) {
2180
- let estimate_ids=[];
2181
- let orders= estimate_order_result.orders ? estimate_order_result.orders : [];
2182
- if(orders && orders.length > 0)
2183
- {
2184
- //return only ids in array
2185
- estimate_ids = orders.map(order => order.id);
2186
- }
2187
-
2188
- return estimate_ids;
2189
- }
2190
-
2191
-
2192
- export function formatDateToMonthNameAndDayOfWeek(date) {
2193
- var date = new Date(date);
2194
- var dayOfWeeks = createShortDayOfWeek();
2195
- var dayOfWeek = dayOfWeeks[date.getDay()];
2196
-
2197
- return dayOfWeek + '. ' + formatDateToShortMonthName(date);
2198
- }
2199
- export function createShortDayOfWeek() {
2200
- var day = i18next.t('SHORTDAYS', { returnObjects: true });
2201
- let days = [
2202
- day.SUNDAY,
2203
- day.MONDAY,
2204
- day.TUESDAY,
2205
- day.WEDNESDAY,
2206
- day.THURSDAY,
2207
- day.FRIDAY,
2208
- day.SATURDAY,
2209
- ];
2210
- return days;
2211
- }
2212
-
2213
- export function createShortMonth() {
2214
- var month = i18next.t('SHORTMONTH', { returnObjects: true });
2215
- let months = [
2216
- month.JAN,
2217
- month.FEB,
2218
- month.MAR,
2219
- month.APR,
2220
- month.MAY,
2221
- month.JUN,
2222
- month.JUL,
2223
- month.AUG,
2224
- month.SEP,
2225
- month.OCT,
2226
- month.NOV,
2227
- month.DEC,
2228
- ];
2229
-
2230
- return months;
2231
- }
2232
-
2233
- export function formatDateToShortMonthName(date) {
2234
- var date = new Date(date);
2235
- var day = date.getDate();
2236
- var month = date.getMonth();
2237
- if (day < 10) day = '0' + day;
2238
- var months = createShortMonth();
2239
- month = months[month];
2240
- var dateFormatted = day + ' ' + month + ' ' + date.getFullYear();
2241
- return dateFormatted;
2242
- }
2243
-
2244
- export function formatDateToDDMMYYYY(date) {
2245
- var date = new Date(date);
2246
- var day = date.getDate();
2247
- var month = date.getMonth() + 1;
2248
- if (day < 10) day = '0' + day;
2249
- if (month < 10) month = '0' + month;
2250
- var dateFormatted = day + '/' + month + '/' + date.getFullYear();
2251
- return dateFormatted;
2252
- }
2253
-
2254
- export function formatDateToDDMMYYYYFrEpoch(epochTime, normal) {
2255
- var d = new Date(epochTime * 1000); // The 0 there is the key, which sets the date to the epoch
2256
- return normal ? formatDateToDDMMYYYY(d) : formatDateToMonthNameAndDayOfWeek(d);
2257
- }
2258
-
2259
- export function newGUID() {
2260
- function s4() {
2261
- return Math.floor((1 + Math.random()) * 0x10000)
2262
- .toString(16)
2263
- .substring(1);
2264
- }
2265
- //return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
2266
- // s4() + '-' + s4() + s4() + s4();
2267
- return s4() + s4() + s4() + s4() +
2268
- s4() + s4() + s4() + s4();
2269
- }