@configura/web-api 2.0.0-alpha.0 → 2.0.0-alpha.3

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