@configura/web-api 2.0.0-alpha.21 → 2.0.0-alpha.22

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 (100) hide show
  1. package/.eslintrc.json +5 -5
  2. package/LICENSE +201 -201
  3. package/README.md +1 -1
  4. package/dist/CatalogueAPI.d.ts +622 -597
  5. package/dist/CatalogueAPI.js +329 -328
  6. package/dist/CfgMeasure.d.ts +32 -32
  7. package/dist/CfgMeasure.js +30 -30
  8. package/dist/CfgProduct.d.ts +344 -328
  9. package/dist/CfgProduct.js +996 -934
  10. package/dist/CfgReferencePathHelper.d.ts +26 -26
  11. package/dist/CfgReferencePathHelper.js +26 -26
  12. package/dist/ConfigurationConverter.d.ts +17 -17
  13. package/dist/ConfigurationConverter.js +175 -175
  14. package/dist/index.d.ts +23 -23
  15. package/dist/index.js +23 -23
  16. package/dist/io/CfgHistoryManager.d.ts +83 -83
  17. package/dist/io/CfgHistoryManager.js +144 -144
  18. package/dist/io/CfgHistoryToProdConfConnector.d.ts +21 -21
  19. package/dist/io/CfgHistoryToProdConfConnector.js +50 -50
  20. package/dist/io/CfgIOManager.d.ts +53 -53
  21. package/dist/io/CfgIOManager.js +134 -134
  22. package/dist/io/CfgIOProdConfConnector.d.ts +64 -64
  23. package/dist/io/CfgIOProdConfConnector.js +149 -149
  24. package/dist/io/CfgIOWarningSupplier.d.ts +3 -3
  25. package/dist/io/CfgIOWarningSupplier.js +1 -1
  26. package/dist/io/CfgObservableStateManager.d.ts +25 -25
  27. package/dist/io/CfgObservableStateManager.js +69 -69
  28. package/dist/io/CfgObservableStateToProdConfConnector.d.ts +14 -14
  29. package/dist/io/CfgObservableStateToProdConfConnector.js +16 -16
  30. package/dist/io/CfgWindowEventManager.d.ts +21 -21
  31. package/dist/io/CfgWindowEventManager.js +38 -38
  32. package/dist/io/CfgWindowMessageManager.d.ts +40 -40
  33. package/dist/io/CfgWindowMessageManager.js +91 -91
  34. package/dist/io/CfgWindowMessageToProdConfConnector.d.ts +16 -16
  35. package/dist/io/CfgWindowMessageToProdConfConnector.js +18 -18
  36. package/dist/io/index.d.ts +8 -8
  37. package/dist/io/index.js +8 -8
  38. package/dist/material/CfgMaterialMapping.d.ts +7 -7
  39. package/dist/material/CfgMaterialMapping.js +181 -181
  40. package/dist/material/CfgMtrlApplication.d.ts +18 -18
  41. package/dist/material/CfgMtrlApplication.js +43 -43
  42. package/dist/material/CfgMtrlApplicationSource.d.ts +7 -7
  43. package/dist/material/CfgMtrlApplicationSource.js +8 -8
  44. package/dist/material/CfgMtrlSource.d.ts +19 -19
  45. package/dist/material/CfgMtrlSource.js +40 -40
  46. package/dist/material/CfgMtrlSourceWithMetaData.d.ts +7 -7
  47. package/dist/material/CfgMtrlSourceWithMetaData.js +1 -1
  48. package/dist/productConfiguration/CfgFeature.d.ts +193 -189
  49. package/dist/productConfiguration/CfgFeature.js +671 -658
  50. package/dist/productConfiguration/CfgOption.d.ts +156 -151
  51. package/dist/productConfiguration/CfgOption.js +439 -422
  52. package/dist/productConfiguration/CfgProductConfiguration.d.ts +129 -129
  53. package/dist/productConfiguration/CfgProductConfiguration.js +340 -340
  54. package/dist/productConfiguration/filters.d.ts +15 -15
  55. package/dist/productConfiguration/filters.js +70 -70
  56. package/dist/productConfiguration/productParamsGenerator.d.ts +15 -15
  57. package/dist/productConfiguration/productParamsGenerator.js +51 -51
  58. package/dist/productConfiguration/utilitiesProductConfiguration.d.ts +17 -17
  59. package/dist/productConfiguration/utilitiesProductConfiguration.js +87 -87
  60. package/dist/productLoader.d.ts +33 -33
  61. package/dist/productLoader.js +49 -49
  62. package/dist/syncGroups/SyncGroupsApplyMode.d.ts +20 -20
  63. package/dist/syncGroups/SyncGroupsApplyMode.js +21 -21
  64. package/dist/syncGroups/SyncGroupsHandler.d.ts +47 -47
  65. package/dist/syncGroups/SyncGroupsHandler.js +370 -370
  66. package/dist/syncGroups/SyncGroupsPathHelper.d.ts +26 -26
  67. package/dist/syncGroups/SyncGroupsPathHelper.js +90 -90
  68. package/dist/syncGroups/SyncGroupsState.d.ts +39 -39
  69. package/dist/syncGroups/SyncGroupsState.js +167 -167
  70. package/dist/syncGroups/SyncGroupsTransaction.d.ts +154 -154
  71. package/dist/syncGroups/SyncGroupsTransaction.js +589 -589
  72. package/dist/tasks/TaskHandler.d.ts +77 -77
  73. package/dist/tasks/TaskHandler.js +276 -276
  74. package/dist/tasks/formats.d.ts +4 -4
  75. package/dist/tasks/formats.js +7 -7
  76. package/dist/tests/testData/collectorForTest.d.ts +73 -73
  77. package/dist/tests/testData/collectorForTest.js +194 -194
  78. package/dist/tests/testData/dummyProductForTest.d.ts +4 -4
  79. package/dist/tests/testData/dummyProductForTest.js +32 -32
  80. package/dist/tests/testData/testDataAdditionalProductInAdditionalProductInProductForTest.d.ts +11 -11
  81. package/dist/tests/testData/testDataAdditionalProductInAdditionalProductInProductForTest.js +282 -282
  82. package/dist/tests/testData/testDataCachedGetProduct.d.ts +5 -5
  83. package/dist/tests/testData/testDataCachedGetProduct.js +187 -187
  84. package/dist/tests/testData/testDataCachedPostValidate.d.ts +7 -7
  85. package/dist/tests/testData/testDataCachedPostValidate.js +185 -185
  86. package/dist/tests/testData/testDataNoAdditionalProductNoPropagateForTest.d.ts +3 -3
  87. package/dist/tests/testData/testDataNoAdditionalProductNoPropagateForTest.js +1099 -1099
  88. package/dist/tests/testData/testDataOptions.d.ts +12 -12
  89. package/dist/tests/testData/testDataOptions.js +60 -60
  90. package/dist/tests/testData/testDataProductAggregatedPrice.d.ts +6 -6
  91. package/dist/tests/testData/testDataProductAggregatedPrice.js +189 -189
  92. package/dist/tests/testData/testDataUpcharge.d.ts +8 -8
  93. package/dist/tests/testData/testDataUpcharge.js +121 -121
  94. package/dist/utilitiesCatalogueData.d.ts +47 -47
  95. package/dist/utilitiesCatalogueData.js +180 -180
  96. package/dist/utilitiesCataloguePermission.d.ts +38 -38
  97. package/dist/utilitiesCataloguePermission.js +79 -79
  98. package/dist/utilitiesNumericValues.d.ts +24 -24
  99. package/dist/utilitiesNumericValues.js +114 -114
  100. package/package.json +3 -3
