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