@hed-hog/catalog 0.0.293 → 0.0.295

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 (66) hide show
  1. package/README.md +391 -361
  2. package/dist/catalog-resource.config.d.ts.map +1 -1
  3. package/dist/catalog-resource.config.js +51 -24
  4. package/dist/catalog-resource.config.js.map +1 -1
  5. package/dist/catalog.controller.d.ts +420 -0
  6. package/dist/catalog.controller.d.ts.map +1 -1
  7. package/dist/catalog.controller.js +98 -0
  8. package/dist/catalog.controller.js.map +1 -1
  9. package/dist/catalog.module.d.ts.map +1 -1
  10. package/dist/catalog.module.js +5 -1
  11. package/dist/catalog.module.js.map +1 -1
  12. package/dist/catalog.service.d.ts +216 -1
  13. package/dist/catalog.service.d.ts.map +1 -1
  14. package/dist/catalog.service.js +1121 -7
  15. package/dist/catalog.service.js.map +1 -1
  16. package/hedhog/data/catalog_attribute.yaml +202 -0
  17. package/hedhog/data/catalog_attribute_option.yaml +109 -0
  18. package/hedhog/data/catalog_category.yaml +47 -0
  19. package/hedhog/data/catalog_category_attribute.yaml +209 -0
  20. package/hedhog/data/menu.yaml +46 -12
  21. package/hedhog/data/role.yaml +7 -7
  22. package/hedhog/data/route.yaml +64 -0
  23. package/hedhog/frontend/app/[resource]/page.tsx.ejs +358 -0
  24. package/hedhog/frontend/app/_components/catalog-ai-form-assist-dialog.tsx.ejs +340 -0
  25. package/hedhog/frontend/app/_components/catalog-resource-form-sheet.tsx.ejs +815 -0
  26. package/hedhog/frontend/app/_lib/catalog-resources.tsx.ejs +504 -736
  27. package/hedhog/frontend/app/dashboard/page.tsx.ejs +14 -83
  28. package/hedhog/frontend/messages/en.json +150 -60
  29. package/hedhog/frontend/messages/pt.json +185 -95
  30. package/hedhog/table/catalog_affiliate_program.yaml +41 -41
  31. package/hedhog/table/catalog_attribute.yaml +22 -7
  32. package/hedhog/table/catalog_attribute_group.yaml +18 -18
  33. package/hedhog/table/catalog_attribute_option.yaml +40 -0
  34. package/hedhog/table/catalog_brand.yaml +34 -34
  35. package/hedhog/table/catalog_category.yaml +40 -0
  36. package/hedhog/table/catalog_category_attribute.yaml +13 -7
  37. package/hedhog/table/catalog_click_event.yaml +50 -50
  38. package/hedhog/table/catalog_comparison.yaml +3 -6
  39. package/hedhog/table/catalog_comparison_highlight.yaml +39 -39
  40. package/hedhog/table/catalog_comparison_item.yaml +30 -30
  41. package/hedhog/table/catalog_content_relation.yaml +42 -42
  42. package/hedhog/table/catalog_import_run.yaml +33 -33
  43. package/hedhog/table/catalog_import_source.yaml +24 -24
  44. package/hedhog/table/catalog_merchant.yaml +29 -29
  45. package/hedhog/table/catalog_offer.yaml +83 -83
  46. package/hedhog/table/catalog_price_history.yaml +34 -34
  47. package/hedhog/table/catalog_product.yaml +5 -3
  48. package/hedhog/table/catalog_product_attribute_value.yaml +15 -2
  49. package/hedhog/table/catalog_product_category.yaml +3 -3
  50. package/hedhog/table/catalog_product_image.yaml +34 -34
  51. package/hedhog/table/catalog_product_score.yaml +38 -38
  52. package/hedhog/table/catalog_product_site.yaml +47 -47
  53. package/hedhog/table/catalog_product_tag.yaml +19 -19
  54. package/hedhog/table/catalog_score_criterion.yaml +25 -8
  55. package/hedhog/table/catalog_seo_page_rule.yaml +2 -2
  56. package/hedhog/table/catalog_similarity_rule.yaml +19 -6
  57. package/hedhog/table/catalog_site.yaml +8 -0
  58. package/hedhog/table/catalog_site_category.yaml +3 -3
  59. package/package.json +7 -7
  60. package/src/catalog-resource.config.ts +51 -24
  61. package/src/catalog.controller.ts +67 -0
  62. package/src/catalog.module.ts +5 -1
  63. package/src/catalog.service.ts +1531 -6
  64. package/src/index.ts +1 -1
  65. package/src/language/en.json +4 -4
  66. package/src/language/pt.json +4 -4
@@ -13,12 +13,14 @@ exports.CatalogService = void 0;
13
13
  const api_locale_1 = require("@hed-hog/api-locale");
14
14
  const api_pagination_1 = require("@hed-hog/api-pagination");
15
15
  const api_prisma_1 = require("@hed-hog/api-prisma");
16
+ const core_1 = require("@hed-hog/core");
16
17
  const common_1 = require("@nestjs/common");
17
18
  const catalog_resource_config_1 = require("./catalog-resource.config");
