@hed-hog/catalog 0.0.293 → 0.0.294

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 (45) hide show
  1. package/README.md +409 -379
  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 +1111 -5
  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 +133 -99
  21. package/hedhog/data/route.yaml +72 -8
  22. package/hedhog/frontend/app/[resource]/page.tsx.ejs +391 -33
  23. package/hedhog/frontend/app/_components/catalog-ai-form-assist-dialog.tsx.ejs +340 -0
  24. package/hedhog/frontend/app/_components/catalog-resource-form-sheet.tsx.ejs +907 -92
  25. package/hedhog/frontend/app/_lib/catalog-resources.tsx.ejs +929 -1161
  26. package/hedhog/frontend/messages/en.json +389 -299
  27. package/hedhog/frontend/messages/pt.json +389 -299
  28. package/hedhog/table/catalog_attribute.yaml +67 -52
  29. package/hedhog/table/catalog_attribute_option.yaml +40 -0
  30. package/hedhog/table/catalog_category.yaml +40 -0
  31. package/hedhog/table/catalog_category_attribute.yaml +37 -31
  32. package/hedhog/table/catalog_comparison.yaml +19 -22
  33. package/hedhog/table/catalog_product.yaml +30 -28
  34. package/hedhog/table/catalog_product_attribute_value.yaml +44 -31
  35. package/hedhog/table/catalog_product_category.yaml +13 -13
  36. package/hedhog/table/catalog_score_criterion.yaml +42 -25
  37. package/hedhog/table/catalog_seo_page_rule.yaml +10 -10
  38. package/hedhog/table/catalog_similarity_rule.yaml +33 -20
  39. package/hedhog/table/catalog_site.yaml +21 -13
  40. package/hedhog/table/catalog_site_category.yaml +12 -12
  41. package/package.json +6 -6
  42. package/src/catalog-resource.config.ts +132 -105
  43. package/src/catalog.controller.ts +91 -24
  44. package/src/catalog.module.ts +16 -12
  45. package/src/catalog.service.ts +1569 -56
