@crmcom/self-service-sdk 2.1.2

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