18
19
  let CatalogService = class CatalogService {
19
- constructor(prisma, pagination) {
20
+ constructor(prisma, pagination, aiService) {
20
21
  this.prisma = prisma;
21
22
  this.pagination = pagination;
23
+ this.aiService = aiService;
22
24
  }
23
25
  getConfig(resource, locale) {
24
26
  const config = catalog_resource_config_1.catalogResourceMap.get(resource);
@@ -29,7 +31,11 @@ let CatalogService = class CatalogService {
29
31
  }
30
32
  getModel(resource, locale) {
31
33
  const config = this.getConfig(resource, locale);
32
- return this.prisma[config.model];
34
+ const model = this.prisma[config.model];
35
+ if (!model) {
36
+ throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('resourceNotSupported', locale, `Model "${config.model}" is not available`));
37
+ }
38
+ return model;
33
39
  }
34
40
  normalizeValue(value) {
35
41
  if (value === 'true') {
@@ -43,11 +49,500 @@ let CatalogService = class CatalogService {
43
49
  }
44
50
  return value;
45
51
  }
52
+ extractJsonObject(content) {
53
+ var _a;
54
+ const trimmed = String(content !== null && content !== void 0 ? content : '').trim();
55
+ if (!trimmed) {
56
+ throw new common_1.BadRequestException('AI returned an empty response');
57
+ }
58
+ const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
59
+ const candidate = ((_a = fencedMatch === null || fencedMatch === void 0 ? void 0 : fencedMatch[1]) === null || _a === void 0 ? void 0 : _a.trim()) || trimmed;
60
+ try {
61
+ return JSON.parse(candidate);
62
+ }
63
+ catch (_b) {
64
+ const firstBraceIndex = candidate.indexOf('{');
65
+ const lastBraceIndex = candidate.lastIndexOf('}');
66
+ if (firstBraceIndex >= 0 && lastBraceIndex > firstBraceIndex) {
67
+ try {
68
+ return JSON.parse(candidate.slice(firstBraceIndex, lastBraceIndex + 1));
69
+ }
70
+ catch (_c) {
71
+ throw new common_1.BadRequestException('AI returned an invalid JSON payload');
72
+ }
73
+ }
74
+ throw new common_1.BadRequestException('AI returned an invalid JSON payload');
75
+ }
76
+ }
77
+ normalizeComparableText(value) {
78
+ return String(value !== null && value !== void 0 ? value : '')
79
+ .normalize('NFD')
80
+ .replace(/[\u0300-\u036f]/g, '')
81
+ .trim()
82
+ .toLowerCase();
83
+ }
84
+ normalizeAiFieldContext(resource, fields) {
85
+ const config = catalog_resource_config_1.catalogResourceMap.get(resource);
86
+ if (!config) {
87
+ return [];
88
+ }
89
+ const allowedKeys = new Set(config.fields);
90
+ return fields
91
+ .map((field) => {
92
+ var _a, _b, _c, _d;
93
+ const key = String((_a = field.key) !== null && _a !== void 0 ? _a : '').trim();
94
+ if (!key || !allowedKeys.has(key)) {
95
+ return null;
96
+ }
97
+ const options = Array.isArray(field.options)
98
+ ? field.options
99
+ .map((option) => {
100
+ var _a, _b;
101
+ return ({
102
+ value: String((_a = option.value) !== null && _a !== void 0 ? _a : '').trim(),
103
+ label: String((_b = option.label) !== null && _b !== void 0 ? _b : '').trim(),
104
+ });
105
+ })
106
+ .filter((option) => option.value && option.label)
107
+ : [];
108
+ const relationData = field.relation && typeof field.relation === 'object'
109
+ ? field.relation
110
+ : null;
111
+ return {
112
+ key,
113
+ label: String((_b = field.label) !== null && _b !== void 0 ? _b : key),
114
+ type: String((_c = field.type) !== null && _c !== void 0 ? _c : 'text'),
115
+ required: Boolean((_d = field.required) !== null && _d !== void 0 ? _d : false),
116
+ options,
117
+ relation: relationData
118
+ ? {
119
+ endpoint: relationData.endpoint
120
+ ? String(relationData.endpoint)
121
+ : undefined,
122
+ resource: relationData.resource
123
+ ? String(relationData.resource)
124
+ : undefined,
125
+ labelKeys: Array.isArray(relationData.labelKeys)
126
+ ? relationData.labelKeys.map((item) => String(item))
127
+ : [],
128
+ }
129
+ : null,
130
+ };
131
+ })
132
+ .filter(Boolean);
133
+ }
134
+ normalizeBooleanSuggestion(value) {
135
+ if (typeof value === 'boolean') {
136
+ return value;
137
+ }
138
+ if (typeof value === 'number') {
139
+ return value !== 0;
140
+ }
141
+ const normalized = this.normalizeComparableText(value);
142
+ if (!normalized) {
143
+ return null;
144
+ }
145
+ if (['true', '1', 'yes', 'y', 'sim', 'ativo', 'active', 'enabled'].includes(normalized)) {
146
+ return true;
147
+ }
148
+ if (['false', '0', 'no', 'n', 'nao', 'não', 'inativo', 'inactive', 'disabled'].includes(normalized)) {
149
+ return false;
150
+ }
151
+ return null;
152
+ }
153
+ normalizeNumberSuggestion(value) {
154
+ if (typeof value === 'number') {
155
+ return Number.isFinite(value) ? value : null;
156
+ }
157
+ const raw = String(value !== null && value !== void 0 ? value : '').trim();
158
+ if (!raw) {
159
+ return null;
160
+ }
161
+ const normalized = raw.replace(/[^\d,.\-]/g, '').replace(',', '.');
162
+ const parsed = Number(normalized);
163
+ return Number.isFinite(parsed) ? parsed : null;
164
+ }
165
+ normalizeSelectSuggestion(rawValue, options) {
166
+ var _a;
167
+ const normalized = this.normalizeComparableText(rawValue);
168
+ if (!normalized) {
169
+ return null;
170
+ }
171
+ const exact = options.find((option) => {
172
+ return (this.normalizeComparableText(option.value) === normalized ||
173
+ this.normalizeComparableText(option.label) === normalized);
174
+ });
175
+ if (exact) {
176
+ return exact.value;
177
+ }
178
+ const partial = options.find((option) => {
179
+ return (this.normalizeComparableText(option.value).includes(normalized) ||
180
+ normalized.includes(this.normalizeComparableText(option.value)) ||
181
+ this.normalizeComparableText(option.label).includes(normalized) ||
182
+ normalized.includes(this.normalizeComparableText(option.label)));
183
+ });
184
+ return (_a = partial === null || partial === void 0 ? void 0 : partial.value) !== null && _a !== void 0 ? _a : null;
185
+ }
186
+ async resolveRelationSuggestion(field, rawValue) {
187
+ if (rawValue === null || rawValue === undefined || rawValue === '') {
188
+ return null;
189
+ }
190
+ const relation = field.relation;
191
+ if (!relation) {
192
+ return null;
193
+ }
194
+ const modelInfo = (() => {
195
+ var _a, _b, _c;
196
+ if (relation.resource) {
197
+ const config = catalog_resource_config_1.catalogResourceMap.get(relation.resource);
198
+ if (config) {
199
+ return {
200
+ model: config.model,
201
+ searchFields: ((_a = relation.labelKeys) === null || _a === void 0 ? void 0 : _a.length) ? relation.labelKeys : config.searchFields,
202
+ idField: 'id',
203
+ };
204
+ }
205
+ }
206
+ if (relation.endpoint === '/locale') {
207
+ return {
208
+ model: 'locale',
209
+ searchFields: ((_b = relation.labelKeys) === null || _b === void 0 ? void 0 : _b.length) ? relation.labelKeys : ['name', 'code'],
210
+ idField: 'id',
211
+ };
212
+ }
213
+ if (relation.endpoint === '/content') {
214
+ return {
215
+ model: 'content',
216
+ searchFields: ((_c = relation.labelKeys) === null || _c === void 0 ? void 0 : _c.length) ? relation.labelKeys : ['title', 'slug'],
217
+ idField: 'id',
218
+ };
219
+ }
220
+ return null;
221
+ })();
222
+ if (!modelInfo) {
223
+ return null;
224
+ }
225
+ const model = this.prisma[modelInfo.model];
226
+ if (!(model === null || model === void 0 ? void 0 : model.findMany)) {
227
+ return null;
228
+ }
229
+ const numericId = this.normalizeNumberSuggestion(rawValue);
230
+ if (numericId && Number.isInteger(numericId)) {
231
+ const byId = await model.findUnique({
232
+ where: { [modelInfo.idField]: numericId },
233
+ });
234
+ if (byId) {
235
+ return Number(byId[modelInfo.idField]);
236
+ }
237
+ }
238
+ const needle = String(rawValue !== null && rawValue !== void 0 ? rawValue : '').trim();
239
+ if (!needle) {
240
+ return null;
241
+ }
242
+ const results = await model.findMany({
243
+ where: {
244
+ OR: modelInfo.searchFields.map((fieldKey) => ({
245
+ [fieldKey]: {
246
+ contains: needle,
247
+ mode: 'insensitive',
248
+ },
249
+ })),
250
+ },
251
+ take: 5,
252
+ });
253
+ if (!results.length) {
254
+ return null;
255
+ }
256
+ const normalizedNeedle = this.normalizeComparableText(needle);
257
+ const exact = results.find((result) => modelInfo.searchFields.some((fieldKey) => {
258
+ return this.normalizeComparableText(result[fieldKey]) === normalizedNeedle;
259
+ }));
260
+ if (exact) {
261
+ return Number(exact[modelInfo.idField]);
262
+ }
263
+ return results.length === 1 ? Number(results[0][modelInfo.idField]) : null;
264
+ }
265
+ async normalizeAiFieldSuggestion(field, rawValue, warnings) {
266
+ if (rawValue === undefined) {
267
+ return undefined;
268
+ }
269
+ if (rawValue === null) {
270
+ return null;
271
+ }
272
+ switch (field.type) {
273
+ case 'switch': {
274
+ const value = this.normalizeBooleanSuggestion(rawValue);
275
+ if (value === null) {
276
+ warnings.push(`Boolean field "${field.label}" could not be resolved safely.`);
277
+ return undefined;
278
+ }
279
+ return value;
280
+ }
281
+ case 'number':
282
+ case 'currency': {
283
+ const value = this.normalizeNumberSuggestion(rawValue);
284
+ if (value === null) {
285
+ warnings.push(`Numeric field "${field.label}" could not be resolved safely.`);
286
+ return undefined;
287
+ }
288
+ return value;
289
+ }
290
+ case 'select': {
291
+ const value = this.normalizeSelectSuggestion(rawValue, field.options);
292
+ if (!value) {
293
+ warnings.push(`Select field "${field.label}" returned an invalid option.`);
294
+ return undefined;
295
+ }
296
+ return value;
297
+ }
298
+ case 'relation': {
299
+ const value = await this.resolveRelationSuggestion(field, rawValue);
300
+ if (!value) {
301
+ warnings.push(`Relation field "${field.label}" could not be resolved safely.`);
302
+ return undefined;
303
+ }
304
+ return value;
305
+ }
306
+ case 'upload':
307
+ warnings.push(`File field "${field.label}" must still be filled manually.`);
308
+ return undefined;
309
+ case 'json':
310
+ if (typeof rawValue === 'object') {
311
+ return rawValue;
312
+ }
313
+ try {
314
+ return JSON.parse(String(rawValue));
315
+ }
316
+ catch (_a) {
317
+ warnings.push(`JSON field "${field.label}" returned an invalid value.`);
318
+ return undefined;
319
+ }
320
+ case 'date':
321
+ case 'datetime':
322
+ case 'text':
323
+ case 'url':
324
+ case 'textarea':
325
+ case 'richtext':
326
+ default:
327
+ return String(rawValue).trim() || null;
328
+ }
329
+ }
330
+ buildCurrentAttributeValueMap(values) {
331
+ var _a;
332
+ const valueMap = new Map();
333
+ for (const value of values) {
334
+ const attributeId = Number((_a = value.attribute_id) !== null && _a !== void 0 ? _a : 0);
335
+ if (!attributeId) {
336
+ continue;
337
+ }
338
+ valueMap.set(attributeId, value);
339
+ }
340
+ return valueMap;
341
+ }
342
+ buildAttributeContext(attributesPayload, currentAttributeValues) {
343
+ var _a;
344
+ const currentMap = this.buildCurrentAttributeValueMap(currentAttributeValues);
345
+ return ((_a = attributesPayload.groups) !== null && _a !== void 0 ? _a : []).flatMap((group) => group.attributes.map((attribute) => {
346
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
347
+ const current = (_b = (_a = currentMap.get(Number(attribute.id))) !== null && _a !== void 0 ? _a : attribute.value) !== null && _b !== void 0 ? _b : null;
348
+ const relation = ((_c = attribute.category_attribute) !== null && _c !== void 0 ? _c : {});
349
+ return {
350
+ id: Number(attribute.id),
351
+ slug: String((_d = attribute.slug) !== null && _d !== void 0 ? _d : ''),
352
+ name: String((_g = (_f = (_e = attribute.label) !== null && _e !== void 0 ? _e : attribute.name) !== null && _f !== void 0 ? _f : attribute.slug) !== null && _g !== void 0 ? _g : ''),
353
+ data_type: String((_h = attribute.data_type) !== null && _h !== void 0 ? _h : 'text'),
354
+ unit: attribute.unit ? String(attribute.unit) : null,
355
+ group_name: String((_j = group.name) !== null && _j !== void 0 ? _j : 'General'),
356
+ is_required: Boolean((_k = relation.is_required) !== null && _k !== void 0 ? _k : false),
357
+ is_highlight: Boolean((_l = relation.is_highlight) !== null && _l !== void 0 ? _l : false),
358
+ is_filter_visible: Boolean((_m = relation.is_filter_visible) !== null && _m !== void 0 ? _m : true),
359
+ is_comparison_visible: Boolean((_o = relation.is_comparison_visible) !== null && _o !== void 0 ? _o : false),
360
+ options: Array.isArray(attribute.options)
361
+ ? attribute.options.map((option) => {
362
+ var _a, _b, _c, _d;
363
+ return ({
364
+ id: Number(option.id),
365
+ slug: String((_a = option.slug) !== null && _a !== void 0 ? _a : ''),
366
+ label: String((_c = (_b = option.label) !== null && _b !== void 0 ? _b : option.option_value) !== null && _c !== void 0 ? _c : ''),
367
+ option_value: String((_d = option.option_value) !== null && _d !== void 0 ? _d : ''),
368
+ normalized_value: option.normalized_value
369
+ ? String(option.normalized_value)
370
+ : null,
371
+ });
372
+ })
373
+ : [],
374
+ current_value: current,
375
+ };
376
+ }));
377
+ }
378
+ async normalizeAiProductAttributeSuggestions(categoryId, rawSuggestions, currentAttributeValues, warnings) {
379
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
380
+ if (!categoryId || rawSuggestions === undefined || rawSuggestions === null) {
381
+ return [];
382
+ }
383
+ const attributesPayload = await this.buildCategoryAttributePayload(categoryId);
384
+ const attributeContext = this.buildAttributeContext(attributesPayload, currentAttributeValues);
385
+ const normalizedEntries = Array.isArray(rawSuggestions)
386
+ ? rawSuggestions
387
+ : rawSuggestions && typeof rawSuggestions === 'object'
388
+ ? Object.entries(rawSuggestions).map(([slug, value]) => (Object.assign({ slug }, (value && typeof value === 'object'
389
+ ? value
390
+ : { value }))))
391
+ : [];
392
+ const normalizedSuggestions = [];
393
+ for (const entry of normalizedEntries) {
394
+ const entryRecord = (entry && typeof entry === 'object'
395
+ ? entry
396
+ : { value: entry });
397
+ const rawIdentifier = (_e = (_d = (_c = (_b = (_a = entryRecord.slug) !== null && _a !== void 0 ? _a : entryRecord.attribute_slug) !== null && _b !== void 0 ? _b : entryRecord.code) !== null && _c !== void 0 ? _c : entryRecord.name) !== null && _d !== void 0 ? _d : entryRecord.attribute) !== null && _e !== void 0 ? _e : null;
398
+ const normalizedIdentifier = this.normalizeComparableText(rawIdentifier);
399
+ const attribute = attributeContext.find((item) => {
400
+ var _a;
401
+ return (item.id === Number((_a = entryRecord.attribute_id) !== null && _a !== void 0 ? _a : 0) ||
402
+ this.normalizeComparableText(item.slug) === normalizedIdentifier ||
403
+ this.normalizeComparableText(item.name) === normalizedIdentifier);
404
+ });
405
+ if (!attribute) {
406
+ if (rawIdentifier) {
407
+ warnings.push(`Structured attribute "${String(rawIdentifier)}" is not available for the selected category.`);
408
+ }
409
+ continue;
410
+ }
411
+ const rawValue = (_l = (_k = (_j = (_h = (_g = (_f = entryRecord.value) !== null && _f !== void 0 ? _f : entryRecord.value_text) !== null && _g !== void 0 ? _g : entryRecord.value_number) !== null && _h !== void 0 ? _h : entryRecord.value_boolean) !== null && _j !== void 0 ? _j : entryRecord.option) !== null && _k !== void 0 ? _k : entryRecord.option_value) !== null && _l !== void 0 ? _l : entryRecord.label;
412
+ const draft = {
413
+ attribute_id: attribute.id,
414
+ attribute_slug: attribute.slug,
415
+ attribute_name: attribute.name,
416
+ data_type: attribute.data_type,
417
+ group_name: attribute.group_name,
418
+ value_unit: (_m = attribute.unit) !== null && _m !== void 0 ? _m : null,
419
+ };
420
+ if (attribute.data_type === 'option') {
421
+ const normalizedOption = this.normalizeComparableText((_q = (_p = (_o = entryRecord.option) !== null && _o !== void 0 ? _o : entryRecord.option_value) !== null && _p !== void 0 ? _p : entryRecord.label) !== null && _q !== void 0 ? _q : rawValue);
422
+ const option = attribute.options.find((item) => {
423
+ return (this.normalizeComparableText(item.option_value) === normalizedOption ||
424
+ this.normalizeComparableText(item.label) === normalizedOption ||
425
+ this.normalizeComparableText(item.slug) === normalizedOption);
426
+ });
427
+ if (!option) {
428
+ warnings.push(`Option value for "${attribute.name}" could not be resolved safely.`);
429
+ continue;
430
+ }
431
+ draft.attribute_option_id = option.id;
432
+ draft.value_text = option.option_value;
433
+ }
434
+ else if (attribute.data_type === 'number') {
435
+ const numberValue = this.normalizeNumberSuggestion(rawValue);
436
+ if (numberValue === null) {
437
+ warnings.push(`Numeric attribute "${attribute.name}" could not be resolved safely.`);
438
+ continue;
439
+ }
440
+ draft.value_number = numberValue;
441
+ draft.raw_value = String(numberValue);
442
+ draft.normalized_value = String(numberValue);
443
+ if (entryRecord.unit) {
444
+ draft.value_unit = String(entryRecord.unit).trim() || attribute.unit || null;
445
+ }
446
+ }
447
+ else if (attribute.data_type === 'boolean') {
448
+ const booleanValue = this.normalizeBooleanSuggestion(rawValue);
449
+ if (booleanValue === null) {
450
+ warnings.push(`Boolean attribute "${attribute.name}" could not be resolved safely.`);
451
+ continue;
452
+ }
453
+ draft.value_boolean = booleanValue;
454
+ draft.raw_value = String(booleanValue);
455
+ draft.normalized_value = String(booleanValue);
456
+ }
457
+ else {
458
+ const textValue = String(rawValue !== null && rawValue !== void 0 ? rawValue : '').trim();
459
+ if (!textValue) {
460
+ continue;
461
+ }
462
+ draft.value_text = textValue;
463
+ draft.raw_value = textValue;
464
+ draft.normalized_value = textValue;
465
+ }
466
+ normalizedSuggestions.push(draft);
467
+ }
468
+ return normalizedSuggestions;
469
+ }
470
+ buildAiSystemPrompt(resource, locale, fieldContext, currentValues, productAttributes) {
471
+ const isPt = locale === null || locale === void 0 ? void 0 : locale.startsWith('pt');
472
+ const fieldLines = fieldContext.map((field) => {
473
+ const optionText = field.options.length
474
+ ? ` options=${field.options.map((option) => `${option.label} (${option.value})`).join(', ')}`
475
+ : '';
476
+ const relationText = field.relation
477
+ ? ` relation=${field.relation.resource || field.relation.endpoint || 'external'}`
478
+ : '';
479
+ return `- ${field.key}: type=${field.type}; required=${field.required ? 'yes' : 'no'}; label="${field.label}"${optionText}${relationText}`;
480
+ });
481
+ const productAttributeLines = productAttributes.map((attribute) => {
482
+ const options = Array.isArray(attribute.options) ? attribute.options : [];
483
+ const optionText = options.length
484
+ ? ` options=${options
485
+ .map((option) => { var _a, _b; return `${String((_a = option.label) !== null && _a !== void 0 ? _a : '')} (${String((_b = option.option_value) !== null && _b !== void 0 ? _b : '')})`; })
486
+ .join(', ')}`
487
+ : '';
488
+ return `- ${String(attribute.slug)}: type=${String(attribute.data_type)}; name="${String(attribute.name)}"; required=${Boolean(attribute.is_required) ? 'yes' : 'no'}; group="${String(attribute.group_name)}"${optionText}`;
489
+ });
490
+ return [
491
+ isPt
492
+ ? 'Voce preenche formularios administrativos do catalogo. Responda apenas com JSON valido.'
493
+ : 'You fill catalog admin forms. Respond with valid JSON only.',
494
+ isPt
495
+ ? `Recurso atual: ${resource}.`
496
+ : `Current resource: ${resource}.`,
497
+ isPt
498
+ ? 'Use apenas os campos permitidos listados abaixo. Nao invente ids, arquivos ou campos extras.'
499
+ : 'Use only the allowed fields listed below. Do not invent ids, files, or extra fields.',
500
+ isPt
501
+ ? 'Para campos relacionais, prefira nomes/slug legiveis; o backend tentara resolver com seguranca.'
502
+ : 'For relation fields, prefer readable names/slugs; the backend will resolve them safely.',
503
+ isPt
504
+ ? 'Para selects, prefira os valores validos informados.'
505
+ : 'For selects, prefer the valid values provided.',
506
+ isPt
507
+ ? 'Estrutura da resposta: {"fields": { ... }, "product_attributes": { ... }, "notes": ["..."]}.'
508
+ : 'Response shape: {"fields": { ... }, "product_attributes": { ... }, "notes": ["..."]}.',
509
+ isPt
510
+ ? 'Se nao souber um campo, simplesmente omita.'
511
+ : 'If you are unsure about a field, omit it.',
512
+ `Allowed fields:\n${fieldLines.join('\n')}`,
513
+ productAttributeLines.length
514
+ ? `Structured product attributes:\n${productAttributeLines.join('\n')}`
515
+ : '',
516
+ `Current values: ${JSON.stringify(currentValues)}`,
517
+ ]
518
+ .filter(Boolean)
519
+ .join('\n\n');
520
+ }
46
521
  sanitizePayload(config, body) {
522
+ const normalizedBody = Object.assign({}, body);
523
+ if (config.resource === 'attributes') {
524
+ if (normalizedBody.name === undefined &&
525
+ normalizedBody.label !== undefined) {
526
+ normalizedBody.name = normalizedBody.label;
527
+ }
528
+ if (normalizedBody.data_type === 'select') {
529
+ normalizedBody.data_type = 'option';
530
+ }
531
+ }
532
+ if (config.resource === 'category-attributes') {
533
+ if (normalizedBody.is_highlight === undefined &&
534
+ normalizedBody.is_highlighted !== undefined) {
535
+ normalizedBody.is_highlight = normalizedBody.is_highlighted;
536
+ }
537
+ if (normalizedBody.sort_order === undefined &&
538
+ normalizedBody.display_order !== undefined) {
539
+ normalizedBody.sort_order = normalizedBody.display_order;
540
+ }
541
+ }
47
542
  const payload = {};
48
543
  for (const field of config.fields) {
49
- if (Object.prototype.hasOwnProperty.call(body, field) && body[field] !== undefined) {
50
- payload[field] = body[field];
544
+ if (Object.prototype.hasOwnProperty.call(normalizedBody, field) && normalizedBody[field] !== undefined) {
545
+ payload[field] = normalizedBody[field];
51
546
  }
52
547
  }
53
548
  return payload;
@@ -68,22 +563,369 @@ let CatalogService = class CatalogService {
68
563
  }
69
564
  return { OR, AND };
70
565
  }
566
+ async ensureCategoryExists(categoryId) {
567
+ const category = await this.prisma.catalog_category.findUnique({
568
+ where: { id: categoryId },
569
+ });
570
+ if (!category) {
571
+ throw new common_1.NotFoundException('Catalog category not found');
572
+ }
573
+ return category;
574
+ }
575
+ normalizeCategoryTree(items) {
576
+ var _a;
577
+ const byId = new Map();
578
+ const roots = [];
579
+ for (const item of items) {
580
+ byId.set(item.id, Object.assign(Object.assign({}, item), { children: [] }));
581
+ }
582
+ for (const item of byId.values()) {
583
+ if (item.parent_category_id && byId.has(item.parent_category_id)) {
584
+ (_a = byId.get(item.parent_category_id)) === null || _a === void 0 ? void 0 : _a.children.push(item);
585
+ }
586
+ else {
587
+ roots.push(item);
588
+ }
589
+ }
590
+ return roots;
591
+ }
592
+ async buildCategoryAttributePayload(categoryId, productId) {
593
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
594
+ const category = await this.ensureCategoryExists(categoryId);
595
+ const categoryAttributes = await this.prisma.catalog_category_attribute.findMany({
596
+ where: { catalog_category_id: categoryId },
597
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
598
+ });
599
+ const attributeIds = [...new Set(categoryAttributes.map((item) => item.attribute_id))];
600
+ const attributes = attributeIds.length
601
+ ? await this.prisma.catalog_attribute.findMany({
602
+ where: { id: { in: attributeIds } },
603
+ orderBy: [{ display_order: 'asc' }, { id: 'asc' }],
604
+ })
605
+ : [];
606
+ const groupIds = [...new Set(attributes.map((item) => item.group_id).filter((value) => typeof value === 'number'))];
607
+ const groups = groupIds.length
608
+ ? await this.prisma.catalog_attribute_group.findMany({
609
+ where: { id: { in: groupIds } },
610
+ })
611
+ : [];
612
+ const options = attributeIds.length
613
+ ? await this.prisma.catalog_attribute_option.findMany({
614
+ where: { attribute_id: { in: attributeIds } },
615
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
616
+ })
617
+ : [];
618
+ const values = productId && attributeIds.length
619
+ ? await this.prisma.catalog_product_attribute_value.findMany({
620
+ where: { product_id: productId, attribute_id: { in: attributeIds } },
621
+ include: {
622
+ catalog_attribute_option: true,
623
+ },
624
+ })
625
+ : [];
626
+ const categoryAttributeMap = new Map(categoryAttributes.map((item) => [item.attribute_id, item]));
627
+ const optionMap = new Map();
628
+ const valueMap = new Map(values.map((item) => [item.attribute_id, item]));
629
+ const groupMap = new Map(groups.map((item) => [item.id, item]));
630
+ for (const option of options) {
631
+ const bucket = (_a = optionMap.get(option.attribute_id)) !== null && _a !== void 0 ? _a : [];
632
+ bucket.push(option);
633
+ optionMap.set(option.attribute_id, bucket);
634
+ }
635
+ const grouped = new Map();
636
+ for (const attribute of attributes) {
637
+ const relation = categoryAttributeMap.get(attribute.id);
638
+ if (!relation) {
639
+ continue;
640
+ }
641
+ const groupId = (_b = attribute.group_id) !== null && _b !== void 0 ? _b : 0;
642
+ const group = attribute.group_id ? groupMap.get(attribute.group_id) : null;
643
+ const fallbackGroupName = String((_c = attribute.group_name) !== null && _c !== void 0 ? _c : '').trim() || 'General';
644
+ const groupKey = attribute.group_id ? String(groupId) : `name:${fallbackGroupName}`;
645
+ const existingGroup = (_d = grouped.get(groupKey)) !== null && _d !== void 0 ? _d : {
646
+ id: (_e = group === null || group === void 0 ? void 0 : group.id) !== null && _e !== void 0 ? _e : null,
647
+ slug: (_f = group === null || group === void 0 ? void 0 : group.slug) !== null && _f !== void 0 ? _f : fallbackGroupName.toLowerCase().replace(/\s+/g, '-'),
648
+ name: (_g = group === null || group === void 0 ? void 0 : group.name) !== null && _g !== void 0 ? _g : fallbackGroupName,
649
+ attributes: [],
650
+ };
651
+ existingGroup.attributes.push(Object.assign(Object.assign({}, attribute), { category_attribute: relation, options: (_h = optionMap.get(attribute.id)) !== null && _h !== void 0 ? _h : [], value: (_j = valueMap.get(attribute.id)) !== null && _j !== void 0 ? _j : null }));
652
+ grouped.set(groupKey, existingGroup);
653
+ }
654
+ const resultGroups = [...grouped.values()].map((group) => (Object.assign(Object.assign({}, group), { attributes: group.attributes.sort((left, right) => {
655
+ var _a, _b, _c, _d, _e, _f, _g, _h;
656
+ const leftRelation = left.category_attribute;
657
+ const rightRelation = right.category_attribute;
658
+ return (Number((_a = leftRelation.sort_order) !== null && _a !== void 0 ? _a : 0) - Number((_b = rightRelation.sort_order) !== null && _b !== void 0 ? _b : 0) ||
659
+ Number((_c = leftRelation.display_order) !== null && _c !== void 0 ? _c : 0) - Number((_d = rightRelation.display_order) !== null && _d !== void 0 ? _d : 0) ||
660
+ Number((_e = left.display_order) !== null && _e !== void 0 ? _e : 0) - Number((_f = right.display_order) !== null && _f !== void 0 ? _f : 0) ||
661
+ Number((_g = left.id) !== null && _g !== void 0 ? _g : 0) - Number((_h = right.id) !== null && _h !== void 0 ? _h : 0));
662
+ }) })));
663
+ resultGroups.sort((left, right) => String(left.name).localeCompare(String(right.name)));
664
+ return {
665
+ category,
666
+ product_id: productId !== null && productId !== void 0 ? productId : null,
667
+ groups: resultGroups,
668
+ attributes: resultGroups.flatMap((group) => group.attributes),
669
+ };
670
+ }
671
+ isMeaningfulAttributeValue(value) {
672
+ var _a;
673
+ if (value.attribute_option_id !== undefined && value.attribute_option_id !== null) {
674
+ return true;
675
+ }
676
+ if (value.value_number !== undefined && value.value_number !== null) {
677
+ return true;
678
+ }
679
+ if (value.value_boolean !== undefined && value.value_boolean !== null) {
680
+ return true;
681
+ }
682
+ return String((_a = value.value_text) !== null && _a !== void 0 ? _a : '').trim().length > 0;
683
+ }
684
+ buildAttributeSnapshotValue(attribute) {
685
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
686
+ const value = ((_a = attribute.value) !== null && _a !== void 0 ? _a : null);
687
+ const dataType = String((_b = attribute.data_type) !== null && _b !== void 0 ? _b : 'text');
688
+ const option = (_c = value === null || value === void 0 ? void 0 : value.catalog_attribute_option) !== null && _c !== void 0 ? _c : null;
689
+ if (!value) {
690
+ return {
691
+ value: null,
692
+ value_text: null,
693
+ value_number: null,
694
+ value_boolean: null,
695
+ normalized_value: null,
696
+ raw_value: null,
697
+ option: null,
698
+ };
699
+ }
700
+ if (dataType === 'option') {
701
+ const optionPayload = option
702
+ ? {
703
+ id: Number(option.id),
704
+ slug: String((_d = option.slug) !== null && _d !== void 0 ? _d : ''),
705
+ label: String((_f = (_e = option.label) !== null && _e !== void 0 ? _e : option.option_value) !== null && _f !== void 0 ? _f : ''),
706
+ option_value: String((_g = option.option_value) !== null && _g !== void 0 ? _g : ''),
707
+ }
708
+ : null;
709
+ return {
710
+ value: (_j = (_h = optionPayload === null || optionPayload === void 0 ? void 0 : optionPayload.option_value) !== null && _h !== void 0 ? _h : value.value_text) !== null && _j !== void 0 ? _j : null,
711
+ value_text: value.value_text ? String(value.value_text) : null,
712
+ value_number: null,
713
+ value_boolean: null,
714
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
715
+ raw_value: value.raw_value ? String(value.raw_value) : null,
716
+ option: optionPayload,
717
+ };
718
+ }
719
+ if (dataType === 'number') {
720
+ return {
721
+ value: value.value_number === null || value.value_number === undefined
722
+ ? null
723
+ : Number(value.value_number),
724
+ value_text: value.value_text ? String(value.value_text) : null,
725
+ value_number: value.value_number === null || value.value_number === undefined
726
+ ? null
727
+ : Number(value.value_number),
728
+ value_boolean: null,
729
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
730
+ raw_value: value.raw_value ? String(value.raw_value) : null,
731
+ option: null,
732
+ };
733
+ }
734
+ if (dataType === 'boolean') {
735
+ return {
736
+ value: value.value_boolean === null || value.value_boolean === undefined
737
+ ? null
738
+ : Boolean(value.value_boolean),
739
+ value_text: value.value_text ? String(value.value_text) : null,
740
+ value_number: null,
741
+ value_boolean: value.value_boolean === null || value.value_boolean === undefined
742
+ ? null
743
+ : Boolean(value.value_boolean),
744
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
745
+ raw_value: value.raw_value ? String(value.raw_value) : null,
746
+ option: null,
747
+ };
748
+ }
749
+ return {
750
+ value: value.value_text ? String(value.value_text) : null,
751
+ value_text: value.value_text ? String(value.value_text) : null,
752
+ value_number: null,
753
+ value_boolean: null,
754
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
755
+ raw_value: value.raw_value ? String(value.raw_value) : null,
756
+ option: null,
757
+ };
758
+ }
759
+ toAttributeSnapshot(attribute) {
760
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
761
+ const relation = ((_a = attribute.category_attribute) !== null && _a !== void 0 ? _a : {});
762
+ const snapshotValue = this.buildAttributeSnapshotValue(attribute);
763
+ return Object.assign({ slug: String((_b = attribute.slug) !== null && _b !== void 0 ? _b : ''), name: String((_d = (_c = attribute.name) !== null && _c !== void 0 ? _c : attribute.slug) !== null && _d !== void 0 ? _d : ''), data_type: String((_e = attribute.data_type) !== null && _e !== void 0 ? _e : 'text'), unit: attribute.unit ? String(attribute.unit) : null, group_name: String((_f = attribute.group_name) !== null && _f !== void 0 ? _f : 'General'), is_required: Boolean((_g = relation.is_required) !== null && _g !== void 0 ? _g : false), is_highlight: Boolean((_h = relation.is_highlight) !== null && _h !== void 0 ? _h : false), is_filter_visible: Boolean((_j = relation.is_filter_visible) !== null && _j !== void 0 ? _j : false), is_comparison_visible: Boolean((_k = relation.is_comparison_visible) !== null && _k !== void 0 ? _k : false) }, snapshotValue);
764
+ }
765
+ async decorateProductRecords(records) {
766
+ if (!records.length) {
767
+ return records;
768
+ }
769
+ const brandIds = [...new Set(records
770
+ .map((record) => record.brand_id)
771
+ .filter((value) => typeof value === 'number'))];
772
+ const categoryIds = [...new Set(records
773
+ .map((record) => record.catalog_category_id)
774
+ .filter((value) => typeof value === 'number'))];
775
+ const [brands, categories] = await Promise.all([
776
+ brandIds.length
777
+ ? this.prisma.catalog_brand.findMany({
778
+ where: { id: { in: brandIds } },
779
+ select: { id: true, name: true, slug: true, logo_file_id: true },
780
+ })
781
+ : Promise.resolve([]),
782
+ categoryIds.length
783
+ ? this.prisma.catalog_category.findMany({
784
+ where: { id: { in: categoryIds } },
785
+ select: { id: true, name: true, slug: true },
786
+ })
787
+ : Promise.resolve([]),
788
+ ]);
789
+ const brandMap = new Map(brands.map((item) => [item.id, item]));
790
+ const categoryMap = new Map(categories.map((item) => [item.id, item]));
791
+ return records.map((record) => {
792
+ var _a, _b, _c, _d, _e;
793
+ const brand = record.brand_id ? brandMap.get(record.brand_id) : null;
794
+ const category = record.catalog_category_id
795
+ ? categoryMap.get(record.catalog_category_id)
796
+ : null;
797
+ return Object.assign(Object.assign({}, record), { brand_name: (_a = brand === null || brand === void 0 ? void 0 : brand.name) !== null && _a !== void 0 ? _a : null, brand_slug: (_b = brand === null || brand === void 0 ? void 0 : brand.slug) !== null && _b !== void 0 ? _b : null, brand_logo_file_id: (_c = brand === null || brand === void 0 ? void 0 : brand.logo_file_id) !== null && _c !== void 0 ? _c : null, category_name: (_d = category === null || category === void 0 ? void 0 : category.name) !== null && _d !== void 0 ? _d : null, category_slug: (_e = category === null || category === void 0 ? void 0 : category.slug) !== null && _e !== void 0 ? _e : null });
798
+ });
799
+ }
800
+ validateAttributeValueByType(attribute, value) {
801
+ var _a;
802
+ const hasText = String((_a = value.value_text) !== null && _a !== void 0 ? _a : '').trim().length > 0;
803
+ const hasNumber = value.value_number !== undefined && value.value_number !== null;
804
+ const hasBoolean = value.value_boolean !== undefined && value.value_boolean !== null;
805
+ const hasOption = value.attribute_option_id !== undefined && value.attribute_option_id !== null;
806
+ const filledKinds = [hasText, hasNumber, hasBoolean, hasOption].filter(Boolean).length;
807
+ const attributeLabel = attribute.name || attribute.slug || `#${attribute.id}`;
808
+ if (filledKinds > 1) {
809
+ throw new common_1.BadRequestException(`Attribute "${attributeLabel}" must use a single value field compatible with its type`);
810
+ }
811
+ switch (attribute.data_type) {
812
+ case 'text':
813
+ case 'long_text':
814
+ if (hasNumber || hasBoolean || hasOption) {
815
+ throw new common_1.BadRequestException(`Attribute "${attributeLabel}" only accepts text values`);
816
+ }
817
+ break;
818
+ case 'number':
819
+ if (hasText || hasBoolean || hasOption) {
820
+ throw new common_1.BadRequestException(`Attribute "${attributeLabel}" only accepts number values`);
821
+ }
822
+ break;
823
+ case 'boolean':
824
+ if (hasText || hasNumber || hasOption) {
825
+ throw new common_1.BadRequestException(`Attribute "${attributeLabel}" only accepts boolean values`);
826
+ }
827
+ break;
828
+ case 'option':
829
+ if (hasText || hasNumber || hasBoolean) {
830
+ throw new common_1.BadRequestException(`Attribute "${attributeLabel}" only accepts option values`);
831
+ }
832
+ break;
833
+ default:
834
+ break;
835
+ }
836
+ }
837
+ async buildProductStructuredPayload(productId) {
838
+ var _a, _b, _c, _d, _e, _f, _g;
839
+ const product = await this.getById('products', productId, 'en');
840
+ const attributes = await this.listProductAttributes(productId);
841
+ const groups = ((_a = attributes.groups) !== null && _a !== void 0 ? _a : []).map((group) => ({
842
+ id: group.id,
843
+ slug: group.slug,
844
+ name: group.name,
845
+ attributes: group.attributes.map((attribute) => this.toAttributeSnapshot(attribute)),
846
+ }));
847
+ const flatAttributes = groups.flatMap((group) => group.attributes);
848
+ return {
849
+ product,
850
+ category: attributes.category,
851
+ groups,
852
+ attributes: flatAttributes,
853
+ comparison: {
854
+ category: {
855
+ id: (_c = (_b = attributes.category) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : null,
856
+ slug: (_e = (_d = attributes.category) === null || _d === void 0 ? void 0 : _d.slug) !== null && _e !== void 0 ? _e : null,
857
+ name: (_g = (_f = attributes.category) === null || _f === void 0 ? void 0 : _f.name) !== null && _g !== void 0 ? _g : null,
858
+ },
859
+ highlights: flatAttributes.filter((attribute) => attribute.is_highlight),
860
+ comparable_attributes: flatAttributes.filter((attribute) => attribute.is_comparison_visible),
861
+ filter_attributes: flatAttributes.filter((attribute) => attribute.is_filter_visible),
862
+ },
863
+ };
864
+ }
865
+ async materializeProductSnapshots(productId) {
866
+ const structured = await this.buildProductStructuredPayload(productId);
867
+ const specSnapshot = {
868
+ version: 1,
869
+ source: 'catalog_product_attribute_value',
870
+ category: structured.category
871
+ ? {
872
+ id: structured.category.id,
873
+ slug: structured.category.slug,
874
+ name: structured.category.name,
875
+ }
876
+ : null,
877
+ groups: structured.groups,
878
+ attributes: structured.attributes.reduce((acc, attribute) => {
879
+ acc[attribute.slug] = attribute;
880
+ return acc;
881
+ }, {}),
882
+ generated_at: new Date().toISOString(),
883
+ };
884
+ const comparisonSnapshot = {
885
+ version: 1,
886
+ source: 'catalog_product_attribute_value',
887
+ category: structured.comparison.category,
888
+ highlights: structured.comparison.highlights,
889
+ comparable_attributes: structured.comparison.comparable_attributes,
890
+ generated_at: new Date().toISOString(),
891
+ };
892
+ await this.prisma.catalog_product.update({
893
+ where: { id: productId },
894
+ data: {
895
+ // Snapshots remain secondary/derived fields for legacy reads and fast payloads.
896
+ spec_snapshot_json: specSnapshot,
897
+ comparison_snapshot_json: comparisonSnapshot,
898
+ },
899
+ });
900
+ return {
901
+ spec_snapshot_json: specSnapshot,
902
+ comparison_snapshot_json: comparisonSnapshot,
903
+ };
904
+ }
71
905
  async list(resource, locale, paginationParams, query) {
72
906
  var _a;
73
907
  const config = this.getConfig(resource, locale);
74
908
  const model = this.getModel(resource, locale);
75
909
  const where = this.buildWhere(config, paginationParams, query);
76
- return this.pagination.paginate(model, paginationParams, {
910
+ const result = await this.pagination.paginate(model, paginationParams, {
77
911
  where,
78
912
  orderBy: (_a = config.defaultOrderBy) !== null && _a !== void 0 ? _a : { id: 'desc' },
79
913
  }, locale);
914
+ if (resource === 'products' && Array.isArray(result.data)) {
915
+ return Object.assign(Object.assign({}, result), { data: await this.decorateProductRecords(result.data) });
916
+ }
917
+ return result;
80
918
  }
81
919
  async stats(resource, locale) {
920
+ var _a;
82
921
  const config = this.getConfig(resource, locale);
83
922
  const model = this.getModel(resource, locale);
84
923
  const total = await model.count({});
85
924
  const result = { total };
86
- if (config.statusField && config.activeStatusValue) {
925
+ const availableFields = Object.keys(((_a = model === null || model === void 0 ? void 0 : model.fields) !== null && _a !== void 0 ? _a : {}));
926
+ if (config.statusField &&
927
+ config.activeStatusValue &&
928
+ availableFields.includes(config.statusField)) {
87
929
  result.active = await model.count({
88
930
  where: {
89
931
  [config.statusField]: config.activeStatusValue,
@@ -93,6 +935,44 @@ let CatalogService = class CatalogService {
93
935
  return result;
94
936
  }
95
937
  async getById(resource, id, locale) {
938
+ if (resource === 'products') {
939
+ const item = await this.prisma.catalog_product.findUnique({
940
+ where: { id },
941
+ include: {
942
+ catalog_brand: {
943
+ select: {
944
+ id: true,
945
+ name: true,
946
+ slug: true,
947
+ logo_file_id: true,
948
+ },
949
+ },
950
+ catalog_category: {
951
+ select: {
952
+ id: true,
953
+ name: true,
954
+ slug: true,
955
+ },
956
+ },
957
+ catalog_product_image: {
958
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
959
+ select: {
960
+ id: true,
961
+ file_id: true,
962
+ role: true,
963
+ sort_order: true,
964
+ is_primary: true,
965
+ alt_text: true,
966
+ },
967
+ },
968
+ },
969
+ });
970
+ if (!item) {
971
+ throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('resourceNotFound', locale, 'Catalog resource not found'));
972
+ }
973
+ const [decorated] = await this.decorateProductRecords([item]);
974
+ return decorated;
975
+ }
96
976
  const model = this.getModel(resource, locale);
97
977
  const item = await model.findUnique({ where: { id } });
98
978
  if (!item) {
@@ -132,11 +1012,245 @@ let CatalogService = class CatalogService {
132
1012
  },
133
1013
  }, locale);
134
1014
  }
1015
+ async getCategoriesTree() {
1016
+ const categories = await this.prisma.catalog_category.findMany({
1017
+ orderBy: [{ sort_order: 'asc' }, { name: 'asc' }],
1018
+ });
1019
+ return this.normalizeCategoryTree(categories);
1020
+ }
1021
+ async listCategoryAttributes(categoryId) {
1022
+ return this.buildCategoryAttributePayload(categoryId);
1023
+ }
1024
+ async listProductAttributes(productId) {
1025
+ const product = await this.prisma.catalog_product.findUnique({
1026
+ where: { id: productId },
1027
+ });
1028
+ if (!product) {
1029
+ throw new common_1.NotFoundException('Catalog product not found');
1030
+ }
1031
+ return this.buildCategoryAttributePayload(product.catalog_category_id, productId);
1032
+ }
1033
+ async getProductStructuredPayload(productId) {
1034
+ return this.buildProductStructuredPayload(productId);
1035
+ }
1036
+ async getProductComparisonPayload(productId) {
1037
+ const structured = await this.buildProductStructuredPayload(productId);
1038
+ return structured.comparison;
1039
+ }
1040
+ async updateProductAttributes(productId, values) {
1041
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
1042
+ const product = await this.prisma.catalog_product.findUnique({
1043
+ where: { id: productId },
1044
+ });
1045
+ if (!product) {
1046
+ throw new common_1.NotFoundException('Catalog product not found');
1047
+ }
1048
+ const categoryAttributes = await this.prisma.catalog_category_attribute.findMany({
1049
+ where: { catalog_category_id: product.catalog_category_id },
1050
+ });
1051
+ const allowedAttributeIds = new Set(categoryAttributes.map((item) => item.attribute_id));
1052
+ const requiredAttributeIds = new Set(categoryAttributes
1053
+ .filter((item) => item.is_required)
1054
+ .map((item) => item.attribute_id));
1055
+ const attributes = allowedAttributeIds.size
1056
+ ? await this.prisma.catalog_attribute.findMany({
1057
+ where: { id: { in: [...allowedAttributeIds] } },
1058
+ select: {
1059
+ id: true,
1060
+ slug: true,
1061
+ name: true,
1062
+ data_type: true,
1063
+ },
1064
+ })
1065
+ : [];
1066
+ const attributeMap = new Map(attributes.map((item) => [item.id, item]));
1067
+ const existingValues = await this.prisma.catalog_product_attribute_value.findMany({
1068
+ where: { product_id: productId },
1069
+ });
1070
+ const optionIds = values
1071
+ .map((value) => value.attribute_option_id)
1072
+ .filter((value) => typeof value === 'number');
1073
+ const options = optionIds.length
1074
+ ? await this.prisma.catalog_attribute_option.findMany({
1075
+ where: { id: { in: optionIds } },
1076
+ })
1077
+ : [];
1078
+ const optionMap = new Map(options.map((item) => [item.id, item]));
1079
+ const incomingByAttribute = new Map();
1080
+ for (const value of values) {
1081
+ const attributeId = Number((_a = value.attribute_id) !== null && _a !== void 0 ? _a : 0);
1082
+ if (!attributeId || !allowedAttributeIds.has(attributeId)) {
1083
+ throw new common_1.BadRequestException(`Attribute ${attributeId} is not allowed for this category`);
1084
+ }
1085
+ const attribute = attributeMap.get(attributeId);
1086
+ if (!attribute) {
1087
+ throw new common_1.BadRequestException(`Attribute ${attributeId} was not found`);
1088
+ }
1089
+ this.validateAttributeValueByType(attribute, value);
1090
+ incomingByAttribute.set(attributeId, value);
1091
+ }
1092
+ const incomingAttributeIds = new Set(incomingByAttribute.keys());
1093
+ for (const attributeId of requiredAttributeIds) {
1094
+ const requiredValue = incomingByAttribute.get(attributeId);
1095
+ if (!requiredValue || !this.isMeaningfulAttributeValue(requiredValue)) {
1096
+ const attribute = attributeMap.get(attributeId);
1097
+ throw new common_1.BadRequestException(`Attribute "${(_c = (_b = attribute === null || attribute === void 0 ? void 0 : attribute.name) !== null && _b !== void 0 ? _b : attribute === null || attribute === void 0 ? void 0 : attribute.slug) !== null && _c !== void 0 ? _c : attributeId}" is required for this category`);
1098
+ }
1099
+ }
1100
+ for (const existingValue of existingValues) {
1101
+ if (!incomingAttributeIds.has(existingValue.attribute_id)) {
1102
+ await this.prisma.catalog_product_attribute_value.delete({
1103
+ where: { id: existingValue.id },
1104
+ });
1105
+ }
1106
+ }
1107
+ for (const [attributeId, value] of incomingByAttribute.entries()) {
1108
+ const option = value.attribute_option_id ? optionMap.get(value.attribute_option_id) : null;
1109
+ const attribute = attributeMap.get(attributeId);
1110
+ if (value.attribute_option_id && (!option || option.attribute_id !== attributeId)) {
1111
+ throw new common_1.BadRequestException(`Option ${value.attribute_option_id} does not belong to attribute ${(_d = attribute === null || attribute === void 0 ? void 0 : attribute.name) !== null && _d !== void 0 ? _d : attributeId}`);
1112
+ }
1113
+ const normalizedText = (_h = (_g = (_f = (_e = value.normalized_text) !== null && _e !== void 0 ? _e : option === null || option === void 0 ? void 0 : option.normalized_value) !== null && _f !== void 0 ? _f : option === null || option === void 0 ? void 0 : option.option_value) !== null && _g !== void 0 ? _g : value.value_text) !== null && _h !== void 0 ? _h : null;
1114
+ const sourceType = value.source_type === 'import' || value.source_type === 'computed'
1115
+ ? value.source_type
1116
+ : 'manual';
1117
+ const payload = {
1118
+ attribute_option_id: (_j = value.attribute_option_id) !== null && _j !== void 0 ? _j : null,
1119
+ value_text: (_k = option === null || option === void 0 ? void 0 : option.option_value) !== null && _k !== void 0 ? _k : (String((_l = value.value_text) !== null && _l !== void 0 ? _l : '').trim() || null),
1120
+ value_number: (_m = value.value_number) !== null && _m !== void 0 ? _m : null,
1121
+ value_boolean: (_o = value.value_boolean) !== null && _o !== void 0 ? _o : null,
1122
+ raw_value: (_p = option === null || option === void 0 ? void 0 : option.option_value) !== null && _p !== void 0 ? _p : (value.value_number !== undefined && value.value_number !== null
1123
+ ? String(value.value_number)
1124
+ : value.value_boolean !== undefined && value.value_boolean !== null
1125
+ ? String(value.value_boolean)
1126
+ : String((_q = value.value_text) !== null && _q !== void 0 ? _q : '').trim() || null),
1127
+ value_unit: String((_r = value.value_unit) !== null && _r !== void 0 ? _r : '').trim() || null,
1128
+ normalized_value: normalizedText
1129
+ ? String(normalizedText).trim()
1130
+ : value.value_number !== undefined && value.value_number !== null
1131
+ ? String(value.value_number)
1132
+ : value.value_boolean !== undefined && value.value_boolean !== null
1133
+ ? String(value.value_boolean)
1134
+ : null,
1135
+ normalized_text: normalizedText ? String(normalizedText).trim() : null,
1136
+ normalized_number: (_t = (_s = value.normalized_number) !== null && _s !== void 0 ? _s : value.value_number) !== null && _t !== void 0 ? _t : null,
1137
+ source_type: sourceType,
1138
+ confidence_score: (_u = value.confidence_score) !== null && _u !== void 0 ? _u : null,
1139
+ is_verified: Boolean((_v = value.is_verified) !== null && _v !== void 0 ? _v : false),
1140
+ };
1141
+ const existingValue = existingValues.find((item) => item.attribute_id === attributeId);
1142
+ if (!this.isMeaningfulAttributeValue(payload)) {
1143
+ if (existingValue) {
1144
+ await this.prisma.catalog_product_attribute_value.delete({
1145
+ where: { id: existingValue.id },
1146
+ });
1147
+ }
1148
+ continue;
1149
+ }
1150
+ if (existingValue) {
1151
+ const updatePayload = {
1152
+ attribute_option_id: payload.attribute_option_id,
1153
+ value_text: payload.value_text,
1154
+ value_number: payload.value_number,
1155
+ value_boolean: payload.value_boolean,
1156
+ raw_value: payload.raw_value,
1157
+ value_unit: payload.value_unit,
1158
+ normalized_value: payload.normalized_value,
1159
+ normalized_text: payload.normalized_text,
1160
+ normalized_number: payload.normalized_number,
1161
+ source_type: payload.source_type,
1162
+ confidence_score: payload.confidence_score,
1163
+ is_verified: payload.is_verified,
1164
+ };
1165
+ await this.prisma.catalog_product_attribute_value.update({
1166
+ where: { id: existingValue.id },
1167
+ data: updatePayload,
1168
+ });
1169
+ }
1170
+ else {
1171
+ const createPayload = {
1172
+ product_id: productId,
1173
+ attribute_id: attributeId,
1174
+ attribute_option_id: payload.attribute_option_id,
1175
+ value_text: payload.value_text,
1176
+ value_number: payload.value_number,
1177
+ value_boolean: payload.value_boolean,
1178
+ raw_value: payload.raw_value,
1179
+ value_unit: payload.value_unit,
1180
+ normalized_value: payload.normalized_value,
1181
+ normalized_text: payload.normalized_text,
1182
+ normalized_number: payload.normalized_number,
1183
+ source_type: payload.source_type,
1184
+ confidence_score: payload.confidence_score,
1185
+ is_verified: payload.is_verified,
1186
+ };
1187
+ await this.prisma.catalog_product_attribute_value.create({
1188
+ data: createPayload,
1189
+ });
1190
+ }
1191
+ }
1192
+ await this.materializeProductSnapshots(productId);
1193
+ return this.listProductAttributes(productId);
1194
+ }
1195
+ async generateFormAssistSuggestion(resource, input, locale) {
1196
+ var _a, _b, _c, _d, _e, _f;
1197
+ const config = this.getConfig(resource, locale);
1198
+ const fieldContext = this.normalizeAiFieldContext(resource, (_a = input.fields) !== null && _a !== void 0 ? _a : []);
1199
+ const currentValues = (_b = input.current_values) !== null && _b !== void 0 ? _b : {};
1200
+ const warnings = [];
1201
+ const categoryId = resource === 'products'
1202
+ ? Number((_c = currentValues.catalog_category_id) !== null && _c !== void 0 ? _c : 0) || null
1203
+ : null;
1204
+ const productAttributeContext = categoryId
1205
+ ? this.buildAttributeContext(await this.buildCategoryAttributePayload(categoryId), (_d = input.current_attribute_values) !== null && _d !== void 0 ? _d : [])
1206
+ : [];
1207
+ const systemPrompt = this.buildAiSystemPrompt(resource, locale, fieldContext, currentValues, productAttributeContext);
1208
+ const aiResponse = await this.aiService.chat({
1209
+ provider: 'openai',
1210
+ model: 'gpt-4o-mini',
1211
+ message: input.prompt,
1212
+ systemPrompt,
1213
+ });
1214
+ const parsed = this.extractJsonObject(String((_e = aiResponse.content) !== null && _e !== void 0 ? _e : ''));
1215
+ const rawFields = parsed.fields && typeof parsed.fields === 'object'
1216
+ ? parsed.fields
1217
+ : {};
1218
+ const normalizedFields = {};
1219
+ for (const field of fieldContext) {
1220
+ if (!Object.prototype.hasOwnProperty.call(rawFields, field.key)) {
1221
+ continue;
1222
+ }
1223
+ const normalizedValue = await this.normalizeAiFieldSuggestion(field, rawFields[field.key], warnings);
1224
+ if (normalizedValue !== undefined) {
1225
+ normalizedFields[field.key] = normalizedValue;
1226
+ }
1227
+ }
1228
+ const productAttributes = await this.normalizeAiProductAttributeSuggestions(categoryId, parsed.product_attributes, (_f = input.current_attribute_values) !== null && _f !== void 0 ? _f : [], warnings);
1229
+ const appliedFields = fieldContext
1230
+ .filter((field) => Object.prototype.hasOwnProperty.call(normalizedFields, field.key))
1231
+ .map((field) => ({
1232
+ key: field.key,
1233
+ label: field.label,
1234
+ type: field.type,
1235
+ value: normalizedFields[field.key],
1236
+ }));
1237
+ return {
1238
+ resource: config.resource,
1239
+ fields: normalizedFields,
1240
+ applied_fields: appliedFields,
1241
+ product_attributes: productAttributes,
1242
+ warnings: [
1243
+ ...warnings,
1244
+ ...(Array.isArray(parsed.notes) ? parsed.notes.map((note) => String(note)) : []),
1245
+ ],
1246
+ };
1247
+ }
135
1248
  };
136
1249
  exports.CatalogService = CatalogService;
137
1250
  exports.CatalogService = CatalogService = __decorate([
138
1251
  (0, common_1.Injectable)(),
139
1252
  __metadata("design:paramtypes", [api_prisma_1.PrismaService,
140
- api_pagination_1.PaginationService])
1253
+ api_pagination_1.PaginationService,
1254
+ core_1.AiService])
141
1255
  ], CatalogService);
142
1256
  //# sourceMappingURL=catalog.service.js.map