@@ -1,15 +1,96 @@
1
- import { getLocaleText } from '@hed-hog/api-locale';
2
- import { PaginationDTO, PaginationService } from '@hed-hog/api-pagination';
3
- import { PrismaService } from '@hed-hog/api-prisma';
4
- import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
5
- import { CatalogResourceConfig, catalogResourceMap } from './catalog-resource.config';
6
-
7
- @Injectable()
8
- export class CatalogService {
9
- constructor(
10
- private readonly prisma: PrismaService,
11
- private readonly pagination: PaginationService,
12
- ) {}
1
+ import { getLocaleText } from '@hed-hog/api-locale';
2
+ import { PaginationDTO, PaginationService } from '@hed-hog/api-pagination';
3
+ import {
4
+ Prisma,
5
+ PrismaService,
6
+ type catalog_product_attribute_value_source_type_enum,
7
+ } from '@hed-hog/api-prisma';
8
+ import { AiService } from '@hed-hog/core';
9
+ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
10
+ import { CatalogResourceConfig, catalogResourceMap } from './catalog-resource.config';
11
+
12
+ type CatalogAttributeValueInput = {
13
+ attribute_id?: number;
14
+ attribute_option_id?: number | null;
15
+ value_text?: string | null;
16
+ value_number?: number | null;
17
+ value_boolean?: boolean | null;
18
+ raw_value?: string | null;
19
+ value_unit?: string | null;
20
+ normalized_value?: string | null;
21
+ normalized_text?: string | null;
22
+ normalized_number?: number | null;
23
+ source_type?: string | null;
24
+ confidence_score?: number | null;
25
+ is_verified?: boolean | null;
26
+ };
27
+
28
+ type CatalogAttributeGroupPayload = {
29
+ id: number | null;
30
+ slug: string;
31
+ name: string;
32
+ attributes: Array<Record<string, any>>;
33
+ };
34
+
35
+ type CatalogAttributeSnapshotPayload = {
36
+ slug: string;
37
+ name: string;
38
+ data_type: string;
39
+ unit: string | null;
40
+ group_name: string;
41
+ is_required: boolean;
42
+ is_highlight: boolean;
43
+ is_filter_visible: boolean;
44
+ is_comparison_visible: boolean;
45
+ value: string | number | boolean | null;
46
+ value_text: string | null;
47
+ value_number: number | null;
48
+ value_boolean: boolean | null;
49
+ normalized_value: string | null;
50
+ raw_value: string | null;
51
+ option: {
52
+ id: number;
53
+ slug: string;
54
+ label: string;
55
+ option_value: string;
56
+ } | null;
57
+ };
58
+
59
+ type ProductRecordWithRelations = Record<string, any> & {
60
+ brand_id?: number | null;
61
+ catalog_category_id?: number | null;
62
+ };
63
+
64
+ type CatalogAiFieldContext = {
65
+ key: string;
66
+ label: string;
67
+ type: string;
68
+ required: boolean;
69
+ options: Array<{
70
+ value: string;
71
+ label: string;
72
+ }>;
73
+ relation?: {
74
+ endpoint?: string;
75
+ resource?: string;
76
+ labelKeys?: string[];
77
+ } | null;
78
+ };
79
+
80
+ type CatalogAiAssistInput = {
81
+ prompt: string;
82
+ current_values?: Record<string, unknown>;
83
+ fields?: Record<string, unknown>[];
84
+ current_attribute_values?: Record<string, unknown>[];
85
+ };
86
+
87
+ @Injectable()
88
+ export class CatalogService {
89
+ constructor(
90
+ private readonly prisma: PrismaService,
91
+ private readonly pagination: PaginationService,
92
+ private readonly aiService: AiService,
93
+ ) {}
13
94
 
14
95
  private getConfig(resource: string, locale: string): CatalogResourceConfig {
15
96
  const config = catalogResourceMap.get(resource);
@@ -28,7 +109,7 @@ export class CatalogService {
28
109
  return this.prisma[config.model];
29
110
  }
30
111
 
31
- private normalizeValue(value: unknown) {
112
+ private normalizeValue(value: unknown) {
32
113
  if (value === 'true') {
33
114
  return true;
34
115
  }
@@ -41,24 +122,666 @@ export class CatalogService {
41
122
  return value.includes('.') ? Number(value) : Number.parseInt(value, 10);
42
123
  }
43
124
 
44
- return value;
45
- }
46
-
47
- private sanitizePayload(config: CatalogResourceConfig, body: Record<string, unknown>) {
48
- const payload: Record<string, unknown> = {};
49
-
50
- for (const field of config.fields) {
51
- if (Object.prototype.hasOwnProperty.call(body, field) && body[field] !== undefined) {
52
- payload[field] = body[field];
53
- }
54
- }
125
+ return value;
126
+ }
127
+
128
+ private extractJsonObject(content: string) {
129
+ const trimmed = String(content ?? '').trim();
130
+
131
+ if (!trimmed) {
132
+ throw new BadRequestException('AI returned an empty response');
133
+ }
134
+
135
+ const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
136
+ const candidate = fencedMatch?.[1]?.trim() || trimmed;
137
+
138
+ try {
139
+ return JSON.parse(candidate) as Record<string, unknown>;
140
+ } catch {
141
+ const firstBraceIndex = candidate.indexOf('{');
142
+ const lastBraceIndex = candidate.lastIndexOf('}');
143
+
144
+ if (firstBraceIndex >= 0 && lastBraceIndex > firstBraceIndex) {
145
+ try {
146
+ return JSON.parse(candidate.slice(firstBraceIndex, lastBraceIndex + 1)) as Record<string, unknown>;
147
+ } catch {
148
+ throw new BadRequestException('AI returned an invalid JSON payload');
149
+ }
150
+ }
151
+
152
+ throw new BadRequestException('AI returned an invalid JSON payload');
153
+ }
154
+ }
155
+
156
+ private normalizeComparableText(value: unknown) {
157
+ return String(value ?? '')
158
+ .normalize('NFD')
159
+ .replace(/[\u0300-\u036f]/g, '')
160
+ .trim()
161
+ .toLowerCase();
162
+ }
163
+
164
+ private normalizeAiFieldContext(
165
+ resource: string,
166
+ fields: Record<string, unknown>[],
167
+ ) {
168
+ const config = catalogResourceMap.get(resource);
169
+
170
+ if (!config) {
171
+ return [];
172
+ }
173
+
174
+ const allowedKeys = new Set(config.fields);
175
+
176
+ return fields
177
+ .map((field) => {
178
+ const key = String(field.key ?? '').trim();
179
+
180
+ if (!key || !allowedKeys.has(key)) {
181
+ return null;
182
+ }
183
+
184
+ const options = Array.isArray(field.options)
185
+ ? field.options
186
+ .map((option) => ({
187
+ value: String((option as Record<string, unknown>).value ?? '').trim(),
188
+ label: String((option as Record<string, unknown>).label ?? '').trim(),
189
+ }))
190
+ .filter((option) => option.value && option.label)
191
+ : [];
192
+ const relationData =
193
+ field.relation && typeof field.relation === 'object'
194
+ ? (field.relation as Record<string, unknown>)
195
+ : null;
196
+
197
+ return {
198
+ key,
199
+ label: String(field.label ?? key),
200
+ type: String(field.type ?? 'text'),
201
+ required: Boolean(field.required ?? false),
202
+ options,
203
+ relation: relationData
204
+ ? {
205
+ endpoint: relationData.endpoint
206
+ ? String(relationData.endpoint)
207
+ : undefined,
208
+ resource: relationData.resource
209
+ ? String(relationData.resource)
210
+ : undefined,
211
+ labelKeys: Array.isArray(relationData.labelKeys)
212
+ ? relationData.labelKeys.map((item) => String(item))
213
+ : [],
214
+ }
215
+ : null,
216
+ } satisfies CatalogAiFieldContext;
217
+ })
218
+ .filter(Boolean) as CatalogAiFieldContext[];
219
+ }
220
+
221
+ private normalizeBooleanSuggestion(value: unknown) {
222
+ if (typeof value === 'boolean') {
223
+ return value;
224
+ }
225
+
226
+ if (typeof value === 'number') {
227
+ return value !== 0;
228
+ }
229
+
230
+ const normalized = this.normalizeComparableText(value);
231
+
232
+ if (!normalized) {
233
+ return null;
234
+ }
235
+
236
+ if (['true', '1', 'yes', 'y', 'sim', 'ativo', 'active', 'enabled'].includes(normalized)) {
237
+ return true;
238
+ }
239
+
240
+ if (['false', '0', 'no', 'n', 'nao', 'não', 'inativo', 'inactive', 'disabled'].includes(normalized)) {
241
+ return false;
242
+ }
243
+
244
+ return null;
245
+ }
246
+
247
+ private normalizeNumberSuggestion(value: unknown) {
248
+ if (typeof value === 'number') {
249
+ return Number.isFinite(value) ? value : null;
250
+ }
251
+
252
+ const raw = String(value ?? '').trim();
253
+
254
+ if (!raw) {
255
+ return null;
256
+ }
257
+
258
+ const normalized = raw.replace(/[^\d,.\-]/g, '').replace(',', '.');
259
+ const parsed = Number(normalized);
260
+ return Number.isFinite(parsed) ? parsed : null;
261
+ }
262
+
263
+ private normalizeSelectSuggestion(
264
+ rawValue: unknown,
265
+ options: Array<{ value: string; label: string }>,
266
+ ) {
267
+ const normalized = this.normalizeComparableText(rawValue);
268
+
269
+ if (!normalized) {
270
+ return null;
271
+ }
272
+
273
+ const exact = options.find((option) => {
274
+ return (
275
+ this.normalizeComparableText(option.value) === normalized ||
276
+ this.normalizeComparableText(option.label) === normalized
277
+ );
278
+ });
279
+
280
+ if (exact) {
281
+ return exact.value;
282
+ }
283
+
284
+ const partial = options.find((option) => {
285
+ return (
286
+ this.normalizeComparableText(option.value).includes(normalized) ||
287
+ normalized.includes(this.normalizeComparableText(option.value)) ||
288
+ this.normalizeComparableText(option.label).includes(normalized) ||
289
+ normalized.includes(this.normalizeComparableText(option.label))
290
+ );
291
+ });
292
+
293
+ return partial?.value ?? null;
294
+ }
295
+
296
+ private async resolveRelationSuggestion(
297
+ field: CatalogAiFieldContext,
298
+ rawValue: unknown,
299
+ ) {
300
+ if (rawValue === null || rawValue === undefined || rawValue === '') {
301
+ return null;
302
+ }
303
+
304
+ const relation = field.relation;
305
+
306
+ if (!relation) {
307
+ return null;
308
+ }
309
+
310
+ const modelInfo = (() => {
311
+ if (relation.resource) {
312
+ const config = catalogResourceMap.get(relation.resource);
313
+
314
+ if (config) {
315
+ return {
316
+ model: config.model,
317
+ searchFields:
318
+ relation.labelKeys?.length ? relation.labelKeys : config.searchFields,
319
+ idField: 'id',
320
+ };
321
+ }
322
+ }
323
+
324
+ if (relation.endpoint === '/locale') {
325
+ return {
326
+ model: 'locale',
327
+ searchFields: relation.labelKeys?.length ? relation.labelKeys : ['name', 'code'],
328
+ idField: 'id',
329
+ };
330
+ }
331
+
332
+ if (relation.endpoint === '/content') {
333
+ return {
334
+ model: 'content',
335
+ searchFields: relation.labelKeys?.length ? relation.labelKeys : ['title', 'slug'],
336
+ idField: 'id',
337
+ };
338
+ }
339
+
340
+ return null;
341
+ })();
342
+
343
+ if (!modelInfo) {
344
+ return null;
345
+ }
346
+
347
+ const model = (this.prisma as Record<string, any>)[modelInfo.model];
348
+
349
+ if (!model?.findMany) {
350
+ return null;
351
+ }
352
+
353
+ const numericId = this.normalizeNumberSuggestion(rawValue);
354
+ if (numericId && Number.isInteger(numericId)) {
355
+ const byId = await model.findUnique({
356
+ where: { [modelInfo.idField]: numericId },
357
+ });
358
+
359
+ if (byId) {
360
+ return Number(byId[modelInfo.idField]);
361
+ }
362
+ }
363
+
364
+ const needle = String(rawValue ?? '').trim();
365
+
366
+ if (!needle) {
367
+ return null;
368
+ }
369
+
370
+ const results = await model.findMany({
371
+ where: {
372
+ OR: modelInfo.searchFields.map((fieldKey) => ({
373
+ [fieldKey]: {
374
+ contains: needle,
375
+ mode: 'insensitive',
376
+ },
377
+ })),
378
+ },
379
+ take: 5,
380
+ });
381
+
382
+ if (!results.length) {
383
+ return null;
384
+ }
385
+
386
+ const normalizedNeedle = this.normalizeComparableText(needle);
387
+ const exact = results.find((result: Record<string, unknown>) =>
388
+ modelInfo.searchFields.some((fieldKey) => {
389
+ return this.normalizeComparableText(result[fieldKey]) === normalizedNeedle;
390
+ }),
391
+ );
392
+
393
+ if (exact) {
394
+ return Number(exact[modelInfo.idField]);
395
+ }
396
+
397
+ return results.length === 1 ? Number(results[0][modelInfo.idField]) : null;
398
+ }
399
+
400
+ private async normalizeAiFieldSuggestion(
401
+ field: CatalogAiFieldContext,
402
+ rawValue: unknown,
403
+ warnings: string[],
404
+ ) {
405
+ if (rawValue === undefined) {
406
+ return undefined;
407
+ }
408
+
409
+ if (rawValue === null) {
410
+ return null;
411
+ }
412
+
413
+ switch (field.type) {
414
+ case 'switch': {
415
+ const value = this.normalizeBooleanSuggestion(rawValue);
416
+
417
+ if (value === null) {
418
+ warnings.push(`Boolean field "${field.label}" could not be resolved safely.`);
419
+ return undefined;
420
+ }
421
+
422
+ return value;
423
+ }
424
+ case 'number':
425
+ case 'currency': {
426
+ const value = this.normalizeNumberSuggestion(rawValue);
427
+
428
+ if (value === null) {
429
+ warnings.push(`Numeric field "${field.label}" could not be resolved safely.`);
430
+ return undefined;
431
+ }
432
+
433
+ return value;
434
+ }
435
+ case 'select': {
436
+ const value = this.normalizeSelectSuggestion(rawValue, field.options);
437
+
438
+ if (!value) {
439
+ warnings.push(`Select field "${field.label}" returned an invalid option.`);
440
+ return undefined;
441
+ }
442
+
443
+ return value;
444
+ }
445
+ case 'relation': {
446
+ const value = await this.resolveRelationSuggestion(field, rawValue);
447
+
448
+ if (!value) {
449
+ warnings.push(`Relation field "${field.label}" could not be resolved safely.`);
450
+ return undefined;
451
+ }
452
+
453
+ return value;
454
+ }
455
+ case 'upload':
456
+ warnings.push(`File field "${field.label}" must still be filled manually.`);
457
+ return undefined;
458
+ case 'json':
459
+ if (typeof rawValue === 'object') {
460
+ return rawValue;
461
+ }
462
+
463
+ try {
464
+ return JSON.parse(String(rawValue));
465
+ } catch {
466
+ warnings.push(`JSON field "${field.label}" returned an invalid value.`);
467
+ return undefined;
468
+ }
469
+ case 'date':
470
+ case 'datetime':
471
+ case 'text':
472
+ case 'url':
473
+ case 'textarea':
474
+ case 'richtext':
475
+ default:
476
+ return String(rawValue).trim() || null;
477
+ }
478
+ }
479
+
480
+ private buildCurrentAttributeValueMap(values: Record<string, unknown>[]) {
481
+ const valueMap = new Map<number, Record<string, unknown>>();
482
+
483
+ for (const value of values) {
484
+ const attributeId = Number(value.attribute_id ?? 0);
485
+
486
+ if (!attributeId) {
487
+ continue;
488
+ }
489
+
490
+ valueMap.set(attributeId, value);
491
+ }
492
+
493
+ return valueMap;
494
+ }
495
+
496
+ private buildAttributeContext(
497
+ attributesPayload: Awaited<ReturnType<CatalogService['buildCategoryAttributePayload']>>,
498
+ currentAttributeValues: Record<string, unknown>[],
499
+ ) {
500
+ const currentMap = this.buildCurrentAttributeValueMap(currentAttributeValues);
501
+
502
+ return (attributesPayload.groups ?? []).flatMap((group) =>
503
+ group.attributes.map((attribute) => {
504
+ const current = currentMap.get(Number(attribute.id)) ?? attribute.value ?? null;
505
+ const relation = (attribute.category_attribute ?? {}) as Record<string, unknown>;
506
+
507
+ return {
508
+ id: Number(attribute.id),
509
+ slug: String(attribute.slug ?? ''),
510
+ name: String(attribute.name ?? attribute.slug ?? ''),
511
+ data_type: String(attribute.data_type ?? 'text'),
512
+ unit: attribute.unit ? String(attribute.unit) : null,
513
+ group_name: String(group.name ?? attribute.group_name ?? 'General'),
514
+ is_required: Boolean(relation.is_required ?? false),
515
+ is_highlight: Boolean(relation.is_highlight ?? false),
516
+ is_filter_visible: Boolean(relation.is_filter_visible ?? false),
517
+ is_comparison_visible: Boolean(relation.is_comparison_visible ?? false),
518
+ options: Array.isArray(attribute.options)
519
+ ? attribute.options.map((option) => ({
520
+ id: Number(option.id),
521
+ slug: String(option.slug ?? ''),
522
+ label: String(option.label ?? option.option_value ?? ''),
523
+ option_value: String(option.option_value ?? ''),
524
+ normalized_value: option.normalized_value
525
+ ? String(option.normalized_value)
526
+ : null,
527
+ }))
528
+ : [],
529
+ current_value: current,
530
+ };
531
+ }),
532
+ );
533
+ }
534
+
535
+ private async normalizeAiProductAttributeSuggestions(
536
+ categoryId: number | null,
537
+ rawSuggestions: unknown,
538
+ currentAttributeValues: Record<string, unknown>[],
539
+ warnings: string[],
540
+ ) {
541
+ if (!categoryId || rawSuggestions === undefined || rawSuggestions === null) {
542
+ return [];
543
+ }
544
+
545
+ const attributesPayload = await this.buildCategoryAttributePayload(categoryId);
546
+ const attributeContext = this.buildAttributeContext(
547
+ attributesPayload,
548
+ currentAttributeValues,
549
+ );
550
+
551
+ const normalizedEntries = Array.isArray(rawSuggestions)
552
+ ? rawSuggestions
553
+ : rawSuggestions && typeof rawSuggestions === 'object'
554
+ ? Object.entries(rawSuggestions as Record<string, unknown>).map(
555
+ ([slug, value]) => ({
556
+ slug,
557
+ ...(value && typeof value === 'object'
558
+ ? (value as Record<string, unknown>)
559
+ : { value }),
560
+ }),
561
+ )
562
+ : [];
563
+
564
+ const normalizedSuggestions: Record<string, unknown>[] = [];
565
+
566
+ for (const entry of normalizedEntries) {
567
+ const entryRecord = (
568
+ entry && typeof entry === 'object'
569
+ ? entry
570
+ : { value: entry }
571
+ ) as Record<string, unknown>;
572
+ const rawIdentifier =
573
+ entryRecord.slug ??
574
+ entryRecord.attribute_slug ??
575
+ entryRecord.code ??
576
+ entryRecord.name ??
577
+ entryRecord.attribute ??
578
+ null;
579
+ const normalizedIdentifier = this.normalizeComparableText(rawIdentifier);
580
+
581
+ const attribute = attributeContext.find((item) => {
582
+ return (
583
+ item.id === Number(entryRecord.attribute_id ?? 0) ||
584
+ this.normalizeComparableText(item.slug) === normalizedIdentifier ||
585
+ this.normalizeComparableText(item.name) === normalizedIdentifier
586
+ );
587
+ });
588
+
589
+ if (!attribute) {
590
+ if (rawIdentifier) {
591
+ warnings.push(`Structured attribute "${String(rawIdentifier)}" is not available for the selected category.`);
592
+ }
593
+ continue;
594
+ }
595
+
596
+ const rawValue =
597
+ entryRecord.value ??
598
+ entryRecord.value_text ??
599
+ entryRecord.value_number ??
600
+ entryRecord.value_boolean ??
601
+ entryRecord.option ??
602
+ entryRecord.option_value ??
603
+ entryRecord.label;
604
+ const draft: Record<string, unknown> = {
605
+ attribute_id: attribute.id,
606
+ attribute_slug: attribute.slug,
607
+ attribute_name: attribute.name,
608
+ data_type: attribute.data_type,
609
+ group_name: attribute.group_name,
610
+ value_unit: attribute.unit ?? null,
611
+ };
612
+
613
+ if (attribute.data_type === 'option') {
614
+ const normalizedOption = this.normalizeComparableText(
615
+ entryRecord.option ??
616
+ entryRecord.option_value ??
617
+ entryRecord.label ??
618
+ rawValue,
619
+ );
620
+ const option = attribute.options.find((item) => {
621
+ return (
622
+ this.normalizeComparableText(item.option_value) === normalizedOption ||
623
+ this.normalizeComparableText(item.label) === normalizedOption ||
624
+ this.normalizeComparableText(item.slug) === normalizedOption
625
+ );
626
+ });
627
+
628
+ if (!option) {
629
+ warnings.push(`Option value for "${attribute.name}" could not be resolved safely.`);
630
+ continue;
631
+ }
632
+
633
+ draft.attribute_option_id = option.id;
634
+ draft.value_text = option.option_value;
635
+ } else if (attribute.data_type === 'number') {
636
+ const numberValue = this.normalizeNumberSuggestion(rawValue);
637
+
638
+ if (numberValue === null) {
639
+ warnings.push(`Numeric attribute "${attribute.name}" could not be resolved safely.`);
640
+ continue;
641
+ }
642
+
643
+ draft.value_number = numberValue;
644
+ draft.raw_value = String(numberValue);
645
+ draft.normalized_value = String(numberValue);
646
+ if (entryRecord.unit) {
647
+ draft.value_unit = String(entryRecord.unit).trim() || attribute.unit || null;
648
+ }
649
+ } else if (attribute.data_type === 'boolean') {
650
+ const booleanValue = this.normalizeBooleanSuggestion(rawValue);
651
+
652
+ if (booleanValue === null) {
653
+ warnings.push(`Boolean attribute "${attribute.name}" could not be resolved safely.`);
654
+ continue;
655
+ }
656
+
657
+ draft.value_boolean = booleanValue;
658
+ draft.raw_value = String(booleanValue);
659
+ draft.normalized_value = String(booleanValue);
660
+ } else {
661
+ const textValue = String(rawValue ?? '').trim();
662
+
663
+ if (!textValue) {
664
+ continue;
665
+ }
666
+
667
+ draft.value_text = textValue;
668
+ draft.raw_value = textValue;
669
+ draft.normalized_value = textValue;
670
+ }
671
+
672
+ normalizedSuggestions.push(draft);
673
+ }
674
+
675
+ return normalizedSuggestions;
676
+ }
677
+
678
+ private buildAiSystemPrompt(
679
+ resource: string,
680
+ locale: string,
681
+ fieldContext: CatalogAiFieldContext[],
682
+ currentValues: Record<string, unknown>,
683
+ productAttributes: Record<string, unknown>[],
684
+ ) {
685
+ const isPt = locale?.startsWith('pt');
686
+ const fieldLines = fieldContext.map((field) => {
687
+ const optionText = field.options.length
688
+ ? ` options=${field.options.map((option) => `${option.label} (${option.value})`).join(', ')}`
689
+ : '';
690
+ const relationText = field.relation
691
+ ? ` relation=${field.relation.resource || field.relation.endpoint || 'external'}`
692
+ : '';
693
+
694
+ return `- ${field.key}: type=${field.type}; required=${field.required ? 'yes' : 'no'}; label="${field.label}"${optionText}${relationText}`;
695
+ });
696
+ const productAttributeLines = productAttributes.map((attribute) => {
697
+ const options = Array.isArray(attribute.options) ? attribute.options : [];
698
+ const optionText = options.length
699
+ ? ` options=${options
700
+ .map((option) => `${String((option as Record<string, unknown>).label ?? '')} (${String((option as Record<string, unknown>).option_value ?? '')})`)
701
+ .join(', ')}`
702
+ : '';
703
+
704
+ 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}`;
705
+ });
706
+
707
+ return [
708
+ isPt
709
+ ? 'Voce preenche formularios administrativos do catalogo. Responda apenas com JSON valido.'
710
+ : 'You fill catalog admin forms. Respond with valid JSON only.',
711
+ isPt
712
+ ? `Recurso atual: ${resource}.`
713
+ : `Current resource: ${resource}.`,
714
+ isPt
715
+ ? 'Use apenas os campos permitidos listados abaixo. Nao invente ids, arquivos ou campos extras.'
716
+ : 'Use only the allowed fields listed below. Do not invent ids, files, or extra fields.',
717
+ isPt
718
+ ? 'Para campos relacionais, prefira nomes/slug legiveis; o backend tentara resolver com seguranca.'
719
+ : 'For relation fields, prefer readable names/slugs; the backend will resolve them safely.',
720
+ isPt
721
+ ? 'Para selects, prefira os valores validos informados.'
722
+ : 'For selects, prefer the valid values provided.',
723
+ isPt
724
+ ? 'Estrutura da resposta: {"fields": { ... }, "product_attributes": { ... }, "notes": ["..."]}.'
725
+ : 'Response shape: {"fields": { ... }, "product_attributes": { ... }, "notes": ["..."]}.',
726
+ isPt
727
+ ? 'Se nao souber um campo, simplesmente omita.'
728
+ : 'If you are unsure about a field, omit it.',
729
+ `Allowed fields:\n${fieldLines.join('\n')}`,
730
+ productAttributeLines.length
731
+ ? `Structured product attributes:\n${productAttributeLines.join('\n')}`
732
+ : '',
733
+ `Current values: ${JSON.stringify(currentValues)}`,
734
+ ]
735
+ .filter(Boolean)
736
+ .join('\n\n');
737
+ }
55
738
 
56
- return payload;
57
- }
739
+ private sanitizePayload(config: CatalogResourceConfig, body: Record<string, unknown>) {
740
+ const normalizedBody = { ...body };
741
+
742
+ if (config.resource === 'attributes') {
743
+ if (
744
+ normalizedBody.name === undefined &&
745
+ normalizedBody.label !== undefined
746
+ ) {
747
+ normalizedBody.name = normalizedBody.label;
748
+ }
749
+
750
+ if (normalizedBody.data_type === 'select') {
751
+ normalizedBody.data_type = 'option';
752
+ }
753
+ }
754
+
755
+ if (config.resource === 'category-attributes') {
756
+ if (
757
+ normalizedBody.is_highlight === undefined &&
758
+ normalizedBody.is_highlighted !== undefined
759
+ ) {
760
+ normalizedBody.is_highlight = normalizedBody.is_highlighted;
761
+ }
762
+
763
+ if (
764
+ normalizedBody.sort_order === undefined &&
765
+ normalizedBody.display_order !== undefined
766
+ ) {
767
+ normalizedBody.sort_order = normalizedBody.display_order;
768
+ }
769
+ }
770
+
771
+ const payload: Record<string, unknown> = {};
772
+
773
+ for (const field of config.fields) {
774
+ if (Object.prototype.hasOwnProperty.call(normalizedBody, field) && normalizedBody[field] !== undefined) {
775
+ payload[field] = normalizedBody[field];
776
+ }
777
+ }
778
+
779
+ return payload;
780
+ }
58
781
 
59
- private buildWhere(config: CatalogResourceConfig, paginationParams: PaginationDTO, query: Record<string, unknown>) {
60
- const OR = config.searchFields.length
61
- ? this.prisma.createInsensitiveSearch(config.searchFields, paginationParams)
782
+ private buildWhere(config: CatalogResourceConfig, paginationParams: PaginationDTO, query: Record<string, unknown>) {
783
+ const OR = config.searchFields.length
784
+ ? this.prisma.createInsensitiveSearch(config.searchFields, paginationParams)
62
785
  : [];
63
786
  const AND: Record<string, unknown>[] = [];
64
787
 
@@ -72,24 +795,467 @@ export class CatalogService {
72
795
  }
73
796
  }
74
797
 
75
- return { OR, AND };
76
- }
77
-
78
- async list(resource: string, locale: string, paginationParams: PaginationDTO, query: Record<string, unknown>) {
79
- const config = this.getConfig(resource, locale);
80
- const model = this.getModel(resource, locale);
81
- const where = this.buildWhere(config, paginationParams, query);
82
-
83
- return this.pagination.paginate(
84
- model,
85
- paginationParams,
86
- {
87
- where,
88
- orderBy: config.defaultOrderBy ?? { id: 'desc' },
89
- },
90
- locale,
91
- );
92
- }
798
+ return { OR, AND };
799
+ }
800
+
801
+ private async ensureCategoryExists(categoryId: number) {
802
+ const category = await this.prisma.catalog_category.findUnique({
803
+ where: { id: categoryId },
804
+ });
805
+
806
+ if (!category) {
807
+ throw new NotFoundException('Catalog category not found');
808
+ }
809
+
810
+ return category;
811
+ }
812
+
813
+ private normalizeCategoryTree(items: Record<string, any>[]) {
814
+ const byId = new Map<number, Record<string, any>>();
815
+ const roots: Record<string, any>[] = [];
816
+
817
+ for (const item of items) {
818
+ byId.set(item.id, { ...item, children: [] });
819
+ }
820
+
821
+ for (const item of byId.values()) {
822
+ if (item.parent_category_id && byId.has(item.parent_category_id)) {
823
+ byId.get(item.parent_category_id)?.children.push(item);
824
+ } else {
825
+ roots.push(item);
826
+ }
827
+ }
828
+
829
+ return roots;
830
+ }
831
+
832
+ private async buildCategoryAttributePayload(categoryId: number, productId?: number) {
833
+ const category = await this.ensureCategoryExists(categoryId);
834
+ const categoryAttributes = await this.prisma.catalog_category_attribute.findMany({
835
+ where: { catalog_category_id: categoryId },
836
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
837
+ });
838
+
839
+ const attributeIds = [...new Set(categoryAttributes.map((item) => item.attribute_id))];
840
+ const attributes = attributeIds.length
841
+ ? await this.prisma.catalog_attribute.findMany({
842
+ where: { id: { in: attributeIds } },
843
+ orderBy: [{ display_order: 'asc' }, { id: 'asc' }],
844
+ })
845
+ : [];
846
+ const groupIds = [...new Set(attributes.map((item) => item.group_id).filter((value): value is number => typeof value === 'number'))];
847
+ const groups = groupIds.length
848
+ ? await this.prisma.catalog_attribute_group.findMany({
849
+ where: { id: { in: groupIds } },
850
+ })
851
+ : [];
852
+ const options = attributeIds.length
853
+ ? await this.prisma.catalog_attribute_option.findMany({
854
+ where: { attribute_id: { in: attributeIds } },
855
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
856
+ })
857
+ : [];
858
+ const values = productId && attributeIds.length
859
+ ? await this.prisma.catalog_product_attribute_value.findMany({
860
+ where: { product_id: productId, attribute_id: { in: attributeIds } },
861
+ include: {
862
+ catalog_attribute_option: true,
863
+ },
864
+ })
865
+ : [];
866
+
867
+ const categoryAttributeMap = new Map(
868
+ categoryAttributes.map((item) => [item.attribute_id, item]),
869
+ );
870
+ const optionMap = new Map<number, Record<string, any>[]>();
871
+ const valueMap = new Map(
872
+ values.map((item) => [item.attribute_id, item]),
873
+ );
874
+ const groupMap = new Map(
875
+ groups.map((item) => [item.id, item]),
876
+ );
877
+
878
+ for (const option of options) {
879
+ const bucket = optionMap.get(option.attribute_id) ?? [];
880
+ bucket.push(option);
881
+ optionMap.set(option.attribute_id, bucket);
882
+ }
883
+
884
+ const grouped = new Map<string, CatalogAttributeGroupPayload>();
885
+ for (const attribute of attributes) {
886
+ const relation = categoryAttributeMap.get(attribute.id);
887
+ if (!relation) {
888
+ continue;
889
+ }
890
+
891
+ const groupId = attribute.group_id ?? 0;
892
+ const group = attribute.group_id ? groupMap.get(attribute.group_id) : null;
893
+ const fallbackGroupName = String(attribute.group_name ?? '').trim() || 'General';
894
+ const groupKey = attribute.group_id ? String(groupId) : `name:${fallbackGroupName}`;
895
+ const existingGroup: CatalogAttributeGroupPayload = grouped.get(groupKey) ?? {
896
+ id: group?.id ?? null,
897
+ slug: group?.slug ?? fallbackGroupName.toLowerCase().replace(/\s+/g, '-'),
898
+ name: group?.name ?? fallbackGroupName,
899
+ attributes: [],
900
+ };
901
+
902
+ existingGroup.attributes.push({
903
+ ...attribute,
904
+ category_attribute: relation,
905
+ options: optionMap.get(attribute.id) ?? [],
906
+ value: valueMap.get(attribute.id) ?? null,
907
+ });
908
+
909
+ grouped.set(groupKey, existingGroup);
910
+ }
911
+
912
+ const resultGroups: CatalogAttributeGroupPayload[] = [...grouped.values()].map((group) => ({
913
+ ...group,
914
+ attributes: group.attributes.sort((left, right) => {
915
+ const leftRelation = left.category_attribute as Record<string, number>;
916
+ const rightRelation = right.category_attribute as Record<string, number>;
917
+ return (
918
+ Number(leftRelation.sort_order ?? 0) - Number(rightRelation.sort_order ?? 0) ||
919
+ Number(leftRelation.display_order ?? 0) - Number(rightRelation.display_order ?? 0) ||
920
+ Number(left.display_order ?? 0) - Number(right.display_order ?? 0) ||
921
+ Number(left.id ?? 0) - Number(right.id ?? 0)
922
+ );
923
+ }),
924
+ }));
925
+
926
+ resultGroups.sort((left, right) => String(left.name).localeCompare(String(right.name)));
927
+
928
+ return {
929
+ category,
930
+ product_id: productId ?? null,
931
+ groups: resultGroups,
932
+ attributes: resultGroups.flatMap((group) => group.attributes),
933
+ };
934
+ }
935
+
936
+ private isMeaningfulAttributeValue(value: CatalogAttributeValueInput) {
937
+ if (value.attribute_option_id !== undefined && value.attribute_option_id !== null) {
938
+ return true;
939
+ }
940
+
941
+ if (value.value_number !== undefined && value.value_number !== null) {
942
+ return true;
943
+ }
944
+
945
+ if (value.value_boolean !== undefined && value.value_boolean !== null) {
946
+ return true;
947
+ }
948
+
949
+ return String(value.value_text ?? '').trim().length > 0;
950
+ }
951
+
952
+ private buildAttributeSnapshotValue(attribute: Record<string, any>) {
953
+ const value = (attribute.value ?? null) as Record<string, any> | null;
954
+ const dataType = String(attribute.data_type ?? 'text');
955
+ const option = value?.catalog_attribute_option ?? null;
956
+
957
+ if (!value) {
958
+ return {
959
+ value: null,
960
+ value_text: null,
961
+ value_number: null,
962
+ value_boolean: null,
963
+ normalized_value: null,
964
+ raw_value: null,
965
+ option: null,
966
+ };
967
+ }
968
+
969
+ if (dataType === 'option') {
970
+ const optionPayload = option
971
+ ? {
972
+ id: Number(option.id),
973
+ slug: String(option.slug ?? ''),
974
+ label: String(option.label ?? option.option_value ?? ''),
975
+ option_value: String(option.option_value ?? ''),
976
+ }
977
+ : null;
978
+
979
+ return {
980
+ value: optionPayload?.option_value ?? value.value_text ?? null,
981
+ value_text: value.value_text ? String(value.value_text) : null,
982
+ value_number: null,
983
+ value_boolean: null,
984
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
985
+ raw_value: value.raw_value ? String(value.raw_value) : null,
986
+ option: optionPayload,
987
+ };
988
+ }
989
+
990
+ if (dataType === 'number') {
991
+ return {
992
+ value: value.value_number === null || value.value_number === undefined
993
+ ? null
994
+ : Number(value.value_number),
995
+ value_text: value.value_text ? String(value.value_text) : null,
996
+ value_number:
997
+ value.value_number === null || value.value_number === undefined
998
+ ? null
999
+ : Number(value.value_number),
1000
+ value_boolean: null,
1001
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
1002
+ raw_value: value.raw_value ? String(value.raw_value) : null,
1003
+ option: null,
1004
+ };
1005
+ }
1006
+
1007
+ if (dataType === 'boolean') {
1008
+ return {
1009
+ value:
1010
+ value.value_boolean === null || value.value_boolean === undefined
1011
+ ? null
1012
+ : Boolean(value.value_boolean),
1013
+ value_text: value.value_text ? String(value.value_text) : null,
1014
+ value_number: null,
1015
+ value_boolean:
1016
+ value.value_boolean === null || value.value_boolean === undefined
1017
+ ? null
1018
+ : Boolean(value.value_boolean),
1019
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
1020
+ raw_value: value.raw_value ? String(value.raw_value) : null,
1021
+ option: null,
1022
+ };
1023
+ }
1024
+
1025
+ return {
1026
+ value: value.value_text ? String(value.value_text) : null,
1027
+ value_text: value.value_text ? String(value.value_text) : null,
1028
+ value_number: null,
1029
+ value_boolean: null,
1030
+ normalized_value: value.normalized_value ? String(value.normalized_value) : null,
1031
+ raw_value: value.raw_value ? String(value.raw_value) : null,
1032
+ option: null,
1033
+ };
1034
+ }
1035
+
1036
+ private toAttributeSnapshot(attribute: Record<string, any>): CatalogAttributeSnapshotPayload {
1037
+ const relation = (attribute.category_attribute ?? {}) as Record<string, any>;
1038
+ const snapshotValue = this.buildAttributeSnapshotValue(attribute);
1039
+
1040
+ return {
1041
+ slug: String(attribute.slug ?? ''),
1042
+ name: String(attribute.name ?? attribute.slug ?? ''),
1043
+ data_type: String(attribute.data_type ?? 'text'),
1044
+ unit: attribute.unit ? String(attribute.unit) : null,
1045
+ group_name: String(attribute.group_name ?? 'General'),
1046
+ is_required: Boolean(relation.is_required ?? false),
1047
+ is_highlight: Boolean(relation.is_highlight ?? false),
1048
+ is_filter_visible: Boolean(relation.is_filter_visible ?? false),
1049
+ is_comparison_visible: Boolean(relation.is_comparison_visible ?? false),
1050
+ ...snapshotValue,
1051
+ };
1052
+ }
1053
+
1054
+ private async decorateProductRecords<T extends ProductRecordWithRelations>(records: T[]) {
1055
+ if (!records.length) {
1056
+ return records;
1057
+ }
1058
+
1059
+ const brandIds = [...new Set(
1060
+ records
1061
+ .map((record) => record.brand_id)
1062
+ .filter((value): value is number => typeof value === 'number'),
1063
+ )];
1064
+ const categoryIds = [...new Set(
1065
+ records
1066
+ .map((record) => record.catalog_category_id)
1067
+ .filter((value): value is number => typeof value === 'number'),
1068
+ )];
1069
+
1070
+ const [brands, categories] = await Promise.all([
1071
+ brandIds.length
1072
+ ? this.prisma.catalog_brand.findMany({
1073
+ where: { id: { in: brandIds } },
1074
+ select: { id: true, name: true, slug: true, logo_file_id: true },
1075
+ })
1076
+ : Promise.resolve([]),
1077
+ categoryIds.length
1078
+ ? this.prisma.catalog_category.findMany({
1079
+ where: { id: { in: categoryIds } },
1080
+ select: { id: true, name: true, slug: true },
1081
+ })
1082
+ : Promise.resolve([]),
1083
+ ]);
1084
+
1085
+ const brandMap = new Map(brands.map((item) => [item.id, item]));
1086
+ const categoryMap = new Map(categories.map((item) => [item.id, item]));
1087
+
1088
+ return records.map((record) => {
1089
+ const brand = record.brand_id ? brandMap.get(record.brand_id) : null;
1090
+ const category = record.catalog_category_id
1091
+ ? categoryMap.get(record.catalog_category_id)
1092
+ : null;
1093
+
1094
+ return {
1095
+ ...record,
1096
+ brand_name: brand?.name ?? null,
1097
+ brand_slug: brand?.slug ?? null,
1098
+ brand_logo_file_id: brand?.logo_file_id ?? null,
1099
+ category_name: category?.name ?? null,
1100
+ category_slug: category?.slug ?? null,
1101
+ };
1102
+ });
1103
+ }
1104
+
1105
+ private validateAttributeValueByType(
1106
+ attribute: {
1107
+ id: number;
1108
+ slug: string;
1109
+ name: string;
1110
+ data_type: string;
1111
+ },
1112
+ value: CatalogAttributeValueInput,
1113
+ ) {
1114
+ const hasText = String(value.value_text ?? '').trim().length > 0;
1115
+ const hasNumber = value.value_number !== undefined && value.value_number !== null;
1116
+ const hasBoolean = value.value_boolean !== undefined && value.value_boolean !== null;
1117
+ const hasOption = value.attribute_option_id !== undefined && value.attribute_option_id !== null;
1118
+ const filledKinds = [hasText, hasNumber, hasBoolean, hasOption].filter(Boolean).length;
1119
+ const attributeLabel = attribute.name || attribute.slug || `#${attribute.id}`;
1120
+
1121
+ if (filledKinds > 1) {
1122
+ throw new BadRequestException(
1123
+ `Attribute "${attributeLabel}" must use a single value field compatible with its type`,
1124
+ );
1125
+ }
1126
+
1127
+ switch (attribute.data_type) {
1128
+ case 'text':
1129
+ case 'long_text':
1130
+ if (hasNumber || hasBoolean || hasOption) {
1131
+ throw new BadRequestException(`Attribute "${attributeLabel}" only accepts text values`);
1132
+ }
1133
+ break;
1134
+ case 'number':
1135
+ if (hasText || hasBoolean || hasOption) {
1136
+ throw new BadRequestException(`Attribute "${attributeLabel}" only accepts number values`);
1137
+ }
1138
+ break;
1139
+ case 'boolean':
1140
+ if (hasText || hasNumber || hasOption) {
1141
+ throw new BadRequestException(`Attribute "${attributeLabel}" only accepts boolean values`);
1142
+ }
1143
+ break;
1144
+ case 'option':
1145
+ if (hasText || hasNumber || hasBoolean) {
1146
+ throw new BadRequestException(`Attribute "${attributeLabel}" only accepts option values`);
1147
+ }
1148
+ break;
1149
+ default:
1150
+ break;
1151
+ }
1152
+ }
1153
+
1154
+ private async buildProductStructuredPayload(productId: number) {
1155
+ const product = await this.getById('products', productId, 'en');
1156
+ const attributes = await this.listProductAttributes(productId);
1157
+ const groups = (attributes.groups ?? []).map((group) => ({
1158
+ id: group.id,
1159
+ slug: group.slug,
1160
+ name: group.name,
1161
+ attributes: group.attributes.map((attribute) =>
1162
+ this.toAttributeSnapshot(attribute as Record<string, any>),
1163
+ ),
1164
+ }));
1165
+ const flatAttributes = groups.flatMap((group) => group.attributes);
1166
+
1167
+ return {
1168
+ product,
1169
+ category: attributes.category,
1170
+ groups,
1171
+ attributes: flatAttributes,
1172
+ comparison: {
1173
+ category: {
1174
+ id: attributes.category?.id ?? null,
1175
+ slug: attributes.category?.slug ?? null,
1176
+ name: attributes.category?.name ?? null,
1177
+ },
1178
+ highlights: flatAttributes.filter((attribute) => attribute.is_highlight),
1179
+ comparable_attributes: flatAttributes.filter(
1180
+ (attribute) => attribute.is_comparison_visible,
1181
+ ),
1182
+ filter_attributes: flatAttributes.filter(
1183
+ (attribute) => attribute.is_filter_visible,
1184
+ ),
1185
+ },
1186
+ };
1187
+ }
1188
+
1189
+ async materializeProductSnapshots(productId: number) {
1190
+ const structured = await this.buildProductStructuredPayload(productId);
1191
+ const specSnapshot = {
1192
+ version: 1,
1193
+ source: 'catalog_product_attribute_value',
1194
+ category: structured.category
1195
+ ? {
1196
+ id: structured.category.id,
1197
+ slug: structured.category.slug,
1198
+ name: structured.category.name,
1199
+ }
1200
+ : null,
1201
+ groups: structured.groups,
1202
+ attributes: structured.attributes.reduce<Record<string, CatalogAttributeSnapshotPayload>>(
1203
+ (acc, attribute) => {
1204
+ acc[attribute.slug] = attribute;
1205
+ return acc;
1206
+ },
1207
+ {},
1208
+ ),
1209
+ generated_at: new Date().toISOString(),
1210
+ };
1211
+ const comparisonSnapshot = {
1212
+ version: 1,
1213
+ source: 'catalog_product_attribute_value',
1214
+ category: structured.comparison.category,
1215
+ highlights: structured.comparison.highlights,
1216
+ comparable_attributes: structured.comparison.comparable_attributes,
1217
+ generated_at: new Date().toISOString(),
1218
+ };
1219
+
1220
+ await this.prisma.catalog_product.update({
1221
+ where: { id: productId },
1222
+ data: {
1223
+ // Snapshots remain secondary/derived fields for legacy reads and fast payloads.
1224
+ spec_snapshot_json: specSnapshot,
1225
+ comparison_snapshot_json: comparisonSnapshot,
1226
+ },
1227
+ });
1228
+
1229
+ return {
1230
+ spec_snapshot_json: specSnapshot,
1231
+ comparison_snapshot_json: comparisonSnapshot,
1232
+ };
1233
+ }
1234
+
1235
+ async list(resource: string, locale: string, paginationParams: PaginationDTO, query: Record<string, unknown>) {
1236
+ const config = this.getConfig(resource, locale);
1237
+ const model = this.getModel(resource, locale);
1238
+ const where = this.buildWhere(config, paginationParams, query);
1239
+
1240
+ const result = await this.pagination.paginate(
1241
+ model,
1242
+ paginationParams,
1243
+ {
1244
+ where,
1245
+ orderBy: config.defaultOrderBy ?? { id: 'desc' },
1246
+ },
1247
+ locale,
1248
+ );
1249
+
1250
+ if (resource === 'products' && Array.isArray(result.data)) {
1251
+ return {
1252
+ ...result,
1253
+ data: await this.decorateProductRecords(result.data as ProductRecordWithRelations[]),
1254
+ };
1255
+ }
1256
+
1257
+ return result;
1258
+ }
93
1259
 
94
1260
  async stats(resource: string, locale: string) {
95
1261
  const config = this.getConfig(resource, locale);
@@ -108,9 +1274,52 @@ export class CatalogService {
108
1274
  return result;
109
1275
  }
110
1276
 
111
- async getById(resource: string, id: number, locale: string) {
112
- const model = this.getModel(resource, locale);
113
- const item = await model.findUnique({ where: { id } });
1277
+ async getById(resource: string, id: number, locale: string) {
1278
+ if (resource === 'products') {
1279
+ const item = await this.prisma.catalog_product.findUnique({
1280
+ where: { id },
1281
+ include: {
1282
+ catalog_brand: {
1283
+ select: {
1284
+ id: true,
1285
+ name: true,
1286
+ slug: true,
1287
+ logo_file_id: true,
1288
+ },
1289
+ },
1290
+ catalog_category: {
1291
+ select: {
1292
+ id: true,
1293
+ name: true,
1294
+ slug: true,
1295
+ },
1296
+ },
1297
+ catalog_product_image: {
1298
+ orderBy: [{ sort_order: 'asc' }, { id: 'asc' }],
1299
+ select: {
1300
+ id: true,
1301
+ file_id: true,
1302
+ role: true,
1303
+ sort_order: true,
1304
+ is_primary: true,
1305
+ alt_text: true,
1306
+ },
1307
+ },
1308
+ },
1309
+ });
1310
+
1311
+ if (!item) {
1312
+ throw new NotFoundException(
1313
+ getLocaleText('resourceNotFound', locale, 'Catalog resource not found'),
1314
+ );
1315
+ }
1316
+
1317
+ const [decorated] = await this.decorateProductRecords([item]);
1318
+ return decorated;
1319
+ }
1320
+
1321
+ const model = this.getModel(resource, locale);
1322
+ const item = await model.findUnique({ where: { id } });
114
1323
 
115
1324
  if (!item) {
116
1325
  throw new NotFoundException(
@@ -147,8 +1356,8 @@ export class CatalogService {
147
1356
  return model.delete({ where: { id } });
148
1357
  }
149
1358
 
150
- async listProductImages(productId: number, locale: string, paginationParams: PaginationDTO) {
151
- const model = this.getModel('product-images', locale);
1359
+ async listProductImages(productId: number, locale: string, paginationParams: PaginationDTO) {
1360
+ const model = this.getModel('product-images', locale);
152
1361
 
153
1362
  return this.pagination.paginate(
154
1363
  model,
@@ -161,7 +1370,311 @@ export class CatalogService {
161
1370
  sort_order: 'asc',
162
1371
  },
163
1372
  },
164
- locale,
165
- );
166
- }
167
- }
1373
+ locale,
1374
+ );
1375
+ }
1376
+
1377
+ async getCategoriesTree() {
1378
+ const categories = await this.prisma.catalog_category.findMany({
1379
+ orderBy: [{ sort_order: 'asc' }, { name: 'asc' }],
1380
+ });
1381
+
1382
+ return this.normalizeCategoryTree(categories);
1383
+ }
1384
+
1385
+ async listCategoryAttributes(categoryId: number) {
1386
+ return this.buildCategoryAttributePayload(categoryId);
1387
+ }
1388
+
1389
+ async listProductAttributes(productId: number) {
1390
+ const product = await this.prisma.catalog_product.findUnique({
1391
+ where: { id: productId },
1392
+ });
1393
+
1394
+ if (!product) {
1395
+ throw new NotFoundException('Catalog product not found');
1396
+ }
1397
+
1398
+ return this.buildCategoryAttributePayload(product.catalog_category_id, productId);
1399
+ }
1400
+
1401
+ async getProductStructuredPayload(productId: number) {
1402
+ return this.buildProductStructuredPayload(productId);
1403
+ }
1404
+
1405
+ async getProductComparisonPayload(productId: number) {
1406
+ const structured = await this.buildProductStructuredPayload(productId);
1407
+ return structured.comparison;
1408
+ }
1409
+
1410
+ async updateProductAttributes(productId: number, values: CatalogAttributeValueInput[]) {
1411
+ const product = await this.prisma.catalog_product.findUnique({
1412
+ where: { id: productId },
1413
+ });
1414
+
1415
+ if (!product) {
1416
+ throw new NotFoundException('Catalog product not found');
1417
+ }
1418
+
1419
+ const categoryAttributes = await this.prisma.catalog_category_attribute.findMany({
1420
+ where: { catalog_category_id: product.catalog_category_id },
1421
+ });
1422
+ const allowedAttributeIds = new Set(categoryAttributes.map((item) => item.attribute_id));
1423
+ const requiredAttributeIds = new Set(
1424
+ categoryAttributes
1425
+ .filter((item) => item.is_required)
1426
+ .map((item) => item.attribute_id),
1427
+ );
1428
+ const attributes = allowedAttributeIds.size
1429
+ ? await this.prisma.catalog_attribute.findMany({
1430
+ where: { id: { in: [...allowedAttributeIds] } },
1431
+ select: {
1432
+ id: true,
1433
+ slug: true,
1434
+ name: true,
1435
+ data_type: true,
1436
+ },
1437
+ })
1438
+ : [];
1439
+ const attributeMap = new Map(attributes.map((item) => [item.id, item]));
1440
+ const existingValues = await this.prisma.catalog_product_attribute_value.findMany({
1441
+ where: { product_id: productId },
1442
+ });
1443
+ const optionIds = values
1444
+ .map((value) => value.attribute_option_id)
1445
+ .filter((value): value is number => typeof value === 'number');
1446
+ const options = optionIds.length
1447
+ ? await this.prisma.catalog_attribute_option.findMany({
1448
+ where: { id: { in: optionIds } },
1449
+ })
1450
+ : [];
1451
+ const optionMap = new Map(options.map((item) => [item.id, item]));
1452
+
1453
+ const incomingByAttribute = new Map<number, CatalogAttributeValueInput>();
1454
+ for (const value of values) {
1455
+ const attributeId = Number(value.attribute_id ?? 0);
1456
+
1457
+ if (!attributeId || !allowedAttributeIds.has(attributeId)) {
1458
+ throw new BadRequestException(`Attribute ${attributeId} is not allowed for this category`);
1459
+ }
1460
+
1461
+ const attribute = attributeMap.get(attributeId);
1462
+
1463
+ if (!attribute) {
1464
+ throw new BadRequestException(`Attribute ${attributeId} was not found`);
1465
+ }
1466
+
1467
+ this.validateAttributeValueByType(attribute, value);
1468
+
1469
+ incomingByAttribute.set(attributeId, value);
1470
+ }
1471
+
1472
+ const incomingAttributeIds = new Set(incomingByAttribute.keys());
1473
+
1474
+ for (const attributeId of requiredAttributeIds) {
1475
+ const requiredValue = incomingByAttribute.get(attributeId);
1476
+
1477
+ if (!requiredValue || !this.isMeaningfulAttributeValue(requiredValue)) {
1478
+ const attribute = attributeMap.get(attributeId);
1479
+ throw new BadRequestException(
1480
+ `Attribute "${attribute?.name ?? attribute?.slug ?? attributeId}" is required for this category`,
1481
+ );
1482
+ }
1483
+ }
1484
+
1485
+ for (const existingValue of existingValues) {
1486
+ if (!incomingAttributeIds.has(existingValue.attribute_id)) {
1487
+ await this.prisma.catalog_product_attribute_value.delete({
1488
+ where: { id: existingValue.id },
1489
+ });
1490
+ }
1491
+ }
1492
+
1493
+ for (const [attributeId, value] of incomingByAttribute.entries()) {
1494
+ const option = value.attribute_option_id ? optionMap.get(value.attribute_option_id) : null;
1495
+ const attribute = attributeMap.get(attributeId);
1496
+
1497
+ if (value.attribute_option_id && (!option || option.attribute_id !== attributeId)) {
1498
+ throw new BadRequestException(
1499
+ `Option ${value.attribute_option_id} does not belong to attribute ${attribute?.name ?? attributeId}`,
1500
+ );
1501
+ }
1502
+
1503
+ const normalizedText = value.normalized_text ?? option?.normalized_value ?? option?.option_value ?? value.value_text ?? null;
1504
+ const sourceType: catalog_product_attribute_value_source_type_enum =
1505
+ value.source_type === 'import' || value.source_type === 'computed'
1506
+ ? value.source_type
1507
+ : 'manual';
1508
+ const payload = {
1509
+ attribute_option_id: value.attribute_option_id ?? null,
1510
+ value_text: option?.option_value ?? (String(value.value_text ?? '').trim() || null),
1511
+ value_number: value.value_number ?? null,
1512
+ value_boolean: value.value_boolean ?? null,
1513
+ raw_value:
1514
+ option?.option_value ??
1515
+ (value.value_number !== undefined && value.value_number !== null
1516
+ ? String(value.value_number)
1517
+ : value.value_boolean !== undefined && value.value_boolean !== null
1518
+ ? String(value.value_boolean)
1519
+ : String(value.value_text ?? '').trim() || null),
1520
+ value_unit: String(value.value_unit ?? '').trim() || null,
1521
+ normalized_value:
1522
+ normalizedText
1523
+ ? String(normalizedText).trim()
1524
+ : value.value_number !== undefined && value.value_number !== null
1525
+ ? String(value.value_number)
1526
+ : value.value_boolean !== undefined && value.value_boolean !== null
1527
+ ? String(value.value_boolean)
1528
+ : null,
1529
+ normalized_text: normalizedText ? String(normalizedText).trim() : null,
1530
+ normalized_number: value.normalized_number ?? value.value_number ?? null,
1531
+ source_type: sourceType,
1532
+ confidence_score: value.confidence_score ?? null,
1533
+ is_verified: Boolean(value.is_verified ?? false),
1534
+ } satisfies CatalogAttributeValueInput & {
1535
+ source_type: catalog_product_attribute_value_source_type_enum;
1536
+ };
1537
+
1538
+ const existingValue = existingValues.find((item) => item.attribute_id === attributeId);
1539
+
1540
+ if (!this.isMeaningfulAttributeValue(payload)) {
1541
+ if (existingValue) {
1542
+ await this.prisma.catalog_product_attribute_value.delete({
1543
+ where: { id: existingValue.id },
1544
+ });
1545
+ }
1546
+ continue;
1547
+ }
1548
+
1549
+ if (existingValue) {
1550
+ const updatePayload: Prisma.catalog_product_attribute_valueUncheckedUpdateInput = {
1551
+ attribute_option_id: payload.attribute_option_id,
1552
+ value_text: payload.value_text,
1553
+ value_number: payload.value_number,
1554
+ value_boolean: payload.value_boolean,
1555
+ raw_value: payload.raw_value,
1556
+ value_unit: payload.value_unit,
1557
+ normalized_value: payload.normalized_value,
1558
+ normalized_text: payload.normalized_text,
1559
+ normalized_number: payload.normalized_number,
1560
+ source_type: payload.source_type,
1561
+ confidence_score: payload.confidence_score,
1562
+ is_verified: payload.is_verified,
1563
+ };
1564
+
1565
+ await this.prisma.catalog_product_attribute_value.update({
1566
+ where: { id: existingValue.id },
1567
+ data: updatePayload,
1568
+ });
1569
+ } else {
1570
+ const createPayload: Prisma.catalog_product_attribute_valueUncheckedCreateInput = {
1571
+ product_id: productId,
1572
+ attribute_id: attributeId,
1573
+ attribute_option_id: payload.attribute_option_id,
1574
+ value_text: payload.value_text,
1575
+ value_number: payload.value_number,
1576
+ value_boolean: payload.value_boolean,
1577
+ raw_value: payload.raw_value,
1578
+ value_unit: payload.value_unit,
1579
+ normalized_value: payload.normalized_value,
1580
+ normalized_text: payload.normalized_text,
1581
+ normalized_number: payload.normalized_number,
1582
+ source_type: payload.source_type,
1583
+ confidence_score: payload.confidence_score,
1584
+ is_verified: payload.is_verified,
1585
+ };
1586
+
1587
+ await this.prisma.catalog_product_attribute_value.create({
1588
+ data: createPayload,
1589
+ });
1590
+ }
1591
+ }
1592
+
1593
+ await this.materializeProductSnapshots(productId);
1594
+
1595
+ return this.listProductAttributes(productId);
1596
+ }
1597
+
1598
+ async generateFormAssistSuggestion(
1599
+ resource: string,
1600
+ input: CatalogAiAssistInput,
1601
+ locale: string,
1602
+ ) {
1603
+ const config = this.getConfig(resource, locale);
1604
+ const fieldContext = this.normalizeAiFieldContext(resource, input.fields ?? []);
1605
+ const currentValues = input.current_values ?? {};
1606
+ const warnings: string[] = [];
1607
+ const categoryId =
1608
+ resource === 'products'
1609
+ ? Number(currentValues.catalog_category_id ?? 0) || null
1610
+ : null;
1611
+ const productAttributeContext = categoryId
1612
+ ? this.buildAttributeContext(
1613
+ await this.buildCategoryAttributePayload(categoryId),
1614
+ input.current_attribute_values ?? [],
1615
+ )
1616
+ : [];
1617
+ const systemPrompt = this.buildAiSystemPrompt(
1618
+ resource,
1619
+ locale,
1620
+ fieldContext,
1621
+ currentValues,
1622
+ productAttributeContext,
1623
+ );
1624
+ const aiResponse = await this.aiService.chat({
1625
+ provider: 'openai',
1626
+ model: 'gpt-4o-mini',
1627
+ message: input.prompt,
1628
+ systemPrompt,
1629
+ });
1630
+ const parsed = this.extractJsonObject(String(aiResponse.content ?? ''));
1631
+ const rawFields =
1632
+ parsed.fields && typeof parsed.fields === 'object'
1633
+ ? (parsed.fields as Record<string, unknown>)
1634
+ : {};
1635
+ const normalizedFields: Record<string, unknown> = {};
1636
+
1637
+ for (const field of fieldContext) {
1638
+ if (!Object.prototype.hasOwnProperty.call(rawFields, field.key)) {
1639
+ continue;
1640
+ }
1641
+
1642
+ const normalizedValue = await this.normalizeAiFieldSuggestion(
1643
+ field,
1644
+ rawFields[field.key],
1645
+ warnings,
1646
+ );
1647
+
1648
+ if (normalizedValue !== undefined) {
1649
+ normalizedFields[field.key] = normalizedValue;
1650
+ }
1651
+ }
1652
+
1653
+ const productAttributes = await this.normalizeAiProductAttributeSuggestions(
1654
+ categoryId,
1655
+ parsed.product_attributes,
1656
+ input.current_attribute_values ?? [],
1657
+ warnings,
1658
+ );
1659
+
1660
+ const appliedFields = fieldContext
1661
+ .filter((field) => Object.prototype.hasOwnProperty.call(normalizedFields, field.key))
1662
+ .map((field) => ({
1663
+ key: field.key,
1664
+ label: field.label,
1665
+ type: field.type,
1666
+ value: normalizedFields[field.key],
1667
+ }));
1668
+
1669
+ return {
1670
+ resource: config.resource,
1671
+ fields: normalizedFields,
1672
+ applied_fields: appliedFields,
1673
+ product_attributes: productAttributes,
1674
+ warnings: [
1675
+ ...warnings,
1676
+ ...(Array.isArray(parsed.notes) ? parsed.notes.map((note) => String(note)) : []),
1677
+ ],
1678
+ };
1679
+ }
1680
+ }