@controleonline/ui-crm 1.0.42 → 1.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/.github/workflows/integration-source-gate.yml +82 -0
  2. package/.github/workflows/manager-worker.yml +7 -155
  3. package/.github/workflows/publish-npm.yml +73 -22
  4. package/AGENTS.md +2 -0
  5. package/package.json +2 -2
  6. package/src/react/pages/crm/hooks/useCrmData.js +23 -17
  7. package/src/react/pages/proposals/CreateProposalsModal.js +1 -0
  8. package/src/react/pages/proposals/index.js +14 -33
  9. package/src/react/pages/settings/GeneralSettings.styles.js +2 -0
  10. package/src/react/pages/settings/sections/LoyaltyProductPicker.js +58 -145
  11. package/src/react/pages/settings/sections/LoyaltySection.js +35 -9
  12. package/src/react/pages/settings/sections/MapsFranchisePreview.js +102 -0
  13. package/src/react/pages/settings/sections/MapsMapasControls.js +262 -0
  14. package/src/react/pages/settings/sections/MapsSection.js +71 -247
  15. package/src/react/pages/settings/sections/loyaltyProductCompany.js +57 -0
  16. package/src/react/pages/settings/sections/mapsSectionHelpers.js +137 -0
  17. package/src/react/pages/settings/sections/shop/ShopFranchiseLocatorSection.js +7 -28
  18. package/src/react/pages/settings/sections/shop/ShopLoyaltySection.js +54 -8
  19. package/src/react/pages/settings/sections/shop/shopSettingsShared.js +32 -11
  20. package/src/react/utils/clientDetailsNavigation.js +56 -0
  21. package/src/react/utils/clientSellerVisibility.js +60 -0
  22. package/src/react/utils/proposalProductSelection.js +103 -13
  23. package/src/react/utils/proposalStatus.js +160 -0
  24. package/src/tests/browser/crm/create-proposal-product-category-filter.spec.js +25 -0
  25. package/src/tests/browser/manager/general-settings-maps.spec.js +173 -347
  26. package/src/tests/react/pages/settings/sections/loyaltyProductCompany.test.js +41 -0
  27. package/src/tests/react/pages/settings/sections/mapsSectionHelpers.test.js +38 -0
  28. package/src/tests/react/utils/clientDetailsNavigation.test.js +98 -0
  29. package/src/tests/react/utils/clientSellerVisibility.test.js +74 -0
  30. package/src/tests/react/utils/proposalProductSelection.test.js +57 -1
  31. package/src/tests/react/utils/proposalStatus.test.mjs +77 -0
