@pmcretail/mapper-library 0.0.43 → 0.0.45

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.
Files changed (39) hide show
  1. package/bundles/pmcretail-mapper-library.umd.js +4165 -0
  2. package/bundles/pmcretail-mapper-library.umd.js.map +1 -0
  3. package/esm2015/lib/RJ-mapper.class.js +877 -0
  4. package/esm2015/lib/TransactionDocumentBuilder.js +1244 -0
  5. package/esm2015/lib/WebReturn-mapper.class.js +326 -0
  6. package/esm2015/lib/WebReturnSalesforceMapper.class.js +409 -0
  7. package/esm2015/lib/basket.service.js +527 -0
  8. package/esm2015/lib/mapper-library.component.js +26 -0
  9. package/esm2015/lib/mapper-library.module.js +21 -0
  10. package/esm2015/lib/number-util.service.js +42 -0
  11. package/{fesm2022/pmcretail-mapper-library.mjs → fesm2015/pmcretail-mapper-library.js} +173 -154
  12. package/fesm2015/pmcretail-mapper-library.js.map +1 -0
  13. package/lib/RJ-mapper.class.d.ts +1 -0
  14. package/lib/RJ-mapper.class.d.ts.map +1 -1
  15. package/lib/TransactionDocumentBuilder.d.ts +1 -0
  16. package/lib/TransactionDocumentBuilder.d.ts.map +1 -1
  17. package/lib/WebReturn-mapper.class.d.ts +1 -0
  18. package/lib/WebReturn-mapper.class.d.ts.map +1 -1
  19. package/lib/WebReturnSalesforceMapper.class.d.ts +1 -0
  20. package/lib/WebReturnSalesforceMapper.class.d.ts.map +1 -1
  21. package/lib/basket.service.d.ts +1 -0
  22. package/lib/basket.service.d.ts.map +1 -1
  23. package/lib/mapper-library.component.d.ts +1 -1
  24. package/lib/number-util.service.d.ts +1 -0
  25. package/lib/number-util.service.d.ts.map +1 -1
  26. package/package.json +9 -16
  27. package/esm2022/lib/RJ-mapper.class.mjs +0 -875
  28. package/esm2022/lib/TransactionDocumentBuilder.mjs +0 -1240
  29. package/esm2022/lib/WebReturn-mapper.class.mjs +0 -324
  30. package/esm2022/lib/WebReturnSalesforceMapper.class.mjs +0 -410
  31. package/esm2022/lib/basket.service.mjs +0 -516
  32. package/esm2022/lib/mapper-library.component.mjs +0 -22
  33. package/esm2022/lib/mapper-library.module.mjs +0 -21
  34. package/esm2022/lib/number-util.service.mjs +0 -40
  35. package/fesm2022/pmcretail-mapper-library.mjs.map +0 -1
  36. /package/{esm2022/lib/mapper-library.model.mjs → esm2015/lib/mapper-library.model.js} +0 -0
  37. /package/{esm2022/pmcretail-mapper-library.mjs → esm2015/pmcretail-mapper-library.js} +0 -0
  38. /package/{esm2022/public-api.mjs → esm2015/public-api.js} +0 -0
  39. /package/{index.d.ts → pmcretail-mapper-library.d.ts} +0 -0
