From 1ad180a05287ca2ef9c031e3ff9695e0abea3f71 Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Tue, 27 Oct 2026 14:53:19 +0100 Subject: [PATCH] fixes --- apps/api/go.mod | 9 + apps/api/go.sum | 14 + apps/api/internal/catalog/files.go | 32 +- apps/api/internal/feeds/excel.go | 756 ++++++++++++ apps/api/internal/feeds/excel_test.go | 288 +++++ apps/api/internal/feeds/export.go | 19 +- .../feeds/export_short_description_test.go | 18 + apps/api/internal/feeds/extract_schema.go | 20 +- apps/api/internal/feeds/parse.go | 96 ++ .../internal/feeds/parse_xml_property_test.go | 42 + apps/api/internal/feeds/service.go | 16 +- apps/api/internal/feeds/source.go | 2 + apps/api/internal/feeds/sync.go | 2 + apps/api/internal/httpapi/feeds_handlers.go | 2 + apps/api/internal/processing/ai.go | 3 + .../api/internal/processing/attrs_backfill.go | 2 +- apps/api/internal/processing/categorize_ai.go | 59 +- .../internal/processing/categorize_ai_test.go | 12 +- .../processing/categorize_confidence_test.go | 26 +- apps/api/internal/processing/pipeline.go | 12 +- apps/api/internal/processing/specs.go | 21 +- apps/api/internal/processing/steps.go | 12 +- .../processing/uncategorized_attrs_test.go | 49 + apps/api/third_party/grate/LICENSE | 21 + apps/api/third_party/grate/PATCHES.md | 13 + apps/api/third_party/grate/commonxl/cell.go | 463 +++++++ apps/api/third_party/grate/commonxl/dates.go | 78 ++ apps/api/third_party/grate/commonxl/fmt.go | 303 +++++ .../api/third_party/grate/commonxl/formats.go | 382 ++++++ .../api/third_party/grate/commonxl/numbers.go | 74 ++ apps/api/third_party/grate/commonxl/sheet.go | 237 ++++ apps/api/third_party/grate/errs.go | 44 + apps/api/third_party/grate/go.mod | 3 + apps/api/third_party/grate/grate.go | 104 ++ apps/api/third_party/grate/xls/cfb/cfb.go | 363 ++++++ .../third_party/grate/xls/cfb/interface.go | 46 + .../third_party/grate/xls/cfb/slicereader.go | 101 ++ .../third_party/grate/xls/crypto/crypto.go | 103 ++ apps/api/third_party/grate/xls/crypto/rc4.go | 155 +++ apps/api/third_party/grate/xls/hyperlinks.go | 146 +++ apps/api/third_party/grate/xls/records.go | 1076 +++++++++++++++++ apps/api/third_party/grate/xls/sheets.go | 463 +++++++ apps/api/third_party/grate/xls/strings.go | 246 ++++ apps/api/third_party/grate/xls/structs.go | 107 ++ apps/api/third_party/grate/xls/xls.go | 360 ++++++ apps/web/src/lib/i18n/messages/en.ts | 4 +- apps/web/src/routes/export-feeds/+page.svelte | 3 + apps/web/src/routes/feeds/+page.svelte | 20 +- .../feeds/[feedId]/mapping/+page.svelte | 1 + 49 files changed, 6339 insertions(+), 89 deletions(-) create mode 100644 apps/api/internal/feeds/excel.go create mode 100644 apps/api/internal/feeds/excel_test.go create mode 100644 apps/api/internal/feeds/export_short_description_test.go create mode 100644 apps/api/internal/feeds/parse_xml_property_test.go create mode 100644 apps/api/internal/processing/uncategorized_attrs_test.go create mode 100644 apps/api/third_party/grate/LICENSE create mode 100644 apps/api/third_party/grate/PATCHES.md create mode 100644 apps/api/third_party/grate/commonxl/cell.go create mode 100644 apps/api/third_party/grate/commonxl/dates.go create mode 100644 apps/api/third_party/grate/commonxl/fmt.go create mode 100644 apps/api/third_party/grate/commonxl/formats.go create mode 100644 apps/api/third_party/grate/commonxl/numbers.go create mode 100644 apps/api/third_party/grate/commonxl/sheet.go create mode 100644 apps/api/third_party/grate/errs.go create mode 100644 apps/api/third_party/grate/go.mod create mode 100644 apps/api/third_party/grate/grate.go create mode 100644 apps/api/third_party/grate/xls/cfb/cfb.go create mode 100644 apps/api/third_party/grate/xls/cfb/interface.go create mode 100644 apps/api/third_party/grate/xls/cfb/slicereader.go create mode 100644 apps/api/third_party/grate/xls/crypto/crypto.go create mode 100644 apps/api/third_party/grate/xls/crypto/rc4.go create mode 100644 apps/api/third_party/grate/xls/hyperlinks.go create mode 100644 apps/api/third_party/grate/xls/records.go create mode 100644 apps/api/third_party/grate/xls/sheets.go create mode 100644 apps/api/third_party/grate/xls/strings.go create mode 100644 apps/api/third_party/grate/xls/structs.go create mode 100644 apps/api/third_party/grate/xls/xls.go diff --git a/apps/api/go.mod b/apps/api/go.mod index 9368fa8..9c86049 100644 --- a/apps/api/go.mod +++ b/apps/api/go.mod @@ -11,6 +11,8 @@ require ( github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.10.0 github.com/microcosm-cc/bluemonday v1.0.27 + github.com/pbnjay/grate v0.0.0-20231006022435-3f8e65d74a14 + github.com/xuri/excelize/v2 v2.11.0 golang.org/x/crypto v0.54.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -22,8 +24,15 @@ require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/richardlehane/mscfb v1.0.7 // indirect + github.com/richardlehane/msoleps v1.0.6 // indirect + github.com/tiendc/go-deepcopy v1.7.2 // indirect + github.com/xuri/efp v0.0.1 // indirect + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect golang.org/x/net v0.57.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.40.0 // indirect ) + +replace github.com/pbnjay/grate => ./third_party/grate diff --git a/apps/api/go.sum b/apps/api/go.sum index 51b93ed..25d0288 100644 --- a/apps/api/go.sum +++ b/apps/api/go.sum @@ -43,6 +43,10 @@ github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwX github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/+EB0= +github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo= +github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg= +github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -55,12 +59,22 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= +github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ= +github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8= +github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG88= +github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE= +golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= diff --git a/apps/api/internal/catalog/files.go b/apps/api/internal/catalog/files.go index 4cc8a0f..8ce4f7a 100644 --- a/apps/api/internal/catalog/files.go +++ b/apps/api/internal/catalog/files.go @@ -16,7 +16,10 @@ import ( "github.com/jackc/pgx/v5" ) -const maxUploadBytes = 5 << 20 // 5 MiB +const ( + maxUploadBytes = 5 << 20 // 5 MiB + maxFeedUploadBytes = 32 << 20 // 32 MiB; feeds.maxExcelBytes is the Excel parse-time cap +) func sanitizeFileName(name string) string { name = filepath.Base(strings.TrimSpace(name)) @@ -49,10 +52,25 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u isCSV := strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".tsv") isXML := strings.HasSuffix(lower, ".xml") && kind == "feed" isJSON := strings.HasSuffix(lower, ".json") - if !isCSV && !isXML && !isJSON { - return nil, ClientMsg("only CSV, JSON or XML feed uploads are allowed") + // .zip = several workbooks as one feed (e.g. one GroupeSeb product sheet per file). + isExcel := kind == "feed" && (strings.HasSuffix(lower, ".xls") || strings.HasSuffix(lower, ".xlsx") || strings.HasSuffix(lower, ".xlsm") || strings.HasSuffix(lower, ".zip")) + if !isCSV && !isXML && !isJSON && !isExcel { + return nil, ClientMsg("only CSV, JSON, XML, Excel or zipped Excel feed uploads are allowed") } - if contentType != "" && + limit := int64(maxUploadBytes) + if kind == "feed" { + // Supplier catalogs (full XML exports, workbooks with embedded photos) run well past 5 MiB. + limit = maxFeedUploadBytes + } + ctLower := strings.ToLower(contentType) + if isExcel && contentType != "" && + !strings.Contains(ctLower, "excel") && + !strings.Contains(ctLower, "spreadsheetml") && + !strings.Contains(ctLower, "octet-stream") && + !strings.Contains(ctLower, "zip") { + return nil, ClientMsg("invalid content type for Excel upload") + } + if !isExcel && contentType != "" && !strings.Contains(strings.ToLower(contentType), "csv") && !strings.Contains(strings.ToLower(contentType), "json") && !strings.Contains(strings.ToLower(contentType), "xml") && @@ -82,14 +100,14 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u } defer f.Close() - n, err := io.Copy(f, io.LimitReader(r, maxUploadBytes+1)) + n, err := io.Copy(f, io.LimitReader(r, limit+1)) if err != nil { _ = os.Remove(abs) return nil, err } - if n > maxUploadBytes { + if n > limit { _ = os.Remove(abs) - return nil, ClientMsg(fmt.Sprintf("file exceeds %d byte limit", maxUploadBytes)) + return nil, ClientMsg(fmt.Sprintf("file exceeds %d byte limit", limit)) } var uid any diff --git a/apps/api/internal/feeds/excel.go b/apps/api/internal/feeds/excel.go new file mode 100644 index 0000000..f988fb2 --- /dev/null +++ b/apps/api/internal/feeds/excel.go @@ -0,0 +1,756 @@ +package feeds + +import ( + "archive/zip" + "bytes" + "encoding/csv" + "errors" + "fmt" + "io" + "math" + "os" + "path" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode" + + "github.com/pbnjay/grate" + "github.com/pbnjay/grate/commonxl" + "github.com/pbnjay/grate/xls" + "github.com/xuri/excelize/v2" +) + +// maxExcelBytes bounds spreadsheet sources. Workbooks are decoded in memory (BIFF +// fully, OOXML shared strings), so the cap is far below maxDownloadBytes. It also +// bounds each workbook inside a zip archive. +const maxExcelBytes int64 = 64 << 20 + +const ( + // excelHeaderScanRows is how many leading non-empty rows are buffered to find the + // header row (supplier exports often start with a title/date block). + excelHeaderScanRows = 20 + // excelRecordScanRows bounds the per-sheet scan for a record-layout EAN row. + excelRecordScanRows = 600 + // maxExcelArchiveEntries / maxExcelArchiveBytes bound zip uploads of workbooks. + maxExcelArchiveEntries = 2000 + maxExcelArchiveBytes int64 = 512 << 20 +) + +var ( + oleMagic = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1} + zipMagic = []byte{'P', 'K', 0x03, 0x04} + + errExcelStop = errors.New("excel: stop") + + // excelBarcodeLabel matches the label cell of a record-layout barcode row. + excelBarcodeLabel = regexp.MustCompile(`(?i)^(ean|gtin|barcode|bar code|ean code|ean-code|ean koda|črtna koda)\b`) + excelBarcodeValue = regexp.MustCompile(`^[0-9]{8,14}$`) + excelGUID = regexp.MustCompile(`^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f-]{12,17}$`) +) + +// isExcelSample reports whether sample starts like a legacy .xls (OLE2) or a zip: +// an OOXML workbook or an archive of workbooks. Feeds are otherwise text. +func isExcelSample(sample []byte) bool { + return bytes.HasPrefix(sample, oleMagic) || bytes.HasPrefix(sample, zipMagic) +} + +func isExcelName(name string) bool { + n := strings.ToLower(strings.TrimSpace(name)) + if i := strings.IndexAny(n, "?#"); i >= 0 { + n = n[:i] + } + return isWorkbookName(n) || strings.HasSuffix(n, ".zip") +} + +func isWorkbookName(name string) bool { + n := strings.ToLower(name) + return strings.HasSuffix(n, ".xls") || strings.HasSuffix(n, ".xlsx") || strings.HasSuffix(n, ".xlsm") +} + +func isExcelContentType(ct string) bool { + ct = strings.ToLower(ct) + return strings.Contains(ct, "spreadsheetml") || strings.Contains(ct, "ms-excel") +} + +// excelSheetOption returns options.sheet; empty picks the visible sheet with the most rows. +func excelSheetOption(feed map[string]any) string { + if opts, ok := feed["options"].(map[string]any); ok { + if v, ok := opts["sheet"].(string); ok { + return strings.TrimSpace(v) + } + } + return "" +} + +// parseExcel streams the products of a workbook (or zip of workbooks) as +// column-keyed feedRows, like parseCSV. +func parseExcel(path, sheet string, onRow func(feedRow) error) (int, error) { + count := 0 + err := readExcelSource(path, sheet, func(cols, rec []string) error { + count++ + if count > maxParseRows { + return parseTooManyRows() + } + row := make(feedRow, len(cols)) + for i, col := range cols { + if col == "" { + continue + } + if i < len(rec) { + row[col] = rec[i] + } else { + row[col] = "" + } + } + expandSpecificationFields(row) + return onRow(row) + }) + return count, err +} + +// excelSchemaCSV renders the first maxRows products as CSV (header = union of +// their columns, first-seen order) so the schema preview can reuse extractCSVSchema. +func excelSchemaCSV(path, sheet string, maxRows int) ([]byte, error) { + var ( + header []string + index = map[string]int{} + rows []map[string]string + ) + err := readExcelSource(path, sheet, func(cols, rec []string) error { + if len(rows) >= maxRows { + return errExcelStop + } + row := make(map[string]string, len(cols)) + for i, col := range cols { + if col == "" { + continue + } + if _, ok := index[col]; !ok { + index[col] = len(header) + header = append(header, col) + } + if i < len(rec) { + row[col] = rec[i] + } + } + rows = append(rows, row) + return nil + }) + if err != nil && !errors.Is(err, errExcelStop) { + return nil, err + } + var buf bytes.Buffer + w := csv.NewWriter(&buf) + if err := w.Write(header); err != nil { + return nil, err + } + for _, row := range rows { + rec := make([]string, len(header)) + for i, col := range header { + rec[i] = row[col] + } + if err := w.Write(rec); err != nil { + return nil, err + } + } + w.Flush() + return buf.Bytes(), w.Error() +} + +// readExcelSource calls onData once per product with its column names and values. +// path is a workbook or a zip archive of workbooks (e.g. one file per product). +func readExcelSource(path, sheet string, onData func(cols, rec []string) error) error { + info, err := os.Stat(path) + if err != nil { + return err + } + sample, err := (&feedBlob{path: path}).Sniff(len(oleMagic)) + if err != nil { + return err + } + if bytes.HasPrefix(sample, zipMagic) { + zr, err := zip.OpenReader(path) + if err != nil { + return ClientMsg(fmt.Sprintf("could not read Excel file: %v", err)) + } + defer zr.Close() + if !isOOXMLPackage(&zr.Reader) { + return readExcelArchive(&zr.Reader, sheet, onData) + } + } + if info.Size() > maxExcelBytes { + return ClientMsg(fmt.Sprintf("Excel file exceeds %d MiB; export the product sheet as CSV instead", maxExcelBytes>>20)) + } + return readExcelWorkbook(path, sheet, onData) +} + +func isOOXMLPackage(zr *zip.Reader) bool { + for _, f := range zr.File { + if f.Name == "[Content_Types].xml" || strings.HasPrefix(f.Name, "xl/") { + return true + } + } + return false +} + +// readExcelArchive reads every workbook in a zip, in name order, as one feed. +func readExcelArchive(zr *zip.Reader, sheet string, onData func(cols, rec []string) error) error { + files := make([]*zip.File, 0, len(zr.File)) + for _, f := range zr.File { + base := path.Base(f.Name) + if f.FileInfo().IsDir() || strings.HasPrefix(f.Name, "__MACOSX/") || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "~$") { + continue + } + if isWorkbookName(base) { + files = append(files, f) + } + } + if len(files) == 0 { + return ClientMsg("zip contains no Excel files (.xls, .xlsx, .xlsm)") + } + if len(files) > maxExcelArchiveEntries { + return ClientMsg(fmt.Sprintf("zip contains more than %d Excel files", maxExcelArchiveEntries)) + } + sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name }) + var total int64 + for _, f := range files { + tmp, n, err := extractZipEntry(f) + if err != nil { + return err + } + total += n + if total > maxExcelArchiveBytes { + _ = os.Remove(tmp) + return ClientMsg(fmt.Sprintf("zip content exceeds %d MiB", maxExcelArchiveBytes>>20)) + } + err = readExcelWorkbook(tmp, sheet, onData) + _ = os.Remove(tmp) + if err != nil { + if errors.Is(err, errExcelStop) { + return err + } + return fmt.Errorf("%s: %w", path.Base(f.Name), err) + } + } + return nil +} + +func extractZipEntry(f *zip.File) (string, int64, error) { + rc, err := f.Open() + if err != nil { + return "", 0, ClientMsg(fmt.Sprintf("could not read %s from zip: %v", path.Base(f.Name), err)) + } + defer rc.Close() + out, err := os.CreateTemp("", "descrybe-xl-*"+path.Ext(f.Name)) + if err != nil { + return "", 0, err + } + n, err := io.Copy(out, io.LimitReader(rc, maxExcelBytes+1)) + if cerr := out.Close(); err == nil { + err = cerr + } + if err == nil && n > maxExcelBytes { + err = ClientMsg(fmt.Sprintf("%s exceeds %d MiB", path.Base(f.Name), maxExcelBytes>>20)) + } + if err != nil { + _ = os.Remove(out.Name()) + return "", 0, err + } + return out.Name(), n, nil +} + +// readExcelWorkbook emits one product for record-layout workbooks (a product sheet +// of label | value rows, e.g. GroupeSeb), else one per data row of the chosen sheet. +func readExcelWorkbook(path, sheet string, onData func(cols, rec []string) error) error { + wb, err := openWorkbook(path) + if err != nil { + return err + } + defer wb.Close() + names := wb.Sheets() + if len(names) == 0 { + return ClientMsg("Excel workbook has no visible sheets") + } + if strings.TrimSpace(sheet) == "" { + record, err := isRecordWorkbook(wb, names) + if err != nil { + return err + } + if record { + return readExcelRecord(wb, names, onData) + } + } + name, err := pickSheet(wb, names, sheet) + if err != nil { + return err + } + return readExcelTable(wb, name, onData) +} + +// isRecordWorkbook looks for a two-cell "EAN Code | 3168430313385" row: a barcode +// labelled in one column with its value beside it, instead of a header row. +func isRecordWorkbook(wb workbook, names []string) (bool, error) { + found := false + for _, name := range names { + n := 0 + err := wb.Rows(name, func(rec []string) error { + if n++; n > excelRecordScanRows { + return errExcelStop + } + cells := excelFilledCells(rec) + if len(cells) == 2 && excelBarcodeLabel.MatchString(cells[0]) && excelBarcodeValue.MatchString(cells[1]) { + found = true + return errExcelStop + } + return nil + }) + if err != nil && !errors.Is(err, errExcelStop) { + return false, err + } + if found { + return true, nil + } + } + return false, nil +} + +// readExcelRecord turns every sheet into label → value pairs. The sheet's value +// column is its rightmost used column; cells left of it form the label ("Product +// packshot - H1 Image Url"), and rows with no value there are skipped (MEDIA rows +// list "Media Id / Image Url / Picture …" slots, most of them empty). An all-caps +// title alone in the first column starts a section that prefixes the labels below +// it ("TECHNICAL CHARACTERISTICS/Dimenzija"), so a block maps as one source. +// GUID-only values (internal media ids) are dropped. Repeated labels collect their +// distinct values comma-separated. +func readExcelRecord(wb workbook, names []string, onData func(cols, rec []string) error) error { + var cols, vals []string + index := map[string]int{} + for _, name := range names { + valueCol := -1 + if err := wb.Rows(name, func(rec []string) error { + if last := excelLastFilled(rec); last > valueCol && excelFilledCount(rec) >= 2 { + valueCol = last + } + return nil + }); err != nil { + return err + } + section := "" + err := wb.Rows(name, func(rec []string) error { + cells := excelFilledCells(rec) + if len(cells) == 1 && excelFirstFilled(rec) == 0 && isExcelSectionTitle(cells[0]) { + section = strings.ReplaceAll(cells[0], "/", "-") + return nil + } + if len(cells) < 2 || excelLastFilled(rec) != valueCol || isGUIDList(cells[len(cells)-1]) { + return nil // sub-heading, label without a value, or media id + } + label := strings.Join(cells[:len(cells)-1], " ") + if section != "" { + label = section + "/" + strings.ReplaceAll(label, "/", "-") + } + value := cells[len(cells)-1] + i, ok := index[label] + if !ok { + index[label] = len(cols) + cols = append(cols, label) + vals = append(vals, value) + return nil + } + for _, prev := range strings.Split(vals[i], ",") { + if prev == value { + return nil + } + } + vals[i] += "," + value + return nil + }) + if err != nil { + return err + } + } + if len(cols) == 0 { + return ClientMsg("Excel sheet contains no rows") + } + return onData(cols, vals) +} + +func excelFirstFilled(rec []string) int { + for i, v := range rec { + if strings.TrimSpace(v) != "" { + return i + } + } + return -1 +} + +func excelLastFilled(rec []string) int { + for i := len(rec) - 1; i >= 0; i-- { + if strings.TrimSpace(rec[i]) != "" { + return i + } + } + return -1 +} + +// isGUIDList matches "00C4DE5B-EB9B-4B3C-96E4931062A667CD" and ;/, lists of them. +func isGUIDList(v string) bool { + parts := strings.FieldsFunc(v, func(r rune) bool { return r == ';' || r == ',' || unicode.IsSpace(r) }) + if len(parts) == 0 { + return false + } + for _, p := range parts { + if !excelGUID.MatchString(p) { + return false + } + } + return true +} + +// isExcelSectionTitle matches headings like "TECHNICAL CHARACTERISTICS" or "FAQ". +func isExcelSectionTitle(s string) bool { + hasLetter := false + for _, r := range s { + if unicode.IsLetter(r) { + hasLetter = true + if unicode.IsLower(r) { + return false + } + } + } + return hasLetter +} + +// excelFilledCells returns the trimmed non-empty cells with inner whitespace collapsed. +func excelFilledCells(rec []string) []string { + out := make([]string, 0, 4) + for _, v := range rec { + if v = strings.Join(strings.Fields(v), " "); v != "" { + out = append(out, v) + } + } + return out +} + +// readExcelTable finds the header row of the sheet and calls onData with the header +// columns and each following non-empty row. +func readExcelTable(wb workbook, sheet string, onData func(cols, rec []string) error) error { + var ( + cols []string + pending [][]string + ) + flushPending := func() error { + cols = excelHeaderColumns(pending) + for _, rec := range pending[excelHeaderIndex(pending)+1:] { + if err := onData(cols, rec); err != nil { + return err + } + } + pending = nil + return nil + } + err := wb.Rows(sheet, func(rec []string) error { + if excelRowEmpty(rec) { + return nil + } + if cols != nil { + return onData(cols, rec) + } + pending = append(pending, append([]string(nil), rec...)) + if len(pending) < excelHeaderScanRows { + return nil + } + return flushPending() + }) + if err != nil { + return err + } + if cols == nil { + if len(pending) == 0 { + return ClientMsg("Excel sheet contains no rows") + } + return flushPending() + } + return nil +} + +// excelHeaderIndex picks the first row filled at least half as wide as the widest +// buffered row (and with 2+ cells when possible), skipping title/date lines above +// the real header. +func excelHeaderIndex(rows [][]string) int { + widest := 0 + for _, r := range rows { + widest = max(widest, excelFilledCount(r)) + } + need := max(min(widest, 2), (widest+1)/2) + for i, r := range rows { + if excelFilledCount(r) >= need { + return i + } + } + return 0 +} + +// excelHeaderColumns trims header names and makes duplicates unique ("Opis", "Opis (2)"). +func excelHeaderColumns(rows [][]string) []string { + header := rows[excelHeaderIndex(rows)] + cols := make([]string, len(header)) + seen := make(map[string]int, len(header)) + for i, h := range header { + name := strings.Join(strings.Fields(strings.TrimPrefix(h, string(rune(0xFEFF)))), " ") + if name == "" { + continue + } + seen[strings.ToLower(name)]++ + if n := seen[strings.ToLower(name)]; n > 1 { + name = fmt.Sprintf("%s (%d)", name, n) + } + cols[i] = name + } + return cols +} + +func excelFilledCount(rec []string) int { + n := 0 + for _, v := range rec { + if strings.TrimSpace(v) != "" { + n++ + } + } + return n +} + +func excelRowEmpty(rec []string) bool { return excelFilledCount(rec) == 0 } + +// pickSheet returns the requested sheet, else the visible sheet with the most rows. +func pickSheet(wb workbook, names []string, sheet string) (string, error) { + if sheet = strings.TrimSpace(sheet); sheet != "" { + for _, name := range names { + if strings.EqualFold(name, sheet) { + return name, nil + } + } + return "", ClientMsg(fmt.Sprintf("Excel sheet %q not found", sheet)) + } + best, bestRows := names[0], -1 + for _, name := range names { + n, err := wb.RowCount(name) + if err != nil { + return "", err + } + if n > bestRows { + best, bestRows = name, n + } + } + return best, nil +} + +// workbook is the read surface shared by OOXML (.xlsx/.xlsm) and BIFF (.xls). +type workbook interface { + // Sheets lists visible sheets in workbook order. + Sheets() []string + // Rows streams the cell strings of every row; returning an error stops early. + Rows(sheet string, onRow func([]string) error) error + RowCount(sheet string) (int, error) + Close() error +} + +func openWorkbook(path string) (workbook, error) { + sample, err := (&feedBlob{path: path}).Sniff(len(oleMagic)) + if err != nil { + return nil, err + } + if bytes.HasPrefix(sample, oleMagic) { + wb, err := xls.Open(path) + if err != nil { + return nil, ClientMsg(fmt.Sprintf("could not read Excel workbook: %v", err)) + } + return &xlsWorkbook{src: wb}, nil + } + f, err := excelize.OpenFile(path, excelize.Options{ + UnzipSizeLimit: 4 * maxExcelBytes, + UnzipXMLSizeLimit: 2 * maxExcelBytes, + }) + if err != nil { + return nil, ClientMsg(fmt.Sprintf("could not read Excel workbook: %v", err)) + } + return &xlsxWorkbook{f: f}, nil +} + +type xlsxWorkbook struct{ f *excelize.File } + +func (w *xlsxWorkbook) Close() error { return w.f.Close() } + +func (w *xlsxWorkbook) Sheets() []string { + var out []string + for _, name := range w.f.GetSheetList() { + if visible, err := w.f.GetSheetVisible(name); err == nil && !visible { + continue + } + out = append(out, name) + } + return out +} + +func (w *xlsxWorkbook) RowCount(sheet string) (int, error) { + rows, err := w.f.Rows(sheet) + if err != nil { + return 0, err + } + defer rows.Close() + n := 0 + for rows.Next() { + n++ + } + return n, rows.Error() +} + +// Rows runs two iterators in lockstep: formatted values are preferred (dates, +// percentages), raw values rescue long numeric codes shown as 3.83002E+12. +func (w *xlsxWorkbook) Rows(sheet string, onRow func([]string) error) error { + shown, err := w.f.Rows(sheet) + if err != nil { + return err + } + defer shown.Close() + raw, err := w.f.Rows(sheet) + if err != nil { + return err + } + defer raw.Close() + for shown.Next() && raw.Next() { + vals, err := shown.Columns() + if err != nil { + return err + } + raws, err := raw.Columns(excelize.Options{RawCellValue: true}) + if err != nil { + return err + } + for i := range vals { + if i < len(raws) && preferRawExcelValue(vals[i], raws[i]) { + vals[i] = raws[i] + } + } + if err := onRow(vals); err != nil { + return err + } + } + return shown.Error() +} + +// preferRawExcelValue keeps barcodes/SKUs intact when the display format rounds them. +func preferRawExcelValue(shown, raw string) bool { + if shown == raw || raw == "" { + return false + } + digits := strings.TrimSuffix(raw, ".0") + if len(digits) < 8 { + return false + } + for _, r := range digits { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// xlsWorkbook reads legacy BIFF .xls via the vendored, patched grate +// (third_party/grate). Cells are formatted here instead of via grate's Strings() +// so integers stay plain digits (barcodes) and dates use ISO format. +type xlsWorkbook struct { + src grate.Source + sheets map[string]*commonxl.Sheet +} + +func (w *xlsWorkbook) Close() error { return w.src.Close() } + +func (w *xlsWorkbook) Sheets() []string { + names, err := w.src.List() + if err != nil { + return nil + } + return names +} + +func (w *xlsWorkbook) sheet(name string) (*commonxl.Sheet, error) { + if s, ok := w.sheets[name]; ok { + return s, nil + } + c, err := w.src.Get(name) + if err != nil { + return nil, err + } + s, ok := c.(*commonxl.Sheet) + if !ok { + return nil, fmt.Errorf("excel: unexpected sheet type %T", c) + } + if w.sheets == nil { + w.sheets = map[string]*commonxl.Sheet{} + } + w.sheets[name] = s + return s, nil +} + +func (w *xlsWorkbook) RowCount(sheet string) (int, error) { + s, err := w.sheet(sheet) + if err != nil { + return 0, err + } + return s.NumRows, nil +} + +func (w *xlsWorkbook) Rows(sheet string, onRow func([]string) error) error { + s, err := w.sheet(sheet) + if err != nil { + return err + } + // Rewind: a sheet is cached and may be read twice (record scan, then table). + s.CurRow = 0 + for s.Next() { + cells := s.Raw() + rec := make([]string, len(cells)) + for i, c := range cells { + rec[i] = xlsCellString(s.Formatter, c) + } + if err := onRow(rec); err != nil { + return err + } + } + return s.Err() +} + +func xlsCellString(f *commonxl.Formatter, c commonxl.Cell) string { + if c.Type() == commonxl.StaticCell { + return "" // merged-cell placeholder + } + switch v := c.Value().(type) { + case nil: + return "" + case string: + return strings.TrimSpace(v) + case bool: + if v { + return "TRUE" + } + return "FALSE" + case int64: + return strconv.FormatInt(v, 10) + case float64: + if c.Type() == commonxl.DateCell && f != nil { + return f.ConvertToDate(v).Format(time.DateOnly) + } + if v == math.Trunc(v) && math.Abs(v) < 1e15 { + return strconv.FormatInt(int64(v), 10) + } + return strconv.FormatFloat(v, 'f', -1, 64) + case time.Time: + return v.Format(time.DateOnly) + default: + return strings.TrimSpace(fmt.Sprint(v)) + } +} diff --git a/apps/api/internal/feeds/excel_test.go b/apps/api/internal/feeds/excel_test.go new file mode 100644 index 0000000..9b91b15 --- /dev/null +++ b/apps/api/internal/feeds/excel_test.go @@ -0,0 +1,288 @@ +package feeds + +import ( + "archive/zip" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/xuri/excelize/v2" +) + +func writeTestXLSX(t *testing.T) string { + t.Helper() + f := excelize.NewFile() + defer f.Close() + // A hidden helper sheet with more rows must not win the sheet pick. + if _, err := f.NewSheet("Lookup"); err != nil { + t.Fatal(err) + } + for i := 1; i <= 40; i++ { + _ = f.SetCellValue("Lookup", "A"+strconv.Itoa(i), "x") + } + if err := f.SetSheetVisible("Lookup", false); err != nil { + t.Fatal(err) + } + rows := [][]any{ + {"Cenik dobavitelja 2026"}, + {}, + {"EAN", "Artikel", "Opis", "Opis", "Cena"}, + {int64(3830023210103), "UMETNA ČREVA KAL.55", "Kolagena", "", 12.5}, + {}, + {int64(8595025338228), "VODNIK KOAKSIALNI", "", "75 OHM", 3}, + } + for r, row := range rows { + for c, v := range row { + cell, _ := excelize.CoordinatesToCellName(c+1, r+1) + if err := f.SetCellValue("Sheet1", cell, v); err != nil { + t.Fatal(err) + } + } + } + // Scientific display format must not leak into barcodes. + style, err := f.NewStyle(&excelize.Style{NumFmt: 11}) + if err != nil { + t.Fatal(err) + } + if err := f.SetCellStyle("Sheet1", "A4", "A6", style); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "feed.xlsx") + if err := f.SaveAs(path); err != nil { + t.Fatal(err) + } + return path +} + +func TestParseExcelXLSXFindsHeaderAndKeepsBarcodes(t *testing.T) { + path := writeTestXLSX(t) + mappings := []FieldMapping{{Source: "EAN", Target: "gtin"}, {Source: "Artikel", Target: "title"}} + var got []feedRow + n, err := parseExcel(path, "", func(row feedRow) error { + got = append(got, row) + return nil + }) + if err != nil || n != 2 || len(got) != 2 { + t.Fatalf("n=%d rows=%v err=%v", n, got, err) + } + if _, gtin := applyMappings(got[0], mappings); gtin != "3830023210103" { + t.Fatalf("gtin = %q, row %v", gtin, got[0]) + } + if got[0]["Artikel"] != "UMETNA ČREVA KAL.55" || got[1]["Opis (2)"] != "75 OHM" || got[0]["Cena"] != "12.5" { + t.Fatalf("unexpected rows: %v", got) + } +} + +func TestExcelSchemaCSVPreview(t *testing.T) { + data, err := excelSchemaCSV(writeTestXLSX(t), "", schemaMaxRows) + if err != nil { + t.Fatal(err) + } + fields, rows, _, err := extractCSVSchema(data) + if err != nil || rows != 2 { + t.Fatalf("rows=%d err=%v", rows, err) + } + names := map[string]bool{} + for _, f := range fields { + names[f.Path] = true + } + for _, want := range []string{"EAN", "Artikel", "Opis", "Opis (2)", "Cena"} { + if !names[want] { + t.Fatalf("missing field %q in %v", want, names) + } + } +} + +func TestDetectFeedFormatExcel(t *testing.T) { + cases := []struct { + feedType, ct, url string + sample []byte + }{ + {"csv", "text/csv", "", oleMagic}, // local upload labelled text/csv + {"", "", "", append([]byte(nil), zipMagic...)}, // xlsx sniff + {"", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "", nil}, + {"", "", "https://example.com/cenik.XLSX?dl=1", nil}, + {"excel", "", "", nil}, + } + for _, c := range cases { + if got := detectFeedFormat(c.feedType, c.ct, c.url, c.sample); got != "excel" { + t.Errorf("detectFeedFormat(%q,%q,%q) = %q", c.feedType, c.ct, c.url, got) + } + } + if got := detectFeedFormat("", "text/csv", "feed.csv", []byte("gtin,title\n")); got != "csv" { + t.Errorf("csv detected as %q", got) + } +} + +func TestExcelHeaderIndexSkipsTitleRows(t *testing.T) { + rows := [][]string{{"Izpis cenika"}, {"Šifra", "ARTIKEL"}, {"3830023212305", "APARAT"}} + if i := excelHeaderIndex(rows); i != 1 { + t.Fatalf("header index = %d", i) + } +} + +// Real supplier workbooks from the pilot (repo-root examples/); skipped when absent. +func TestParseExcelSupplierExamples(t *testing.T) { + cases := map[string]struct{ gtinCol, wantGTIN string }{ + "KOOPMAN.xls": {"Barcode", "8721461009242"}, + "Kopija datoteke Trbovc_Izpis cenika za dobavitelja_22092026.xls": {"Šifra", "3830023212305"}, + "Artikli za splet Mark01 Descrybe.xlsx": {"EAN", "3830023210103"}, + } + for name, c := range cases { + path := filepath.Join("..", "..", "..", "..", "examples", name) + if _, err := os.Stat(path); err != nil { + t.Logf("skip %s: %v", name, err) + continue + } + var first feedRow + n, err := parseExcel(path, "", func(row feedRow) error { + if first == nil { + first = row + } + return nil + }) + if err != nil || n == 0 { + t.Fatalf("%s: n=%d err=%v", name, n, err) + } + if first[c.gtinCol] != c.wantGTIN { + t.Fatalf("%s: %s = %q, row %v", name, c.gtinCol, first[c.gtinCol], first) + } + t.Logf("%s: %d rows, first %v", name, n, first) + } +} + +func writeRecordXLSX(t *testing.T, dir, name, ean, title string) string { + t.Helper() + f := excelize.NewFile() + defer f.Close() + rows := [][]any{ + {"RANGE TABLE"}, + {"PRODUCT INFORMATION"}, + {"Commercial Name", title}, + {"Set description"}, + {"EAN Code", ean}, + {"Product packshot - H1", "00C4DE5B-EB9B-4B3C-96E4931062A667CD"}, + {"TECHNICAL CHARACTERISTICS"}, + {"", "GLAVNE LASTNOSTI"}, + {"Dimenzija", "24 cm"}, + } + for r, row := range rows { + for c, v := range row { + cell, _ := excelize.CoordinatesToCellName(c+1, r+1) + _ = f.SetCellValue("Sheet1", cell, v) + } + } + if _, err := f.NewSheet("MEDIA"); err != nil { + t.Fatal(err) + } + media := [][]any{ + {"Product packshot - H1", "Image Url", "https://cdn.example/a.jpg"}, + {"Other packshots", "Image Url", "https://cdn.example/b.jpg"}, + {"Other packshots", "Image Url", "https://cdn.example/c.jpg"}, + {"Benefit image 11", "Media Id"}, + } + for r, row := range media { + for c, v := range row { + cell, _ := excelize.CoordinatesToCellName(c+1, r+1) + _ = f.SetCellValue("MEDIA", cell, v) + } + } + p := filepath.Join(dir, name) + if err := f.SaveAs(p); err != nil { + t.Fatal(err) + } + return p +} + +func TestParseExcelRecordWorkbookIsOneProduct(t *testing.T) { + p := writeRecordXLSX(t, t.TempDir(), "B1.xlsm", "3168430313385", "SIMPLY CLEAN FRYPAN 24 CM") + var rows []feedRow + n, err := parseExcel(p, "", func(r feedRow) error { rows = append(rows, r); return nil }) + if err != nil || n != 1 { + t.Fatalf("n=%d err=%v rows=%v", n, err, rows) + } + r := rows[0] + if r["PRODUCT INFORMATION/EAN Code"] != "3168430313385" || r["PRODUCT INFORMATION/Commercial Name"] != "SIMPLY CLEAN FRYPAN 24 CM" || r["TECHNICAL CHARACTERISTICS/Dimenzija"] != "24 cm" { + t.Fatalf("record fields: %v", r) + } + if r["Product packshot - H1 Image Url"] != "https://cdn.example/a.jpg" || + r["Other packshots Image Url"] != "https://cdn.example/b.jpg,https://cdn.example/c.jpg" { + t.Fatalf("media fields: %v", r) + } + for _, junk := range []string{"PRODUCT INFORMATION/Set description", "Benefit image 11", "PRODUCT INFORMATION/Product packshot - H1"} { + if _, ok := r[junk]; ok { + t.Fatalf("%q must be skipped (no value / media id): %v", junk, r) + } + } +} + +func TestParseExcelZipOfWorkbooks(t *testing.T) { + dir := t.TempDir() + a := writeRecordXLSX(t, dir, "A.xlsm", "3168430313385", "Pan A") + b := writeRecordXLSX(t, dir, "B.xlsm", "3168430313392", "Pan B") + zipPath := filepath.Join(dir, "groupeseb.zip") + out, err := os.Create(zipPath) + if err != nil { + t.Fatal(err) + } + zw := zip.NewWriter(out) + for _, p := range []string{b, a} { + w, err := zw.Create("seb/" + filepath.Base(p)) + if err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(p) + _, _ = w.Write(data) + } + _, _ = zw.Create("__MACOSX/seb/._A.xlsm") + if err := zw.Close(); err != nil { + t.Fatal(err) + } + _ = out.Close() + + if got := detectFeedFormat("", "", "", []byte(string(zipMagic))); got != "excel" { + t.Fatalf("zip detected as %q", got) + } + var eans []string + n, err := parseExcel(zipPath, "", func(r feedRow) error { eans = append(eans, r["PRODUCT INFORMATION/EAN Code"]); return nil }) + if err != nil || n != 2 || eans[0] != "3168430313385" || eans[1] != "3168430313392" { + t.Fatalf("n=%d eans=%v err=%v", n, eans, err) + } + data, err := excelSchemaCSV(zipPath, "", schemaMaxRows) + if err != nil { + t.Fatal(err) + } + if _, rows, _, err := extractCSVSchema(data); err != nil || rows != 2 { + t.Fatalf("schema rows=%d err=%v", rows, err) + } +} + +func TestParseExcelGroupeSebExample(t *testing.T) { + p := filepath.Join("..", "..", "..", "..", "examples", "pilot-4-suppliers", "groupe-seb", "B5670453.xlsm") + if _, err := os.Stat(p); err != nil { + t.Skipf("example missing: %v", err) + } + var r feedRow + n, err := parseExcel(p, "", func(row feedRow) error { r = row; return nil }) + if err != nil || n != 1 { + t.Fatalf("n=%d err=%v", n, err) + } + for k, want := range map[string]string{ + "LOGISTICS DATA/EAN Code": "3168430313385", + "PRODUCT INFORMATION/Brand": "TEFAL", + "TECHNICAL CHARACTERISTICS/Dimenzija": "24 cm", + } { + if r[k] != want { + t.Fatalf("%s = %q want %q", k, r[k], want) + } + } + if !strings.HasPrefix(r["Product packshot - H1 Image Url"], "https://") || r["MARKETING INFORMATION/Short description detail"] == "" { + t.Fatalf("missing media/short description: %v", r) + } + if specs := resolveSpecifications(r, "TECHNICAL CHARACTERISTICS"); len(specs) < 10 { + t.Fatalf("technical characteristics as specs: %v", specs) + } + t.Logf("%d fields", len(r)) +} diff --git a/apps/api/internal/feeds/export.go b/apps/api/internal/feeds/export.go index c552a48..761576c 100644 --- a/apps/api/internal/feeds/export.go +++ b/apps/api/internal/feeds/export.go @@ -80,6 +80,8 @@ type exportProduct struct { ProcessedAttributes []byte MappedData []byte FeedID *uuid.UUID + MetaTitle *string + MetaDescription *string } // Known EPREL / energy-label source aliases resolved from processed JSON. @@ -296,7 +298,7 @@ func (s *Service) queryExportProductsBatch( return s.Pool.Query(ctx, ` SELECT p.id, p.updated_at, p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name, p.status, p.attributes, p.processed_attributes, - COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id + COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id, p.meta_title, p.meta_description FROM processed_products p LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id WHERE p.company_id = $1 @@ -402,6 +404,17 @@ func productFieldValue(p exportProduct, source string) string { return derefStr(p.ProcessedDescription) case "processed_name": return derefStr(p.ProcessedName) + case "meta_title": + return derefStr(p.MetaTitle) + case "meta_description": + return derefStr(p.MetaDescription) + case "short_description", "short_desc": + // Supplier-mapped short copy wins; else the generated meta description, + // matching the WooCommerce sync's short_description. + if v := lookupFlattened(flattenProductAttrs(p), "short_description"); v != "" { + return v + } + return derefStr(p.MetaDescription) case "status": return derefStr(p.Status) case "feed_id": @@ -706,6 +719,7 @@ func scanExportProduct(rows pgx.Rows) (exportProduct, error) { err := rows.Scan( &p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName, &p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID, + &p.MetaTitle, &p.MetaDescription, ) return p, err } @@ -720,6 +734,7 @@ func scanExportProductWithCursor(rows pgx.Rows) (exportProduct, uuid.UUID, time. &id, &updatedAt, &p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName, &p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID, + &p.MetaTitle, &p.MetaDescription, ) return p, id, updatedAt, err } @@ -1000,7 +1015,7 @@ func (s *Service) queryExportProductsByIDs(ctx context.Context, companyID uuid.U return s.Pool.Query(ctx, ` SELECT p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name, p.status, p.attributes, p.processed_attributes, - COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id + COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id, p.meta_title, p.meta_description FROM processed_products p LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id WHERE p.company_id = $1 diff --git a/apps/api/internal/feeds/export_short_description_test.go b/apps/api/internal/feeds/export_short_description_test.go new file mode 100644 index 0000000..822b5f7 --- /dev/null +++ b/apps/api/internal/feeds/export_short_description_test.go @@ -0,0 +1,18 @@ +package feeds + +import "testing" + +func TestProductFieldValueShortDescription(t *testing.T) { + meta := "Ponev Tefal Simply Clean 24 cm z oblogo s titanom." + generated := exportProduct{MetaDescription: &meta, MappedData: []byte(`{"gtin":"3168430313385"}`)} + if got := productFieldValue(generated, "short_description"); got != meta { + t.Fatalf("fallback short_description = %q", got) + } + supplier := exportProduct{MetaDescription: &meta, MappedData: []byte(`{"short_description":"Vsi vemo, da je za okusno kuho potreben čas."}`)} + if got := productFieldValue(supplier, "short_description"); got != "Vsi vemo, da je za okusno kuho potreben čas." { + t.Fatalf("mapped short_description = %q", got) + } + if got := productFieldValue(generated, "meta_description"); got != meta { + t.Fatalf("meta_description = %q", got) + } +} diff --git a/apps/api/internal/feeds/extract_schema.go b/apps/api/internal/feeds/extract_schema.go index 6cded2f..7ce7ed4 100644 --- a/apps/api/internal/feeds/extract_schema.go +++ b/apps/api/internal/feeds/extract_schema.go @@ -134,6 +134,20 @@ func (s *Service) ExtractSchema(ctx context.Context, companyID, feedID uuid.UUID preview = preview[:4096] } out.Preview = string(preview) + case "excel": + // Workbooks need the whole file (zip/OLE directory), so read from disk, not the sample. + sheetCSV, err := excelSchemaCSV(f.Name(), excelSheetOption(feed), schemaMaxRows) + if err != nil { + return nil, err + } + fields, rows, preview, err := extractCSVSchema(sheetCSV) + if err != nil { + return nil, err + } + out.Fields = fields + out.SampleRows = rows + out.Preview = preview + out.PreviewTruncated = false default: fields, rows, preview, err := extractCSVSchema(data) if err != nil { @@ -254,6 +268,9 @@ func guessXMLItemPath(data []byte) string { } } } + if path := guessRepeatedXMLItemPath([]byte(sample)); path != "" { + return path + } return "rss/channel/item" } @@ -302,7 +319,8 @@ func extractXMLSchema(data []byte, itemLocal string) ([]SchemaField, int, error) accumulateRowFields(acc, row) return nil }) - if err != nil && !errors.Is(err, errStopSchema) { + // The preview window cuts large feeds mid-record; rows read before the cut count. + if err != nil && !errors.Is(err, errStopSchema) && !(rows > 0 && strings.Contains(err.Error(), "unexpected EOF")) { return nil, rows, err } return finalizeSchema(acc), rows, nil diff --git a/apps/api/internal/feeds/parse.go b/apps/api/internal/feeds/parse.go index 727da18..f41cce1 100644 --- a/apps/api/internal/feeds/parse.go +++ b/apps/api/internal/feeds/parse.go @@ -31,12 +31,18 @@ type feedRow map[string]string func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string { ft := strings.ToLower(strings.TrimSpace(feedType)) + // Binary workbooks win over the declared type: local uploads default to text/csv. + if ft == "excel" || isExcelSample(sample) { + return "excel" + } if ft == "csv" || ft == "xml" || ft == "json" { return ft } ct := strings.ToLower(contentType) u := strings.ToLower(urlHint) switch { + case isExcelContentType(ct) || isExcelName(u): + return "excel" case strings.Contains(ct, "json") || strings.Contains(u, ".json") || strings.Contains(u, "format=json"): return "json" case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"): @@ -183,13 +189,75 @@ func guessXMLItemLocal(data []byte) string { return cand } } + if p := guessRepeatedXMLItemPath([]byte(sample)); p != "" { + return leafName(p) + } return "item" } +// guessRepeatedXMLItemPath finds the record element of feeds with non-English tags +// (…): the most repeated element that has child elements, the +// shallowest on ties. Tolerates a truncated sample. +func guessRepeatedXMLItemPath(data []byte) string { + dec := xml.NewDecoder(bytes.NewReader(data)) + dec.Strict = false + var stack []string + counts := map[string]int{} + hasChildren := map[string]bool{} + for { + tok, err := dec.Token() + if err != nil { + break + } + switch t := tok.(type) { + case xml.StartElement: + if len(stack) > 0 { + hasChildren[strings.Join(stack, "/")] = true + } + stack = append(stack, t.Name.Local) + counts[strings.Join(stack, "/")]++ + case xml.EndElement: + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + } + } + best, bestN := "", 1 + for p, n := range counts { + if !hasChildren[p] { + continue + } + depth, bestDepth := strings.Count(p, "/"), strings.Count(best, "/") + if n > bestN || (n == bestN && best != "" && (depth < bestDepth || (depth == bestDepth && p < best))) { + best, bestN = p, n + } + } + return best +} + func localNameEquals(n xml.Name, local string) bool { return strings.EqualFold(n.Local, local) } +// isXMLPropertyNameAttr lists attributes that name a property element +// (, ). +func isXMLPropertyNameAttr(local string) bool { + switch strings.ToLower(local) { + case "naziv", "name", "ime", "key", "label": + return true + } + return false +} + +func xmlPropertyLabel(attrs []xml.Attr) string { + for _, a := range attrs { + if isXMLPropertyNameAttr(a.Name.Local) { + return sanitizePathSegment(a.Value) + } + } + return "" +} + func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error) { row := make(feedRow) for _, a := range start.Attr { @@ -198,6 +266,12 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error row[start.Name.Local+"/"+key] = a.Value } var path []string + // propNames[i] is the label of path[i] when it is a named property inside a group, + // such as Nahrbtnik… (else ""). + // Its text is also stored under group/