@@ -0,0 +1,137 @@
1
+ /*
2
+ * @agents Pure helpers for General Settings → Mapas (#360).
3
+ * Coordinate parsing, static map URLs and shop primary-entry labels.
4
+ */
5
+ import {
6
+ SHOP_HOME_OPTION_FRANCHISE_LOCATOR,
7
+ SHOP_HOME_OPTION_SALES,
8
+ } from '@controleonline/ui-common/src/react/utils/shopConfig';
9
+
10
+ export const PRIMARY_ENTRY_LABELS = {
11
+ [SHOP_HOME_OPTION_SALES]: 'Vitrine do shop',
12
+ [SHOP_HOME_OPTION_FRANCHISE_LOCATOR]: 'Mapa das franquias',
13
+ };
14
+
15
+ export const parseCoord = value => {
16
+ if (value === null || value === undefined || value === '') {
17
+ return null;
18
+ }
19
+ const n = Number(value);
20
+ if (!Number.isFinite(n) || Math.abs(n) < 0.000001) {
21
+ return null;
22
+ }
23
+ return n;
24
+ };
25
+
26
+ export const resolveAddressCoords = address => {
27
+ const lat = parseCoord(
28
+ address?.latitude ??
29
+ address?.lat ??
30
+ address?.map?.latitude ??
31
+ address?.map?.lat ??
32
+ address?.geo?.latitude,
33
+ );
34
+ const lng = parseCoord(
35
+ address?.longitude ??
36
+ address?.lng ??
37
+ address?.lon ??
38
+ address?.map?.longitude ??
39
+ address?.map?.lng ??
40
+ address?.map?.lon ??
41
+ address?.geo?.longitude,
42
+ );
43
+ if (lat === null || lng === null) {
44
+ return null;
45
+ }
46
+ return {lat, lng};
47
+ };
48
+
49
+ export const buildStaticMapUrl = ({apiKey, markers, size = '640x320'}) => {
50
+ if (!apiKey || !Array.isArray(markers) || markers.length === 0) {
51
+ return null;
52
+ }
53
+ const markerParams = markers
54
+ .slice(0, 40)
55
+ .map(
56
+ m =>
57
+ `markers=color:red%7C${encodeURIComponent(`${m.lat},${m.lng}`)}`,
58
+ )
59
+ .join('&');
60
+ const center = markers[0];
61
+ return `https://maps.googleapis.com/maps/api/staticmap?size=${size}&maptype=roadmap&center=${center.lat},${center.lng}&zoom=${markers.length === 1 ? 14 : 11}&${markerParams}&key=${encodeURIComponent(apiKey)}`;
62
+ };
63
+
64
+ /** Fallback without Google key — OpenStreetMap static (multi-marker). */
65
+ export const buildOsmStaticMapUrl = (markers, size = '640x320') => {
66
+ if (!Array.isArray(markers) || markers.length === 0) {
67
+ return null;
68
+ }
69
+ const center = markers[0];
70
+ const zoom = markers.length === 1 ? 14 : 11;
71
+ const markerParams = markers
72
+ .slice(0, 40)
73
+ .map(m => `markers=${m.lat},${m.lng},red-pushpin`)
74
+ .join('&');
75
+ return `https://staticmap.openstreetmap.de/staticmap.php?center=${center.lat},${center.lng}&zoom=${zoom}&size=${size}&maptype=mapnik&${markerParams}`;
76
+ };
77
+
78
+ /** Interactive Leaflet map HTML for web iframe (no API key). */
79
+ export const buildLeafletMapHtml = markers => {
80
+ if (!Array.isArray(markers) || markers.length === 0) {
81
+ return '';
82
+ }
83
+ const points = markers.slice(0, 40).map(m => ({
84
+ lat: Number(m.lat),
85
+ lng: Number(m.lng),
86
+ label: String(m.companyLabel || m.label || 'Franquia'),
87
+ }));
88
+ const center = points[0];
89
+ const markersJs = points
90
+ .map(
91
+ p =>
92
+ `L.marker([${p.lat}, ${p.lng}]).addTo(map).bindPopup(${JSON.stringify(
93
+ p.label,
94
+ )});`,
95
+ )
96
+ .join('\n');
97
+ const fitJs =
98
+ points.length > 1
99
+ ? `map.fitBounds([${points
100
+ .map(p => `[${p.lat}, ${p.lng}]`)
101
+ .join(', ')}], {padding: [28, 28]});`
102
+ : '';
103
+ return `<!DOCTYPE html>
104
+ <html>
105
+ <head>
106
+ <meta charset="utf-8"/>
107
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
108
+ <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
109
+ <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
110
+ <style>
111
+ html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden;}
112
+ #map{position:absolute;inset:0;width:100%;height:100%;}
113
+ .leaflet-container{width:100%!important;height:100%!important;font:12px/1.4 system-ui,sans-serif;}
114
+ </style>
115
+ </head>
116
+ <body style="position:relative;width:100%;height:100%;">
117
+ <div id="map"></div>
118
+ <script>
119
+ var map = L.map('map').setView([${center.lat}, ${center.lng}], ${points.length === 1 ? 14 : 11});
120
+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
121
+ maxZoom: 19,
122
+ attribution: '&copy; OpenStreetMap'
123
+ }).addTo(map);
124
+ ${markersJs}
125
+ ${fitJs}
126
+ function resizeMap(){ map.invalidateSize(true); }
127
+ setTimeout(resizeMap, 0);
128
+ setTimeout(resizeMap, 100);
129
+ setTimeout(resizeMap, 400);
130
+ window.addEventListener('resize', resizeMap);
131
+ if (typeof ResizeObserver !== 'undefined') {
132
+ new ResizeObserver(resizeMap).observe(document.getElementById('map'));
133
+ }
134
+ </script>
135
+ </body>
136
+ </html>`;
137
+ };
@@ -1,26 +1,9 @@
1
- /*
2
- * @agents Franchise locator visibility (companies + addresses) for shop general settings.
3
- * Persist only on explicit user toggles — never auto-save prunes after refresh.
4
- */
5
1
  import React, {useCallback, useEffect, useMemo, useState} from 'react';