@@ -1,934 +1,996 @@
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 { convertDtoProductConfToV1, isAdditionalProductConfiguration, isProductConf, } from "./ConfigurationConverter.js";
13
- import { CfgProdConfParts } from "./index.js";
14
- import { ProductConfigurationBubbleMode } from "./productConfiguration/CfgOption.js";
15
- import { CfgProductConfiguration } from "./productConfiguration/CfgProductConfiguration.js";
16
- import { collectAdditionalProductRefs } from "./productConfiguration/utilitiesProductConfiguration.js";
17
- import { wrapWithCache } from "./productLoader.js";
18
- import { SyncGroupsHandler } from "./syncGroups/SyncGroupsHandler.js";
19
- import { compareCfgProductData, comparePricesObjects, correctDefaultsOnCatalogueParams, isSameCatalogueParams, isSameProductRef, makeProductKey, } from "./utilitiesCatalogueData.js";
20
- function completeSettings(incompleteSettings) {
21
- var _a;
22
- return {
23
- strictSelectOneSelectionCount: (_a = incompleteSettings === null || incompleteSettings === void 0 ? void 0 : incompleteSettings.strictSelectOneSelectionCount) !== null && _a !== void 0 ? _a : false,
24
- syncGroupsApplyMode: incompleteSettings === null || incompleteSettings === void 0 ? void 0 : incompleteSettings.syncGroupsApplyMode,
25
- };
26
- }
27
- /**
28
- * This enum is used internally in the SDK and is not expected by be used directly by integrators.
29
- */
30
- export var CfgProductBubbleMode;
31
- (function (CfgProductBubbleMode) {
32
- /** Stop bubbling. */
33
- CfgProductBubbleMode["Stop"] = "Stop";
34
- /**
35
- * Bubble to the parent CfgProduct up the tree.
36
- * This makes the CfgProduct we we call from notify that it has changed, and the CfgProduct
37
- * above switch out the reference to this.
38
- */
39
- CfgProductBubbleMode["OneLevel"] = "OneLevel";
40
- /** Bubble to the root CfgProduct. */
41
- CfgProductBubbleMode["ToRoot"] = "ToRoot";
42
- /** Bubble to the root CfgProduct and turn on all optional CfgProducts on the way up. */
43
- CfgProductBubbleMode["ToRootAndBubbleSelected"] = "ToRootAndBubbleSelected";
44
- })(CfgProductBubbleMode || (CfgProductBubbleMode = {}));
45
- function isDescriptionMatch(l, r) {
46
- const ld = l.description;
47
- const rd = r.description;
48
- return ld !== undefined && rd !== undefined && ld.toLowerCase() === rd.toLowerCase();
49
- }
50
- /**
51
- * This class is meant to only be used through CfgProduct. It should never be instantiated on its
52
- * own. Normally the internal state of this class should never be directly modified. CfgProduct is
53
- * the class that should be used and interacted with.
54
- */
55
- export class _CfgProductInternal {
56
- constructor(initSuccess, initFail, _productLoaderRaw, prodParams, settings, optional, selected, rootFeatureRefs, rawFeatures, uuid, _rawUnit, _rawProductData, apiSelection, loadingObservable, parent, root, _additionalProductRef, _syncGroupHandler) {
57
- var _a;
58
- this._productLoaderRaw = _productLoaderRaw;
59
- this.prodParams = prodParams;
60
- this.settings = settings;
61
- this.uuid = uuid;
62
- this._rawUnit = _rawUnit;
63
- this._rawProductData = _rawProductData;
64
- this.loadingObservable = loadingObservable;
65
- this.parent = parent;
66
- this._additionalProductRef = _additionalProductRef;
67
- this._syncGroupHandler = _syncGroupHandler;
68
- this._destroyed = false;
69
- this.additionalProducts = [];
70
- this.changeObservable = new Observable();
71
- /** Mark this and its descendants as destroyed and remove all listeners */
72
- this.destroy = () => {
73
- var _a;
74
- this._destroyed = true;
75
- this.changeObservable.stopAllListen();
76
- this.configuration.stopAllListenForChange();
77
- for (const additionalProduct of (_a = this.additionalProducts) !== null && _a !== void 0 ? _a : []) {
78
- additionalProduct.destroy();
79
- }
80
- };
81
- /**
82
- * Reset will reset the product to its initial state
83
- */
84
- this.reset = () => __awaiter(this, void 0, void 0, function* () {
85
- if (this._initialClone !== undefined) {
86
- yield this.copyFrom(this._initialClone, true);
87
- }
88
- });
89
- this._notifyAllOfChange = (bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
90
- if (bubbleMode === CfgProductBubbleMode.Stop) {
91
- return;
92
- }
93
- const parent = this.parent;
94
- const freshRef = CfgProduct._makeNewRefFrom(this);
95
- this.changeObservable.notifyAll({ freshRef, committed });
96
- if (parent !== undefined) {
97
- yield parent._additionalProductHasChanged(freshRef, bubbleMode === CfgProductBubbleMode.OneLevel
98
- ? CfgProductBubbleMode.Stop
99
- : bubbleMode, committed);
100
- }
101
- });
102
- /** Called when a child (additional product or the configuration) has changed. */
103
- this._childHasChanged = (bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
104
- if (bubbleMode === CfgProductBubbleMode.ToRootAndBubbleSelected &&
105
- this.optional &&
106
- !this.selected) {
107
- yield this.setSelected(true, bubbleMode, false);
108
- return;
109
- }
110
- yield this._notifyAllOfChange(bubbleMode, committed);
111
- });
112
- /** Called by child to tell its parent that it has changed. */
113
- this._additionalProductHasChanged = (freshRef, bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
114
- const i = this.additionalProducts.findIndex((a) => a.isBackedBySame(freshRef));
115
- if (i !== -1) {
116
- // Child additional product might not be found. This probably means that propagate
117
- // has chopped the branch your on. Let's say we have products A -> B -> C.
118
- // We change an option on C. This is propagated to product A. Product A now
119
- // changes its additional product so that B is no longer a child of A. Hence
120
- // C no longer is part of the tree. Odd, but fully permitted.
121
- this.additionalProducts[i] = freshRef;
122
- }
123
- yield this._childHasChanged(bubbleMode, committed);
124
- });
125
- /** Called by the configuration to tell its parent that it has changed. */
126
- this._configurationHasChanged = (freshRef, bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
127
- this._configuration = freshRef;
128
- switch (bubbleMode) {
129
- case ProductConfigurationBubbleMode.ValidateAndBubbleSelected:
130
- // The revalidate call will continue the bubble
131
- yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, this._productLoaderRaw, committed);
132
- return;
133
- case ProductConfigurationBubbleMode.BubbleSelected:
134
- yield this._childHasChanged(CfgProductBubbleMode.ToRootAndBubbleSelected, committed);
135
- return;
136
- case ProductConfigurationBubbleMode.Validate:
137
- // The revalidate call will continue the bubble
138
- yield this._revalidate(CfgProductBubbleMode.ToRoot, this._productLoaderRaw, committed);
139
- return;
140
- case ProductConfigurationBubbleMode.ToParentProduct:
141
- // Do not continue bubble as we have reached the parent CfgProduct
142
- return;
143
- case ProductConfigurationBubbleMode.OneLevel:
144
- yield this._childHasChanged(CfgProductBubbleMode.OneLevel, committed);
145
- return;
146
- case ProductConfigurationBubbleMode.Stop:
147
- yield this._childHasChanged(CfgProductBubbleMode.Stop, committed);
148
- return;
149
- case ProductConfigurationBubbleMode.ToRoot:
150
- yield this._childHasChanged(CfgProductBubbleMode.ToRoot, committed);
151
- return;
152
- }
153
- });
154
- this.getDtoConf = (include) => {
155
- var _a;
156
- const conf = {};
157
- const features = this.configuration._internal.getDtoConf((include & CfgProdConfParts.ExtendedData) === CfgProdConfParts.ExtendedData);
158
- if (0 < features.length) {
159
- conf.features = features;
160
- }
161
- if ((include & CfgProdConfParts.ProdParams) === CfgProdConfParts.ProdParams) {
162
- conf.prodParams = this.prodParams;
163
- }
164
- // Only store the syncGroupState for the root product. The same state
165
- // is used for the entire product, including the additional product,
166
- // so no need to store it for additional products.
167
- if ((include & CfgProdConfParts.SyncGroupState) === CfgProdConfParts.SyncGroupState &&
168
- this.parent === undefined) {
169
- conf.syncGroupState = (_a = this.syncGroupHandler) === null || _a === void 0 ? void 0 : _a.getCompactSyncGroupState();
170
- }
171
- const additionalProducts = this.additionalProducts;
172
- if (0 < additionalProducts.length) {
173
- conf.additionalProducts = additionalProducts.map((p) => p._internal.getDtoConf(include));
174
- }
175
- if (this.isAdditionalProduct) {
176
- const refKey = this.refKey;
177
- if (refKey === undefined) {
178
- throw new Error("AdditionalProduct without refKey, this should not happen");
179
- }
180
- const confAddProd = conf;
181
- confAddProd.refKey = refKey;
182
- confAddProd.selected = this.selected;
183
- }
184
- return conf;
185
- };
186
- this.setDtoConf = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
187
- // The DtoProdConf format can contain a sync group state, but
188
- // not the DtoAdditionalProductConfiguration format. So we apply
189
- // any passed state here.
190
- if (this.root === this) {
191
- const syncGroupHandler = this.syncGroupHandler;
192
- const newSyncGroupState = s.syncGroupState;
193
- if (syncGroupHandler !== undefined && newSyncGroupState !== undefined) {
194
- syncGroupHandler.setCompactSyncGroupState(newSyncGroupState);
195
- }
196
- }
197
- return yield this.setApiSelection(convertDtoProductConfToV1(s), doValidate, productLoaderForGroupedLoad);
198
- });
199
- this.setApiSelection = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
200
- return yield this._setApiSelectionWithOtherProduct(s, doValidate, productLoaderForGroupedLoad, undefined);
201
- });
202
- this.copyFrom = (source, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
203
- return yield this._setApiSelectionWithOtherProduct(convertDtoProductConfToV1(source.getDtoConf(CfgProdConfParts.NoExtra)), doValidate, productLoaderForGroupedLoad, source);
204
- });
205
- this._setApiSelectionWithOtherProduct = (productConfiguration, doValidate, productLoaderForGroupedLoad, sourceProduct) => __awaiter(this, void 0, void 0, function* () {
206
- // Wrap with cache will make getProduct for this function call use the same server call
207
- // for the same product with the same params. Used for getProduct (when a new additional
208
- // product is loaded) and postValidate.
209
- productLoaderForGroupedLoad =
210
- productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
211
- let change = false;
212
- if (sourceProduct !== undefined) {
213
- if (!compareCfgProductData(this._rawProductData, sourceProduct.rawProductData)) {
214
- this._rawProductData = sourceProduct.rawProductData;
215
- change = true;
216
- }
217
- if (this.configuration._internal.addRawFeatures(sourceProduct.configuration.rawFeatures, false)) {
218
- change = true;
219
- }
220
- if (this.configuration._internal.populateFeatures(sourceProduct.configuration.rootFeatureRefs)) {
221
- change = true;
222
- }
223
- }
224
- const configurationChange = yield this.configuration._internal.setApiSelection(productConfiguration.selOptions, false);
225
- if (configurationChange) {
226
- change = true;
227
- }
228
- if (this.optional) {
229
- if (yield this.setSelected(productConfiguration.selected !== false, CfgProductBubbleMode.Stop, false)) {
230
- change = true;
231
- }
232
- }
233
- yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad, productConfiguration);
234
- const apiSelectionAdditionalProducts = productConfiguration.additionalProducts || [];
235
- const additionalProducts = this.additionalProducts.slice();
236
- const additionalProductsCount = additionalProducts.length;
237
- const apiSelectionAdditionalProductsCount = apiSelectionAdditionalProducts.length;
238
- if (apiSelectionAdditionalProductsCount !== additionalProductsCount) {
239
- 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}`);
240
- }
241
- const sourceProductAdditionalProducts = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.additionalProducts;
242
- assert(!sourceProductAdditionalProducts ||
243
- additionalProductsCount === sourceProductAdditionalProducts.length, `Passed sourceProduct does not have the same number of additional products as this.`);
244
- if ((yield Promise.all(apiSelectionAdditionalProducts.map((apiSelectionAdditionalProduct) => __awaiter(this, void 0, void 0, function* () {
245
- var _b;
246
- const refKey = apiSelectionAdditionalProduct.refKey;
247
- assertDefined(refKey, "Additional product api configurations must have refKey.");
248
- const i = additionalProducts.findIndex((a) => refKey === a.refKey);
249
- assert(i !== -1, `Additional product not found. This product: "${this.key}". refKey of not found additional product: "${refKey}"`);
250
- let sourceProductAdditionalProduct = undefined;
251
- if (sourceProductAdditionalProducts !== undefined) {
252
- sourceProductAdditionalProduct =
253
- (_b = sourceProductAdditionalProducts.find((a) => refKey === a.refKey)) === null || _b === void 0 ? void 0 : _b._internal;
254
- assertDefined(sourceProductAdditionalProduct, "Additional product not found in sourceProduct");
255
- }
256
- const additionalProduct = additionalProducts.splice(i, 1)[0]; // Splicing like this is okay because this is done synchronous. The setCon. is what is async.
257
- return yield additionalProduct._internal._setApiSelectionWithOtherProduct(apiSelectionAdditionalProduct, doValidate, productLoaderForGroupedLoad, sourceProductAdditionalProduct);
258
- })))).some((b) => b)) {
259
- change = true;
260
- }
261
- if (doValidate && configurationChange) {
262
- yield this._revalidate(CfgProductBubbleMode.ToRoot, productLoaderForGroupedLoad, true);
263
- }
264
- else if (change) {
265
- // As setApiSelection is done recursively each level takes care of its own notifications
266
- // so we only need to bubble one level to notify this and swap out the reference in the
267
- // parent.
268
- yield this._notifyAllOfChange(CfgProductBubbleMode.OneLevel, true);
269
- }
270
- return change;
271
- });
272
- this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => {
273
- if (!this.configuration.structureCompare(other.configuration, strictOrder, descriptionMatch)) {
274
- return false;
275
- }
276
- return compareArrays(this.additionalProducts, other.additionalProducts, (l, r) => (!descriptionMatch || (descriptionMatch && isDescriptionMatch(l, r))) &&
277
- l.structureCompare(r, strictOrder, descriptionMatch), !descriptionMatch);
278
- };
279
- this.tryMatchSelection = (other, descriptionMatch = false, // Match on case insensitive description, not code
280
- productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
281
- // wrap with cache will make getProduct for this function call use the same server call
282
- // for the same product with the same params
283
- productLoaderForGroupedLoad =
284
- productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
285
- let change = false;
286
- if (this.optional && other.optional) {
287
- if (yield this.setSelected(other.selected, CfgProductBubbleMode.Stop, false)) {
288
- change = true;
289
- }
290
- }
291
- const configurationChange = yield this.configuration._internal.tryMatchSelection(other.configuration._internal, descriptionMatch, false);
292
- if (configurationChange) {
293
- change = true;
294
- yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, productLoaderForGroupedLoad, true);
295
- }
296
- else if (change) {
297
- yield this._notifyAllOfChange(CfgProductBubbleMode.ToRootAndBubbleSelected, true);
298
- }
299
- const thisAdditionalProducts = this.additionalProducts;
300
- const otherAdditionalProducts = other.additionalProducts;
301
- const promises = [];
302
- if (descriptionMatch) {
303
- for (const otherAdditionalProduct of otherAdditionalProducts) {
304
- if (1 <
305
- count(otherAdditionalProducts, (product) => isDescriptionMatch(product, otherAdditionalProduct))) {
306
- console.warn("tryMatchSelection will ignore products that have the same description");
307
- continue;
308
- }
309
- const toTryMatchProducts = thisAdditionalProducts.filter((product) => isDescriptionMatch(product, otherAdditionalProduct));
310
- if (1 < toTryMatchProducts.length) {
311
- console.warn("tryMatchSelection will ignore products that have the same description");
312
- continue;
313
- }
314
- if (toTryMatchProducts.length === 0) {
315
- continue;
316
- }
317
- promises.push(toTryMatchProducts[0]._internal.tryMatchSelection(otherAdditionalProduct._internal, descriptionMatch, productLoaderForGroupedLoad));
318
- }
319
- }
320
- else {
321
- if (thisAdditionalProducts.length !== otherAdditionalProducts.length) {
322
- console.warn("tryMatchSelection not same count, will not try to match further.");
323
- return change;
324
- }
325
- for (let i = 0; i < thisAdditionalProducts.length; i++) {
326
- promises.push(thisAdditionalProducts[i]._internal.tryMatchSelection(otherAdditionalProducts[i]._internal, descriptionMatch, productLoaderForGroupedLoad));
327
- }
328
- }
329
- if ((yield Promise.all(promises)).some((b) => b)) {
330
- change = true;
331
- }
332
- return change;
333
- });
334
- /** Only features in selected options and selected additional products. */
335
- this._getDescendantFeaturesWithCode = (code) => this.additionalProducts.reduce((agg, additionalProduct) => {
336
- if (additionalProduct.selected) {
337
- agg.push(...additionalProduct._internal._getDescendantFeaturesWithCode(code));
338
- }
339
- return agg;
340
- }, this._configuration._internal._getFeaturesWithCode(code));
341
- /**
342
- * Do a validate call for this product. It does not validate additional products, only this
343
- * product in isolation. The validation result is applied on the configuration. Then additional
344
- * products are synced (unloaded, loaded etc.) Finally the changes bubble up the tree.
345
- */
346
- this._revalidate = (bubbleMode, productLoader, committed) => __awaiter(this, void 0, void 0, function* () {
347
- const { _configuration: configuration } = this;
348
- const token = this.loadingObservable.startChildLoading();
349
- this._revalidateInProgressToken = token;
350
- try {
351
- const response = yield productLoader.postValidate(correctDefaultsOnCatalogueParams(this.prodParams), {
352
- selOptions: configuration._internal.getApiSelection(),
353
- knownFeatureCodes: configuration.rawFeatures.map((f) => f.code),
354
- });
355
- // The revalidateInProgressToken is used to know if some other revalidate
356
- // call has happened after this call, thereby making this call obsolete.
357
- // This is a bit crude in that it does not actually cancel previous validate
358
- // calls, but this is fine because 1. it is hard to cancel a call, especially
359
- // if you wanna have clear code 2. the actual calls are small anyhow 3. most
360
- // of all, the heavy work happens on the server, and that work will not be
361
- // cancelled even if we would cancel the call.
362
- if (this._revalidateInProgressToken !== token) {
363
- return false;
364
- }
365
- // After a successful validate-call we will always assume there
366
- // is a change. It would be possible to compare relevant parts
367
- // of productData, consider the result of setApiSelection and
368
- // syndAndLoad, however the code comparing productData would be fragile
369
- // and likely to break if new data-fields were added.
370
- if (this._destroyed) {
371
- return false;
372
- }
373
- const { productData, rootFeatureRefs, features } = response;
374
- const pricesUpdated = !comparePricesObjects(this.prices, productData.partsData.prices);
375
- this._rawProductData = productData;
376
- configuration._internal.addRawFeatures(features, true);
377
- if (rootFeatureRefs !== undefined) {
378
- configuration._internal.populateFeatures(rootFeatureRefs);
379
- }
380
- if (pricesUpdated) {
381
- this._configuration._internal._freshRefDescendants();
382
- this._configuration = CfgProductConfiguration._makeNewRefFrom(this._configuration._internal);
383
- }
384
- yield configuration._internal.setApiSelection(productData.partsData.selOptions || [], false);
385
- yield this._syncAndLoadAdditionalProducts(productLoader, undefined);
386
- if (this._destroyed) {
387
- return false;
388
- }
389
- yield this._notifyAllOfChange(bubbleMode, committed);
390
- return true;
391
- }
392
- catch (e) {
393
- throw augmentErrorMessage(e, `Validate product configuration request (${this.prodParams.partNumber}) failure`);
394
- }
395
- finally {
396
- this.loadingObservable.stopChildLoading(token);
397
- }
398
- });
399
- /**
400
- * Based on this configuration find what additional products should be shown and not, unload
401
- * (i.e. destroy) those that should no longer be shown, load the new ones.
402
- */
403
- this._syncAndLoadAdditionalProducts = (productLoaderForGroupedLoad, initialProductConfiguration) => __awaiter(this, void 0, void 0, function* () {
404
- const { _productLoaderRaw: productLoaderRaw, rawProductData: productData, configuration, additionalProducts: currentAdditionalProducts, } = this;
405
- const additionalProductRefs = [
406
- ...(productData.additionalProductRefs || []),
407
- ...collectAdditionalProductRefs(configuration),
408
- ]
409
- .reduce((a, c) => {
410
- if (a.every((p) => !isSameProductRef(p, c))) {
411
- a.push(c);
412
- }
413
- return a;
414
- }, [])
415
- .map((prodRef, originalIndex) => ({
416
- prodRef,
417
- originalIndex,
418
- }));
419
- let change = false;
420
- let i = currentAdditionalProducts.length;
421
- while (i--) {
422
- const currentAdditionalProduct = currentAdditionalProducts[i];
423
- const j = additionalProductRefs.findIndex((p) => {
424
- const prodRef = p.prodRef;
425
- return (prodRef.refKey === currentAdditionalProduct.refKey &&
426
- prodRef.partNumber === currentAdditionalProduct.partNumber &&
427
- isSameCatalogueParams(prodRef.catId, currentAdditionalProduct.catId));
428
- });
429
- if (j === -1) {
430
- currentAdditionalProduct.destroy();
431
- currentAdditionalProducts.splice(i, 1);
432
- change = true;
433
- }
434
- else {
435
- currentAdditionalProduct._internal._updateAdditionalProdRef(additionalProductRefs[j].prodRef);
436
- additionalProductRefs.splice(j, 1);
437
- }
438
- }
439
- const token = this.loadingObservable.startChildLoading();
440
- try {
441
- if (additionalProductRefs.length !== 0) {
442
- change = true;
443
- }
444
- const newAdditionalProducts = yield Promise.all(additionalProductRefs.map((p) => (() => __awaiter(this, void 0, void 0, function* () {
445
- var _c;
446
- const additionalProductRef = p.prodRef;
447
- const refKey = additionalProductRef.refKey;
448
- const additionalProductInitialProductConfiguration = (_c = initialProductConfiguration === null || initialProductConfiguration === void 0 ? void 0 : initialProductConfiguration.additionalProducts) === null || _c === void 0 ? void 0 : _c.find((aP) => refKey === aP.refKey);
449
- if (initialProductConfiguration !== undefined &&
450
- additionalProductInitialProductConfiguration === undefined) {
451
- console.warn(`Did not find initial product configuration for additional product with refKey ${refKey}`);
452
- }
453
- return {
454
- originalIndex: p.originalIndex,
455
- 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, additionalProductInitialProductConfiguration)),
456
- };
457
- }))()));
458
- if (this._destroyed) {
459
- return change;
460
- }
461
- for (const newAdditionalProduct of newAdditionalProducts) {
462
- currentAdditionalProducts.splice(newAdditionalProduct.originalIndex, 0, newAdditionalProduct.product);
463
- }
464
- return change;
465
- }
466
- finally {
467
- this.loadingObservable.stopChildLoading(token);
468
- }
469
- });
470
- this.root = root !== null && root !== void 0 ? root : this;
471
- 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 }));
472
- this._selected = optional ? selected : undefined;
473
- this.isAdditionalProduct = _additionalProductRef !== undefined;
474
- this._configuration = CfgProductConfiguration.make(initSuccess, initFail, rootFeatureRefs, rawFeatures, apiSelection, this, this.root);
475
- }
476
- get selected() {
477
- return this._selected !== false;
478
- }
479
- /**
480
- * Please note that cloning an additional product will make the clone believe is is
481
- * an additional product, even if it has no parent and root.
482
- * Providing the parent and root of what you clone as arguments is unwise as it will
483
- * make changes you do on the clone be propagated up to the original non-clone root product.
484
- */
485
- clone(parent, root) {
486
- return __awaiter(this, void 0, void 0, function* () {
487
- const product = yield new Promise((initSuccess, initFail) => {
488
- var _a;
489
- const p = new _CfgProductInternal(() => {
490
- initSuccess(p);
491
- }, initFail, this._productLoaderRaw, this.prodParams, this.settings, this.optional, this.selected, this._configuration.rootFeatureRefs, this._configuration.rawFeatures, this.uuid, this._rawUnit, this._rawProductData, this.configuration._internal.getApiSelection(), new AggregatedLoadingObservable(), parent, root, this._additionalProductRef, (_a = this._syncGroupHandler) === null || _a === void 0 ? void 0 : _a.clone());
492
- });
493
- for (const additionalProduct of this.additionalProducts) {
494
- product.additionalProducts.push(CfgProduct._makeNewRefFrom(yield additionalProduct._internal.clone(product, root || product)));
495
- }
496
- return product;
497
- });
498
- }
499
- /**
500
- * Internal use. Used when this product is an additional product, and
501
- * changing a parent product has made the settings for this product
502
- * change.
503
- */
504
- _updateAdditionalProdRef(p) {
505
- this._additionalProductRef = p;
506
- if (p.optional !== this.optional) {
507
- this._selected = p.optional ? false : undefined;
508
- }
509
- }
510
- get hasRootFeaturesChanged() {
511
- return (this._configuration._internal.hasRootFeaturesChanged ||
512
- this.additionalProducts.some((p) => p._internal.hasRootFeaturesChanged));
513
- }
514
- get description() {
515
- var _a, _b;
516
- return (_b = (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.refDescription) !== null && _b !== void 0 ? _b : this._rawProductData.description;
517
- }
518
- get rootNodeSources() {
519
- return this._rawProductData.models;
520
- }
521
- get mtrlApplications() {
522
- return this._rawProductData.mtrlApplications;
523
- }
524
- get currency() {
525
- return this._rawProductData.partsData.currency;
526
- }
527
- get fractionDigits() {
528
- return this._rawProductData.partsData.rounding || 0;
529
- }
530
- get prices() {
531
- return this._rawProductData.partsData.prices;
532
- }
533
- get measureDefinitions() {
534
- var _a;
535
- if (this._measureDefinitions === undefined) {
536
- this._measureDefinitions = ((_a = this._rawProductData.measurements) !== null && _a !== void 0 ? _a : [])
537
- .map((m) => CfgMeasureDefinition.make(m))
538
- .filter((m) => m !== undefined);
539
- }
540
- return this._measureDefinitions;
541
- }
542
- get refKey() {
543
- var _a;
544
- return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.refKey;
545
- }
546
- get transform() {
547
- var _a;
548
- return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.transform;
549
- }
550
- get anchor() {
551
- var _a;
552
- return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.anchor;
553
- }
554
- /** @throws an error if the actual unit sent by the server was not a LengthUnit */
555
- get unit() {
556
- if (this._unit === undefined) {
557
- this._unit = toLengthUnit(this._rawUnit);
558
- }
559
- return this._unit;
560
- }
561
- get aggregatedPrice() {
562
- const { currency, fractionDigits, rawProductData } = this;
563
- const { partsData } = rawProductData;
564
- let { listPrice, basePrice } = partsData;
565
- if (this._selected === false) {
566
- return { basePrice: 0, listPrice: 0, currency, fractionDigits };
567
- }
568
- for (const additionalProduct of this.additionalProducts || []) {
569
- const { basePrice: additionalBasePrice, listPrice: additionalListPrice, currency: additionalCurrency, fractionDigits: additionalFractionDigits, } = additionalProduct.aggregatedPrice;
570
- basePrice += additionalBasePrice;
571
- listPrice += additionalListPrice;
572
- if (currency !== additionalCurrency) {
573
- // This should not be possible
574
- // The server shouldn't return additional products with different currency from their parent
575
- 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}`);
576
- }
577
- if (fractionDigits !== additionalFractionDigits) {
578
- // This should not be possible
579
- // The server shouldn't return additional products with different fraction digits from their parent
580
- 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}`);
581
- }
582
- }
583
- return { basePrice, listPrice, currency, fractionDigits };
584
- }
585
- get optional() {
586
- return this._selected !== undefined;
587
- }
588
- setSelected(selected, bubbleMode, interactive) {
589
- return __awaiter(this, void 0, void 0, function* () {
590
- if (!this.optional) {
591
- console.warn("This product is not optional. Nothing will happen");
592
- return false;
593
- }
594
- if (this._selected === selected) {
595
- return false;
596
- }
597
- // Vitally important that this happens before the call to reset,
598
- // so that the reset won't cause infinite loops
599
- this._selected = selected;
600
- if (interactive) {
601
- if (selected) {
602
- const syncGroupHandler = this.syncGroupHandler;
603
- if (syncGroupHandler !== undefined) {
604
- yield syncGroupHandler.init(this.root, wrapWithCache(this._productLoaderRaw));
605
- }
606
- }
607
- else {
608
- yield this.reset();
609
- // In case a passed initial configuration has made it reset to selected
610
- this._selected = selected;
611
- }
612
- }
613
- yield this._notifyAllOfChange(bubbleMode, true);
614
- return true;
615
- });
616
- }
617
- get configuration() {
618
- return this._configuration;
619
- }
620
- get rawProductData() {
621
- return this._rawProductData;
622
- }
623
- /**
624
- * Please note that this relates to the visibility in the Configuration tree.
625
- * It does not affect the visibility of anything in the 3D view at all.
626
- */
627
- get visibleIfAdditionalProduct() {
628
- return this.rawProductData.hideIfAdditionalProduct !== true;
629
- }
630
- /**
631
- * Please note that this relates to the visibility in the Configuration tree.
632
- * It does not affect the visibility of anything in the 3D view at all.
633
- */
634
- get visibleIfMainProduct() {
635
- return this.rawProductData.hideIfMainProduct !== true;
636
- }
637
- /**
638
- * Please note that this relates to the visibility in the Configuration tree.
639
- * It does not affect the visibility of anything in the 3D view at all.
640
- */
641
- get visible() {
642
- return this.isAdditionalProduct
643
- ? this.visibleIfAdditionalProduct
644
- : this.visibleIfMainProduct;
645
- }
646
- get syncGroupHandler() {
647
- return this.root._syncGroupHandler;
648
- }
649
- get syncGroupsVerboseLogging() {
650
- var _a, _b;
651
- return (_b = (_a = this.syncGroupHandler) === null || _a === void 0 ? void 0 : _a.verboseLogging) !== null && _b !== void 0 ? _b : false;
652
- }
653
- /**
654
- * Set to true to get verbose sync state changes logged to the console.
655
- */
656
- set syncGroupsVerboseLogging(v) {
657
- const syncGroupHandler = this.syncGroupHandler;
658
- if (syncGroupHandler === undefined) {
659
- throw new Error("No syncGroupHandler, so can not change log verbosity");
660
- }
661
- syncGroupHandler.verboseLogging = v;
662
- }
663
- }
664
- _CfgProductInternal.make = (productLoaderRaw, productLoaderForGroupedLoad, // Used when instantiating the current product
665
- prodParams, settings, optional, loadingObservable, parent, root, additionalProductRef, initialProductConfiguration) => __awaiter(void 0, void 0, void 0, function* () {
666
- // Wrap with cache will make getProduct for this function call use the same server call
667
- // for the same product with the same params. Not retained for future calls, only used
668
- // at this initial load.
669
- productLoaderForGroupedLoad =
670
- productLoaderForGroupedLoad || wrapWithCache(productLoaderRaw);
671
- let syncGroupHandler = undefined;
672
- // No root means we are root. We only create SyncGroupsHandler if this is the root product
673
- if (root === undefined) {
674
- let initialSyncGroupsState = undefined;
675
- // DtoProductConf supports containing the sync group state, but the old
676
- // DtoAdditionalProductConfiguration does not
677
- if (initialProductConfiguration !== undefined &&
678
- isProductConf(initialProductConfiguration)) {
679
- initialSyncGroupsState = initialProductConfiguration.syncGroupState;
680
- }
681
- syncGroupHandler = SyncGroupsHandler.make(settings.syncGroupsApplyMode, loadingObservable, initialSyncGroupsState);
682
- }
683
- try {
684
- const defaultCorrectedProdParams = correctDefaultsOnCatalogueParams(prodParams);
685
- let initialProductConfigurationV1 = undefined;
686
- if (initialProductConfiguration !== undefined) {
687
- if (isProductConf(initialProductConfiguration)) {
688
- initialProductConfigurationV1 = convertDtoProductConfToV1(initialProductConfiguration);
689
- }
690
- else if (isAdditionalProductConfiguration(initialProductConfiguration)) {
691
- initialProductConfigurationV1 = initialProductConfiguration;
692
- }
693
- }
694
- const productResponse = yield (initialProductConfigurationV1
695
- ? productLoaderForGroupedLoad.postValidate(defaultCorrectedProdParams, {
696
- knownFeatureCodes: [],
697
- selOptions: initialProductConfigurationV1.selOptions,
698
- })
699
- : productLoaderForGroupedLoad.getProduct(defaultCorrectedProdParams));
700
- const { productData, rootFeatureRefs, features: rawFeatures, uuid, unit, } = productResponse;
701
- const initiallySelected = !optional || (initialProductConfigurationV1 === null || initialProductConfigurationV1 === void 0 ? void 0 : initialProductConfigurationV1.selected) === true;
702
- const product = yield new Promise((initSuccess, initFail) => {
703
- var _a;
704
- const p = new _CfgProductInternal(() => {
705
- // We absolutely do not want anyone to assign to this._configuration. So we want that field private.
706
- // But we can not set the api selection synchronously. And the product configuration needs "this". So we use this callback.
707
- // Feel free to find a nicer more readable solution :)
708
- initSuccess(p);
709
- }, initFail, productLoaderRaw, prodParams, settings, optional, initiallySelected, rootFeatureRefs !== null && rootFeatureRefs !== void 0 ? rootFeatureRefs : [], rawFeatures, uuid, unit, productData, (_a = productData.partsData.selOptions) !== null && _a !== void 0 ? _a : [], loadingObservable, parent, root, additionalProductRef, syncGroupHandler);
710
- });
711
- yield product._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad, initialProductConfigurationV1);
712
- product._initialClone = yield product.clone();
713
- if (syncGroupHandler !== undefined && !initialProductConfiguration) {
714
- // As syncGroupHandler is only set for root product we know that we will init with root.
715
- // If we have an initialProductConfiguration we do not run init for the syncGroups.
716
- // The idea with an initial configuration is that the product should look as it did when
717
- // the configuration was saved. Not running init does that. Also, the DtoProductConf
718
- // object can contain a sync state which is then used to populate the sync state.
719
- yield syncGroupHandler.init(product, productLoaderForGroupedLoad);
720
- }
721
- return product;
722
- }
723
- catch (e) {
724
- throw augmentErrorMessage(e, `Load product request (${prodParams.partNumber}) failure`);
725
- }
726
- });
727
- export class CfgProduct {
728
- constructor(_internal) {
729
- this._internal = _internal;
730
- this.isBackedBySame = (other) => this._internal === other._internal;
731
- /**
732
- * Recursively marks this and descendants as destroyed so that late events are ignored
733
- * correctly. If you destroy one shallow copy of this you destroy all.
734
- */
735
- this.destroy = () => this._internal.destroy();
736
- /** Makes a clone of this. It is disconnected from the original. */
737
- this.clone = () => __awaiter(this, void 0, void 0, function* () { return CfgProduct._makeNewRefFrom(yield this._internal.clone()); });
738
- /**
739
- * Only applicable when this product is optional.
740
- * Setting this does not cause a validation call as toggling an optional additional product is
741
- * assumed to always be legal.
742
- */
743
- this.setSelected = (v) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setSelected(v, CfgProductBubbleMode.ToRootAndBubbleSelected, true); });
744
- /**
745
- * Experimental. Additional products lacks descriptions or keys that are suitably for structure
746
- * compare, so we use strict-order when trying to match the additional products. This makes
747
- * this method work nicely for different products having pretty much the same child products.
748
- */
749
- this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => this._internal.structureCompare(other._internal, strictOrder, descriptionMatch);
750
- /**
751
- * Experimental. Additional products lacks descriptions or keys that are suitably for try
752
- * match, so we use strict-order when trying to match the additional products. This makes
753
- * this method work nicely for different products having pretty much the same child products.
754
- * This method does not propagate its selections.
755
- * This method will cause validation calls if something change.
756
- */
757
- this.tryMatchSelection = (other, descriptionMatch = false // Match on case insensitive description, not code
758
- ) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.tryMatchSelection(other._internal, descriptionMatch); });
759
- /**
760
- * Gets what selections has been made on the product, recursively including product
761
- * configuration, optional products and additional products. Used when a full view of all
762
- * selections on a product is needed, such as when doing Render or Export.
763
- * @deprecated getDtoConf provides a newer format.
764
- * @see getDtoConf
765
- */
766
- this.getApiSelection = () => convertDtoProductConfToV1(this._internal.getDtoConf(CfgProdConfParts.NoExtra), true);
767
- /**
768
- * Applies the configuration (selections) in the passed object onto the product recursively
769
- * including product configuration, optional products and additional products.
770
- * @param doValidate Makes a server side validation call. These are necessary to ensure that
771
- * the right models are loaded.
772
- * @deprecated setDtoConf uses a newer format.
773
- */
774
- this.setApiSelection = (configuration, doValidate = true) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setApiSelection(configuration, doValidate); });
775
- /**
776
- * A newer alternative version of getApiSelection. This returns the configuration (selections)
777
- * on the product, recursively including product configuration, optional products and additional
778
- * products.
779
- * This version has the following advantages over getApiSelection:
780
- * - The format is clearer, designed to be readable
781
- * - Makes less assumptions about the structure in the Product being unchanging over time. In
782
- * particular, the Feature codes are included in the data, so that changes to what Features
783
- * are used in a Product is less likely to lead to unexpected results.
784
- * - You can request ExtendedData, ProductParams and/or SyncGroupState to be included in the
785
- * result. This extra data is ignored when passed back into the API, but it can be very useful
786
- * for external applications.
787
- * The other version (getApiSelection) has the advantage of using a format directly compatible with the API:s.
788
- * @param include Includes extra data which is not an actual part of the configuration
789
- */
790
- this.getDtoConf = (include = CfgProdConfParts.NoExtra) => this._internal.getDtoConf(include);
791
- /**
792
- * A newer alternative version of setApiSelection.
793
- * @param doValidate Makes a server side validation call. These are necessary to ensure that
794
- * the right models are loaded.
795
- */
796
- this.setDtoConf = (configuration, doValidate = true) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setDtoConf(configuration, doValidate); });
797
- this.listenForChange = (l) => this._internal.changeObservable.listen(l);
798
- this.stopListenForChange = (l) => this._internal.changeObservable.stopListen(l);
799
- this.stopAllListenForChange = () => this._internal.changeObservable.stopAllListen();
800
- this.listenForLoading = (l) => this._internal.loadingObservable.listen(l);
801
- this.stopListenForLoading = (l) => this._internal.loadingObservable.stopListen(l);
802
- this.stopAllListenForLoading = () => this._internal.loadingObservable.stopAllListen();
803
- }
804
- static make(productLoader, prodParams, settings, initialProductConfiguration) {
805
- return __awaiter(this, void 0, void 0, function* () {
806
- return this._makeNewRefFrom(yield _CfgProductInternal.make(productLoader, undefined, prodParams, completeSettings(settings), false, new AggregatedLoadingObservable(), undefined, undefined, undefined, initialProductConfiguration));
807
- });
808
- }
809
- /**
810
- * Makes an object wrapping the passed object. This is not a clone method, it is a method to
811
- * make a new outer reference. Like a shallow copy. We use this to help frameworks that are
812
- * build around using equals to detect change.
813
- */
814
- static _makeNewRefFrom(source) {
815
- return new this(source);
816
- }
817
- /**
818
- * A client side only key that should uniquely identify this product amongst other additional
819
- * products.
820
- */
821
- get key() {
822
- return this._internal.key;
823
- }
824
- /**
825
- * Only used when this product is in additional product.
826
- * As a product can have multiple instances of the same additional product this key exists.
827
- * It will be unique amongst child products, but not globally unique.
828
- */
829
- get refKey() {
830
- return this._internal.refKey;
831
- }
832
- get prodParams() {
833
- return this._internal.prodParams;
834
- }
835
- get lang() {
836
- return this._internal.prodParams.lang;
837
- }
838
- get catId() {
839
- const { cid, enterprise, prdCat, prdCatVersion, priceList, vendor } = this._internal.prodParams;
840
- return {
841
- cid,
842
- enterprise,
843
- prdCat,
844
- prdCatVersion,
845
- priceList,
846
- vendor,
847
- };
848
- }
849
- get partNumber() {
850
- return this._internal.prodParams.partNumber;
851
- }
852
- get isAdditionalProduct() {
853
- return this._internal.isAdditionalProduct;
854
- }
855
- /** Only used when this product is an additional product. Root products are never optional. */
856
- get optional() {
857
- return this._internal.optional;
858
- }
859
- /**
860
- * Only applicable when this product is optional. If this product is not optional this is
861
- * always true.
862
- */
863
- get selected() {
864
- return this._internal.selected;
865
- }
866
- /**
867
- * Please note that this relates to the visibility in the Configuration tree.
868
- * It does not affect the visibility of anything in the 3D view at all.
869
- * Visibility is affects the Configuration for this Product, but any Additional Products
870
- * will not be affected.
871
- */
872
- get visible() {
873
- return this._internal.visible;
874
- }
875
- // A similar text to the one below exists in global-message-managers.md and should be kept in sync.
876
- /**
877
- * Functional selection is a Catalogues feature where selecting Options on Features result in that you
878
- * "jump" to another Product as a result of the Validate call. You normally do not notice that a functional
879
- * selection has occurred except for the styleNr changing. Functional selection can change which Features
880
- * from the original product call are used as root Features. This can in turn affect if serialized
881
- * configuration can be applied or not.
882
- *
883
- * The SDK can currently only apply serialized configuration if the list of root Features has not changed.
884
- * For this reason, when functional selection has happened, extracting data for external systems might work
885
- * well, but reapplying back into Stage will probably fail.
886
- */
887
- get hasRootFeaturesChanged() {
888
- return this._internal.hasRootFeaturesChanged;
889
- }
890
- get rawProductData() {
891
- return this._internal.rawProductData;
892
- }
893
- get uuid() {
894
- return this._internal.uuid;
895
- }
896
- get unit() {
897
- return this._internal.unit;
898
- }
899
- get sku() {
900
- return this._internal.rawProductData.sku;
901
- }
902
- get styleNr() {
903
- return this._internal.rawProductData.partsData.styleNr;
904
- }
905
- /** An URL. */
906
- get preview() {
907
- return this._internal.rawProductData.navImage;
908
- }
909
- get description() {
910
- return this._internal.description;
911
- }
912
- get additionalProducts() {
913
- return this._internal.additionalProducts;
914
- }
915
- get configuration() {
916
- return this._internal.configuration;
917
- }
918
- get transform() {
919
- return this._internal.transform;
920
- }
921
- get currency() {
922
- return this._internal.currency;
923
- }
924
- /**
925
- * If positive the number of fraction digits.
926
- * If negative rounding (essentially the number of zeros to the right)
927
- */
928
- get fractionDigits() {
929
- return this._internal.fractionDigits;
930
- }
931
- get aggregatedPrice() {
932
- return this._internal.aggregatedPrice;
933
- }
934
- }
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 { convertDtoProductConfToV1, isAdditionalProductConfiguration, isProductConf, } from "./ConfigurationConverter.js";
13
+ import { CfgProdConfParts } from "./index.js";
14
+ import { ProductConfigurationBubbleMode } from "./productConfiguration/CfgOption.js";
15
+ import { CfgProductConfiguration } from "./productConfiguration/CfgProductConfiguration.js";
16
+ import { collectAdditionalProductRefs } from "./productConfiguration/utilitiesProductConfiguration.js";
17
+ import { wrapWithCache } from "./productLoader.js";
18
+ import { SyncGroupsHandler } from "./syncGroups/SyncGroupsHandler.js";
19
+ import { compareCfgProductData, comparePricesObjects, correctDefaultsOnCatalogueParams, isSameCatalogueParams, isSameProductRef, makeProductKey, } from "./utilitiesCatalogueData.js";
20
+ function completeSettings(incompleteSettings) {
21
+ var _a;
22
+ return {
23
+ strictSelectOneSelectionCount: (_a = incompleteSettings === null || incompleteSettings === void 0 ? void 0 : incompleteSettings.strictSelectOneSelectionCount) !== null && _a !== void 0 ? _a : false,
24
+ syncGroupsApplyMode: incompleteSettings === null || incompleteSettings === void 0 ? void 0 : incompleteSettings.syncGroupsApplyMode,
25
+ };
26
+ }
27
+ /**
28
+ * This enum is used internally in the SDK and is not expected by be used directly by integrators.
29
+ */
30
+ export var CfgProductBubbleMode;
31
+ (function (CfgProductBubbleMode) {
32
+ /** Stop bubbling. */
33
+ CfgProductBubbleMode["Stop"] = "Stop";
34
+ /**
35
+ * Bubble to the parent CfgProduct up the tree.
36
+ * This makes the CfgProduct we we call from notify that it has changed, and the CfgProduct
37
+ * above switch out the reference to this.
38
+ */
39
+ CfgProductBubbleMode["OneLevel"] = "OneLevel";
40
+ /** Bubble to the root CfgProduct. */
41
+ CfgProductBubbleMode["ToRoot"] = "ToRoot";
42
+ /** Bubble to the root CfgProduct and turn on all optional CfgProducts on the way up. */
43
+ CfgProductBubbleMode["ToRootAndBubbleSelected"] = "ToRootAndBubbleSelected";
44
+ })(CfgProductBubbleMode || (CfgProductBubbleMode = {}));
45
+ function isDescriptionMatch(l, r) {
46
+ const ld = l.description;
47
+ const rd = r.description;
48
+ return ld !== undefined && rd !== undefined && ld.toLowerCase() === rd.toLowerCase();
49
+ }
50
+ /**
51
+ * This class is meant to only be used through CfgProduct. It should never be instantiated on its
52
+ * own. Normally the internal state of this class should never be directly modified. CfgProduct is
53
+ * the class that should be used and interacted with.
54
+ */
55
+ export class _CfgProductInternal {
56
+ constructor(initSuccess, initFail, _productLoaderRaw, prodParams, settings, optional, selected, rootFeatureRefs, rawFeatures, notes, uuid, _rawUnit, _rawProductData, apiSelection, loadingObservable, parent, root, _additionalProductRef, _syncGroupHandler) {
57
+ var _a;
58
+ this._productLoaderRaw = _productLoaderRaw;
59
+ this.prodParams = prodParams;
60
+ this.settings = settings;
61
+ this.uuid = uuid;
62
+ this._rawUnit = _rawUnit;
63
+ this._rawProductData = _rawProductData;
64
+ this.loadingObservable = loadingObservable;
65
+ this.parent = parent;
66
+ this._additionalProductRef = _additionalProductRef;
67
+ this._syncGroupHandler = _syncGroupHandler;
68
+ this._destroyed = false;
69
+ this.additionalProducts = [];
70
+ this._notes = new Map();
71
+ this.changeObservable = new Observable();
72
+ /** Mark this and its descendants as destroyed and remove all listeners */
73
+ this.destroy = () => {
74
+ var _a;
75
+ this._destroyed = true;
76
+ this.changeObservable.stopAllListen();
77
+ this.configuration.stopAllListenForChange();
78
+ for (const additionalProduct of (_a = this.additionalProducts) !== null && _a !== void 0 ? _a : []) {
79
+ additionalProduct.destroy();
80
+ }
81
+ };
82
+ /**
83
+ * Reset will reset the product to its initial state
84
+ */
85
+ this.reset = () => __awaiter(this, void 0, void 0, function* () {
86
+ if (this._initialClone !== undefined) {
87
+ yield this.copyFrom(this._initialClone, true);
88
+ }
89
+ });
90
+ this._notifyAllOfChange = (bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
91
+ if (bubbleMode === CfgProductBubbleMode.Stop) {
92
+ return;
93
+ }
94
+ const parent = this.parent;
95
+ const freshRef = CfgProduct._makeNewRefFrom(this);
96
+ this.changeObservable.notifyAll({ freshRef, committed });
97
+ if (parent !== undefined) {
98
+ yield parent._additionalProductHasChanged(freshRef, bubbleMode === CfgProductBubbleMode.OneLevel
99
+ ? CfgProductBubbleMode.Stop
100
+ : bubbleMode, committed);
101
+ }
102
+ });
103
+ /** Called when a child (additional product or the configuration) has changed. */
104
+ this._childHasChanged = (bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
105
+ if (bubbleMode === CfgProductBubbleMode.ToRootAndBubbleSelected &&
106
+ this.optional &&
107
+ !this.selected) {
108
+ yield this.setSelected(true, bubbleMode, false);
109
+ return;
110
+ }
111
+ yield this._notifyAllOfChange(bubbleMode, committed);
112
+ });
113
+ /** Called by child to tell its parent that it has changed. */
114
+ this._additionalProductHasChanged = (freshRef, bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
115
+ const i = this.additionalProducts.findIndex((a) => a.isBackedBySame(freshRef));
116
+ if (i !== -1) {
117
+ // Child additional product might not be found. This probably means that propagate
118
+ // has chopped the branch your on. Let's say we have products A -> B -> C.
119
+ // We change an option on C. This is propagated to product A. Product A now
120
+ // changes its additional product so that B is no longer a child of A. Hence
121
+ // C no longer is part of the tree. Odd, but fully permitted.
122
+ this.additionalProducts[i] = freshRef;
123
+ }
124
+ yield this._childHasChanged(bubbleMode, committed);
125
+ });
126
+ /** Called by the configuration to tell its parent that it has changed. */
127
+ this._configurationHasChanged = (freshRef, bubbleMode, committed) => __awaiter(this, void 0, void 0, function* () {
128
+ this._configuration = freshRef;
129
+ switch (bubbleMode) {
130
+ case ProductConfigurationBubbleMode.ValidateAndBubbleSelected:
131
+ // The revalidate call will continue the bubble
132
+ yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, this._productLoaderRaw, committed);
133
+ return;
134
+ case ProductConfigurationBubbleMode.BubbleSelected:
135
+ yield this._childHasChanged(CfgProductBubbleMode.ToRootAndBubbleSelected, committed);
136
+ return;
137
+ case ProductConfigurationBubbleMode.Validate:
138
+ // The revalidate call will continue the bubble
139
+ yield this._revalidate(CfgProductBubbleMode.ToRoot, this._productLoaderRaw, committed);
140
+ return;
141
+ case ProductConfigurationBubbleMode.ToParentProduct:
142
+ // Do not continue bubble as we have reached the parent CfgProduct
143
+ return;
144
+ case ProductConfigurationBubbleMode.OneLevel:
145
+ yield this._childHasChanged(CfgProductBubbleMode.OneLevel, committed);
146
+ return;
147
+ case ProductConfigurationBubbleMode.Stop:
148
+ yield this._childHasChanged(CfgProductBubbleMode.Stop, committed);
149
+ return;
150
+ case ProductConfigurationBubbleMode.ToRoot:
151
+ yield this._childHasChanged(CfgProductBubbleMode.ToRoot, committed);
152
+ return;
153
+ }
154
+ });
155
+ this.getDtoConf = (include) => {
156
+ var _a;
157
+ const conf = {};
158
+ const features = this.configuration._internal.getDtoConf((include & CfgProdConfParts.ExtendedData) === CfgProdConfParts.ExtendedData);
159
+ if (0 < features.length) {
160
+ conf.features = features;
161
+ }
162
+ if ((include & CfgProdConfParts.ProdParams) === CfgProdConfParts.ProdParams) {
163
+ conf.prodParams = this.prodParams;
164
+ }
165
+ // Only store the syncGroupState for the root product. The same state
166
+ // is used for the entire product, including the additional product,
167
+ // so no need to store it for additional products.
168
+ if ((include & CfgProdConfParts.SyncGroupState) === CfgProdConfParts.SyncGroupState &&
169
+ this.parent === undefined) {
170
+ conf.syncGroupState = (_a = this.syncGroupHandler) === null || _a === void 0 ? void 0 : _a.getCompactSyncGroupState();
171
+ }
172
+ const additionalProducts = this.additionalProducts;
173
+ if (0 < additionalProducts.length) {
174
+ conf.additionalProducts = additionalProducts.map((p) => p._internal.getDtoConf(include));
175
+ }
176
+ if (this.isAdditionalProduct) {
177
+ const refKey = this.refKey;
178
+ if (refKey === undefined) {
179
+ throw new Error("AdditionalProduct without refKey, this should not happen");
180
+ }
181
+ const confAddProd = conf;
182
+ confAddProd.refKey = refKey;
183
+ confAddProd.selected = this.selected;
184
+ }
185
+ return conf;
186
+ };
187
+ this.setDtoConf = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
188
+ // The DtoProdConf format can contain a sync group state, but
189
+ // not the DtoAdditionalProductConfiguration format. So we apply
190
+ // any passed state here.
191
+ if (this.root === this) {
192
+ const syncGroupHandler = this.syncGroupHandler;
193
+ const newSyncGroupState = s.syncGroupState;
194
+ if (syncGroupHandler !== undefined && newSyncGroupState !== undefined) {
195
+ syncGroupHandler.setCompactSyncGroupState(newSyncGroupState);
196
+ }
197
+ }
198
+ return yield this.setApiSelection(convertDtoProductConfToV1(s), doValidate, productLoaderForGroupedLoad);
199
+ });
200
+ this.setApiSelection = (s, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
201
+ return yield this._setApiSelectionWithOtherProduct(s, doValidate, productLoaderForGroupedLoad, undefined);
202
+ });
203
+ this.copyFrom = (source, doValidate, productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
204
+ return yield this._setApiSelectionWithOtherProduct(convertDtoProductConfToV1(source.getDtoConf(CfgProdConfParts.NoExtra)), doValidate, productLoaderForGroupedLoad, source);
205
+ });
206
+ this._setApiSelectionWithOtherProduct = (productConfiguration, doValidate, productLoaderForGroupedLoad, sourceProduct) => __awaiter(this, void 0, void 0, function* () {
207
+ // Wrap with cache will make getProduct for this function call use the same server call
208
+ // for the same product with the same params. Used for getProduct (when a new additional
209
+ // product is loaded) and postValidate.
210
+ productLoaderForGroupedLoad =
211
+ productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
212
+ let change = false;
213
+ if (sourceProduct !== undefined) {
214
+ if (!compareCfgProductData(this._rawProductData, sourceProduct.rawProductData)) {
215
+ this._rawProductData = sourceProduct.rawProductData;
216
+ change = true;
217
+ }
218
+ if (this.configuration._internal.addRawFeatures(sourceProduct.configuration.rawFeatures, false)) {
219
+ change = true;
220
+ }
221
+ if (this.configuration._internal.populateFeatures(sourceProduct.configuration.rootFeatureRefs)) {
222
+ change = true;
223
+ }
224
+ const targetNotes = this._notes;
225
+ const sourceNotes = sourceProduct._notes;
226
+ for (const targetKey of targetNotes.keys()) {
227
+ if (!sourceNotes.has(targetKey)) {
228
+ targetNotes.delete(targetKey);
229
+ change = true;
230
+ }
231
+ }
232
+ for (const [sourceKey, sourceNote] of sourceNotes) {
233
+ if (!targetNotes.has(sourceKey)) {
234
+ targetNotes.set(sourceKey, sourceNote);
235
+ change = true;
236
+ }
237
+ }
238
+ }
239
+ const configurationChange = yield this.configuration._internal.setApiSelection(productConfiguration.selOptions, false);
240
+ if (configurationChange) {
241
+ change = true;
242
+ }
243
+ if (this.optional) {
244
+ if (yield this.setSelected(productConfiguration.selected !== false, CfgProductBubbleMode.Stop, false)) {
245
+ change = true;
246
+ }
247
+ }
248
+ yield this._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad, productConfiguration);
249
+ const apiSelectionAdditionalProducts = productConfiguration.additionalProducts || [];
250
+ const additionalProducts = this.additionalProducts.slice();
251
+ const additionalProductsCount = additionalProducts.length;
252
+ const apiSelectionAdditionalProductsCount = apiSelectionAdditionalProducts.length;
253
+ if (apiSelectionAdditionalProductsCount !== additionalProductsCount) {
254
+ 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}`);
255
+ }
256
+ const sourceProductAdditionalProducts = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.additionalProducts;
257
+ assert(!sourceProductAdditionalProducts ||
258
+ additionalProductsCount === sourceProductAdditionalProducts.length, `Passed sourceProduct does not have the same number of additional products as this.`);
259
+ if ((yield Promise.all(apiSelectionAdditionalProducts.map((apiSelectionAdditionalProduct) => __awaiter(this, void 0, void 0, function* () {
260
+ var _b;
261
+ const refKey = apiSelectionAdditionalProduct.refKey;
262
+ assertDefined(refKey, "Additional product api configurations must have refKey.");
263
+ const i = additionalProducts.findIndex((a) => refKey === a.refKey);
264
+ assert(i !== -1, `Additional product not found. This product: "${this.key}". refKey of not found additional product: "${refKey}"`);
265
+ let sourceProductAdditionalProduct = undefined;
266
+ if (sourceProductAdditionalProducts !== undefined) {
267
+ sourceProductAdditionalProduct =
268
+ (_b = sourceProductAdditionalProducts.find((a) => refKey === a.refKey)) === null || _b === void 0 ? void 0 : _b._internal;
269
+ assertDefined(sourceProductAdditionalProduct, "Additional product not found in sourceProduct");
270
+ }
271
+ const additionalProduct = additionalProducts.splice(i, 1)[0]; // Splicing like this is okay because this is done synchronous. The setCon. is what is async.
272
+ return yield additionalProduct._internal._setApiSelectionWithOtherProduct(apiSelectionAdditionalProduct, doValidate, productLoaderForGroupedLoad, sourceProductAdditionalProduct);
273
+ })))).some((b) => b)) {
274
+ change = true;
275
+ }
276
+ if (doValidate && configurationChange) {
277
+ yield this._revalidate(CfgProductBubbleMode.ToRoot, productLoaderForGroupedLoad, true);
278
+ }
279
+ else if (change) {
280
+ // As setApiSelection is done recursively each level takes care of its own notifications
281
+ // so we only need to bubble one level to notify this and swap out the reference in the
282
+ // parent.
283
+ yield this._notifyAllOfChange(CfgProductBubbleMode.OneLevel, true);
284
+ }
285
+ return change;
286
+ });
287
+ this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => {
288
+ if (!this.configuration.structureCompare(other.configuration, strictOrder, descriptionMatch)) {
289
+ return false;
290
+ }
291
+ return compareArrays(this.additionalProducts, other.additionalProducts, (l, r) => (!descriptionMatch || (descriptionMatch && isDescriptionMatch(l, r))) &&
292
+ l.structureCompare(r, strictOrder, descriptionMatch), !descriptionMatch);
293
+ };
294
+ this.tryMatchSelection = (other, descriptionMatch = false, // Match on case insensitive description, not code
295
+ productLoaderForGroupedLoad) => __awaiter(this, void 0, void 0, function* () {
296
+ // wrap with cache will make getProduct for this function call use the same server call
297
+ // for the same product with the same params
298
+ productLoaderForGroupedLoad =
299
+ productLoaderForGroupedLoad || wrapWithCache(this._productLoaderRaw);
300
+ let change = false;
301
+ if (this.optional && other.optional) {
302
+ if (yield this.setSelected(other.selected, CfgProductBubbleMode.Stop, false)) {
303
+ change = true;
304
+ }
305
+ }
306
+ const configurationChange = yield this.configuration._internal.tryMatchSelection(other.configuration._internal, descriptionMatch, false);
307
+ if (configurationChange) {
308
+ change = true;
309
+ yield this._revalidate(CfgProductBubbleMode.ToRootAndBubbleSelected, productLoaderForGroupedLoad, true);
310
+ }
311
+ else if (change) {
312
+ yield this._notifyAllOfChange(CfgProductBubbleMode.ToRootAndBubbleSelected, true);
313
+ }
314
+ const thisAdditionalProducts = this.additionalProducts;
315
+ const otherAdditionalProducts = other.additionalProducts;
316
+ const promises = [];
317
+ if (descriptionMatch) {
318
+ for (const otherAdditionalProduct of otherAdditionalProducts) {
319
+ if (1 <
320
+ count(otherAdditionalProducts, (product) => isDescriptionMatch(product, otherAdditionalProduct))) {
321
+ console.warn("tryMatchSelection will ignore products that have the same description");
322
+ continue;
323
+ }
324
+ const toTryMatchProducts = thisAdditionalProducts.filter((product) => isDescriptionMatch(product, otherAdditionalProduct));
325
+ if (1 < toTryMatchProducts.length) {
326
+ console.warn("tryMatchSelection will ignore products that have the same description");
327
+ continue;
328
+ }
329
+ if (toTryMatchProducts.length === 0) {
330
+ continue;
331
+ }
332
+ promises.push(toTryMatchProducts[0]._internal.tryMatchSelection(otherAdditionalProduct._internal, descriptionMatch, productLoaderForGroupedLoad));
333
+ }
334
+ }
335
+ else {
336
+ if (thisAdditionalProducts.length !== otherAdditionalProducts.length) {
337
+ console.warn("tryMatchSelection not same count, will not try to match further.");
338
+ return change;
339
+ }
340
+ for (let i = 0; i < thisAdditionalProducts.length; i++) {
341
+ promises.push(thisAdditionalProducts[i]._internal.tryMatchSelection(otherAdditionalProducts[i]._internal, descriptionMatch, productLoaderForGroupedLoad));
342
+ }
343
+ }
344
+ if ((yield Promise.all(promises)).some((b) => b)) {
345
+ change = true;
346
+ }
347
+ return change;
348
+ });
349
+ /** Only features in selected options and selected additional products. */
350
+ this._getDescendantFeaturesWithCode = (code) => this.additionalProducts.reduce((agg, additionalProduct) => {
351
+ if (additionalProduct.selected) {
352
+ agg.push(...additionalProduct._internal._getDescendantFeaturesWithCode(code));
353
+ }
354
+ return agg;
355
+ }, this._configuration._internal._getFeaturesWithCode(code));
356
+ /**
357
+ * Do a validate call for this product. It does not validate additional products, only this
358
+ * product in isolation. The validation result is applied on the configuration. Then additional
359
+ * products are synced (unloaded, loaded etc.) Finally the changes bubble up the tree.
360
+ */
361
+ this._revalidate = (bubbleMode, productLoader, committed) => __awaiter(this, void 0, void 0, function* () {
362
+ const { _configuration: configuration } = this;
363
+ const token = this.loadingObservable.startChildLoading();
364
+ this._revalidateInProgressToken = token;
365
+ try {
366
+ const response = yield productLoader.postValidate(correctDefaultsOnCatalogueParams(this.prodParams), {
367
+ selOptions: configuration._internal.getApiSelection(),
368
+ knownFeatureCodes: configuration.rawFeatures.map((f) => f.code),
369
+ });
370
+ // The revalidateInProgressToken is used to know if some other revalidate
371
+ // call has happened after this call, thereby making this call obsolete.
372
+ // This is a bit crude in that it does not actually cancel previous validate
373
+ // calls, but this is fine because 1. it is hard to cancel a call, especially
374
+ // if you wanna have clear code 2. the actual calls are small anyhow 3. most
375
+ // of all, the heavy work happens on the server, and that work will not be
376
+ // cancelled even if we would cancel the call.
377
+ if (this._revalidateInProgressToken !== token) {
378
+ return false;
379
+ }
380
+ // After a successful validate-call we will always assume there
381
+ // is a change. It would be possible to compare relevant parts
382
+ // of productData, consider the result of setApiSelection and
383
+ // syndAndLoad, however the code comparing productData would be fragile
384
+ // and likely to break if new data-fields were added.
385
+ if (this._destroyed) {
386
+ return false;
387
+ }
388
+ const { productData, rootFeatureRefs, features, notes } = response;
389
+ if (notes !== undefined) {
390
+ this.addNotes(notes.values());
391
+ }
392
+ const pricesUpdated = !comparePricesObjects(this.prices, productData.partsData.prices);
393
+ this._rawProductData = productData;
394
+ configuration._internal.addRawFeatures(features, true);
395
+ if (rootFeatureRefs !== undefined) {
396
+ configuration._internal.populateFeatures(rootFeatureRefs);
397
+ }
398
+ if (pricesUpdated) {
399
+ this._configuration._internal._freshRefDescendants();
400
+ this._configuration = CfgProductConfiguration._makeNewRefFrom(this._configuration._internal);
401
+ }
402
+ yield configuration._internal.setApiSelection(productData.partsData.selOptions || [], false);
403
+ yield this._syncAndLoadAdditionalProducts(productLoader, undefined);
404
+ if (this._destroyed) {
405
+ return false;
406
+ }
407
+ yield this._notifyAllOfChange(bubbleMode, committed);
408
+ return true;
409
+ }
410
+ catch (e) {
411
+ throw augmentErrorMessage(e, `Validate product configuration request (${this.prodParams.partNumber}) failure`);
412
+ }
413
+ finally {
414
+ this.loadingObservable.stopChildLoading(token);
415
+ }
416
+ });
417
+ /**
418
+ * Based on this configuration find what additional products should be shown and not, unload
419
+ * (i.e. destroy) those that should no longer be shown, load the new ones.
420
+ */
421
+ this._syncAndLoadAdditionalProducts = (productLoaderForGroupedLoad, initialProductConfiguration) => __awaiter(this, void 0, void 0, function* () {
422
+ const { _productLoaderRaw: productLoaderRaw, rawProductData: productData, configuration, additionalProducts: currentAdditionalProducts, } = this;
423
+ const additionalProductRefs = [
424
+ ...(productData.additionalProductRefs || []),
425
+ ...collectAdditionalProductRefs(configuration),
426
+ ]
427
+ .reduce((a, c) => {
428
+ if (a.every((p) => !isSameProductRef(p, c))) {
429
+ a.push(c);
430
+ }
431
+ return a;
432
+ }, [])
433
+ .map((prodRef, originalIndex) => ({
434
+ prodRef,
435
+ originalIndex,
436
+ }));
437
+ let change = false;
438
+ let i = currentAdditionalProducts.length;
439
+ while (i--) {
440
+ const currentAdditionalProduct = currentAdditionalProducts[i];
441
+ const j = additionalProductRefs.findIndex((p) => {
442
+ const prodRef = p.prodRef;
443
+ return (prodRef.refKey === currentAdditionalProduct.refKey &&
444
+ prodRef.partNumber === currentAdditionalProduct.partNumber &&
445
+ isSameCatalogueParams(prodRef.catId, currentAdditionalProduct.catId));
446
+ });
447
+ if (j === -1) {
448
+ currentAdditionalProduct.destroy();
449
+ currentAdditionalProducts.splice(i, 1);
450
+ change = true;
451
+ }
452
+ else {
453
+ currentAdditionalProduct._internal._updateAdditionalProdRef(additionalProductRefs[j].prodRef);
454
+ additionalProductRefs.splice(j, 1);
455
+ }
456
+ }
457
+ const token = this.loadingObservable.startChildLoading();
458
+ try {
459
+ if (additionalProductRefs.length !== 0) {
460
+ change = true;
461
+ }
462
+ const newAdditionalProducts = yield Promise.all(additionalProductRefs.map((p) => (() => __awaiter(this, void 0, void 0, function* () {
463
+ var _c;
464
+ const additionalProductRef = p.prodRef;
465
+ const refKey = additionalProductRef.refKey;
466
+ const additionalProductInitialProductConfiguration = (_c = initialProductConfiguration === null || initialProductConfiguration === void 0 ? void 0 : initialProductConfiguration.additionalProducts) === null || _c === void 0 ? void 0 : _c.find((aP) => refKey === aP.refKey);
467
+ if (initialProductConfiguration !== undefined &&
468
+ additionalProductInitialProductConfiguration === undefined) {
469
+ console.warn(`Did not find initial product configuration for additional product with refKey ${refKey}`);
470
+ }
471
+ return {
472
+ originalIndex: p.originalIndex,
473
+ 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, additionalProductInitialProductConfiguration)),
474
+ };
475
+ }))()));
476
+ if (this._destroyed) {
477
+ return change;
478
+ }
479
+ for (const newAdditionalProduct of newAdditionalProducts) {
480
+ currentAdditionalProducts.splice(newAdditionalProduct.originalIndex, 0, newAdditionalProduct.product);
481
+ }
482
+ return change;
483
+ }
484
+ finally {
485
+ this.loadingObservable.stopChildLoading(token);
486
+ }
487
+ });
488
+ this.root = root !== null && root !== void 0 ? root : this;
489
+ 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 }));
490
+ this._selected = optional ? selected : undefined;
491
+ this.isAdditionalProduct = _additionalProductRef !== undefined;
492
+ if (notes !== undefined) {
493
+ this.addNotes(notes);
494
+ }
495
+ this._configuration = CfgProductConfiguration.make(initSuccess, initFail, rootFeatureRefs, rawFeatures, apiSelection, this, this.root);
496
+ }
497
+ get selected() {
498
+ return this._selected !== false;
499
+ }
500
+ /**
501
+ * Please note that cloning an additional product will make the clone believe is is
502
+ * an additional product, even if it has no parent and root.
503
+ * Providing the parent and root of what you clone as arguments is unwise as it will
504
+ * make changes you do on the clone be propagated up to the original non-clone root product.
505
+ */
506
+ clone(parent, root) {
507
+ return __awaiter(this, void 0, void 0, function* () {
508
+ const product = yield new Promise((initSuccess, initFail) => {
509
+ var _a;
510
+ const p = new _CfgProductInternal(() => {
511
+ initSuccess(p);
512
+ }, initFail, this._productLoaderRaw, this.prodParams, this.settings, this.optional, this.selected, this._configuration.rootFeatureRefs, this._configuration.rawFeatures, this._notes.values(), this.uuid, this._rawUnit, this._rawProductData, this.configuration._internal.getApiSelection(), new AggregatedLoadingObservable(), parent, root, this._additionalProductRef, (_a = this._syncGroupHandler) === null || _a === void 0 ? void 0 : _a.clone());
513
+ });
514
+ for (const additionalProduct of this.additionalProducts) {
515
+ product.additionalProducts.push(CfgProduct._makeNewRefFrom(yield additionalProduct._internal.clone(product, root || product)));
516
+ }
517
+ return product;
518
+ });
519
+ }
520
+ /**
521
+ * Internal use. Used when this product is an additional product, and
522
+ * changing a parent product has made the settings for this product
523
+ * change.
524
+ */
525
+ _updateAdditionalProdRef(p) {
526
+ this._additionalProductRef = p;
527
+ if (p.optional !== this.optional) {
528
+ this._selected = p.optional ? false : undefined;
529
+ }
530
+ }
531
+ /**
532
+ * Return a DtoNode using noteRef as a key.
533
+ * Throws an error if no note is found.
534
+ */
535
+ getNote(noteRef) {
536
+ const note = this._notes.get(noteRef);
537
+ if (note === undefined) {
538
+ throw new Error(`Note with noteRef ${noteRef} not found.`);
539
+ }
540
+ return note;
541
+ }
542
+ /**
543
+ * noteRefs is a list of keys coming from CfgOption, CfgFeature or CfgProduct.
544
+ * The keys are used to get a DtoNote[] from notes at CfgProduct.
545
+ */
546
+ getNotes(noteRefs) {
547
+ return noteRefs.map((noteRef) => this.getNote(noteRef));
548
+ }
549
+ addNotes(notes) {
550
+ for (const note of notes) {
551
+ const code = note.code;
552
+ if (!code) {
553
+ throw new Error("Note with no code");
554
+ }
555
+ this._notes.set(code, note);
556
+ }
557
+ }
558
+ get notes() {
559
+ var _a;
560
+ return this.getNotes((_a = this.rawProductData.noteRefs) !== null && _a !== void 0 ? _a : []);
561
+ }
562
+ get miscFiles() {
563
+ var _a;
564
+ return (_a = this._rawProductData.miscFiles) !== null && _a !== void 0 ? _a : [];
565
+ }
566
+ get hasRootFeaturesChanged() {
567
+ return (this._configuration._internal.hasRootFeaturesChanged ||
568
+ this.additionalProducts.some((p) => p._internal.hasRootFeaturesChanged));
569
+ }
570
+ get description() {
571
+ var _a, _b;
572
+ return (_b = (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.refDescription) !== null && _b !== void 0 ? _b : this._rawProductData.description;
573
+ }
574
+ get rootNodeSources() {
575
+ return this._rawProductData.models;
576
+ }
577
+ get mtrlApplications() {
578
+ return this._rawProductData.mtrlApplications;
579
+ }
580
+ get currency() {
581
+ return this._rawProductData.partsData.currency;
582
+ }
583
+ get fractionDigits() {
584
+ return this._rawProductData.partsData.rounding || 0;
585
+ }
586
+ get prices() {
587
+ return this._rawProductData.partsData.prices;
588
+ }
589
+ get measureDefinitions() {
590
+ var _a;
591
+ if (this._measureDefinitions === undefined) {
592
+ this._measureDefinitions = ((_a = this._rawProductData.measurements) !== null && _a !== void 0 ? _a : [])
593
+ .map((m) => CfgMeasureDefinition.make(m))
594
+ .filter((m) => m !== undefined);
595
+ }
596
+ return this._measureDefinitions;
597
+ }
598
+ get refKey() {
599
+ var _a;
600
+ return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.refKey;
601
+ }
602
+ get transform() {
603
+ var _a;
604
+ return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.transform;
605
+ }
606
+ get anchor() {
607
+ var _a;
608
+ return (_a = this._additionalProductRef) === null || _a === void 0 ? void 0 : _a.anchor;
609
+ }
610
+ /** @throws an error if the actual unit sent by the server was not a LengthUnit */
611
+ get unit() {
612
+ if (this._unit === undefined) {
613
+ this._unit = toLengthUnit(this._rawUnit);
614
+ }
615
+ return this._unit;
616
+ }
617
+ get aggregatedPrice() {
618
+ const { currency, fractionDigits, rawProductData } = this;
619
+ const { partsData } = rawProductData;
620
+ let { listPrice, basePrice } = partsData;
621
+ if (this._selected === false) {
622
+ return { basePrice: 0, listPrice: 0, currency, fractionDigits };
623
+ }
624
+ for (const additionalProduct of this.additionalProducts || []) {
625
+ const { basePrice: additionalBasePrice, listPrice: additionalListPrice, currency: additionalCurrency, fractionDigits: additionalFractionDigits, } = additionalProduct.aggregatedPrice;
626
+ basePrice += additionalBasePrice;
627
+ listPrice += additionalListPrice;
628
+ if (currency !== additionalCurrency) {
629
+ // This should not be possible
630
+ // The server shouldn't return additional products with different currency from their parent
631
+ 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}`);
632
+ }
633
+ if (fractionDigits !== additionalFractionDigits) {
634
+ // This should not be possible
635
+ // The server shouldn't return additional products with different fraction digits from their parent
636
+ 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}`);
637
+ }
638
+ }
639
+ return { basePrice, listPrice, currency, fractionDigits };
640
+ }
641
+ get optional() {
642
+ return this._selected !== undefined;
643
+ }
644
+ setSelected(selected, bubbleMode, interactive) {
645
+ return __awaiter(this, void 0, void 0, function* () {
646
+ if (!this.optional) {
647
+ console.warn("This product is not optional. Nothing will happen");
648
+ return false;
649
+ }
650
+ if (this._selected === selected) {
651
+ return false;
652
+ }
653
+ // Vitally important that this happens before the call to reset,
654
+ // so that the reset won't cause infinite loops
655
+ this._selected = selected;
656
+ if (interactive) {
657
+ if (selected) {
658
+ const syncGroupHandler = this.syncGroupHandler;
659
+ if (syncGroupHandler !== undefined) {
660
+ yield syncGroupHandler.init(this.root, wrapWithCache(this._productLoaderRaw));
661
+ }
662
+ }
663
+ else {
664
+ yield this.reset();
665
+ // In case a passed initial configuration has made it reset to selected
666
+ this._selected = selected;
667
+ }
668
+ }
669
+ yield this._notifyAllOfChange(bubbleMode, true);
670
+ return true;
671
+ });
672
+ }
673
+ get configuration() {
674
+ return this._configuration;
675
+ }
676
+ get rawProductData() {
677
+ return this._rawProductData;
678
+ }
679
+ /**
680
+ * Please note that this relates to the visibility in the Configuration tree.
681
+ * It does not affect the visibility of anything in the 3D view at all.
682
+ */
683
+ get visibleIfAdditionalProduct() {
684
+ return this.rawProductData.hideIfAdditionalProduct !== true;
685
+ }
686
+ /**
687
+ * Please note that this relates to the visibility in the Configuration tree.
688
+ * It does not affect the visibility of anything in the 3D view at all.
689
+ */
690
+ get visibleIfMainProduct() {
691
+ return this.rawProductData.hideIfMainProduct !== true;
692
+ }
693
+ /**
694
+ * Please note that this relates to the visibility in the Configuration tree.
695
+ * It does not affect the visibility of anything in the 3D view at all.
696
+ */
697
+ get visible() {
698
+ return this.isAdditionalProduct
699
+ ? this.visibleIfAdditionalProduct
700
+ : this.visibleIfMainProduct;
701
+ }
702
+ get syncGroupHandler() {
703
+ return this.root._syncGroupHandler;
704
+ }
705
+ get syncGroupsVerboseLogging() {
706
+ var _a, _b;
707
+ return (_b = (_a = this.syncGroupHandler) === null || _a === void 0 ? void 0 : _a.verboseLogging) !== null && _b !== void 0 ? _b : false;
708
+ }
709
+ /**
710
+ * Set to true to get verbose sync state changes logged to the console.
711
+ */
712
+ set syncGroupsVerboseLogging(v) {
713
+ const syncGroupHandler = this.syncGroupHandler;
714
+ if (syncGroupHandler === undefined) {
715
+ throw new Error("No syncGroupHandler, so can not change log verbosity");
716
+ }
717
+ syncGroupHandler.verboseLogging = v;
718
+ }
719
+ }
720
+ _CfgProductInternal.make = (productLoaderRaw, productLoaderForGroupedLoad, // Used when instantiating the current product
721
+ prodParams, settings, optional, loadingObservable, parent, root, additionalProductRef, initialProductConfiguration) => __awaiter(void 0, void 0, void 0, function* () {
722
+ // Wrap with cache will make getProduct for this function call use the same server call
723
+ // for the same product with the same params. Not retained for future calls, only used
724
+ // at this initial load.
725
+ productLoaderForGroupedLoad =
726
+ productLoaderForGroupedLoad || wrapWithCache(productLoaderRaw);
727
+ let syncGroupHandler = undefined;
728
+ // No root means we are root. We only create SyncGroupsHandler if this is the root product
729
+ if (root === undefined) {
730
+ let initialSyncGroupsState = undefined;
731
+ // DtoProductConf supports containing the sync group state, but the old
732
+ // DtoAdditionalProductConfiguration does not
733
+ if (initialProductConfiguration !== undefined &&
734
+ isProductConf(initialProductConfiguration)) {
735
+ initialSyncGroupsState = initialProductConfiguration.syncGroupState;
736
+ }
737
+ syncGroupHandler = SyncGroupsHandler.make(settings.syncGroupsApplyMode, loadingObservable, initialSyncGroupsState);
738
+ }
739
+ try {
740
+ const defaultCorrectedProdParams = correctDefaultsOnCatalogueParams(prodParams);
741
+ let initialProductConfigurationV1 = undefined;
742
+ if (initialProductConfiguration !== undefined) {
743
+ if (isProductConf(initialProductConfiguration)) {
744
+ initialProductConfigurationV1 = convertDtoProductConfToV1(initialProductConfiguration);
745
+ }
746
+ else if (isAdditionalProductConfiguration(initialProductConfiguration)) {
747
+ initialProductConfigurationV1 = initialProductConfiguration;
748
+ }
749
+ }
750
+ const productResponse = yield (initialProductConfigurationV1
751
+ ? productLoaderForGroupedLoad.postValidate(defaultCorrectedProdParams, {
752
+ knownFeatureCodes: [],
753
+ selOptions: initialProductConfigurationV1.selOptions,
754
+ })
755
+ : productLoaderForGroupedLoad.getProduct(defaultCorrectedProdParams));
756
+ const { productData, rootFeatureRefs, features: rawFeatures, notes, uuid, unit, } = productResponse;
757
+ const initiallySelected = !optional || (initialProductConfigurationV1 === null || initialProductConfigurationV1 === void 0 ? void 0 : initialProductConfigurationV1.selected) === true;
758
+ const product = yield new Promise((initSuccess, initFail) => {
759
+ var _a;
760
+ const p = new _CfgProductInternal(() => {
761
+ // We absolutely do not want anyone to assign to this._configuration. So we want that field private.
762
+ // But we can not set the api selection synchronously. And the product configuration needs "this". So we use this callback.
763
+ // Feel free to find a nicer more readable solution :)
764
+ initSuccess(p);
765
+ }, initFail, productLoaderRaw, prodParams, settings, optional, initiallySelected, rootFeatureRefs !== null && rootFeatureRefs !== void 0 ? rootFeatureRefs : [], rawFeatures, notes === null || notes === void 0 ? void 0 : notes.values(), uuid, unit, productData, (_a = productData.partsData.selOptions) !== null && _a !== void 0 ? _a : [], loadingObservable, parent, root, additionalProductRef, syncGroupHandler);
766
+ });
767
+ yield product._syncAndLoadAdditionalProducts(productLoaderForGroupedLoad, initialProductConfigurationV1);
768
+ product._initialClone = yield product.clone();
769
+ if (syncGroupHandler !== undefined && !initialProductConfiguration) {
770
+ // As syncGroupHandler is only set for root product we know that we will init with root.
771
+ // If we have an initialProductConfiguration we do not run init for the syncGroups.
772
+ // The idea with an initial configuration is that the product should look as it did when
773
+ // the configuration was saved. Not running init does that. Also, the DtoProductConf
774
+ // object can contain a sync state which is then used to populate the sync state.
775
+ yield syncGroupHandler.init(product, productLoaderForGroupedLoad);
776
+ }
777
+ return product;
778
+ }
779
+ catch (e) {
780
+ throw augmentErrorMessage(e, `Load product request (${prodParams.partNumber}) failure`);
781
+ }
782
+ });
783
+ export class CfgProduct {
784
+ constructor(_internal) {
785
+ this._internal = _internal;
786
+ this.isBackedBySame = (other) => this._internal === other._internal;
787
+ /**
788
+ * Recursively marks this and descendants as destroyed so that late events are ignored
789
+ * correctly. If you destroy one shallow copy of this you destroy all.
790
+ */
791
+ this.destroy = () => this._internal.destroy();
792
+ /** Makes a clone of this. It is disconnected from the original. */
793
+ this.clone = () => __awaiter(this, void 0, void 0, function* () { return CfgProduct._makeNewRefFrom(yield this._internal.clone()); });
794
+ /**
795
+ * Only applicable when this product is optional.
796
+ * Setting this does not cause a validation call as toggling an optional additional product is
797
+ * assumed to always be legal.
798
+ */
799
+ this.setSelected = (v) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setSelected(v, CfgProductBubbleMode.ToRootAndBubbleSelected, true); });
800
+ /**
801
+ * Experimental. Additional products lacks descriptions or keys that are suitably for structure
802
+ * compare, so we use strict-order when trying to match the additional products. This makes
803
+ * this method work nicely for different products having pretty much the same child products.
804
+ */
805
+ this.structureCompare = (other, strictOrder = true, descriptionMatch = false) => this._internal.structureCompare(other._internal, strictOrder, descriptionMatch);
806
+ /**
807
+ * Experimental. Additional products lacks descriptions or keys that are suitably for try
808
+ * match, so we use strict-order when trying to match the additional products. This makes
809
+ * this method work nicely for different products having pretty much the same child products.
810
+ * This method does not propagate its selections.
811
+ * This method will cause validation calls if something change.
812
+ */
813
+ this.tryMatchSelection = (other, descriptionMatch = false // Match on case insensitive description, not code
814
+ ) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.tryMatchSelection(other._internal, descriptionMatch); });
815
+ /**
816
+ * Gets what selections has been made on the product, recursively including product
817
+ * configuration, optional products and additional products. Used when a full view of all
818
+ * selections on a product is needed, such as when doing Render or Export.
819
+ * @deprecated getDtoConf provides a newer format.
820
+ * @see getDtoConf
821
+ */
822
+ this.getApiSelection = () => convertDtoProductConfToV1(this._internal.getDtoConf(CfgProdConfParts.NoExtra), true);
823
+ /**
824
+ * Applies the configuration (selections) in the passed object onto the product recursively
825
+ * including product configuration, optional products and additional products.
826
+ * @param doValidate Makes a server side validation call. These are necessary to ensure that
827
+ * the right models are loaded.
828
+ * @deprecated setDtoConf uses a newer format.
829
+ */
830
+ this.setApiSelection = (configuration, doValidate = true) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setApiSelection(configuration, doValidate); });
831
+ /**
832
+ * A newer alternative version of getApiSelection. This returns the configuration (selections)
833
+ * on the product, recursively including product configuration, optional products and additional
834
+ * products.
835
+ * This version has the following advantages over getApiSelection:
836
+ * - The format is clearer, designed to be readable
837
+ * - Makes less assumptions about the structure in the Product being unchanging over time. In
838
+ * particular, the Feature codes are included in the data, so that changes to what Features
839
+ * are used in a Product is less likely to lead to unexpected results.
840
+ * - You can request ExtendedData, ProductParams and/or SyncGroupState to be included in the
841
+ * result. This extra data is ignored when passed back into the API, but it can be very useful
842
+ * for external applications.
843
+ * The other version (getApiSelection) has the advantage of using a format directly compatible with the API:s.
844
+ * @param include Includes extra data which is not an actual part of the configuration
845
+ */
846
+ this.getDtoConf = (include = CfgProdConfParts.NoExtra) => this._internal.getDtoConf(include);
847
+ /**
848
+ * A newer alternative version of setApiSelection.
849
+ * @param doValidate Makes a server side validation call. These are necessary to ensure that
850
+ * the right models are loaded.
851
+ */
852
+ this.setDtoConf = (configuration, doValidate = true) => __awaiter(this, void 0, void 0, function* () { return yield this._internal.setDtoConf(configuration, doValidate); });
853
+ this.listenForChange = (l) => this._internal.changeObservable.listen(l);
854
+ this.stopListenForChange = (l) => this._internal.changeObservable.stopListen(l);
855
+ this.stopAllListenForChange = () => this._internal.changeObservable.stopAllListen();
856
+ this.listenForLoading = (l) => this._internal.loadingObservable.listen(l);
857
+ this.stopListenForLoading = (l) => this._internal.loadingObservable.stopListen(l);
858
+ this.stopAllListenForLoading = () => this._internal.loadingObservable.stopAllListen();
859
+ }
860
+ static make(productLoader, prodParams, settings, initialProductConfiguration) {
861
+ return __awaiter(this, void 0, void 0, function* () {
862
+ return this._makeNewRefFrom(yield _CfgProductInternal.make(productLoader, undefined, prodParams, completeSettings(settings), false, new AggregatedLoadingObservable(), undefined, undefined, undefined, initialProductConfiguration));
863
+ });
864
+ }
865
+ /**
866
+ * Makes an object wrapping the passed object. This is not a clone method, it is a method to
867
+ * make a new outer reference. Like a shallow copy. We use this to help frameworks that are
868
+ * build around using equals to detect change.
869
+ */
870
+ static _makeNewRefFrom(source) {
871
+ return new this(source);
872
+ }
873
+ /**
874
+ * A client side only key that should uniquely identify this product amongst other additional
875
+ * products.
876
+ */
877
+ get key() {
878
+ return this._internal.key;
879
+ }
880
+ /**
881
+ * Only used when this product is in additional product.
882
+ * As a product can have multiple instances of the same additional product this key exists.
883
+ * It will be unique amongst child products, but not globally unique.
884
+ */
885
+ get refKey() {
886
+ return this._internal.refKey;
887
+ }
888
+ get notes() {
889
+ return this._internal.notes;
890
+ }
891
+ get miscFiles() {
892
+ return this._internal.miscFiles;
893
+ }
894
+ get prodParams() {
895
+ return this._internal.prodParams;
896
+ }
897
+ get lang() {
898
+ return this._internal.prodParams.lang;
899
+ }
900
+ get catId() {
901
+ const { cid, enterprise, prdCat, prdCatVersion, priceList, vendor } = this._internal.prodParams;
902
+ return {
903
+ cid,
904
+ enterprise,
905
+ prdCat,
906
+ prdCatVersion,
907
+ priceList,
908
+ vendor,
909
+ };
910
+ }
911
+ get partNumber() {
912
+ return this._internal.prodParams.partNumber;
913
+ }
914
+ get isAdditionalProduct() {
915
+ return this._internal.isAdditionalProduct;
916
+ }
917
+ /** Only used when this product is an additional product. Root products are never optional. */
918
+ get optional() {
919
+ return this._internal.optional;
920
+ }
921
+ /**
922
+ * Only applicable when this product is optional. If this product is not optional this is
923
+ * always true.
924
+ */
925
+ get selected() {
926
+ return this._internal.selected;
927
+ }
928
+ /**
929
+ * Please note that this relates to the visibility in the Configuration tree.
930
+ * It does not affect the visibility of anything in the 3D view at all.
931
+ * Visibility affects the Configuration for this Product, but any Additional Products
932
+ * will not be affected.
933
+ */
934
+ get visible() {
935
+ return this._internal.visible;
936
+ }
937
+ // A similar text to the one below exists in global-message-managers.md and should be kept in sync.
938
+ /**
939
+ * Functional selection is a Catalogues feature where selecting Options on Features result in that you
940
+ * "jump" to another Product as a result of the Validate call. You normally do not notice that a functional
941
+ * selection has occurred except for the styleNr changing. Functional selection can change which Features
942
+ * from the original product call are used as root Features. This can in turn affect if serialized
943
+ * configuration can be applied or not.
944
+ *
945
+ * The SDK can currently only apply serialized configuration if the list of root Features has not changed.
946
+ * For this reason, when functional selection has happened, extracting data for external systems might work
947
+ * well, but reapplying back into Stage will probably fail.
948
+ */
949
+ get hasRootFeaturesChanged() {
950
+ return this._internal.hasRootFeaturesChanged;
951
+ }
952
+ get rawProductData() {
953
+ return this._internal.rawProductData;
954
+ }
955
+ get uuid() {
956
+ return this._internal.uuid;
957
+ }
958
+ get unit() {
959
+ return this._internal.unit;
960
+ }
961
+ get sku() {
962
+ return this._internal.rawProductData.sku;
963
+ }
964
+ get styleNr() {
965
+ return this._internal.rawProductData.partsData.styleNr;
966
+ }
967
+ /** An URL. */
968
+ get preview() {
969
+ return this._internal.rawProductData.navImage;
970
+ }
971
+ get description() {
972
+ return this._internal.description;
973
+ }
974
+ get additionalProducts() {
975
+ return this._internal.additionalProducts;
976
+ }
977
+ get configuration() {
978
+ return this._internal.configuration;
979
+ }
980
+ get transform() {
981
+ return this._internal.transform;
982
+ }
983
+ get currency() {
984
+ return this._internal.currency;
985
+ }
986
+ /**
987
+ * If positive the number of fraction digits.
988
+ * If negative rounding (essentially the number of zeros to the right)
989
+ */
990
+ get fractionDigits() {
991
+ return this._internal.fractionDigits;
992
+ }
993
+ get aggregatedPrice() {
994
+ return this._internal.aggregatedPrice;
995
+ }
996
+ }