@configura/web-api 1.3.0-alpha.3 → 1.3.0

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 (57) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +1 -1
  3. package/dist/CatalogueAPI.d.ts +502 -448
  4. package/dist/CatalogueAPI.js +206 -206
  5. package/dist/CfgMeasure.d.ts +33 -0
  6. package/dist/CfgMeasure.js +30 -0
  7. package/dist/CfgProduct.d.ts +217 -116
  8. package/dist/CfgProduct.js +634 -588
  9. package/dist/index.d.ts +16 -15
  10. package/dist/index.js +16 -15
  11. package/dist/material/CfgMaterialMapping.d.ts +7 -7
  12. package/dist/material/CfgMaterialMapping.js +181 -176
  13. package/dist/material/CfgMtrlApplication.d.ts +18 -18
  14. package/dist/material/CfgMtrlApplication.js +43 -43
  15. package/dist/material/CfgMtrlApplicationSource.d.ts +7 -7
  16. package/dist/material/CfgMtrlApplicationSource.js +8 -8
  17. package/dist/material/CfgMtrlSource.d.ts +19 -19
  18. package/dist/material/CfgMtrlSource.js +40 -40
  19. package/dist/material/CfgMtrlSourceWithMetaData.d.ts +7 -7
  20. package/dist/material/CfgMtrlSourceWithMetaData.js +1 -1
  21. package/dist/productConfiguration/CfgFeature.d.ts +160 -134
  22. package/dist/productConfiguration/CfgFeature.js +593 -483
  23. package/dist/productConfiguration/CfgOption.d.ts +128 -112
  24. package/dist/productConfiguration/CfgOption.js +394 -293
  25. package/dist/productConfiguration/CfgProductConfiguration.d.ts +120 -50
  26. package/dist/productConfiguration/CfgProductConfiguration.js +307 -198
  27. package/dist/productConfiguration/filters.d.ts +7 -7
  28. package/dist/productConfiguration/filters.js +29 -29
  29. package/dist/productConfiguration/productParamsGenerator.d.ts +15 -15
  30. package/dist/productConfiguration/productParamsGenerator.js +51 -51
  31. package/dist/productConfiguration/utilitiesProductConfiguration.d.ts +17 -9
  32. package/dist/productConfiguration/utilitiesProductConfiguration.js +80 -61
  33. package/dist/productLoader.d.ts +33 -11
  34. package/dist/productLoader.js +49 -41
  35. package/dist/tests/testData/collectorForTest.d.ts +73 -73
  36. package/dist/tests/testData/collectorForTest.js +195 -195
  37. package/dist/tests/testData/dummyProductForTest.d.ts +4 -4
  38. package/dist/tests/testData/dummyProductForTest.js +36 -35
  39. package/dist/tests/testData/testDataAdditionalProductInAdditionalProductInProductForTest.d.ts +32 -32
  40. package/dist/tests/testData/testDataAdditionalProductInAdditionalProductInProductForTest.js +381 -368
  41. package/dist/tests/testData/testDataCachedGetProduct.d.ts +5 -5
  42. package/dist/tests/testData/testDataCachedGetProduct.js +205 -199
  43. package/dist/tests/testData/testDataCachedPostValidate.d.ts +7 -7
  44. package/dist/tests/testData/testDataCachedPostValidate.js +195 -189
  45. package/dist/tests/testData/testDataNoAdditionalProductNoPropagateForTest.d.ts +3 -3
  46. package/dist/tests/testData/testDataNoAdditionalProductNoPropagateForTest.js +1119 -1117
  47. package/dist/tests/testData/testDataProductAggregatedPrice.d.ts +28 -28
  48. package/dist/tests/testData/testDataProductAggregatedPrice.js +210 -205
  49. package/dist/tests/testData/testDataUpcharge.d.ts +29 -29
  50. package/dist/tests/testData/testDataUpcharge.js +163 -159
  51. package/dist/utilitiesCatalogueData.d.ts +22 -20
  52. package/dist/utilitiesCatalogueData.js +64 -64
  53. package/dist/utilitiesCataloguePermission.d.ts +39 -39
  54. package/dist/utilitiesCataloguePermission.js +84 -84
  55. package/dist/utilitiesNumericValues.d.ts +25 -0
  56. package/dist/utilitiesNumericValues.js +109 -0
  57. package/package.json +3 -3