6
2
  import {useNavigation} from '@react-navigation/native';
7
- import {
8
- ActivityIndicator,
9
- Text,
10
- TextInput,
11
- TouchableOpacity,
12
- View,
13
- } from 'react-native';
3
+ import {ActivityIndicator, Text, TextInput, TouchableOpacity, View} from 'react-native';
14
4
  import Icon from 'react-native-vector-icons/MaterialIcons';
15
- import {
16
- fetchAllShopFranchiseDirectory,
17
- resolveFranchiseAddressCoords,
18
- } from '@controleonline/ui-common/src/react/utils/shopFranchises';
19
- import {
20
- normalizeShopEntityId,
21
- SHOP_FRANCHISE_VISIBLE_ADDRESS_IDS_CONFIG_KEY,
22
- SHOP_FRANCHISE_VISIBLE_COMPANY_IDS_CONFIG_KEY,
23
- } from '@controleonline/ui-common/src/react/utils/shopConfig';
5
+ import {fetchAllShopFranchiseDirectory, resolveFranchiseAddressCoords} from '@controleonline/ui-common/src/react/utils/shopFranchises';
6
+ import {normalizeShopEntityId, SHOP_FRANCHISE_VISIBLE_ADDRESS_IDS_CONFIG_KEY, SHOP_FRANCHISE_VISIBLE_COMPANY_IDS_CONFIG_KEY} from '@controleonline/ui-common/src/react/utils/shopConfig';
24
7
  import {
25
8
  buildFranchiseAddressesById,
26
9
  buildFranchiseCompaniesById,
@@ -47,7 +30,6 @@ const ShopFranchiseLocatorSection = ({
47
30
  saveConfigs,
48
31
  themePalette,
49
32
  globalStyles,
50
- onVisibilityChange,
51
33
  }) => {
52
34
  const navigation = useNavigation();
53
35
  const [visibleFranchiseCompanyIds, setVisibleFranchiseCompanyIds] = useState([]);
@@ -194,15 +176,12 @@ const ShopFranchiseLocatorSection = ({
194
176
  (nextCompanyIds, nextAddressIds) => {
195
177
  setVisibleFranchiseCompanyIds(nextCompanyIds);
196
178
  setVisibleFranchiseAddressIds(nextAddressIds);
197
- if (typeof onVisibilityChange === 'function') {
198
- onVisibilityChange(nextCompanyIds, nextAddressIds);
199
- }
200
179
  return saveConfigs({
201
180
  [SHOP_FRANCHISE_VISIBLE_COMPANY_IDS_CONFIG_KEY]: nextCompanyIds,
202
181
  [SHOP_FRANCHISE_VISIBLE_ADDRESS_IDS_CONFIG_KEY]: nextAddressIds,
203
182
  });
204
183
  },
205
- [onVisibilityChange, saveConfigs],
184
+ [saveConfigs],
206
185
  );
207
186
 
208
187
  const companyHasMapCoords = useCallback(company => {
@@ -309,8 +288,8 @@ const ShopFranchiseLocatorSection = ({
309
288
  );
310
289
 
311
290
  return (
312
- <>
313
- <View style={localStyles.fieldBlock} testID="maps-franchise-locator">
291
+ <View testID="maps-franchise-locator">
292
+ <View style={localStyles.fieldBlock}>
314
293
  <Text style={localStyles.fieldLabel}>Franquias exibidas no localizador</Text>
315
294
  <Text style={localStyles.helperText}>
316
295
  Selecione quais empresas vinculadas como franquia podem aparecer no mapa do shop.
@@ -519,7 +498,7 @@ const ShopFranchiseLocatorSection = ({
519
498
  selectionMeta={() => 'Franquia liberada para o localizador'}
520
499
  styles={localStyles}
521
500
  />
522
- </>
501
+ </View>
523
502
  );
524
503
  };
525
504
 
@@ -29,6 +29,7 @@ import {
29
29
  SelectionModal,
30
30
  resolveProductLabel,
31
31
  resolveProductMeta,
32
+ resolveProductMetaParts,
32
33
  useShopProductBrowser,
33
34
  useShopProductSearch,
34
35
  } from './shopSettingsShared';
@@ -292,11 +293,26 @@ const ShopLoyaltySection = ({
292
293
  onPress={() => toggleLoyaltyProduct(product)}>
293
294
  <Icon name="remove-circle-outline" size={20} color={themePalette.iconDanger} />
294
295
  <View style={localStyles.printerCopy}>
295
- <Text style={localStyles.printerName}>{resolveProductLabel(product)}</Text>
296
- <Text style={localStyles.printerDevice}>
297
- {resolveProductMeta(product) || 'Toque para remover'}
296
+ <Text style={localStyles.printerName} numberOfLines={2}>
297
+ {resolveProductLabel(product)}
298
+ </Text>
299
+ <Text style={localStyles.printerDevice} numberOfLines={1}>
300
+ {resolveProductMetaParts(product).metaLine ||
301
+ resolveProductMetaParts(product).sku ||
302
+ 'Toque para remover'}
298
303
  </Text>
299
304
  </View>
305
+ {!!resolveProductMetaParts(product).priceLabel && (
306
+ <Text
307
+ style={{
308
+ fontSize: 13,
309
+ fontWeight: '700',
310
+ color: themePalette.iconSuccess || themePalette.success,
311
+ marginLeft: 8,
312
+ }}>
313
+ {resolveProductMetaParts(product).priceLabel}
314
+ </Text>
315
+ )}
300
316
  </TouchableOpacity>
301
317
  );
302
318
  })}
@@ -310,11 +326,26 @@ const ShopLoyaltySection = ({
310
326
  onPress={() => toggleLoyaltyProduct(product)}>
311
327
  <Icon name="inventory-2" size={20} color={themePalette.cardIconColor} />
312
328
  <View style={localStyles.printerCopy}>
313
- <Text style={localStyles.printerName}>{resolveProductLabel(product)}</Text>
314
- <Text style={localStyles.printerDevice}>
315
- {resolveProductMeta(product) || 'Toque para incluir'}
329
+ <Text style={localStyles.printerName} numberOfLines={2}>
330
+ {resolveProductLabel(product)}
331
+ </Text>
332
+ <Text style={localStyles.printerDevice} numberOfLines={1}>
333
+ {resolveProductMetaParts(product).metaLine ||
334
+ resolveProductMetaParts(product).sku ||
335
+ 'Toque para incluir'}
316
336
  </Text>
317
337
  </View>
338
+ {!!resolveProductMetaParts(product).priceLabel && (
339
+ <Text
340
+ style={{
341
+ fontSize: 13,
342
+ fontWeight: '700',
343
+ color: themePalette.iconSuccess || themePalette.success,
344
+ marginLeft: 8,
345
+ }}>
346
+ {resolveProductMetaParts(product).priceLabel}
347
+ </Text>
348
+ )}
318
349
  </TouchableOpacity>
319
350
  );
320
351
  })}
@@ -351,11 +382,26 @@ const ShopLoyaltySection = ({
351
382
  onPress={clearGiftProduct}>
352
383
  <Icon name="remove-circle-outline" size={20} color={themePalette.iconDanger} />
353
384
  <View style={localStyles.printerCopy}>
354
- <Text style={localStyles.printerName}>
385
+ <Text style={localStyles.printerName} numberOfLines={2}>
355
386
  {resolveProductLabel(selectedGiftProduct)}
356
387
  </Text>
357
- <Text style={localStyles.printerDevice}>Toque para limpar</Text>
388
+ <Text style={localStyles.printerDevice} numberOfLines={1}>
389
+ {resolveProductMetaParts(selectedGiftProduct).metaLine ||
390
+ resolveProductMetaParts(selectedGiftProduct).sku ||
391
+ 'Toque para limpar'}
392
+ </Text>
358
393
  </View>
394
+ {!!resolveProductMetaParts(selectedGiftProduct).priceLabel && (
395
+ <Text
396
+ style={{
397
+ fontSize: 13,
398
+ fontWeight: '700',
399
+ color: themePalette.iconSuccess || themePalette.success,
400
+ marginLeft: 8,
401
+ }}>
402
+ {resolveProductMetaParts(selectedGiftProduct).priceLabel}
403
+ </Text>
404
+ )}
359
405
  </TouchableOpacity>
360
406
  ) : null}
361
407
  <View style={localStyles.printerList}>
@@ -29,16 +29,25 @@ export const resolveProductLabel = product => {
29
29
  );
30
30
  };
31
31
 
32
- export const resolveProductMeta = product => {
32
+ export const resolveProductMetaParts = product => {
33
33
  const sku = String(product?.sku || '').trim();
34
34
  const price = Number(product?.price || 0);
35
- const priceLabel = Number.isFinite(price)
36
- ? `R$ ${price.toFixed(2).replace('.', ',')}`
37
- : '';
35
+ const priceLabel =
36
+ Number.isFinite(price) && price > 0
37
+ ? `R$ ${price.toFixed(2).replace('.', ',')}`
38
+ : '';
38
39
 
39
- return [sku ? `SKU ${sku}` : null, price > 0 ? priceLabel : null]
40
- .filter(Boolean)
41
- .join(' • ');
40
+ return {
41
+ sku: sku ? `SKU ${sku}` : '',
42
+ priceLabel,
43
+ metaLine: [sku ? `SKU ${sku}` : null].filter(Boolean).join(' • '),
44
+ };
45
+ };
46
+
47
+ /** Prefer resolveProductMetaParts when layout needs price separated. */
48
+ export const resolveProductMeta = product => {
49
+ const {sku, priceLabel} = resolveProductMetaParts(product);
50
+ return [sku || null, priceLabel || null].filter(Boolean).join(' • ');
42
51
  };
43
52
 
44
53
  export const resolveCompanyLabel = company =>
@@ -392,17 +401,29 @@ export const SelectionModal = ({
392
401
  color={selected ? palette.iconActive : palette.iconDisabled}
393
402
  />
394
403
  <View style={styles.selectionModalItemCopy}>
395
- <Text style={styles.selectionModalItemTitle}>
404
+ <Text style={styles.selectionModalItemTitle} numberOfLines={2}>
396
405
  {resolveItemLabel(item)}
397
406
  </Text>
398
- <Text style={styles.selectionModalItemMeta}>
407
+ <Text style={styles.selectionModalItemMeta} numberOfLines={1}>
399
408
  {(selected
400
409
  ? selectionMeta?.(item, {selected, multiSelect})
401
410
  : null) ||
402
- resolveItemMeta(item) ||
411
+ resolveProductMetaParts(item).metaLine ||
412
+ resolveProductMetaParts(item).sku ||
403
413
  'Toque para selecionar'}
404
414
  </Text>
405
415
  </View>
416
+ {!!resolveProductMetaParts(item).priceLabel && (
417
+ <Text
418
+ style={{
419
+ fontSize: 13,
420
+ fontWeight: '700',
421
+ color: palette.iconSuccess || palette.success,
422
+ marginLeft: 8,
423
+ }}>
424
+ {resolveProductMetaParts(item).priceLabel}
425
+ </Text>
426
+ )}
406
427
  </TouchableOpacity>
407
428
  );
408
429
  })
@@ -417,7 +438,7 @@ export const SelectionModal = ({
417
438
  styles.selectionModalActionButton,
418
439
  ]}
419
440
  onPress={onClose}>
420
- <Text style={styles.primaryButtonText}>Concluir selecao</Text>
441
+ <Text style={styles.primaryButtonText}>Concluir seleção</Text>
421
442
  </TouchableOpacity>
422
443
  )}
