This commit is contained in:
greeneclipse committed 2026-10-16 13:48:51 +02:00
1 parent feebf7d3c1
commit 486502852e
41 files changed
+1311 -259

No files matched your search

+45 -26
View File
@@ -124,6 +124,7 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
byUID := make(map[string]categoryCSVRow, len(batch))
order := make([]string, 0, len(batch))
@@ -184,12 +185,15 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
if len(updIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE categories AS c SET
name = v.name,
description = CASE WHEN v.description <> '' THEN v.description ELSE c.description END,
name = CASE WHEN $5 THEN v.name ELSE c.name END,
description = CASE WHEN $5 AND v.description <> '' THEN v.description ELSE c.description END,
localized_fields = jsonb_set(COALESCE(c.localized_fields, '{}'::jsonb), ARRAY[$6::text],
COALESCE(c.localized_fields -> ($6::text), '{}'::jsonb) ||
jsonb_strip_nulls(jsonb_build_object('name', NULLIF(v.name,''), 'description',NULLIF(v.description,''))), true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description)
WHERE c.id = v.id AND c.company_id = $1`,
companyID, updIDs, updNames, updDescs)
companyID, updIDs, updNames, updDescs, primary, lang)
if err != nil {
return err
}
@@ -228,12 +232,13 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
}
rows, err := tx.Query(ctx, `
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level)
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level, localized_fields)
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level,
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object('name',v.name,'description',NULLIF(v.description,''))))
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::int[])
AS v(name, unique_id, parent_unique_id, description, path, level)
RETURNING id, unique_id, COALESCE(path, ''), level`,
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels)
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels, lang)
if err != nil {
return err
}
@@ -396,6 +401,7 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
byKey := make(map[string]attributeCSVRow, len(batch))
order := make([]string, 0, len(batch))
@@ -465,12 +471,14 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(updIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE attributes AS a SET
name = CASE WHEN v.name <> '' THEN v.name ELSE a.name END,
name = CASE WHEN $5 AND v.name <> '' THEN v.name ELSE a.name END,
value_type = CASE WHEN v.value_type <> '' THEN v.value_type ELSE a.value_type END,
localized_fields = jsonb_set(COALESCE(a.localized_fields,'{}'::jsonb), ARRAY[$6::text],
COALESCE(a.localized_fields -> ($6::text),'{}'::jsonb) || jsonb_build_object('name',v.name), true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type)
WHERE a.id = v.id AND a.company_id = $1`,
companyID, updIDs, updNames, updTypes)
companyID, updIDs, updNames, updTypes, primary, lang)
if err != nil {
return err
}
@@ -479,12 +487,13 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(insKeys) > 0 {
ct, err := tx.Exec(ctx, `
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key)
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key, localized_fields)
SELECT $1, v.attribute_key, v.name, v.value_type,
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, '')
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, ''),
jsonb_build_object($8::text, jsonb_build_object('name',v.name))
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(attribute_key, name, value_type, unit, example, parent_key)`,
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents)
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents, lang)
if err != nil {
return err
}
@@ -508,6 +517,7 @@ type productCSVRow struct {
func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) {
res := ImportResult{}
lang, primary := s.importLanguage(ctx, companyID)
merge, err := s.MergeProductsByGTIN(ctx, companyID)
if err != nil {
return res, err
@@ -566,7 +576,7 @@ func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r
batch = append(batch, productCSVRow{
gtin: gtin, productID: productID, name: name, category: category,
desc: desc, status: status, rawJSON: string(rawData),
mergeable: merge && !strings.HasPrefix(gtin, "nogtin-"),
mergeable: (merge || lang != primary) && !strings.HasPrefix(gtin, "nogtin-"),
})
if len(batch) >= importCSVBatchSize {
if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil {
@@ -585,6 +595,7 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
// Last row wins per GTIN so a single INSERT cannot hit the same unique key twice.
byGTIN := make(map[string]productCSVRow, len(batch))
@@ -677,13 +688,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(updRawIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE raw_products AS r SET
raw_data = v.raw_data::jsonb,
mapped_data = v.raw_data::jsonb,
raw_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.mapped_data END,
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb), ARRAY[$5::text],
COALESCE(r.source_localizations -> ($5::text),'{}'::jsonb) || v.raw_data::jsonb, true),
file_id = COALESCE($3, r.file_id),
updated_at = now()
FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data)
WHERE r.id = v.id AND r.company_id = $1`,
companyID, updRawIDs, fileID, updRawJSON)
companyID, updRawIDs, fileID, updRawJSON, lang, primary)
if err != nil {
return err
}
@@ -694,12 +707,13 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insGTINs) > 0 {
rows, err := tx.Query(ctx, `
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id)
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id, source_localizations)
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2,
jsonb_build_object($5::text, v.raw_data::jsonb)
FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data)
ON CONFLICT (company_id, gtin) DO NOTHING
RETURNING id, gtin`,
companyID, fileID, insGTINs, insJSON)
companyID, fileID, insGTINs, insJSON, lang)
if err != nil {
return err
}
@@ -803,15 +817,18 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
_, err = tx.Exec(ctx, `
UPDATE processed_products AS p SET
product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id),
name = COALESCE(NULLIF(v.name, ''), p.name),
category = COALESCE(NULLIF(v.category, ''), p.category),
description = COALESCE(NULLIF(v.description, ''), p.description),
status = COALESCE(NULLIF(v.status, ''), p.status),
name = CASE WHEN $9 THEN COALESCE(NULLIF(v.name, ''), p.name) ELSE p.name END,
category = CASE WHEN $9 THEN COALESCE(NULLIF(v.category, ''), p.category) ELSE p.category END,
description = CASE WHEN $9 THEN COALESCE(NULLIF(v.description, ''), p.description) ELSE p.description END,
status = CASE WHEN $9 THEN COALESCE(NULLIF(v.status, ''), p.status) ELSE p.status END,
source_localizations = jsonb_set(COALESCE(p.source_localizations,'{}'::jsonb), ARRAY[$8::text],
COALESCE(p.source_localizations -> ($8::text),'{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(
'name',NULLIF(v.name,''),'category',NULLIF(v.category,''),'description',NULLIF(v.description,''))),true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(id, product_id, name, category, description, status)
WHERE p.id = v.id AND p.company_id = $1`,
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses)
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses, lang, primary)
if err != nil {
return err
}
@@ -820,13 +837,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insRawIDs) > 0 {
_, err = tx.Exec(ctx, `
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id)
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id, source_localizations)
SELECT $1,
NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''),
NULLIF(v.description, ''), v.status, v.raw_product_id
NULLIF(v.description, ''), v.status, v.raw_product_id,
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object(
'name', NULLIF(v.name,''), 'category',NULLIF(v.category,''), 'description',NULLIF(v.description,''))))
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(raw_product_id, product_id, name, category, description, status)`,
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses)
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses, lang)
if err != nil {
return err
}
@@ -0,0 +1,56 @@
package catalog
import (
"context"
"encoding/json"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/google/uuid"
)
type importLanguageContextKey struct{}
// WithImportLanguage marks the language of a supplier import. An empty code means
// the company primary language. The HTTP layer validates explicit codes.
func WithImportLanguage(ctx context.Context, lang string) context.Context {
return context.WithValue(ctx, importLanguageContextKey{}, lang)
}
func (s *Service) importLanguage(ctx context.Context, companyID uuid.UUID) (string, bool) {
primary := company.LoadLanguage(ctx, s.Pool, companyID)
lang, _ := ctx.Value(importLanguageContextKey{}).(string)
if lang == "" {
lang = primary
}
return lang, lang == primary
}
// localizeCatalogImportNames changes presentation only; it never overwrites
// the primary-language columns in storage. The full translations map remains
// present in API responses for clients that need several languages.
func localizeCatalogImportNames(ctx context.Context, items []map[string]any) {
lang, _ := ctx.Value(importLanguageContextKey{}).(string)
if lang == "" {
return
}
for _, item := range items {
var all map[string]map[string]string
switch raw := item["localized_fields"].(type) {
case []byte:
_ = json.Unmarshal(raw, &all)
case string:
_ = json.Unmarshal([]byte(raw), &all)
default:
b, _ := json.Marshal(raw)
_ = json.Unmarshal(b, &all)
}
if fields := all[lang]; fields != nil {
if val := fields["name"]; val != "" {
item["name"] = val
}
if val := fields["description"]; val != "" {
item["description"] = val
}
}
}
}
@@ -0,0 +1,24 @@
package catalog
import (
"context"
"testing"
)
func TestLocalizedImportViewPreservesPrimary(t *testing.T) {
rows := []map[string]any{{
"name": "Shower mixer", "description": "Chrome mixer",
"localized_fields": map[string]any{
"en": map[string]any{"name": "Shower mixer", "description": "Chrome mixer"},
"sl": map[string]any{"name": "Armatura za prho", "description": "Kromirana armatura"},
},
}}
localizeCatalogImportNames(WithImportLanguage(context.Background(), "sl"), rows)
if rows[0]["name"] != "Armatura za prho" || rows[0]["description"] != "Kromirana armatura" {
t.Fatalf("wrong Slovenian fields: %+v", rows[0])
}
localizeCatalogImportNames(WithImportLanguage(context.Background(), "en"), rows)
if rows[0]["name"] != "Shower mixer" {
t.Fatalf("English label not restored: %+v", rows[0])
}
}
+13 -8
View File
@@ -94,7 +94,7 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
off := len(args)
rows, err := s.Pool.Query(ctx, fmt.Sprintf(`
SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description,
title_template, description_template,
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb) AS localized_fields,
(title_template IS NOT NULL AND jsonb_typeof(title_template) = 'object'
AND COALESCE(jsonb_array_length(title_template->'elements'), 0) > 0) AS has_title_formula,
(description_template IS NOT NULL AND jsonb_typeof(description_template) = 'object'
@@ -113,12 +113,13 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
defer rows.Close()
items, err := scanMaps(rows, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
"title_template", "description_template", "has_title_formula", "has_description_formula", "has_prompt",
"title_template", "description_template", "localized_fields", "has_title_formula", "has_description_formula", "has_prompt",
"created_at", "updated_at",
})
if err != nil {
return nil, 0, err
}
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil
}
@@ -186,15 +187,16 @@ func (s *Service) GetCategory(ctx context.Context, companyID, id uuid.UUID) (map
SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv
WHERE length(trim(kv.value)) > 0
)) AS has_prompt,
title_template, description_template, created_at, updated_at
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb), created_at, updated_at
FROM categories WHERE id = $1 AND company_id = $2`, id, companyID)
item, err := scanMap(row, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
"prompts", "has_prompt", "title_template", "description_template", "created_at", "updated_at",
"prompts", "has_prompt", "title_template", "description_template", "localized_fields", "created_at", "updated_at",
})
if err != nil {
return nil, err
}
localizeCatalogImportNames(ctx, []map[string]any{item})
return enrichCategoryPrompts(ctx, s.Pool, companyID, item)
}
@@ -377,8 +379,8 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
args := []any{companyID}
where := []string{"a.company_id = $1"}
from := "attributes a"
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, a.created_at, a.updated_at"
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "created_at", "updated_at"}
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, COALESCE(a.localized_fields,'{}'::jsonb), a.created_at, a.updated_at"
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "localized_fields", "created_at", "updated_at"}
if f.Category != "" {
from = `attributes a
INNER JOIN category_attributes ca
@@ -417,6 +419,7 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
if err != nil {
return nil, 0, err
}
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil
}
@@ -1324,6 +1327,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
`+processedHasProcessedAttributesSQL+` AS has_processed_attributes,
`+processedHasEprelSQL+` AS has_eprel,
COALESCE(p.localized_content, '{}'::jsonb) AS localized_content,
COALESCE(r.source_localizations, '{}'::jsonb) || COALESCE(p.source_localizations, '{}'::jsonb) AS source_localizations,
p.created_at, p.updated_at
FROM processed_products p
LEFT JOIN raw_products r ON r.id = p.raw_product_id
@@ -1338,7 +1342,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
"localized_content",
"localized_content", "source_localizations",
"created_at", "updated_at",
})
if err != nil {
@@ -1384,6 +1388,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
false AS has_processed_attributes,
`+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel,
'{}'::jsonb AS localized_content,
COALESCE(rp.source_localizations, '{}'::jsonb) AS source_localizations,
rp.created_at, rp.updated_at,
(COALESCE(NULLIF(trim(rp.mapped_data->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name,
(COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description,
@@ -1399,7 +1404,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
"localized_content",
"localized_content", "source_localizations",
"created_at", "updated_at",
"has_name", "has_description", "has_category",
"is_processed", "processing_status",