@pmcretail/mapper-library 0.0.1

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.
@@ -0,0 +1,2521 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Injectable, Inject, Component, NgModule } from '@angular/core';
3
+ import * as JsonToXML from 'js2xmlparser';
4
+ import { BehaviorSubject } from 'rxjs';
5
+
6
+ var TRANSACTION_TYPE;
7
+ (function (TRANSACTION_TYPE) {
8
+ TRANSACTION_TYPE["SALE"] = "SALE";
9
+ TRANSACTION_TYPE["REFUND"] = "REFUND";
10
+ TRANSACTION_TYPE["SALE_REFUND"] = "SALE_REFUND";
11
+ TRANSACTION_TYPE["SALE_EXCHANGE"] = "SALE_EXCHANGE";
12
+ TRANSACTION_TYPE["VOID"] = "VOID";
13
+ })(TRANSACTION_TYPE || (TRANSACTION_TYPE = {}));
14
+ var DELIVERY_METHODS;
15
+ (function (DELIVERY_METHODS) {
16
+ DELIVERY_METHODS[DELIVERY_METHODS["DELIVERY"] = 1] = "DELIVERY";
17
+ DELIVERY_METHODS[DELIVERY_METHODS["DROP_SHIP"] = 2] = "DROP_SHIP";
18
+ DELIVERY_METHODS[DELIVERY_METHODS["COLLECT_FROM_STORE"] = 3] = "COLLECT_FROM_STORE";
19
+ })(DELIVERY_METHODS || (DELIVERY_METHODS = {}));
20
+ var DISCOUNTTYPE;
21
+ (function (DISCOUNTTYPE) {
22
+ DISCOUNTTYPE["PERCENT"] = "Percent";
23
+ DISCOUNTTYPE["AMOUNT"] = "AMOUNT";
24
+ })(DISCOUNTTYPE || (DISCOUNTTYPE = {}));
25
+
26
+ class NumberUtilService {
27
+ constructor(cp) {
28
+ this.cp = cp;
29
+ }
30
+ trimTo2Decimal(no) {
31
+ //return Math.floor(no * 100) / 100;
32
+ return no;
33
+ }
34
+ trimTo2Decimal2(no) {
35
+ return Number(this.getFlooredFixed(no, 2));
36
+ }
37
+ getFlooredFixed(v, d) {
38
+ return (Math.floor(v * Math.pow(10, d)) / Math.pow(10, d)).toFixed(d);
39
+ }
40
+ AppendWithCurrencySymbol(numValue, currencyCode) {
41
+ let returnValue = "";
42
+ if (numValue) {
43
+ const numb = parseFloat(numValue.toString().replace(',', ''));
44
+ returnValue = this.cp.transform(Number(numValue).toFixed(2), currencyCode.toLocaleUpperCase(), "symbol");
45
+ console.log("AppendWithCurrencySymbol :" + returnValue);
46
+ }
47
+ else {
48
+ returnValue = this.cp.transform("0.00", currencyCode.toLocaleUpperCase(), "symbol");
49
+ }
50
+ return returnValue;
51
+ }
52
+ }
53
+ NumberUtilService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: NumberUtilService, deps: [{ token: null }], target: i0.ɵɵFactoryTarget.Injectable });
54
+ NumberUtilService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: NumberUtilService, providedIn: "root" });
55
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: NumberUtilService, decorators: [{
56
+ type: Injectable,
57
+ args: [{
58
+ providedIn: "root",
59
+ }]
60
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
61
+ type: Inject,
62
+ args: [null]
63
+ }] }]; } });
64
+
65
+ class BasketService {
66
+ constructor(numberUtilService) {
67
+ this.numberUtilService = numberUtilService;
68
+ this.currentBasket = {
69
+ products: [],
70
+ transactionDiscount: [],
71
+ quantity: 0,
72
+ total: 0,
73
+ saleTotal: 0,
74
+ baseCurrency: ''
75
+ };
76
+ this.basketSource = new BehaviorSubject(null);
77
+ this.basket = this.basketSource.asObservable();
78
+ this.productSource = new BehaviorSubject(null);
79
+ this.product = this.productSource.asObservable();
80
+ this.peerSource = new BehaviorSubject(false);
81
+ this.peerSync = this.peerSource.asObservable();
82
+ this.scanSource = new BehaviorSubject(false);
83
+ this.scanner = this.scanSource.asObservable();
84
+ }
85
+ get isMixedBasketSales() {
86
+ return this._isMixedBasketSales;
87
+ }
88
+ set isMixedBasketSales(v) {
89
+ this._isMixedBasketSales = v;
90
+ }
91
+ updateBasket(basket) {
92
+ this.currentBasket = basket;
93
+ this.isMixedBasketSales = this.filterProductListWithWebOrder(true).length > 0;
94
+ this.basketSource.next(basket);
95
+ }
96
+ /**
97
+ * calculates the total basket value and quantity
98
+ * @param null
99
+ * @returns void
100
+ */
101
+ updateBasketTotal(basketDetails, basketState) {
102
+ basketDetails.quantity = 0;
103
+ basketDetails.total = 0;
104
+ for (const p of basketDetails.products) {
105
+ basketDetails.quantity = basketDetails.quantity + p.quantity;
106
+ basketDetails.total =
107
+ this.numberUtilService.trimTo2Decimal(basketDetails.total) +
108
+ this.numberUtilService.trimTo2Decimal(p.total);
109
+ }
110
+ console.log("e:basket :basket service : basketDetails updated values for transaction id", basketDetails.transactionId, JSON.stringify(basketDetails));
111
+ basketDetails.basketTotal = basketDetails.total;
112
+ basketState.updateBasket(basketDetails);
113
+ }
114
+ /**
115
+ * add Line promotion
116
+ * @param null
117
+ * @returns basketDetails
118
+ */
119
+ addlinePromotion(promotionList, basketDetails) {
120
+ console.log("e:basket :basket Service : promotionList and basketDetails for linePromotions", JSON.stringify(promotionList), JSON.stringify(basketDetails));
121
+ if (promotionList &&
122
+ promotionList.result &&
123
+ promotionList.result.linePromotions &&
124
+ promotionList.result.linePromotions.length > 0) {
125
+ for (var element of basketDetails.products) {
126
+ for (var promotionelement of promotionList.result.linePromotions) {
127
+ if (element.itemLineId.toString() ===
128
+ promotionelement.itemLineId.toString()) {
129
+ element.linePromotions = promotionelement;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ return basketDetails;
135
+ }
136
+ /**
137
+ * add Transaction promotion
138
+ * @param null
139
+ * @returns basketDetails
140
+ */
141
+ addTransactionPromotion(promotionList, basketdetails) {
142
+ console.log("e:basket :basket Service : promotionList and basketDetails for transactionPromotion", JSON.stringify(promotionList), JSON.stringify(basketdetails), JSON.stringify(basketdetails.transactionPromotion));
143
+ if (promotionList &&
144
+ promotionList.result &&
145
+ promotionList.result.transactionPromotion &&
146
+ promotionList.result.transactionPromotion.length > 0) {
147
+ promotionList.result.transactionPromotion.forEach((tPromotion) => {
148
+ let transactionPromotionEntryUpdated = Object.assign({}, tPromotion);
149
+ transactionPromotionEntryUpdated.itemLineIds = basketdetails.products.map((product) => {
150
+ return product.itemLineId;
151
+ });
152
+ if (!basketdetails.transactionPromotion) {
153
+ basketdetails.transactionPromotion = [];
154
+ }
155
+ basketdetails.transactionPromotion.push(transactionPromotionEntryUpdated);
156
+ basketdetails = this.transactionPromotionProductPortionCalc(basketdetails, transactionPromotionEntryUpdated);
157
+ });
158
+ }
159
+ console.log("basket details in refund calculation file", JSON.stringify(basketdetails));
160
+ return basketdetails;
161
+ }
162
+ updateProductTotalForSummary(basketDetails) {
163
+ /*sale- product refundedQuantity = undefined
164
+ partial refund - product refundedQuantity is > 0
165
+ total refund - proudct refundedQuantity is > 0
166
+ exchange - exchange product refundedQuantity is > 0
167
+ new product refundedQuantity = undefined
168
+ old product without exchange refundedQuantity = 0
169
+ unreference refund-product refundedQuantity is > 0 */
170
+ basketDetails.total = 0;
171
+ basketDetails.quantity = 0;
172
+ for (var product of basketDetails.products) {
173
+ if (product.linePromotions) {
174
+ product.total = product.linePromotions.promotionLinePrice;
175
+ }
176
+ else if (product.lineDiscount && !product.linePromotions) {
177
+ product.total = product.lineDiscount.discountedLinePrice;
178
+ }
179
+ else {
180
+ product.total = product.totalLinePrice;
181
+ }
182
+ product.total =
183
+ product.total -
184
+ Math.abs(product.refundedTotal ? product.refundedTotal : 0);
185
+ basketDetails.total += product.total;
186
+ basketDetails.quantity =
187
+ basketDetails.quantity +
188
+ (product.quantity -
189
+ (product.refundedQuantity ? product.refundedQuantity : 0));
190
+ console.log("e-basket:ExchangeSummaryScreen:update basketdetails total :" +
191
+ basketDetails.total +
192
+ " Product line ID : " +
193
+ product.itemLineId +
194
+ " product total : " +
195
+ product.total, "quantity : " + basketDetails.quantity);
196
+ }
197
+ return this.updateBasketTotalForSummary(basketDetails);
198
+ }
199
+ updateBasketTotalForSummary(basketDetails) {
200
+ basketDetails.basketTotal = basketDetails.total;
201
+ console.info("ebasket : basket Service : update Basket Total for transaction transactionDiscount ", JSON.stringify(basketDetails.transactionDiscount));
202
+ console.info("ebasket : basket Service : update Basket Total for transaction transactionPromotion ", JSON.stringify(basketDetails.transactionPromotion));
203
+ basketDetails = this.updateTransactionPromotion(basketDetails);
204
+ basketDetails = this.updateTransactionDiscount(basketDetails);
205
+ basketDetails.basketTotal = Number(basketDetails.basketTotal.toFixed(2));
206
+ console.info("ebasket : basket Service : update Basket Total: basketTotal after promotion applied for basketTotal", basketDetails.basketTotal);
207
+ return basketDetails;
208
+ }
209
+ updateTransactionDiscount(basketDetails) {
210
+ if (basketDetails.transactionDiscount &&
211
+ basketDetails.transactionDiscount.length > 0) {
212
+ const discountTotal = basketDetails.transactionDiscount.reduce((n, { discountAmount }) => n + discountAmount, 0);
213
+ console.log("ebasket : basket Service : discountTotal ", discountTotal);
214
+ basketDetails.basketTotal =
215
+ basketDetails.basketTotal - Math.abs(discountTotal);
216
+ }
217
+ return basketDetails;
218
+ }
219
+ updateTransactionPromotion(basketDetails) {
220
+ if (basketDetails.transactionPromotion &&
221
+ basketDetails.transactionPromotion.length > 0) {
222
+ const discountTotal = basketDetails.transactionPromotion.reduce((n, { promotionAmount }) => n + promotionAmount, 0);
223
+ basketDetails.basketTotal =
224
+ basketDetails.basketTotal - Math.abs(discountTotal);
225
+ }
226
+ return basketDetails;
227
+ }
228
+ updateBasketTotalWithoutDiscount(basket) {
229
+ basket.total = 0;
230
+ basket.quantity = 0;
231
+ for (var product of basket.products) {
232
+ if (product.linePromotions) {
233
+ product.total = product.linePromotions.promotionLinePrice;
234
+ }
235
+ else if (product.lineDiscount && !product.linePromotions) {
236
+ product.total = product.lineDiscount.discountedLinePrice || 0;
237
+ }
238
+ else {
239
+ product.total = product.totalLinePrice;
240
+ }
241
+ product.total =
242
+ product.total -
243
+ Math.abs(product.refundedTotal ? product.refundedTotal : 0);
244
+ basket.total += product.total;
245
+ basket.quantity =
246
+ basket.quantity +
247
+ (product.quantity -
248
+ (product.refundedQuantity ? product.refundedQuantity : 0));
249
+ console.log("e-basket:basket service:update basketdetails total :" +
250
+ JSON.stringify(basket) +
251
+ basket.total +
252
+ " Product line ID : " +
253
+ product.itemLineId +
254
+ " product total : " +
255
+ product.total);
256
+ }
257
+ basket.basketTotal = basket.total;
258
+ return basket;
259
+ }
260
+ updateBasketTotalWithDiscounts(basket) {
261
+ console.log("e:basket :RefundBasketScreen : this.basketDetails new values", basket, JSON.stringify(basket.basketTotal));
262
+ if (basket.transactionPromotion && basket.transactionPromotion.length > 0) {
263
+ const discountTotal = basket.transactionPromotion.reduce((n, { promotionAmount }) => n + promotionAmount, 0);
264
+ basket.basketTotal = basket.basketTotal - discountTotal;
265
+ }
266
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
267
+ const discountTotal = basket.transactionDiscount.reduce((n, { discountAmount }) => n + discountAmount, 0);
268
+ basket.basketTotal = basket.basketTotal - discountTotal;
269
+ }
270
+ console.log("e:basket :RefundBasketScreen : basket new values", JSON.stringify(basket));
271
+ return basket;
272
+ }
273
+ transactionDiscountAndPromotionProductortionCalculation(basket) {
274
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
275
+ basket.transactionDiscount.forEach((discount) => (basket = this.transactionDiscountProductPortionCalc(basket, discount)));
276
+ }
277
+ if (basket.transactionPromotion && basket.transactionPromotion.length > 0) {
278
+ basket.transactionPromotion.forEach((promotion) => {
279
+ basket = this.transactionPromotionProductPortionCalc(basket, promotion);
280
+ });
281
+ }
282
+ console.log("ebasket: basket item discount protion calculation", basket, basket.products);
283
+ return basket;
284
+ }
285
+ transactionPromotionProductPortionCalc(basket, promotion) {
286
+ let total = 0;
287
+ let percentage = 0;
288
+ {
289
+ basket.products.forEach((p) => {
290
+ if (promotion.itemLineIds.includes(p.itemLineId)) {
291
+ p = this.validateProductItemDiscount(p);
292
+ const productContributionInTotal = this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnDiscountsPortion) +
293
+ this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnPromotionsPortion) -
294
+ this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.refundPortion);
295
+ total += (p.total - this.numberUtilService.trimTo2Decimal2(productContributionInTotal));
296
+ }
297
+ });
298
+ console.log(`ebasket: trnsactionPromotion: ${JSON.stringify(promotion)}, selected products total: ${total}`);
299
+ basket.products.forEach((product) => {
300
+ product = this.validateProductItemDiscount(product);
301
+ const productContributionInTotal = this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion) +
302
+ this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion) -
303
+ this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.refundPortion);
304
+ if (promotion.itemLineIds.includes(product.itemLineId)) {
305
+ percentage = ((product.total - this.numberUtilService.trimTo2Decimal2(productContributionInTotal)) / total) * 100;
306
+ product.itemDiscounts.trnPromotionsPortion +=
307
+ (promotion.promotionAmount * percentage) / 100;
308
+ product.itemDiscounts.trnPromotionsPortion = this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion);
309
+ }
310
+ });
311
+ }
312
+ return basket;
313
+ }
314
+ transactionDiscountProductPortionCalc(basket, discount) {
315
+ let total = 0;
316
+ let percentage = 0;
317
+ basket.products.forEach((p) => {
318
+ if (discount.itemLineIds.includes(p.itemLineId)) {
319
+ p = this.validateProductItemDiscount(p);
320
+ const productContributionInTotal = this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnDiscountsPortion) +
321
+ this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnPromotionsPortion) -
322
+ this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.refundPortion);
323
+ total += (p.total - this.numberUtilService.trimTo2Decimal2(productContributionInTotal));
324
+ }
325
+ });
326
+ console.log(`ebasket: trnsactionDiscount: ${JSON.stringify(discount)}, selected products total: ${total}`);
327
+ basket.products.forEach((product) => {
328
+ product = this.validateProductItemDiscount(product);
329
+ console.log(product.discountable, "ebasket : basket service : discountable in basket service");
330
+ const productContributionInTotal = this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion) +
331
+ this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion) -
332
+ this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.refundPortion);
333
+ if (discount.itemLineIds.includes(product.itemLineId) && product.discountable == true) {
334
+ percentage = ((product.total - this.numberUtilService.trimTo2Decimal2(productContributionInTotal)) / total) * 100;
335
+ product.itemDiscounts.trnDiscountsPortion +=
336
+ (discount.discountAmount * percentage) / 100;
337
+ product.itemDiscounts.trnDiscountsPortion = this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion);
338
+ }
339
+ });
340
+ return basket;
341
+ }
342
+ validateProductItemDiscount(product) {
343
+ if (!product.itemDiscounts) {
344
+ product.itemDiscounts = {
345
+ trnDiscountsPortion: 0,
346
+ trnPromotionsPortion: 0,
347
+ refundPortion: 0,
348
+ };
349
+ }
350
+ return product;
351
+ }
352
+ markProduct(product) {
353
+ this.productSource.next(product);
354
+ }
355
+ stopPeerSyncProcess(peerSync) {
356
+ this.peerSource.next(peerSync);
357
+ }
358
+ scanStart(isScanning) {
359
+ this.scanSource.next(isScanning);
360
+ }
361
+ promotionRemainingCalculation(promotion) {
362
+ var promotionValue = 0;
363
+ promotion.forEach((element) => {
364
+ promotionValue += element.promotionAmount;
365
+ });
366
+ return promotionValue;
367
+ }
368
+ discountRemainingCalculation(discount) {
369
+ var discountValue = 0;
370
+ discount.forEach((element) => {
371
+ discountValue += element.discountAmount;
372
+ });
373
+ return discountValue;
374
+ }
375
+ discountRefundedCalculation(discount) {
376
+ var discountValue = 0;
377
+ discount.forEach((element) => {
378
+ if (element.discountAmount < 0) {
379
+ discountValue += element.discountAmount;
380
+ }
381
+ });
382
+ return discountValue;
383
+ }
384
+ generateNewItemLineId(products) {
385
+ let largestNumber = 0;
386
+ if (products.length > 0) {
387
+ let itemLineIdArray = products.map((product) => {
388
+ return product.itemLineId;
389
+ });
390
+ largestNumber = itemLineIdArray.reduce((a, b) => Math.max(a, b));
391
+ }
392
+ return largestNumber + 1;
393
+ }
394
+ updateBasketProductDataAsPerQuantity(product, quantity) {
395
+ console.log(`ebasket: updateBasketProductDataAsPerQuantity : ${quantity} product: ${JSON.stringify(product)}`);
396
+ product.quantity = quantity;
397
+ if (product.hasOwnProperty("lineDiscount")) {
398
+ // && this.product.quantity !== this.productDetailForm.controls.quantity.value
399
+ product.lineDiscount.discountedLinePrice = Number(this.numberUtilService.getFlooredFixed(product.lineDiscount.unitPrice * quantity, 2));
400
+ product.lineDiscount.discountAmount =
401
+ product.totalLinePrice - product.lineDiscount.discountedLinePrice;
402
+ }
403
+ else {
404
+ product.totalLinePrice =
405
+ quantity * this.numberUtilService.trimTo2Decimal(product.selectedPrice);
406
+ }
407
+ if (product.lineDiscount) {
408
+ product.total = product.lineDiscount.discountedLinePrice;
409
+ }
410
+ else {
411
+ product.total = product.totalLinePrice;
412
+ }
413
+ console.log(`ebasket: updateBasketProductDataAsPerQuantity : ${quantity} product: ${JSON.stringify(product)}`);
414
+ return product;
415
+ }
416
+ filterProductListWithWebOrder(isWebOrder) {
417
+ console.log("ebasket: filterProductListWithWebOrder hit", JSON.stringify(this.currentBasket.products));
418
+ if (isWebOrder)
419
+ return this.currentBasket.products.filter((x) => x.isWebOrder);
420
+ else {
421
+ return this.currentBasket.products.filter((x) => !x.isWebOrder);
422
+ }
423
+ }
424
+ filterProductListWithDelivery() {
425
+ console.log("ebasket: filterProductListWithDelivery hit", JSON.stringify(this.currentBasket.products));
426
+ return this.currentBasket.products.filter((x) => x.deliveryMethod === DELIVERY_METHODS.DELIVERY.toString());
427
+ }
428
+ filterProductListWithDeliveryGroup(group, products) {
429
+ console.log("ebasket: filterProductListWithDeliveryGroup hit", JSON.stringify(products));
430
+ return products.filter((x) => x.deliveryGroup === group);
431
+ }
432
+ generateNewDeliveryGroupNumber(products) {
433
+ let largestNumber = 0;
434
+ if (products.length > 0) {
435
+ let deliveryGroupArr = products.map((product) => {
436
+ if (product.deliveryGroup) {
437
+ return parseInt(product.deliveryGroup);
438
+ }
439
+ return 0;
440
+ });
441
+ largestNumber = deliveryGroupArr.reduce((a, b) => Math.max(a, b));
442
+ }
443
+ return (largestNumber + 1).toString();
444
+ }
445
+ getDeliveryGroupNumbers(products) {
446
+ console.log("getDeliveryGroupNumbers initiating : ", JSON.stringify(products));
447
+ let uniqueAndsortedResult = [];
448
+ if (products.length > 0) {
449
+ let deliveryGroupArr = products.map((product) => {
450
+ if (product.deliveryGroup) {
451
+ return parseInt(product.deliveryGroup);
452
+ }
453
+ else if (product.deliveryMethod === "1") {
454
+ return 1;
455
+ }
456
+ return 0;
457
+ });
458
+ uniqueAndsortedResult = Array.from(new Set(deliveryGroupArr)).sort((a, b) => a - b);
459
+ console.log("getDeliveryGroupNumbers : ", JSON.stringify(uniqueAndsortedResult));
460
+ }
461
+ return uniqueAndsortedResult;
462
+ }
463
+ updateProductsWithNewDeliveryGroupNumber(products) {
464
+ console.log("updateProductsWithNewDeliveryGroupNumber initiating : ", JSON.stringify(products));
465
+ let newGroupNumber = this.generateNewDeliveryGroupNumber(this.currentBasket.products);
466
+ if (products.length > 0) {
467
+ this.currentBasket.products.forEach(cBProducts => {
468
+ products.forEach(element => {
469
+ if (cBProducts.itemLineId === element.itemLineId) {
470
+ cBProducts.deliveryGroup = newGroupNumber;
471
+ }
472
+ });
473
+ });
474
+ }
475
+ this.updateBasket(this.currentBasket);
476
+ return;
477
+ }
478
+ calculateEstimatedTime(products) {
479
+ try {
480
+ let time;
481
+ let estmatedTime = 0;
482
+ let estimatedDays = "Hours";
483
+ products.forEach((element) => {
484
+ if (element.leadTime.type.toLocaleLowerCase() === "weeks") {
485
+ time = Number(element.leadTime.value) * 24 * 7;
486
+ estmatedTime = Math.max(estmatedTime, time);
487
+ estimatedDays = (estmatedTime === time) ? element.leadTime.type : estimatedDays;
488
+ console.log("week", estmatedTime, estimatedDays);
489
+ }
490
+ else if (element.leadTime.type.toLocaleLowerCase() === "days") {
491
+ time = Number(element.leadTime.value) * 24;
492
+ estmatedTime = Math.max(estmatedTime, time);
493
+ estimatedDays = (estmatedTime === time) ? element.leadTime.type : estimatedDays;
494
+ console.log("days", estmatedTime, estimatedDays);
495
+ }
496
+ else if (element.leadTime.type.toLocaleLowerCase() === "months") {
497
+ time = Number(element.leadTime.value) * 24 * 30;
498
+ estmatedTime = Math.max(estmatedTime, time);
499
+ estimatedDays = (estmatedTime === time) ? element.leadTime.type : estimatedDays;
500
+ console.log("months", estmatedTime, estimatedDays);
501
+ }
502
+ else if (element.leadTime.type.toLocaleLowerCase() === "years") {
503
+ time = Number(element.leadTime.value) * 24 * 365;
504
+ estmatedTime = Math.max(estmatedTime, time);
505
+ estimatedDays = (estmatedTime === time) ? element.leadTime.type : estimatedDays;
506
+ console.log("years", estmatedTime, estimatedDays);
507
+ }
508
+ else {
509
+ time = Number(element.leadTime.value);
510
+ estmatedTime = Math.max(estmatedTime, time);
511
+ estimatedDays = (estmatedTime === time) ? element.leadTime.type : estimatedDays;
512
+ console.log("hours", estmatedTime, estimatedDays);
513
+ }
514
+ });
515
+ if (estimatedDays.toLocaleLowerCase() === "days") {
516
+ estmatedTime = estmatedTime / 24;
517
+ }
518
+ else if (estimatedDays.toLocaleLowerCase() === "weeks") {
519
+ estmatedTime = estmatedTime / (24 * 7);
520
+ }
521
+ else if (estimatedDays.toLocaleLowerCase() === "months") {
522
+ estmatedTime = estmatedTime / (24 * 30);
523
+ }
524
+ else if (estimatedDays.toLocaleLowerCase() === "years") {
525
+ estmatedTime = estmatedTime / (24 * 365);
526
+ }
527
+ let estimate = {
528
+ value: estmatedTime.toString(),
529
+ type: estimatedDays
530
+ };
531
+ return estimate;
532
+ }
533
+ catch (error) {
534
+ console.log("error in calculateEstimatedTime", error);
535
+ }
536
+ return 0;
537
+ }
538
+ updateProductsWithDeliveryGroupNumber(oldGroup, newGroup) {
539
+ console.log("updateProductsWithDeliveryGroupNumber initiating");
540
+ this.currentBasket.products.forEach(cBProducts => {
541
+ if (cBProducts.deliveryGroup === oldGroup) {
542
+ cBProducts.deliveryGroup = newGroup;
543
+ }
544
+ });
545
+ this.updateBasket(this.currentBasket);
546
+ return;
547
+ }
548
+ getDeliveryInfo() {
549
+ console.log("getDeliveryGroupInfor initiating");
550
+ try {
551
+ let groupInfo = {
552
+ groups: []
553
+ };
554
+ this.getDeliveryGroupNumbers(this.currentBasket.products).forEach((groupNumber) => {
555
+ let group = {
556
+ groupNumber: groupNumber,
557
+ items: [],
558
+ estimate: {
559
+ type: "Hours",
560
+ value: "0"
561
+ }
562
+ };
563
+ this.currentBasket.products.forEach(cBProducts => {
564
+ if (cBProducts.deliveryGroup === groupNumber.toString()) {
565
+ group.items.push(cBProducts);
566
+ }
567
+ });
568
+ group.estimate = this.calculateEstimatedTime(group.items);
569
+ groupInfo.groups.push(group);
570
+ });
571
+ return groupInfo;
572
+ }
573
+ catch (error) {
574
+ console.log("error", error);
575
+ }
576
+ }
577
+ }
578
+ BasketService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: BasketService, deps: [{ token: NumberUtilService }], target: i0.ɵɵFactoryTarget.Injectable });
579
+ BasketService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: BasketService, providedIn: "root" });
580
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: BasketService, decorators: [{
581
+ type: Injectable,
582
+ args: [{
583
+ providedIn: "root",
584
+ }]
585
+ }], ctorParameters: function () { return [{ type: NumberUtilService }]; } });
586
+
587
+ /**
588
+ * Transaction document builder
589
+ */
590
+ class TransactionDocumentBuilder {
591
+ constructor(transactionDoc, currencyPipe, basketService) {
592
+ this.currencyPipe = currencyPipe;
593
+ this.basketService = basketService;
594
+ this.numberUtilService = new NumberUtilService(currencyPipe);
595
+ this.basketService = new BasketService(this.numberUtilService);
596
+ this.storeInfo = JSON.parse(localStorage.getItem('storeInfo') || '{}');
597
+ if (transactionDoc) {
598
+ this.transactionDocument = transactionDoc;
599
+ }
600
+ else {
601
+ this.transactionDocument = {
602
+ transactionId: "",
603
+ offlineTransactionId: "",
604
+ transactionRef: "",
605
+ dateTime: "",
606
+ orgCode: "",
607
+ storeId: "",
608
+ storeNodeId: "",
609
+ storeNodeStructure: "",
610
+ deviceId: "",
611
+ terminalId: "",
612
+ userId: "",
613
+ initiatingModule: "eBasket",
614
+ export: false,
615
+ basket: {},
616
+ basketSummary: {},
617
+ baseCurrency: "",
618
+ type: "",
619
+ operationStatus: "",
620
+ createdAt: "",
621
+ updatedAt: "",
622
+ id: "",
623
+ currentTransactionDetails: {},
624
+ saleTotal: 0,
625
+ };
626
+ }
627
+ }
628
+ /**
629
+ * Transactions ref
630
+ * @returns ref
631
+ */
632
+ transactionRef() {
633
+ const storeDetails = JSON.parse(localStorage.getItem('storeInfo') || '{}');
634
+ const date = new Date();
635
+ const random = (((1 + Math.random()) * 0x10000) | 0)
636
+ .toString(16)
637
+ .substring(1);
638
+ this.transactionDocument.transactionRef =
639
+ storeDetails.orgCode + storeDetails.storeId + date.toISOString() + random;
640
+ console.log("ebasket: transaction ref created", this.transactionDocument.transactionRef);
641
+ return this;
642
+ }
643
+ /**
644
+ * Transactions id
645
+ * @param transactionID
646
+ * @returns id
647
+ */
648
+ transactionId(transactionID, isOnline = true) {
649
+ if (isOnline) {
650
+ this.transactionDocument.transactionId = transactionID;
651
+ }
652
+ return this;
653
+ }
654
+ /**
655
+ * Transactions id
656
+ * @param transactionID
657
+ * @returns id
658
+ */
659
+ offlineTransactionId(transactionID, isOnline) {
660
+ if (!isOnline) {
661
+ this.transactionDocument.offlineTransactionId = transactionID;
662
+ }
663
+ return this;
664
+ }
665
+ /**
666
+ * storeNode Id
667
+ * @param storeNodeId
668
+ * @returns id
669
+ */
670
+ storeNodeId(storeNodeId) {
671
+ this.transactionDocument.storeNodeId = storeNodeId;
672
+ return this;
673
+ }
674
+ /**
675
+ * storeNode structure
676
+ * @param storeNodeStructure
677
+ * @returns id
678
+ */
679
+ storeNodeStructure(storeNodeStructure) {
680
+ this.transactionDocument.storeNodeStructure = storeNodeStructure;
681
+ return this;
682
+ }
683
+ /**
684
+ * Orgs code
685
+ * @param orgCode
686
+ * @returns code
687
+ */
688
+ orgCode(orgCode) {
689
+ this.transactionDocument.orgCode = orgCode;
690
+ return this;
691
+ }
692
+ /**
693
+ * Stores id
694
+ * @param storeId
695
+ * @returns id
696
+ */
697
+ storeId(storeId) {
698
+ this.transactionDocument.storeId = storeId;
699
+ return this;
700
+ }
701
+ /**
702
+ * Dates time
703
+ * @returns time
704
+ */
705
+ dateTime() {
706
+ const date = new Date();
707
+ this.transactionDocument.dateTime = date.toISOString();
708
+ return this;
709
+ }
710
+ /**
711
+ * Devices id
712
+ * @param deviceId
713
+ * @returns id
714
+ */
715
+ deviceId(deviceId) {
716
+ this.transactionDocument.deviceId = deviceId;
717
+ return this;
718
+ }
719
+ /**
720
+ * terminal id
721
+ * @param terminalId
722
+ * @returns id
723
+ */
724
+ terminalId(terminalId) {
725
+ this.transactionDocument.terminalId = terminalId;
726
+ return this;
727
+ }
728
+ /**
729
+ * saleExport
730
+ * @param saleExport
731
+ * @returns id
732
+ */
733
+ export(saleExport) {
734
+ this.transactionDocument.export = saleExport;
735
+ return this;
736
+ }
737
+ /* customer(): TransactionDocumentBuilder {
738
+ const user = JSON.parse(localStorage.getItem('userDetails'));
739
+ this.transactionDocument.customer = user;
740
+ return this;
741
+ } */
742
+ /**
743
+ * Baskets transaction document builder
744
+ * @param basketDetails
745
+ * @returns basket
746
+ */
747
+ basket(basketDetails) {
748
+ console.log("ebasket: basket details update in transaction document", JSON.stringify(basketDetails));
749
+ this.transactionDocument.subsidiaryId = basketDetails.subsidiaryId || (localStorage.getItem('subsidiaryId') || '');
750
+ this.transactionDocument.basket.products = [];
751
+ this.transactionDocument.basket.lineDiscount = [];
752
+ this.transactionDocument.basket.linePromotion = [];
753
+ this.transactionDocument.basket.transactionPromotion = [];
754
+ basketDetails.products.forEach((product, index) => {
755
+ const p = {};
756
+ p.itemDiscounts = {};
757
+ p.SKU = product.SKU;
758
+ p.excludePromotion = product.excludePromotion;
759
+ p.barCode = product.barcode;
760
+ p.barcodes = product.barcodes;
761
+ p.description = product.description;
762
+ p.itemLineId = product.itemLineId ? product.itemLineId.toString() : "" + (index + 1);
763
+ p.price = product.selectedPrice;
764
+ p.quantity = product.quantity;
765
+ p.totalLinePrice = product.quantity * product.selectedPrice;
766
+ p.imageUrls = product.imageUrls;
767
+ p.selectedRRPPrice = product.selectedRRPPrice;
768
+ //inventory fields
769
+ p.fullfilmentId = product.fullfilmentId ? product.fullfilmentId : this.storeInfo.storeId;
770
+ p.fullfilmentLocationName = product.fullfilmentLocationName;
771
+ p.deliveryGroup = product.deliveryGroup;
772
+ p.leadTime = product.leadTime;
773
+ p.deliveryMethod = product.deliveryMethod;
774
+ p.giftCard = product.giftCard;
775
+ p.giftCardExpiryDate = product.giftCardExpiryDate;
776
+ p.giftCardNumberIssued = product.giftCardNumberIssued;
777
+ p.giftCardRecipientEmail = product.giftCardRecipientEmail;
778
+ p.giftCardRecipientName = product.giftCardRecipientName;
779
+ if (product.refundedQuantity > 0) {
780
+ p.refundedQuantity = product.refundedQuantity;
781
+ p.refundedPromotionalQuantity = product.refundPromotionalQuantity;
782
+ p.refunded = product.refunded;
783
+ p.refundedReasonDescription = product.refundedReasonDescription;
784
+ p.refundedReason = product.refundedReason;
785
+ if (!p.refundedReasonDescription) {
786
+ p.refundedReasonDescription = p.refundedReason;
787
+ }
788
+ p.refundedTotal = product.refundedTotal;
789
+ p.isLastExchanged = product.isLastExchanged;
790
+ }
791
+ if (product.exchange) {
792
+ p.exchange = product.exchange;
793
+ }
794
+ if (product.lineDiscount) {
795
+ p.lineDiscount = product.lineDiscount;
796
+ }
797
+ p.itemDiscounts = product.itemDiscounts;
798
+ this.transactionDocument.basket.products.push(p);
799
+ this.lineDiscount(basketDetails);
800
+ });
801
+ console.info("ebasket: transactiondocument basket details updated", JSON.stringify(this.transactionDocument.basket));
802
+ return this;
803
+ }
804
+ /**
805
+ * current transaction Details Total(New Products)
806
+ * @returns currentTransactionDetails
807
+ */
808
+ currentTransactionDetails(basket) {
809
+ console.log("ebasket: current transaction details for exchanges", basket);
810
+ this.transactionDocument.currentTransactionDetails.products = [];
811
+ this.transactionDocument.currentTransactionDetails.linePromotion = [];
812
+ this.transactionDocument.currentTransactionDetails.lineDiscount = [];
813
+ this.transactionDocument.currentTransactionDetails.transactionDiscount = [];
814
+ this.transactionDocument.currentTransactionDetails.products = basket.products;
815
+ this.transactionDocument.currentTransactionDetails.products = this.transactionDocument.currentTransactionDetails.products.filter((proj) => proj.refundedQuantity != 0);
816
+ this.transactionDocument.currentTransactionDetails.products.forEach((product) => {
817
+ if (product.refundedQuantity) {
818
+ product.quantity = product.refundedQuantity;
819
+ // updating total line price with actual price to be refunded including the refunding qty
820
+ product.totalLinePrice = Math.abs(product.refundedTotal);
821
+ product.total = product.totalLinePrice;
822
+ if (product.quantity === product.refundedQuantity) {
823
+ product.refunded = true;
824
+ }
825
+ }
826
+ //Updating line promotions and line discounts
827
+ if (product.linePromotions && !product.refundedQuantity) {
828
+ this.transactionDocument.currentTransactionDetails.linePromotion.push(product.linePromotions);
829
+ }
830
+ if (product.lineDiscount && !product.refundedQuantity) {
831
+ this.transactionDocument.currentTransactionDetails.lineDiscount.push(product.lineDiscount);
832
+ }
833
+ });
834
+ console.log("ebasket: current transaction details after removing old products", this.transactionDocument.currentTransactionDetails.products);
835
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
836
+ this.transactionDocument.currentTransactionDetails.transactionDiscount.push(...basket.transactionDiscount);
837
+ }
838
+ this.transactionDocument.currentTransactionDetails.basketSummary = {};
839
+ this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal = this.numberUtilService.trimTo2Decimal2(this.updateSaleTotal(this.transactionDocument.currentTransactionDetails));
840
+ this.transactionDocument.currentTransactionDetails.basketSummary.totalItems = basket.quantity;
841
+ this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal = basket.basketTotal;
842
+ this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal = this.updateCurrentTransactionDetailsRefundTotal();
843
+ // For partial refund discount is updatied in total line price so discountTotal will always be zero & in case of exchange discount total is calculated
844
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
845
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = this.numberUtilService.trimTo2Decimal2(this.updateCurrentTransactionDetailsDiscountTotal());
846
+ }
847
+ else {
848
+ if (this.transactionDocument.currentTransactionDetails.transactionDiscount && this.transactionDocument.currentTransactionDetails.transactionDiscount.length > 0) {
849
+ let discountTotal = 0;
850
+ this.transactionDocument.currentTransactionDetails.transactionDiscount.forEach((discount) => {
851
+ discountTotal += discount.discountAmount;
852
+ });
853
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = Math.abs(discountTotal);
854
+ }
855
+ else {
856
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = 0;
857
+ }
858
+ }
859
+ console.log("ebasket:this.transactionDocument.currentTransactionDetails", JSON.stringify(this.transactionDocument.currentTransactionDetails));
860
+ return this;
861
+ }
862
+ /**
863
+ * current transaction Tax Total
864
+ * @returns Tax Total
865
+ */
866
+ updateCurrentTransactionDetailsTaxBreakdown(basketDetails) {
867
+ let transactionDiscountTotal = 0;
868
+ let taxBreakdown = {
869
+ taxLines: [],
870
+ totalTaxableAmount: 0,
871
+ };
872
+ if (this.transactionDocument.currentTransactionDetails.transactionDiscount && this.transactionDocument.currentTransactionDetails.transactionDiscount.length > 0) {
873
+ this.transactionDocument.currentTransactionDetails.transactionDiscount.forEach((discount) => {
874
+ transactionDiscountTotal += discount.discountAmount;
875
+ });
876
+ }
877
+ if (this.transactionDocument.currentTransactionDetails.products && this.transactionDocument.currentTransactionDetails.products.length > 0) {
878
+ this.transactionDocument.currentTransactionDetails.products.forEach((product) => {
879
+ let taxLine = {
880
+ itemLineId: product.itemLineId,
881
+ VAT: product.selectedVAT ? product.selectedVAT : 0,
882
+ VATCode: product.selectedVATCode,
883
+ taxLineTotal: 0,
884
+ taxableAmount: product.total,
885
+ PreTax: 0
886
+ };
887
+ console.info("Product contribution : item line ID :current transaction Details", product.itemLineId, "tax line :", JSON.stringify(taxLine), JSON.stringify(basketDetails.basketTotal));
888
+ //step 1
889
+ // if Transaction Discount and/or promotion applied, find net selling price of each product as taxableamount
890
+ //If transaction discount/promotion is applied taxable amount should be deducting transaction promotion and transaction disacount portion
891
+ if (product.refundedQuantity && product.refundedQuantity > 0) {
892
+ taxLine.taxableAmount = -Math.abs(taxLine.taxableAmount - product.itemDiscounts.currentRefundPortion);
893
+ }
894
+ else {
895
+ taxLine.taxableAmount = taxLine.taxableAmount - product.itemDiscounts.trnDiscountsPortion - product.itemDiscounts.trnPromotionsPortion;
896
+ }
897
+ //step 2 - find pre tax
898
+ taxLine.PreTax = this.numberUtilService.trimTo2Decimal2((taxLine.taxableAmount * 100) / (100 + taxLine.VAT));
899
+ //step 3 - Update taxbreakdown
900
+ taxBreakdown.totalTaxableAmount += taxLine.taxableAmount;
901
+ taxLine.taxableAmount = this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount);
902
+ // step 4 - update tax Line total
903
+ taxLine.taxLineTotal = this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount - taxLine.PreTax);
904
+ taxBreakdown.taxLines.push(taxLine);
905
+ });
906
+ }
907
+ taxBreakdown.totalTaxableAmount = this.numberUtilService.trimTo2Decimal2(taxBreakdown.totalTaxableAmount);
908
+ this.transactionDocument.currentTransactionDetails.taxBreakdown = taxBreakdown;
909
+ if (this.transactionDocument.currentTransactionDetails.taxBreakdown && this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines && this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.length > 0) {
910
+ this.transactionDocument.currentTransactionDetails.basketSummary.VATTotal = this.numberUtilService.trimTo2Decimal2(this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.reduce((n, { taxLineTotal }) => n + taxLineTotal, 0));
911
+ }
912
+ else {
913
+ this.transactionDocument.currentTransactionDetails.basketSummary.VATTotal = 0.00;
914
+ }
915
+ console.log("eBasket:after calculating tax currenttransactionDetails", this.transactionDocument.currentTransactionDetails);
916
+ return this;
917
+ }
918
+ updateCurrentTransactionDetailsTotalTaxSummary() {
919
+ console.log("Total Tax Summery Request :", JSON.stringify(this.transactionDocument.currentTransactionDetails.taxBreakdown));
920
+ let totalTaxSummaryArray = [];
921
+ let totalTaxSummaryGroup = [];
922
+ console.log("Tax Lines for Total Tax Summery :", JSON.stringify(this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines));
923
+ this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.forEach((element) => {
924
+ let TaxSummary = {
925
+ VATCode: "",
926
+ VAT: -12345,
927
+ PreTaxSum: 0,
928
+ TaxSum: 0,
929
+ TXrateSum: 0
930
+ };
931
+ TaxSummary.VATCode = element.VATCode;
932
+ TaxSummary.VAT = element.VAT;
933
+ TaxSummary.PreTaxSum = this.numberUtilService.trimTo2Decimal2(element.PreTax);
934
+ TaxSummary.TaxSum = this.numberUtilService.trimTo2Decimal2(element.taxLineTotal);
935
+ TaxSummary.TXrateSum = this.numberUtilService.trimTo2Decimal2(TaxSummary.PreTaxSum + TaxSummary.TaxSum);
936
+ totalTaxSummaryArray.push(TaxSummary);
937
+ });
938
+ console.log("Total Tax Summery Without Grouped : ", JSON.stringify(totalTaxSummaryArray));
939
+ totalTaxSummaryGroup = totalTaxSummaryArray.reduce((preparedArray, currentObj) => {
940
+ let ind = preparedArray.findIndex((x) => x.VAT === currentObj.VAT);
941
+ if (ind === -1) {
942
+ preparedArray.push(currentObj);
943
+ }
944
+ else {
945
+ preparedArray[ind].VATCode = currentObj.VATCode;
946
+ preparedArray[ind].VAT = currentObj.VAT;
947
+ preparedArray[ind].PreTaxSum += currentObj.PreTaxSum;
948
+ preparedArray[ind].TaxSum += currentObj.TaxSum;
949
+ preparedArray[ind].TXrateSum += currentObj.TXrateSum;
950
+ }
951
+ return preparedArray;
952
+ }, []);
953
+ // listOfTags.map(x => unique.filter(a => a.label == x.label && a.color == x.color).length > 0 ? null : unique.push(x));
954
+ console.log("Total Tax Summer Group :", JSON.stringify(totalTaxSummaryGroup));
955
+ this.transactionDocument.currentTransactionDetails.totalTaxSummary = totalTaxSummaryGroup;
956
+ return this;
957
+ }
958
+ /**
959
+ * current transaction Disocunt Total
960
+ * @returns Discount Total
961
+ */
962
+ updateCurrentTransactionDetailsDiscountTotal() {
963
+ let refundTotal = this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal ? this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal : 0;
964
+ console.log("e-basket: transaction builder updateCurrentTransactionDetailsDiscountTotal: discountTotal", refundTotal, this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal, this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal);
965
+ const discountTotal = Math.abs(Math.abs(this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal) -
966
+ (Math.abs(this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal) + Math.abs(refundTotal)));
967
+ console.log("e-basket: transaction builder updateCurrentTransactionDetailsDiscountTotal: discountTotal", discountTotal);
968
+ return Number(discountTotal.toFixed(2));
969
+ }
970
+ /**
971
+ * current transaction Refund Total
972
+ * @returns Refund Total
973
+ */
974
+ updateCurrentTransactionDetailsRefundTotal() {
975
+ let totalRefund = 0;
976
+ for (let index = 0; index < this.transactionDocument.currentTransactionDetails.products.length; index++) {
977
+ const product = this.transactionDocument.currentTransactionDetails.products[index];
978
+ if (product.refundedTotal) {
979
+ totalRefund = totalRefund + product.refundedTotal;
980
+ }
981
+ console.log("ebasket : transaction Service: totalRefund for Current TransactionDetails" + totalRefund);
982
+ }
983
+ return totalRefund;
984
+ }
985
+ /**
986
+ * Baskets summary
987
+ * @param basketDetails
988
+ * @returns summary
989
+ */
990
+ basketSummary(basketDetails) {
991
+ this.transactionDocument.basketSummary.basketTotal = this.numberUtilService.trimTo2Decimal(basketDetails.basketTotal);
992
+ this.transactionDocument.basketSummary.saleTotal = this.numberUtilService.trimTo2Decimal2(this.updateSaleTotal(basketDetails));
993
+ this.transactionDocument.basketSummary.refundTotal = this.getRefundTotal();
994
+ if (this.transactionDocument.basket.lineDiscount ||
995
+ this.transactionDocument.basket.linePromotion) {
996
+ this.transactionDocument.basketSummary.discountTotal = this.numberUtilService.trimTo2Decimal2(this.updateDiscountTotal());
997
+ }
998
+ this.transactionDocument.basketSummary.totalItems = basketDetails.quantity;
999
+ if (this.transactionDocument.basket.taxBreakdown) {
1000
+ this.transactionDocument.basketSummary.VATTotal = this.numberUtilService.trimTo2Decimal2(this.transactionDocument.basket.taxBreakdown.taxLines.reduce((n, { taxLineTotal }) => n + taxLineTotal, 0));
1001
+ }
1002
+ else {
1003
+ this.transactionDocument.basketSummary.VATTotal = 0.00;
1004
+ }
1005
+ console.info("ebasket: basketsummary updated in transaction document: ", JSON.stringify(this.transactionDocument.basketSummary));
1006
+ return this;
1007
+ }
1008
+ /**
1009
+ * Line Discount
1010
+ * @param basketDetails
1011
+ * @returns line Discount
1012
+ */
1013
+ lineDiscount(basketDetails) {
1014
+ this.transactionDocument.basket.lineDiscount = [];
1015
+ for (let index = 0; index < basketDetails.products.length; index++) {
1016
+ const element = basketDetails.products[index];
1017
+ if (element.lineDiscount) {
1018
+ this.transactionDocument.basket.lineDiscount.push(element.lineDiscount);
1019
+ this.transactionDocument.basket.lineDiscount = this.transactionDocument.basket.lineDiscount.reduce((acc, val) => {
1020
+ if (!acc.find((el) => el.itemLineId === val.itemLineId)) {
1021
+ acc.push(val);
1022
+ }
1023
+ return acc;
1024
+ }, []);
1025
+ }
1026
+ // console.info(
1027
+ // "e-basket :line discount updated in transaction document",
1028
+ // this.transactionDocument.basket.lineDiscount
1029
+ // );
1030
+ }
1031
+ return this;
1032
+ }
1033
+ /**
1034
+ * exchange
1035
+ * @param basketDetails
1036
+ * @returns exchange
1037
+ */
1038
+ exchange(basketDetails) {
1039
+ this.transactionDocument.basket.exchange = basketDetails.exchange && basketDetails.exchange.length > 0 ? [...basketDetails.exchange] : [];
1040
+ for (let index = 0; index < basketDetails.products.length; index++) {
1041
+ const element = basketDetails.products[index];
1042
+ if (element.exchange != undefined) {
1043
+ const isPresent = this.transactionDocument.basket.exchange.some((el) => el.exchangeId === element.exchange.exchangeId);
1044
+ if (!isPresent) {
1045
+ let exchangeItems = [];
1046
+ for (let j = 0; j < element.exchange.newItems.length; j++) {
1047
+ const item = element.exchange.newItems[j];
1048
+ let newItems = { lineItemId: item.itemLineId, Quantity: item.quantity };
1049
+ exchangeItems.push(newItems);
1050
+ }
1051
+ element.exchange.newItems = [...exchangeItems];
1052
+ this.transactionDocument.basket.exchange.push(element.exchange);
1053
+ }
1054
+ }
1055
+ console.log("e-basket :TransactionDocumentBuilder: this.transactionDocument.basket exchange", JSON.stringify(this.transactionDocument.basket.exchange));
1056
+ }
1057
+ return this;
1058
+ }
1059
+ /**
1060
+ * add previous exchange data
1061
+ * @param originalTransactionDocument
1062
+ * @returns line Promotions
1063
+ */
1064
+ addExchangeData(originalTransactionDocument) {
1065
+ this.transactionDocument.basket.exchange = originalTransactionDocument.basket.exchange ? [...originalTransactionDocument.basket.exchange] : null;
1066
+ return this;
1067
+ }
1068
+ /**
1069
+ * line Promotions
1070
+ * @param basketDetails
1071
+ * @returns line Promotions
1072
+ */
1073
+ linePromotion(basketDetails) {
1074
+ this.transactionDocument.basket.linePromotion = [];
1075
+ for (let index = 0; index < basketDetails.products.length; index++) {
1076
+ const element = basketDetails.products[index];
1077
+ if (element.linePromotions) {
1078
+ this.transactionDocument.basket.linePromotion.push(element.linePromotions);
1079
+ this.transactionDocument.basket.linePromotion = this.transactionDocument.basket.linePromotion.reduce((acc, val) => {
1080
+ if (!acc.find((el) => el.itemLineId === val.itemLineId)) {
1081
+ acc.push(val);
1082
+ }
1083
+ return acc;
1084
+ }, []);
1085
+ }
1086
+ }
1087
+ return this;
1088
+ }
1089
+ /**
1090
+ * transaction Promotion
1091
+ * @param basketDetails
1092
+ * @returns transaction Promotion
1093
+ */
1094
+ transactionPromotion(basketDetails) {
1095
+ if (basketDetails.transactionPromotion) {
1096
+ this.transactionDocument.basket.transactionPromotion =
1097
+ basketDetails.transactionPromotion;
1098
+ // for (let index = 0; index < basketDetails.TransactionDiscount.length; index++) {
1099
+ // this.transactionDocument.basket.transactionPromotion.push(element.linePromotions)
1100
+ // this.transactionDocument.basket.transactionPromotion = this.transactionDocument.basket.linePromotions.reduce((acc, val) => {
1101
+ // if (!acc.find(el => el.itemLineId === val.itemLineId)) {
1102
+ // acc.push(val);
1103
+ // }
1104
+ // return acc;
1105
+ // }, []);
1106
+ // }
1107
+ console.log("e-basket :TransactionDocumentBuilder: this.transactionDocument.basket.transactionPromotion", JSON.stringify(this.transactionDocument.basket.transactionPromotion));
1108
+ }
1109
+ return this;
1110
+ }
1111
+ transactionDiscount(basketDetails) {
1112
+ if (basketDetails.transactionDiscount) {
1113
+ this.transactionDocument.basket.transactionDiscount =
1114
+ basketDetails.transactionDiscount;
1115
+ console.log("e-basket :TransactionDocumentBuilder: transaction Discount", JSON.stringify(this.transactionDocument.basket.transactionDiscount));
1116
+ }
1117
+ return this;
1118
+ }
1119
+ /**
1120
+ * Payments details
1121
+ * @param paymentDetails
1122
+ * @returns
1123
+ */
1124
+ paymentDetails(paymentDetails) {
1125
+ console.info("ebasket : payment details after transaction completed", JSON.stringify(paymentDetails));
1126
+ this.transactionDocument.paymentDetails = paymentDetails;
1127
+ return this;
1128
+ }
1129
+ /**
1130
+ * Payments details
1131
+ * @param paymentDetails
1132
+ * @returns
1133
+ */
1134
+ splitPayment(splitPayment) {
1135
+ this.transactionDocument.splitPayment = splitPayment;
1136
+ return this;
1137
+ }
1138
+ /**
1139
+ * Payments details
1140
+ * @param paymentDetails
1141
+ * @returns
1142
+ */
1143
+ isPaymentCompleted(isPaymentCompleted) {
1144
+ this.transactionDocument.isPaymentCompleted = isPaymentCompleted;
1145
+ return this;
1146
+ }
1147
+ /**
1148
+ * Bases currency
1149
+ * @param currency
1150
+ * @returns currency
1151
+ */
1152
+ baseCurrency(currency) {
1153
+ this.transactionDocument.baseCurrency = currency;
1154
+ return this;
1155
+ }
1156
+ /**
1157
+ * gift option at
1158
+ * @returns at
1159
+ */
1160
+ giftOption(gift) {
1161
+ console.log("e-basket :TransactionDocumentBuilder: this.transactionDocument.giftoption", gift);
1162
+ if (gift) {
1163
+ this.transactionDocument.giftedReceipt = gift;
1164
+ }
1165
+ return this;
1166
+ }
1167
+ /**
1168
+
1169
+ /**
1170
+ * manual Discount
1171
+ * @param discountData
1172
+ * @returns
1173
+ */
1174
+ // manualDiscount(discountData : basketDiscount):TransactionDocumentBuilder {
1175
+ // let saleTotal = this.transactionDocument.basketSummary.basketTotal;
1176
+ // if(discountData.discountType =='Percent'){
1177
+ // this.transactionDocument.basketSummary.basketTotal = saleTotal-(saleTotal*(discountData.discountAmount/100));
1178
+ // discountData.discountAmount = -1*(saleTotal-this.transactionDocument.basketSummary.basketTotal);
1179
+ // }else {
1180
+ // this.transactionDocument.basketSummary.basketTotal =saleTotal-discountData.discountAmount;
1181
+ // discountData.discountAmount = -1*discountData.discountAmount;
1182
+ // }
1183
+ // this.transactionDocument.transactionDiscount.push(discountData);
1184
+ // return this;
1185
+ // }
1186
+ /**
1187
+ * Types transaction document builder
1188
+ * @param t
1189
+ * @returns type
1190
+ */
1191
+ type(t) {
1192
+ this.transactionDocument.type = t;
1193
+ return this;
1194
+ }
1195
+ /**
1196
+ * Operations status
1197
+ * @param o
1198
+ * @returns status
1199
+ */
1200
+ operationStatus(o) {
1201
+ this.transactionDocument.operationStatus = o;
1202
+ return this;
1203
+ }
1204
+ /**
1205
+ * Created at
1206
+ * @returns at
1207
+ */
1208
+ createdAt() {
1209
+ const date = new Date();
1210
+ this.transactionDocument.createdAt = date.toISOString();
1211
+ this.transactionDocument.updatedAt = date.toISOString();
1212
+ return this;
1213
+ }
1214
+ /**
1215
+ * Updated at
1216
+ * @returns at
1217
+ */
1218
+ updatedAt() {
1219
+ const date = new Date();
1220
+ this.transactionDocument.updatedAt = date.toISOString();
1221
+ return this;
1222
+ }
1223
+ /**
1224
+ * transsaction completion at
1225
+ * @returns transaction completion date
1226
+ */
1227
+ transactionCompletedAt() {
1228
+ const date = new Date();
1229
+ this.transactionDocument.transCompletedAt = date.toISOString();
1230
+ return this;
1231
+ }
1232
+ /**
1233
+ * Builds transaction document builder
1234
+ * @returns build
1235
+ */
1236
+ build() {
1237
+ return this.transactionDocument;
1238
+ }
1239
+ /**
1240
+ * Sales total in refund
1241
+ * @param saleTotal
1242
+ * @returns total in refund
1243
+ */
1244
+ saleTotalInRefund(saleTotal) {
1245
+ this.transactionDocument.saleTotal = saleTotal;
1246
+ return this;
1247
+ }
1248
+ /**
1249
+ * Gets basket details
1250
+ * @returns basket details
1251
+ */
1252
+ getBasketDetails() {
1253
+ console.info("ebasket: Getting Basket for transactionDocument", JSON.stringify(this.transactionDocument));
1254
+ let basket = {
1255
+ subsidiaryId: this.transactionDocument.subsidiaryId,
1256
+ transactionDiscount: this.transactionDocument.basket.transactionDiscount,
1257
+ transactionPromotion: this.transactionDocument.basket.transactionPromotion,
1258
+ transactionId: this.transactionDocument.transactionId,
1259
+ offlineTransactionId: this.transactionDocument.offlineTransactionId,
1260
+ total: this.transactionDocument.basketSummary.basketTotal,
1261
+ basketTotal: this.transactionDocument.basketSummary.basketTotal,
1262
+ discountTotal: this.transactionDocument.basketSummary.discountTotal,
1263
+ saleTotal: this.transactionDocument.basketSummary.saleTotal,
1264
+ refundTotal: this.transactionDocument.basketSummary.refundTotal,
1265
+ quantity: this.transactionDocument.basketSummary.totalItems,
1266
+ products: [],
1267
+ baseCurrency: this.transactionDocument.baseCurrency,
1268
+ customer: this.transactionDocument.customer,
1269
+ };
1270
+ basket.products = [];
1271
+ this.transactionDocument.basket.products.forEach((product, index) => {
1272
+ console.log(JSON.stringify(product), "ebasket: basket detail update in basket");
1273
+ const p = {};
1274
+ p.SKU = product.SKU;
1275
+ p.barcode = product.barCode;
1276
+ p.barcodes = product.barcodes;
1277
+ p.description = product.description;
1278
+ p.imageUrls = product.imageUrls;
1279
+ p.currency = this.transactionDocument.baseCurrency;
1280
+ p.totalLinePrice = product.totalLinePrice;
1281
+ p.itemLineId = Number(product.itemLineId);
1282
+ p.excludePromotion = product.excludePromotion;
1283
+ p.selectedPrice = product.price;
1284
+ p.quantity = product.quantity;
1285
+ p.total = product.totalLinePrice;
1286
+ p.selectedRRPPrice = product.selectedRRPPrice;
1287
+ p.fullfilmentId = product.fullfilmentId;
1288
+ p.fullfilmentLocationName = product.fullfilmentLocationName;
1289
+ p.deliveryGroup = product.deliveryGroup || "1";
1290
+ p.leadTime = product.leadTime;
1291
+ p.deliveryMethod = product.deliveryMethod || DELIVERY_METHODS.COLLECT_FROM_STORE.toString();
1292
+ if (p.fullfilmentId != this.transactionDocument.storeId) {
1293
+ p.isWebOrder = true;
1294
+ }
1295
+ p.giftCard = product.giftCard;
1296
+ p.giftCardExpiryDate = product.giftCardExpiryDate;
1297
+ p.giftCardNumberIssued = product.giftCardNumberIssued;
1298
+ p.giftCardRecipientEmail = product.giftCardRecipientEmail;
1299
+ p.giftCardRecipientName = product.giftCardRecipientName;
1300
+ if (this.transactionDocument.basket.lineDiscount &&
1301
+ this.transactionDocument.basket.lineDiscount.length > 0) {
1302
+ this.transactionDocument.basket.lineDiscount.forEach((lineDiscount) => {
1303
+ if (product.itemLineId === lineDiscount.itemLineId.toString()) {
1304
+ p.lineDiscount = lineDiscount;
1305
+ p.total = lineDiscount.discountedLinePrice;
1306
+ }
1307
+ });
1308
+ }
1309
+ if (this.transactionDocument.basket.linePromotion &&
1310
+ this.transactionDocument.basket.linePromotion.length > 0) {
1311
+ this.transactionDocument.basket.linePromotion.forEach((linePromotion) => {
1312
+ if (product.itemLineId === linePromotion.itemLineId.toString()) {
1313
+ p.linePromotions = linePromotion;
1314
+ p.total = linePromotion.promotionLinePrice;
1315
+ }
1316
+ });
1317
+ }
1318
+ if (this.transactionDocument.basket.taxBreakdown &&
1319
+ this.transactionDocument.basket.taxBreakdown.taxLines.length > 0) {
1320
+ this.transactionDocument.basket.taxBreakdown.taxLines.forEach((taxLine) => {
1321
+ if (product.itemLineId && product.itemLineId === taxLine.itemLineId.toString()) {
1322
+ p.selectedVAT = taxLine.VAT;
1323
+ p.selectedVATCode = taxLine.VATCode;
1324
+ }
1325
+ });
1326
+ }
1327
+ if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
1328
+ p.total = product.refundedTotal;
1329
+ }
1330
+ else if ((this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND || TRANSACTION_TYPE.SALE_EXCHANGE) && product.refundedQuantity > 0) {
1331
+ p.refundedReasonDescription = product.refundedReasonDescription;
1332
+ p.refundedReason = product.refundedReason;
1333
+ if (!p.refundedReasonDescription) {
1334
+ p.refundedReasonDescription = p.refundedReason;
1335
+ }
1336
+ p.refundedQuantity = product.refundedQuantity;
1337
+ p.refundPromotionalQuantity = product.refundedPromotionalQuantity;
1338
+ p.refundedTotal = product.refundedTotal;
1339
+ p.total -= Math.abs(p.refundedTotal);
1340
+ p.isLastExchanged = product.isLastExchanged;
1341
+ }
1342
+ if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
1343
+ if (p.total > 0) {
1344
+ p.total *= -1;
1345
+ }
1346
+ }
1347
+ basket.products.push(p);
1348
+ });
1349
+ basket = this.getTransactionDiscountAndTransactionPromotionPortion(basket);
1350
+ basket.total = (basket.basketTotal || 0) + this.getTotalDiscountWithTransactionDiscountsAndPromotions(basket);
1351
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND) {
1352
+ basket.quantity = this.getRefundedTotalWithQuantity(basket);
1353
+ }
1354
+ console.info("ebasket: Basket created successfully", JSON.stringify(basket));
1355
+ return basket;
1356
+ }
1357
+ /**
1358
+ * Gets basket details
1359
+ * @returns refund basket details
1360
+ */
1361
+ // getRefundBasketDetails(): Basket {
1362
+ // let basket: Basket = {
1363
+ // subsidiaryId : this.transactionDocument.subsidiaryId,
1364
+ // transactionDiscount: this.transactionDocument.basket.transactionDiscount,
1365
+ // transactionPromotion: this.transactionDocument.basket.transactionPromotion,
1366
+ // transactionId: this.transactionDocument.transactionId,
1367
+ // total: this.transactionDocument.basketSummary.basketTotal,
1368
+ // basketTotal: this.transactionDocument.basketSummary.basketTotal,
1369
+ // discountTotal: this.transactionDocument.basketSummary.discountTotal,
1370
+ // saleTotal: this.transactionDocument.basketSummary.saleTotal,
1371
+ // quantity: this.transactionDocument.basketSummary.totalItems,
1372
+ // products: [],
1373
+ // baseCurrency: this.transactionDocument.baseCurrency,
1374
+ // customer: this.transactionDocument.customer,
1375
+ // };
1376
+ // basket.products = [] as Product[];
1377
+ // this.transactionDocument.basket.products.forEach((product: { SKU: any; barCode: any; barcodes: any; description: any; imageUrls: any; totalLinePrice: any; itemLineId: any; excludePromotion: any; price: number; quantity: any; selectedRRPPrice: any; fullfilmentId: any; fullfilmentLocationName: any; deliveryGroup: string; leadTime: any; deliveryMethod: any; giftCard: any; giftCardExpiryDate: any; giftCardNumberIssued: any; giftCardRecipientEmail: any; giftCardRecipientName: any; itemDiscounts: any; refundedPromotionalQuantity: any; refundedQuantity: number; refunded: any; isLastExchanged: any; exchange: any; refundedTotal: number; }, index: any) => {
1378
+ // const p = {} as Product;
1379
+ // p.SKU = product.SKU;
1380
+ // p.barcode = product.barCode;
1381
+ // p.barcodes = product.barcodes;
1382
+ // p.description = product.description;
1383
+ // p.imageUrls = product.imageUrls;
1384
+ // p.currency = this.transactionDocument.baseCurrency;
1385
+ // p.totalLinePrice = product.totalLinePrice;
1386
+ // p.itemLineId = Number(product.itemLineId);
1387
+ // p.excludePromotion = product.excludePromotion;
1388
+ // p.selectedPrice = product.price;
1389
+ // p.quantity = product.quantity;
1390
+ // p.total = product.totalLinePrice;
1391
+ // p.selectedRRPPrice = product.selectedRRPPrice;
1392
+ // p.fullfilmentId = product.fullfilmentId;
1393
+ // p.fullfilmentLocationName = product.fullfilmentLocationName;
1394
+ // p.deliveryGroup = product.deliveryGroup || "1";
1395
+ // p.leadTime = product.leadTime;
1396
+ // p.deliveryMethod = product.deliveryMethod || DELIVERY_METHODS.COLLECT_FROM_STORE.toString();
1397
+ // p.giftCard = product.giftCard;
1398
+ // p.giftCardExpiryDate = product.giftCardExpiryDate;
1399
+ // p.giftCardNumberIssued = product.giftCardNumberIssued;
1400
+ // p.giftCardRecipientEmail = product.giftCardRecipientEmail;
1401
+ // p.giftCardRecipientName = product.giftCardRecipientName;
1402
+ // if(p.fullfilmentId != this.transactionDocument.storeId)
1403
+ // {
1404
+ // p.isWebOrder = true;
1405
+ // }
1406
+ // if (product.itemDiscounts) {
1407
+ // p.itemDiscounts = product.itemDiscounts as ItemDiscount;
1408
+ // }
1409
+ // // if(!p.itemDiscounts){
1410
+ // // console.log(p.itemDiscounts);
1411
+ // // this.basketService.transactionDiscountAndPromotionProductortionCalculation(basket);
1412
+ // // }
1413
+ // p.refundPromotionalQuantity = product.refundedPromotionalQuantity ? product.refundedPromotionalQuantity : 0;
1414
+ // if (product.refundedQuantity) {
1415
+ // p.quantity = p.quantity - product.refundedQuantity;
1416
+ // p.totalLinePrice = (p.quantity * product.price);
1417
+ // p.total = p.totalLinePrice;
1418
+ // // p.refundPromotionalQuantity = product.refundedPromotionalQuantity;
1419
+ // p.refunded = product.refunded;
1420
+ // p.isLastExchanged = product.isLastExchanged;
1421
+ // }
1422
+ // if (product.exchange) {
1423
+ // p.exchange = product.exchange;
1424
+ // }
1425
+ // if (
1426
+ // this.transactionDocument.basket.lineDiscount &&
1427
+ // this.transactionDocument.basket.lineDiscount.length > 0
1428
+ // ) {
1429
+ // this.transactionDocument.basket.lineDiscount.forEach((lineDiscount: { itemLineId: { toString: () => any; }; discountedLinePrice: any; }) => {
1430
+ // if (product.itemLineId === lineDiscount.itemLineId.toString() && product.refundedQuantity > 0) {
1431
+ // p.lineDiscount = Object.assign({}, lineDiscount);
1432
+ // p.lineDiscount.discountedLinePrice = p.lineDiscount.unitPrice * p.quantity
1433
+ // p.lineDiscount.discountAmount = p.total - p.lineDiscount.discountedLinePrice
1434
+ // p.total = p.lineDiscount.discountedLinePrice;
1435
+ // } else if (product.itemLineId === lineDiscount.itemLineId.toString()) {
1436
+ // p.lineDiscount = lineDiscount;
1437
+ // p.total = lineDiscount.discountedLinePrice
1438
+ // }
1439
+ // });
1440
+ // }
1441
+ // if (
1442
+ // this.transactionDocument.basket.linePromotion &&
1443
+ // this.transactionDocument.basket.linePromotion.length > 0
1444
+ // ) {
1445
+ // this.transactionDocument.basket.linePromotion.forEach((linePromotion: { itemLineId: { toString: () => any; }; refunded: any; }) => {
1446
+ // if (product.itemLineId === linePromotion.itemLineId.toString() && !linePromotion.refunded) {
1447
+ // p.linePromotions = linePromotion;
1448
+ // p.total = p.linePromotions.promotionLinePrice;
1449
+ // p.total = p.total - (product.refundedTotal ? Math.abs(product.refundedTotal) : 0);
1450
+ // }
1451
+ // });
1452
+ // }
1453
+ // p.refundedQuantity = 0;
1454
+ // p.refundedTotal = 0;
1455
+ // if (
1456
+ // this.transactionDocument.basket.taxBreakdown &&
1457
+ // this.transactionDocument.basket.taxBreakdown.taxLines.length > 0
1458
+ // ) {
1459
+ // this.transactionDocument.basket.taxBreakdown.taxLines.forEach((taxLine: { itemLineId: { toString: () => any; }; VAT: any; VATCode: any; }) => {
1460
+ // if (product.itemLineId === taxLine.itemLineId.toString()) {
1461
+ // p.selectedVAT = taxLine.VAT;
1462
+ // p.selectedVATCode = taxLine.VATCode;
1463
+ // }
1464
+ // });
1465
+ // }
1466
+ // if (p.quantity > 0) {
1467
+ // basket.products.push(p);
1468
+ // }
1469
+ // });
1470
+ // // product.itemDiscounts
1471
+ // if (!basket.products[0].hasOwnProperty('itemDiscounts')) {
1472
+ // basket = this.getTransactionDiscountAndTransactionPromotionPortion(basket);
1473
+ // }
1474
+ // console.log("ebasket : TransactionDocumentBuilder :new created refunded basket", JSON.stringify(basket))
1475
+ // basket.quantity = basket.products.reduce(
1476
+ // (n: any, { quantity }: any) => n + quantity,
1477
+ // 0
1478
+ // );
1479
+ // basket.total = this.getTotalWithLineDiscountAndLinePromotionApplied(basket);
1480
+ // basket.basketTotal = basket.total;
1481
+ // basket.basketTotal = basket.basketTotal - this.getTotalDiscountWithTransactionDiscountsAndPromotions(basket);
1482
+ // console.log(
1483
+ // "ebasket : TransactionDocumentBuilder : update Basket Total: after promotion :basketTotal",
1484
+ // basket.basketTotal
1485
+ // );
1486
+ // console.log(
1487
+ // "e:basket :TransactionDocumentBuilder : basketDetails updated values",
1488
+ // JSON.stringify(basket)
1489
+ // );
1490
+ // return basket;
1491
+ // }
1492
+ getTransactionDiscountAndTransactionPromotionPortion(basket) {
1493
+ if (basket.transactionDiscount &&
1494
+ basket.transactionDiscount.length > 0) {
1495
+ basket.transactionDiscount.forEach((discount) => {
1496
+ if (!discount.itemLineIds) {
1497
+ discount.itemLineIds = basket.products.map((product) => {
1498
+ return product.itemLineId;
1499
+ });
1500
+ }
1501
+ basket = this.basketService?.transactionDiscountProductPortionCalc(basket, discount);
1502
+ });
1503
+ }
1504
+ if (basket.transactionPromotion &&
1505
+ basket.transactionPromotion.length > 0) {
1506
+ basket.transactionPromotion.forEach((tPromotion) => {
1507
+ if (!tPromotion.itemLineIds) {
1508
+ const filteredData = basket.products.filter((item) => {
1509
+ return item.excludePromotion === false;
1510
+ });
1511
+ tPromotion.itemLineIds =
1512
+ filteredData.map((product) => {
1513
+ return product.itemLineId;
1514
+ });
1515
+ }
1516
+ basket = this.basketService?.transactionPromotionProductPortionCalc(basket, tPromotion);
1517
+ });
1518
+ }
1519
+ return basket;
1520
+ }
1521
+ getTotalDiscountWithTransactionDiscountsAndPromotions(basketDetails) {
1522
+ let discountTotal = 0;
1523
+ if (basketDetails.transactionPromotion &&
1524
+ basketDetails.transactionPromotion.length > 0) {
1525
+ discountTotal += basketDetails.transactionPromotion.reduce((n, { promotionAmount }) => n + promotionAmount, 0);
1526
+ }
1527
+ if (basketDetails.transactionDiscount &&
1528
+ basketDetails.transactionDiscount.length > 0) {
1529
+ discountTotal += basketDetails.transactionDiscount.reduce((n, { discountAmount }) => n + discountAmount, 0);
1530
+ }
1531
+ console.log("ebasket : TransactionDocumentBuilder : Transaction discount Total:", discountTotal);
1532
+ return discountTotal;
1533
+ }
1534
+ appendCurrencySymbol(currency, value) {
1535
+ // value=this.decimalpipe.transform(value,'1.2');
1536
+ if (value >= 0) {
1537
+ const returnval = currency + value;
1538
+ console.log(returnval, "ebasket: add currency with value");
1539
+ return returnval;
1540
+ }
1541
+ else {
1542
+ const returnval = "-" + (currency + value * -1);
1543
+ console.log(returnval, "-(currency+(value*-1))");
1544
+ return returnval;
1545
+ }
1546
+ }
1547
+ // /**
1548
+ // * Updates total refund
1549
+ // * @returns total refund
1550
+ // */
1551
+ // updateTotalRefund(): TransactionDocumentBuilder {
1552
+ // this.transactionDocument.basket.products.forEach((product) => {
1553
+ // product.refundedQuantity = product.quantity;
1554
+ // product.refundedTotal = product.totalLinePrice * -1;
1555
+ // console.log(
1556
+ // "ebasket: Transaction price override :",
1557
+ // this.transactionDocument.basket.lineDiscount
1558
+ // );
1559
+ // if (
1560
+ // this.transactionDocument.basket.linePromotion &&
1561
+ // this.transactionDocument.basket.linePromotion.length > 0
1562
+ // ) {
1563
+ // this.transactionDocument.basket.linePromotion.forEach((linePromotion) => {
1564
+ // console.log(
1565
+ // "Promotion: basket linePromotion : ",
1566
+ // this.transactionDocument.basket.linePromotion
1567
+ // );
1568
+ // console.log(
1569
+ // "linePromotion.itemLineId.toString() : ",
1570
+ // linePromotion.itemLineId.toString()
1571
+ // );
1572
+ // console.log(
1573
+ // "condition : " +
1574
+ // (product.itemLineId === linePromotion.itemLineId.toString())
1575
+ // );
1576
+ // if (product.itemLineId === linePromotion.itemLineId.toString()) {
1577
+ // product.refundedTotal =
1578
+ // linePromotion.promotionLinePrice * -1;
1579
+ // }
1580
+ // });
1581
+ // } else
1582
+ // if (
1583
+ // this.transactionDocument.basket.lineDiscount &&
1584
+ // this.transactionDocument.basket.lineDiscount.length > 0
1585
+ // ) {
1586
+ // this.transactionDocument.basket.lineDiscount.forEach((lineDiscount) => {
1587
+ // console.log(
1588
+ // "product.itemLineId : " +
1589
+ // this.transactionDocument.basket.lineDiscount
1590
+ // );
1591
+ // console.log(
1592
+ // "lineDiscount.itemLineId.toString() : " +
1593
+ // lineDiscount.itemLineId.toString()
1594
+ // );
1595
+ // console.log(
1596
+ // "condition : " +
1597
+ // (product.itemLineId === lineDiscount.itemLineId.toString())
1598
+ // );
1599
+ // if (product.itemLineId === lineDiscount.itemLineId.toString()) {
1600
+ // product.refundedTotal = lineDiscount.unitPrice * product.refundedQuantity * -1;
1601
+ // }
1602
+ // });
1603
+ // }
1604
+ // console.log("Product description :" + product.description);
1605
+ // console.log("Product total :" + product.refundedTotal);
1606
+ // // product.displayrefundedamount=this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency],product.refundedTotal);
1607
+ // // console.log(product.displayrefundedamount,"displayrefundedamount");
1608
+ // product.refunded = true;
1609
+ // });
1610
+ // const baskettotal = (this.transactionDocument.basketSummary.basketTotal *= -1);
1611
+ // // this.transactionDocument.basketSummary.displaybaskettotal=this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency], baskettotal);
1612
+ // const saletotal = (this.transactionDocument.basketSummary.saleTotal *= -1);
1613
+ // // this.transactionDocument.basketSummary.displaysaletotal = this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency], saletotal);
1614
+ // (this.transactionDocument.basketSummary.VATTotal *= -1);
1615
+ // return this;
1616
+ // }
1617
+ /**
1618
+ * Sale Total
1619
+ * @param basketDetails
1620
+ * @returns Sale Total
1621
+ */
1622
+ updateSaleTotal(basketDetails) {
1623
+ const saleTotal = basketDetails.products.reduce((n, { totalLinePrice }) => n + totalLinePrice, 0);
1624
+ return saleTotal;
1625
+ }
1626
+ getTotalWithLineDiscountAndLinePromotionApplied(basketDetails) {
1627
+ let saletotal = 0.0;
1628
+ for (let product of basketDetails.products) {
1629
+ // if (product.linePromotions) {
1630
+ // saletotal += product.linePromotions.promotionLinePrice;
1631
+ // } else if (
1632
+ // product.lineDiscount &&
1633
+ // !product.linePromotions
1634
+ // ) {
1635
+ // saletotal +=
1636
+ // product.quantity * Number(product.lineDiscount.unitPrice.toFixed(2));
1637
+ // } else {
1638
+ // saletotal +=
1639
+ // product.quantity * Number(product.selectedPrice.toFixed(2));
1640
+ // }
1641
+ saletotal += product.total;
1642
+ console.log("e-basket:update product Total:" + saletotal, JSON.stringify(product));
1643
+ }
1644
+ return saletotal;
1645
+ }
1646
+ getRefundedTotalWithQuantity(basketDetails) {
1647
+ let quantity = 0;
1648
+ for (let index = 0; index < basketDetails.products.length; index++) {
1649
+ const product = basketDetails.products[index];
1650
+ if (!product.refundedReasonDescription) {
1651
+ quantity = quantity + product.quantity;
1652
+ }
1653
+ else {
1654
+ quantity = quantity + (product.quantity - product.refundedQuantity);
1655
+ // basketDetails.total = basketDetails.total + product.refundedTotal;
1656
+ }
1657
+ }
1658
+ return quantity;
1659
+ }
1660
+ /**
1661
+ * Discount Total
1662
+ * @returns Discount Total
1663
+ */
1664
+ updateDiscountTotal() {
1665
+ let refundTotal = this.transactionDocument.basketSummary.refundTotal ? this.transactionDocument.basketSummary.refundTotal : 0;
1666
+ console.info("e-basket: transaction builder: refundTotal", JSON.stringify(refundTotal), JSON.stringify(this.transactionDocument.basketSummary));
1667
+ const discountTotal = Math.abs(Math.abs(this.transactionDocument.basketSummary.saleTotal) -
1668
+ (Math.abs(this.transactionDocument.basketSummary.basketTotal) + Math.abs(refundTotal)));
1669
+ console.log("e-basket: transaction builder: discountTotal", JSON.stringify(discountTotal));
1670
+ return Number(discountTotal.toFixed(2));
1671
+ }
1672
+ updateReasonCode(reasonCode) {
1673
+ this.transactionDocument.reasonCode = reasonCode.code;
1674
+ this.transactionDocument.reasonDescription = reasonCode.name;
1675
+ return this;
1676
+ }
1677
+ updateManagerOverride(useroverride) {
1678
+ this.transactionDocument.override = useroverride;
1679
+ return this;
1680
+ }
1681
+ updateUserID(userID) {
1682
+ this.transactionDocument.userId = userID;
1683
+ return this;
1684
+ }
1685
+ updateUserName(name) {
1686
+ this.transactionDocument.userName = name;
1687
+ return this;
1688
+ }
1689
+ addCustomerDetails(customerDetail) {
1690
+ this.transactionDocument.customer = customerDetail;
1691
+ return this;
1692
+ }
1693
+ updateTaxBreakdown(basketDetails) {
1694
+ // let transactionDiscountTotal = 0;
1695
+ let taxBreakdown = {
1696
+ taxLines: [],
1697
+ totalTaxableAmount: 0,
1698
+ };
1699
+ // if (this.transactionDocument.basket.transactionDiscount && this.transactionDocument.basket.transactionDiscount.length > 0) {
1700
+ // this.transactionDocument.basket.transactionDiscount.forEach((discount) => {
1701
+ // transactionDiscountTotal += discount.discountAmount;
1702
+ // });
1703
+ // }
1704
+ // if (this.transactionDocument.basket.transactionPromotion && this.transactionDocument.basket.transactionPromotion.length > 0) {
1705
+ // this.transactionDocument.basket.transactionPromotion.forEach(
1706
+ // (promotion) => {
1707
+ // transactionDiscountTotal += promotion.promotionAmount;
1708
+ // }
1709
+ // );
1710
+ // }
1711
+ basketDetails.products.forEach((product) => {
1712
+ let taxLine = {
1713
+ itemLineId: product.itemLineId,
1714
+ VAT: product.selectedVAT ? product.selectedVAT : 0,
1715
+ VATCode: product.selectedVATCode,
1716
+ taxLineTotal: 0,
1717
+ taxableAmount: product.total,
1718
+ PreTax: 0
1719
+ };
1720
+ console.info("Product contribution : item line ID :", product.itemLineId, "tax line :", JSON.stringify(taxLine));
1721
+ // step 1
1722
+ // if Transaction Discount and/or promotion applied, find net selling price of each product as taxableamount
1723
+ // if (transactionDiscountTotal > 0) {
1724
+ product = this.basketService?.validateProductItemDiscount(product);
1725
+ const productContributionInTotal = product.itemDiscounts.trnDiscountsPortion +
1726
+ product.itemDiscounts.trnPromotionsPortion -
1727
+ product.itemDiscounts.refundPortion;
1728
+ // tp+td-rp;
1729
+ console.info("Product contribution : item line ID :", product.itemLineId, "contribution :", JSON.stringify(productContributionInTotal));
1730
+ // calculate net selling price after applying transaction discount as per product contribution
1731
+ taxLine.taxableAmount -= productContributionInTotal;
1732
+ // }
1733
+ //step 2 - find pre tax
1734
+ taxLine.PreTax = this.numberUtilService.trimTo2Decimal2((taxLine.taxableAmount * 100) / (100 + taxLine.VAT));
1735
+ //step 3 - Update taxbreakdown
1736
+ taxBreakdown.totalTaxableAmount += taxLine.taxableAmount;
1737
+ taxLine.taxableAmount = this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount);
1738
+ // step 4 - update tax Line total
1739
+ taxLine.taxLineTotal = this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount - taxLine.PreTax);
1740
+ taxBreakdown.taxLines.push(taxLine);
1741
+ });
1742
+ taxBreakdown.totalTaxableAmount = this.numberUtilService.trimTo2Decimal2(taxBreakdown.totalTaxableAmount);
1743
+ this.transactionDocument.basket.taxBreakdown = taxBreakdown;
1744
+ return this;
1745
+ }
1746
+ updateTotalTaxSummary() {
1747
+ console.log("Total Tax Summery Request :", JSON.stringify(this.transactionDocument.basket.taxBreakdown));
1748
+ let totalTaxSummaryArray = [];
1749
+ let totalTaxSummaryGroup = [];
1750
+ console.log("Tax Lines for Total Tax Summery :", JSON.stringify(this.transactionDocument.basket.taxBreakdown.taxLines));
1751
+ this.transactionDocument.basket.taxBreakdown.taxLines.forEach((element) => {
1752
+ let TaxSummary = {
1753
+ VATCode: "",
1754
+ VAT: -12345,
1755
+ PreTaxSum: 0,
1756
+ TaxSum: 0,
1757
+ TXrateSum: 0
1758
+ };
1759
+ TaxSummary.VATCode = element.VATCode;
1760
+ TaxSummary.VAT = element.VAT;
1761
+ TaxSummary.PreTaxSum = this.numberUtilService.trimTo2Decimal2(element.PreTax);
1762
+ TaxSummary.TaxSum = this.numberUtilService.trimTo2Decimal2(element.taxLineTotal);
1763
+ TaxSummary.TXrateSum = this.numberUtilService.trimTo2Decimal2(TaxSummary.PreTaxSum + TaxSummary.TaxSum);
1764
+ totalTaxSummaryArray.push(TaxSummary);
1765
+ });
1766
+ console.log("Total Tax Summery Without Grouped : ", JSON.stringify(totalTaxSummaryArray));
1767
+ totalTaxSummaryGroup = totalTaxSummaryArray.reduce((preparedArray, currentObj) => {
1768
+ let ind = preparedArray.findIndex((x) => x.VAT === currentObj.VAT);
1769
+ if (ind === -1) {
1770
+ preparedArray.push(currentObj);
1771
+ }
1772
+ else {
1773
+ preparedArray[ind].VATCode = currentObj.VATCode;
1774
+ preparedArray[ind].VAT = currentObj.VAT;
1775
+ preparedArray[ind].PreTaxSum += currentObj.PreTaxSum;
1776
+ preparedArray[ind].TaxSum += currentObj.TaxSum;
1777
+ preparedArray[ind].TXrateSum += currentObj.TXrateSum;
1778
+ }
1779
+ return preparedArray;
1780
+ }, []);
1781
+ console.log("Total Tax Summer Group :", totalTaxSummaryGroup);
1782
+ this.transactionDocument.basket.totalTaxSummary = totalTaxSummaryGroup;
1783
+ return this;
1784
+ }
1785
+ /**
1786
+ * TransactionId
1787
+ * @returns OriginalTransactionId
1788
+ */
1789
+ addOriginalTransId(tranDoc) {
1790
+ if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND || this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND || this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
1791
+ this.transactionDocument.originalTransId = tranDoc.transactionId;
1792
+ if (tranDoc.apiResponse && tranDoc.apiResponse.internalId) {
1793
+ this.transactionDocument.originalExternalId = tranDoc.apiResponse.internalId.toString();
1794
+ }
1795
+ }
1796
+ return this;
1797
+ }
1798
+ /**
1799
+ * unreferenced Refund
1800
+ * @returns boolean value
1801
+ */
1802
+ addUnreferencedRefund() {
1803
+ this.transactionDocument.unreferencedRefund = true;
1804
+ return this;
1805
+ }
1806
+ getRefundTotal() {
1807
+ let totalRefund = 0;
1808
+ for (let index = 0; index < this.transactionDocument.basket.products.length; index++) {
1809
+ const product = this.transactionDocument.basket.products[index];
1810
+ if (product.refundedTotal) {
1811
+ totalRefund = totalRefund + product.refundedTotal;
1812
+ }
1813
+ console.log("ebasket : transaction Service: totalRefund" + totalRefund);
1814
+ }
1815
+ return totalRefund;
1816
+ }
1817
+ docId(docId) {
1818
+ this.transactionDocument.id = docId;
1819
+ return this;
1820
+ }
1821
+ }
1822
+
1823
+ class RJMapperBuilderClass {
1824
+ constructor(transactionDoc) {
1825
+ this.productQuantity = 0;
1826
+ this.itemCount = 0;
1827
+ this.largestNumber = 0;
1828
+ this.rjObject = {};
1829
+ this.paymentTypes = [
1830
+ {
1831
+ paymentType: 'Card',
1832
+ type: 'SEPAY',
1833
+ tenderType: '5',
1834
+ tenderSubType: '8',
1835
+ },
1836
+ {
1837
+ paymentType: 'Cash',
1838
+ type: 'TMC_CASH',
1839
+ tenderType: '1',
1840
+ tenderSubType: '0'
1841
+ },
1842
+ {
1843
+ paymentType: 'PDQ',
1844
+ type: 'Unintegrated',
1845
+ tenderType: '2',
1846
+ tenderSubType: '8'
1847
+ },
1848
+ {
1849
+ paymentType: 'Gift Card',
1850
+ type: 'TMC_GIFTCARD',
1851
+ tenderType: '5',
1852
+ tenderSubType: '8'
1853
+ }
1854
+ ];
1855
+ if (transactionDoc) {
1856
+ this.transactionDocument = transactionDoc;
1857
+ }
1858
+ else {
1859
+ this.transactionDocument = {
1860
+ transactionId: "",
1861
+ offlineTransactionId: "",
1862
+ transactionRef: "",
1863
+ dateTime: "",
1864
+ orgCode: "",
1865
+ storeId: "",
1866
+ storeNodeId: "",
1867
+ storeNodeStructure: "",
1868
+ deviceId: "",
1869
+ terminalId: "",
1870
+ userId: "",
1871
+ initiatingModule: "eBasket",
1872
+ export: false,
1873
+ basket: {},
1874
+ basketSummary: {},
1875
+ baseCurrency: "",
1876
+ type: "",
1877
+ operationStatus: "",
1878
+ createdAt: "",
1879
+ updatedAt: "",
1880
+ id: "",
1881
+ currentTransactionDetails: {},
1882
+ saleTotal: 0,
1883
+ };
1884
+ }
1885
+ this.initilizeItemCount();
1886
+ this.setLineNumberForProducts();
1887
+ }
1888
+ getPosbasketInfo() {
1889
+ this.rjObject['Keyword'] = this.generateKeyword();
1890
+ this.rjObject['ID'] = this.generateId(this.transactionDocument.createdAt);
1891
+ this.rjObject['XMLSchemaVersion'] = '2';
1892
+ this.rjObject['LastUpdated'] = this.transactionDocument.updatedAt;
1893
+ this.rjObject['MajorVersion'] = this.majorVersion;
1894
+ this.rjObject['MinorVersion'] = this.minorVersion;
1895
+ this.rjObject['ManifestVersion'] = this.manifestVersion;
1896
+ this.rjObject['DatabaseSchemaVersion'] = this.databaseSchemaVersion;
1897
+ this.rjObject['BasketType'] = this.basketType;
1898
+ this.rjObject['State'] = this.getState();
1899
+ this.rjObject['ExternalState'] = this.externalState;
1900
+ return this;
1901
+ }
1902
+ getheaderInfo() {
1903
+ this.rjObject['Header'] = {};
1904
+ this.rjObject['Header'].TimeZoneOffset = this.convertToString(this.generateTimezoneoffset(this.transactionDocument.createdAt));
1905
+ this.rjObject['Header'].DateTimeCreated = this.transactionDocument.createdAt;
1906
+ this.rjObject['Header'].OriginatedBy = {};
1907
+ this.rjObject['Header'].OriginatedBy.DeviceID = this.deviceId;
1908
+ this.rjObject['Header'].OriginatedBy.CashierID = this.cashierId;
1909
+ this.rjObject['Header'].OriginatedBy.CompanyID = this.companyId;
1910
+ this.rjObject['Header'].OriginatedBy.StoreID = this.transactionDocument.storeId;
1911
+ this.rjObject['Header'].OriginatedBy.BranchID = this.transactionDocument.storeId;
1912
+ this.rjObject['Header'].OriginatedBy.TerminalNumber = this.terminalNumber;
1913
+ this.rjObject['Header'].OriginatedBy.TransactionNumber = this.transactionNumber;
1914
+ this.rjObject['Header'].TaxMethodID = this.taxMethodId;
1915
+ this.rjObject['Header'].DynamicStockLookup = this.generateDynamicStockLookUp(); //todo
1916
+ this.rjObject['Header'].BasketLanguageID = this.basketLanguageId; //todo
1917
+ this.rjObject['Header'].BasketCountryID = this.basketCountryId; //todo
1918
+ this.rjObject['Header'].BasketCurrencyID = this.transactionDocument.baseCurrency;
1919
+ this.rjObject['Header'].TradingRegionID = this.tradingRegionId;
1920
+ this.rjObject['Header'].Eurozone = " "; //unknown
1921
+ this.rjObject['Header'].EuroBaseExchangeRate = ""; //unknown
1922
+ this.rjObject['Header'].PrintableName = ""; //unknown
1923
+ return this;
1924
+ }
1925
+ rjMapper() {
1926
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE) {
1927
+ this.rjObject['ProductSale'] = [];
1928
+ this.rjObject['ModifierItem'] = [];
1929
+ this.transactionDocument.basket.products.forEach((element) => {
1930
+ let lineDiscount = [];
1931
+ if (this.transactionDocument.basket.lineDiscount && this.transactionDocument.basket.lineDiscount.length > 0) {
1932
+ lineDiscount = this.transactionDocument.basket.lineDiscount.filter((x) => x.itemLineId === element.itemLineId);
1933
+ if (lineDiscount.length > 0) {
1934
+ const index = this.transactionDocument.basket.lineDiscount.indexOf(lineDiscount[0]);
1935
+ if (index > -1) {
1936
+ this.transactionDocument.basket.lineDiscount.splice(index, 1);
1937
+ }
1938
+ }
1939
+ }
1940
+ let data = this.addProduct(element, (lineDiscount.length > 0 ? lineDiscount[0] : null));
1941
+ this.rjObject['ProductSale'].push(data);
1942
+ this.getModifierItem(lineDiscount.length > 0 ? lineDiscount[0] : null, element.itemLineId);
1943
+ });
1944
+ }
1945
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
1946
+ this.rjObject['ProductReturn'] = [];
1947
+ this.rjObject['ModifierItem'] = [];
1948
+ this.transactionDocument.basket.products.forEach((element) => {
1949
+ let data = this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null));
1950
+ this.rjObject['ProductReturn'].push(data);
1951
+ this.getModifierItem(element.lineDiscount, element.itemLineId);
1952
+ });
1953
+ }
1954
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND) {
1955
+ this.rjObject['ProductReturn'] = [];
1956
+ this.rjObject['ModifierItem'] = [];
1957
+ let transactionDoc = new TransactionDocumentBuilder().basket(this.transactionDocument.currentTransactionDetails).build();
1958
+ transactionDoc.basket.products.forEach((element) => {
1959
+ let data = this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null));
1960
+ this.rjObject['ProductReturn'].push(data);
1961
+ this.getModifierItem(element.lineDiscount, element.itemLineId);
1962
+ });
1963
+ }
1964
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
1965
+ this.rjObject['ProductReturn'] = [];
1966
+ this.rjObject['ProductSale'] = [];
1967
+ this.rjObject['ModifierItem'] = [];
1968
+ let transactionDoc = new TransactionDocumentBuilder().basket(this.transactionDocument.currentTransactionDetails).build();
1969
+ transactionDoc.basket.products.forEach((element) => {
1970
+ if (element.refundedQuantity > 0) {
1971
+ let returnProduct = this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null));
1972
+ this.rjObject['ProductReturn'].push(returnProduct);
1973
+ }
1974
+ else {
1975
+ let addProduct = this.addProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null));
1976
+ this.rjObject['ProductSale'].push(addProduct);
1977
+ }
1978
+ this.getModifierItem(element.lineDiscount, element.itemLineId);
1979
+ });
1980
+ }
1981
+ return this;
1982
+ }
1983
+ getBasketDiscount() {
1984
+ this.rjObject['BasketDiscount'] = [];
1985
+ if (!this.transactionDocument.basket.transactionDiscount)
1986
+ return this;
1987
+ this.transactionDocument.basket.transactionDiscount.forEach((element) => {
1988
+ let obj = {};
1989
+ obj['XMLSchemaVersion'] = 1;
1990
+ obj['NetValue'] = element.discountAmount < 0 ? element.discountAmount : -element.discountAmount;
1991
+ obj['EffectiveNetValue'] = element.discountAmount < 0 ? element.discountAmount : -element.discountAmount;
1992
+ obj['Description'] = element.reasonCode;
1993
+ obj['UserID'] = this.transactionDocument.basket.userId;
1994
+ obj['ReasonCodeID'] = element.reasonCode;
1995
+ obj['DiscountType'] = element.discountType.toUpperCase() == DISCOUNTTYPE.PERCENT.toUpperCase() ? 0 : 1; // todo - compare values
1996
+ obj['RoundingRule'] = 2;
1997
+ obj['ModifiedLineNumber '] = [];
1998
+ element.itemLineIds.forEach((element) => {
1999
+ obj['ModifiedLineNumber'].push(element);
2000
+ });
2001
+ obj['LineNumber'] = this.generateLineNumber();
2002
+ // obj['DiscountedValue'] = obj['discountAmount'] // todo - confirm value before discount;
2003
+ // obj['DiscountPercentage'] = obj['discountAmount'] / 100 ; // todo - optional
2004
+ this.rjObject['BasketDiscount'].push(obj);
2005
+ });
2006
+ return this;
2007
+ }
2008
+ getModifierItem(data, lineNo) {
2009
+ if (data && lineNo) {
2010
+ let obj = {};
2011
+ obj.XMLSchemaVersion = 1;
2012
+ obj.LineNumber = this.generateLineNumber();
2013
+ obj.NetValue = 0;
2014
+ obj.EffectiveNetValue = 0;
2015
+ obj.Description = data.percentageDiscountReasonName ? data.percentageDiscountReasonName : data.priceOverrideReasonName;
2016
+ obj.DeviceID = this.deviceId;
2017
+ obj.UserID = this.userId;
2018
+ obj.DateTimeCreated = this.transactionDocument.updatedAt;
2019
+ obj.AuthorisingUserID = this.userId;
2020
+ obj.ReasonCodeID = data.percentageDiscountReasonCode ? data.percentageDiscountReasonCode : data.priceOverrideReasonCode;
2021
+ obj.ModifiedLineNumber = lineNo;
2022
+ obj.ModifiedIndex = 1;
2023
+ this.rjObject['ModifierItem'].push(obj);
2024
+ }
2025
+ }
2026
+ getTrailerInfo() {
2027
+ this.rjObject['Trailer'] = {};
2028
+ this.rjObject.Trailer.DateTimeCompleted = this.transactionDocument.updatedAt;
2029
+ this.rjObject.Trailer.CompletedBy = {};
2030
+ this.rjObject.Trailer.CompletedBy.DeviceID = this.deviceId; //todo
2031
+ this.rjObject.Trailer.CompletedBy.CashierID = this.cashierId; //todo
2032
+ this.rjObject.Trailer.CompletedBy.StoreID = this.transactionDocument.storeId;
2033
+ this.rjObject.Trailer.CompletedBy.BranchID = this.transactionDocument.storeId;
2034
+ this.rjObject.Trailer.CompletedBy.TerminalNumber = this.transactionDocument.terminalId;
2035
+ this.rjObject.Trailer.Total = this.convertToString(this.transactionDocument.basketSummary.basketTotal * 100);
2036
+ this.rjObject.Trailer.ItemCount = this.itemCount; //gives total count for product
2037
+ this.rjObject.Trailer.ItemQuantity = this.convertToString(this.transactionDocument.basketSummary.totalItems);
2038
+ this.rjObject.Trailer.NetItemQuantity = this.convertToString(this.transactionDocument.basketSummary.totalItems);
2039
+ this.rjObject.Trailer.TaxTotal = this.convertToString(this.transactionDocument.basketSummary.VATTotal);
2040
+ this.rjObject.Trailer.SequenceDeviceID = this.deviceId;
2041
+ this.rjObject.Trailer.SequenceNumber = 'snsn'; //static for now
2042
+ this.rjObject['Trailer']['TaxItem'] = [];
2043
+ this.transactionDocument.basket.taxBreakdown.taxLines.forEach((element) => {
2044
+ let obj = {};
2045
+ obj['XMLSchemaVersion'] = this.xmlSchemaVersion;
2046
+ obj['TaxRate'] = element.VAT;
2047
+ obj['TaxableTotal'] = this.convertToString(element.taxableAmount);
2048
+ obj['TaxTotal'] = this.convertToString(element.taxLineTotal);
2049
+ obj['TaxDescription'] = this.convertToString(element.VATCode);
2050
+ obj['TaxIncluded'] = '1';
2051
+ obj['TaxPercentage'] = element.VAT; // todo
2052
+ this.rjObject['Trailer']['TaxItem'].push(obj);
2053
+ });
2054
+ // TODO: make Trailer object from promotion
2055
+ this.rjObject['Trailer']['PromotionItem'] = [];
2056
+ this.transactionDocument.basket.linePromotion.forEach((element) => {
2057
+ let obj = {};
2058
+ obj['PromotionID'] = element.promotionId;
2059
+ obj['PromotionSaving'] = element.promotionAmount < 0 ? element.promotionAmount : -element.promotionAmount;
2060
+ obj['PromotionQuantity'] = ""; // todo - not avaialble
2061
+ obj['PromotionDescription'] = element.displayText;
2062
+ obj['PromotionHit']['XMLSchemaVersion'] = this.transactionDocument.storeId;
2063
+ obj['PromotionHit']['HitNumber'] = ""; // todo;
2064
+ obj['PromotionHit']['HitQuantity'] = ""; // todo;
2065
+ obj['PromotionHit']['HitSaving'] = ""; // todo;
2066
+ obj['PromotionHit']['PromotionTrigger'] = [];
2067
+ element.trigger.forEach((subElement) => {
2068
+ let objSub = {};
2069
+ let product = this.transactionDocument.basket.products.find((item) => item.lineItemId == subElement.itemLineId);
2070
+ objSub['XMLSchemaVersion'] = this.xmlSchemaVersion;
2071
+ objSub['ProductID'] = this.transactionDocument.basket.products.find((item) => item.itemLineId === subElement.itemLineId).SKU;
2072
+ objSub['UnitValue'] = this.convertToString(element.promotionLinePrice / product.quantity);
2073
+ objSub['LineNumber'] = this.convertToString(subElement.itemLineId);
2074
+ objSub['Quantity'] = this.convertToString(subElement.quantity.toFixed(1));
2075
+ objSub['TaxCode'] = this.transactionDocument.basket.taxBreakdown.taxLines.find((item) => item.itemLineId == element.itemLineId).VATCode; // todo
2076
+ obj['PromotionHit']['PromotionTrigger'].push(objSub);
2077
+ });
2078
+ this.rjObject['Trailer']['PromotionItem'].push(obj);
2079
+ });
2080
+ //console.log(this.rjObject);
2081
+ return this;
2082
+ }
2083
+ getTenderInfo() {
2084
+ this.rjObject['CashTender'] = [];
2085
+ if (this.transactionDocument.paymentDetails && this.transactionDocument.paymentDetails.length > 0) {
2086
+ this.transactionDocument.paymentDetails.forEach((element) => {
2087
+ let value = this.paymentTypes.filter(x => x.paymentType?.toUpperCase() === element.paymentType.toUpperCase());
2088
+ if (element.paymentType.toUpperCase() === 'GIFT CARD') {
2089
+ let obj = {
2090
+ XMLSchemaVersion: this.xmlSchemaVersion,
2091
+ LineNumber: this.generateLineNumber(),
2092
+ NetValue: this.convertToString(-1 * (Math.round(element.amount))),
2093
+ EffectiveNetValue: this.convertToString(-1 * (Math.round(element.amount))),
2094
+ Description: this.getDescription(value[0].paymentType, element),
2095
+ DeviceID: this.deviceId,
2096
+ UserID: this.userId,
2097
+ DateTimeCreated: this.transactionDocument.updatedAt,
2098
+ TenderType: value[0].tenderType,
2099
+ TenderSubType: value[0].tenderSubType,
2100
+ TenderAmount: this.convertToString(-1 * (Math.round(element.amount))),
2101
+ CurrencyID: this.transactionDocument.baseCurrency,
2102
+ CurrencyDescription: this.transactionDocument.baseCurrency,
2103
+ GiftVoucherSalesAllowed: '',
2104
+ AllowRechargeableVoucherSales: '',
2105
+ GiftVoucherID: ''
2106
+ };
2107
+ this.rjObject['CashTender'].push(obj);
2108
+ }
2109
+ else {
2110
+ let obj1 = {
2111
+ XMLSchemaVersion: "1",
2112
+ LineNumber: this.generateLineNumber(),
2113
+ NetValue: JSON.stringify(-1 * (Math.round(element.amount))),
2114
+ EffectiveNetValue: JSON.stringify(-1 * (Math.round(element.amount))),
2115
+ Description: this.getDescription(value[0].paymentType, element),
2116
+ DeviceID: this.deviceId,
2117
+ UserID: this.userId,
2118
+ DateTimeCreated: this.transactionDocument.updatedAt,
2119
+ TenderType: value[0].tenderType,
2120
+ TenderSubType: value[0].tenderSubType,
2121
+ TenderAmount: JSON.stringify(-1 * (Math.round(element.amount))),
2122
+ CurrencyID: this.transactionDocument.baseCurrency,
2123
+ CurrencyDescription: this.transactionDocument.baseCurrency,
2124
+ IncludeInTransactionTotalCheck: "1",
2125
+ AllowRechargeableVoucherSales: "1",
2126
+ OpenDrawerAtEnd: "1"
2127
+ };
2128
+ this.rjObject['CashTender'].push(obj1);
2129
+ }
2130
+ });
2131
+ }
2132
+ return this;
2133
+ }
2134
+ setLineNumberForProducts() {
2135
+ let itemLineIdArray = [];
2136
+ itemLineIdArray = this.transactionDocument.basket.products.map((product) => {
2137
+ return parseInt(product.itemLineId);
2138
+ });
2139
+ this.largestNumber = itemLineIdArray.reduce((a, b) => Math.max(a, b));
2140
+ }
2141
+ generateLineNumber() {
2142
+ this.largestNumber += 1;
2143
+ this.itemCount += 1;
2144
+ return this.largestNumber;
2145
+ }
2146
+ initilizeItemCount() {
2147
+ this.itemCount = this.transactionDocument.basket.products.length;
2148
+ }
2149
+ build() {
2150
+ return this.rjObject;
2151
+ }
2152
+ getDescription(paymentType, element) {
2153
+ if (paymentType.toUpperCase() === 'CARD') {
2154
+ return element.cardType;
2155
+ }
2156
+ else {
2157
+ return paymentType;
2158
+ }
2159
+ }
2160
+ setDeviceInfo(id) {
2161
+ this.deviceId = id;
2162
+ return this;
2163
+ }
2164
+ setUserInfo(id) {
2165
+ this.userId = id;
2166
+ return this;
2167
+ }
2168
+ removeDecimal(value) {
2169
+ return value * 100;
2170
+ }
2171
+ setTransactionNumber(value) {
2172
+ this.transactionNumber = value;
2173
+ return this;
2174
+ }
2175
+ setManifestVersion(value) {
2176
+ this.manifestVersion = value;
2177
+ return this;
2178
+ }
2179
+ setDatabaseSchemaVersion(value) {
2180
+ this.databaseSchemaVersion = value;
2181
+ return this;
2182
+ }
2183
+ setBasketType(value) {
2184
+ this.basketType = value;
2185
+ return this;
2186
+ }
2187
+ setTradingRegionID(value) {
2188
+ this.tradingRegionId = value;
2189
+ return this;
2190
+ }
2191
+ setCompanyID(value) {
2192
+ this.companyId = value;
2193
+ return this;
2194
+ }
2195
+ setTaxMethodID(value) {
2196
+ this.taxMethodId = value;
2197
+ return this;
2198
+ }
2199
+ setMajorVersion(value) {
2200
+ this.majorVersion = value;
2201
+ return this;
2202
+ }
2203
+ setMinorVersion(value) {
2204
+ this.minorVersion = value;
2205
+ return this;
2206
+ }
2207
+ setXMLSchemaVersion(value) {
2208
+ this.xmlSchemaVersion = value;
2209
+ return this;
2210
+ }
2211
+ setExternalState(value) {
2212
+ this.externalState = value;
2213
+ return this;
2214
+ }
2215
+ setCashierID(value) {
2216
+ this.cashierId = value;
2217
+ return this;
2218
+ }
2219
+ setTerminalNumber(value) {
2220
+ this.terminalNumber = value;
2221
+ return this;
2222
+ }
2223
+ setBasketLanguageID(value) {
2224
+ this.basketLanguageId = value;
2225
+ return this;
2226
+ }
2227
+ setBasketCountryID(value) {
2228
+ this.basketCountryId = value;
2229
+ return this;
2230
+ }
2231
+ setBasketCurrencyID(value) {
2232
+ this.basketCurrencyId = value;
2233
+ return this;
2234
+ }
2235
+ generateId(date) {
2236
+ let newDateTime = date.replace(/[^0-9]/g, '');
2237
+ let id = (this.deviceId + '|' + newDateTime + '|' + this.transactionNumber).toString();
2238
+ return id;
2239
+ }
2240
+ generateTimezoneoffset(date) {
2241
+ let x = date ? date : '';
2242
+ return new Date(x).getTimezoneOffset();
2243
+ }
2244
+ generateKeyword() {
2245
+ let x = (this.companyId + '|' + this.transactionDocument.storeId + '|' + this.terminalNumber + '|' + this.transactionNumber).toString();
2246
+ return x;
2247
+ }
2248
+ getState() {
2249
+ if (this.transactionDocument.operationStatus === 'PAY_SUCCESS') {
2250
+ return 'Completed';
2251
+ }
2252
+ else {
2253
+ return 'Cancelled';
2254
+ }
2255
+ }
2256
+ returnProduct(element, lineDiscount) {
2257
+ let obj = {};
2258
+ obj['LineNumber'] = element['itemLineId'];
2259
+ obj['NetValue'] = this.removeDecimal(element['refundedTotal']);
2260
+ obj['EffectiveNetValue'] = this.removeDecimal(element['refundedTotal']);
2261
+ obj['Description'] = element['description'];
2262
+ obj['DeviceID'] = this.transactionDocument['terminalId'];
2263
+ obj['UserID'] = this.userId;
2264
+ obj['DateTimeCreated'] = this.transactionDocument['createdAt'];
2265
+ obj['ExtendedValue'] = this.removeDecimal(element['totalLinePrice']);
2266
+ obj['UnitPrice'] = this.removeDecimal(element['price']);
2267
+ obj['Quantity'] = element['refundedQuantity'] < 0 ? element['refundedQuantity'].toFixed(1) : -element['refundedQuantity'].toFixed(1);
2268
+ obj['OriginalTaxAmountSet'] = 1;
2269
+ obj['ProductID'] = element['SKU'];
2270
+ obj['HandKeyed'] = 1;
2271
+ obj['LongDescription'] = element['description'];
2272
+ obj['Return'] = {};
2273
+ obj['Return']['ReturnReasonID'] = element['refundedReason'];
2274
+ obj['Return']['ReturnDescription'] = element['refundedReasonDescription'];
2275
+ obj['Return']['ReturnToStock'] = element['refundedQuantity'] > 0 ? element['refundedQuantity'] : -1 * element['refundedQuantity'];
2276
+ obj['TaxCode'] = this.transactionDocument.basket['taxBreakdown']['taxLines'].find((item) => item.itemLineId == element['itemLineId']).VATCode;
2277
+ obj['DisplayTaxCode'] = ''; // todo
2278
+ obj['ProductAttributes'] = ''; //todo - not required
2279
+ obj['Perishable'] = this.getAttributes();
2280
+ obj['MMGroupID'] = this.getAttributes();
2281
+ obj['CustomerDetails'] = ""; // todo - blank
2282
+ obj['TotalPromotionSaving'] = element['promotionAmount'] || -1; // TODO
2283
+ let taxTotal = this.transactionDocument.basket['taxBreakdown']['taxLines'].find((item) => item.itemLineId == element['itemLineId']);
2284
+ obj['OriginalTaxAmount'] = taxTotal.taxLineTotal < 0 ? this.removeDecimal(taxTotal.taxLineTotal) : this.removeDecimal(-taxTotal.taxLineTotal); //todo
2285
+ obj['taxAmount'] = taxTotal.taxLineTotal < 0 ? this.removeDecimal(taxTotal.taxLineTotal) : this.removeDecimal(-taxTotal.taxLineTotal);
2286
+ if (lineDiscount) {
2287
+ if (lineDiscount.percentageDiscountReasonName && lineDiscount.percentageDiscountReasonCode) {
2288
+ // line discount
2289
+ obj['Discount'] = {};
2290
+ obj['Discount'].ModifierValue = this.removeDecimal(lineDiscount.unitPrice) * -1;
2291
+ obj['Discount'].ModifierDateTime = obj.DateTimeCreated;
2292
+ obj['Discount'].ModifierReasonID = lineDiscount.percentageDiscountReasonCode;
2293
+ obj['Discount'].ModifierDescription = lineDiscount.percentageDiscountReasonName;
2294
+ obj['Discount'].AuthorisingUserID = this.userId;
2295
+ obj['Discount'].DiscountType = lineDiscount.discountType;
2296
+ obj['Discount'].XMLSchemaVersion = 1;
2297
+ obj['Discount'].OriginalPrice = this.removeDecimal(lineDiscount.discountAmount + (lineDiscount.discountedLinePrice || 0));
2298
+ obj['Discount'].DiscountedValue = this.removeDecimal(lineDiscount.unitPrice);
2299
+ obj['Discount'].DiscountPercentage = lineDiscount.percentageDiscountValue;
2300
+ obj['Discount'].RoundingRule = 2;
2301
+ }
2302
+ if (lineDiscount.priceOverrideReasonCode && lineDiscount.priceOverrideReasonName) {
2303
+ //price override
2304
+ obj['PriceOverride'] = {};
2305
+ obj['PriceOverride'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
2306
+ obj['PriceOverride'].ModifierDateTime = obj.DateTimeCreated;
2307
+ obj['PriceOverride'].ModifierReasonID = lineDiscount.priceOverrideReasonCode;
2308
+ obj['PriceOverride'].ModifierReasonDescription = lineDiscount.priceOverrideReasonName;
2309
+ obj['PriceOverride'].AuthorisingUserID = this.userId;
2310
+ obj['PriceOverride'].XMLSchemaVersion = 1;
2311
+ obj['PriceOverride'].NewPrice = this.removeDecimal(lineDiscount.unitPrice);
2312
+ obj['PriceOverride'].OriginalPrice = this.removeDecimal(lineDiscount.discountedLinePrice || 0 + lineDiscount.discountAmount);
2313
+ }
2314
+ //update the product price
2315
+ obj.NetValue = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
2316
+ obj.EffectiveNetValue = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
2317
+ obj.ExtendedValue = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
2318
+ obj.UnitPrice = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
2319
+ }
2320
+ return obj;
2321
+ }
2322
+ addProduct(element, lineDiscount) {
2323
+ let obj = {
2324
+ XMLSchemaVersion: this.xmlSchemaVersion,
2325
+ LineNumber: element.itemLineId,
2326
+ NetValue: this.removeDecimal(element.totalLinePrice),
2327
+ EffectiveNetValue: this.removeDecimal(element.totalLinePrice),
2328
+ Description: element.description,
2329
+ DeviceID: this.deviceId,
2330
+ UserID: this.userId,
2331
+ DateTimeCreated: this.transactionDocument.createdAt,
2332
+ ExtendedValue: this.removeDecimal(element.price),
2333
+ UnitPrice: this.removeDecimal(element.price),
2334
+ MMGroupID: this.getAttributes(),
2335
+ Quantity: element.quantity.toFixed(1),
2336
+ SalespersonID: this.transactionDocument.userId,
2337
+ SalespersonName: this.transactionDocument.userName,
2338
+ TaxCode: 0,
2339
+ TaxModifiable: 1,
2340
+ TaxAmount: 0,
2341
+ OriginalTaxAmount: 0,
2342
+ OriginalTaxAmountSet: 1,
2343
+ ProductID: element.SKU,
2344
+ HandKeyed: 1,
2345
+ CustomerDetails: "",
2346
+ Perishable: this.getAttributes()
2347
+ };
2348
+ if (lineDiscount) {
2349
+ if (lineDiscount.percentageDiscountReasonName && lineDiscount.percentageDiscountReasonCode) {
2350
+ // line discount
2351
+ obj['Discount'] = {};
2352
+ obj['Discount'].ModifierValue = this.removeDecimal(lineDiscount.unitPrice) * -1;
2353
+ obj['Discount'].ModifierDateTime = obj.DateTimeCreated;
2354
+ obj['Discount'].ModifierReasonID = lineDiscount.percentageDiscountReasonCode;
2355
+ obj['Discount'].ModifierDescription = lineDiscount.percentageDiscountReasonName;
2356
+ obj['Discount'].AuthorisingUserID = this.userId;
2357
+ obj['Discount'].DiscountType = lineDiscount.discountType;
2358
+ obj['Discount'].XMLSchemaVersion = 1;
2359
+ obj['Discount'].OriginalPrice = this.removeDecimal(lineDiscount.discountAmount + (lineDiscount.discountedLinePrice || 0));
2360
+ obj['Discount'].DiscountedValue = this.removeDecimal(lineDiscount.unitPrice);
2361
+ obj['Discount'].DiscountPercentage = lineDiscount.percentageDiscountValue;
2362
+ obj['Discount'].RoundingRule = 2;
2363
+ }
2364
+ if (lineDiscount.priceOverrideReasonCode && lineDiscount.priceOverrideReasonName) {
2365
+ //price override
2366
+ obj['PriceOverride'] = {};
2367
+ obj['PriceOverride'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
2368
+ obj['PriceOverride'].ModifierDateTime = obj.DateTimeCreated;
2369
+ obj['PriceOverride'].ModifierReasonID = lineDiscount.priceOverrideReasonCode;
2370
+ obj['PriceOverride'].ModifierReasonDescription = lineDiscount.priceOverrideReasonName;
2371
+ obj['PriceOverride'].AuthorisingUserID = this.userId;
2372
+ obj['PriceOverride'].XMLSchemaVersion = 1;
2373
+ obj['PriceOverride'].NewPrice = this.removeDecimal(lineDiscount.unitPrice);
2374
+ obj['PriceOverride'].OriginalPrice = this.removeDecimal(lineDiscount.discountedLinePrice || 0 + lineDiscount.discountAmount);
2375
+ }
2376
+ //update the product price
2377
+ obj['NetValue'] = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount);
2378
+ obj['EffectiveNetValue'] = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount);
2379
+ obj['ExtendedValue'] = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount);
2380
+ obj['UnitPrice'] = ((lineDiscount?.discountedLinePrice || 0) + lineDiscount.discountAmount);
2381
+ }
2382
+ return obj;
2383
+ }
2384
+ convertToString(value) {
2385
+ try {
2386
+ value = JSON.stringify(value);
2387
+ return value;
2388
+ }
2389
+ catch (e) {
2390
+ console.log(value, ' can not be converted in string', e);
2391
+ }
2392
+ }
2393
+ generateDynamicStockLookUp() {
2394
+ let x = '0';
2395
+ this.transactionDocument.basket.products.forEach((element) => {
2396
+ if (element.deliveryMethod === '1' || element.deliveryMethod === '2') {
2397
+ x = '1';
2398
+ }
2399
+ });
2400
+ return x;
2401
+ }
2402
+ getAttributes() {
2403
+ let name = [];
2404
+ this.transactionDocument.basket.products.forEach((element) => {
2405
+ if (element.attributes && element.attributes.length > 0) {
2406
+ name = element.attributes.filter((x) => x.name.toUpperCase() === element.name?.toUpperCase());
2407
+ }
2408
+ });
2409
+ if (name.length > 0) {
2410
+ return name[0].value;
2411
+ }
2412
+ else {
2413
+ return "";
2414
+ }
2415
+ }
2416
+ }
2417
+
2418
+ class MapperLibraryService {
2419
+ constructor() { }
2420
+ saleDoc(transactionDoc) {
2421
+ console.log('TransactionDocuments', transactionDoc);
2422
+ let value = new RJMapperBuilderClass(transactionDoc)
2423
+ .setTransactionNumber('tttt')
2424
+ .setManifestVersion('mmmm')
2425
+ .setDatabaseSchemaVersion('dddd')
2426
+ .setTradingRegionID('trtr')
2427
+ .setCompanyID('cccc')
2428
+ .setTaxMethodID('tmtm')
2429
+ .setBasketType('SALE')
2430
+ .setMajorVersion('1')
2431
+ .setMinorVersion('0')
2432
+ .setXMLSchemaVersion('1')
2433
+ .setExternalState('1')
2434
+ .setCashierID('0009')
2435
+ .setTerminalNumber('1')
2436
+ .setUserInfo('123')
2437
+ .setDeviceInfo('XYZ.ab.123')
2438
+ .setBasketLanguageID('IT')
2439
+ .setBasketCountryID('IT')
2440
+ .setBasketCurrencyID('EUR')
2441
+ .rjMapper()
2442
+ .getBasketDiscount()
2443
+ .getPosbasketInfo()
2444
+ .getheaderInfo()
2445
+ .getTrailerInfo()
2446
+ .getTenderInfo()
2447
+ .build();
2448
+ console.log('JSONobject', value);
2449
+ console.log('XML', JsonToXML.parse("POSBasket", value));
2450
+ return JsonToXML.parse("POSBasket", value);
2451
+ }
2452
+ refundDoc(transactionDoc) {
2453
+ console.log('TransactionDocument', transactionDoc);
2454
+ let value = new RJMapperBuilderClass(transactionDoc)
2455
+ .rjMapper()
2456
+ .getTrailerInfo()
2457
+ .build();
2458
+ console.log('JSONobject', value);
2459
+ }
2460
+ }
2461
+ MapperLibraryService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2462
+ MapperLibraryService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryService, providedIn: 'root' });
2463
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryService, decorators: [{
2464
+ type: Injectable,
2465
+ args: [{
2466
+ providedIn: 'root'
2467
+ }]
2468
+ }], ctorParameters: function () { return []; } });
2469
+
2470
+ class MapperLibraryComponent {
2471
+ constructor() { }
2472
+ ngOnInit() {
2473
+ }
2474
+ }
2475
+ MapperLibraryComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
2476
+ MapperLibraryComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.3.11", type: MapperLibraryComponent, selector: "lib-mapper-library", ngImport: i0, template: `
2477
+ <p>
2478
+ mapper-library works!
2479
+ </p>
2480
+ `, isInline: true });
2481
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryComponent, decorators: [{
2482
+ type: Component,
2483
+ args: [{
2484
+ selector: 'lib-mapper-library',
2485
+ template: `
2486
+ <p>
2487
+ mapper-library works!
2488
+ </p>
2489
+ `,
2490
+ styles: []
2491
+ }]
2492
+ }], ctorParameters: function () { return []; } });
2493
+
2494
+ class MapperLibraryModule {
2495
+ }
2496
+ MapperLibraryModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2497
+ MapperLibraryModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryModule, declarations: [MapperLibraryComponent], exports: [MapperLibraryComponent] });
2498
+ MapperLibraryModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryModule, imports: [[]] });
2499
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.11", ngImport: i0, type: MapperLibraryModule, decorators: [{
2500
+ type: NgModule,
2501
+ args: [{
2502
+ declarations: [
2503
+ MapperLibraryComponent
2504
+ ],
2505
+ imports: [],
2506
+ exports: [
2507
+ MapperLibraryComponent
2508
+ ]
2509
+ }]
2510
+ }] });
2511
+
2512
+ /*
2513
+ * Public API Surface of mapper-library
2514
+ */
2515
+
2516
+ /**
2517
+ * Generated bundle index. Do not edit.
2518
+ */
2519
+
2520
+ export { MapperLibraryComponent, MapperLibraryModule, MapperLibraryService, RJMapperBuilderClass };
2521
+ //# sourceMappingURL=pmcretail-mapper-library.mjs.map