@@ -1,588 +1,634 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { AggregatedLoadingObservable, compareArrays, count, Observable, } from "@configura/web-utilities";
11
- import { ProductConfigurationBubbleMode } from "./productConfiguration/CfgOption.js";
12
- import { CfgProductConfiguration } from "./productConfiguration/CfgProductConfiguration.js";
13
- import { collectAdditionalProductRefs } from "./productConfiguration/utilitiesProductConfiguration.js";
14
- import { wrapWithCache } from "./productLoader.js";
15
- import { comparePricesObjects, correctDefaultsOnCatalogueParams, makeProductKey, } from "./utilitiesCatalogueData.js";
16
- function completeSettings(uncompleteSettings) {
17
- var _a, _b;
18
- return {
19
- strictSelectOneSelectionCount: (_a = uncompleteSettings === null || uncompleteSettings === void 0 ? void 0 : uncompleteSettings.strictSelectOneSelectionCount) !== null && _a !== void 0 ? _a : false,
20
- strictSetApiSelectionMatch: (_b = uncompleteSettings === null || uncompleteSettings === void 0 ? void 0 : uncompleteSettings.strictSetApiSelectionMatch) !== null && _b !== void 0 ? _b : false,
21
- };
22
- }
23
- export var CfgProductBubbleMode;
24
- (function (CfgProductBubbleMode) {
25
- /// Stop bubbling
26
- /// This mode is support for internal functionality is not expected to be used by integrators
27
- CfgProductBubbleMode["Stop"] = "Stop";
28
- /// Bubble to the parent CfgProduct up the tree. This makes the CfgProduct we
29
- /// we call from notify that it has changed, and the CfgProduct above switch out the reference
30
- /// to this.
31
- /// This mode is support for internal functionality is not expected to be used by integrators
32
- CfgProductBubbleMode["OneLevel"] = "OneLevel";
33
- /// Bubble to the root CfgProduct
34
- /// This mode is support for internal functionality is not expected to be used by integrators
35
- CfgProductBubbleMode["ToRoot"] = "ToRoot";
36
- /// Bubble to the root CfgProduct and turn on all optional CfgProducts on the way up
37
- /// This mode is support for internal functionality is not expected to be used by integrators
38
- CfgProductBubbleMode["ToRootAndBubbleSelected"] = "ToRootAndBubbleSelected";
39
- })(CfgProductBubbleMode || (CfgProductBubbleMode = {}));
40
- function isDescriptionMatch(l, r) {
41
- const ld = l.description;
42
- const rd = r.description;
43
- return ld !== undefined && rd !== undefined && ld.toLowerCase() === rd.toLowerCase();
44
- }
45
- /// This class is meant to only be used through CfgProduct. It should never
46
- /// be instantiated on its own. Normally the internal state of this class
47
- /// should never be directly modified. CfgProduct is the class that should
48
- /// be used and interacted with.
49
- export class _CfgProductInternal {
50
- constructor(initSuccess, initFail, _productLoaderRaw, lang, catId, partNumber, settings, optional, selected, rootFeatureRefs, allRawFeatures, uuid, _rawProductData, apiSelection, loadingObservable, refKey, refDescription, parent, root, transform) {
51
- this._productLoaderRaw = _productLoaderRaw;
52
- this.lang = lang;
53
- this.catId = catId;
54
- this.partNumber = partNumber;
55
- this.settings = settings;
56
- this.uuid = uuid;
57
- this._rawProductData = _rawProductData;
58
- this.loadingObservable = loadingObservable;
59
- this.refKey = refKey;
60
- this.refDescription = refDescription;
61
- this.parent = parent;
62
- this.transform = transform;
63
- this._destroyed = false;
64
- this.additionalProducts = [];
65
- this.changeObservable = new Observable();
66
- this.destroy = () => {
67
- this._destroyed = true;
68
- this.changeObservable.stopAllListen();
69
- this.configuration.stopAllListenForChange();
70
- for (const additionalProduct of this.additionalProducts || []) {
71
- additionalProduct.destroy();
72
- }
73
- };
74
- this._notifyAllOfChange = (bubbleMode) => __awaiter(this, void 0, void 0, function* () {
75
- if (bubbleMode === CfgProductBubbleMode.Stop) {
76
- return;
77
- }
78
- const parent = this.parent;
79
- const freshRef = CfgProduct._makeNewRefFrom(this);
80
- this.changeObservable.notifyAll({ freshRef });
81
- if (parent !== undefined) {
82
- yield parent._additionalProductHasChanged(freshRef, bubbleMode === CfgProductBubbleMode.OneLevel
83
- ? CfgProductBubbleMode.Stop
84
- : bubbleMode);
85
- }
86
- });
87
- /// Called when a child (additional product or the configuration) has changed
88
- this._childHasChanged = (bubbleMode) => __awaiter(this, void 0, void 0, function* () {
89
- if (bubbleMode === CfgProductBubbleMode.ToRootAndBubbleSelected &&
90
- this.optional &&
91
- !this.selected) {
92
- yield this.setSelected(true, bubbleMode);
93
- return;
94
- }
95
- yield this._notifyAllOfChange(bubbleMode);
96
- });
97
- /// Called by child to tell its parent that it has changed.
98
- this._additionalProductHasChanged = (freshRef, bubbleMode) => __awaiter(this, void 0, void 0, function* () {
99
- const i = this.additionalProducts.findIndex((a) => a.isBackedBySame(freshRef));
100
- if (i !== -1) {
101
- // Child additional product might not be found. This probably means that propagate
102
- // has chopped the branch your on. Let's say we have products A -> B -> C.
103
- // We change an option on C. This is propagated to product A. Product A now
104
- // changes its additional product so that B is no longer a child of A. Hence
105
- // C no longer is part of the tree. Odd, but fully permitted.
106
- this.additionalProducts[i] = freshRef;
107
- }
108
- yield this._childHasChanged(bubbleMode);
109
- });
110
- /// Called by the configuration to tell its parent that it has changed.
111
- this._configurationHasChanged = (freshRef, bubbleMode) => __awaiter(this, void 0, void 0, function* () {
112
- this._configuration = freshRef;
113
- switch (bubbleMode) {
114
- case ProductConfigurationBubbleMode.ValidateAndBubbleSelected:
115
- // The revalidate call will continue the bubble
116
- yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, this._productLoaderRaw);
117
- return;
118
- case ProductConfigurationBubbleMode.Validate:
119
- // The revalidate call will continue the bubble
120
- yield this._revalidate(CfgProductBubbleMode.ToRoot, this._productLoaderRaw);
121
- return;
122
- case ProductConfigurationBubbleMode.ToParentProduct:
123
- // Do not continue bubble as we have reached the parent CfgProduct
124
- return;
125
- case ProductConfigurationBubbleMode.OneLevel:
126
- yield this._childHasChanged(CfgProductBubbleMode.OneLevel);
127
- return;
128
- case ProductConfigurationBubbleMode.Stop:
129
- yield this._childHasChanged(CfgProductBubbleMode.Stop);
130
- return;
131
- case ProductConfigurationBubbleMode.ToRoot:
132
- yield this._childHasChanged(CfgProductBubbleMode.ToRoot);
133
- return;
134
- }
135
- });
136
- this.getApiSelection = () => ({
137
- refKey: this.refKey,
138
- selected: this.selected,
139
- selOptions: this.configuration.getApiSelection(),
140
- additionalProducts: this.additionalProducts.map((additionalProduct) => additionalProduct.getApiSelection()),
141
- });
142
- this.setApiSelection = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
143
- // wrap with cache will make getProduct for this function call use the same server call
144
- // for the same product with the same params
145
- productLoaderForGroupedLoad =
146
- productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
147
- const configurationChange = yield this.configuration._internal.setApiSelection(s.selOptions, false);
148
- let change = configurationChange;
149
- if (this.optional) {
150
- if (yield this.setSelected(s.selected !== false, CfgProductBubbleMode.Stop)) {
151
- change = true;
152
- }
153
- }
154
- yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
155
- const apiSelectionAdditionalProducts = s.additionalProducts || [];
156
- const additionalProducts = this.additionalProducts.slice();
157
- const additionalProductsCount = additionalProducts.length;
158
- const apiSelectionAdditionalProductsCount = apiSelectionAdditionalProducts.length;
159
- if (apiSelectionAdditionalProductsCount !== additionalProductsCount) {
160
- throw new Error(`Additional products are not same length. This product: "${this.key}". This product additional products count: ${additionalProductsCount}. Passed apiSelection additional products count: ${apiSelectionAdditionalProductsCount}`);
161
- }
162
- if ((yield Promise.all(apiSelectionAdditionalProducts.map((apiSelectionChild) => {
163
- const refKey = apiSelectionChild.refKey;
164
- if (refKey === undefined) {
165
- throw new Error("Additional product api configurations must have refKey.");
166
- }
167
- const i = additionalProducts.findIndex((a) => refKey === a.refKey);
168
- if (i === -1) {
169
- throw new Error(`Additional product not found. This product: "${this.key}". refKey of not found additional product: "${refKey}"`);
170
- }
171
- const additionalProduct = additionalProducts.splice(i, 1)[0]; // Splicing like this is okay because this is done synchronous. The setCon. is what is async.
172
- return additionalProduct._internal.setApiSelection(apiSelectionChild, doValidate, productLoaderForGroupedLoad);
173
- }))).some((b) => b)) {
174
- change = true;
175
- }
176
- if (doValidate && configurationChange) {
177
- yield this._revalidate(CfgProductBubbleMode.ToRoot, productLoaderForGroupedLoad);
178
- }
179
- else if (change) {
180
- // As setApiSelection is done recursively each level takes care of its own notifications
181
- // so we only need to bubble one level to notify this and swap out the reference in the
182
- // parent.
183
- yield this._notifyAllOfChange(CfgProductBubbleMode.OneLevel);
184
- }
185
- return change;
186
- });
187
- this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => {
188
- if (!this.configuration.structureCompare(other.configuration, strictOrder, descriptionMatch)) {
189
- return false;
190
- }
191
- return compareArrays(this.additionalProducts, other.additionalProducts, (l, r) => (!descriptionMatch || (descriptionMatch && isDescriptionMatch(l, r))) &&
192
- l.structureCompare(r, strictOrder, descriptionMatch), !descriptionMatch);
193
- };
194
- this.tryMatchSelection = (other, descriptionMatch = false, // Match on case insensitive description, not code
195
- productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
196
- // wrap with cache will make getProduct for this function call use the same server call
197
- // for the same product with the same params
198
- productLoaderForGroupedLoad =
199
- productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
200
- let change = false;
201
- if (this.optional && other.optional) {
202
- if (yield this.setSelected(other.selected, CfgProductBubbleMode.Stop)) {
203
- change = true;
204
- }
205
- }
206
- const configurationChange = yield this.configuration._internal.tryMatchSelection(other.configuration._internal, descriptionMatch, false);
207
- if (configurationChange) {
208
- change = true;
209
- yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, productLoaderForGroupedLoad);
210
- }
211
- else if (change) {
212
- yield this._notifyAllOfChange(CfgProductBubbleMode.ToRootAndBubbleSelected);
213
- }
214
- const thisAdditionalProducts = this.additionalProducts;
215
- const otherAdditionalProducts = other.additionalProducts;
216
- const promises = [];
217
- if (descriptionMatch) {
218
- for (const otherAdditionalProduct of otherAdditionalProducts) {
219
- if (1 <
220
- count(otherAdditionalProducts, (product) => isDescriptionMatch(product, otherAdditionalProduct))) {
221
- console.warn("tryMatchSelection will ignore products that have the same description");
222
- continue;
223
- }
224
- const toTryMatchProducts = thisAdditionalProducts.filter((product) => isDescriptionMatch(product, otherAdditionalProduct));
225
- if (1 < toTryMatchProducts.length) {
226
- console.warn("tryMatchSelection will ignore products that have the same description");
227
- continue;
228
- }
229
- if (toTryMatchProducts.length === 0) {
230
- continue;
231
- }
232
- promises.push(toTryMatchProducts[0]._internal.tryMatchSelection(otherAdditionalProduct._internal, descriptionMatch, productLoaderForGroupedLoad));
233
- }
234
- }
235
- else {
236
- if (thisAdditionalProducts.length !== otherAdditionalProducts.length) {
237
- console.warn("tryMatchSelection not same count, will not try to match further.");
238
- return change;
239
- }
240
- for (let i = 0; i < thisAdditionalProducts.length; i++) {
241
- promises.push(thisAdditionalProducts[i]._internal.tryMatchSelection(otherAdditionalProducts[i]._internal, descriptionMatch, productLoaderForGroupedLoad));
242
- }
243
- }
244
- if ((yield Promise.all(promises)).some((b) => b)) {
245
- change = true;
246
- }
247
- return change;
248
- });
249
- /// Only features in selected options and selected additional products
250
- this._getDescendantFeaturesWithCode = (code) => this.additionalProducts.reduce((agg, additionalProduct) => {
251
- if (additionalProduct.selected) {
252
- agg.push(...additionalProduct._internal._getDescendantFeaturesWithCode(code));
253
- }
254
- return agg;
255
- }, this._configuration._internal._getFeaturesWithCode(code));
256
- /// Do a validate call for this product. It does not validate additional products, only
257
- /// this product in isolation. The validation result is applied on the configuration.
258
- /// Then additional products are synced (unloaded, loaded etc.) Finally the changes
259
- /// bubble up the tree.
260
- this._revalidate = (bubbleMode, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
261
- const { _configuration: configuration } = this;
262
- const token = this.loadingObservable.startChildLoading();
263
- this._revalidateInProgressToken = token;
264
- try {
265
- const response = yield productLoaderForGroupedLoad.postValidate(Object.assign(Object.assign({ lang: this.lang }, correctDefaultsOnCatalogueParams(this.catId)), { partNumber: this.partNumber }), { selOptions: configuration.getApiSelection() });
266
- // The revalidateInProgressToken is used to know if some other revalidate
267
- // call has happened after this call, thereby making this call obsolete.
268
- // This is a bit crude in that it does not actually cancel previous validate
269
- // calls, but this is fine because 1. it is hard to cancel a call, especially
270
- // if you wanna have clear code 2. the actual calls are small anyhow 3. most
271
- // of all, the heavy work happens on the server, and that work will not be
272
- // cancelled even if we would cancel the call.
273
- if (this._revalidateInProgressToken !== token) {
274
- return false;
275
- }
276
- // After a successful validate-call we will always assume there
277
- // is a change. It would be possible to compare relevant parts
278
- // of productData, consider the result of setApiSelection and
279
- // syndAndLoad, however the code comparing productData would be fragile
280
- // and likely to break if new data-fields were added.
281
- if (this._destroyed) {
282
- return false;
283
- }
284
- const { productData, rootFeatureRefs } = response;
285
- const pricesUpdated = !comparePricesObjects(this.prices, productData.partsData.prices);
286
- this._rawProductData = productData;
287
- if (rootFeatureRefs !== undefined) {
288
- configuration._internal.populateFeatures(rootFeatureRefs);
289
- }
290
- if (pricesUpdated) {
291
- this._configuration._internal._freshRefDescendants();
292
- this._configuration = CfgProductConfiguration._makeNewRefFrom(this._configuration._internal);
293
- }
294
- yield configuration._internal.setApiSelection(productData.partsData.selOptions || [], false);
295
- yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
296
- if (this._destroyed) {
297
- return false;
298
- }
299
- yield this._notifyAllOfChange(bubbleMode);
300
- return true;
301
- }
302
- catch (e) {
303
- throw e;
304
- }
305
- finally {
306
- this.loadingObservable.stopChildLoading(token);
307
- }
308
- });
309
- /// Based on this configuration find what additional products should be shown and not,
310
- /// unload (destroy) those that should no longer be shown, load the new ones.
311
- this._syncAndLoadAdditionalProducts = (productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
312
- const { lang, _productLoaderRaw: productLoaderRaw, rawProductData: productData, configuration, additionalProducts: currentAdditionalProducts, } = this;
313
- const additionalProductRefs = [
314
- ...(productData.additionalProductRefs || []),
315
- ...collectAdditionalProductRefs(configuration),
316
- ].map((prodRef, originalIndex) => ({
317
- prodRef,
318
- originalIndex,
319
- }));
320
- let change = false;
321
- let i = currentAdditionalProducts.length;
322
- while (i--) {
323
- const currentAdditionalProduct = currentAdditionalProducts[i];
324
- const refKey = currentAdditionalProduct.refKey;
325
- const j = additionalProductRefs.findIndex((p) => p.prodRef.refKey === refKey);
326
- if (j === -1) {
327
- currentAdditionalProduct.destroy();
328
- currentAdditionalProducts.splice(i, 1);
329
- change = true;
330
- }
331
- else {
332
- additionalProductRefs.splice(j, 1);
333
- }
334
- }
335
- const token = this.loadingObservable.startChildLoading();
336
- try {
337
- if (additionalProductRefs.length !== 0) {
338
- change = true;
339
- }
340
- const newAdditionalProducts = yield Promise.all(additionalProductRefs.map((p) => (() => __awaiter(this, void 0, void 0, function* () {
341
- const additionalProductRef = p.prodRef;
342
- return {
343
- originalIndex: p.originalIndex,
344
- product: CfgProduct._makeNewRefFrom(yield _CfgProductInternal.make(productLoaderRaw, productLoaderForGroupedLoad, lang, additionalProductRef.catId, additionalProductRef.partNumber, this.settings, additionalProductRef.optional === true, this.loadingObservable, additionalProductRef.refKey, additionalProductRef.refDescription, this, this.root, additionalProductRef.transform)),
345
- };
346
- }))()));
347
- if (this._destroyed) {
348
- return change;
349
- }
350
- for (const newAdditionalProduct of newAdditionalProducts) {
351
- currentAdditionalProducts.splice(newAdditionalProduct.originalIndex, 0, newAdditionalProduct.product);
352
- }
353
- return change;
354
- }
355
- catch (e) {
356
- throw e;
357
- }
358
- finally {
359
- this.loadingObservable.stopChildLoading(token);
360
- }
361
- });
362
- this.root = root || this;
363
- this.key = makeProductKey(catId, refKey || partNumber);
364
- this._selected = optional ? selected : undefined;
365
- this.isAdditionalProduct = parent !== undefined;
366
- this._configuration = CfgProductConfiguration.make(initSuccess, initFail, rootFeatureRefs, allRawFeatures, apiSelection, this, this.root);
367
- }
368
- get selected() {
369
- return this._selected !== false;
370
- }
371
- clone(parent, root) {
372
- return __awaiter(this, void 0, void 0, function* () {
373
- const product = yield new Promise((initSuccess, initFail) => {
374
- const p = new _CfgProductInternal(() => {
375
- initSuccess(p);
376
- }, initFail, this._productLoaderRaw, this.lang, this.catId, this.partNumber, this.settings, this.optional, this.selected, this._configuration.rootFeatureRefs, this._configuration.allRawFeatures, this.uuid, this._rawProductData, this.configuration.getApiSelection(), new AggregatedLoadingObservable(), this.refKey, this.refDescription, parent, root, this.transform);
377
- });
378
- for (const additionalProduct of this.additionalProducts) {
379
- product.additionalProducts.push(CfgProduct._makeNewRefFrom(yield additionalProduct._internal.clone(product, root || product)));
380
- }
381
- return product;
382
- });
383
- }
384
- get description() {
385
- return this.refDescription || this._rawProductData.description;
386
- }
387
- get rootNodeSources() {
388
- return this._rawProductData.models;
389
- }
390
- get mtrlApplications() {
391
- return this._rawProductData.mtrlApplications;
392
- }
393
- get currency() {
394
- return this._rawProductData.partsData.currency;
395
- }
396
- get fractionDigits() {
397
- return this._rawProductData.partsData.rounding || 0;
398
- }
399
- get prices() {
400
- return this._rawProductData.partsData.prices;
401
- }
402
- get aggregatedPrice() {
403
- const { currency, fractionDigits, rawProductData } = this;
404
- const { partsData } = rawProductData;
405
- let { listPrice, basePrice } = partsData;
406
- if (this._selected === false) {
407
- return { basePrice: 0, listPrice: 0, currency, fractionDigits };
408
- }
409
- for (const additionalProduct of this.additionalProducts || []) {
410
- const { basePrice: additionalBasePrice, listPrice: additionalListPrice, currency: additionalCurrency, fractionDigits: additionalFractionDigits, } = additionalProduct.aggregatedPrice;
411
- basePrice += additionalBasePrice;
412
- listPrice += additionalListPrice;
413
- if (currency !== additionalCurrency) {
414
- // This should not be possible
415
- // The server shouldn't return additional products with different currency from their parent
416
- throw new Error(`Currency mismatch between parent product and additional product. Parent product: "${this.key}" Additional product: "${additionalProduct.key}". Currency on parent product: ${currency}. Currency on additional product: ${additionalCurrency}`);
417
- }
418
- if (fractionDigits !== additionalFractionDigits) {
419
- // This should not be possible
420
- // The server shouldn't return additional products with different fraction digits from their parent
421
- throw new Error(`Fraction digits mismatch between parent product and additional product. Parent product: "${this.key}" Additional product: "${additionalProduct.key}". Fraction digits on parent product: ${fractionDigits}. Fraction digits on additional product: ${additionalFractionDigits}`);
422
- }
423
- }
424
- return { basePrice, listPrice, currency, fractionDigits };
425
- }
426
- get optional() {
427
- return this._selected !== undefined;
428
- }
429
- setSelected(v, bubbleMode) {
430
- return __awaiter(this, void 0, void 0, function* () {
431
- if (!this.optional) {
432
- console.warn("This product is not optional. Nothing will happen");
433
- return false;
434
- }
435
- if (this._selected === v) {
436
- return false;
437
- }
438
- this._selected = v;
439
- yield this._notifyAllOfChange(bubbleMode);
440
- return true;
441
- });
442
- }
443
- get configuration() {
444
- return this._configuration;
445
- }
446
- get rawProductData() {
447
- return this._rawProductData;
448
- }
449
- }
450
- _CfgProductInternal.make = (productLoaderRaw, productLoaderForGroupedLoad, // Used when instantiating the current product
451
- lang, catId, partNumber, settings, optional, loadingObservable, refKey, refDescription, parent, root, transform) => __awaiter(void 0, void 0, void 0, function* () {
452
- // wrap with cache will make getProduct for this function call use the same server call
453
- // for the same product with the same params
454
- productLoaderForGroupedLoad =
455
- productLoaderForGroupedLoad || wrapWithCache(productLoaderRaw);
456
- const productResponse = yield productLoaderForGroupedLoad.getProduct(Object.assign(Object.assign({ lang }, correctDefaultsOnCatalogueParams(catId)), { partNumber }));
457
- const { productData, rootFeatureRefs, features: allRawFeatures, uuid } = productResponse;
458
- const product = yield new Promise((initSuccess, initFail) => {
459
- const p = new _CfgProductInternal(() => {
460
- // We absolutely do not want anyone to assign to this._configuration. So we want that field private.
461
- // But we can not set the api selection synchronously. And the product configuration needs "this". So we use this callback.
462
- // Feel free to find a nicer more readable solution :)
463
- initSuccess(p);
464
- }, initFail, productLoaderRaw, lang, catId, partNumber, settings, optional, !optional, rootFeatureRefs, allRawFeatures, uuid, productData, productData.partsData.selOptions || [], loadingObservable, refKey, refDescription, parent, root, transform);
465
- });
466
- yield product._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
467
- return product;
468
- });
469
- export class CfgProduct {
470
- constructor(_internal) {
471
- this._internal = _internal;
472
- this.isBackedBySame = (other) => this._internal === other._internal;
473
- /// Recursively marks this and descendants as destroyed so that late events
474
- /// are ignored correctly.
475
- /// If you destroy one shallow copy of this you destroy all.
476
- this.destroy = () => this._internal.destroy();
477
- /// Makes a clone of this. It is disconnected from the original.
478
- this.clone = () => __awaiter(this, void 0, void 0, function* () { return CfgProduct._makeNewRefFrom(yield this._internal.clone()); });
479
- /// Only applicable when this product is optional.
480
- /// Setting this does not cause a validation call as toggling an optional additional
481
- /// product is assumed to always be legal.
482
- this.setSelected = (v) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setSelected(v, CfgProductBubbleMode.ToRootAndBubbleSelected); });
483
- /// Experimental. Additional products lacks descriptions or keys that are suitably for structure
484
- /// compare, so we use strict-order when trying to match the additional products. This makes
485
- /// this method work nicely for different products having pretty much the same child products.
486
- this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => this._internal.structureCompare(other._internal, strictOrder, descriptionMatch);
487
- /// Experimental. Additional products lacks descriptions or keys that are suitably for try
488
- /// match, so we use strict-order when trying to match the additional products. This makes
489
- /// this method work nicely for different products having pretty much the same child products.
490
- /// This method does not propagate its selections.
491
- /// This method will cause validation calls if something change.
492
- this.tryMatchSelection = (other, descriptionMatch = false // Match on case insensitive description, not code
493
- ) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.tryMatchSelection(other._internal, descriptionMatch); });
494
- /// Gets what selections has been made on the product, recursively including product configuration,
495
- /// optional products and additional products. Used when a full view of all selections on a product
496
- /// is needed, such as when doing Render or Export.
497
- this.getApiSelection = () => this._internal.getApiSelection();
498
- /// Experimental. The API currently never sends ApiSelections for products with additional products
499
- /// downstream, so this is only provided as a convenience function if someone would for instance want
500
- /// to store previous selection states of a product by doing getApiSelection.
501
- /// This method does not propagate its selections.
502
- this.setApiSelection = (s, doValidate = false) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setApiSelection(s, doValidate); });
503
- this.listenForChange = (l) => this._internal.changeObservable.listen(l);
504
- this.stopListenForChange = (l) => this._internal.changeObservable.stopListen(l);
505
- this.stopAllListenForChange = () => this._internal.changeObservable.stopAllListen();
506
- this.listenForLoading = (l) => this._internal.loadingObservable.listen(l);
507
- this.stopListenForLoading = (l) => this._internal.loadingObservable.stopListen(l);
508
- this.stopAllListenForLoading = () => this._internal.loadingObservable.stopAllListen();
509
- }
510
- /// A client side only key that should uniquely identify this product amongst
511
- /// other additional products.
512
- get key() {
513
- return this._internal.key;
514
- }
515
- /// Only used when this product is in additional product. As a product can
516
- /// have multiple instances of the same additional product this key exists.
517
- /// It will be unique amongst child products, but not globally unique.
518
- get refKey() {
519
- return this._internal.refKey;
520
- }
521
- get lang() {
522
- return this._internal.lang;
523
- }
524
- get catId() {
525
- return this._internal.catId;
526
- }
527
- get partNumber() {
528
- return this._internal.partNumber;
529
- }
530
- get isAdditionalProduct() {
531
- return this._internal.isAdditionalProduct;
532
- }
533
- /// Only used when this product is an additional product. Root products are never optional.
534
- get optional() {
535
- return this._internal.optional;
536
- }
537
- /// Only applicable when this product is optional. If this product is not
538
- /// optional this is always true.
539
- get selected() {
540
- return this._internal.selected;
541
- }
542
- get rawProductData() {
543
- return this._internal.rawProductData;
544
- }
545
- get uuid() {
546
- return this._internal.uuid;
547
- }
548
- get sku() {
549
- return this._internal.rawProductData.sku;
550
- }
551
- get styleNr() {
552
- return this._internal.rawProductData.partsData.styleNr;
553
- }
554
- /// An URL
555
- get preview() {
556
- return this._internal.rawProductData.navImage;
557
- }
558
- get description() {
559
- return this._internal.description;
560
- }
561
- get additionalProducts() {
562
- return this._internal.additionalProducts;
563
- }
564
- get configuration() {
565
- return this._internal.configuration;
566
- }
567
- get transform() {
568
- return this._internal.transform;
569
- }
570
- get currency() {
571
- return this._internal.currency;
572
- }
573
- /// If positive the number of fraction digits, if negative
574
- /// rounding (essentially the number of zeros to the right)
575
- get fractionDigits() {
576
- return this._internal.fractionDigits;
577
- }
578
- get aggregatedPrice() {
579
- return this._internal.aggregatedPrice;
580
- }
581
- }
582
- CfgProduct.make = (productLoader, lang, catId, partNumber, settings) => __awaiter(void 0, void 0, void 0, function* () {
583
- return CfgProduct._makeNewRefFrom(yield _CfgProductInternal.make(productLoader, undefined, lang, catId, partNumber, completeSettings(settings), false, new AggregatedLoadingObservable(), undefined, undefined, undefined, undefined, undefined));
584
- });
585
- /// Makes an object wrapping the passed object. This is not a clone method,
586
- /// it is a method to make a new outer reference. Like a shallow copy.
587
- /// We use this to help frameworks that are build around using equals to detect change.
588
- CfgProduct._makeNewRefFrom = (source) => new CfgProduct(source);
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AggregatedLoadingObservable, compareArrays, count, Observable, toLengthUnit, } from "@configura/web-utilities";
11
+ import { CfgMeasureDefinition } from "./CfgMeasure.js";
12
+ import { ProductConfigurationBubbleMode } from "./productConfiguration/CfgOption.js";
13
+ import { CfgProductConfiguration } from "./productConfiguration/CfgProductConfiguration.js";
14
+ import { collectAdditionalProductRefs } from "./productConfiguration/utilitiesProductConfiguration.js";
15
+ import { wrapWithCache } from "./productLoader.js";
16
+ import { comparePricesObjects, correctDefaultsOnCatalogueParams, makeProductKey, } from "./utilitiesCatalogueData.js";
17
+ function completeSettings(uncompleteSettings) {
18
+ var _a, _b;
19
+ return {
20
+ strictSelectOneSelectionCount: (_a = uncompleteSettings === null || uncompleteSettings === void 0 ? void 0 : uncompleteSettings.strictSelectOneSelectionCount) !== null && _a !== void 0 ? _a : false,
21
+ strictSetApiSelectionMatch: (_b = uncompleteSettings === null || uncompleteSettings === void 0 ? void 0 : uncompleteSettings.strictSetApiSelectionMatch) !== null && _b !== void 0 ? _b : false,
22
+ };
23
+ }
24
+ /**
25
+ * This enum is used internally in the SDK and is not expected by be used directly by integrators.
26
+ */
27
+ export var CfgProductBubbleMode;
28
+ (function (CfgProductBubbleMode) {
29
+ /** Stop bubbling. */
30
+ CfgProductBubbleMode["Stop"] = "Stop";
31
+ /**
32
+ * Bubble to the parent CfgProduct up the tree.
33
+ * This makes the CfgProduct we we call from notify that it has changed, and the CfgProduct
34
+ * above switch out the reference to this.
35
+ */
36
+ CfgProductBubbleMode["OneLevel"] = "OneLevel";
37
+ /** Bubble to the root CfgProduct. */
38
+ CfgProductBubbleMode["ToRoot"] = "ToRoot";
39
+ /** Bubble to the root CfgProduct and turn on all optional CfgProducts on the way up. */
40
+ CfgProductBubbleMode["ToRootAndBubbleSelected"] = "ToRootAndBubbleSelected";
41
+ })(CfgProductBubbleMode || (CfgProductBubbleMode = {}));
42
+ function isDescriptionMatch(l, r) {
43
+ const ld = l.description;
44
+ const rd = r.description;
45
+ return ld !== undefined && rd !== undefined && ld.toLowerCase() === rd.toLowerCase();
46
+ }
47
+ /**
48
+ * This class is meant to only be used through CfgProduct. It should never be instantiated on its
49
+ * own. Normally the internal state of this class should never be directly modified. CfgProduct is
50
+ * the class that should be used and interacted with.
51
+ */
52
+ export class _CfgProductInternal {
53
+ constructor(initSuccess, initFail, _productLoaderRaw, lang, catId, partNumber, settings, optional, selected, rootFeatureRefs, allRawFeatures, uuid, _rawUnit, _rawProductData, apiSelection, loadingObservable, refKey, refDescription, parent, root, transform, anchor) {
54
+ this._productLoaderRaw = _productLoaderRaw;
55
+ this.lang = lang;
56
+ this.catId = catId;
57
+ this.partNumber = partNumber;
58
+ this.settings = settings;
59
+ this.uuid = uuid;
60
+ this._rawUnit = _rawUnit;
61
+ this._rawProductData = _rawProductData;
62
+ this.loadingObservable = loadingObservable;
63
+ this.refKey = refKey;
64
+ this.refDescription = refDescription;
65
+ this.parent = parent;
66
+ this.transform = transform;
67
+ this.anchor = anchor;
68
+ this._destroyed = false;
69
+ this.additionalProducts = [];
70
+ this.changeObservable = new Observable();
71
+ this.destroy = () => {
72
+ this._destroyed = true;
73
+ this.changeObservable.stopAllListen();
74
+ this.configuration.stopAllListenForChange();
75
+ for (const additionalProduct of this.additionalProducts || []) {
76
+ additionalProduct.destroy();
77
+ }
78
+ };
79
+ this._notifyAllOfChange = (bubbleMode) => __awaiter(this, void 0, void 0, function* () {
80
+ if (bubbleMode === CfgProductBubbleMode.Stop) {
81
+ return;
82
+ }
83
+ const parent = this.parent;
84
+ const freshRef = CfgProduct._makeNewRefFrom(this);
85
+ this.changeObservable.notifyAll({ freshRef });
86
+ if (parent !== undefined) {
87
+ yield parent._additionalProductHasChanged(freshRef, bubbleMode === CfgProductBubbleMode.OneLevel
88
+ ? CfgProductBubbleMode.Stop
89
+ : bubbleMode);
90
+ }
91
+ });
92
+ /** Called when a child (additional product or the configuration) has changed. */
93
+ this._childHasChanged = (bubbleMode) => __awaiter(this, void 0, void 0, function* () {
94
+ if (bubbleMode === CfgProductBubbleMode.ToRootAndBubbleSelected &&
95
+ this.optional &&
96
+ !this.selected) {
97
+ yield this.setSelected(true, bubbleMode);
98
+ return;
99
+ }
100
+ yield this._notifyAllOfChange(bubbleMode);
101
+ });
102
+ /** Called by child to tell its parent that it has changed. */
103
+ this._additionalProductHasChanged = (freshRef, bubbleMode) => __awaiter(this, void 0, void 0, function* () {
104
+ const i = this.additionalProducts.findIndex((a) => a.isBackedBySame(freshRef));
105
+ if (i !== -1) {
106
+ // Child additional product might not be found. This probably means that propagate
107
+ // has chopped the branch your on. Let's say we have products A -> B -> C.
108
+ // We change an option on C. This is propagated to product A. Product A now
109
+ // changes its additional product so that B is no longer a child of A. Hence
110
+ // C no longer is part of the tree. Odd, but fully permitted.
111
+ this.additionalProducts[i] = freshRef;
112
+ }
113
+ yield this._childHasChanged(bubbleMode);
114
+ });
115
+ /** Called by the configuration to tell its parent that it has changed. */
116
+ this._configurationHasChanged = (freshRef, bubbleMode) => __awaiter(this, void 0, void 0, function* () {
117
+ this._configuration = freshRef;
118
+ switch (bubbleMode) {
119
+ case ProductConfigurationBubbleMode.ValidateAndBubbleSelected:
120
+ // The revalidate call will continue the bubble
121
+ yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, this._productLoaderRaw);
122
+ return;
123
+ case ProductConfigurationBubbleMode.Validate:
124
+ // The revalidate call will continue the bubble
125
+ yield this._revalidate(CfgProductBubbleMode.ToRoot, this._productLoaderRaw);
126
+ return;
127
+ case ProductConfigurationBubbleMode.ToParentProduct:
128
+ // Do not continue bubble as we have reached the parent CfgProduct
129
+ return;
130
+ case ProductConfigurationBubbleMode.OneLevel:
131
+ yield this._childHasChanged(CfgProductBubbleMode.OneLevel);
132
+ return;
133
+ case ProductConfigurationBubbleMode.Stop:
134
+ yield this._childHasChanged(CfgProductBubbleMode.Stop);
135
+ return;
136
+ case ProductConfigurationBubbleMode.ToRoot:
137
+ yield this._childHasChanged(CfgProductBubbleMode.ToRoot);
138
+ return;
139
+ }
140
+ });
141
+ this.getApiSelection = () => ({
142
+ refKey: this.refKey,
143
+ selected: this.selected,
144
+ selOptions: this.configuration.getApiSelection(),
145
+ additionalProducts: this.additionalProducts.map((additionalProduct) => additionalProduct.getApiSelection()),
146
+ });
147
+ this.setApiSelection = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
148
+ // wrap with cache will make getProduct for this function call use the same server call
149
+ // for the same product with the same params
150
+ productLoaderForGroupedLoad =
151
+ productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
152
+ const configurationChange = yield this.configuration._internal.setApiSelection(s.selOptions, false);
153
+ let change = configurationChange;
154
+ if (this.optional) {
155
+ if (yield this.setSelected(s.selected !== false, CfgProductBubbleMode.Stop)) {
156
+ change = true;
157
+ }
158
+ }
159
+ yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
160
+ const apiSelectionAdditionalProducts = s.additionalProducts || [];
161
+ const additionalProducts = this.additionalProducts.slice();
162
+ const additionalProductsCount = additionalProducts.length;
163
+ const apiSelectionAdditionalProductsCount = apiSelectionAdditionalProducts.length;
164
+ if (apiSelectionAdditionalProductsCount !== additionalProductsCount) {
165
+ throw new Error(`Additional products are not same length. This product: "${this.key}". This product additional products count: ${additionalProductsCount}. Passed apiSelection additional products count: ${apiSelectionAdditionalProductsCount}`);
166
+ }
167
+ if ((yield Promise.all(apiSelectionAdditionalProducts.map((apiSelectionChild) => {
168
+ const refKey = apiSelectionChild.refKey;
169
+ if (refKey === undefined) {
170
+ throw new Error("Additional product api configurations must have refKey.");
171
+ }
172
+ const i = additionalProducts.findIndex((a) => refKey === a.refKey);
173
+ if (i === -1) {
174
+ throw new Error(`Additional product not found. This product: "${this.key}". refKey of not found additional product: "${refKey}"`);
175
+ }
176
+ const additionalProduct = additionalProducts.splice(i, 1)[0]; // Splicing like this is okay because this is done synchronous. The setCon. is what is async.
177
+ return additionalProduct._internal.setApiSelection(apiSelectionChild, doValidate, productLoaderForGroupedLoad);
178
+ }))).some((b) => b)) {
179
+ change = true;
180
+ }
181
+ if (doValidate && configurationChange) {
182
+ yield this._revalidate(CfgProductBubbleMode.ToRoot, productLoaderForGroupedLoad);
183
+ }
184
+ else if (change) {
185
+ // As setApiSelection is done recursively each level takes care of its own notifications
186
+ // so we only need to bubble one level to notify this and swap out the reference in the
187
+ // parent.
188
+ yield this._notifyAllOfChange(CfgProductBubbleMode.OneLevel);
189
+ }
190
+ return change;
191
+ });
192
+ this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => {
193
+ if (!this.configuration.structureCompare(other.configuration, strictOrder, descriptionMatch)) {
194
+ return false;
195
+ }
196
+ return compareArrays(this.additionalProducts, other.additionalProducts, (l, r) => (!descriptionMatch || (descriptionMatch && isDescriptionMatch(l, r))) &&
197
+ l.structureCompare(r, strictOrder, descriptionMatch), !descriptionMatch);
198
+ };
199
+ this.tryMatchSelection = (other, descriptionMatch = false, // Match on case insensitive description, not code
200
+ productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
201
+ // wrap with cache will make getProduct for this function call use the same server call
202
+ // for the same product with the same params
203
+ productLoaderForGroupedLoad =
204
+ productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
205
+ let change = false;
206
+ if (this.optional && other.optional) {
207
+ if (yield this.setSelected(other.selected, CfgProductBubbleMode.Stop)) {
208
+ change = true;
209
+ }
210
+ }
211
+ const configurationChange = yield this.configuration._internal.tryMatchSelection(other.configuration._internal, descriptionMatch, false);
212
+ if (configurationChange) {
213
+ change = true;
214
+ yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, productLoaderForGroupedLoad);
215
+ }
216
+ else if (change) {
217
+ yield this._notifyAllOfChange(CfgProductBubbleMode.ToRootAndBubbleSelected);
218
+ }
219
+ const thisAdditionalProducts = this.additionalProducts;
220
+ const otherAdditionalProducts = other.additionalProducts;
221
+ const promises = [];
222
+ if (descriptionMatch) {
223
+ for (const otherAdditionalProduct of otherAdditionalProducts) {
224
+ if (1 <
225
+ count(otherAdditionalProducts, (product) => isDescriptionMatch(product, otherAdditionalProduct))) {
226
+ console.warn("tryMatchSelection will ignore products that have the same description");
227
+ continue;
228
+ }
229
+ const toTryMatchProducts = thisAdditionalProducts.filter((product) => isDescriptionMatch(product, otherAdditionalProduct));
230
+ if (1 < toTryMatchProducts.length) {
231
+ console.warn("tryMatchSelection will ignore products that have the same description");
232
+ continue;
233
+ }
234
+ if (toTryMatchProducts.length === 0) {
235
+ continue;
236
+ }
237
+ promises.push(toTryMatchProducts[0]._internal.tryMatchSelection(otherAdditionalProduct._internal, descriptionMatch, productLoaderForGroupedLoad));
238
+ }
239
+ }
240
+ else {
241
+ if (thisAdditionalProducts.length !== otherAdditionalProducts.length) {
242
+ console.warn("tryMatchSelection not same count, will not try to match further.");
243
+ return change;
244
+ }
245
+ for (let i = 0; i < thisAdditionalProducts.length; i++) {
246
+ promises.push(thisAdditionalProducts[i]._internal.tryMatchSelection(otherAdditionalProducts[i]._internal, descriptionMatch, productLoaderForGroupedLoad));
247
+ }
248
+ }
249
+ if ((yield Promise.all(promises)).some((b) => b)) {
250
+ change = true;
251
+ }
252
+ return change;
253
+ });
254
+ /** Only features in selected options and selected additional products. */
255
+ this._getDescendantFeaturesWithCode = (code) => this.additionalProducts.reduce((agg, additionalProduct) => {
256
+ if (additionalProduct.selected) {
257
+ agg.push(...additionalProduct._internal._getDescendantFeaturesWithCode(code));
258
+ }
259
+ return agg;
260
+ }, this._configuration._internal._getFeaturesWithCode(code));
261
+ /**
262
+ * Do a validate call for this product. It does not validate additional products, only this
263
+ * product in isolation. The validation result is applied on the configuration. Then additional
264
+ * products are synced (unloaded, loaded etc.) Finally the changes bubble up the tree.
265
+ */
266
+ this._revalidate = (bubbleMode, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
267
+ const { _configuration: configuration } = this;
268
+ const token = this.loadingObservable.startChildLoading();
269
+ this._revalidateInProgressToken = token;
270
+ try {
271
+ const response = yield productLoaderForGroupedLoad.postValidate(Object.assign(Object.assign({ lang: this.lang }, correctDefaultsOnCatalogueParams(this.catId)), { partNumber: this.partNumber }), { selOptions: configuration.getApiSelection() });
272
+ // The revalidateInProgressToken is used to know if some other revalidate
273
+ // call has happened after this call, thereby making this call obsolete.
274
+ // This is a bit crude in that it does not actually cancel previous validate
275
+ // calls, but this is fine because 1. it is hard to cancel a call, especially
276
+ // if you wanna have clear code 2. the actual calls are small anyhow 3. most
277
+ // of all, the heavy work happens on the server, and that work will not be
278
+ // cancelled even if we would cancel the call.
279
+ if (this._revalidateInProgressToken !== token) {
280
+ return false;
281
+ }
282
+ // After a successful validate-call we will always assume there
283
+ // is a change. It would be possible to compare relevant parts
284
+ // of productData, consider the result of setApiSelection and
285
+ // syndAndLoad, however the code comparing productData would be fragile
286
+ // and likely to break if new data-fields were added.
287
+ if (this._destroyed) {
288
+ return false;
289
+ }
290
+ const { productData, rootFeatureRefs } = response;
291
+ const pricesUpdated = !comparePricesObjects(this.prices, productData.partsData.prices);
292
+ this._rawProductData = productData;
293
+ if (rootFeatureRefs !== undefined) {
294
+ configuration._internal.populateFeatures(rootFeatureRefs);
295
+ }
296
+ if (pricesUpdated) {
297
+ this._configuration._internal._freshRefDescendants();
298
+ this._configuration = CfgProductConfiguration._makeNewRefFrom(this._configuration._internal);
299
+ }
300
+ yield configuration._internal.setApiSelection(productData.partsData.selOptions || [], false);
301
+ yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
302
+ if (this._destroyed) {
303
+ return false;
304
+ }
305
+ yield this._notifyAllOfChange(bubbleMode);
306
+ return true;
307
+ }
308
+ catch (e) {
309
+ throw e;
310
+ }
311
+ finally {
312
+ this.loadingObservable.stopChildLoading(token);
313
+ }
314
+ });
315
+ /**
316
+ * Based on this configuration find what additional products should be shown and not, unload
317
+ * (i.e. destroy) those that should no longer be shown, load the new ones.
318
+ */
319
+ this._syncAndLoadAdditionalProducts = (productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
320
+ const { lang, _productLoaderRaw: productLoaderRaw, rawProductData: productData, configuration, additionalProducts: currentAdditionalProducts, } = this;
321
+ const additionalProductRefs = [
322
+ ...(productData.additionalProductRefs || []),
323
+ ...collectAdditionalProductRefs(configuration),
324
+ ].map((prodRef, originalIndex) => ({
325
+ prodRef,
326
+ originalIndex,
327
+ }));
328
+ let change = false;
329
+ let i = currentAdditionalProducts.length;
330
+ while (i--) {
331
+ const currentAdditionalProduct = currentAdditionalProducts[i];
332
+ const refKey = currentAdditionalProduct.refKey;
333
+ const j = additionalProductRefs.findIndex((p) => p.prodRef.refKey === refKey);
334
+ if (j === -1) {
335
+ currentAdditionalProduct.destroy();
336
+ currentAdditionalProducts.splice(i, 1);
337
+ change = true;
338
+ }
339
+ else {
340
+ additionalProductRefs.splice(j, 1);
341
+ }
342
+ }
343
+ const token = this.loadingObservable.startChildLoading();
344
+ try {
345
+ if (additionalProductRefs.length !== 0) {
346
+ change = true;
347
+ }
348
+ const newAdditionalProducts = yield Promise.all(additionalProductRefs.map((p) => (() => __awaiter(this, void 0, void 0, function* () {
349
+ const additionalProductRef = p.prodRef;
350
+ return {
351
+ originalIndex: p.originalIndex,
352
+ product: CfgProduct._makeNewRefFrom(yield _CfgProductInternal.make(productLoaderRaw, productLoaderForGroupedLoad, lang, additionalProductRef.catId, additionalProductRef.partNumber, this.settings, additionalProductRef.optional === true, this.loadingObservable, additionalProductRef.refKey, additionalProductRef.refDescription, this, this.root, additionalProductRef.transform, additionalProductRef.anchor)),
353
+ };
354
+ }))()));
355
+ if (this._destroyed) {
356
+ return change;
357
+ }
358
+ for (const newAdditionalProduct of newAdditionalProducts) {
359
+ currentAdditionalProducts.splice(newAdditionalProduct.originalIndex, 0, newAdditionalProduct.product);
360
+ }
361
+ return change;
362
+ }
363
+ catch (e) {
364
+ throw e;
365
+ }
366
+ finally {
367
+ this.loadingObservable.stopChildLoading(token);
368
+ }
369
+ });
370
+ this.root = root || this;
371
+ this.key = makeProductKey(catId, refKey || partNumber);
372
+ this._selected = optional ? selected : undefined;
373
+ this.isAdditionalProduct = parent !== undefined;
374
+ this._configuration = CfgProductConfiguration.make(initSuccess, initFail, rootFeatureRefs, allRawFeatures, apiSelection, this, this.root);
375
+ }
376
+ get selected() {
377
+ return this._selected !== false;
378
+ }
379
+ clone(parent, root) {
380
+ return __awaiter(this, void 0, void 0, function* () {
381
+ const product = yield new Promise((initSuccess, initFail) => {
382
+ const p = new _CfgProductInternal(() => {
383
+ initSuccess(p);
384
+ }, initFail, this._productLoaderRaw, this.lang, this.catId, this.partNumber, this.settings, this.optional, this.selected, this._configuration.rootFeatureRefs, this._configuration.allRawFeatures, this.uuid, this._rawUnit, this._rawProductData, this.configuration.getApiSelection(), new AggregatedLoadingObservable(), this.refKey, this.refDescription, parent, root, this.transform, this.anchor);
385
+ });
386
+ for (const additionalProduct of this.additionalProducts) {
387
+ product.additionalProducts.push(CfgProduct._makeNewRefFrom(yield additionalProduct._internal.clone(product, root || product)));
388
+ }
389
+ return product;
390
+ });
391
+ }
392
+ get description() {
393
+ return this.refDescription || this._rawProductData.description;
394
+ }
395
+ get rootNodeSources() {
396
+ return this._rawProductData.models;
397
+ }
398
+ get mtrlApplications() {
399
+ return this._rawProductData.mtrlApplications;
400
+ }
401
+ get currency() {
402
+ return this._rawProductData.partsData.currency;
403
+ }
404
+ get fractionDigits() {
405
+ return this._rawProductData.partsData.rounding || 0;
406
+ }
407
+ get prices() {
408
+ return this._rawProductData.partsData.prices;
409
+ }
410
+ get measureDefinitions() {
411
+ var _a;
412
+ if (this._measureDefinitions === undefined) {
413
+ this._measureDefinitions = ((_a = this._rawProductData.measurements) !== null && _a !== void 0 ? _a : [])
414
+ .map((m) => CfgMeasureDefinition.make(m))
415
+ .filter((m) => m !== undefined);
416
+ }
417
+ return this._measureDefinitions;
418
+ }
419
+ /** @throws an error if the actual unit sent by the server was not a LengthUnit */
420
+ get unit() {
421
+ if (this._unit === undefined) {
422
+ this._unit = toLengthUnit(this._rawUnit);
423
+ }
424
+ return this._unit;
425
+ }
426
+ get aggregatedPrice() {
427
+ const { currency, fractionDigits, rawProductData } = this;
428
+ const { partsData } = rawProductData;
429
+ let { listPrice, basePrice } = partsData;
430
+ if (this._selected === false) {
431
+ return { basePrice: 0, listPrice: 0, currency, fractionDigits };
432
+ }
433
+ for (const additionalProduct of this.additionalProducts || []) {
434
+ const { basePrice: additionalBasePrice, listPrice: additionalListPrice, currency: additionalCurrency, fractionDigits: additionalFractionDigits, } = additionalProduct.aggregatedPrice;
435
+ basePrice += additionalBasePrice;
436
+ listPrice += additionalListPrice;
437
+ if (currency !== additionalCurrency) {
438
+ // This should not be possible
439
+ // The server shouldn't return additional products with different currency from their parent
440
+ throw new Error(`Currency mismatch between parent product and additional product. Parent product: "${this.key}" Additional product: "${additionalProduct.key}". Currency on parent product: ${currency}. Currency on additional product: ${additionalCurrency}`);
441
+ }
442
+ if (fractionDigits !== additionalFractionDigits) {
443
+ // This should not be possible
444
+ // The server shouldn't return additional products with different fraction digits from their parent
445
+ throw new Error(`Fraction digits mismatch between parent product and additional product. Parent product: "${this.key}" Additional product: "${additionalProduct.key}". Fraction digits on parent product: ${fractionDigits}. Fraction digits on additional product: ${additionalFractionDigits}`);
446
+ }
447
+ }
448
+ return { basePrice, listPrice, currency, fractionDigits };
449
+ }
450
+ get optional() {
451
+ return this._selected !== undefined;
452
+ }
453
+ setSelected(v, bubbleMode) {
454
+ return __awaiter(this, void 0, void 0, function* () {
455
+ if (!this.optional) {
456
+ console.warn("This product is not optional. Nothing will happen");
457
+ return false;
458
+ }
459
+ if (this._selected === v) {
460
+ return false;
461
+ }
462
+ this._selected = v;
463
+ yield this._notifyAllOfChange(bubbleMode);
464
+ return true;
465
+ });
466
+ }
467
+ get configuration() {
468
+ return this._configuration;
469
+ }
470
+ get rawProductData() {
471
+ return this._rawProductData;
472
+ }
473
+ }
474
+ _CfgProductInternal.make = (productLoaderRaw, productLoaderForGroupedLoad, // Used when instantiating the current product
475
+ lang, catId, partNumber, settings, optional, loadingObservable, refKey, refDescription, parent, root, transform, anchor) => __awaiter(void 0, void 0, void 0, function* () {
476
+ // wrap with cache will make getProduct for this function call use the same server call
477
+ // for the same product with the same params
478
+ productLoaderForGroupedLoad =
479
+ productLoaderForGroupedLoad || wrapWithCache(productLoaderRaw);
480
+ const productResponse = yield productLoaderForGroupedLoad.getProduct(Object.assign(Object.assign({ lang }, correctDefaultsOnCatalogueParams(catId)), { partNumber }));
481
+ const { productData, rootFeatureRefs, features: allRawFeatures, uuid, unit, } = productResponse;
482
+ const product = yield new Promise((initSuccess, initFail) => {
483
+ const p = new _CfgProductInternal(() => {
484
+ // We absolutely do not want anyone to assign to this._configuration. So we want that field private.
485
+ // But we can not set the api selection synchronously. And the product configuration needs "this". So we use this callback.
486
+ // Feel free to find a nicer more readable solution :)
487
+ initSuccess(p);
488
+ }, initFail, productLoaderRaw, lang, catId, partNumber, settings, optional, !optional, rootFeatureRefs, allRawFeatures, uuid, unit, productData, productData.partsData.selOptions || [], loadingObservable, refKey, refDescription, parent, root, transform, anchor);
489
+ });
490
+ yield product._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad);
491
+ return product;
492
+ });
493
+ export class CfgProduct {
494
+ constructor(_internal) {
495
+ this._internal = _internal;
496
+ this.isBackedBySame = (other) => this._internal === other._internal;
497
+ /**
498
+ * Recursively marks this and descendants as destroyed so that late events are ignored
499
+ * correctly. If you destroy one shallow copy of this you destroy all.
500
+ */
501
+ this.destroy = () => this._internal.destroy();
502
+ /** Makes a clone of this. It is disconnected from the original. */
503
+ this.clone = () => __awaiter(this, void 0, void 0, function* () { return CfgProduct._makeNewRefFrom(yield this._internal.clone()); });
504
+ /**
505
+ * Only applicable when this product is optional.
506
+ * Setting this does not cause a validation call as toggling an optional additional product is
507
+ * assumed to always be legal.
508
+ */
509
+ this.setSelected = (v) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setSelected(v, CfgProductBubbleMode.ToRootAndBubbleSelected); });
510
+ /**
511
+ * Experimental. Additional products lacks descriptions or keys that are suitably for structure
512
+ * compare, so we use strict-order when trying to match the additional products. This makes
513
+ * this method work nicely for different products having pretty much the same child products.
514
+ */
515
+ this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => this._internal.structureCompare(other._internal, strictOrder, descriptionMatch);
516
+ /**
517
+ * Experimental. Additional products lacks descriptions or keys that are suitably for try
518
+ * match, so we use strict-order when trying to match the additional products. This makes
519
+ * this method work nicely for different products having pretty much the same child products.
520
+ * This method does not propagate its selections.
521
+ * This method will cause validation calls if something change.
522
+ */
523
+ this.tryMatchSelection = (other, descriptionMatch = false // Match on case insensitive description, not code
524
+ ) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.tryMatchSelection(other._internal, descriptionMatch); });
525
+ /**
526
+ * Gets what selections has been made on the product, recursively including product
527
+ * configuration, optional products and additional products. Used when a full view of all
528
+ * selections on a product is needed, such as when doing Render or Export.
529
+ */
530
+ this.getApiSelection = () => this._internal.getApiSelection();
531
+ this.setApiSelection = (s, doValidate = false) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setApiSelection(s, doValidate); });
532
+ this.listenForChange = (l) => this._internal.changeObservable.listen(l);
533
+ this.stopListenForChange = (l) => this._internal.changeObservable.stopListen(l);
534
+ this.stopAllListenForChange = () => this._internal.changeObservable.stopAllListen();
535
+ this.listenForLoading = (l) => this._internal.loadingObservable.listen(l);
536
+ this.stopListenForLoading = (l) => this._internal.loadingObservable.stopListen(l);
537
+ this.stopAllListenForLoading = () => this._internal.loadingObservable.stopAllListen();
538
+ }
539
+ static make(productLoader, lang, catId, partNumber, settings) {
540
+ return __awaiter(this, void 0, void 0, function* () {
541
+ return this._makeNewRefFrom(yield _CfgProductInternal.make(productLoader, undefined, lang, catId, partNumber, completeSettings(settings), false, new AggregatedLoadingObservable(), undefined, undefined, undefined, undefined, undefined, undefined));
542
+ });
543
+ }
544
+ /**
545
+ * Makes an object wrapping the passed object. This is not a clone method, it is a method to
546
+ * make a new outer reference. Like a shallow copy./ We use this to help frameworks that are
547
+ * build around using equals to detect change.
548
+ */
549
+ static _makeNewRefFrom(source) {
550
+ return new this(source);
551
+ }
552
+ /**
553
+ * A client side only key that should uniquely identify this product amongst other additional
554
+ * products.
555
+ */
556
+ get key() {
557
+ return this._internal.key;
558
+ }
559
+ /**
560
+ * Only used when this product is in additional product.
561
+ * As a product can have multiple instances of the same additional product this key exists.
562
+ * It will be unique amongst child products, but not globally unique.
563
+ */
564
+ get refKey() {
565
+ return this._internal.refKey;
566
+ }
567
+ get lang() {
568
+ return this._internal.lang;
569
+ }
570
+ get catId() {
571
+ return this._internal.catId;
572
+ }
573
+ get partNumber() {
574
+ return this._internal.partNumber;
575
+ }
576
+ get isAdditionalProduct() {
577
+ return this._internal.isAdditionalProduct;
578
+ }
579
+ /** Only used when this product is an additional product. Root products are never optional. */
580
+ get optional() {
581
+ return this._internal.optional;
582
+ }
583
+ /**
584
+ * Only applicable when this product is optional. If this product is not optional this is
585
+ * always true.
586
+ */
587
+ get selected() {
588
+ return this._internal.selected;
589
+ }
590
+ get rawProductData() {
591
+ return this._internal.rawProductData;
592
+ }
593
+ get uuid() {
594
+ return this._internal.uuid;
595
+ }
596
+ get unit() {
597
+ return this._internal.unit;
598
+ }
599
+ get sku() {
600
+ return this._internal.rawProductData.sku;
601
+ }
602
+ get styleNr() {
603
+ return this._internal.rawProductData.partsData.styleNr;
604
+ }
605
+ /** An URL. */
606
+ get preview() {
607
+ return this._internal.rawProductData.navImage;
608
+ }
609
+ get description() {
610
+ return this._internal.description;
611
+ }
612
+ get additionalProducts() {
613
+ return this._internal.additionalProducts;
614
+ }
615
+ get configuration() {
616
+ return this._internal.configuration;
617
+ }
618
+ get transform() {
619
+ return this._internal.transform;
620
+ }
621
+ get currency() {
622
+ return this._internal.currency;
623
+ }
624
+ /**
625
+ * If positive the number of fraction digits.
626
+ * If negative rounding (essentially the number of zeros to the right)
627
+ */
628
+ get fractionDigits() {
629
+ return this._internal.fractionDigits;
630
+ }
631
+ get aggregatedPrice() {
632
+ return this._internal.aggregatedPrice;
633
+ }
634
+ }