423
444
  </View>
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Pure helper: resolves safe CRM → ClientDetails navigation.
3
+ * Ensures clientId is present, sets contextKey=client, and opens
4
+ * sellers tab for legal entities (PJ / peopleType J).
5
+ */
6
+ const extractId = value => String(value || '').replace(/\D/g, '');
7
+
8
+ const resolveClientDetailsNavigation = ({
9
+ reference,
10
+ matchedPerson,
11
+ opportunityClient,
12
+ fallbackName,
13
+ } = {}) => {
14
+ const normalizedReference = String(reference || '').trim();
15
+ if (!normalizedReference) {
16
+ return null;
17
+ }
18
+
19
+ const selectedClient =
20
+ matchedPerson ||
21
+ (typeof opportunityClient === 'object' && opportunityClient
22
+ ? opportunityClient
23
+ : null) || {
24
+ id: extractId(normalizedReference),
25
+ '@id': normalizedReference,
26
+ name: fallbackName,
27
+ };
28
+
29
+ const clientId = extractId(normalizedReference);
30
+ if (!clientId) {
31
+ return null;
32
+ }
33
+
34
+ const peopleType = String(
35
+ selectedClient?.peopleType ||
36
+ matchedPerson?.peopleType ||
37
+ opportunityClient?.peopleType ||
38
+ '',
39
+ )
40
+ .trim()
41
+ .toUpperCase();
42
+
43
+ return {
44
+ selectedClient,
45
+ params: {
46
+ clientId,
47
+ contextKey: 'client',
48
+ initialTab: peopleType === 'J' ? 'sellers' : 'general',
49
+ },
50
+ };
51
+ };
52
+
53
+ module.exports = {
54
+ resolveClientDetailsNavigation,
55
+ extractId,
56
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Permission rules for client ↔ seller linkage UI (issue #2 / residual #36).
3
+ * Boundary is APP_TYPE (MANAGER vs others), not only company role.
4
+ *
5
+ * MANAGER: full management + commission visibility
6
+ * Non-MANAGER (e.g. CRM): can see linked seller name only
7
+ */
8
+
9
+ const normalizeAppType = appType =>
10
+ String(appType || '')
11
+ .trim()
12
+ .toUpperCase();
13
+
14
+ const isManagerApp = appType => normalizeAppType(appType) === 'MANAGER';
15
+
16
+ /**
17
+ * @param {string} [appType] - APP_TYPE from runtime (MANAGER, CRM, POS, SHOP, …)
18
+ * @returns {{
19
+ * canViewSeller: boolean,
20
+ * canManageSellers: boolean,
21
+ * canChangeSeller: boolean,
22
+ * canRemoveSeller: boolean,
23
+ * canAddMultipleSellers: boolean,
24
+ * canEditSeller: boolean,
25
+ * canViewCommissionPercent: boolean,
26
+ * canViewMinimumCommission: boolean,
27
+ * }}
28
+ */
29
+ const resolveClientSellerVisibility = (appType) => {
30
+ const manager = isManagerApp(appType);
31
+
32
+ return {
33
+ canViewSeller: true,
34
+ canManageSellers: manager,
35
+ canChangeSeller: manager,
36
+ canRemoveSeller: manager,
37
+ canAddMultipleSellers: manager,
38
+ canEditSeller: manager,
39
+ canViewCommissionPercent: manager,
40
+ canViewMinimumCommission: manager,
41
+ };
42
+ };
43
+
44
+ /**
45
+ * Whether commission-related fields should be shown in the UI.
46
+ */
47
+ const canShowCommissionFields = appType => isManagerApp(appType);
48
+
49
+ /**
50
+ * Whether seller linkage management actions (add/change/remove) are allowed.
51
+ */
52
+ const canManageSellerLinks = appType => isManagerApp(appType);
53
+
54
+ module.exports = {
55
+ resolveClientSellerVisibility,
56
+ canShowCommissionFields,
57
+ canManageSellerLinks,
58
+ isManagerApp,
59
+ normalizeAppType,
60
+ };
@@ -24,20 +24,102 @@ const normalizeEntityId = value => {
24
24
  return String(value);
25
25
  };
26
26
 
27
- const normalizeCategoryId = value =>
28
- normalizeEntityId(
29
- value?.category ||
30
- value?.parent ||
31
- value?.['@id'] ||
32
- value?.id ||
33
- value,
34
- );
27
+ /**
28
+ * Resolve a category id from common payload shapes:
29
+ * - plain id / IRI / Category object
30
+ * - product.category (legacy / sparse payloads)
31
+ * - product.productCategory[] (ProductCategory join entities)
32
+ * - nested { category: ... } wrappers
33
+ */
34
+ const normalizeCategoryId = value => {
35
+ if (value === null || value === undefined || value === '') {
36
+ return null;
37
+ }
38
+
39
+ if (Array.isArray(value)) {
40
+ for (const entry of value) {
41
+ const resolved = normalizeCategoryId(entry);
42
+ if (resolved) {
43
+ return resolved;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ if (typeof value === 'object') {
50
+ // ProductCategory join: { category: Category|IRI, product: ... }
51
+ if (value.category !== undefined && value.category !== null) {
52
+ return normalizeCategoryId(value.category);
53
+ }
54
+
55
+ // Category entity or sparse object
56
+ if (value.parent !== undefined && value.parent !== null && !value['@id'] && !value.id) {
57
+ return normalizeCategoryId(value.parent);
58
+ }
59
+
60
+ return normalizeEntityId(value['@id'] || value.id || value.value || value.parent);
61
+ }
62
+
63
+ return normalizeEntityId(value);
64
+ };
65
+
66
+ const collectProductCategoryIds = product => {
67
+ const ids = new Set();
68
+
69
+ const pushId = candidate => {
70
+ const id = normalizeCategoryId(candidate);
71
+ if (id) {
72
+ ids.add(id);
73
+ }
74
+ };
75
+
76
+ if (!product || typeof product !== 'object') {
77
+ return ids;
78
+ }
79
+
80
+ // Legacy / sparse single category field
81
+ pushId(product.category);
82
+
83
+ // Canonical join collection from Product::productCategory
84
+ const joinCollection =
85
+ product.productCategory ||
86
+ product.productCategories ||
87
+ product.categories ||
88
+ product.product_category;
89
+
90
+ if (Array.isArray(joinCollection)) {
91
+ joinCollection.forEach(entry => {
92
+ pushId(entry);
93
+ pushId(entry?.category);
94
+ });
95
+ } else if (joinCollection) {
96
+ pushId(joinCollection);
97
+ pushId(joinCollection?.category);
98
+ }
99
+
100
+ return ids;
101
+ };
35
102
 
36
103
  const getProposalModelCategoryId = model => normalizeCategoryId(model?.category);
37
104
 
38
105
  const getProposalModelCategoryName = model =>
39
106
  String(model?.category?.name || model?.category?.category || '').trim();
40
107
 
108
+ const productMatchesModelCategory = (product, selectedModelCategoryId) => {
109
+ if (!selectedModelCategoryId) {
110
+ return true;
111
+ }
112
+
113
+ const productCategoryIds = collectProductCategoryIds(product);
114
+ if (productCategoryIds.size === 0) {
115
+ // When the payload does not embed categories, do not client-side-reject:
116
+ // the API filter (productCategory.category) is the source of truth.
117
+ return true;
118
+ }
119
+
120
+ return productCategoryIds.has(String(selectedModelCategoryId));
121
+ };
122
+
41
123
  const filterProductsByModelCategory = ({ products, selectedModelCategoryId }) => {
42
124
  const normalizedProducts = Array.isArray(products) ? products : [];
43
125
 
@@ -45,8 +127,8 @@ const filterProductsByModelCategory = ({ products, selectedModelCategoryId }) =>
45
127
  return normalizedProducts;
46
128
  }
47
129
 
48
- return normalizedProducts.filter(
49
- product => normalizeCategoryId(product?.category) === selectedModelCategoryId,
130
+ return normalizedProducts.filter(product =>
131
+ productMatchesModelCategory(product, selectedModelCategoryId),
50
132
  );
51
133
  };
52
134
 
@@ -55,17 +137,25 @@ const keepCompatibleSelectedProducts = ({ selectedProducts, selectedModelCategor
55
137
  return Array.isArray(selectedProducts) ? selectedProducts : [];
56
138
  }
57
139
 
58
- return filterProductsByModelCategory({
59
- products: selectedProducts,
60
- selectedModelCategoryId,
140
+ const list = Array.isArray(selectedProducts) ? selectedProducts : [];
141
+
142
+ return list.filter(product => {
143
+ const productCategoryIds = collectProductCategoryIds(product);
144
+ // Keep selection when we cannot prove incompatibility from sparse payload
145
+ if (productCategoryIds.size === 0) {
146
+ return true;
147
+ }
148
+ return productCategoryIds.has(String(selectedModelCategoryId));
61
149
  });
62
150
  };
63
151
 
64
152
  module.exports = {
153
+ collectProductCategoryIds,
65
154
  filterProductsByModelCategory,
66
155
  getProposalModelCategoryId,
67
156
  getProposalModelCategoryName,
68
157
  keepCompatibleSelectedProducts,
69
158
  normalizeCategoryId,
70
159
  normalizeEntityId,
160
+ productMatchesModelCategory,
71
161
  };