@pmcretail/mapper-library 0.0.43 → 0.0.44

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