@@ -0,0 +1,4165 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs'), require('@pmcretail/common-services/common/app-logger.service'), require('@angular/common')) :
3
+ typeof define === 'function' && define.amd ? define('@pmcretail/mapper-library', ['exports', '@angular/core', 'rxjs', '@pmcretail/common-services/common/app-logger.service', '@angular/common'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.pmcretail = global.pmcretail || {}, global.pmcretail["mapper-library"] = {}), global.ng.core, global.rxjs, global.appLogger_service, global.ng.common));
5
+ })(this, (function (exports, i0, rxjs, appLogger_service, i1) { 'use strict';
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n["default"] = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var i0__namespace = /*#__PURE__*/_interopNamespace(i0);
26
+ var i1__namespace = /*#__PURE__*/_interopNamespace(i1);
27
+
28
+ var MapperLibraryComponent = /** @class */ (function () {
29
+ function MapperLibraryComponent() {
30
+ }
31
+ MapperLibraryComponent.prototype.ngOnInit = function () {
32
+ };
33
+ return MapperLibraryComponent;
34
+ }());
35
+ MapperLibraryComponent.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryComponent, deps: [], target: i0__namespace.ɵɵFactoryTarget.Component });
36
+ MapperLibraryComponent.ɵcmp = i0__namespace.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.17", type: MapperLibraryComponent, selector: "lib-mapper-library", ngImport: i0__namespace, template: "\n <p>\n mapper-library works!\n </p>\n ", isInline: true });
37
+ i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryComponent, decorators: [{
38
+ type: i0.Component,
39
+ args: [{
40
+ selector: 'lib-mapper-library',
41
+ template: "\n <p>\n mapper-library works!\n </p>\n ",
42
+ styles: []
43
+ }]
44
+ }], ctorParameters: function () { return []; } });
45
+
46
+ var MapperLibraryModule = /** @class */ (function () {
47
+ function MapperLibraryModule() {
48
+ }
49
+ return MapperLibraryModule;
50
+ }());
51
+ MapperLibraryModule.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryModule, deps: [], target: i0__namespace.ɵɵFactoryTarget.NgModule });
52
+ MapperLibraryModule.ɵmod = i0__namespace.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryModule, declarations: [MapperLibraryComponent], exports: [MapperLibraryComponent] });
53
+ MapperLibraryModule.ɵinj = i0__namespace.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryModule, imports: [[]] });
54
+ i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: MapperLibraryModule, decorators: [{
55
+ type: i0.NgModule,
56
+ args: [{
57
+ declarations: [
58
+ MapperLibraryComponent
59
+ ],
60
+ imports: [],
61
+ exports: [
62
+ MapperLibraryComponent
63
+ ]
64
+ }]
65
+ }] });
66
+
67
+ var TRANSACTION_TYPE;
68
+ (function (TRANSACTION_TYPE) {
69
+ TRANSACTION_TYPE["SALE"] = "SALE";
70
+ TRANSACTION_TYPE["REFUND"] = "REFUND";
71
+ TRANSACTION_TYPE["SALE_REFUND"] = "SALE_REFUND";
72
+ TRANSACTION_TYPE["SALE_EXCHANGE"] = "SALE_EXCHANGE";
73
+ TRANSACTION_TYPE["VOID"] = "VOID";
74
+ TRANSACTION_TYPE["WEB_RETURNS"] = "WEB_RETURNS";
75
+ })(TRANSACTION_TYPE || (TRANSACTION_TYPE = {}));
76
+ var DELIVERY_METHODS;
77
+ (function (DELIVERY_METHODS) {
78
+ DELIVERY_METHODS[DELIVERY_METHODS["DELIVERY"] = 1] = "DELIVERY";
79
+ DELIVERY_METHODS[DELIVERY_METHODS["DROP_SHIP"] = 2] = "DROP_SHIP";
80
+ DELIVERY_METHODS[DELIVERY_METHODS["COLLECT_FROM_STORE"] = 3] = "COLLECT_FROM_STORE";
81
+ DELIVERY_METHODS[DELIVERY_METHODS["SHIP_TO_STORE"] = 4] = "SHIP_TO_STORE";
82
+ })(DELIVERY_METHODS || (DELIVERY_METHODS = {}));
83
+ var DISCOUNTTYPE;
84
+ (function (DISCOUNTTYPE) {
85
+ DISCOUNTTYPE["PERCENT"] = "Percent";
86
+ DISCOUNTTYPE["AMOUNT"] = "AMOUNT";
87
+ })(DISCOUNTTYPE || (DISCOUNTTYPE = {}));
88
+ var INITIATING_MODULE;
89
+ (function (INITIATING_MODULE) {
90
+ INITIATING_MODULE["EBASKET"] = "eBasket";
91
+ })(INITIATING_MODULE || (INITIATING_MODULE = {}));
92
+ var PROVIDERS;
93
+ (function (PROVIDERS) {
94
+ PROVIDERS["SALESFORCE"] = "Salesforce";
95
+ })(PROVIDERS || (PROVIDERS = {}));
96
+ var PROMOTION_LEVEL;
97
+ (function (PROMOTION_LEVEL) {
98
+ PROMOTION_LEVEL["LINE"] = "LINE";
99
+ PROMOTION_LEVEL["TRANSACTION"] = "TRANSACTION";
100
+ })(PROMOTION_LEVEL || (PROMOTION_LEVEL = {}));
101
+ var PROMOTION_TYPE;
102
+ (function (PROMOTION_TYPE) {
103
+ PROMOTION_TYPE["COUPON"] = "COUPON";
104
+ })(PROMOTION_TYPE || (PROMOTION_TYPE = {}));
105
+
106
+ /******************************************************************************
107
+ Copyright (c) Microsoft Corporation.
108
+
109
+ Permission to use, copy, modify, and/or distribute this software for any
110
+ purpose with or without fee is hereby granted.
111
+
112
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
113
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
114
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
115
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
116
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
117
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
118
+ PERFORMANCE OF THIS SOFTWARE.
119
+ ***************************************************************************** */
120
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
121
+ var extendStatics = function (d, b) {
122
+ extendStatics = Object.setPrototypeOf ||
123
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
124
+ function (d, b) { for (var p in b)
125
+ if (Object.prototype.hasOwnProperty.call(b, p))
126
+ d[p] = b[p]; };
127
+ return extendStatics(d, b);
128
+ };
129
+ function __extends(d, b) {
130
+ if (typeof b !== "function" && b !== null)
131
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
132
+ extendStatics(d, b);
133
+ function __() { this.constructor = d; }
134
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
135
+ }
136
+ var __assign = function () {
137
+ __assign = Object.assign || function __assign(t) {
138
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
139
+ s = arguments[i];
140
+ for (var p in s)
141
+ if (Object.prototype.hasOwnProperty.call(s, p))
142
+ t[p] = s[p];
143
+ }
144
+ return t;
145
+ };
146
+ return __assign.apply(this, arguments);
147
+ };
148
+ function __rest(s, e) {
149
+ var t = {};
150
+ for (var p in s)
151
+ if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
152
+ t[p] = s[p];
153
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
154
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
155
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
156
+ t[p[i]] = s[p[i]];
157
+ }
158
+ return t;
159
+ }
160
+ function __decorate(decorators, target, key, desc) {
161
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
162
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
163
+ r = Reflect.decorate(decorators, target, key, desc);
164
+ else
165
+ for (var i = decorators.length - 1; i >= 0; i--)
166
+ if (d = decorators[i])
167
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
168
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
169
+ }
170
+ function __param(paramIndex, decorator) {
171
+ return function (target, key) { decorator(target, key, paramIndex); };
172
+ }
173
+ function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
174
+ function accept(f) { if (f !== void 0 && typeof f !== "function")
175
+ throw new TypeError("Function expected"); return f; }
176
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
177
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
178
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
179
+ var _, done = false;
180
+ for (var i = decorators.length - 1; i >= 0; i--) {
181
+ var context = {};
182
+ for (var p in contextIn)
183
+ context[p] = p === "access" ? {} : contextIn[p];
184
+ for (var p in contextIn.access)
185
+ context.access[p] = contextIn.access[p];
186
+ context.addInitializer = function (f) { if (done)
187
+ throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
188
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
189
+ if (kind === "accessor") {
190
+ if (result === void 0)
191
+ continue;
192
+ if (result === null || typeof result !== "object")
193
+ throw new TypeError("Object expected");
194
+ if (_ = accept(result.get))
195
+ descriptor.get = _;
196
+ if (_ = accept(result.set))
197
+ descriptor.set = _;
198
+ if (_ = accept(result.init))
199
+ initializers.unshift(_);
200
+ }
201
+ else if (_ = accept(result)) {
202
+ if (kind === "field")
203
+ initializers.unshift(_);
204
+ else
205
+ descriptor[key] = _;
206
+ }
207
+ }
208
+ if (target)
209
+ Object.defineProperty(target, contextIn.name, descriptor);
210
+ done = true;
211
+ }
212
+ ;
213
+ function __runInitializers(thisArg, initializers, value) {
214
+ var useValue = arguments.length > 2;
215
+ for (var i = 0; i < initializers.length; i++) {
216
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
217
+ }
218
+ return useValue ? value : void 0;
219
+ }
220
+ ;
221
+ function __propKey(x) {
222
+ return typeof x === "symbol" ? x : "".concat(x);
223
+ }
224
+ ;
225
+ function __setFunctionName(f, name, prefix) {
226
+ if (typeof name === "symbol")
227
+ name = name.description ? "[".concat(name.description, "]") : "";
228
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
229
+ }
230
+ ;
231
+ function __metadata(metadataKey, metadataValue) {
232
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
233
+ return Reflect.metadata(metadataKey, metadataValue);
234
+ }
235
+ function __awaiter(thisArg, _arguments, P, generator) {
236
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
237
+ return new (P || (P = Promise))(function (resolve, reject) {
238
+ function fulfilled(value) { try {
239
+ step(generator.next(value));
240
+ }
241
+ catch (e) {
242
+ reject(e);
243
+ } }
244
+ function rejected(value) { try {
245
+ step(generator["throw"](value));
246
+ }
247
+ catch (e) {
248
+ reject(e);
249
+ } }
250
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
251
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
252
+ });
253
+ }
254
+ function __generator(thisArg, body) {
255
+ var _ = { label: 0, sent: function () { if (t[0] & 1)
256
+ throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
257
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
258
+ function verb(n) { return function (v) { return step([n, v]); }; }
259
+ function step(op) {
260
+ if (f)
261
+ throw new TypeError("Generator is already executing.");
262
+ while (g && (g = 0, op[0] && (_ = 0)), _)
263
+ try {
264
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
265
+ return t;
266
+ if (y = 0, t)
267
+ op = [op[0] & 2, t.value];
268
+ switch (op[0]) {
269
+ case 0:
270
+ case 1:
271
+ t = op;
272
+ break;
273
+ case 4:
274
+ _.label++;
275
+ return { value: op[1], done: false };
276
+ case 5:
277
+ _.label++;
278
+ y = op[1];
279
+ op = [0];
280
+ continue;
281
+ case 7:
282
+ op = _.ops.pop();
283
+ _.trys.pop();
284
+ continue;
285
+ default:
286
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
287
+ _ = 0;
288
+ continue;
289
+ }
290
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
291
+ _.label = op[1];
292
+ break;
293
+ }
294
+ if (op[0] === 6 && _.label < t[1]) {
295
+ _.label = t[1];
296
+ t = op;
297
+ break;
298
+ }
299
+ if (t && _.label < t[2]) {
300
+ _.label = t[2];
301
+ _.ops.push(op);
302
+ break;
303
+ }
304
+ if (t[2])
305
+ _.ops.pop();
306
+ _.trys.pop();
307
+ continue;
308
+ }
309
+ op = body.call(thisArg, _);
310
+ }
311
+ catch (e) {
312
+ op = [6, e];
313
+ y = 0;
314
+ }
315
+ finally {
316
+ f = t = 0;
317
+ }
318
+ if (op[0] & 5)
319
+ throw op[1];
320
+ return { value: op[0] ? op[1] : void 0, done: true };
321
+ }
322
+ }
323
+ var __createBinding = Object.create ? (function (o, m, k, k2) {
324
+ if (k2 === undefined)
325
+ k2 = k;
326
+ var desc = Object.getOwnPropertyDescriptor(m, k);
327
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
328
+ desc = { enumerable: true, get: function () { return m[k]; } };
329
+ }
330
+ Object.defineProperty(o, k2, desc);
331
+ }) : (function (o, m, k, k2) {
332
+ if (k2 === undefined)
333
+ k2 = k;
334
+ o[k2] = m[k];
335
+ });
336
+ function __exportStar(m, o) {
337
+ for (var p in m)
338
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
339
+ __createBinding(o, m, p);
340
+ }
341
+ function __values(o) {
342
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
343
+ if (m)
344
+ return m.call(o);
345
+ if (o && typeof o.length === "number")
346
+ return {
347
+ next: function () {
348
+ if (o && i >= o.length)
349
+ o = void 0;
350
+ return { value: o && o[i++], done: !o };
351
+ }
352
+ };
353
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
354
+ }
355
+ function __read(o, n) {
356
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
357
+ if (!m)
358
+ return o;
359
+ var i = m.call(o), r, ar = [], e;
360
+ try {
361
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
362
+ ar.push(r.value);
363
+ }
364
+ catch (error) {
365
+ e = { error: error };
366
+ }
367
+ finally {
368
+ try {
369
+ if (r && !r.done && (m = i["return"]))
370
+ m.call(i);
371
+ }
372
+ finally {
373
+ if (e)
374
+ throw e.error;
375
+ }
376
+ }
377
+ return ar;
378
+ }
379
+ /** @deprecated */
380
+ function __spread() {
381
+ for (var ar = [], i = 0; i < arguments.length; i++)
382
+ ar = ar.concat(__read(arguments[i]));
383
+ return ar;
384
+ }
385
+ /** @deprecated */
386
+ function __spreadArrays() {
387
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++)
388
+ s += arguments[i].length;
389
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
390
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
391
+ r[k] = a[j];
392
+ return r;
393
+ }
394
+ function __spreadArray(to, from, pack) {
395
+ if (pack || arguments.length === 2)
396
+ for (var i = 0, l = from.length, ar; i < l; i++) {
397
+ if (ar || !(i in from)) {
398
+ if (!ar)
399
+ ar = Array.prototype.slice.call(from, 0, i);
400
+ ar[i] = from[i];
401
+ }
402
+ }
403
+ return to.concat(ar || Array.prototype.slice.call(from));
404
+ }
405
+ function __await(v) {
406
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
407
+ }
408
+ function __asyncGenerator(thisArg, _arguments, generator) {
409
+ if (!Symbol.asyncIterator)
410
+ throw new TypeError("Symbol.asyncIterator is not defined.");
411
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
412
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
413
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
414
+ function verb(n, f) { if (g[n]) {
415
+ i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
416
+ if (f)
417
+ i[n] = f(i[n]);
418
+ } }
419
+ function resume(n, v) { try {
420
+ step(g[n](v));
421
+ }
422
+ catch (e) {
423
+ settle(q[0][3], e);
424
+ } }
425
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
426
+ function fulfill(value) { resume("next", value); }
427
+ function reject(value) { resume("throw", value); }
428
+ function settle(f, v) { if (f(v), q.shift(), q.length)
429
+ resume(q[0][0], q[0][1]); }
430
+ }
431
+ function __asyncDelegator(o) {
432
+ var i, p;
433
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
434
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
435
+ }
436
+ function __asyncValues(o) {
437
+ if (!Symbol.asyncIterator)
438
+ throw new TypeError("Symbol.asyncIterator is not defined.");
439
+ var m = o[Symbol.asyncIterator], i;
440
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
441
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
442
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
443
+ }
444
+ function __makeTemplateObject(cooked, raw) {
445
+ if (Object.defineProperty) {
446
+ Object.defineProperty(cooked, "raw", { value: raw });
447
+ }
448
+ else {
449
+ cooked.raw = raw;
450
+ }
451
+ return cooked;
452
+ }
453
+ ;
454
+ var __setModuleDefault = Object.create ? (function (o, v) {
455
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
456
+ }) : function (o, v) {
457
+ o["default"] = v;
458
+ };
459
+ var ownKeys = function (o) {
460
+ ownKeys = Object.getOwnPropertyNames || function (o) {
461
+ var ar = [];
462
+ for (var k in o)
463
+ if (Object.prototype.hasOwnProperty.call(o, k))
464
+ ar[ar.length] = k;
465
+ return ar;
466
+ };
467
+ return ownKeys(o);
468
+ };
469
+ function __importStar(mod) {
470
+ if (mod && mod.__esModule)
471
+ return mod;
472
+ var result = {};
473
+ if (mod != null)
474
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++)
475
+ if (k[i] !== "default")
476
+ __createBinding(result, mod, k[i]);
477
+ __setModuleDefault(result, mod);
478
+ return result;
479
+ }
480
+ function __importDefault(mod) {
481
+ return (mod && mod.__esModule) ? mod : { default: mod };
482
+ }
483
+ function __classPrivateFieldGet(receiver, state, kind, f) {
484
+ if (kind === "a" && !f)
485
+ throw new TypeError("Private accessor was defined without a getter");
486
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
487
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
488
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
489
+ }
490
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
491
+ if (kind === "m")
492
+ throw new TypeError("Private method is not writable");
493
+ if (kind === "a" && !f)
494
+ throw new TypeError("Private accessor was defined without a setter");
495
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
496
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
497
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
498
+ }
499
+ function __classPrivateFieldIn(state, receiver) {
500
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
501
+ throw new TypeError("Cannot use 'in' operator on non-object");
502
+ return typeof state === "function" ? receiver === state : state.has(receiver);
503
+ }
504
+ function __addDisposableResource(env, value, async) {
505
+ if (value !== null && value !== void 0) {
506
+ if (typeof value !== "object" && typeof value !== "function")
507
+ throw new TypeError("Object expected.");
508
+ var dispose, inner;
509
+ if (async) {
510
+ if (!Symbol.asyncDispose)
511
+ throw new TypeError("Symbol.asyncDispose is not defined.");
512
+ dispose = value[Symbol.asyncDispose];
513
+ }
514
+ if (dispose === void 0) {
515
+ if (!Symbol.dispose)
516
+ throw new TypeError("Symbol.dispose is not defined.");
517
+ dispose = value[Symbol.dispose];
518
+ if (async)
519
+ inner = dispose;
520
+ }
521
+ if (typeof dispose !== "function")
522
+ throw new TypeError("Object not disposable.");
523
+ if (inner)
524
+ dispose = function () { try {
525
+ inner.call(this);
526
+ }
527
+ catch (e) {
528
+ return Promise.reject(e);
529
+ } };
530
+ env.stack.push({ value: value, dispose: dispose, async: async });
531
+ }
532
+ else if (async) {
533
+ env.stack.push({ async: true });
534
+ }
535
+ return value;
536
+ }
537
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
538
+ var e = new Error(message);
539
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
540
+ };
541
+ function __disposeResources(env) {
542
+ function fail(e) {
543
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
544
+ env.hasError = true;
545
+ }
546
+ var r, s = 0;
547
+ function next() {
548
+ while (r = env.stack.pop()) {
549
+ try {
550
+ if (!r.async && s === 1)
551
+ return s = 0, env.stack.push(r), Promise.resolve().then(next);
552
+ if (r.dispose) {
553
+ var result = r.dispose.call(r.value);
554
+ if (r.async)
555
+ return s |= 2, Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
556
+ }
557
+ else
558
+ s |= 1;
559
+ }
560
+ catch (e) {
561
+ fail(e);
562
+ }
563
+ }
564
+ if (s === 1)
565
+ return env.hasError ? Promise.reject(env.error) : Promise.resolve();
566
+ if (env.hasError)
567
+ throw env.error;
568
+ }
569
+ return next();
570
+ }
571
+ function __rewriteRelativeImportExtension(path, preserveJsx) {
572
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
573
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
574
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
575
+ });
576
+ }
577
+ return path;
578
+ }
579
+ var tslib_es6 = {
580
+ __extends: __extends,
581
+ __assign: __assign,
582
+ __rest: __rest,
583
+ __decorate: __decorate,
584
+ __param: __param,
585
+ __esDecorate: __esDecorate,
586
+ __runInitializers: __runInitializers,
587
+ __propKey: __propKey,
588
+ __setFunctionName: __setFunctionName,
589
+ __metadata: __metadata,
590
+ __awaiter: __awaiter,
591
+ __generator: __generator,
592
+ __createBinding: __createBinding,
593
+ __exportStar: __exportStar,
594
+ __values: __values,
595
+ __read: __read,
596
+ __spread: __spread,
597
+ __spreadArrays: __spreadArrays,
598
+ __spreadArray: __spreadArray,
599
+ __await: __await,
600
+ __asyncGenerator: __asyncGenerator,
601
+ __asyncDelegator: __asyncDelegator,
602
+ __asyncValues: __asyncValues,
603
+ __makeTemplateObject: __makeTemplateObject,
604
+ __importStar: __importStar,
605
+ __importDefault: __importDefault,
606
+ __classPrivateFieldGet: __classPrivateFieldGet,
607
+ __classPrivateFieldSet: __classPrivateFieldSet,
608
+ __classPrivateFieldIn: __classPrivateFieldIn,
609
+ __addDisposableResource: __addDisposableResource,
610
+ __disposeResources: __disposeResources,
611
+ __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
612
+ };
613
+
614
+ var BasketService = /** @class */ (function () {
615
+ function BasketService(numberUtilService) {
616
+ this.numberUtilService = numberUtilService;
617
+ this.currentBasket = {
618
+ products: [],
619
+ transactionDiscount: [],
620
+ quantity: 0,
621
+ total: 0,
622
+ saleTotal: 0,
623
+ baseCurrency: ''
624
+ };
625
+ this.basketSource = new rxjs.BehaviorSubject(null);
626
+ this.basket = this.basketSource.asObservable();
627
+ this.productSource = new rxjs.BehaviorSubject(null);
628
+ this.product = this.productSource.asObservable();
629
+ this.peerSource = new rxjs.BehaviorSubject(false);
630
+ this.peerSync = this.peerSource.asObservable();
631
+ this.scanSource = new rxjs.BehaviorSubject(false);
632
+ this.scanner = this.scanSource.asObservable();
633
+ this.className = "BasketService";
634
+ }
635
+ Object.defineProperty(BasketService.prototype, "isMixedBasketSales", {
636
+ get: function () {
637
+ return this._isMixedBasketSales;
638
+ },
639
+ set: function (v) {
640
+ this._isMixedBasketSales = v;
641
+ },
642
+ enumerable: false,
643
+ configurable: true
644
+ });
645
+ BasketService.prototype.updateBasket = function (basket) {
646
+ this.currentBasket = basket;
647
+ this.isMixedBasketSales = this.filterProductListWithWebOrder(true).length > 0;
648
+ this.basketSource.next(basket);
649
+ };
650
+ /**
651
+ * calculates the total basket value and quantity
652
+ * @param null
653
+ * @returns void
654
+ */
655
+ BasketService.prototype.updateBasketTotal = function (basketDetails, basketState) {
656
+ var e_1, _a;
657
+ basketDetails.quantity = 0;
658
+ basketDetails.total = 0;
659
+ try {
660
+ for (var _b = __values(basketDetails.products), _c = _b.next(); !_c.done; _c = _b.next()) {
661
+ var p = _c.value;
662
+ basketDetails.quantity = basketDetails.quantity + p.quantity;
663
+ basketDetails.total =
664
+ this.numberUtilService.trimTo2Decimal(basketDetails.total) +
665
+ this.numberUtilService.trimTo2Decimal(p.total);
666
+ }
667
+ }
668
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
669
+ finally {
670
+ try {
671
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
672
+ }
673
+ finally { if (e_1) throw e_1.error; }
674
+ }
675
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketTotal", "basketDetails updated values for transaction id\n " + basketDetails.transactionId + ", basketDetails\n " + JSON.stringify(basketDetails));
676
+ basketDetails.basketTotal = basketDetails.total;
677
+ basketState.updateBasket(basketDetails);
678
+ };
679
+ /**
680
+ * add Line promotion
681
+ * @param null
682
+ * @returns basketDetails
683
+ */
684
+ BasketService.prototype.addlinePromotion = function (promotionList, basketDetails) {
685
+ var e_2, _a, e_3, _b;
686
+ appLogger_service.AppLoggerService.logDebug(this.className, "addlinePromotion", "promotionList " + JSON.stringify(promotionList) + " and \n basketDetails\n " + JSON.stringify(basketDetails) + " for linePromotions");
687
+ if (promotionList &&
688
+ promotionList.result &&
689
+ promotionList.result.linePromotions &&
690
+ promotionList.result.linePromotions.length > 0) {
691
+ try {
692
+ for (var _c = __values(basketDetails.products), _d = _c.next(); !_d.done; _d = _c.next()) {
693
+ var element = _d.value;
694
+ try {
695
+ for (var _e = (e_3 = void 0, __values(promotionList.result.linePromotions)), _f = _e.next(); !_f.done; _f = _e.next()) {
696
+ var promotionelement = _f.value;
697
+ if (element.itemLineId.toString() ===
698
+ promotionelement.itemLineId.toString()) {
699
+ element.linePromotions = promotionelement;
700
+ }
701
+ }
702
+ }
703
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
704
+ finally {
705
+ try {
706
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
707
+ }
708
+ finally { if (e_3) throw e_3.error; }
709
+ }
710
+ }
711
+ }
712
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
713
+ finally {
714
+ try {
715
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
716
+ }
717
+ finally { if (e_2) throw e_2.error; }
718
+ }
719
+ }
720
+ return basketDetails;
721
+ };
722
+ /**
723
+ * add Transaction promotion
724
+ * @param null
725
+ * @returns basketDetails
726
+ */
727
+ BasketService.prototype.addTransactionPromotion = function (promotionList, basketdetails) {
728
+ var _this = this;
729
+ appLogger_service.AppLoggerService.logDebug(this.className, "addTransactionPromotion", "promotionList " + JSON.stringify(promotionList) + " and \n basketDetails\n " + JSON.stringify(basketdetails) + " for transactionPromotions " + JSON.stringify(basketdetails.transactionPromotion));
730
+ if (promotionList &&
731
+ promotionList.result &&
732
+ promotionList.result.transactionPromotion &&
733
+ promotionList.result.transactionPromotion.length > 0) {
734
+ promotionList.result.transactionPromotion.forEach(function (tPromotion) {
735
+ var transactionPromotionEntryUpdated = Object.assign({}, tPromotion);
736
+ transactionPromotionEntryUpdated.itemLineIds = basketdetails.products.map(function (product) {
737
+ return product.itemLineId;
738
+ });
739
+ if (!basketdetails.transactionPromotion) {
740
+ basketdetails.transactionPromotion = [];
741
+ }
742
+ basketdetails.transactionPromotion.push(transactionPromotionEntryUpdated);
743
+ basketdetails = _this.transactionPromotionProductPortionCalc(basketdetails, transactionPromotionEntryUpdated);
744
+ });
745
+ }
746
+ appLogger_service.AppLoggerService.logDebug(this.className, "addTransactionPromotion", "basket details in refund calculation file", basketdetails);
747
+ return basketdetails;
748
+ };
749
+ BasketService.prototype.updateProductTotalForSummary = function (basketDetails) {
750
+ var e_4, _a;
751
+ /*sale- product refundedQuantity = undefined
752
+ partial refund - product refundedQuantity is > 0
753
+ total refund - proudct refundedQuantity is > 0
754
+ exchange - exchange product refundedQuantity is > 0
755
+ new product refundedQuantity = undefined
756
+ old product without exchange refundedQuantity = 0
757
+ unreference refund-product refundedQuantity is > 0 */
758
+ basketDetails.total = 0;
759
+ basketDetails.quantity = 0;
760
+ try {
761
+ for (var _b = __values(basketDetails.products), _c = _b.next(); !_c.done; _c = _b.next()) {
762
+ var product = _c.value;
763
+ if (product.linePromotions) {
764
+ product.total = product.linePromotions.promotionLinePrice;
765
+ }
766
+ else if (product.lineDiscount && !product.linePromotions) {
767
+ product.total = product.lineDiscount.discountedLinePrice;
768
+ }
769
+ else {
770
+ product.total = product.totalLinePrice;
771
+ }
772
+ product.total =
773
+ product.total -
774
+ Math.abs(product.refundedTotal ? product.refundedTotal : 0);
775
+ basketDetails.total += product.total;
776
+ basketDetails.quantity =
777
+ basketDetails.quantity +
778
+ (product.quantity -
779
+ (product.refundedQuantity ? product.refundedQuantity : 0));
780
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateProductTotalForSummary", "update basketdetails total :" +
781
+ basketDetails.total +
782
+ " Product line ID : " +
783
+ product.itemLineId +
784
+ " product total : " +
785
+ product.total, "quantity : " + basketDetails.quantity);
786
+ }
787
+ }
788
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
789
+ finally {
790
+ try {
791
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
792
+ }
793
+ finally { if (e_4) throw e_4.error; }
794
+ }
795
+ return this.updateBasketTotalForSummary(basketDetails);
796
+ };
797
+ BasketService.prototype.updateBasketTotalForSummary = function (basketDetails) {
798
+ basketDetails.basketTotal = basketDetails.total;
799
+ appLogger_service.AppLoggerService.logInfo(this.className, "updateBasketTotalForSummary", "update Basket Total for transaction transactionDiscount ", basketDetails.transactionDiscount);
800
+ appLogger_service.AppLoggerService.logInfo(this.className, "updateBasketTotalForSummary", "update Basket Total for transaction transactionPromotion ", basketDetails.transactionPromotion);
801
+ basketDetails = this.updateTransactionPromotion(basketDetails);
802
+ basketDetails = this.updateTransactionDiscount(basketDetails);
803
+ basketDetails.basketTotal = Number(basketDetails.basketTotal.toFixed(2));
804
+ appLogger_service.AppLoggerService.logInfo(this.className, "updateBasketTotalForSummary", "update Basket Total: basketTotal after promotion applied for basketTotal", basketDetails.basketTotal);
805
+ return basketDetails;
806
+ };
807
+ BasketService.prototype.updateTransactionDiscount = function (basketDetails) {
808
+ if (basketDetails.transactionDiscount &&
809
+ basketDetails.transactionDiscount.length > 0) {
810
+ var discountTotal = basketDetails.transactionDiscount.reduce(function (n, _a) {
811
+ var discountAmount = _a.discountAmount;
812
+ return n + discountAmount;
813
+ }, 0);
814
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateTransactionDiscount", "discountTotal ", discountTotal);
815
+ basketDetails.basketTotal =
816
+ basketDetails.basketTotal - Math.abs(discountTotal);
817
+ }
818
+ return basketDetails;
819
+ };
820
+ BasketService.prototype.updateTransactionPromotion = function (basketDetails) {
821
+ if (basketDetails.transactionPromotion &&
822
+ basketDetails.transactionPromotion.length > 0) {
823
+ var discountTotal = basketDetails.transactionPromotion.reduce(function (n, _a) {
824
+ var promotionAmount = _a.promotionAmount;
825
+ return n + promotionAmount;
826
+ }, 0);
827
+ basketDetails.basketTotal =
828
+ basketDetails.basketTotal - Math.abs(discountTotal);
829
+ }
830
+ return basketDetails;
831
+ };
832
+ BasketService.prototype.updateBasketTotalWithoutDiscount = function (basket) {
833
+ var e_5, _a;
834
+ basket.total = 0;
835
+ basket.quantity = 0;
836
+ try {
837
+ for (var _b = __values(basket.products), _c = _b.next(); !_c.done; _c = _b.next()) {
838
+ var product = _c.value;
839
+ if (product.linePromotions) {
840
+ product.total = product.linePromotions.promotionLinePrice;
841
+ }
842
+ else if (product.lineDiscount && !product.linePromotions) {
843
+ product.total = product.lineDiscount.discountedLinePrice || 0;
844
+ }
845
+ else {
846
+ product.total = product.totalLinePrice;
847
+ }
848
+ product.total =
849
+ product.total -
850
+ Math.abs(product.refundedTotal ? product.refundedTotal : 0);
851
+ basket.total += product.total;
852
+ basket.quantity =
853
+ basket.quantity +
854
+ (product.quantity -
855
+ (product.refundedQuantity ? product.refundedQuantity : 0));
856
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketTotalWithoutDiscount", "e-basket:basket service:update basketdetails total :" +
857
+ JSON.stringify(basket) +
858
+ basket.total +
859
+ " Product line ID : " +
860
+ product.itemLineId +
861
+ " product total : " +
862
+ product.total);
863
+ }
864
+ }
865
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
866
+ finally {
867
+ try {
868
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
869
+ }
870
+ finally { if (e_5) throw e_5.error; }
871
+ }
872
+ basket.basketTotal = basket.total;
873
+ return basket;
874
+ };
875
+ BasketService.prototype.updateBasketTotalWithDiscounts = function (basket) {
876
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketTotalWithDiscounts", "this.basketDetails new values " + basket + ", \n " + JSON.stringify(basket.basketTotal));
877
+ if (basket.transactionPromotion && basket.transactionPromotion.length > 0) {
878
+ var discountTotal = basket.transactionPromotion.reduce(function (n, _a) {
879
+ var promotionAmount = _a.promotionAmount;
880
+ return n + promotionAmount;
881
+ }, 0);
882
+ basket.basketTotal = basket.basketTotal - discountTotal;
883
+ }
884
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
885
+ var discountTotal = basket.transactionDiscount.reduce(function (n, _a) {
886
+ var discountAmount = _a.discountAmount;
887
+ return n + discountAmount;
888
+ }, 0);
889
+ basket.basketTotal = basket.basketTotal - discountTotal;
890
+ }
891
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketTotalWithDiscounts", "basket new values", basket);
892
+ return basket;
893
+ };
894
+ BasketService.prototype.transactionDiscountAndPromotionProductortionCalculation = function (basket) {
895
+ var _this = this;
896
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
897
+ basket.transactionDiscount.forEach(function (discount) { return (basket = _this.transactionDiscountProductPortionCalc(basket, discount)); });
898
+ }
899
+ if (basket.transactionPromotion && basket.transactionPromotion.length > 0) {
900
+ basket.transactionPromotion.forEach(function (promotion) {
901
+ basket = _this.transactionPromotionProductPortionCalc(basket, promotion);
902
+ });
903
+ }
904
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionDiscountAndPromotionProductortionCalculation", "basket item discount protion calculation ,\n " + basket + ",\n " + basket.products);
905
+ return basket;
906
+ };
907
+ BasketService.prototype.transactionPromotionProductPortionCalc = function (basket, promotion) {
908
+ var _this = this;
909
+ var total = 0;
910
+ var percentage = 0;
911
+ {
912
+ basket.products.forEach(function (p) {
913
+ if (promotion.itemLineIds.includes(p.itemLineId)) {
914
+ p = _this.validateProductItemDiscount(p);
915
+ var productContributionInTotal = _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnDiscountsPortion) +
916
+ _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnPromotionsPortion) -
917
+ _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.refundPortion);
918
+ total += (p.total - _this.numberUtilService.trimTo2Decimal2(productContributionInTotal));
919
+ }
920
+ });
921
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotionProductPortionCalc", "ebasket: trnsactionPromotion: " + JSON.stringify(promotion) + ", selected products total: " + total);
922
+ basket.products.forEach(function (product) {
923
+ product = _this.validateProductItemDiscount(product);
924
+ var productContributionInTotal = _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion) +
925
+ _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion) -
926
+ _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.refundPortion);
927
+ if (promotion.itemLineIds.includes(product.itemLineId)) {
928
+ percentage = ((product.total - _this.numberUtilService.trimTo2Decimal2(productContributionInTotal)) / total) * 100;
929
+ product.itemDiscounts.trnPromotionsPortion +=
930
+ (promotion.promotionAmount * percentage) / 100;
931
+ product.itemDiscounts.trnPromotionsPortion = _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion);
932
+ }
933
+ });
934
+ }
935
+ return basket;
936
+ };
937
+ BasketService.prototype.transactionDiscountProductPortionCalc = function (basket, discount) {
938
+ var _this = this;
939
+ var total = 0;
940
+ var percentage = 0;
941
+ basket.products.forEach(function (p) {
942
+ if (discount.itemLineIds.includes(p.itemLineId)) {
943
+ p = _this.validateProductItemDiscount(p);
944
+ var productContributionInTotal = _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnDiscountsPortion) +
945
+ _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.trnPromotionsPortion) -
946
+ _this.numberUtilService.trimTo2Decimal2(p.itemDiscounts.refundPortion);
947
+ total += (p.total - _this.numberUtilService.trimTo2Decimal2(productContributionInTotal));
948
+ }
949
+ });
950
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionDiscountProductPortionCalc", "ebasket: trnsactionDiscount: " + JSON.stringify(discount) + ", selected products total: " + total);
951
+ basket.products.forEach(function (product) {
952
+ product = _this.validateProductItemDiscount(product);
953
+ appLogger_service.AppLoggerService.logDebug(_this.className, "transactionDiscountProductPortionCalc", "discountable in basket service", product.discountable);
954
+ var productContributionInTotal = _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion) +
955
+ _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnPromotionsPortion) -
956
+ _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.refundPortion);
957
+ if (discount.itemLineIds.includes(product.itemLineId) && product.discountable == true) {
958
+ percentage = ((product.total - _this.numberUtilService.trimTo2Decimal2(productContributionInTotal)) / total) * 100;
959
+ product.itemDiscounts.trnDiscountsPortion +=
960
+ (discount.discountAmount * percentage) / 100;
961
+ product.itemDiscounts.trnDiscountsPortion = _this.numberUtilService.trimTo2Decimal2(product.itemDiscounts.trnDiscountsPortion);
962
+ }
963
+ });
964
+ return basket;
965
+ };
966
+ BasketService.prototype.validateProductItemDiscount = function (product) {
967
+ if (!product.itemDiscounts) {
968
+ product.itemDiscounts = {
969
+ trnDiscountsPortion: 0,
970
+ trnPromotionsPortion: 0,
971
+ refundPortion: 0,
972
+ };
973
+ }
974
+ return product;
975
+ };
976
+ BasketService.prototype.markProduct = function (product) {
977
+ this.productSource.next(product);
978
+ };
979
+ BasketService.prototype.stopPeerSyncProcess = function (peerSync) {
980
+ this.peerSource.next(peerSync);
981
+ };
982
+ BasketService.prototype.scanStart = function (isScanning) {
983
+ this.scanSource.next(isScanning);
984
+ };
985
+ BasketService.prototype.promotionRemainingCalculation = function (promotion) {
986
+ var promotionValue = 0;
987
+ promotion.forEach(function (element) {
988
+ promotionValue += element.promotionAmount;
989
+ });
990
+ return promotionValue;
991
+ };
992
+ BasketService.prototype.discountRemainingCalculation = function (discount) {
993
+ var discountValue = 0;
994
+ discount.forEach(function (element) {
995
+ discountValue += element.discountAmount;
996
+ });
997
+ return discountValue;
998
+ };
999
+ BasketService.prototype.discountRefundedCalculation = function (discount) {
1000
+ var discountValue = 0;
1001
+ discount.forEach(function (element) {
1002
+ if (element.discountAmount < 0) {
1003
+ discountValue += element.discountAmount;
1004
+ }
1005
+ });
1006
+ return discountValue;
1007
+ };
1008
+ BasketService.prototype.generateNewItemLineId = function (products) {
1009
+ var largestNumber = 0;
1010
+ if (products.length > 0) {
1011
+ var itemLineIdArray = products.map(function (product) {
1012
+ return product.itemLineId;
1013
+ });
1014
+ largestNumber = itemLineIdArray.reduce(function (a, b) { return Math.max(a, b); });
1015
+ }
1016
+ return largestNumber + 1;
1017
+ };
1018
+ BasketService.prototype.updateBasketProductDataAsPerQuantity = function (product, quantity) {
1019
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketProductDataAsPerQuantity", "ebasket: updateBasketProductDataAsPerQuantity : " + quantity + " product: " + JSON.stringify(product));
1020
+ product.quantity = quantity;
1021
+ if (product.hasOwnProperty("lineDiscount")) {
1022
+ // && this.product.quantity !== this.productDetailForm.controls.quantity.value
1023
+ product.lineDiscount.discountedLinePrice = Number(this.numberUtilService.getFlooredFixed(product.lineDiscount.unitPrice * quantity, 2));
1024
+ product.lineDiscount.discountAmount =
1025
+ product.totalLinePrice - product.lineDiscount.discountedLinePrice;
1026
+ }
1027
+ else {
1028
+ product.totalLinePrice =
1029
+ quantity * this.numberUtilService.trimTo2Decimal(product.selectedPrice);
1030
+ }
1031
+ if (product.lineDiscount) {
1032
+ product.total = product.lineDiscount.discountedLinePrice;
1033
+ }
1034
+ else {
1035
+ product.total = product.totalLinePrice;
1036
+ }
1037
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateBasketProductDataAsPerQuantity", "ebasket: updateBasketProductDataAsPerQuantity : " + quantity + " product: " + JSON.stringify(product));
1038
+ return product;
1039
+ };
1040
+ BasketService.prototype.filterProductListWithWebOrder = function (isWebOrder) {
1041
+ appLogger_service.AppLoggerService.logDebug(this.className, "filterProductListWithWebOrder", "filterProductListWithWebOrder hit", this.currentBasket.products);
1042
+ if (isWebOrder)
1043
+ return this.currentBasket.products.filter(function (x) { return x.isWebOrder; });
1044
+ else {
1045
+ return this.currentBasket.products.filter(function (x) { return !x.isWebOrder; });
1046
+ }
1047
+ };
1048
+ BasketService.prototype.filterProductListWithDelivery = function () {
1049
+ appLogger_service.AppLoggerService.logDebug(this.className, "filterProductListWithDelivery", "filterProductListWithDelivery hit", this.currentBasket.products);
1050
+ return this.currentBasket.products.filter(function (x) { return x.deliveryMethod === DELIVERY_METHODS.DELIVERY.toString(); });
1051
+ };
1052
+ BasketService.prototype.filterProductListWithDeliveryGroup = function (group, products) {
1053
+ appLogger_service.AppLoggerService.logDebug(this.className, "filterProductListWithDeliveryGroup", "filterProductListWithDeliveryGroup hit", products);
1054
+ return products.filter(function (x) { return x.deliveryGroup === group; });
1055
+ };
1056
+ BasketService.prototype.generateNewDeliveryGroupNumber = function (products) {
1057
+ var largestNumber = 0;
1058
+ if (products.length > 0) {
1059
+ var deliveryGroupArr = products.map(function (product) {
1060
+ if (product.deliveryGroup) {
1061
+ return parseInt(product.deliveryGroup);
1062
+ }
1063
+ return 0;
1064
+ });
1065
+ largestNumber = deliveryGroupArr.reduce(function (a, b) { return Math.max(a, b); });
1066
+ }
1067
+ return (largestNumber + 1).toString();
1068
+ };
1069
+ BasketService.prototype.getDeliveryGroupNumbers = function (products) {
1070
+ appLogger_service.AppLoggerService.logDebug(this.className, "getDeliveryGroupNumbers", "getDeliveryGroupNumbers initiating : ", products);
1071
+ var uniqueAndsortedResult = [];
1072
+ if (products.length > 0) {
1073
+ var deliveryGroupArr = products.map(function (product) {
1074
+ if (product.deliveryGroup) {
1075
+ return parseInt(product.deliveryGroup);
1076
+ }
1077
+ else if (product.deliveryMethod === "1") {
1078
+ return 1;
1079
+ }
1080
+ return 0;
1081
+ });
1082
+ uniqueAndsortedResult = Array.from(new Set(deliveryGroupArr)).sort(function (a, b) { return a - b; });
1083
+ appLogger_service.AppLoggerService.logDebug(this.className, "getDeliveryGroupNumbers", "getDeliveryGroupNumbers : uniqueAndsortedResult", uniqueAndsortedResult);
1084
+ }
1085
+ return uniqueAndsortedResult;
1086
+ };
1087
+ BasketService.prototype.updateProductsWithNewDeliveryGroupNumber = function (products) {
1088
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateProductsWithNewDeliveryGroupNumber", "initiating : ", products);
1089
+ var newGroupNumber = this.generateNewDeliveryGroupNumber(this.currentBasket.products);
1090
+ if (products.length > 0) {
1091
+ this.currentBasket.products.forEach(function (cBProducts) {
1092
+ products.forEach(function (element) {
1093
+ if (cBProducts.itemLineId === element.itemLineId) {
1094
+ cBProducts.deliveryGroup = newGroupNumber;
1095
+ }
1096
+ });
1097
+ });
1098
+ }
1099
+ this.updateBasket(this.currentBasket);
1100
+ return;
1101
+ };
1102
+ BasketService.prototype.calculateEstimatedTime = function (products) {
1103
+ var _this = this;
1104
+ try {
1105
+ var time_1;
1106
+ var estmatedTime_1 = 0;
1107
+ var estimatedDays_1 = "Hours";
1108
+ products.forEach(function (element) {
1109
+ if (element.leadTime.type.toLocaleLowerCase() === "weeks") {
1110
+ time_1 = Number(element.leadTime.value) * 24 * 7;
1111
+ estmatedTime_1 = Math.max(estmatedTime_1, time_1);
1112
+ estimatedDays_1 = (estmatedTime_1 === time_1) ? element.leadTime.type : estimatedDays_1;
1113
+ appLogger_service.AppLoggerService.logDebug(_this.className, "calculateEstimatedTime", "week " + estmatedTime_1 + " " + estimatedDays_1);
1114
+ }
1115
+ else if (element.leadTime.type.toLocaleLowerCase() === "days") {
1116
+ time_1 = Number(element.leadTime.value) * 24;
1117
+ estmatedTime_1 = Math.max(estmatedTime_1, time_1);
1118
+ estimatedDays_1 = (estmatedTime_1 === time_1) ? element.leadTime.type : estimatedDays_1;
1119
+ appLogger_service.AppLoggerService.logDebug(_this.className, "calculateEstimatedTime", "days " + estmatedTime_1 + " " + estimatedDays_1);
1120
+ }
1121
+ else if (element.leadTime.type.toLocaleLowerCase() === "months") {
1122
+ time_1 = Number(element.leadTime.value) * 24 * 30;
1123
+ estmatedTime_1 = Math.max(estmatedTime_1, time_1);
1124
+ estimatedDays_1 = (estmatedTime_1 === time_1) ? element.leadTime.type : estimatedDays_1;
1125
+ appLogger_service.AppLoggerService.logDebug(_this.className, "calculateEstimatedTime", "months " + estmatedTime_1 + " " + estimatedDays_1);
1126
+ }
1127
+ else if (element.leadTime.type.toLocaleLowerCase() === "years") {
1128
+ time_1 = Number(element.leadTime.value) * 24 * 365;
1129
+ estmatedTime_1 = Math.max(estmatedTime_1, time_1);
1130
+ estimatedDays_1 = (estmatedTime_1 === time_1) ? element.leadTime.type : estimatedDays_1;
1131
+ appLogger_service.AppLoggerService.logDebug(_this.className, "calculateEstimatedTime", "years " + estmatedTime_1 + " " + estimatedDays_1);
1132
+ }
1133
+ else {
1134
+ time_1 = Number(element.leadTime.value);
1135
+ estmatedTime_1 = Math.max(estmatedTime_1, time_1);
1136
+ estimatedDays_1 = (estmatedTime_1 === time_1) ? element.leadTime.type : estimatedDays_1;
1137
+ appLogger_service.AppLoggerService.logDebug(_this.className, "calculateEstimatedTime", "hours " + estmatedTime_1 + " " + estimatedDays_1);
1138
+ }
1139
+ });
1140
+ if (estimatedDays_1.toLocaleLowerCase() === "days") {
1141
+ estmatedTime_1 = estmatedTime_1 / 24;
1142
+ }
1143
+ else if (estimatedDays_1.toLocaleLowerCase() === "weeks") {
1144
+ estmatedTime_1 = estmatedTime_1 / (24 * 7);
1145
+ }
1146
+ else if (estimatedDays_1.toLocaleLowerCase() === "months") {
1147
+ estmatedTime_1 = estmatedTime_1 / (24 * 30);
1148
+ }
1149
+ else if (estimatedDays_1.toLocaleLowerCase() === "years") {
1150
+ estmatedTime_1 = estmatedTime_1 / (24 * 365);
1151
+ }
1152
+ var estimate = {
1153
+ value: estmatedTime_1.toString(),
1154
+ type: estimatedDays_1
1155
+ };
1156
+ return estimate;
1157
+ }
1158
+ catch (error) {
1159
+ appLogger_service.AppLoggerService.logError(this.className, "calculateEstimatedTime", "error in calculateEstimatedTime", error);
1160
+ }
1161
+ return 0;
1162
+ };
1163
+ BasketService.prototype.updateProductsWithDeliveryGroupNumber = function (oldGroup, newGroup) {
1164
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateProductsWithDeliveryGroupNumber initiating");
1165
+ this.currentBasket.products.forEach(function (cBProducts) {
1166
+ if (cBProducts.deliveryGroup === oldGroup) {
1167
+ cBProducts.deliveryGroup = newGroup;
1168
+ }
1169
+ });
1170
+ this.updateBasket(this.currentBasket);
1171
+ return;
1172
+ };
1173
+ BasketService.prototype.getDeliveryInfo = function () {
1174
+ var _this = this;
1175
+ appLogger_service.AppLoggerService.logDebug(this.className, "getDeliveryInfo", "getDeliveryGroupInfor initiating");
1176
+ try {
1177
+ var groupInfo_1 = {
1178
+ groups: []
1179
+ };
1180
+ this.getDeliveryGroupNumbers(this.currentBasket.products).forEach(function (groupNumber) {
1181
+ var group = {
1182
+ groupNumber: groupNumber,
1183
+ items: [],
1184
+ estimate: {
1185
+ type: "Hours",
1186
+ value: "0"
1187
+ }
1188
+ };
1189
+ _this.currentBasket.products.forEach(function (cBProducts) {
1190
+ if (cBProducts.deliveryGroup === groupNumber.toString()) {
1191
+ group.items.push(cBProducts);
1192
+ }
1193
+ });
1194
+ group.estimate = _this.calculateEstimatedTime(group.items);
1195
+ groupInfo_1.groups.push(group);
1196
+ });
1197
+ return groupInfo_1;
1198
+ }
1199
+ catch (error) {
1200
+ appLogger_service.AppLoggerService.logError(this.className, "getDeliveryInfo", "error while getting delivery info", error);
1201
+ }
1202
+ };
1203
+ return BasketService;
1204
+ }());
1205
+
1206
+ var NumberUtilService = /** @class */ (function () {
1207
+ function NumberUtilService(cp) {
1208
+ this.cp = cp;
1209
+ this.className = "NumberUtilService";
1210
+ }
1211
+ NumberUtilService.prototype.trimTo2Decimal = function (no) {
1212
+ //return Math.floor(no * 100) / 100;
1213
+ return no;
1214
+ };
1215
+ NumberUtilService.prototype.trimTo2Decimal2 = function (no) {
1216
+ // SEAM-11411 - Had to change 2nd param to 3 to fix rounding issue (FIXME - Needs a new story for refactoring)
1217
+ return Number(this.getFlooredFixed(no, 3));
1218
+ };
1219
+ NumberUtilService.prototype.getFlooredFixed = function (v, d) {
1220
+ return (Math.floor(v * Math.pow(10, d)) / Math.pow(10, d)).toFixed(d);
1221
+ };
1222
+ NumberUtilService.prototype.AppendWithCurrencySymbol = function (numValue, currencyCode) {
1223
+ var returnValue = "";
1224
+ if (numValue) {
1225
+ var numb = parseFloat(numValue.toString().replace(',', ''));
1226
+ returnValue = this.cp.transform(Number(numValue).toFixed(2), currencyCode.toLocaleUpperCase(), "symbol");
1227
+ appLogger_service.AppLoggerService.logDebug(this.className, "AppendWithCurrencySymbol", "AppendWithCurrencySymbol :", returnValue);
1228
+ }
1229
+ else {
1230
+ returnValue = this.cp.transform("0.00", currencyCode.toLocaleUpperCase(), "symbol");
1231
+ }
1232
+ return returnValue;
1233
+ };
1234
+ return NumberUtilService;
1235
+ }());
1236
+ NumberUtilService.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: NumberUtilService, deps: [{ token: i1__namespace.CurrencyPipe }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1237
+ NumberUtilService.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: NumberUtilService, providedIn: "root" });
1238
+ i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0__namespace, type: NumberUtilService, decorators: [{
1239
+ type: i0.Injectable,
1240
+ args: [{
1241
+ providedIn: "root",
1242
+ }]
1243
+ }], ctorParameters: function () { return [{ type: i1__namespace.CurrencyPipe }]; } });
1244
+
1245
+ /**
1246
+ * Transaction document builder
1247
+ */
1248
+ var TransactionDocumentBuilder = /** @class */ (function () {
1249
+ function TransactionDocumentBuilder(transactionDoc, currencyPipe, basketService) {
1250
+ this.currencyPipe = currencyPipe;
1251
+ this.basketService = basketService;
1252
+ this.className = "TransactionDocumentBuilder";
1253
+ this.numberUtilService = new NumberUtilService(currencyPipe);
1254
+ this.basketService = new BasketService(this.numberUtilService);
1255
+ this.storeInfo = JSON.parse(localStorage.getItem('storeInfo') || '{}');
1256
+ if (transactionDoc) {
1257
+ this.transactionDocument = transactionDoc;
1258
+ }
1259
+ else {
1260
+ this.transactionDocument = {
1261
+ transactionId: "",
1262
+ offlineTransactionId: "",
1263
+ transactionRef: "",
1264
+ dateTime: "",
1265
+ orgCode: "",
1266
+ storeId: "",
1267
+ storeNodeId: "",
1268
+ storeNodeStructure: "",
1269
+ deviceId: "",
1270
+ terminalId: "",
1271
+ userId: "",
1272
+ initiatingModule: "eBasket",
1273
+ export: false,
1274
+ basket: {},
1275
+ basketSummary: {},
1276
+ baseCurrency: "",
1277
+ type: "",
1278
+ operationStatus: "",
1279
+ createdAt: "",
1280
+ updatedAt: "",
1281
+ id: "",
1282
+ currentTransactionDetails: {},
1283
+ saleTotal: 0,
1284
+ };
1285
+ }
1286
+ }
1287
+ /**
1288
+ * Transactions ref
1289
+ * @returns ref
1290
+ */
1291
+ TransactionDocumentBuilder.prototype.transactionRef = function () {
1292
+ var storeDetails = JSON.parse(localStorage.getItem('storeInfo') || '{}');
1293
+ var date = new Date();
1294
+ var random = (((1 + Math.random()) * 0x10000) | 0)
1295
+ .toString(16)
1296
+ .substring(1);
1297
+ this.transactionDocument.transactionRef =
1298
+ storeDetails.orgCode + storeDetails.storeId + date.toISOString() + random;
1299
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionRef", "transaction ref created", this.transactionDocument.transactionRef);
1300
+ return this;
1301
+ };
1302
+ /**
1303
+ * Transactions id
1304
+ * @param transactionID
1305
+ * @returns id
1306
+ */
1307
+ TransactionDocumentBuilder.prototype.transactionId = function (transactionID, isOnline) {
1308
+ if (isOnline === void 0) { isOnline = true; }
1309
+ if (isOnline) {
1310
+ this.transactionDocument.transactionId = transactionID;
1311
+ }
1312
+ return this;
1313
+ };
1314
+ /**
1315
+ * Transactions id
1316
+ * @param transactionID
1317
+ * @returns id
1318
+ */
1319
+ TransactionDocumentBuilder.prototype.offlineTransactionId = function (transactionID, isOnline) {
1320
+ if (!isOnline) {
1321
+ this.transactionDocument.offlineTransactionId = transactionID;
1322
+ }
1323
+ return this;
1324
+ };
1325
+ /**
1326
+ * storeNode Id
1327
+ * @param storeNodeId
1328
+ * @returns id
1329
+ */
1330
+ TransactionDocumentBuilder.prototype.storeNodeId = function (storeNodeId) {
1331
+ this.transactionDocument.storeNodeId = storeNodeId;
1332
+ return this;
1333
+ };
1334
+ /**
1335
+ * storeNode structure
1336
+ * @param storeNodeStructure
1337
+ * @returns id
1338
+ */
1339
+ TransactionDocumentBuilder.prototype.storeNodeStructure = function (storeNodeStructure) {
1340
+ this.transactionDocument.storeNodeStructure = storeNodeStructure;
1341
+ return this;
1342
+ };
1343
+ /**
1344
+ * Orgs code
1345
+ * @param orgCode
1346
+ * @returns code
1347
+ */
1348
+ TransactionDocumentBuilder.prototype.orgCode = function (orgCode) {
1349
+ this.transactionDocument.orgCode = orgCode;
1350
+ return this;
1351
+ };
1352
+ /**
1353
+ * Stores id
1354
+ * @param storeId
1355
+ * @returns id
1356
+ */
1357
+ TransactionDocumentBuilder.prototype.storeId = function (storeId) {
1358
+ this.transactionDocument.storeId = storeId;
1359
+ return this;
1360
+ };
1361
+ /**
1362
+ * Dates time
1363
+ * @returns time
1364
+ */
1365
+ TransactionDocumentBuilder.prototype.dateTime = function () {
1366
+ var date = new Date();
1367
+ this.transactionDocument.dateTime = date.toISOString();
1368
+ return this;
1369
+ };
1370
+ /**
1371
+ * Devices id
1372
+ * @param deviceId
1373
+ * @returns id
1374
+ */
1375
+ TransactionDocumentBuilder.prototype.deviceId = function (deviceId) {
1376
+ this.transactionDocument.deviceId = deviceId;
1377
+ return this;
1378
+ };
1379
+ /**
1380
+ * terminal id
1381
+ * @param terminalId
1382
+ * @returns id
1383
+ */
1384
+ TransactionDocumentBuilder.prototype.terminalId = function (terminalId) {
1385
+ this.transactionDocument.terminalId = terminalId;
1386
+ return this;
1387
+ };
1388
+ /**
1389
+ * saleExport
1390
+ * @param saleExport
1391
+ * @returns id
1392
+ */
1393
+ TransactionDocumentBuilder.prototype.export = function (saleExport) {
1394
+ this.transactionDocument.export = saleExport;
1395
+ return this;
1396
+ };
1397
+ /* customer(): TransactionDocumentBuilder {
1398
+ const user = JSON.parse(localStorage.getItem('userDetails'));
1399
+ this.transactionDocument.customer = user;
1400
+ return this;
1401
+ } */
1402
+ /**
1403
+ * Baskets transaction document builder
1404
+ * @param basketDetails
1405
+ * @returns basket
1406
+ */
1407
+ TransactionDocumentBuilder.prototype.basket = function (basketDetails) {
1408
+ var _this = this;
1409
+ appLogger_service.AppLoggerService.logDebug(this.className, "basket", "basket details update in transaction document", basketDetails);
1410
+ this.transactionDocument.subsidiaryId = basketDetails.subsidiaryId || (localStorage.getItem('subsidiaryId') || '');
1411
+ this.transactionDocument.basket.products = [];
1412
+ this.transactionDocument.basket.lineDiscount = [];
1413
+ this.transactionDocument.basket.linePromotion = [];
1414
+ this.transactionDocument.basket.transactionPromotion = [];
1415
+ basketDetails.products.forEach(function (product, index) {
1416
+ var p = {};
1417
+ p.itemDiscounts = {};
1418
+ p.SKU = product.SKU;
1419
+ p.excludePromotion = product.excludePromotion;
1420
+ p.barCode = product.barcode;
1421
+ p.barcodes = product.barcodes;
1422
+ p.description = product.description;
1423
+ p.itemLineId = product.itemLineId ? product.itemLineId.toString() : "" + (index + 1);
1424
+ p.price = product.selectedPrice;
1425
+ p.quantity = product.quantity;
1426
+ p.totalLinePrice = product.quantity * product.selectedPrice;
1427
+ p.imageUrls = product.imageUrls;
1428
+ p.selectedRRPPrice = product.selectedRRPPrice;
1429
+ //inventory fields
1430
+ p.fullfilmentId = product.fullfilmentId ? product.fullfilmentId : _this.storeInfo.storeId;
1431
+ p.fullfilmentLocationName = product.fullfilmentLocationName;
1432
+ p.deliveryGroup = product.deliveryGroup;
1433
+ p.leadTime = product.leadTime;
1434
+ p.deliveryMethod = product.deliveryMethod;
1435
+ p.giftCard = product.giftCard;
1436
+ p.giftCardExpiryDate = product.giftCardExpiryDate;
1437
+ p.giftCardNumberIssued = product.giftCardNumberIssued;
1438
+ p.giftCardRecipientEmail = product.giftCardRecipientEmail;
1439
+ p.giftCardRecipientName = product.giftCardRecipientName;
1440
+ if (product.refundedQuantity > 0) {
1441
+ p.refundedQuantity = product.refundedQuantity;
1442
+ p.refundedPromotionalQuantity = product.refundPromotionalQuantity;
1443
+ p.refunded = product.refunded;
1444
+ p.refundedReasonDescription = product.refundedReasonDescription;
1445
+ p.refundedReason = product.refundedReason;
1446
+ if (!p.refundedReasonDescription) {
1447
+ p.refundedReasonDescription = p.refundedReason;
1448
+ }
1449
+ p.refundedTotal = product.refundedTotal;
1450
+ p.isLastExchanged = product.isLastExchanged;
1451
+ }
1452
+ if (product.exchange) {
1453
+ p.exchange = product.exchange;
1454
+ }
1455
+ if (product.lineDiscount) {
1456
+ p.lineDiscount = product.lineDiscount;
1457
+ }
1458
+ p.itemDiscounts = product.itemDiscounts;
1459
+ _this.transactionDocument.basket.products.push(p);
1460
+ _this.lineDiscount(basketDetails);
1461
+ });
1462
+ appLogger_service.AppLoggerService.logInfo(this.className, "basket", "transactiondocument basket details updated", this.transactionDocument.basket);
1463
+ return this;
1464
+ };
1465
+ /**
1466
+ * current transaction Details Total(New Products)
1467
+ * @returns currentTransactionDetails
1468
+ */
1469
+ TransactionDocumentBuilder.prototype.currentTransactionDetails = function (basket) {
1470
+ var _a;
1471
+ var _this = this;
1472
+ appLogger_service.AppLoggerService.logDebug(this.className, "currentTransactionDetails", "current transaction details for exchanges", basket);
1473
+ this.transactionDocument.currentTransactionDetails.products = [];
1474
+ this.transactionDocument.currentTransactionDetails.linePromotion = [];
1475
+ this.transactionDocument.currentTransactionDetails.lineDiscount = [];
1476
+ this.transactionDocument.currentTransactionDetails.transactionDiscount = [];
1477
+ this.transactionDocument.currentTransactionDetails.products = basket.products;
1478
+ this.transactionDocument.currentTransactionDetails.products = this.transactionDocument.currentTransactionDetails.products.filter(function (proj) { return proj.refundedQuantity != 0; });
1479
+ this.transactionDocument.currentTransactionDetails.products.forEach(function (product) {
1480
+ if (product.refundedQuantity) {
1481
+ product.quantity = product.refundedQuantity;
1482
+ // updating total line price with actual price to be refunded including the refunding qty
1483
+ product.totalLinePrice = Math.abs(product.refundedTotal);
1484
+ product.total = product.totalLinePrice;
1485
+ if (product.quantity === product.refundedQuantity) {
1486
+ product.refunded = true;
1487
+ }
1488
+ }
1489
+ //Updating line promotions and line discounts
1490
+ if (product.linePromotions && !product.refundedQuantity) {
1491
+ _this.transactionDocument.currentTransactionDetails.linePromotion.push(product.linePromotions);
1492
+ }
1493
+ if (product.lineDiscount && !product.refundedQuantity) {
1494
+ _this.transactionDocument.currentTransactionDetails.lineDiscount.push(product.lineDiscount);
1495
+ }
1496
+ });
1497
+ appLogger_service.AppLoggerService.logDebug(this.className, "currentTransactionDetails", "current transaction details after removing old products", this.transactionDocument.currentTransactionDetails.products);
1498
+ if (basket.transactionDiscount && basket.transactionDiscount.length > 0) {
1499
+ (_a = this.transactionDocument.currentTransactionDetails.transactionDiscount).push.apply(_a, __spreadArray([], __read(basket.transactionDiscount)));
1500
+ }
1501
+ this.transactionDocument.currentTransactionDetails.basketSummary = {};
1502
+ this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal = this.numberUtilService.trimTo2Decimal2(this.updateSaleTotal(this.transactionDocument.currentTransactionDetails));
1503
+ this.transactionDocument.currentTransactionDetails.basketSummary.totalItems = basket.quantity;
1504
+ this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal = basket.basketTotal;
1505
+ this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal = this.updateCurrentTransactionDetailsRefundTotal();
1506
+ // For partial refund discount is updatied in total line price so discountTotal will always be zero & in case of exchange discount total is calculated
1507
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
1508
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = this.numberUtilService.trimTo2Decimal2(this.updateCurrentTransactionDetailsDiscountTotal());
1509
+ }
1510
+ else {
1511
+ if (this.transactionDocument.currentTransactionDetails.transactionDiscount && this.transactionDocument.currentTransactionDetails.transactionDiscount.length > 0) {
1512
+ var discountTotal_1 = 0;
1513
+ this.transactionDocument.currentTransactionDetails.transactionDiscount.forEach(function (discount) {
1514
+ discountTotal_1 += discount.discountAmount;
1515
+ });
1516
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = Math.abs(discountTotal_1);
1517
+ }
1518
+ else {
1519
+ this.transactionDocument.currentTransactionDetails.basketSummary.discountTotal = 0;
1520
+ }
1521
+ }
1522
+ appLogger_service.AppLoggerService.logInfo(this.className, "currentTransactionDetails", "currentTransactionDetails", this.transactionDocument.currentTransactionDetails);
1523
+ return this;
1524
+ };
1525
+ /**
1526
+ * current transaction Tax Total
1527
+ * @returns Tax Total
1528
+ */
1529
+ TransactionDocumentBuilder.prototype.updateCurrentTransactionDetailsTaxBreakdown = function (basketDetails) {
1530
+ var _this = this;
1531
+ var transactionDiscountTotal = 0;
1532
+ var taxBreakdown = {
1533
+ taxLines: [],
1534
+ totalTaxableAmount: 0,
1535
+ };
1536
+ if (this.transactionDocument.currentTransactionDetails.transactionDiscount && this.transactionDocument.currentTransactionDetails.transactionDiscount.length > 0) {
1537
+ this.transactionDocument.currentTransactionDetails.transactionDiscount.forEach(function (discount) {
1538
+ transactionDiscountTotal += discount.discountAmount;
1539
+ });
1540
+ }
1541
+ if (this.transactionDocument.currentTransactionDetails.products && this.transactionDocument.currentTransactionDetails.products.length > 0) {
1542
+ this.transactionDocument.currentTransactionDetails.products.forEach(function (product) {
1543
+ var taxLine = {
1544
+ itemLineId: product.itemLineId,
1545
+ VAT: product.selectedVAT ? product.selectedVAT : 0,
1546
+ VATCode: product.selectedVATCode,
1547
+ taxLineTotal: 0,
1548
+ taxableAmount: product.total,
1549
+ PreTax: 0
1550
+ };
1551
+ appLogger_service.AppLoggerService.logInfo(_this.className, "updateCurrentTransactionDetailsTaxBreakdown", "item line ID :current transaction Details\",\n " + product.itemLineId + ", tax line : " + taxLine + ", basketDetails.basketTotal " + basketDetails.basketTotal);
1552
+ //step 1
1553
+ // if Transaction Discount and/or promotion applied, find net selling price of each product as taxableamount
1554
+ //If transaction discount/promotion is applied taxable amount should be deducting transaction promotion and transaction disacount portion
1555
+ if (product.refundedQuantity && product.refundedQuantity > 0) {
1556
+ taxLine.taxableAmount = -Math.abs(taxLine.taxableAmount - product.itemDiscounts.currentRefundPortion);
1557
+ }
1558
+ else {
1559
+ taxLine.taxableAmount = taxLine.taxableAmount - product.itemDiscounts.trnDiscountsPortion - product.itemDiscounts.trnPromotionsPortion;
1560
+ }
1561
+ //step 2 - find pre tax
1562
+ taxLine.PreTax = _this.numberUtilService.trimTo2Decimal2((taxLine.taxableAmount * 100) / (100 + taxLine.VAT));
1563
+ //step 3 - Update taxbreakdown
1564
+ taxBreakdown.totalTaxableAmount += taxLine.taxableAmount;
1565
+ taxLine.taxableAmount = _this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount);
1566
+ // step 4 - update tax Line total
1567
+ taxLine.taxLineTotal = _this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount - taxLine.PreTax);
1568
+ taxBreakdown.taxLines.push(taxLine);
1569
+ });
1570
+ }
1571
+ taxBreakdown.totalTaxableAmount = this.numberUtilService.trimTo2Decimal2(taxBreakdown.totalTaxableAmount);
1572
+ this.transactionDocument.currentTransactionDetails.taxBreakdown = taxBreakdown;
1573
+ if (this.transactionDocument.currentTransactionDetails.taxBreakdown && this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines && this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.length > 0) {
1574
+ this.transactionDocument.currentTransactionDetails.basketSummary.VATTotal = this.numberUtilService.trimTo2Decimal2(this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.reduce(function (n, _a) {
1575
+ var taxLineTotal = _a.taxLineTotal;
1576
+ return n + taxLineTotal;
1577
+ }, 0));
1578
+ }
1579
+ else {
1580
+ this.transactionDocument.currentTransactionDetails.basketSummary.VATTotal = 0.00;
1581
+ }
1582
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsTaxBreakdown", "eBasket:after calculating tax currenttransactionDetails", this.transactionDocument.currentTransactionDetails);
1583
+ return this;
1584
+ };
1585
+ TransactionDocumentBuilder.prototype.updateCurrentTransactionDetailsTotalTaxSummary = function () {
1586
+ var _this = this;
1587
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsTotalTaxSummary", "Total Tax Summery Request :", this.transactionDocument.currentTransactionDetails.taxBreakdown);
1588
+ var totalTaxSummaryArray = [];
1589
+ var totalTaxSummaryGroup = [];
1590
+ this.transactionDocument.currentTransactionDetails.taxBreakdown.taxLines.forEach(function (element) {
1591
+ var TaxSummary = {
1592
+ VATCode: "",
1593
+ VAT: -12345,
1594
+ PreTaxSum: 0,
1595
+ TaxSum: 0,
1596
+ TXrateSum: 0
1597
+ };
1598
+ TaxSummary.VATCode = element.VATCode;
1599
+ TaxSummary.VAT = element.VAT;
1600
+ TaxSummary.PreTaxSum = _this.numberUtilService.trimTo2Decimal2(element.PreTax);
1601
+ TaxSummary.TaxSum = _this.numberUtilService.trimTo2Decimal2(element.taxLineTotal);
1602
+ TaxSummary.TXrateSum = _this.numberUtilService.trimTo2Decimal2(TaxSummary.PreTaxSum + TaxSummary.TaxSum);
1603
+ totalTaxSummaryArray.push(TaxSummary);
1604
+ });
1605
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsTotalTaxSummary", "Total Tax Summery Without Grouped : ", totalTaxSummaryArray);
1606
+ totalTaxSummaryGroup = totalTaxSummaryArray.reduce(function (preparedArray, currentObj) {
1607
+ var ind = preparedArray.findIndex(function (x) { return x.VAT === currentObj.VAT; });
1608
+ if (ind === -1) {
1609
+ preparedArray.push(currentObj);
1610
+ }
1611
+ else {
1612
+ preparedArray[ind].VATCode = currentObj.VATCode;
1613
+ preparedArray[ind].VAT = currentObj.VAT;
1614
+ preparedArray[ind].PreTaxSum += currentObj.PreTaxSum;
1615
+ preparedArray[ind].TaxSum += currentObj.TaxSum;
1616
+ preparedArray[ind].TXrateSum += currentObj.TXrateSum;
1617
+ }
1618
+ return preparedArray;
1619
+ }, []);
1620
+ // listOfTags.map(x => unique.filter(a => a.label == x.label && a.color == x.color).length > 0 ? null : unique.push(x));
1621
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsTotalTaxSummary", "Total Tax Summer Group :", totalTaxSummaryGroup);
1622
+ this.transactionDocument.currentTransactionDetails.totalTaxSummary = totalTaxSummaryGroup;
1623
+ return this;
1624
+ };
1625
+ /**
1626
+ * current transaction Disocunt Total
1627
+ * @returns Discount Total
1628
+ */
1629
+ TransactionDocumentBuilder.prototype.updateCurrentTransactionDetailsDiscountTotal = function () {
1630
+ var refundTotal = this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal ? this.transactionDocument.currentTransactionDetails.basketSummary.refundTotal : 0;
1631
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsDiscountTotal", "refundTotal " + refundTotal + ", basketTotal " + this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal + ",saleTotal " + this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal);
1632
+ var discountTotal = Math.abs(Math.abs(this.transactionDocument.currentTransactionDetails.basketSummary.saleTotal) -
1633
+ (Math.abs(this.transactionDocument.currentTransactionDetails.basketSummary.basketTotal) + Math.abs(refundTotal)));
1634
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsDiscountTotal", "discountTotal", discountTotal);
1635
+ return Number(discountTotal.toFixed(2));
1636
+ };
1637
+ /**
1638
+ * current transaction Refund Total
1639
+ * @returns Refund Total
1640
+ */
1641
+ TransactionDocumentBuilder.prototype.updateCurrentTransactionDetailsRefundTotal = function () {
1642
+ var totalRefund = 0;
1643
+ for (var index = 0; index < this.transactionDocument.currentTransactionDetails.products.length; index++) {
1644
+ var product = this.transactionDocument.currentTransactionDetails.products[index];
1645
+ if (product.refundedTotal) {
1646
+ totalRefund = totalRefund + product.refundedTotal;
1647
+ }
1648
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateCurrentTransactionDetailsRefundTotal", "totalRefund for Current TransactionDetails", totalRefund);
1649
+ }
1650
+ return totalRefund;
1651
+ };
1652
+ /**
1653
+ * Baskets summary
1654
+ * @param basketDetails
1655
+ * @returns summary
1656
+ */
1657
+ TransactionDocumentBuilder.prototype.basketSummary = function (basketDetails) {
1658
+ this.transactionDocument.basketSummary.basketTotal = this.numberUtilService.trimTo2Decimal(basketDetails.basketTotal);
1659
+ this.transactionDocument.basketSummary.saleTotal = this.numberUtilService.trimTo2Decimal2(this.updateSaleTotal(basketDetails));
1660
+ this.transactionDocument.basketSummary.refundTotal = this.getRefundTotal();
1661
+ if (this.transactionDocument.basket.lineDiscount ||
1662
+ this.transactionDocument.basket.linePromotion) {
1663
+ this.transactionDocument.basketSummary.discountTotal = this.numberUtilService.trimTo2Decimal2(this.updateDiscountTotal());
1664
+ }
1665
+ this.transactionDocument.basketSummary.totalItems = basketDetails.quantity;
1666
+ if (this.transactionDocument.basket.taxBreakdown) {
1667
+ this.transactionDocument.basketSummary.VATTotal = this.numberUtilService.trimTo2Decimal2(this.transactionDocument.basket.taxBreakdown.taxLines.reduce(function (n, _a) {
1668
+ var taxLineTotal = _a.taxLineTotal;
1669
+ return n + taxLineTotal;
1670
+ }, 0));
1671
+ }
1672
+ else {
1673
+ this.transactionDocument.basketSummary.VATTotal = 0.00;
1674
+ }
1675
+ appLogger_service.AppLoggerService.logInfo(this.className, "basketSummary", "basketsummary updated in transaction document: ", this.transactionDocument.basketSummary);
1676
+ return this;
1677
+ };
1678
+ /**
1679
+ * Line Discount
1680
+ * @param basketDetails
1681
+ * @returns line Discount
1682
+ */
1683
+ TransactionDocumentBuilder.prototype.lineDiscount = function (basketDetails) {
1684
+ this.transactionDocument.basket.lineDiscount = [];
1685
+ for (var index = 0; index < basketDetails.products.length; index++) {
1686
+ var element = basketDetails.products[index];
1687
+ if (element.lineDiscount) {
1688
+ this.transactionDocument.basket.lineDiscount.push(element.lineDiscount);
1689
+ this.transactionDocument.basket.lineDiscount = this.transactionDocument.basket.lineDiscount.reduce(function (acc, val) {
1690
+ if (!acc.find(function (el) { return el.itemLineId === val.itemLineId; })) {
1691
+ acc.push(val);
1692
+ }
1693
+ return acc;
1694
+ }, []);
1695
+ }
1696
+ // AppLoggerService.logInfo(this.className,
1697
+ // "e-basket :line discount updated in transaction document",
1698
+ // this.transactionDocument.basket.lineDiscount
1699
+ // );
1700
+ }
1701
+ return this;
1702
+ };
1703
+ /**
1704
+ * exchange
1705
+ * @param basketDetails
1706
+ * @returns exchange
1707
+ */
1708
+ TransactionDocumentBuilder.prototype.exchange = function (basketDetails) {
1709
+ this.transactionDocument.basket.exchange = basketDetails.exchange && basketDetails.exchange.length > 0 ? __spreadArray([], __read(basketDetails.exchange)) : [];
1710
+ var _loop_1 = function (index) {
1711
+ var element = basketDetails.products[index];
1712
+ if (element.exchange != undefined) {
1713
+ var isPresent = this_1.transactionDocument.basket.exchange.some(function (el) { return el.exchangeId === element.exchange.exchangeId; });
1714
+ if (!isPresent) {
1715
+ var exchangeItems = [];
1716
+ for (var j = 0; j < element.exchange.newItems.length; j++) {
1717
+ var item = element.exchange.newItems[j];
1718
+ var newItems = { lineItemId: item.itemLineId, Quantity: item.quantity };
1719
+ exchangeItems.push(newItems);
1720
+ }
1721
+ element.exchange.newItems = __spreadArray([], __read(exchangeItems));
1722
+ this_1.transactionDocument.basket.exchange.push(element.exchange);
1723
+ }
1724
+ }
1725
+ appLogger_service.AppLoggerService.logDebug(this_1.className, "exchange", "this.transactionDocument.basket exchange", this_1.transactionDocument.basket.exchange);
1726
+ };
1727
+ var this_1 = this;
1728
+ for (var index = 0; index < basketDetails.products.length; index++) {
1729
+ _loop_1(index);
1730
+ }
1731
+ return this;
1732
+ };
1733
+ /**
1734
+ * add previous exchange data
1735
+ * @param originalTransactionDocument
1736
+ * @returns line Promotions
1737
+ */
1738
+ TransactionDocumentBuilder.prototype.addExchangeData = function (originalTransactionDocument) {
1739
+ this.transactionDocument.basket.exchange = originalTransactionDocument.basket.exchange ? __spreadArray([], __read(originalTransactionDocument.basket.exchange)) : null;
1740
+ return this;
1741
+ };
1742
+ /**
1743
+ * line Promotions
1744
+ * @param basketDetails
1745
+ * @returns line Promotions
1746
+ */
1747
+ TransactionDocumentBuilder.prototype.linePromotion = function (basketDetails) {
1748
+ this.transactionDocument.basket.linePromotion = [];
1749
+ for (var index = 0; index < basketDetails.products.length; index++) {
1750
+ var element = basketDetails.products[index];
1751
+ if (element.linePromotions) {
1752
+ this.transactionDocument.basket.linePromotion.push(element.linePromotions);
1753
+ this.transactionDocument.basket.linePromotion = this.transactionDocument.basket.linePromotion.reduce(function (acc, val) {
1754
+ if (!acc.find(function (el) { return el.itemLineId === val.itemLineId; })) {
1755
+ acc.push(val);
1756
+ }
1757
+ return acc;
1758
+ }, []);
1759
+ }
1760
+ }
1761
+ return this;
1762
+ };
1763
+ /**
1764
+ * transaction Promotion
1765
+ * @param basketDetails
1766
+ * @returns transaction Promotion
1767
+ */
1768
+ TransactionDocumentBuilder.prototype.transactionPromotion = function (basketDetails) {
1769
+ if (basketDetails.transactionPromotion) {
1770
+ this.transactionDocument.basket.transactionPromotion =
1771
+ basketDetails.transactionPromotion;
1772
+ // for (let index = 0; index < basketDetails.TransactionDiscount.length; index++) {
1773
+ // this.transactionDocument.basket.transactionPromotion.push(element.linePromotions)
1774
+ // this.transactionDocument.basket.transactionPromotion = this.transactionDocument.basket.linePromotions.reduce((acc, val) => {
1775
+ // if (!acc.find(el => el.itemLineId === val.itemLineId)) {
1776
+ // acc.push(val);
1777
+ // }
1778
+ // return acc;
1779
+ // }, []);
1780
+ // }
1781
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotion", "this.transactionDocument.basket.transactionPromotion", this.transactionDocument.basket.transactionPromotion);
1782
+ }
1783
+ return this;
1784
+ };
1785
+ TransactionDocumentBuilder.prototype.transactionDiscount = function (basketDetails) {
1786
+ if (basketDetails.transactionDiscount) {
1787
+ this.transactionDocument.basket.transactionDiscount =
1788
+ basketDetails.transactionDiscount;
1789
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionDiscount", "transaction Discount", this.transactionDocument.basket.transactionDiscount);
1790
+ }
1791
+ return this;
1792
+ };
1793
+ /**
1794
+ * Payments details
1795
+ * @param paymentDetails
1796
+ * @returns
1797
+ */
1798
+ TransactionDocumentBuilder.prototype.paymentDetails = function (paymentDetails) {
1799
+ appLogger_service.AppLoggerService.logInfo(this.className, "paymentDetails", "payment details after transaction completed", paymentDetails);
1800
+ this.transactionDocument.paymentDetails = paymentDetails;
1801
+ return this;
1802
+ };
1803
+ /**
1804
+ * Payments details
1805
+ * @param paymentDetails
1806
+ * @returns
1807
+ */
1808
+ TransactionDocumentBuilder.prototype.splitPayment = function (splitPayment) {
1809
+ this.transactionDocument.splitPayment = splitPayment;
1810
+ return this;
1811
+ };
1812
+ /**
1813
+ * Payments details
1814
+ * @param paymentDetails
1815
+ * @returns
1816
+ */
1817
+ TransactionDocumentBuilder.prototype.isPaymentCompleted = function (isPaymentCompleted) {
1818
+ this.transactionDocument.isPaymentCompleted = isPaymentCompleted;
1819
+ return this;
1820
+ };
1821
+ /**
1822
+ * Bases currency
1823
+ * @param currency
1824
+ * @returns currency
1825
+ */
1826
+ TransactionDocumentBuilder.prototype.baseCurrency = function (currency) {
1827
+ this.transactionDocument.baseCurrency = currency;
1828
+ return this;
1829
+ };
1830
+ /**
1831
+ * gift option at
1832
+ * @returns at
1833
+ */
1834
+ TransactionDocumentBuilder.prototype.giftOption = function (gift) {
1835
+ appLogger_service.AppLoggerService.logDebug(this.className, "giftOption", "this.transactionDocument.giftoption", gift);
1836
+ if (gift) {
1837
+ this.transactionDocument.giftedReceipt = gift;
1838
+ }
1839
+ return this;
1840
+ };
1841
+ /**
1842
+
1843
+ /**
1844
+ * manual Discount
1845
+ * @param discountData
1846
+ * @returns
1847
+ */
1848
+ // manualDiscount(discountData : basketDiscount):TransactionDocumentBuilder {
1849
+ // let saleTotal = this.transactionDocument.basketSummary.basketTotal;
1850
+ // if(discountData.discountType =='Percent'){
1851
+ // this.transactionDocument.basketSummary.basketTotal = saleTotal-(saleTotal*(discountData.discountAmount/100));
1852
+ // discountData.discountAmount = -1*(saleTotal-this.transactionDocument.basketSummary.basketTotal);
1853
+ // }else {
1854
+ // this.transactionDocument.basketSummary.basketTotal =saleTotal-discountData.discountAmount;
1855
+ // discountData.discountAmount = -1*discountData.discountAmount;
1856
+ // }
1857
+ // this.transactionDocument.transactionDiscount.push(discountData);
1858
+ // return this;
1859
+ // }
1860
+ /**
1861
+ * Types transaction document builder
1862
+ * @param t
1863
+ * @returns type
1864
+ */
1865
+ TransactionDocumentBuilder.prototype.type = function (t) {
1866
+ this.transactionDocument.type = t;
1867
+ return this;
1868
+ };
1869
+ /**
1870
+ * Operations status
1871
+ * @param o
1872
+ * @returns status
1873
+ */
1874
+ TransactionDocumentBuilder.prototype.operationStatus = function (o) {
1875
+ this.transactionDocument.operationStatus = o;
1876
+ return this;
1877
+ };
1878
+ /**
1879
+ * Created at
1880
+ * @returns at
1881
+ */
1882
+ TransactionDocumentBuilder.prototype.createdAt = function () {
1883
+ var date = new Date();
1884
+ this.transactionDocument.createdAt = date.toISOString();
1885
+ this.transactionDocument.updatedAt = date.toISOString();
1886
+ return this;
1887
+ };
1888
+ /**
1889
+ * Updated at
1890
+ * @returns at
1891
+ */
1892
+ TransactionDocumentBuilder.prototype.updatedAt = function () {
1893
+ var date = new Date();
1894
+ this.transactionDocument.updatedAt = date.toISOString();
1895
+ return this;
1896
+ };
1897
+ /**
1898
+ * transsaction completion at
1899
+ * @returns transaction completion date
1900
+ */
1901
+ TransactionDocumentBuilder.prototype.transactionCompletedAt = function () {
1902
+ var date = new Date();
1903
+ this.transactionDocument.transCompletedAt = date.toISOString();
1904
+ return this;
1905
+ };
1906
+ /**
1907
+ * Builds transaction document builder
1908
+ * @returns build
1909
+ */
1910
+ TransactionDocumentBuilder.prototype.build = function () {
1911
+ return this.transactionDocument;
1912
+ };
1913
+ /**
1914
+ * Sales total in refund
1915
+ * @param saleTotal
1916
+ * @returns total in refund
1917
+ */
1918
+ TransactionDocumentBuilder.prototype.saleTotalInRefund = function (saleTotal) {
1919
+ this.transactionDocument.saleTotal = saleTotal;
1920
+ return this;
1921
+ };
1922
+ /**
1923
+ * Gets basket details
1924
+ * @returns basket details
1925
+ */
1926
+ TransactionDocumentBuilder.prototype.getBasketDetails = function () {
1927
+ var _this = this;
1928
+ appLogger_service.AppLoggerService.logInfo(this.className, "getBasketDetails", "Getting Basket for transactionDocument", this.transactionDocument);
1929
+ var basket = {
1930
+ subsidiaryId: this.transactionDocument.subsidiaryId,
1931
+ transactionDiscount: this.transactionDocument.basket.transactionDiscount,
1932
+ transactionPromotion: this.transactionDocument.basket.transactionPromotion,
1933
+ transactionId: this.transactionDocument.transactionId,
1934
+ offlineTransactionId: this.transactionDocument.offlineTransactionId,
1935
+ total: this.transactionDocument.basketSummary.basketTotal,
1936
+ basketTotal: this.transactionDocument.basketSummary.basketTotal,
1937
+ discountTotal: this.transactionDocument.basketSummary.discountTotal,
1938
+ saleTotal: this.transactionDocument.basketSummary.saleTotal,
1939
+ refundTotal: this.transactionDocument.basketSummary.refundTotal,
1940
+ quantity: this.transactionDocument.basketSummary.totalItems,
1941
+ products: [],
1942
+ baseCurrency: this.transactionDocument.baseCurrency,
1943
+ customer: this.transactionDocument.customer,
1944
+ };
1945
+ basket.products = [];
1946
+ this.transactionDocument.basket.products.forEach(function (product, index) {
1947
+ appLogger_service.AppLoggerService.logDebug(_this.className, JSON.stringify(product), "ebasket: basket detail update in basket");
1948
+ var p = {};
1949
+ p.SKU = product.SKU;
1950
+ p.barcode = product.barCode;
1951
+ p.barcodes = product.barcodes;
1952
+ p.description = product.description;
1953
+ p.imageUrls = product.imageUrls;
1954
+ p.currency = _this.transactionDocument.baseCurrency;
1955
+ p.totalLinePrice = product.totalLinePrice;
1956
+ p.itemLineId = Number(product.itemLineId);
1957
+ p.excludePromotion = product.excludePromotion;
1958
+ p.selectedPrice = product.price;
1959
+ p.quantity = product.quantity;
1960
+ p.total = product.totalLinePrice;
1961
+ p.selectedRRPPrice = product.selectedRRPPrice;
1962
+ p.fullfilmentId = product.fullfilmentId;
1963
+ p.fullfilmentLocationName = product.fullfilmentLocationName;
1964
+ p.deliveryGroup = product.deliveryGroup || "1";
1965
+ p.leadTime = product.leadTime;
1966
+ p.deliveryMethod = product.deliveryMethod || DELIVERY_METHODS.COLLECT_FROM_STORE.toString();
1967
+ if (p.fullfilmentId != _this.transactionDocument.storeId) {
1968
+ p.isWebOrder = true;
1969
+ }
1970
+ p.giftCard = product.giftCard;
1971
+ p.giftCardExpiryDate = product.giftCardExpiryDate;
1972
+ p.giftCardNumberIssued = product.giftCardNumberIssued;
1973
+ p.giftCardRecipientEmail = product.giftCardRecipientEmail;
1974
+ p.giftCardRecipientName = product.giftCardRecipientName;
1975
+ if (_this.transactionDocument.basket.lineDiscount &&
1976
+ _this.transactionDocument.basket.lineDiscount.length > 0) {
1977
+ _this.transactionDocument.basket.lineDiscount.forEach(function (lineDiscount) {
1978
+ if (product.itemLineId === lineDiscount.itemLineId.toString()) {
1979
+ p.lineDiscount = lineDiscount;
1980
+ p.total = lineDiscount.discountedLinePrice;
1981
+ }
1982
+ });
1983
+ }
1984
+ if (_this.transactionDocument.basket.linePromotion &&
1985
+ _this.transactionDocument.basket.linePromotion.length > 0) {
1986
+ _this.transactionDocument.basket.linePromotion.forEach(function (linePromotion) {
1987
+ if (product.itemLineId === linePromotion.itemLineId.toString()) {
1988
+ p.linePromotions = linePromotion;
1989
+ p.total = linePromotion.promotionLinePrice;
1990
+ }
1991
+ });
1992
+ }
1993
+ if (_this.transactionDocument.basket.taxBreakdown &&
1994
+ _this.transactionDocument.basket.taxBreakdown.taxLines.length > 0) {
1995
+ _this.transactionDocument.basket.taxBreakdown.taxLines.forEach(function (taxLine) {
1996
+ if (product.itemLineId && product.itemLineId === taxLine.itemLineId.toString()) {
1997
+ p.selectedVAT = taxLine.VAT;
1998
+ p.selectedVATCode = taxLine.VATCode;
1999
+ }
2000
+ });
2001
+ }
2002
+ if (_this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
2003
+ p.total = product.refundedTotal;
2004
+ }
2005
+ else if ((_this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND || TRANSACTION_TYPE.SALE_EXCHANGE) && product.refundedQuantity > 0) {
2006
+ p.refundedReasonDescription = product.refundedReasonDescription;
2007
+ p.refundedReason = product.refundedReason;
2008
+ if (!p.refundedReasonDescription) {
2009
+ p.refundedReasonDescription = p.refundedReason;
2010
+ }
2011
+ p.refundedQuantity = product.refundedQuantity;
2012
+ p.refundPromotionalQuantity = product.refundedPromotionalQuantity;
2013
+ p.refundedTotal = product.refundedTotal;
2014
+ p.total -= Math.abs(p.refundedTotal);
2015
+ p.isLastExchanged = product.isLastExchanged;
2016
+ }
2017
+ if (_this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
2018
+ if (p.total > 0) {
2019
+ p.total *= -1;
2020
+ }
2021
+ }
2022
+ basket.products.push(p);
2023
+ });
2024
+ basket = this.getTransactionDiscountAndTransactionPromotionPortion(basket);
2025
+ basket.total = (basket.basketTotal || 0) + this.getTotalDiscountWithTransactionDiscountsAndPromotions(basket);
2026
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND) {
2027
+ basket.quantity = this.getRefundedTotalWithQuantity(basket);
2028
+ }
2029
+ appLogger_service.AppLoggerService.logInfo(this.className, "getBasketDetails", "Basket created successfully", basket);
2030
+ return basket;
2031
+ };
2032
+ /**
2033
+ * Gets basket details
2034
+ * @returns refund basket details
2035
+ */
2036
+ // getRefundBasketDetails(): Basket {
2037
+ // let basket: Basket = {
2038
+ // subsidiaryId : this.transactionDocument.subsidiaryId,
2039
+ // transactionDiscount: this.transactionDocument.basket.transactionDiscount,
2040
+ // transactionPromotion: this.transactionDocument.basket.transactionPromotion,
2041
+ // transactionId: this.transactionDocument.transactionId,
2042
+ // total: this.transactionDocument.basketSummary.basketTotal,
2043
+ // basketTotal: this.transactionDocument.basketSummary.basketTotal,
2044
+ // discountTotal: this.transactionDocument.basketSummary.discountTotal,
2045
+ // saleTotal: this.transactionDocument.basketSummary.saleTotal,
2046
+ // quantity: this.transactionDocument.basketSummary.totalItems,
2047
+ // products: [],
2048
+ // baseCurrency: this.transactionDocument.baseCurrency,
2049
+ // customer: this.transactionDocument.customer,
2050
+ // };
2051
+ // basket.products = [] as Product[];
2052
+ // 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) => {
2053
+ // const p = {} as Product;
2054
+ // p.SKU = product.SKU;
2055
+ // p.barcode = product.barCode;
2056
+ // p.barcodes = product.barcodes;
2057
+ // p.description = product.description;
2058
+ // p.imageUrls = product.imageUrls;
2059
+ // p.currency = this.transactionDocument.baseCurrency;
2060
+ // p.totalLinePrice = product.totalLinePrice;
2061
+ // p.itemLineId = Number(product.itemLineId);
2062
+ // p.excludePromotion = product.excludePromotion;
2063
+ // p.selectedPrice = product.price;
2064
+ // p.quantity = product.quantity;
2065
+ // p.total = product.totalLinePrice;
2066
+ // p.selectedRRPPrice = product.selectedRRPPrice;
2067
+ // p.fullfilmentId = product.fullfilmentId;
2068
+ // p.fullfilmentLocationName = product.fullfilmentLocationName;
2069
+ // p.deliveryGroup = product.deliveryGroup || "1";
2070
+ // p.leadTime = product.leadTime;
2071
+ // p.deliveryMethod = product.deliveryMethod || DELIVERY_METHODS.COLLECT_FROM_STORE.toString();
2072
+ // p.giftCard = product.giftCard;
2073
+ // p.giftCardExpiryDate = product.giftCardExpiryDate;
2074
+ // p.giftCardNumberIssued = product.giftCardNumberIssued;
2075
+ // p.giftCardRecipientEmail = product.giftCardRecipientEmail;
2076
+ // p.giftCardRecipientName = product.giftCardRecipientName;
2077
+ // if(p.fullfilmentId != this.transactionDocument.storeId)
2078
+ // {
2079
+ // p.isWebOrder = true;
2080
+ // }
2081
+ // if (product.itemDiscounts) {
2082
+ // p.itemDiscounts = product.itemDiscounts as ItemDiscount;
2083
+ // }
2084
+ // // if(!p.itemDiscounts){
2085
+ // // AppLoggerService.logDebug(this.className, p.itemDiscounts);
2086
+ // // this.basketService.transactionDiscountAndPromotionProductortionCalculation(basket);
2087
+ // // }
2088
+ // p.refundPromotionalQuantity = product.refundedPromotionalQuantity ? product.refundedPromotionalQuantity : 0;
2089
+ // if (product.refundedQuantity) {
2090
+ // p.quantity = p.quantity - product.refundedQuantity;
2091
+ // p.totalLinePrice = (p.quantity * product.price);
2092
+ // p.total = p.totalLinePrice;
2093
+ // // p.refundPromotionalQuantity = product.refundedPromotionalQuantity;
2094
+ // p.refunded = product.refunded;
2095
+ // p.isLastExchanged = product.isLastExchanged;
2096
+ // }
2097
+ // if (product.exchange) {
2098
+ // p.exchange = product.exchange;
2099
+ // }
2100
+ // if (
2101
+ // this.transactionDocument.basket.lineDiscount &&
2102
+ // this.transactionDocument.basket.lineDiscount.length > 0
2103
+ // ) {
2104
+ // this.transactionDocument.basket.lineDiscount.forEach((lineDiscount: { itemLineId: { toString: () => any; }; discountedLinePrice: any; }) => {
2105
+ // if (product.itemLineId === lineDiscount.itemLineId.toString() && product.refundedQuantity > 0) {
2106
+ // p.lineDiscount = Object.assign({}, lineDiscount);
2107
+ // p.lineDiscount.discountedLinePrice = p.lineDiscount.unitPrice * p.quantity
2108
+ // p.lineDiscount.discountAmount = p.total - p.lineDiscount.discountedLinePrice
2109
+ // p.total = p.lineDiscount.discountedLinePrice;
2110
+ // } else if (product.itemLineId === lineDiscount.itemLineId.toString()) {
2111
+ // p.lineDiscount = lineDiscount;
2112
+ // p.total = lineDiscount.discountedLinePrice
2113
+ // }
2114
+ // });
2115
+ // }
2116
+ // if (
2117
+ // this.transactionDocument.basket.linePromotion &&
2118
+ // this.transactionDocument.basket.linePromotion.length > 0
2119
+ // ) {
2120
+ // this.transactionDocument.basket.linePromotion.forEach((linePromotion: { itemLineId: { toString: () => any; }; refunded: any; }) => {
2121
+ // if (product.itemLineId === linePromotion.itemLineId.toString() && !linePromotion.refunded) {
2122
+ // p.linePromotions = linePromotion;
2123
+ // p.total = p.linePromotions.promotionLinePrice;
2124
+ // p.total = p.total - (product.refundedTotal ? Math.abs(product.refundedTotal) : 0);
2125
+ // }
2126
+ // });
2127
+ // }
2128
+ // p.refundedQuantity = 0;
2129
+ // p.refundedTotal = 0;
2130
+ // if (
2131
+ // this.transactionDocument.basket.taxBreakdown &&
2132
+ // this.transactionDocument.basket.taxBreakdown.taxLines.length > 0
2133
+ // ) {
2134
+ // this.transactionDocument.basket.taxBreakdown.taxLines.forEach((taxLine: { itemLineId: { toString: () => any; }; VAT: any; VATCode: any; }) => {
2135
+ // if (product.itemLineId === taxLine.itemLineId.toString()) {
2136
+ // p.selectedVAT = taxLine.VAT;
2137
+ // p.selectedVATCode = taxLine.VATCode;
2138
+ // }
2139
+ // });
2140
+ // }
2141
+ // if (p.quantity > 0) {
2142
+ // basket.products.push(p);
2143
+ // }
2144
+ // });
2145
+ // // product.itemDiscounts
2146
+ // if (!basket.products[0].hasOwnProperty('itemDiscounts')) {
2147
+ // basket = this.getTransactionDiscountAndTransactionPromotionPortion(basket);
2148
+ // }
2149
+ // AppLoggerService.logDebug(this.className, "ebasket : TransactionDocumentBuilder :new created refunded basket", JSON.stringify(basket))
2150
+ // basket.quantity = basket.products.reduce(
2151
+ // (n: any, { quantity }: any) => n + quantity,
2152
+ // 0
2153
+ // );
2154
+ // basket.total = this.getTotalWithLineDiscountAndLinePromotionApplied(basket);
2155
+ // basket.basketTotal = basket.total;
2156
+ // basket.basketTotal = basket.basketTotal - this.getTotalDiscountWithTransactionDiscountsAndPromotions(basket);
2157
+ // AppLoggerService.logDebug(this.className,
2158
+ // "ebasket : TransactionDocumentBuilder : update Basket Total: after promotion :basketTotal",
2159
+ // basket.basketTotal
2160
+ // );
2161
+ // AppLoggerService.logDebug(this.className,
2162
+ // "e:basket :TransactionDocumentBuilder : basketDetails updated values",
2163
+ // JSON.stringify(basket)
2164
+ // );
2165
+ // return basket;
2166
+ // }
2167
+ TransactionDocumentBuilder.prototype.getTransactionDiscountAndTransactionPromotionPortion = function (basket) {
2168
+ var _this = this;
2169
+ if (basket.transactionDiscount &&
2170
+ basket.transactionDiscount.length > 0) {
2171
+ basket.transactionDiscount.forEach(function (discount) {
2172
+ if (!discount.itemLineIds) {
2173
+ discount.itemLineIds = basket.products.map(function (product) {
2174
+ return product.itemLineId;
2175
+ });
2176
+ }
2177
+ basket = _this.basketService.transactionDiscountProductPortionCalc(basket, discount);
2178
+ });
2179
+ }
2180
+ if (basket.transactionPromotion &&
2181
+ basket.transactionPromotion.length > 0) {
2182
+ basket.transactionPromotion.forEach(function (tPromotion) {
2183
+ if (!tPromotion.itemLineIds) {
2184
+ var filteredData = basket.products.filter(function (item) {
2185
+ return item.excludePromotion === false;
2186
+ });
2187
+ tPromotion.itemLineIds =
2188
+ filteredData.map(function (product) {
2189
+ return product.itemLineId;
2190
+ });
2191
+ }
2192
+ basket = _this.basketService.transactionPromotionProductPortionCalc(basket, tPromotion);
2193
+ });
2194
+ }
2195
+ return basket;
2196
+ };
2197
+ TransactionDocumentBuilder.prototype.getTotalDiscountWithTransactionDiscountsAndPromotions = function (basketDetails) {
2198
+ var discountTotal = 0;
2199
+ if (basketDetails.transactionPromotion &&
2200
+ basketDetails.transactionPromotion.length > 0) {
2201
+ discountTotal += basketDetails.transactionPromotion.reduce(function (n, _a) {
2202
+ var promotionAmount = _a.promotionAmount;
2203
+ return n + promotionAmount;
2204
+ }, 0);
2205
+ }
2206
+ if (basketDetails.transactionDiscount &&
2207
+ basketDetails.transactionDiscount.length > 0) {
2208
+ discountTotal += basketDetails.transactionDiscount.reduce(function (n, _a) {
2209
+ var discountAmount = _a.discountAmount;
2210
+ return n + discountAmount;
2211
+ }, 0);
2212
+ }
2213
+ appLogger_service.AppLoggerService.logDebug(this.className, "getTotalDiscountWithTransactionDiscountsAndPromotions", "Transaction discount Total:", discountTotal);
2214
+ return discountTotal;
2215
+ };
2216
+ TransactionDocumentBuilder.prototype.appendCurrencySymbol = function (currency, value) {
2217
+ // value=this.decimalpipe.transform(value,'1.2');
2218
+ if (value >= 0) {
2219
+ var returnval = currency + value;
2220
+ appLogger_service.AppLoggerService.logDebug(this.className, "appendCurrencySymbol", "add currency with value", returnval);
2221
+ return returnval;
2222
+ }
2223
+ else {
2224
+ var returnval = "-" + (currency + value * -1);
2225
+ appLogger_service.AppLoggerService.logDebug(this.className, "appendCurrencySymbol", "returnVal", returnval);
2226
+ return returnval;
2227
+ }
2228
+ };
2229
+ // /**
2230
+ // * Updates total refund
2231
+ // * @returns total refund
2232
+ // */
2233
+ // updateTotalRefund(): TransactionDocumentBuilder {
2234
+ // this.transactionDocument.basket.products.forEach((product) => {
2235
+ // product.refundedQuantity = product.quantity;
2236
+ // product.refundedTotal = product.totalLinePrice * -1;
2237
+ // AppLoggerService.logDebug(this.className,
2238
+ // "ebasket: Transaction price override :",
2239
+ // this.transactionDocument.basket.lineDiscount
2240
+ // );
2241
+ // if (
2242
+ // this.transactionDocument.basket.linePromotion &&
2243
+ // this.transactionDocument.basket.linePromotion.length > 0
2244
+ // ) {
2245
+ // this.transactionDocument.basket.linePromotion.forEach((linePromotion) => {
2246
+ // AppLoggerService.logDebug(this.className,
2247
+ // "Promotion: basket linePromotion : ",
2248
+ // this.transactionDocument.basket.linePromotion
2249
+ // );
2250
+ // AppLoggerService.logDebug(this.className,
2251
+ // "linePromotion.itemLineId.toString() : ",
2252
+ // linePromotion.itemLineId.toString()
2253
+ // );
2254
+ // AppLoggerService.logDebug(this.className,
2255
+ // "condition : " +
2256
+ // (product.itemLineId === linePromotion.itemLineId.toString())
2257
+ // );
2258
+ // if (product.itemLineId === linePromotion.itemLineId.toString()) {
2259
+ // product.refundedTotal =
2260
+ // linePromotion.promotionLinePrice * -1;
2261
+ // }
2262
+ // });
2263
+ // } else
2264
+ // if (
2265
+ // this.transactionDocument.basket.lineDiscount &&
2266
+ // this.transactionDocument.basket.lineDiscount.length > 0
2267
+ // ) {
2268
+ // this.transactionDocument.basket.lineDiscount.forEach((lineDiscount) => {
2269
+ // AppLoggerService.logDebug(this.className,
2270
+ // "product.itemLineId : " +
2271
+ // this.transactionDocument.basket.lineDiscount
2272
+ // );
2273
+ // AppLoggerService.logDebug(this.className,
2274
+ // "lineDiscount.itemLineId.toString() : " +
2275
+ // lineDiscount.itemLineId.toString()
2276
+ // );
2277
+ // AppLoggerService.logDebug(this.className,
2278
+ // "condition : " +
2279
+ // (product.itemLineId === lineDiscount.itemLineId.toString())
2280
+ // );
2281
+ // if (product.itemLineId === lineDiscount.itemLineId.toString()) {
2282
+ // product.refundedTotal = lineDiscount.unitPrice * product.refundedQuantity * -1;
2283
+ // }
2284
+ // });
2285
+ // }
2286
+ // AppLoggerService.logDebug(this.className, "Product description :" + product.description);
2287
+ // AppLoggerService.logDebug(this.className, "Product total :" + product.refundedTotal);
2288
+ // // product.displayrefundedamount=this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency],product.refundedTotal);
2289
+ // // AppLoggerService.logDebug(this.className, product.displayrefundedamount,"displayrefundedamount");
2290
+ // product.refunded = true;
2291
+ // });
2292
+ // const baskettotal = (this.transactionDocument.basketSummary.basketTotal *= -1);
2293
+ // // this.transactionDocument.basketSummary.displaybaskettotal=this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency], baskettotal);
2294
+ // const saletotal = (this.transactionDocument.basketSummary.saleTotal *= -1);
2295
+ // // this.transactionDocument.basketSummary.displaysaletotal = this.appendCurrencySymbol(CURRENCY[this.transactionDocument.baseCurrency], saletotal);
2296
+ // (this.transactionDocument.basketSummary.VATTotal *= -1);
2297
+ // return this;
2298
+ // }
2299
+ /**
2300
+ * Sale Total
2301
+ * @param basketDetails
2302
+ * @returns Sale Total
2303
+ */
2304
+ TransactionDocumentBuilder.prototype.updateSaleTotal = function (basketDetails) {
2305
+ var saleTotal = basketDetails.products.reduce(function (n, _a) {
2306
+ var totalLinePrice = _a.totalLinePrice;
2307
+ return n + totalLinePrice;
2308
+ }, 0);
2309
+ return saleTotal;
2310
+ };
2311
+ TransactionDocumentBuilder.prototype.getTotalWithLineDiscountAndLinePromotionApplied = function (basketDetails) {
2312
+ var e_1, _a;
2313
+ var saletotal = 0.0;
2314
+ try {
2315
+ for (var _b = __values(basketDetails.products), _c = _b.next(); !_c.done; _c = _b.next()) {
2316
+ var product = _c.value;
2317
+ // if (product.linePromotions) {
2318
+ // saletotal += product.linePromotions.promotionLinePrice;
2319
+ // } else if (
2320
+ // product.lineDiscount &&
2321
+ // !product.linePromotions
2322
+ // ) {
2323
+ // saletotal +=
2324
+ // product.quantity * Number(product.lineDiscount.unitPrice.toFixed(2));
2325
+ // } else {
2326
+ // saletotal +=
2327
+ // product.quantity * Number(product.selectedPrice.toFixed(2));
2328
+ // }
2329
+ saletotal += product.total;
2330
+ appLogger_service.AppLoggerService.logDebug(this.className, "getTotalWithLineDiscountAndLinePromotionApplied", "e-basket:update product Total:" + saletotal, product);
2331
+ }
2332
+ }
2333
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2334
+ finally {
2335
+ try {
2336
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2337
+ }
2338
+ finally { if (e_1) throw e_1.error; }
2339
+ }
2340
+ return saletotal;
2341
+ };
2342
+ TransactionDocumentBuilder.prototype.getRefundedTotalWithQuantity = function (basketDetails) {
2343
+ var quantity = 0;
2344
+ for (var index = 0; index < basketDetails.products.length; index++) {
2345
+ var product = basketDetails.products[index];
2346
+ if (!product.refundedReasonDescription) {
2347
+ quantity = quantity + product.quantity;
2348
+ }
2349
+ else {
2350
+ quantity = quantity + (product.quantity - product.refundedQuantity);
2351
+ // basketDetails.total = basketDetails.total + product.refundedTotal;
2352
+ }
2353
+ }
2354
+ return quantity;
2355
+ };
2356
+ /**
2357
+ * Discount Total
2358
+ * @returns Discount Total
2359
+ */
2360
+ TransactionDocumentBuilder.prototype.updateDiscountTotal = function () {
2361
+ var refundTotal = this.transactionDocument.basketSummary.refundTotal ? this.transactionDocument.basketSummary.refundTotal : 0;
2362
+ appLogger_service.AppLoggerService.logInfo(this.className, "updateDiscountTotal", "refundTotal: " + refundTotal + " this.transactionDocument.basketSummary: " + this.transactionDocument.basketSummary);
2363
+ var discountTotal = Math.abs(Math.abs(this.transactionDocument.basketSummary.saleTotal) -
2364
+ (Math.abs(this.transactionDocument.basketSummary.basketTotal) + Math.abs(refundTotal)));
2365
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateDiscountTotal", "discountTotal", discountTotal);
2366
+ return Number(discountTotal.toFixed(2));
2367
+ };
2368
+ TransactionDocumentBuilder.prototype.updateReasonCode = function (reasonCode) {
2369
+ this.transactionDocument.reasonCode = reasonCode.code;
2370
+ this.transactionDocument.reasonDescription = reasonCode.name;
2371
+ return this;
2372
+ };
2373
+ TransactionDocumentBuilder.prototype.updateManagerOverride = function (useroverride) {
2374
+ this.transactionDocument.override = useroverride;
2375
+ return this;
2376
+ };
2377
+ TransactionDocumentBuilder.prototype.updateUserID = function (userID) {
2378
+ this.transactionDocument.userId = userID;
2379
+ return this;
2380
+ };
2381
+ TransactionDocumentBuilder.prototype.updateUserName = function (name) {
2382
+ this.transactionDocument.userName = name;
2383
+ return this;
2384
+ };
2385
+ TransactionDocumentBuilder.prototype.addCustomerDetails = function (customerDetail) {
2386
+ this.transactionDocument.customer = customerDetail;
2387
+ return this;
2388
+ };
2389
+ TransactionDocumentBuilder.prototype.updateTaxBreakdown = function (basketDetails) {
2390
+ var _this = this;
2391
+ // let transactionDiscountTotal = 0;
2392
+ var taxBreakdown = {
2393
+ taxLines: [],
2394
+ totalTaxableAmount: 0,
2395
+ };
2396
+ // if (this.transactionDocument.basket.transactionDiscount && this.transactionDocument.basket.transactionDiscount.length > 0) {
2397
+ // this.transactionDocument.basket.transactionDiscount.forEach((discount) => {
2398
+ // transactionDiscountTotal += discount.discountAmount;
2399
+ // });
2400
+ // }
2401
+ // if (this.transactionDocument.basket.transactionPromotion && this.transactionDocument.basket.transactionPromotion.length > 0) {
2402
+ // this.transactionDocument.basket.transactionPromotion.forEach(
2403
+ // (promotion) => {
2404
+ // transactionDiscountTotal += promotion.promotionAmount;
2405
+ // }
2406
+ // );
2407
+ // }
2408
+ basketDetails.products.forEach(function (product) {
2409
+ var taxLine = {
2410
+ itemLineId: product.itemLineId,
2411
+ VAT: product.selectedVAT ? product.selectedVAT : 0,
2412
+ VATCode: product.selectedVATCode,
2413
+ taxLineTotal: 0,
2414
+ taxableAmount: product.total,
2415
+ PreTax: 0
2416
+ };
2417
+ appLogger_service.AppLoggerService.logInfo(_this.className, "updateTaxBreakdown", "item line ID :, " + product.itemLineId + ",\n \"tax line :\", " + taxLine);
2418
+ // step 1
2419
+ // if Transaction Discount and/or promotion applied, find net selling price of each product as taxableamount
2420
+ // if (transactionDiscountTotal > 0) {
2421
+ product = _this.basketService.validateProductItemDiscount(product);
2422
+ var productContributionInTotal = product.itemDiscounts.trnDiscountsPortion +
2423
+ product.itemDiscounts.trnPromotionsPortion -
2424
+ product.itemDiscounts.refundPortion;
2425
+ // tp+td-rp;
2426
+ appLogger_service.AppLoggerService.logInfo(_this.className, "updateTaxBreakdown", "item line ID , " + product.itemLineId + ",\n \"contribution :\", " + productContributionInTotal);
2427
+ // calculate net selling price after applying transaction discount as per product contribution
2428
+ taxLine.taxableAmount -= productContributionInTotal;
2429
+ // }
2430
+ //step 2 - find pre tax
2431
+ taxLine.PreTax = _this.numberUtilService.trimTo2Decimal2((taxLine.taxableAmount * 100) / (100 + taxLine.VAT));
2432
+ //step 3 - Update taxbreakdown
2433
+ taxBreakdown.totalTaxableAmount += taxLine.taxableAmount;
2434
+ taxLine.taxableAmount = _this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount);
2435
+ // step 4 - update tax Line total
2436
+ taxLine.taxLineTotal = _this.numberUtilService.trimTo2Decimal2(taxLine.taxableAmount - taxLine.PreTax);
2437
+ taxBreakdown.taxLines.push(taxLine);
2438
+ });
2439
+ taxBreakdown.totalTaxableAmount = this.numberUtilService.trimTo2Decimal2(taxBreakdown.totalTaxableAmount);
2440
+ this.transactionDocument.basket.taxBreakdown = taxBreakdown;
2441
+ return this;
2442
+ };
2443
+ TransactionDocumentBuilder.prototype.updateTotalTaxSummary = function () {
2444
+ var _this = this;
2445
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateTotalTaxSummary", "Total Tax Summery Request :", this.transactionDocument.basket.taxBreakdown);
2446
+ var totalTaxSummaryArray = [];
2447
+ var totalTaxSummaryGroup = [];
2448
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateTotalTaxSummary", "Tax Lines for Total Tax Summery :", this.transactionDocument.basket.taxBreakdown.taxLines);
2449
+ this.transactionDocument.basket.taxBreakdown.taxLines.forEach(function (element) {
2450
+ var TaxSummary = {
2451
+ VATCode: "",
2452
+ VAT: -12345,
2453
+ PreTaxSum: 0,
2454
+ TaxSum: 0,
2455
+ TXrateSum: 0
2456
+ };
2457
+ TaxSummary.VATCode = element.VATCode;
2458
+ TaxSummary.VAT = element.VAT;
2459
+ TaxSummary.PreTaxSum = _this.numberUtilService.trimTo2Decimal2(element.PreTax);
2460
+ TaxSummary.TaxSum = _this.numberUtilService.trimTo2Decimal2(element.taxLineTotal);
2461
+ TaxSummary.TXrateSum = _this.numberUtilService.trimTo2Decimal2(TaxSummary.PreTaxSum + TaxSummary.TaxSum);
2462
+ totalTaxSummaryArray.push(TaxSummary);
2463
+ });
2464
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateTotalTaxSummary", "Total Tax Summery Without Grouped : ", totalTaxSummaryArray);
2465
+ totalTaxSummaryGroup = totalTaxSummaryArray.reduce(function (preparedArray, currentObj) {
2466
+ var ind = preparedArray.findIndex(function (x) { return x.VAT === currentObj.VAT; });
2467
+ if (ind === -1) {
2468
+ preparedArray.push(currentObj);
2469
+ }
2470
+ else {
2471
+ preparedArray[ind].VATCode = currentObj.VATCode;
2472
+ preparedArray[ind].VAT = currentObj.VAT;
2473
+ preparedArray[ind].PreTaxSum += currentObj.PreTaxSum;
2474
+ preparedArray[ind].TaxSum += currentObj.TaxSum;
2475
+ preparedArray[ind].TXrateSum += currentObj.TXrateSum;
2476
+ }
2477
+ return preparedArray;
2478
+ }, []);
2479
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateTotalTaxSummary", "Total Tax Summer Group :", totalTaxSummaryGroup);
2480
+ this.transactionDocument.basket.totalTaxSummary = totalTaxSummaryGroup;
2481
+ return this;
2482
+ };
2483
+ /**
2484
+ * TransactionId
2485
+ * @returns OriginalTransactionId
2486
+ */
2487
+ TransactionDocumentBuilder.prototype.addOriginalTransId = function (tranDoc) {
2488
+ if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND || this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND || this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
2489
+ this.transactionDocument.originalTransId = tranDoc.transactionId;
2490
+ if (tranDoc.apiResponse && tranDoc.apiResponse.internalId) {
2491
+ this.transactionDocument.originalExternalId = tranDoc.apiResponse.internalId.toString();
2492
+ }
2493
+ }
2494
+ return this;
2495
+ };
2496
+ /**
2497
+ * unreferenced Refund
2498
+ * @returns boolean value
2499
+ */
2500
+ TransactionDocumentBuilder.prototype.addUnreferencedRefund = function () {
2501
+ this.transactionDocument.unreferencedRefund = true;
2502
+ return this;
2503
+ };
2504
+ TransactionDocumentBuilder.prototype.getRefundTotal = function () {
2505
+ var totalRefund = 0;
2506
+ for (var index = 0; index < this.transactionDocument.basket.products.length; index++) {
2507
+ var product = this.transactionDocument.basket.products[index];
2508
+ if (product.refundedTotal) {
2509
+ totalRefund = totalRefund + product.refundedTotal;
2510
+ }
2511
+ appLogger_service.AppLoggerService.logDebug(this.className, "getRefundTotal", "totalRefund", totalRefund);
2512
+ }
2513
+ return totalRefund;
2514
+ };
2515
+ TransactionDocumentBuilder.prototype.docId = function (docId) {
2516
+ this.transactionDocument.id = docId;
2517
+ return this;
2518
+ };
2519
+ return TransactionDocumentBuilder;
2520
+ }());
2521
+
2522
+ var RJMapperBuilderClass = /** @class */ (function () {
2523
+ function RJMapperBuilderClass(transactionDoc) {
2524
+ this.className = "RJMapperBuilderClass";
2525
+ this.itemCount = 0;
2526
+ this.largestNumber = 0;
2527
+ this.rjObject = {};
2528
+ if (transactionDoc) {
2529
+ this.transactionDocument = transactionDoc;
2530
+ }
2531
+ else {
2532
+ this.transactionDocument = {
2533
+ transactionId: "",
2534
+ offlineTransactionId: "",
2535
+ transactionRef: "",
2536
+ dateTime: "",
2537
+ orgCode: "",
2538
+ storeId: "",
2539
+ storeNodeId: "",
2540
+ storeNodeStructure: "",
2541
+ deviceId: "",
2542
+ terminalId: "",
2543
+ userId: "",
2544
+ initiatingModule: "eBasket",
2545
+ export: false,
2546
+ basket: {},
2547
+ basketSummary: {},
2548
+ baseCurrency: "",
2549
+ type: "",
2550
+ operationStatus: "",
2551
+ createdAt: "",
2552
+ updatedAt: "",
2553
+ id: "",
2554
+ currentTransactionDetails: {},
2555
+ saleTotal: 0,
2556
+ };
2557
+ }
2558
+ this.initilizeItemCount();
2559
+ this.setLineNumberForProducts();
2560
+ this.createdAt = this.getDate(this.transactionDocument.createdAt);
2561
+ this.updatedAt = this.getDate(this.transactionDocument.updatedAt);
2562
+ }
2563
+ RJMapperBuilderClass.prototype.getPosbasketInfo = function () {
2564
+ this.rjObject['Keyword'] = this.generateKeyword();
2565
+ this.rjObject['ID'] = this.generateId(this.createdAt);
2566
+ this.rjObject['XMLSchemaVersion'] = '2';
2567
+ this.rjObject['LastUpdated'] = this.updatedAt;
2568
+ this.rjObject['MajorVersion'] = this.majorVersion;
2569
+ this.rjObject['MinorVersion'] = this.minorVersion;
2570
+ this.rjObject['ManifestVersion'] = this.manifestVersion;
2571
+ this.rjObject['DatabaseSchemaVersion'] = this.databaseSchemaVersion;
2572
+ this.rjObject['BasketType'] = this.basketType;
2573
+ this.rjObject['State'] = this.getState();
2574
+ this.rjObject['ExternalState'] = this.externalState;
2575
+ return this;
2576
+ };
2577
+ RJMapperBuilderClass.prototype.getheaderInfo = function () {
2578
+ this.rjObject['Header'] = {};
2579
+ this.rjObject['Header'].TimeZoneOffset = this.convertToString(this.generateTimezoneoffset(this.transactionDocument.createdAt));
2580
+ this.rjObject['Header'].DateTimeCreated = this.createdAt;
2581
+ this.rjObject['Header'].OriginatedBy = {};
2582
+ this.rjObject['Header'].OriginatedBy.DeviceID = this.deviceId;
2583
+ this.rjObject['Header'].OriginatedBy.CashierID = this.cashierId;
2584
+ this.rjObject['Header'].OriginatedBy.CompanyID = this.companyId;
2585
+ this.rjObject['Header'].OriginatedBy.StoreID = this.transactionDocument.storeId;
2586
+ this.rjObject['Header'].OriginatedBy.BranchID = this.branchId;
2587
+ this.rjObject['Header'].OriginatedBy.TerminalNumber = this.terminalNumber;
2588
+ this.rjObject['Header'].OriginatedBy.TransactionNumber = this.transactionNumber;
2589
+ this.rjObject['Header'].TaxMethodID = this.taxMethodId;
2590
+ this.rjObject['Header'].DynamicStockLookup = this.generateDynamicStockLookUp();
2591
+ this.rjObject['Header'].BasketLanguageID = this.basketLanguageId; //todo
2592
+ this.rjObject['Header'].BasketCountryID = this.basketCountryId; //todo
2593
+ this.rjObject['Header'].BasketCurrencyID = this.transactionDocument.baseCurrency;
2594
+ this.rjObject['Header'].TradingRegionID = this.tradingRegionId;
2595
+ this.rjObject['Header'].Eurozone = " "; //unknown
2596
+ this.rjObject['Header'].EuroBaseExchangeRate = ""; //unknown
2597
+ this.rjObject['Header'].PrintableName = this.transactionDocument.userName; //unknown
2598
+ return this;
2599
+ };
2600
+ RJMapperBuilderClass.prototype.rjMapper = function () {
2601
+ var _this = this;
2602
+ var transactionDiscount = [];
2603
+ if (this.transactionDocument.basket.transactionDiscount && this.transactionDocument.basket.transactionDiscount.length > 0) {
2604
+ transactionDiscount = this.transactionDocument.basket.transactionDiscount;
2605
+ }
2606
+ if (this.transactionDocument.type === TRANSACTION_TYPE.SALE) {
2607
+ this.rjObject['ProductSale'] = [];
2608
+ this.rjObject['ModifierItem'] = [];
2609
+ this.transactionDocument.basket.products.forEach(function (element) {
2610
+ var lineDiscount = [];
2611
+ if (_this.transactionDocument.basket.lineDiscount && _this.transactionDocument.basket.lineDiscount.length > 0) {
2612
+ lineDiscount = _this.transactionDocument.basket.lineDiscount.filter(function (x) { return x.itemLineId === element.itemLineId; });
2613
+ if (lineDiscount.length > 0) {
2614
+ var index = _this.transactionDocument.basket.lineDiscount.indexOf(lineDiscount[0]);
2615
+ if (index > -1) {
2616
+ _this.transactionDocument.basket.lineDiscount.splice(index, 1);
2617
+ }
2618
+ }
2619
+ }
2620
+ var data = _this.addProduct(element, (lineDiscount.length > 0 ? lineDiscount[0] : null), (transactionDiscount.length > 0 ? transactionDiscount : null));
2621
+ _this.rjObject['ProductSale'].push(data);
2622
+ _this.getModifierItem(lineDiscount.length > 0 ? lineDiscount[0] : null, element.itemLineId);
2623
+ });
2624
+ var transactionPromotion = [];
2625
+ if (this.transactionDocument.basket.transactionPromotion && this.transactionDocument.basket.transactionPromotion.length > 0) {
2626
+ transactionPromotion = this.transactionDocument.basket.transactionPromotion;
2627
+ this.getTransactionPromotion(transactionPromotion);
2628
+ }
2629
+ }
2630
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.REFUND) {
2631
+ this.rjObject['ProductReturn'] = [];
2632
+ this.rjObject['ModifierItem'] = [];
2633
+ this.transactionDocument.basket.products.forEach(function (element) {
2634
+ var data = _this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null), (transactionDiscount.length > 0 ? transactionDiscount : null));
2635
+ _this.rjObject['ProductReturn'].push(data);
2636
+ _this.getModifierItem(element.lineDiscount, element.itemLineId);
2637
+ });
2638
+ }
2639
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_REFUND) {
2640
+ this.rjObject['ProductReturn'] = [];
2641
+ this.rjObject['ModifierItem'] = [];
2642
+ var transactionDoc = new TransactionDocumentBuilder().basket(this.transactionDocument.currentTransactionDetails).build();
2643
+ transactionDoc.basket.products.forEach(function (element) {
2644
+ var data = _this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null), (transactionDiscount.length > 0 ? transactionDiscount : null));
2645
+ var obj = {
2646
+ "OriginalReceiptSupplied": 0,
2647
+ "OriginalBranchID": 0,
2648
+ "OriginalTerminalNumber": 0,
2649
+ "OriginalTransactionNumber": 0,
2650
+ "OriginalCashierNumber": 0
2651
+ };
2652
+ data['Return'] = Object.assign(Object.assign({}, data['Return']), obj);
2653
+ _this.rjObject['ProductReturn'].push(data);
2654
+ _this.getModifierItem(element.lineDiscount, element.itemLineId);
2655
+ });
2656
+ }
2657
+ else if (this.transactionDocument.type === TRANSACTION_TYPE.SALE_EXCHANGE) {
2658
+ this.rjObject['ProductReturn'] = [];
2659
+ this.rjObject['ProductSale'] = [];
2660
+ this.rjObject['ModifierItem'] = [];
2661
+ var transactionDoc = new TransactionDocumentBuilder().basket(this.transactionDocument.currentTransactionDetails).build();
2662
+ transactionDoc.basket.products.forEach(function (element) {
2663
+ if (element.refundedQuantity > 0) {
2664
+ var returnProduct = _this.returnProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null), (transactionDiscount.length > 0 ? transactionDiscount : null));
2665
+ var obj = {
2666
+ "OriginalReceiptSupplied": 0,
2667
+ "OriginalBranchID": 0,
2668
+ "OriginalTerminalNumber": 0,
2669
+ "OriginalTransactionNumber": 0,
2670
+ "OriginalCashierNumber": 0
2671
+ };
2672
+ returnProduct['Return'] = Object.assign(Object.assign({}, returnProduct['Return']), obj);
2673
+ _this.rjObject['ProductReturn'].push(returnProduct);
2674
+ }
2675
+ else {
2676
+ var addProduct = _this.addProduct(element, (element.hasOwnProperty('lineDiscount') ? element.lineDiscount : null), (transactionDiscount.length > 0 ? transactionDiscount : null));
2677
+ _this.rjObject['ProductSale'].push(addProduct);
2678
+ }
2679
+ _this.getModifierItem(element.lineDiscount, element.itemLineId);
2680
+ });
2681
+ }
2682
+ return this;
2683
+ };
2684
+ RJMapperBuilderClass.prototype.getBasketDiscount = function () {
2685
+ var _this = this;
2686
+ if (!this.transactionDocument.basket.transactionDiscount)
2687
+ return this;
2688
+ this.rjObject['BasketDiscount'] = [];
2689
+ this.transactionDocument.basket.transactionDiscount.forEach(function (element) {
2690
+ var obj = {};
2691
+ obj['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2692
+ obj['DeviceID'] = _this.deviceId;
2693
+ obj['DateTimeCreated'] = _this.updatedAt;
2694
+ obj['NetValue'] = _this.convertToString(element.discountAmount * -1);
2695
+ obj['EffectiveNetValue'] = _this.convertToString(element.discountAmount * -1);
2696
+ obj['Description'] = element.reasonDisplayText;
2697
+ obj['UserID'] = _this.transactionDocument.userName;
2698
+ obj['ReasonCodeID'] = element.reasonCode;
2699
+ obj['DiscountType'] = _this.convertToString(element.discountType.toUpperCase() == DISCOUNTTYPE.PERCENT.toUpperCase() ? 0 : 1);
2700
+ obj['RoundingRule'] = _this.convertToString(2);
2701
+ obj['ModifiedLineNumber'] = element.itemLineIds;
2702
+ obj['LineNumber'] = _this.convertToString(_this.generateLineNumber());
2703
+ obj['DiscountedValue'] = _this.transactionDocument.basketSummary.basketTotal + _this.transactionDocument.basketSummary.discountTotal;
2704
+ if (element.discountType.toUpperCase() == DISCOUNTTYPE.PERCENT.toUpperCase()) {
2705
+ obj['DiscountPercentage'] = _this.convertToString((element.discountAmount / _this.transactionDocument.basketSummary.basketTotal).toFixed(1));
2706
+ }
2707
+ if (_this.transactionDocument.type === 'REFUND') {
2708
+ obj['NetValue'] = _this.convertToString(element.discountAmount < 0 ? -element.discountAmount : element.discountAmount);
2709
+ obj['EffectiveNetValue'] = _this.convertToString(element.discountAmount < 0 ? -element.discountAmount : element.discountAmount);
2710
+ }
2711
+ _this.rjObject['BasketDiscount'].push(obj);
2712
+ });
2713
+ return this;
2714
+ };
2715
+ RJMapperBuilderClass.prototype.getModifierItem = function (data, lineNo) {
2716
+ if (data && lineNo) {
2717
+ var obj = {};
2718
+ obj.XMLSchemaVersion = 1;
2719
+ obj.LineNumber = this.generateLineNumber();
2720
+ obj.NetValue = 0;
2721
+ obj.EffectiveNetValue = 0;
2722
+ obj.Description = data.percentageDiscountReasonName ? data.percentageDiscountReasonName : data.priceOverrideReasonName;
2723
+ obj.DeviceID = this.deviceId;
2724
+ obj.UserID = this.transactionDocument.userName;
2725
+ obj.DateTimeCreated = this.updatedAt;
2726
+ obj.AuthorisingUserID = this.transactionDocument.userName;
2727
+ obj.ReasonCodeID = data.percentageDiscountReasonCode ? data.percentageDiscountReasonCode : data.priceOverrideReasonCode;
2728
+ obj.ModifiedLineNumber = lineNo;
2729
+ obj.ModifiedIndex = 1;
2730
+ this.rjObject['ModifierItem'].push(obj);
2731
+ }
2732
+ };
2733
+ RJMapperBuilderClass.prototype.getTrailerInfo = function () {
2734
+ var _this = this;
2735
+ this.rjObject['Trailer'] = {};
2736
+ this.rjObject.Trailer.DateTimeCompleted = this.updatedAt;
2737
+ this.rjObject.Trailer.CompletedBy = {};
2738
+ this.rjObject.Trailer.CompletedBy.DeviceID = this.deviceId;
2739
+ this.rjObject.Trailer.CompletedBy.CashierID = this.cashierId;
2740
+ this.rjObject.Trailer.CompletedBy.StoreID = this.transactionDocument.storeId;
2741
+ this.rjObject.Trailer.CompletedBy.BranchID = this.branchId;
2742
+ this.rjObject.Trailer.CompletedBy.TerminalNumber = this.terminalNumber;
2743
+ this.rjObject.Trailer.CompletedBy.TransactionNumber = this.transactionNumber;
2744
+ this.rjObject.Trailer.Total = this.convertToString(this.transactionDocument.basketSummary.basketTotal * 100);
2745
+ this.rjObject.Trailer.ItemCount = this.itemCount; //gives total count for product
2746
+ this.rjObject.Trailer.ItemQuantity = this.convertToString(this.transactionDocument.basketSummary.totalItems);
2747
+ this.rjObject.Trailer.NetItemQuantity = this.convertToString(this.transactionDocument.basketSummary.totalItems);
2748
+ this.rjObject.Trailer.TaxTotal = this.convertToString(this.removeDecimal(this.transactionDocument.basketSummary.VATTotal));
2749
+ this.rjObject.Trailer.SequenceDeviceID = this.deviceId;
2750
+ this.rjObject.Trailer.SequenceNumber = 'snsn'; //static for now
2751
+ this.rjObject['Trailer']['TaxItem'] = [];
2752
+ this.transactionDocument.basket.taxBreakdown.taxLines.forEach(function (element) {
2753
+ var obj = {};
2754
+ obj['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2755
+ obj['TaxRate'] = _this.convertToString(element.VATCode);
2756
+ obj['TaxableTotal'] = _this.convertToString(_this.removeDecimal(element.taxableAmount));
2757
+ obj['TaxTotal'] = _this.convertToString(_this.removeDecimal(_this.removeDecimal(element.taxLineTotal)));
2758
+ obj['TaxDescription'] = _this.convertToString(element.VATCode);
2759
+ obj['TaxIncluded'] = '1';
2760
+ obj['TaxPercentage'] = _this.addDecimal(element.VAT.toFixed(2)).toFixed(2);
2761
+ _this.rjObject['Trailer']['TaxItem'].push(obj);
2762
+ });
2763
+ if (this.transactionDocument.basket.linePromotion.length > 0 || this.transactionDocument.basket.linePromotion.length > 0) {
2764
+ this.rjObject['Trailer']['PromotionItem'] = [];
2765
+ if (this.transactionDocument.basket.linePromotion.length > 0) {
2766
+ this.transactionDocument.basket.linePromotion.forEach(function (element) {
2767
+ var obj = {};
2768
+ obj['PromotionID'] = element.promotionId;
2769
+ obj['PromotionSaving'] = element.promotionAmount < 0 ? element.promotionAmount : -element.promotionAmount;
2770
+ obj['PromotionQuantity'] = "1";
2771
+ obj['PromotionDescription'] = element.displayText;
2772
+ obj['PromotionHit'] = {};
2773
+ obj['PromotionHit']['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2774
+ obj['PromotionHit']['HitNumber'] = "1";
2775
+ obj['PromotionHit']['HitQuantity'] = "1";
2776
+ obj['PromotionHit']['HitSaving'] = element.promotionAmount < 0 ? element.promotionAmount : -element.promotionAmount;
2777
+ obj['PromotionHit']['PromotionTrigger'] = {};
2778
+ var product = _this.transactionDocument.basket.products.find(function (item) { return item.itemLineId == element.itemLineId; });
2779
+ obj['PromotionHit']['PromotionTrigger']['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2780
+ obj['PromotionHit']['PromotionTrigger']['ProductID'] = product.SKU;
2781
+ obj['PromotionHit']['PromotionTrigger']['UnitValue'] = _this.convertToString(element.promotionLinePrice / product.quantity);
2782
+ obj['PromotionHit']['PromotionTrigger']['LineNumber'] = _this.getNumber(product.SKU);
2783
+ obj['PromotionHit']['PromotionTrigger']['Quantity'] = _this.convertToString(product.quantity.toFixed(1));
2784
+ obj['PromotionHit']['PromotionTrigger']['TaxCode'] = _this.transactionDocument.basket.taxBreakdown.taxLines.find(function (item) { return item.itemLineId == element.itemLineId; }).VATCode;
2785
+ _this.rjObject['Trailer']['PromotionItem'].push(obj);
2786
+ });
2787
+ }
2788
+ if (this.transactionDocument.basket.transactionPromotion.length > 0) {
2789
+ this.transactionDocument.basket.transactionPromotion.forEach(function (element) {
2790
+ var obj = {};
2791
+ obj['PromotionID'] = element.promotionId;
2792
+ obj['PromotionSaving'] = element.promotionAmount < 0 ? element.promotionAmount : -element.promotionAmount;
2793
+ obj['PromotionQuantity'] = "1";
2794
+ obj['PromotionDescription'] = element.displayText;
2795
+ obj['PromotionHit'] = {};
2796
+ obj['PromotionHit']['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2797
+ obj['PromotionHit']['HitNumber'] = "1";
2798
+ obj['PromotionHit']['HitQuantity'] = "1";
2799
+ obj['PromotionHit']['HitSaving'] = element.promotionAmount < 0 ? element.promotionAmount : -element.promotionAmount;
2800
+ obj['PromotionHit']['PromotionTrigger'] = [];
2801
+ _this.transactionDocument.basket.products.forEach(function (product) {
2802
+ var promotionTrigger = {};
2803
+ element.itemLineIds.forEach(function (itemLineId) {
2804
+ if (JSON.stringify(itemLineId) === product.itemLineId) {
2805
+ promotionTrigger['XMLSchemaVersion'] = _this.xmlSchemaVersion;
2806
+ promotionTrigger['ProductID'] = product.SKU;
2807
+ promotionTrigger['UnitValue'] = _this.convertToString(element.promotionLinePrice / product.quantity);
2808
+ promotionTrigger['LineNumber'] = _this.getNumber(product.SKU);
2809
+ promotionTrigger['Quantity'] = _this.convertToString(product.quantity);
2810
+ promotionTrigger['TaxCode'] = _this.transactionDocument.basket.taxBreakdown.taxLines.find(function (item) { return item.itemLineId == product.itemLineId; }).VATCode;
2811
+ obj['PromotionHit']['PromotionTrigger'].push(promotionTrigger);
2812
+ }
2813
+ });
2814
+ });
2815
+ _this.rjObject['Trailer']['PromotionItem'].push(obj);
2816
+ });
2817
+ }
2818
+ }
2819
+ return this;
2820
+ };
2821
+ RJMapperBuilderClass.prototype.getTenderInfo = function () {
2822
+ var _this = this;
2823
+ if (this.transactionDocument.paymentDetails && this.transactionDocument.paymentDetails.length > 0) {
2824
+ this.transactionDocument.paymentDetails.forEach(function (element) {
2825
+ if (element.externalTenderKey) {
2826
+ _this.rjObject[element.externalTenderKey] = [];
2827
+ if (element.paymentType.toUpperCase() === 'GIFT CARD') {
2828
+ var obj = {
2829
+ XMLSchemaVersion: _this.xmlSchemaVersion,
2830
+ LineNumber: _this.generateLineNumber(),
2831
+ NetValue: _this.convertToString(-1 * _this.removeDecimal((Math.round(element.amount)))),
2832
+ EffectiveNetValue: _this.convertToString(-1 * _this.removeDecimal((Math.round(element.amount)))),
2833
+ Description: _this.getDescription(element),
2834
+ DeviceID: _this.deviceId,
2835
+ UserID: _this.transactionDocument.userName,
2836
+ DateTimeCreated: _this.updatedAt,
2837
+ TenderType: element.externalTenderType ? element.externalTenderType : '',
2838
+ TenderSubType: element.externalSubTenderType ? element.externalSubTenderType : '',
2839
+ TenderAmount: _this.convertToString(-1 * _this.removeDecimal((Math.round(element.amount)))),
2840
+ CurrencyID: _this.transactionDocument.baseCurrency,
2841
+ CurrencyDescription: _this.transactionDocument.baseCurrency,
2842
+ GiftVoucherSalesAllowed: '',
2843
+ AllowRechargeableVoucherSales: '',
2844
+ GiftVoucherID: ''
2845
+ };
2846
+ _this.rjObject[element.externalTenderKey].push(obj);
2847
+ }
2848
+ else {
2849
+ var obj1 = {
2850
+ XMLSchemaVersion: "1",
2851
+ LineNumber: _this.generateLineNumber(),
2852
+ NetValue: _this.convertToString(-1 * _this.removeDecimal(Math.round(element.amount))),
2853
+ EffectiveNetValue: _this.convertToString(-1 * _this.removeDecimal(Math.round(element.amount))),
2854
+ Description: _this.getDescription(element),
2855
+ DeviceID: _this.deviceId,
2856
+ UserID: _this.transactionDocument.userName,
2857
+ DateTimeCreated: _this.updatedAt,
2858
+ TenderType: element.externalTenderType ? element.externalTenderType : '',
2859
+ TenderSubType: element.externalSubTenderType ? element.externalSubTenderType : '',
2860
+ TenderAmount: _this.convertToString(-1 * _this.removeDecimal(Math.round(element.amount))),
2861
+ CurrencyID: _this.transactionDocument.baseCurrency,
2862
+ CurrencyDescription: _this.transactionDocument.baseCurrency,
2863
+ IncludeInTransactionTotalCheck: "1",
2864
+ AllowRechargeableVoucherSales: "1",
2865
+ OpenDrawerAtEnd: "1"
2866
+ };
2867
+ _this.rjObject[element.externalTenderKey].push(obj1);
2868
+ }
2869
+ }
2870
+ else {
2871
+ _this.rjObject['CashTender'] = [];
2872
+ if (element.paymentType.toUpperCase() === 'GIFT CARD') {
2873
+ var obj = {
2874
+ XMLSchemaVersion: _this.xmlSchemaVersion,
2875
+ LineNumber: _this.generateLineNumber(),
2876
+ NetValue: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2877
+ EffectiveNetValue: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2878
+ Description: _this.getDescription(element),
2879
+ DeviceID: _this.deviceId,
2880
+ UserID: _this.transactionDocument.userName,
2881
+ DateTimeCreated: _this.updatedAt,
2882
+ TenderType: element.externalTenderType ? element.externalTenderType : '',
2883
+ TenderSubType: element.externalSubTenderType ? element.externalSubTenderType : '',
2884
+ TenderAmount: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2885
+ CurrencyID: _this.transactionDocument.baseCurrency,
2886
+ CurrencyDescription: _this.transactionDocument.baseCurrency,
2887
+ GiftVoucherSalesAllowed: '',
2888
+ AllowRechargeableVoucherSales: '',
2889
+ GiftVoucherID: ''
2890
+ };
2891
+ _this.rjObject['CashTender'].push(obj);
2892
+ }
2893
+ else {
2894
+ var obj1 = {
2895
+ XMLSchemaVersion: "1",
2896
+ LineNumber: _this.generateLineNumber(),
2897
+ NetValue: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2898
+ EffectiveNetValue: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2899
+ Description: _this.getDescription(element),
2900
+ DeviceID: _this.deviceId,
2901
+ UserID: _this.transactionDocument.userName,
2902
+ DateTimeCreated: _this.updatedAt,
2903
+ TenderType: element.externalTenderType ? element.externalTenderType : '',
2904
+ TenderSubType: element.externalSubTenderType ? element.externalSubTenderType : '',
2905
+ TenderAmount: JSON.stringify(-1 * _this.removeDecimal((Math.round(element.amount)))),
2906
+ CurrencyID: _this.transactionDocument.baseCurrency,
2907
+ CurrencyDescription: _this.transactionDocument.baseCurrency,
2908
+ IncludeInTransactionTotalCheck: "1",
2909
+ AllowRechargeableVoucherSales: "1",
2910
+ OpenDrawerAtEnd: "1"
2911
+ };
2912
+ _this.rjObject['CashTender'].push(obj1);
2913
+ }
2914
+ }
2915
+ });
2916
+ }
2917
+ return this;
2918
+ };
2919
+ RJMapperBuilderClass.prototype.getNumber = function (productId) {
2920
+ var lineNumber;
2921
+ for (var i = 0; i < this.rjObject['ProductSale'].length; i++) {
2922
+ var element = this.rjObject['ProductSale'][i];
2923
+ if (JSON.stringify(productId) === JSON.stringify(element.ProductID)) {
2924
+ lineNumber = element.LineNumber;
2925
+ break;
2926
+ }
2927
+ }
2928
+ return lineNumber;
2929
+ };
2930
+ RJMapperBuilderClass.prototype.setLineNumberForProducts = function () {
2931
+ var itemLineIdArray = [];
2932
+ itemLineIdArray = this.transactionDocument.basket.products.map(function (product) {
2933
+ return parseInt(product.itemLineId);
2934
+ });
2935
+ this.largestNumber = itemLineIdArray.reduce(function (a, b) { return Math.max(a, b); });
2936
+ };
2937
+ RJMapperBuilderClass.prototype.generateLineNumber = function () {
2938
+ this.largestNumber += 1;
2939
+ this.itemCount += 1;
2940
+ return this.largestNumber;
2941
+ };
2942
+ RJMapperBuilderClass.prototype.initilizeItemCount = function () {
2943
+ this.itemCount = this.transactionDocument.basket.products.length;
2944
+ };
2945
+ RJMapperBuilderClass.prototype.build = function () {
2946
+ return this.rjObject;
2947
+ };
2948
+ RJMapperBuilderClass.prototype.getDescription = function (element) {
2949
+ if (element.paymentType.toUpperCase() === 'CARD') {
2950
+ return element.cardType;
2951
+ }
2952
+ else {
2953
+ return element.paymentType;
2954
+ }
2955
+ };
2956
+ RJMapperBuilderClass.prototype.getMMGROUPID = function (attributes) {
2957
+ if (attributes && attributes.length > 0) {
2958
+ var filterValue = attributes.filter(function (attribute) { return attribute.name === "MMGROUPID"; });
2959
+ if (filterValue && filterValue.length > 0) {
2960
+ return filterValue[0].value;
2961
+ }
2962
+ }
2963
+ };
2964
+ RJMapperBuilderClass.prototype.setDeviceInfo = function (id) {
2965
+ this.deviceId = id;
2966
+ return this;
2967
+ };
2968
+ RJMapperBuilderClass.prototype.removeDecimal = function (value) {
2969
+ return value * 100;
2970
+ };
2971
+ RJMapperBuilderClass.prototype.addDecimal = function (value) {
2972
+ return value / 100;
2973
+ };
2974
+ RJMapperBuilderClass.prototype.setTransactionNumber = function (value) {
2975
+ this.transactionNumber = value;
2976
+ return this;
2977
+ };
2978
+ RJMapperBuilderClass.prototype.setManifestVersion = function (value) {
2979
+ this.manifestVersion = value;
2980
+ return this;
2981
+ };
2982
+ RJMapperBuilderClass.prototype.setDatabaseSchemaVersion = function (value) {
2983
+ this.databaseSchemaVersion = value;
2984
+ return this;
2985
+ };
2986
+ RJMapperBuilderClass.prototype.setBasketType = function (value) {
2987
+ this.basketType = value;
2988
+ return this;
2989
+ };
2990
+ RJMapperBuilderClass.prototype.setTradingRegionID = function (value) {
2991
+ this.tradingRegionId = value;
2992
+ return this;
2993
+ };
2994
+ RJMapperBuilderClass.prototype.setCompanyID = function (value) {
2995
+ this.companyId = value;
2996
+ return this;
2997
+ };
2998
+ RJMapperBuilderClass.prototype.setTaxMethodID = function (value) {
2999
+ this.taxMethodId = value;
3000
+ return this;
3001
+ };
3002
+ RJMapperBuilderClass.prototype.setMajorVersion = function (value) {
3003
+ this.majorVersion = value;
3004
+ return this;
3005
+ };
3006
+ RJMapperBuilderClass.prototype.setMinorVersion = function (value) {
3007
+ this.minorVersion = value;
3008
+ return this;
3009
+ };
3010
+ RJMapperBuilderClass.prototype.setXMLSchemaVersion = function (value) {
3011
+ this.xmlSchemaVersion = value;
3012
+ return this;
3013
+ };
3014
+ RJMapperBuilderClass.prototype.setExternalState = function (value) {
3015
+ this.externalState = value;
3016
+ return this;
3017
+ };
3018
+ RJMapperBuilderClass.prototype.setCashierID = function () {
3019
+ this.cashierId = (this.transactionDocument && this.transactionDocument.userName) ? this.transactionDocument.userName : '';
3020
+ return this;
3021
+ };
3022
+ RJMapperBuilderClass.prototype.setTerminalNumber = function (value) {
3023
+ this.terminalNumber = value;
3024
+ return this;
3025
+ };
3026
+ RJMapperBuilderClass.prototype.setBasketLanguageID = function (value) {
3027
+ this.basketLanguageId = value;
3028
+ return this;
3029
+ };
3030
+ RJMapperBuilderClass.prototype.setBasketCountryID = function (value) {
3031
+ this.basketCountryId = value;
3032
+ return this;
3033
+ };
3034
+ RJMapperBuilderClass.prototype.setBasketCurrencyID = function (value) {
3035
+ this.basketCurrencyId = value;
3036
+ return this;
3037
+ };
3038
+ RJMapperBuilderClass.prototype.setBranchID = function (value) {
3039
+ this.branchId = value;
3040
+ return this;
3041
+ };
3042
+ RJMapperBuilderClass.prototype.setSalesPersonName = function (value) {
3043
+ this.salesPersonName = value;
3044
+ return this;
3045
+ };
3046
+ RJMapperBuilderClass.prototype.generateId = function (date) {
3047
+ var newDateTime = date.replace(/[^0-9]/g, '');
3048
+ var id = (this.deviceId + '|' + newDateTime + '|' + this.transactionNumber).toString();
3049
+ return id;
3050
+ };
3051
+ RJMapperBuilderClass.prototype.generateTimezoneoffset = function (date) {
3052
+ var x = date ? date : '';
3053
+ return new Date(x).getTimezoneOffset();
3054
+ };
3055
+ RJMapperBuilderClass.prototype.generateKeyword = function () {
3056
+ var x = (this.companyId + '|' + this.transactionDocument.storeId + '|' + this.terminalNumber + '|' + this.transactionNumber).toString();
3057
+ return x;
3058
+ };
3059
+ RJMapperBuilderClass.prototype.getState = function () {
3060
+ if (this.transactionDocument.operationStatus === 'PAY_SUCCESS') {
3061
+ return 'Completed';
3062
+ }
3063
+ else {
3064
+ return 'Cancelled';
3065
+ }
3066
+ };
3067
+ RJMapperBuilderClass.prototype.returnProduct = function (element, lineDiscount, transactionDiscount) {
3068
+ var _this = this;
3069
+ var obj = {};
3070
+ var taxTotal = this.transactionDocument.basket['taxBreakdown']['taxLines'].find(function (item) { return item.itemLineId == element['itemLineId']; });
3071
+ obj['XMLSchemaVersion'] = this.xmlSchemaVersion;
3072
+ obj['LineNumber'] = element['itemLineId'];
3073
+ obj['NetValue'] = this.removeDecimal(element['refundedTotal']);
3074
+ obj['EffectiveNetValue'] = this.removeDecimal(element['refundedTotal']);
3075
+ obj['Description'] = element['description'];
3076
+ obj['DeviceID'] = this.transactionDocument['terminalId'];
3077
+ obj['UserID'] = this.transactionDocument.userName;
3078
+ obj['DateTimeCreated'] = this.createdAt;
3079
+ obj['ExtendedValue'] = this.removeDecimal(element['totalLinePrice'] * -1);
3080
+ obj['UnitPrice'] = this.removeDecimal(element['price']);
3081
+ obj['Quantity'] = this.getQuantity(element);
3082
+ obj['OriginalTaxAmountSet'] = 1;
3083
+ obj['ProductID'] = element['SKU'];
3084
+ obj['HandKeyed'] = 1;
3085
+ obj['LongDescription'] = element['description'];
3086
+ obj['Return'] = {};
3087
+ obj['Return']['ReturnReasonID'] = element['refundedReason'];
3088
+ obj['Return']['ReturnDescription'] = element['refundedReasonDescription'];
3089
+ obj['Return']['ReturnToStock'] = this.getQuantity(element);
3090
+ obj['TaxCode'] = this.transactionDocument.basket['taxBreakdown']['taxLines'].find(function (item) { return item.itemLineId == element['itemLineId']; }).VATCode;
3091
+ obj['DisplayTaxCode'] = ''; // todo
3092
+ obj['ProductAttributes'] = ''; //todo - not required
3093
+ obj['Perishable'] = this.getMMGROUPID(element.attributes);
3094
+ //obj['MMGroupID'] = this.getCaregories(element);
3095
+ obj['MMGroupID'] = this.getMMGROUPID(element.attributes);
3096
+ obj['CustomerDetails'] = ""; // todo - blank
3097
+ obj['TotalPromotionSaving'] = element['promotionAmount'] || -1; // TODO
3098
+ obj['OriginalTaxAmount'] = this.convertToString((this.removeDecimal(this.getOriginalTax(element, taxTotal.VAT) * -1)).toFixed(2));
3099
+ obj['taxAmount'] = this.removeDecimal(taxTotal.taxLineTotal < 0 ? (taxTotal.taxLineTotal) : (-taxTotal.taxLineTotal));
3100
+ if (lineDiscount) {
3101
+ if (lineDiscount.percentageDiscountReasonName && lineDiscount.percentageDiscountReasonCode) {
3102
+ // line discount
3103
+ obj['Discount'] = {};
3104
+ obj['Discount'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
3105
+ obj['Discount'].ModifierDateTime = obj.DateTimeCreated;
3106
+ obj['Discount'].ModifierReasonID = lineDiscount.percentageDiscountReasonCode;
3107
+ obj['Discount'].ModifierDescription = lineDiscount.percentageDiscountReasonName;
3108
+ obj['Discount'].AuthorisingUserID = this.transactionDocument.userName;
3109
+ obj['Discount'].DiscountType = lineDiscount.discountType;
3110
+ obj['Discount'].XMLSchemaVersion = 1;
3111
+ obj['Discount'].OriginalPrice = this.removeDecimal(lineDiscount.discountAmount + (lineDiscount.discountedLinePrice || 0));
3112
+ obj['Discount'].DiscountedValue = this.removeDecimal(lineDiscount.unitPrice);
3113
+ obj['Discount'].DiscountPercentage = lineDiscount.percentageDiscountValue;
3114
+ obj['Discount'].RoundingRule = 2;
3115
+ }
3116
+ if (lineDiscount.priceOverrideReasonCode && lineDiscount.priceOverrideReasonName) {
3117
+ //price override
3118
+ obj['PriceOverride'] = {};
3119
+ obj['PriceOverride'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
3120
+ obj['PriceOverride'].ModifierDateTime = obj.DateTimeCreated;
3121
+ obj['PriceOverride'].ModifierReasonID = lineDiscount.priceOverrideReasonCode;
3122
+ obj['PriceOverride'].ModifierReasonDescription = lineDiscount.priceOverrideReasonName;
3123
+ obj['PriceOverride'].AuthorisingUserID = this.transactionDocument.userName;
3124
+ obj['PriceOverride'].XMLSchemaVersion = 1;
3125
+ obj['PriceOverride'].NewPrice = this.removeDecimal(lineDiscount.unitPrice);
3126
+ obj['PriceOverride'].OriginalPrice = this.removeDecimal(lineDiscount.discountedLinePrice || 0 + lineDiscount.discountAmount);
3127
+ }
3128
+ //update the product price
3129
+ obj.NetValue = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
3130
+ obj.EffectiveNetValue = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
3131
+ obj.ExtendedValue = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
3132
+ obj.UnitPrice = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount) * -1;
3133
+ }
3134
+ if (transactionDiscount) {
3135
+ obj['BasketDiscountModifier'] = [];
3136
+ this.transactionDocument.basket.transactionDiscount.forEach(function (e) {
3137
+ var discountObj = {};
3138
+ e.itemLineIds.forEach(function (x) {
3139
+ if (x == element.itemLineId) {
3140
+ var discountAmount = _this.convertToString(e.discountAmount * -1);
3141
+ discountObj.BasketDiscountLineNumber = _this.getLineNumber(e, discountAmount);
3142
+ discountObj.XMLSchemaVersion = _this.xmlSchemaVersion;
3143
+ discountObj.DiscountedValue = _this.getDiscountedValue(element.totalLinePrice, e.discountAmount);
3144
+ obj['BasketDiscountModifier'].push(discountObj);
3145
+ }
3146
+ });
3147
+ });
3148
+ var totaltransactionDiscount = 0;
3149
+ obj['BasketDiscountModifier'].forEach(function (value) {
3150
+ totaltransactionDiscount = totaltransactionDiscount + value.DiscountedValue;
3151
+ });
3152
+ //update the product price
3153
+ obj['EffectiveNetValue'] = obj.EffectiveNetValue + totaltransactionDiscount;
3154
+ }
3155
+ if (this.transactionDocument.basket.transactionPromotion.length > 0) {
3156
+ obj['PromotionSaving'] = [];
3157
+ this.transactionDocument.basket.transactionPromotion.forEach(function (transactionPromo) {
3158
+ var promotionObj = {};
3159
+ transactionPromo.itemLineIds.forEach(function (itemLineId) {
3160
+ if (itemLineId == element.itemLineId) {
3161
+ promotionObj.ModifierValue = transactionPromo.promotionAmount;
3162
+ promotionObj.ModifierDateTime = _this.transactionDocument.createdAt;
3163
+ promotionObj.ModifierDescription = transactionPromo.displayText;
3164
+ promotionObj.XMLSchemaVersion = _this.xmlSchemaVersion;
3165
+ promotionObj.PromotionID = transactionPromo.promotionId;
3166
+ promotionObj.PromotionDescription = transactionPromo.displayText;
3167
+ promotionObj.HitNumber = '1';
3168
+ promotionObj.PromotionHitProductQuantity = _this.getQuantity(element);
3169
+ promotionObj.PromotionHitQuantity = _this.getQuantity(element) * -1;
3170
+ obj['PromotionSaving'].push(promotionObj);
3171
+ }
3172
+ });
3173
+ });
3174
+ }
3175
+ return obj;
3176
+ };
3177
+ RJMapperBuilderClass.prototype.addProduct = function (element, lineDiscount, transactionDiscount) {
3178
+ var _this = this;
3179
+ var taxTotal = this.transactionDocument.basket['taxBreakdown']['taxLines'].find(function (item) { return item.itemLineId == element['itemLineId']; });
3180
+ var obj = {
3181
+ XMLSchemaVersion: this.xmlSchemaVersion,
3182
+ LineNumber: element.itemLineId,
3183
+ NetValue: this.removeDecimal(element.totalLinePrice),
3184
+ EffectiveNetValue: this.removeDecimal(element.totalLinePrice),
3185
+ Description: element.description,
3186
+ DeviceID: this.deviceId,
3187
+ UserID: this.transactionDocument.userName,
3188
+ DateTimeCreated: this.createdAt,
3189
+ ExtendedValue: this.removeDecimal(element.price),
3190
+ UnitPrice: this.removeDecimal(element.price),
3191
+ //MMGroupID: this.getCaregories(element),
3192
+ Quantity: element.quantity,
3193
+ SalespersonID: this.transactionDocument.userName,
3194
+ SalespersonName: this.salesPersonName,
3195
+ TaxCode: this.transactionDocument.basket['taxBreakdown']['taxLines'].find(function (item) { return item.itemLineId == element['itemLineId']; }).VATCode,
3196
+ TaxModifiable: "1",
3197
+ OriginalTaxAmount: this.convertToString((this.removeDecimal(this.getOriginalTax(element, taxTotal.VAT)).toFixed(2))),
3198
+ TaxAmount: this.convertToString(this.removeDecimal(taxTotal.taxLineTotal)),
3199
+ OriginalTaxAmountSet: "1",
3200
+ ProductID: element.SKU,
3201
+ HandKeyed: "1",
3202
+ CustomerDetails: "",
3203
+ Perishable: this.getMMGROUPID(element.attributes),
3204
+ MMGroupID: this.getMMGROUPID(element.attributes)
3205
+ };
3206
+ if (lineDiscount) {
3207
+ if (lineDiscount.percentageDiscountReasonName && lineDiscount.percentageDiscountReasonCode) {
3208
+ // line discount
3209
+ obj['Discount'] = {};
3210
+ obj['Discount'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
3211
+ obj['Discount'].ModifierDateTime = obj.DateTimeCreated;
3212
+ obj['Discount'].ModifierReasonID = lineDiscount.percentageDiscountReasonCode;
3213
+ obj['Discount'].ModifierDescription = lineDiscount.percentageDiscountReasonName;
3214
+ obj['Discount'].AuthorisingUserID = this.transactionDocument.userName;
3215
+ obj['Discount'].DiscountType = lineDiscount.discountType;
3216
+ obj['Discount'].XMLSchemaVersion = 1;
3217
+ obj['Discount'].OriginalPrice = this.removeDecimal(lineDiscount.discountAmount + (lineDiscount.discountedLinePrice || 0));
3218
+ obj['Discount'].DiscountedValue = this.removeDecimal(lineDiscount.unitPrice);
3219
+ obj['Discount'].DiscountPercentage = lineDiscount.percentageDiscountValue;
3220
+ obj['Discount'].RoundingRule = 2;
3221
+ }
3222
+ if (lineDiscount.priceOverrideReasonCode && lineDiscount.priceOverrideReasonName) {
3223
+ //price override
3224
+ obj['PriceOverride'] = {};
3225
+ obj['PriceOverride'].ModifierValue = this.removeDecimal(lineDiscount.discountAmount) * -1;
3226
+ obj['PriceOverride'].ModifierDateTime = obj.DateTimeCreated;
3227
+ obj['PriceOverride'].ModifierReasonID = lineDiscount.priceOverrideReasonCode;
3228
+ obj['PriceOverride'].ModifierReasonDescription = lineDiscount.priceOverrideReasonName;
3229
+ obj['PriceOverride'].AuthorisingUserID = this.transactionDocument.userName;
3230
+ obj['PriceOverride'].XMLSchemaVersion = this.xmlSchemaVersion;
3231
+ obj['PriceOverride'].NewPrice = this.removeDecimal(lineDiscount.unitPrice);
3232
+ obj['PriceOverride'].OriginalPrice = this.removeDecimal(lineDiscount.discountedLinePrice || 0 + lineDiscount.discountAmount);
3233
+ }
3234
+ //update the product price
3235
+ obj['NetValue'] = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount);
3236
+ obj['EffectiveNetValue'] = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount);
3237
+ obj['ExtendedValue'] = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount);
3238
+ obj['UnitPrice'] = ((lineDiscount.discountedLinePrice || 0) + lineDiscount.discountAmount);
3239
+ }
3240
+ if (transactionDiscount) {
3241
+ obj['BasketDiscountModifier'] = [];
3242
+ this.transactionDocument.basket.transactionDiscount.forEach(function (e) {
3243
+ var discountObj = {};
3244
+ e.itemLineIds.forEach(function (itemLineId) {
3245
+ if (itemLineId == element.itemLineId) {
3246
+ var discountAmount = _this.convertToString(e.discountAmount * -1);
3247
+ discountObj.XMLSchemaVersion = _this.xmlSchemaVersion;
3248
+ discountObj.DiscountedValue = -(_this.getDiscountedValue(element.totalLinePrice, e.discountAmount));
3249
+ discountObj.BasketDiscountLineNumber = _this.getLineNumber(e, discountAmount);
3250
+ obj['BasketDiscountModifier'].push(discountObj);
3251
+ }
3252
+ });
3253
+ });
3254
+ var totaltransactionDiscount_1 = 0;
3255
+ obj['BasketDiscountModifier'].forEach(function (value) {
3256
+ totaltransactionDiscount_1 = totaltransactionDiscount_1 + value.DiscountedValue;
3257
+ });
3258
+ //update the product price
3259
+ obj['EffectiveNetValue'] = obj.EffectiveNetValue + totaltransactionDiscount_1;
3260
+ }
3261
+ if (this.transactionDocument.basket.transactionPromotion.length > 0 || this.transactionDocument.basket.linePromotion.length > 0) {
3262
+ obj['DistributedPromotionSaving'] = [];
3263
+ if (this.transactionDocument.basket.transactionPromotion.length > 0) {
3264
+ this.transactionDocument.basket.transactionPromotion.forEach(function (e) {
3265
+ var promotionObj = {};
3266
+ e.itemLineIds.forEach(function (itemLineId) {
3267
+ if (itemLineId == element.itemLineId) {
3268
+ promotionObj.PromotionID = e.promotionId;
3269
+ promotionObj.Hit = '1';
3270
+ promotionObj.Saving = _this.getSaving(element.totalLinePrice, e.promotionAmount);
3271
+ promotionObj.ISaving = _this.getSaving(element.totalLinePrice, e.promotionAmount);
3272
+ obj['DistributedPromotionSaving'].push(promotionObj);
3273
+ }
3274
+ });
3275
+ });
3276
+ }
3277
+ if (this.transactionDocument.basket.linePromotion.length > 0) {
3278
+ this.transactionDocument.basket.linePromotion.forEach(function (linePromotion) {
3279
+ var promotionObj = {};
3280
+ if (element.itemLineId == linePromotion.itemLineId) {
3281
+ promotionObj.PromotionID = linePromotion.promotionId;
3282
+ promotionObj.Hit = "1";
3283
+ promotionObj.Saving = linePromotion.promotionLinePrice;
3284
+ promotionObj.ISaving = linePromotion.promotionLinePrice;
3285
+ obj['DistributedPromotionSaving'].push(promotionObj);
3286
+ }
3287
+ });
3288
+ }
3289
+ var transactionPromotion_1 = 0;
3290
+ obj['DistributedPromotionSaving'].forEach(function (value) {
3291
+ transactionPromotion_1 = transactionPromotion_1 + value.Saving;
3292
+ });
3293
+ obj['EffectiveNetValue'] = obj.EffectiveNetValue + transactionPromotion_1;
3294
+ }
3295
+ return obj;
3296
+ };
3297
+ RJMapperBuilderClass.prototype.getSaving = function (price, promotionAmount) {
3298
+ var Saving = (price * promotionAmount) / this.transactionDocument.basketSummary.saleTotal;
3299
+ return Saving;
3300
+ };
3301
+ RJMapperBuilderClass.prototype.getLineNumber = function (value, discountAmount) {
3302
+ var lineNumber;
3303
+ for (var i = 0; i < this.rjObject['BasketDiscount'].length; i++) {
3304
+ var element = this.rjObject['BasketDiscount'][i];
3305
+ if (value.reasonCode === element.ReasonCodeID && discountAmount === element.NetValue) {
3306
+ lineNumber = element.LineNumber;
3307
+ break;
3308
+ }
3309
+ }
3310
+ return lineNumber;
3311
+ };
3312
+ RJMapperBuilderClass.prototype.getDiscountedValue = function (price, discountAmount) {
3313
+ var DiscountedValue = ((price * discountAmount) / this.transactionDocument.basketSummary.saleTotal) * 100;
3314
+ return DiscountedValue;
3315
+ };
3316
+ RJMapperBuilderClass.prototype.getOriginalTax = function (element, VAT) {
3317
+ var pricebeforetax = (element.price * 100) / (100 + VAT);
3318
+ var originaltax = element.price - pricebeforetax;
3319
+ return originaltax;
3320
+ };
3321
+ RJMapperBuilderClass.prototype.convertToString = function (value) {
3322
+ try {
3323
+ value = JSON.stringify(value);
3324
+ return value;
3325
+ }
3326
+ catch (e) {
3327
+ appLogger_service.AppLoggerService.logError(this.className, "convertToString", 'can not be converted in string', e);
3328
+ }
3329
+ };
3330
+ RJMapperBuilderClass.prototype.generateDynamicStockLookUp = function () {
3331
+ var x = '0';
3332
+ this.transactionDocument.basket.products.forEach(function (element) {
3333
+ if (element.deliveryMethod === '1' || element.deliveryMethod === '2') {
3334
+ x = '1';
3335
+ }
3336
+ });
3337
+ return x;
3338
+ };
3339
+ // getAttributes(){
3340
+ // let name: string | any[] = []
3341
+ // this.transactionDocument.basket.products.forEach((element: any) => {
3342
+ // if (element && element.attributes && element.attributes.length > 0) {
3343
+ // name = element.attributes.filter((x: any) => x.name.toUpperCase() === element.name.toUpperCase());
3344
+ // }
3345
+ // });
3346
+ // if (name.length > 0) {
3347
+ // return name[0].value
3348
+ // }
3349
+ // else{
3350
+ // return ""
3351
+ // }
3352
+ // }
3353
+ // getCaregories(element) {
3354
+ // let MMGroupId = " ";
3355
+ // if (element.categories && element.categories.length > 0) {
3356
+ // let categories = element.categories.filter((x) => x.parentId != '');
3357
+ // let value = categories.filter((x) => x.id != x.parentId);
3358
+ // MMGroupId = value[0].name;
3359
+ // }
3360
+ // return MMGroupId;
3361
+ // }
3362
+ RJMapperBuilderClass.prototype.getDate = function (date) {
3363
+ var offset = this.generateTimezoneoffset(date) * -1;
3364
+ var offsetHours = Math.abs(Math.floor(offset / 60));
3365
+ var offsetMinutes = Math.abs(offset) - offsetHours * 60;
3366
+ var offsetSign = '+';
3367
+ if (offset < 0) {
3368
+ offsetSign = '-';
3369
+ }
3370
+ var newdate = date.substring(0, 19);
3371
+ var x = (newdate + offsetSign + String(offsetHours).padStart(2, '0') + ':' + String(offsetMinutes).padStart(2, '0')).toString();
3372
+ return x;
3373
+ };
3374
+ RJMapperBuilderClass.prototype.getTransactionPromotion = function (transactionPromotion) {
3375
+ if (transactionPromotion && transactionPromotion.length > 0) {
3376
+ this.rjObject['PromoVoucherItem'] = {};
3377
+ this.rjObject['PromoVoucherItem']['XMLSchemaVersion'] = this.xmlSchemaVersion;
3378
+ this.rjObject['PromoVoucherItem']['LineNumber'] = this.generateLineNumber();
3379
+ this.rjObject['PromoVoucherItem']['NetValue'] = this.removeDecimal(transactionPromotion[0].promotionLinePrice) * -1;
3380
+ this.rjObject['PromoVoucherItem']['EffectiveNetValue'] = this.removeDecimal(transactionPromotion[0].promotionLinePrice) * -1;
3381
+ this.rjObject['PromoVoucherItem']['Description'] = transactionPromotion[0].promotionInfo;
3382
+ this.rjObject['PromoVoucherItem']['DeviceID'] = this.deviceId;
3383
+ this.rjObject['PromoVoucherItem']['UserID'] = this.transactionDocument.userName;
3384
+ this.rjObject['PromoVoucherItem']['DateTimeCreated'] = this.createdAt;
3385
+ this.rjObject['PromoVoucherItem']['ProductId'] = ""; //todo
3386
+ this.rjObject['PromoVoucherItem']['SerialNumber'] = ""; //todo
3387
+ this.rjObject['PromoVoucherItem']['MMGroupId'] = "";
3388
+ }
3389
+ };
3390
+ RJMapperBuilderClass.prototype.getQuantity = function (element) {
3391
+ var quantity;
3392
+ if (this.transactionDocument.unreferencedRefund) {
3393
+ quantity = element['quantity'] < 0 ? element['quantity'] : (-element['quantity']);
3394
+ }
3395
+ else {
3396
+ quantity = element['refundedQuantity'] < 0 ? element['refundedQuantity'] : (-element['refundedQuantity']);
3397
+ }
3398
+ return quantity;
3399
+ };
3400
+ return RJMapperBuilderClass;
3401
+ }());
3402
+
3403
+ var WebReturnMapperBuilderClass = /** @class */ (function () {
3404
+ function WebReturnMapperBuilderClass(document, currencyPipe) {
3405
+ this.currencyPipe = currencyPipe;
3406
+ this.className = "WebReturnMapperBuilderClass";
3407
+ this.webReturnObject = {
3408
+ id: '',
3409
+ orgCode: "",
3410
+ storeId: "",
3411
+ storeNodeId: "",
3412
+ storeNodeStructure: "",
3413
+ deviceId: "",
3414
+ terminalId: "",
3415
+ initiatingModule: "",
3416
+ export: false,
3417
+ isInStoreOrder: false,
3418
+ basket: {},
3419
+ basketSummary: {},
3420
+ baseCurrency: "",
3421
+ customer: {
3422
+ firstName: '',
3423
+ lastName: '',
3424
+ email: '',
3425
+ postCode: '',
3426
+ id: '',
3427
+ billingAddress: {},
3428
+ shippingAddress: {},
3429
+ },
3430
+ currentTransactionDetails: {}
3431
+ };
3432
+ if (document) {
3433
+ this.document = document;
3434
+ }
3435
+ this.numberUtilService = new NumberUtilService(currencyPipe);
3436
+ }
3437
+ WebReturnMapperBuilderClass.prototype.WebReturnMapper = function () {
3438
+ var _this = this;
3439
+ this.webReturnObject['type'] = 'WEB_RETURNS';
3440
+ this.webReturnObject['datetime'] = this.getUTCDateTime(this.getText(this.document.updated_at));
3441
+ this.webReturnObject.baseCurrency = this.getText(this.document.base_currency_code);
3442
+ this.webReturnObject.storeId = this.getText(this.document.store_id);
3443
+ this.webReturnObject.subsidiaryId = '1';
3444
+ this.webReturnObject.initiatingModule = 'MAGENTO';
3445
+ this.webReturnObject.createdAt = this.getUTCDateTime(this.getText(this.document.created_at));
3446
+ this.webReturnObject.updatedAt = this.getUTCDateTime(this.getText(this.document.updated_at));
3447
+ this.webReturnObject.export = true;
3448
+ this.webReturnObject.transCompletedAt = this.getUTCDateTime(this.getText(this.document.updated_at));
3449
+ this.webReturnObject['externalTransactionId'] = this.getText(this.document.order_id);
3450
+ // customer
3451
+ this.webReturnObject['customer']['firstName'] = this.getText(this.document.customer_firstname) || '';
3452
+ this.webReturnObject['customer']['lastName'] = this.getText(this.document.customer_lastname) || '';
3453
+ this.webReturnObject['customer']['email'] = this.getText(this.document.customer_email) || '';
3454
+ this.webReturnObject['customer']['postCode'] = '';
3455
+ // Billing address
3456
+ this.webReturnObject['customer']['billingAddress']['address1'] = (this.document.billing_address && this.document.billing_address.street) ? this.getText(this.document.billing_address.street) : '';
3457
+ this.webReturnObject['customer']['billingAddress']['city'] = (this.document.billing_address && this.document.billing_address.city) ? this.getText(this.document.billing_address.city) : '';
3458
+ this.webReturnObject['customer']['billingAddress']['county'] = (this.document.billing_address && this.document.billing_address.region) ? this.getText(this.document.billing_address.region) : '';
3459
+ this.webReturnObject['customer']['billingAddress']['postCode'] = (this.document.billing_address && this.document.billing_address.postcode) ? this.getText(this.document.billing_address.postcode) : '';
3460
+ this.webReturnObject['customer']['billingAddress']['country'] = (this.document.billing_address && this.document.billing_address.country) ? this.getText(this.document.billing_address.country) : '';
3461
+ // Shipping address
3462
+ this.webReturnObject['customer']['shippingAddress']['address1'] = (this.document.shipping_address && this.document.shipping_address.street) ? this.getText(this.document.shipping_address.street) : '';
3463
+ this.webReturnObject['customer']['shippingAddress']['city'] = (this.document.shipping_address && this.document.shipping_address.city) ? this.getText(this.document.shipping_address.city) : '';
3464
+ this.webReturnObject['customer']['shippingAddress']['county'] = (this.document.shipping_address && this.document.shipping_address.region) ? this.getText(this.document.shipping_address.region) : '';
3465
+ this.webReturnObject['customer']['shippingAddress']['postCode'] = (this.document.shipping_address && this.document.shipping_address.postcode) ? this.getText(this.document.shipping_address.postcode) : '';
3466
+ this.webReturnObject['customer']['shippingAddress']['country'] = (this.document.shipping_address && this.document.shipping_address.country) ? this.getText(this.document.shipping_address.country) : '';
3467
+ // basketSummary
3468
+ this.webReturnObject.basketSummary['discountTotal'] = Math.abs(Number(this.document.discount_amount ? this.getText(this.document.discount_amount) : 0));
3469
+ this.webReturnObject.basketSummary['VATTotal'] = Number(this.document.base_total_paid ? this.getText(this.document.base_total_paid) : 0);
3470
+ this.webReturnObject.basketSummary['saleTotal'] = Number(this.document.base_total_invoiced ? this.getText(this.document.base_total_invoiced) : 0);
3471
+ this.webReturnObject.basketSummary['basketTotal'] = Number(this.document.base_total_paid ? this.getText(this.document.base_total_paid) : 0);
3472
+ this.webReturnObject.basketSummary['totalItems'] = Number(this.document.total_qty_ordered ? this.getText(this.document.total_qty_ordered) : 0);
3473
+ this.webReturnObject.basketSummary['refundTotal'] = Number(this.document.base_total_refunded ? this.getText(this.document.base_total_refunded) : 0);
3474
+ // // basket line discount
3475
+ // this.webReturnObject.basket['lineDiscount'] = [];
3476
+ // let lineDiscount = {
3477
+ // itemLineId: (this.document.items && this.document.items.item && this.document.items.item.item_id) ? this.getText(this.document.items.item.item_id) : 0,
3478
+ // discountAmount: (this.document.items && this.document.items.item && this.document.items.item.discount_amount) ? Number(this.getText(this.document.items.item.discount_amount)) : 0
3479
+ // }
3480
+ // this.webReturnObject.basket['lineDiscount'].push(lineDiscount);
3481
+ // basket transaction discount
3482
+ // basket products
3483
+ this.webReturnObject.basket['products'] = [];
3484
+ this.webReturnObject.basket['linePromotion'] = [];
3485
+ this.webReturnObject.basket['transactionDiscount'] = [];
3486
+ this.webReturnObject.basket['transactionPromotion'] = [];
3487
+ // let transactionDiscount = {
3488
+ // discountAmount: (this.document && this.document.discount_amount) ? Number(this.getText(this.document.discount_amount)) : 0
3489
+ // }
3490
+ // this.webReturnObject.basket['transactionDiscount'].push(transactionDiscount);
3491
+ var product = {};
3492
+ if (this.document.items && this.document.items.item) {
3493
+ if (this.document.items.item instanceof Array) {
3494
+ this.document.items.item.forEach(function (element, index) {
3495
+ var qty = _this.getText(element.qty_ordered) ? Number(_this.getText(element.qty_ordered)) : 0;
3496
+ var refundQty = _this.getText(element.qty_refunded) ? Number(_this.getText(element.qty_refunded)) : 0;
3497
+ var price = _this.getText(element.price_incl_tax) ? Number(_this.getText(element.price_incl_tax)) : 0;
3498
+ product = {
3499
+ description: (element.name) ? _this.getText(element.name) : '',
3500
+ SKU: (element.sku) ? _this.getText(element.sku) : '',
3501
+ quantity: (element.qty_ordered) ? Number(_this.getText(element.qty_ordered)) : 0,
3502
+ refundedQuantity: (element.qty_refunded) ? Number(_this.getText(element.qty_refunded)) : 0,
3503
+ //price: (element.original_price) ? Number(this.getText(element.original_price)) : 0,
3504
+ price: price,
3505
+ itemLineId: (index + 1).toString(),
3506
+ // totalLinePrice: (element.row_invoiced) ? Number(this.getText(element.row_invoiced)) : 0,
3507
+ totalLinePrice: ((qty - refundQty) * price),
3508
+ };
3509
+ var promotionAmount = _this.getText(element.discount_amount) ? Number(_this.getText(element.discount_amount)) : 0;
3510
+ var appliedIDs = _this.getText(element.applied_rule_ids) ? _this.getText(element.applied_rule_ids) : '';
3511
+ if (product && product.price != 0) {
3512
+ if (promotionAmount) {
3513
+ var trigger = {};
3514
+ trigger.itemLineId = product.itemLineId;
3515
+ trigger.quantity = product.quantity ? product.quantity : 0;
3516
+ var promotion = {
3517
+ promotionAmount: promotionAmount,
3518
+ promotionId: appliedIDs,
3519
+ itemLineId: product.itemLineId,
3520
+ promotionLinePrice: product.totalLinePrice - promotionAmount,
3521
+ trigger: trigger
3522
+ };
3523
+ _this.webReturnObject.basket['linePromotion'].push(promotion);
3524
+ }
3525
+ _this.webReturnObject.basket['products'].push(product);
3526
+ }
3527
+ });
3528
+ }
3529
+ else {
3530
+ var qty = (this.document.items && this.document.items.item && this.document.items.item.qty_ordered) ? Number(this.getText(this.document.items.item.qty_ordered)) : 0;
3531
+ var refundQty = (this.document.items && this.document.items.item && this.document.items.item.qty_refunded) ? Number(this.getText(this.document.items.item.qty_refunded)) : 0;
3532
+ var price = (this.document.items && this.document.items.item && this.document.items.item.price_incl_tax) ? Number(this.getText(this.document.items.item.price_incl_tax)) : 0;
3533
+ product = {
3534
+ description: (this.document.items && this.document.items.item && this.document.items.item.name) ? this.getText(this.document.items.item.name) : '',
3535
+ SKU: (this.document.items && this.document.items.item && this.document.items.item.sku) ? this.getText(this.document.items.item.sku) : '',
3536
+ quantity: (this.document.items && this.document.items.item && this.document.items.item.qty_ordered) ? Number(this.getText(this.document.items.item.qty_ordered)) : 0,
3537
+ refundedQuantity: (this.document.items && this.document.items.item && this.document.items.item.qty_refunded) ? Number(this.getText(this.document.items.item.qty_refunded)) : 0,
3538
+ // price: (this.document.items && this.document.items.item && this.document.items.item.original_price) ? Number(this.getText(this.document.items.item.original_price)) : 0,
3539
+ price: price,
3540
+ itemLineId: "1",
3541
+ // totalLinePrice: (this.document.items && this.document.items.item && this.document.items.item.row_invoiced) ? Number(this.getText(this.document.items.item.row_invoiced)) : 0,
3542
+ totalLinePrice: ((qty - refundQty) * price),
3543
+ };
3544
+ var promotionAmount = this.getText(this.document.items.item.discount_amount) ? Number(this.getText(this.document.items.item.discount_amount)) : 0;
3545
+ var appliedIDs_1 = this.getText(this.document.items.item.applied_rule_ids) ? this.getText(this.document.items.item.applied_rule_ids) : '';
3546
+ if (product && product.price != 0) {
3547
+ if (promotionAmount) {
3548
+ var trigger = {};
3549
+ trigger.itemLineId = product.itemLineId;
3550
+ trigger.quantity = product.quantity ? product.quantity : 0;
3551
+ var promotion = {
3552
+ promotionAmount: promotionAmount,
3553
+ promotionId: appliedIDs_1,
3554
+ itemLineId: product.itemLineId,
3555
+ promotionLinePrice: product.totalLinePrice - promotionAmount,
3556
+ trigger: trigger
3557
+ };
3558
+ this.webReturnObject.basket['linePromotion'].push(promotion);
3559
+ }
3560
+ this.webReturnObject.basket['products'].push(product);
3561
+ }
3562
+ }
3563
+ var couponCode_1 = this.getText(this.document.coupon_code) ? this.getText(this.document.coupon_code) : 0;
3564
+ var appliedIDs_2 = this.getText(this.document.applied_rule_ids) ? this.getText(this.document.applied_rule_ids) : '';
3565
+ var discountDescription_1 = this.getText(this.document.discount_description) ? this.getText(this.document.discount_description) : '';
3566
+ var couponTriggerPromotions_1 = [];
3567
+ if (couponCode_1 && appliedIDs_2) {
3568
+ var transactionPromotion = {};
3569
+ if (this.webReturnObject.basket['linePromotion'] && this.webReturnObject.basket['linePromotion'].length > 0) {
3570
+ this.webReturnObject.basket['linePromotion'].forEach(function (promotion) {
3571
+ if (promotion.promotionId === appliedIDs_2) {
3572
+ var trigger = {};
3573
+ trigger.itemLineId = promotion.itemLineId;
3574
+ trigger.quantity = promotion.trigger.quantity;
3575
+ trigger.totalQuantity = promotion.trigger.quantity;
3576
+ trigger.promotionAmount = promotion.promotionAmount;
3577
+ trigger.refundedReason = couponCode_1;
3578
+ trigger.refundedReasonDescription = discountDescription_1;
3579
+ trigger.promotionId = promotion.promotionId;
3580
+ couponTriggerPromotions_1.push(trigger);
3581
+ _this.webReturnObject.basket['linePromotion'] = _this.webReturnObject.basket['linePromotion'].filter(function (x) { return x.itemLineId !== promotion.itemLineId; });
3582
+ }
3583
+ });
3584
+ }
3585
+ if (couponTriggerPromotions_1.length > 0) {
3586
+ transactionPromotion.displayText = couponTriggerPromotions_1[0].refundedReasonDescription;
3587
+ transactionPromotion.name = couponTriggerPromotions_1[0].refundedReason;
3588
+ transactionPromotion.promotionAmount = -(couponTriggerPromotions_1.reduce(function (n, _a) {
3589
+ var promotionAmount = _a.promotionAmount;
3590
+ return n + promotionAmount;
3591
+ }, 0));
3592
+ transactionPromotion.promotionId = couponTriggerPromotions_1[0].promotionId;
3593
+ transactionPromotion.promotionInfo = couponTriggerPromotions_1[0].refundedReasonDescription;
3594
+ transactionPromotion.couponCode = couponCode_1;
3595
+ transactionPromotion.itemLineIds = [];
3596
+ transactionPromotion.type = PROMOTION_TYPE.COUPON;
3597
+ transactionPromotion.subLevelType = PROMOTION_LEVEL.LINE;
3598
+ transactionPromotion.trigger = couponTriggerPromotions_1;
3599
+ }
3600
+ appLogger_service.AppLoggerService.logDebug(this.className, "WebReturnMapper", "update LinePromotion With Coupon", transactionPromotion);
3601
+ if (!this.webReturnObject.basket.transactionPromotion) {
3602
+ this.webReturnObject.basket.transactionPromotion = [];
3603
+ }
3604
+ if (transactionPromotion && transactionPromotion.promotionId) {
3605
+ this.webReturnObject.basket.transactionPromotion.push(transactionPromotion);
3606
+ }
3607
+ }
3608
+ this.updateTransactionPromotionPrtionCalc();
3609
+ }
3610
+ return this;
3611
+ };
3612
+ WebReturnMapperBuilderClass.prototype.validateProductItemDiscount = function (product) {
3613
+ if (!product.itemDiscounts) {
3614
+ product.itemDiscounts = {
3615
+ trnDiscountsPortion: 0,
3616
+ trnPromotionsPortion: 0,
3617
+ refundPortion: 0,
3618
+ };
3619
+ }
3620
+ return product;
3621
+ };
3622
+ WebReturnMapperBuilderClass.prototype.transactionPromotionProductPortionCalc = function (txDoc, promotion) {
3623
+ var _this = this;
3624
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotionProductPortionCalc", "trnsactionPromotion: " + JSON.stringify(promotion));
3625
+ if (promotion.type === PROMOTION_TYPE.COUPON && promotion.subLevelType === PROMOTION_LEVEL.LINE) {
3626
+ txDoc.basket.products.forEach(function (product) {
3627
+ product = _this.validateProductItemDiscount(product);
3628
+ if (promotion.trigger && promotion.trigger.length > 0) {
3629
+ promotion.trigger.forEach(function (t) {
3630
+ if (t.itemLineId === product.itemLineId.toString()) {
3631
+ product.itemDiscounts.trnPromotionsPortion += t.promotionAmount;
3632
+ }
3633
+ });
3634
+ }
3635
+ });
3636
+ }
3637
+ else {
3638
+ txDoc.basket.products.forEach(function (product) {
3639
+ product = _this.validateProductItemDiscount(product);
3640
+ if (promotion.itemLineIds.includes(+product.itemLineId)) {
3641
+ var discountAmount = 0;
3642
+ if (_this.document.items.item instanceof Array) {
3643
+ var productItem = _this.document.items.item.find(function (productItem) { return productItem.sku === product.SKU; });
3644
+ discountAmount = productItem.discount_amount ? +productItem.discount_amount : 0;
3645
+ }
3646
+ else {
3647
+ discountAmount = _this.document.items.item.sku === product.SKU && _this.document.items.item.discount_amount ?
3648
+ +_this.document.items.item.discount_amount : 0;
3649
+ }
3650
+ var transactionPromotionPortion = discountAmount;
3651
+ product.itemDiscounts.trnPromotionsPortion += _this.numberUtilService.trimTo2Decimal2(transactionPromotionPortion);
3652
+ }
3653
+ });
3654
+ }
3655
+ return txDoc;
3656
+ };
3657
+ WebReturnMapperBuilderClass.prototype.updateTransactionPromotionPrtionCalc = function () {
3658
+ var _this = this;
3659
+ try {
3660
+ if (this.webReturnObject.basket.transactionPromotion && this.webReturnObject.basket.transactionPromotion.length > 0) {
3661
+ this.webReturnObject.basket.transactionPromotion.forEach(function (tr) {
3662
+ _this.transactionPromotionProductPortionCalc(_this.webReturnObject, tr);
3663
+ });
3664
+ }
3665
+ }
3666
+ catch (error) {
3667
+ appLogger_service.AppLoggerService.logError(this.className, "updateTransactionPromotionPrtionCalc", "updateTransactionPromotionPrtionCalc => failed:", error);
3668
+ }
3669
+ };
3670
+ WebReturnMapperBuilderClass.prototype.deviceId = function (deviceId) {
3671
+ this.webReturnObject.deviceId = deviceId;
3672
+ return this;
3673
+ };
3674
+ WebReturnMapperBuilderClass.prototype.terminalId = function (terminalId) {
3675
+ this.webReturnObject.terminalId = terminalId;
3676
+ return this;
3677
+ };
3678
+ WebReturnMapperBuilderClass.prototype.orgCode = function (orgCode) {
3679
+ this.webReturnObject.orgCode = orgCode;
3680
+ return this;
3681
+ };
3682
+ WebReturnMapperBuilderClass.prototype.storeId = function (storeId) {
3683
+ this.webReturnObject.storeId = storeId;
3684
+ return this;
3685
+ };
3686
+ WebReturnMapperBuilderClass.prototype.storeNodeId = function (storeNodeId) {
3687
+ this.webReturnObject.storeNodeId = storeNodeId;
3688
+ return this;
3689
+ };
3690
+ WebReturnMapperBuilderClass.prototype.storeNodeStructure = function (storeNodeStructure) {
3691
+ this.webReturnObject.storeNodeStructure = storeNodeStructure;
3692
+ return this;
3693
+ };
3694
+ WebReturnMapperBuilderClass.prototype.docId = function (docId) {
3695
+ this.webReturnObject.id = docId;
3696
+ return this;
3697
+ };
3698
+ WebReturnMapperBuilderClass.prototype.updateUserID = function (userID) {
3699
+ this.webReturnObject.userId = userID;
3700
+ return this;
3701
+ };
3702
+ WebReturnMapperBuilderClass.prototype.updateUserName = function (name) {
3703
+ this.webReturnObject.userName = name;
3704
+ return this;
3705
+ };
3706
+ WebReturnMapperBuilderClass.prototype.build = function () {
3707
+ return this.webReturnObject;
3708
+ };
3709
+ WebReturnMapperBuilderClass.prototype.getText = function (obj) {
3710
+ if (obj && obj.text) {
3711
+ return obj.text;
3712
+ }
3713
+ else {
3714
+ return obj;
3715
+ }
3716
+ };
3717
+ WebReturnMapperBuilderClass.prototype.getUTCDateTime = function (date) {
3718
+ if (date) {
3719
+ return new Date(date).toISOString();
3720
+ }
3721
+ };
3722
+ WebReturnMapperBuilderClass.prototype.isInStoreOrder = function () {
3723
+ appLogger_service.AppLoggerService.logDebug(this.className, "isInStoreOrder", "isInStoreOrder mapping started...");
3724
+ if (this.document.payment && this.document.payment.method && this.document.payment.method === 'pos_order') {
3725
+ this.webReturnObject.isInStoreOrder = true;
3726
+ }
3727
+ appLogger_service.AppLoggerService.logDebug(this.className, "isInStoreOrder", "isInStoreOrder mapping ended...");
3728
+ return this;
3729
+ };
3730
+ return WebReturnMapperBuilderClass;
3731
+ }());
3732
+
3733
+ var WebReturnSalesforceMapperBuilderClass = /** @class */ (function () {
3734
+ function WebReturnSalesforceMapperBuilderClass(orderDetails, currencyPipe) {
3735
+ this.currencyPipe = currencyPipe;
3736
+ this.className = "WebReturnSalesforceMapperBuilderClass";
3737
+ this.webReturnObject = {
3738
+ id: '',
3739
+ orgCode: "",
3740
+ storeId: "",
3741
+ storeNodeId: "",
3742
+ storeNodeStructure: "",
3743
+ deviceId: "",
3744
+ terminalId: "",
3745
+ initiatingModule: "",
3746
+ export: false,
3747
+ isInStoreOrder: false,
3748
+ basket: {},
3749
+ basketSummary: {},
3750
+ baseCurrency: "",
3751
+ customer: {
3752
+ id: '',
3753
+ email: '',
3754
+ firstName: '',
3755
+ lastName: '',
3756
+ billingAddress: [],
3757
+ shippingAddress: [],
3758
+ shipmentDetails: [],
3759
+ telephone: '',
3760
+ postCode: '',
3761
+ noCustomerSelected: false
3762
+ },
3763
+ currentTransactionDetails: {}
3764
+ };
3765
+ if (orderDetails) {
3766
+ this.orderDetails = orderDetails;
3767
+ }
3768
+ this.numberUtilService = new NumberUtilService(currencyPipe);
3769
+ }
3770
+ WebReturnSalesforceMapperBuilderClass.prototype.webReturnCommonMapper = function () {
3771
+ appLogger_service.AppLoggerService.logDebug(this.className, "webReturnCommonMapper", "Mapper library: WebReturnSalesforceMapperBuilderClass: webReturnCommonMapper started...");
3772
+ this.webReturnObject['type'] = TRANSACTION_TYPE.WEB_RETURNS;
3773
+ this.webReturnObject['datetime'] = this.getUTCDateTime(this.orderDetails.last_modified);
3774
+ this.webReturnObject.baseCurrency = this.orderDetails.currency;
3775
+ this.webReturnObject.subsidiaryId = '1';
3776
+ this.webReturnObject.export = true;
3777
+ this.webReturnObject.initiatingModule = INITIATING_MODULE.EBASKET;
3778
+ this.webReturnObject.createdAt = this.getUTCDateTime(this.orderDetails.creation_date);
3779
+ this.webReturnObject.updatedAt = this.getUTCDateTime(this.orderDetails.last_modified);
3780
+ this.webReturnObject.transCompletedAt = this.getUTCDateTime(this.orderDetails.last_modified);
3781
+ this.webReturnObject['externalTransactionId'] = this.orderDetails.order_no;
3782
+ appLogger_service.AppLoggerService.logDebug(this.className, "webReturnCommonMapper", "webReturnCommonMapper ended...");
3783
+ return this;
3784
+ };
3785
+ // export(status, details) {
3786
+ // AppLoggerService.logDebug(this.className, "Mapper library: WebReturnSalesforceMapperBuilderClass: export mapping started...");
3787
+ // AppLoggerService.logDebug(this.className, "Mapper library: WebReturnSalesforceMapperBuilderClass: status:", status);
3788
+ // AppLoggerService.logDebug(this.className, "Mapper library: WebReturnSalesforceMapperBuilderClass: details:", JSON.stringify(details));
3789
+ // if (status && details && details.providers && details.providers.length > 0) {
3790
+ // details.providers.forEach(
3791
+ // providerObj => {
3792
+ // if (providerObj.provider && providerObj.provider === PROVIDERS.SALESFORCE) {
3793
+ // this.webReturnObject.export = true;
3794
+ // } else {
3795
+ // this.webReturnObject.export = false;
3796
+ // }
3797
+ // }
3798
+ // );
3799
+ // } else {
3800
+ // this.webReturnObject.export = false;
3801
+ // }
3802
+ // AppLoggerService.logDebug(this.className, "Mapper library: WebReturnSalesforceMapperBuilderClass: export mapping end...")
3803
+ // return this;
3804
+ // }
3805
+ WebReturnSalesforceMapperBuilderClass.prototype.getDeliveryMethod = function () {
3806
+ if (this.orderDetails.shipments && this.orderDetails.shipments.length > 0) {
3807
+ var shipToStoreShipment = this.orderDetails.shipments.find(function (shipment) { return shipment.c_fromStoreId; });
3808
+ if (shipToStoreShipment)
3809
+ return DELIVERY_METHODS.SHIP_TO_STORE;
3810
+ else
3811
+ return DELIVERY_METHODS.DELIVERY;
3812
+ }
3813
+ else {
3814
+ return '';
3815
+ }
3816
+ };
3817
+ WebReturnSalesforceMapperBuilderClass.prototype.product = function () {
3818
+ var _this = this;
3819
+ appLogger_service.AppLoggerService.logDebug(this.className, "product", "product mapping started...");
3820
+ this.webReturnObject.basket['products'] = [];
3821
+ if (this.orderDetails.product_items && this.orderDetails.product_items.length > 0) {
3822
+ this.orderDetails.product_items.forEach(function (product, index) {
3823
+ var productObj = {
3824
+ description: product.item_text ? product.item_text : '',
3825
+ SKU: product.product_id ? product.product_id : '',
3826
+ quantity: product.quantity ? product.quantity : 0,
3827
+ refundedQuantity: 0,
3828
+ price: product.base_price ? product.base_price : 0,
3829
+ itemLineId: (index + 1).toString(),
3830
+ deliveryMethod: _this.getDeliveryMethod().toString(),
3831
+ totalLinePrice: product.price ? product.price : 0
3832
+ };
3833
+ if (product && product.price != 0) {
3834
+ _this.webReturnObject.basket['products'].push(productObj);
3835
+ }
3836
+ });
3837
+ }
3838
+ appLogger_service.AppLoggerService.logDebug(this.className, "product", "product mapping ended...");
3839
+ return this;
3840
+ };
3841
+ WebReturnSalesforceMapperBuilderClass.prototype.linePromotion = function () {
3842
+ appLogger_service.AppLoggerService.logDebug(this.className, "linePromotion", "linePromotion mapping started...");
3843
+ this.webReturnObject.basket.linePromotion = [];
3844
+ var linePromotionArray = [];
3845
+ if (this.orderDetails.product_items && this.orderDetails.product_items.length > 0) {
3846
+ this.orderDetails.product_items.forEach(function (product, index) {
3847
+ product.item_id = (index + 1).toString();
3848
+ if (product.price_adjustments && product.price_adjustments.length > 0) {
3849
+ product.price_adjustments.forEach(function (promotion) {
3850
+ if (!promotion.coupon_code) {
3851
+ var linePromotionObj = {};
3852
+ var trigger = {};
3853
+ trigger.itemLineId = product.item_id;
3854
+ trigger.quantity = product.quantity ? product.quantity : 0;
3855
+ linePromotionObj.trigger = [];
3856
+ linePromotionObj.trigger.push(trigger);
3857
+ linePromotionObj.itemLineId = index + 1;
3858
+ linePromotionObj.promotionId = promotion.promotion_id ? promotion.promotion_id : '';
3859
+ linePromotionObj.displayText = promotion.item_text ? promotion.item_text : '';
3860
+ linePromotionObj.promotionType = promotion.applied_discount && promotion.applied_discount.type ? promotion.applied_discount.type : '';
3861
+ linePromotionObj.promotionAmount = promotion.price ? Math.abs(promotion.price) : 0;
3862
+ linePromotionObj.name = promotion.coupon_code ? promotion.coupon_code : (promotion.item_text ? promotion.item_text : '');
3863
+ linePromotionObj.promotionInfo = promotion.item_text ? promotion.item_text : '';
3864
+ linePromotionObj.promotionLinePrice = product.price - Math.abs(promotion.price);
3865
+ linePromotionArray.push(linePromotionObj);
3866
+ }
3867
+ });
3868
+ }
3869
+ });
3870
+ }
3871
+ this.webReturnObject.basket.linePromotion = linePromotionArray;
3872
+ appLogger_service.AppLoggerService.logDebug(this.className, "linePromotion", "linePromotion mapping ended...");
3873
+ return this;
3874
+ };
3875
+ WebReturnSalesforceMapperBuilderClass.prototype.transactionPromotion = function () {
3876
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotion", "transactionPromotion mapping started...");
3877
+ var transactionPromotionArray = this.getTransactionPromotions(this.orderDetails);
3878
+ this.webReturnObject.basket.transactionPromotion = transactionPromotionArray;
3879
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotion", "transactionPromotion mapping ended...");
3880
+ return this;
3881
+ };
3882
+ WebReturnSalesforceMapperBuilderClass.prototype.getTransactionPromotions = function (basket) {
3883
+ var _this = this;
3884
+ try {
3885
+ var transactionPromotionArray_1 = [];
3886
+ if (basket.order_price_adjustments && basket.order_price_adjustments.length > 0) {
3887
+ basket.order_price_adjustments.forEach(function (transactionPromotion) {
3888
+ var transactionPromotionObj = {};
3889
+ transactionPromotionObj.displayText = transactionPromotion.item_text ? transactionPromotion.item_text : '';
3890
+ transactionPromotionObj.name = transactionPromotion.coupon_code ? transactionPromotion.coupon_code : (transactionPromotion.item_text ? transactionPromotion.item_text : '');
3891
+ transactionPromotionObj.promotionAmount = transactionPromotion.price ? Math.abs(transactionPromotion.price) : 0;
3892
+ transactionPromotionObj.promotionId = transactionPromotion.promotion_id ? transactionPromotion.promotion_id : '';
3893
+ transactionPromotionObj.promotionInfo = transactionPromotion.item_text ? transactionPromotion.item_text : '';
3894
+ transactionPromotionObj.promotionType = transactionPromotion.applied_discount && transactionPromotion.applied_discount.type ? transactionPromotion.applied_discount.type : '';
3895
+ transactionPromotionObj.itemLineIds = _this.orderDetails.product_items.map(function (product, index) { return index + 1; });
3896
+ if (transactionPromotion.coupon_code) {
3897
+ transactionPromotionObj.type = PROMOTION_TYPE.COUPON;
3898
+ transactionPromotionObj.couponCode = transactionPromotion.coupon_code;
3899
+ transactionPromotionObj.subLevelType = PROMOTION_LEVEL.TRANSACTION;
3900
+ }
3901
+ transactionPromotionArray_1.push(transactionPromotionObj);
3902
+ });
3903
+ }
3904
+ appLogger_service.AppLoggerService.logDebug(this.className, "getTransactionPromotions", "getTransactionPromotions : ", transactionPromotionArray_1);
3905
+ return transactionPromotionArray_1;
3906
+ }
3907
+ catch (error) {
3908
+ appLogger_service.AppLoggerService.logError(this.className, "getTransactionPromotions", "failed:", error);
3909
+ throw new Error(error);
3910
+ }
3911
+ };
3912
+ WebReturnSalesforceMapperBuilderClass.prototype.updateLinePromotionWithCoupon = function () {
3913
+ try {
3914
+ var transactionPromotion = {};
3915
+ var triggerPromotion_1 = [];
3916
+ if (this.orderDetails.product_items && this.orderDetails.product_items.length > 0) {
3917
+ this.orderDetails.product_items.forEach(function (product, index) {
3918
+ product.item_id = (index + 1).toString();
3919
+ if (product.price_adjustments && product.price_adjustments.length > 0) {
3920
+ product.price_adjustments.forEach(function (promotion) {
3921
+ if (promotion.coupon_code) {
3922
+ var trigger = {};
3923
+ trigger.itemLineId = product.item_id;
3924
+ trigger.quantity = product.quantity ? product.quantity : 0;
3925
+ trigger.totalQuantity = product.quantity ? product.quantity : 0;
3926
+ trigger.promotionAmount = promotion.price ? Math.abs(promotion.price) : 0;
3927
+ trigger.refundedReason = promotion.coupon_code ? promotion.coupon_code : '';
3928
+ trigger.refundedReasonDescription = promotion.item_text ? promotion.item_text : '';
3929
+ trigger.promotionId = promotion.promotion_id;
3930
+ triggerPromotion_1.push(trigger);
3931
+ }
3932
+ });
3933
+ }
3934
+ });
3935
+ }
3936
+ if (triggerPromotion_1.length > 0) {
3937
+ transactionPromotion.displayText = triggerPromotion_1[0].refundedReasonDescription;
3938
+ transactionPromotion.name = triggerPromotion_1[0].refundedReason;
3939
+ transactionPromotion.promotionAmount = -(triggerPromotion_1.reduce(function (n, _a) {
3940
+ var promotionAmount = _a.promotionAmount;
3941
+ return n + promotionAmount;
3942
+ }, 0));
3943
+ transactionPromotion.promotionId = triggerPromotion_1[0].promotionId;
3944
+ transactionPromotion.promotionInfo = triggerPromotion_1[0].refundedReasonDescription;
3945
+ transactionPromotion.couponCode = triggerPromotion_1[0].refundedReason;
3946
+ transactionPromotion.itemLineIds = [];
3947
+ transactionPromotion.type = PROMOTION_TYPE.COUPON;
3948
+ transactionPromotion.subLevelType = PROMOTION_LEVEL.LINE;
3949
+ transactionPromotion.trigger = triggerPromotion_1;
3950
+ }
3951
+ appLogger_service.AppLoggerService.logDebug(this.className, "updateLinePromotionWithCoupon", "transactionPromotion", transactionPromotion);
3952
+ if (!this.webReturnObject.basket.transactionPromotion) {
3953
+ this.webReturnObject.basket.transactionPromotion = [];
3954
+ }
3955
+ if (transactionPromotion && transactionPromotion.promotionId) {
3956
+ this.webReturnObject.basket.transactionPromotion.push(transactionPromotion);
3957
+ }
3958
+ return this;
3959
+ }
3960
+ catch (error) {
3961
+ appLogger_service.AppLoggerService.logError(this.className, "updateLinePromotionWithCoupon", "linePromotion mapping=> failed:", error);
3962
+ throw new Error(error);
3963
+ }
3964
+ };
3965
+ WebReturnSalesforceMapperBuilderClass.prototype.updateTransactionPromotionPrtionCalc = function () {
3966
+ var _this = this;
3967
+ if (this.webReturnObject.basket.transactionPromotion && this.webReturnObject.basket.transactionPromotion.length > 0) {
3968
+ this.webReturnObject.basket.transactionPromotion.forEach(function (tr) {
3969
+ _this.transactionPromotionProductPortionCalc(_this.webReturnObject, tr);
3970
+ });
3971
+ }
3972
+ return this;
3973
+ };
3974
+ WebReturnSalesforceMapperBuilderClass.prototype.transactionPromotionProductPortionCalc = function (txDoc, promotion) {
3975
+ var _this = this;
3976
+ appLogger_service.AppLoggerService.logDebug(this.className, "transactionPromotionProductPortionCalc", "trnsactionPromotion: " + JSON.stringify(promotion));
3977
+ if (promotion.type === PROMOTION_TYPE.COUPON && promotion.subLevelType === PROMOTION_LEVEL.LINE) {
3978
+ txDoc.basket.products.forEach(function (product) {
3979
+ product = _this.validateProductItemDiscount(product);
3980
+ if (promotion.trigger && promotion.trigger.length > 0) {
3981
+ promotion.trigger.forEach(function (t) {
3982
+ if (t.itemLineId === product.itemLineId.toString()) {
3983
+ product.itemDiscounts.trnPromotionsPortion += t.promotionAmount;
3984
+ }
3985
+ });
3986
+ }
3987
+ });
3988
+ }
3989
+ else {
3990
+ txDoc.basket.products.forEach(function (product) {
3991
+ product = _this.validateProductItemDiscount(product);
3992
+ if (promotion.itemLineIds.includes(+product.itemLineId)) {
3993
+ var productItem = _this.orderDetails.product_items.find(function (productItem) { return productItem.product_id === product.SKU; });
3994
+ var transactionPromotionPortion = (productItem && productItem.price_after_item_discount && productItem.price_after_order_discount) ?
3995
+ (productItem.price_after_item_discount - productItem.price_after_order_discount) : 0;
3996
+ product.itemDiscounts.trnPromotionsPortion += _this.numberUtilService.trimTo2Decimal2(transactionPromotionPortion);
3997
+ }
3998
+ });
3999
+ }
4000
+ return txDoc;
4001
+ };
4002
+ WebReturnSalesforceMapperBuilderClass.prototype.validateProductItemDiscount = function (product) {
4003
+ if (!product.itemDiscounts) {
4004
+ product.itemDiscounts = {
4005
+ trnDiscountsPortion: 0,
4006
+ trnPromotionsPortion: 0,
4007
+ refundPortion: 0,
4008
+ };
4009
+ }
4010
+ return product;
4011
+ };
4012
+ WebReturnSalesforceMapperBuilderClass.prototype.customer = function () {
4013
+ appLogger_service.AppLoggerService.logDebug(this.className, "customer", "customer mapping started...");
4014
+ var customerObj = {};
4015
+ customerObj.email = this.orderDetails.customer_info && this.orderDetails.customer_info.email ? this.orderDetails.customer_info.email : '';
4016
+ customerObj.firstName = this.orderDetails.billing_address && this.orderDetails.billing_address.first_name ? this.orderDetails.billing_address.first_name : '';
4017
+ customerObj.lastName = this.orderDetails.billing_address && this.orderDetails.billing_address.last_name ? this.orderDetails.billing_address.last_name : '';
4018
+ var shippingAddress = [];
4019
+ this.orderDetails.shipments.forEach(function (shipment) {
4020
+ var shippingAddressObj = {};
4021
+ shippingAddressObj.id = shipment.shipping_address && shipment.shipping_address.id ? shipment.shipping_address.id : '';
4022
+ shippingAddressObj.countryCode = shipment.shipping_address && shipment.shipping_address.country_code ? shipment.shipping_address.country_code : '';
4023
+ shippingAddressObj.address1 = shipment.shipping_address && shipment.shipping_address.address1 ? shipment.shipping_address.address1 : '';
4024
+ shippingAddressObj.city = shipment.shipping_address && shipment.shipping_address.city ? shipment.shipping_address.city : '';
4025
+ shippingAddressObj.country = '';
4026
+ shippingAddressObj.postCode = shipment.shipping_address && shipment.shipping_address.postal_code ? shipment.shipping_address.postal_code : '';
4027
+ shippingAddress.push(shippingAddressObj);
4028
+ });
4029
+ customerObj.shippingAddress = shippingAddress;
4030
+ var billingAddress = [];
4031
+ var billingAddressObj = {};
4032
+ billingAddressObj.id = this.orderDetails.billing_address && this.orderDetails.billing_address.id ? this.orderDetails.billing_address.id : '';
4033
+ billingAddressObj.countryCode = this.orderDetails.billing_address && this.orderDetails.billing_address.country_code ? this.orderDetails.billing_address.country_code : '';
4034
+ billingAddressObj.address1 = this.orderDetails.billing_address && this.orderDetails.billing_address.address1 ? this.orderDetails.billing_address.address1 : '';
4035
+ billingAddressObj.city = this.orderDetails.billing_address && this.orderDetails.billing_address.city ? this.orderDetails.billing_address.city : '';
4036
+ billingAddressObj.country = '';
4037
+ billingAddressObj.postCode = '';
4038
+ billingAddress.push(billingAddressObj);
4039
+ customerObj.billingAddress = billingAddress;
4040
+ var shipmentDetails = [];
4041
+ this.orderDetails.shipments.forEach(function (shipment) {
4042
+ var shipmentDetailsObj = {};
4043
+ shipmentDetailsObj.id = shipment.shipment_id ? shipment.shipment_id : '';
4044
+ shipmentDetailsObj.deliveryGroup = shipment.shipment_id ? shipment.shipment_id : '';
4045
+ shipmentDetails.push(shipmentDetailsObj);
4046
+ });
4047
+ customerObj.shipmentDetails = shipmentDetails;
4048
+ this.webReturnObject.customer = customerObj;
4049
+ appLogger_service.AppLoggerService.logDebug(this.className, "customer", "customer mapping ended...");
4050
+ return this;
4051
+ };
4052
+ WebReturnSalesforceMapperBuilderClass.prototype.isInStoreOrder = function () {
4053
+ appLogger_service.AppLoggerService.logDebug(this.className, "isInStoreOrder", "isInStoreOrder mapping started...");
4054
+ if (this.orderDetails.c_isInStoreOrder) {
4055
+ this.webReturnObject.isInStoreOrder = true;
4056
+ }
4057
+ appLogger_service.AppLoggerService.logDebug(this.className, "isInStoreOrder", "isInStoreOrder mapping ended...");
4058
+ return this;
4059
+ };
4060
+ WebReturnSalesforceMapperBuilderClass.prototype.externalTransactionDetails = function () {
4061
+ var _this = this;
4062
+ appLogger_service.AppLoggerService.logDebug(this.className, "externalTransactionDetails", "externalTransactionDetails mapping started...");
4063
+ var externalTransactionDetails = [];
4064
+ if (this.orderDetails.shipments && this.orderDetails.shipments.length > 0) {
4065
+ this.orderDetails.shipments.forEach(function (shipment) {
4066
+ var externalTransactionDetailsObj = {};
4067
+ var transactionInfo = {};
4068
+ externalTransactionDetailsObj.uniqueId = _this.orderDetails.order_no ? _this.orderDetails.order_no : '';
4069
+ externalTransactionDetailsObj.providerType = PROVIDERS.SALESFORCE;
4070
+ transactionInfo.shippingId = shipment.shipping_method && shipment.shipping_method.id ? shipment.shipping_method.id : '';
4071
+ transactionInfo.externalShippingId = shipment.shipment_id ? shipment.shipment_id : '';
4072
+ externalTransactionDetailsObj.details = transactionInfo;
4073
+ externalTransactionDetails.push(externalTransactionDetailsObj);
4074
+ });
4075
+ }
4076
+ this.webReturnObject.externalTransactionDetails = externalTransactionDetails;
4077
+ appLogger_service.AppLoggerService.logDebug(this.className, "externalTransactionDetails", "externalTransactionDetails mapping ended...");
4078
+ return this;
4079
+ };
4080
+ WebReturnSalesforceMapperBuilderClass.prototype.basketSummary = function () {
4081
+ appLogger_service.AppLoggerService.logDebug(this.className, "basketSummary", "basketSummary mapping started...");
4082
+ var basketSummary = {};
4083
+ var basketSummaryWebOrder = {};
4084
+ var linePromotionTotal = this.webReturnObject.basket.linePromotion.map(function (linePromotion) { return linePromotion.promotionAmount; }).reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0);
4085
+ var transactionPromotionTotal = this.webReturnObject.basket.transactionPromotion.map(function (transactionPromotion) { return transactionPromotion.promotionAmount; }).reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0);
4086
+ basketSummary.discountTotal = linePromotionTotal + transactionPromotionTotal;
4087
+ basketSummary.VATTotal = this.orderDetails.tax_total ? this.orderDetails.tax_total : 0;
4088
+ basketSummary.saleTotal = this.orderDetails.order_total ? this.orderDetails.order_total : 0;
4089
+ basketSummary.basketTotal = this.orderDetails.order_total ? this.orderDetails.order_total : 0;
4090
+ basketSummary.totalItems = this.orderDetails.product_items && this.orderDetails.product_items.length > 0 ? this.orderDetails.product_items.length : 0;
4091
+ basketSummary.shippingTotal = this.orderDetails.shipping_total ? this.orderDetails.shipping_total : 0;
4092
+ basketSummary.basketTotalWithShippingTotal = this.orderDetails.order_total ? this.orderDetails.order_total : 0;
4093
+ basketSummaryWebOrder.shippingTotal = this.orderDetails.shipping_total ? this.orderDetails.shipping_total : 0;
4094
+ basketSummaryWebOrder.basketTotalWithShippingTotal = this.orderDetails.order_total ? this.orderDetails.order_total : 0;
4095
+ basketSummary.webOrder = basketSummaryWebOrder;
4096
+ this.webReturnObject.basketSummary = basketSummary;
4097
+ appLogger_service.AppLoggerService.logDebug(this.className, "basketSummary", "basketSummary mapping ended...");
4098
+ return this;
4099
+ };
4100
+ WebReturnSalesforceMapperBuilderClass.prototype.deviceId = function (deviceId) {
4101
+ this.webReturnObject.deviceId = deviceId;
4102
+ return this;
4103
+ };
4104
+ WebReturnSalesforceMapperBuilderClass.prototype.terminalId = function (terminalId) {
4105
+ this.webReturnObject.terminalId = terminalId;
4106
+ return this;
4107
+ };
4108
+ WebReturnSalesforceMapperBuilderClass.prototype.orgCode = function (orgCode) {
4109
+ this.webReturnObject.orgCode = orgCode;
4110
+ return this;
4111
+ };
4112
+ WebReturnSalesforceMapperBuilderClass.prototype.storeId = function (storeId) {
4113
+ this.webReturnObject.storeId = storeId;
4114
+ return this;
4115
+ };
4116
+ WebReturnSalesforceMapperBuilderClass.prototype.storeNodeId = function (storeNodeId) {
4117
+ this.webReturnObject.storeNodeId = storeNodeId;
4118
+ return this;
4119
+ };
4120
+ WebReturnSalesforceMapperBuilderClass.prototype.storeNodeStructure = function (storeNodeStructure) {
4121
+ this.webReturnObject.storeNodeStructure = storeNodeStructure;
4122
+ return this;
4123
+ };
4124
+ WebReturnSalesforceMapperBuilderClass.prototype.docId = function (docId) {
4125
+ this.webReturnObject.id = docId;
4126
+ return this;
4127
+ };
4128
+ WebReturnSalesforceMapperBuilderClass.prototype.updateUserID = function (userID) {
4129
+ this.webReturnObject.userId = userID;
4130
+ return this;
4131
+ };
4132
+ WebReturnSalesforceMapperBuilderClass.prototype.updateUserName = function (name) {
4133
+ this.webReturnObject.userName = name;
4134
+ return this;
4135
+ };
4136
+ WebReturnSalesforceMapperBuilderClass.prototype.build = function () {
4137
+ appLogger_service.AppLoggerService.logDebug(this.className, "build", "mapping done...");
4138
+ return this.webReturnObject;
4139
+ };
4140
+ WebReturnSalesforceMapperBuilderClass.prototype.getUTCDateTime = function (date) {
4141
+ if (date) {
4142
+ return new Date(date).toISOString();
4143
+ }
4144
+ };
4145
+ return WebReturnSalesforceMapperBuilderClass;
4146
+ }());
4147
+
4148
+ /*
4149
+ * Public API Surface of mapper-library
4150
+ */
4151
+
4152
+ /**
4153
+ * Generated bundle index. Do not edit.
4154
+ */
4155
+
4156
+ exports.MapperLibraryComponent = MapperLibraryComponent;
4157
+ exports.MapperLibraryModule = MapperLibraryModule;
4158
+ exports.RJMapperBuilderClass = RJMapperBuilderClass;
4159
+ exports.WebReturnMapperBuilderClass = WebReturnMapperBuilderClass;
4160
+ exports.WebReturnSalesforceMapperBuilderClass = WebReturnSalesforceMapperBuilderClass;
4161
+
4162
+ Object.defineProperty(exports, '__esModule', { value: true });
4163
+
4164
+ }));
4165
+ //# sourceMappingURL=pmcretail-mapper-library.umd.js.map