This commit is contained in:
greeneclipse committed 2026-10-27 14:53:19 +01:00
1 parent c347d2418f
commit 1ad180a052
49 files changed
+6339 -89

No files matched your search

+25 -7
View File
@@ -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
+756
View File
@@ -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))
}
}
+288
View File
@@ -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))
}
+17 -2
View File
@@ -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
@@ -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)
}
}
+19 -1
View File
@@ -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
+96
View File
@@ -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
// (<izdelki><izdelek>…): 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
// (<lastnost naziv="…">, <param name="…">).
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 <dodatneLastnosti><lastnost naziv="Vrsta">Nahrbtnik</lastnost>… (else "").
// Its text is also stored under group/<label>; propCounts tracks group/leaf paths
// so the merged "all siblings" value can be dropped once two labels share it.
var propNames []string
propCounts := map[string]int{}
var paramName, paramValue string
for {
tok, err := dec.Token()
@@ -207,6 +281,14 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
switch t := tok.(type) {
case xml.StartElement:
path = append(path, t.Name.Local)
label := ""
if len(path) >= 2 {
label = xmlPropertyLabel(t.Attr)
}
if label != "" {
propCounts[strings.Join(path, "/")]++
}
propNames = append(propNames, label)
for _, a := range t.Attr {
key := strings.Join(path, "/") + "/@" + a.Name.Local
row["@"+a.Name.Local] = a.Value
@@ -225,6 +307,11 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
paramName, paramValue = "", ""
}
if len(path) == 0 {
for p, n := range propCounts {
if n > 1 {
delete(row, p) // "MicroUSB 1 m": every sibling's text merged
}
}
count := 0
for k := range row {
if strings.HasPrefix(k, "PARAMS/") && !strings.Contains(strings.TrimPrefix(k, "PARAMS/"), "/") {
@@ -248,11 +335,20 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
return row, nil
}
path = path[:len(path)-1]
propNames = propNames[:len(propNames)-1]
case xml.CharData:
text := strings.TrimSpace(string(t))
if text == "" || len(path) == 0 {
continue
}
if label := propNames[len(propNames)-1]; label != "" {
key := strings.Join(append(path[:len(path)-1:len(path)-1], label), "/")
if prev := row[key]; prev != "" && prev != text {
row[key] = prev + " " + text
} else {
row[key] = text
}
}
leaf := path[len(path)-1]
if len(path) >= 3 && strings.EqualFold(path[len(path)-3], "PARAMS") && strings.EqualFold(path[len(path)-2], "PARAM") {
if strings.EqualFold(leaf, "PARAM_NAME") {
@@ -0,0 +1,42 @@
package feeds
import (
"strings"
"testing"
)
// Janus Trade / Avtera: repeated <lastnost naziv="…"> siblings are separate specs.
func TestParseXMLNamedPropertiesBecomeSpecs(t *testing.T) {
body := `<podjetje><izdelki><izdelek st="1"><EAN>3567041102652</EAN>
<dodatneLastnosti><lastnost naziv="Vrsta priključka"><![CDATA[MicroUSB]]></lastnost><lastnost naziv="Dolžina kabla"><![CDATA[1 m]]></lastnost></dodatneLastnosti>
<kategorija id="NH99">Nahrbtniki</kategorija></izdelek></izdelki></podjetje>`
var row feedRow
if _, err := parseXMLItems(strings.NewReader(body), "izdelek", func(r feedRow) error { row = r; return nil }); err != nil {
t.Fatal(err)
}
specs := resolveSpecifications(row, "dodatneLastnosti")
if len(specs) != 2 || specs[CanonicalAttributeKey("Vrsta_priključka")] != "MicroUSB" || specs[CanonicalAttributeKey("Dolžina_kabla")] != "1 m" {
t.Fatalf("specs = %v (row %v)", specs, row)
}
// Elements merely carrying an id keep their old keys.
if row["kategorija"] != "Nahrbtniki" {
t.Fatalf("kategorija = %q", row["kategorija"])
}
}
func TestGuessXMLItemForNonEnglishTags(t *testing.T) {
body := `<?xml version="1.0"?><podjetje id="JANUS"><izdelki>
<izdelek st="1"><EAN>1</EAN><dodatneLastnosti><lastnost naziv="a">x</lastnost></dodatneLastnosti></izdelek>
<izdelek st="2"><EAN>2</EAN><dodatneLastnosti><lastnost naziv="a">y</lastnost></dodatneLastnosti></izdelek>
<izdelek st="3"><EAN>3</EAN><opis><![CDATA[cut off mid`
if got := guessXMLItemPath([]byte(body)); got != "podjetje/izdelki/izdelek" {
t.Fatalf("item path = %q", got)
}
if got := guessXMLItemLocal([]byte(body)); got != "izdelek" {
t.Fatalf("item local = %q", got)
}
fields, rows, err := extractXMLSchema([]byte(body), "izdelek")
if err != nil || rows != 2 || len(fields) == 0 {
t.Fatalf("truncated preview: rows=%d fields=%d err=%v", rows, len(fields), err)
}
}
+12 -4
View File
@@ -157,8 +157,8 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
}
}
}
if feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
if !isSupportedFeedType(feedType) {
return nil, ClientMsg("feed_type must be xml, csv, json or excel")
}
interval := in.SyncIntervalMinutes
if interval <= 0 && in.SyncFrequencyHours > 0 {
@@ -260,6 +260,14 @@ func (s *Service) attachMappingFieldCounts(ctx context.Context, companyID uuid.U
return rows.Err()
}
func isSupportedFeedType(feedType string) bool {
switch feedType {
case "xml", "csv", "json", "excel":
return true
}
return false
}
func isCSVFeedType(feedType string) bool {
t := strings.ToLower(strings.TrimSpace(feedType))
return t == "csv" || t == "excel"
@@ -318,8 +326,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return nil, err
}
feedType = strings.ToLower(strings.TrimSpace(feedType))
if feedType != "" && feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
if feedType != "" && !isSupportedFeedType(feedType) {
return nil, ClientMsg("feed_type must be xml, csv, json or excel")
}
interval := 0
switch v := body["sync_interval_minutes"].(type) {
+2
View File
@@ -127,6 +127,8 @@ func (s *Service) readLocalFeed(companyID uuid.UUID, rel string) (*feedBlob, err
ct = "application/xml"
} else if strings.HasSuffix(lower, ".json") {
ct = "application/json"
} else if isExcelName(lower) {
ct = "application/vnd.ms-excel"
}
return &feedBlob{
path: abs,
+2
View File
@@ -428,6 +428,8 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
}
}
parseCount, err = parseJSONItems(body, jsonPath, onRow)
case "excel":
parseCount, err = parseExcel(body.Name(), excelSheetOption(feed), onRow)
default:
parseCount, err = parseCSV(body, onRow)
}
@@ -137,6 +137,8 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
feedType = "xml"
} else if strings.HasSuffix(strings.ToLower(header.Filename), ".json") {
feedType = "json"
} else if lower := strings.ToLower(header.Filename); strings.HasSuffix(lower, ".xls") || strings.HasSuffix(lower, ".xlsx") || strings.HasSuffix(lower, ".xlsm") || strings.HasSuffix(lower, ".zip") {
feedType = "excel"
}
}
if fid, err := uuid.Parse(fileID); err == nil {
+3
View File
@@ -116,6 +116,9 @@ type ProductInput struct {
// CategoryAttrKeys maps category unique_id → attribute keys (job cache).
// When set, enhance resolves allowlist from the step result category.
CategoryAttrKeys map[string]map[string]struct{}
// FeedAttrKeys are the supplier's parsed spec keys (set by StepParseSpecs). For an
// uncategorized product they extend the core allowlist so feed specs survive.
FeedAttrKeys map[string]struct{}
// Prior* are loaded from the last processed_products row for this raw product.
PriorEnhanceHash string
PriorProcessedName string
@@ -42,7 +42,7 @@ func BackfillCompanyProcessedAttributes(ctx context.Context, pool *pgxpool.Pool,
}
attrs := decodeAttrMap(attrsJSON)
procAttrs := decodeAttrMap(procAttrsJSON)
allowed := allowedAttrKeysFromSets(sets, category)
allowed := persistAllowedAttrKeys(sets, category)
cleanAttrs := AttrsForPersist(attrs, allowed)
cleanProc := AttrsForPersist(procAttrs, allowed)
if len(cleanProc) == 0 {
+24 -35
View File
@@ -3,7 +3,6 @@ package processing
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"sort"
@@ -13,12 +12,6 @@ import (
"github.com/descrybe/descrybe-v2/apps/api/internal/aiaudit"
)
// ErrCategoryNotFound fails a product whose category could not be determined:
// the model's pick was outside the taxonomy, or it scored below the confidence
// floor. Processing stops for that product instead of enhancing it under a
// category nobody believes in.
var ErrCategoryNotFound = errors.New("product category could not be determined")
// MaxCategorizeOptions caps the taxonomy list injected into the categorize LLM
// prompt (token/cost bound). Prefer stable sort by display name then unique_id.
const MaxCategorizeOptions = 200
@@ -29,7 +22,8 @@ const MaxCategorizeOptions = 200
// like {"categoryId":"1","confidence":0.08} is the model saying "I do not know" —
// taking it at face value files a camping chair under Generators and then drives
// that category's title/description formula, producing confidently wrong copy.
// Below this floor the product fails with ErrCategoryNotFound instead.
// Below this floor the pick is discarded and the product continues uncategorized
// (generic enhance template, feed attributes kept) instead of under a wrong formula.
const DefaultMinCategorizeConfidence = 0.75
// MaxTokensCategorize budgets a short JSON reply {"categoryId","confidence"}.
@@ -134,16 +128,17 @@ func ProductCategorizeUser(name, description string, opts []categoryOption) stri
// tryAICategorize asks the Completer to pick a company taxonomy unique_id when
// Category is still empty after mapped/prior/vector. Never invents outside taxonomy:
// responses are coerced then filtered to namesByUID / valid unique_ids.
func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in ProductInput, policy StepPolicy) error {
// responses are coerced then filtered to namesByUID / valid unique_ids. A rejected
// pick leaves Category empty; supplier feeds without categories must still process.
func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in ProductInput, policy StepPolicy) {
if out == nil || strings.TrimSpace(out.Category) != "" {
return nil
return
}
if !policy.AllowAI {
return nil
return
}
if e == nil || !e.CompleterEnabled() {
return nil
return
}
opts := categoryOptionsFromNames(in.CategoryNamesByUID)
if len(opts) == 0 {
@@ -152,7 +147,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"status": "skipped",
"reason": "no_taxonomy",
})
return nil
return
}
name := strings.TrimSpace(out.Name)
if name == "" {
@@ -168,7 +163,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"status": "skipped",
"reason": "empty_product",
})
return nil
return
}
system := ProductCategorizeSystem
@@ -185,7 +180,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"error": TruncateError(err),
"tokens": comp.TotalTokens,
})
return nil
return
}
raw := categoryIDFromCategorizeJSON(obj)
@@ -202,12 +197,13 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"returned": raw,
"tokens": comp.TotalTokens,
})
return fmt.Errorf("%w: model returned %q, which is not in the company taxonomy",
ErrCategoryNotFound, truncateRunes(raw, 60))
log.Printf("processing: category rejected returned=%q reason=not_in_taxonomy; continuing uncategorized",
truncateRunes(raw, 60))
return
}
// A confident-looking id with a low score is the model guessing. Refuse it
// rather than driving the wrong category's formula with it.
// rather than driving the wrong category's formula with it; process uncategorized.
if min := policy.CategorizeConfidence(); hasConfidence && confidence < min {
out.Notes = append(out.Notes, fmt.Sprintf(
"ai_categorize: no category found (confidence %.2f below %.2f)", confidence, min))
@@ -219,10 +215,9 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"minimum": min,
"tokens": comp.TotalTokens,
})
log.Printf("processing: category rejected uid=%s confidence=%.2f min=%.2f reason=low_confidence",
log.Printf("processing: category rejected uid=%s confidence=%.2f min=%.2f reason=low_confidence; continuing uncategorized",
resolved, confidence, min)
return fmt.Errorf("%w: best match %q scored %.2f, below the %.2f minimum",
ErrCategoryNotFound, truncateRunes(resolved, 60), confidence, min)
return
}
out.Category = SanitizeText(resolved)
@@ -244,7 +239,6 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
if hasConfidence {
out.Notes = append(out.Notes, fmt.Sprintf("ai_categorize: confidence %.2f", confidence))
}
return nil
}
// categorizeConfidenceFromJSON reads the model's self-reported score. ok=false when
@@ -317,12 +311,10 @@ func firstAvailableCategoryIDFromPrompt(user string) string {
}
// runCategorizeStep applies vector then LLM taxonomy selection when Category empty.
// runCategorizeStep returns ErrCategoryNotFound when the model was asked for a
// category and could not give a usable one — the caller fails the product rather
// than enhancing it under a guess.
func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *StepResult, in ProductInput, categoryNames []string, policy StepPolicy) error {
// Category is optional: when nothing usable is found the product continues without one.
func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *StepResult, in ProductInput, categoryNames []string, policy StepPolicy) {
if out == nil {
return nil
return
}
if strings.TrimSpace(out.Category) != "" {
appendStepLog(out.GPTResponse, StepCategorize, map[string]any{
@@ -330,7 +322,7 @@ func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *St
"reason": "already_set",
"category": out.Category,
})
return nil
return
}
if !policy.AllowAI {
out.Notes = append(out.Notes, "categorize: skipped (AI not allowed)")
@@ -338,24 +330,21 @@ func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *St
"status": "skipped",
"reason": "entitlement_can_use_ai",
})
return nil
return
}
tryVectorCategorize(ctx, e, companyID, out, categoryNames, policy)
if strings.TrimSpace(out.Category) != "" {
return nil
return
}
// Taxonomy picks and copy generation share one Completer; tag the role so the
// admin inspector can tell them apart.
if err := tryAICategorize(aiaudit.WithCall(ctx, aiaudit.CallContext{Role: aiaudit.RoleCategorize}), e, out, in, policy); err != nil {
return err
}
tryAICategorize(aiaudit.WithCall(ctx, aiaudit.CallContext{Role: aiaudit.RoleCategorize}), e, out, in, policy)
if strings.TrimSpace(out.Category) == "" {
appendStepLog(out.GPTResponse, StepCategorize, map[string]any{
"status": "unset",
"reason": "no_vector_or_ai_match",
})
}
return nil
}
// MappedCategorySourceKey marks a mapped_data.category this pipeline wrote itself.
@@ -2,7 +2,6 @@ package processing
import (
"context"
"errors"
"strings"
"testing"
)
@@ -63,20 +62,15 @@ func TestTryAICategorize_rejectsInventedID(t *testing.T) {
}},
Vector: NoopVectorCategorizer{},
}
// An id outside the taxonomy means the category could not be determined. The
// product must fail rather than continue uncategorised into enhance, which
// would generate copy with no formula behind it.
// An id outside the taxonomy is never stored; the product continues uncategorized.
out, err := e.RunSteps(context.Background(), "co", ProductInput{
Name: "Widget",
CategoryNamesByUID: map[string]string{
"50": "Štedilniki",
},
}, "full", nil, StepPolicy{AllowAI: true})
if !errors.Is(err, ErrCategoryNotFound) {
t.Fatalf("err=%v want ErrCategoryNotFound", err)
}
if !strings.Contains(err.Error(), "99999") {
t.Fatalf("error should name the rejected id, got %v", err)
if err != nil {
t.Fatalf("an invented id must not fail the product, got %v", err)
}
if out.Category != "" {
t.Fatalf("Category=%q want empty (invented id rejected)", out.Category)
@@ -2,7 +2,6 @@ package processing
import (
"context"
"errors"
"fmt"
"strings"
"testing"
@@ -37,27 +36,28 @@ func categorizeInput() ProductInput {
// The reported case: the model always answers with SOME id, so a low score is it
// saying "I do not know". Taking it at face value files a camping chair under
// Generators and then drives that category's formula.
func TestRunSteps_lowConfidenceCategoryFailsTheProduct(t *testing.T) {
// Generators and then drives that category's formula. The guess is discarded, but
// the product still processes uncategorized (supplier feeds often have no category).
func TestRunSteps_lowConfidenceCategoryProcessesUncategorized(t *testing.T) {
t.Parallel()
e, enhanceCalls := categorizeEngine(`{"categoryId":"1","confidence":0.08}`)
out, err := e.RunSteps(context.Background(), "co", categorizeInput(), "full", nil,
StepPolicy{AllowAI: true})
if !errors.Is(err, ErrCategoryNotFound) {
t.Fatalf("err=%v want ErrCategoryNotFound", err)
}
for _, want := range []string{"0.08", "0.75"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error should report the score and the minimum, got %v", err)
}
if err != nil {
t.Fatalf("an undetermined category must not fail the product, got %v", err)
}
if out.Category != "" {
t.Fatalf("a rejected pick must not be persisted, got %q", out.Category)
}
// The whole point: stop before spending an enhance call on the wrong category.
if *enhanceCalls != 0 {
t.Fatalf("enhance ran %d time(s) after the category was rejected", *enhanceCalls)
notes := strings.Join(out.Notes, " ")
for _, want := range []string{"0.08", "0.75"} {
if !strings.Contains(notes, want) {
t.Fatalf("notes should report the score and the minimum, got %v", out.Notes)
}
}
if *enhanceCalls == 0 {
t.Fatal("enhance should still run without a category")
}
}
+11 -1
View File
@@ -1124,6 +1124,16 @@ func categoryAttrKeysFromCache(cache *jobScopedCache) map[string]map[string]stru
return cache.categoryAttrKeys
}
// persistAllowedAttrKeys is the post-RunSteps allowlist. Uncategorized attrs were
// already limited to core + supplier spec keys inside RunSteps, so they are only
// sanitized here; re-filtering to core keys would drop the supplier's specs.
func persistAllowedAttrKeys(sets map[string]map[string]struct{}, categoryUID string) map[string]struct{} {
if strings.TrimSpace(categoryUID) == "" {
return nil
}
return allowedAttrKeysFromSets(sets, categoryUID)
}
// allowedAttrKeysFromSets picks category keys when present; empty non-nil → core only.
// When sets is nil, returns nil (sanitize-only / unit tests).
func allowedAttrKeysFromSets(sets map[string]map[string]struct{}, categoryUID string) map[string]struct{} {
@@ -1684,7 +1694,7 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
syncCategoryName(&result, cache.categoryNamesByUID)
}
// Re-apply after category validation so allowlist matches the persisted category.
allowed := allowedAttrKeysForCategory(cache, result.Category)
allowed := persistAllowedAttrKeys(categoryAttrKeysFromCache(cache), result.Category)
result.Attributes = AttrsForPersist(result.Attributes, allowed)
result.ProcessedAttributes = AttrsForPersist(result.ProcessedAttributes, allowed)
if len(result.ProcessedAttributes) == 0 {
+20 -1
View File
@@ -235,13 +235,32 @@ func AttrsForPersist(attrs map[string]any, allowed map[string]struct{}) map[stri
// enhanceAllowedAttrKeys prefers category_attributes for the resolved category;
// falls back to AllowedAttrKeys (nil = sanitize-only for unit tests).
// Uncategorized products have no schema to enforce, so the supplier's own spec keys
// are allowed too: the model may refine them but cannot invent new keys.
func enhanceAllowedAttrKeys(in ProductInput, categoryUID string) map[string]struct{} {
if in.CategoryAttrKeys != nil {
return allowedAttrKeysFromSets(in.CategoryAttrKeys, categoryUID)
allowed := allowedAttrKeysFromSets(in.CategoryAttrKeys, categoryUID)
if strings.TrimSpace(categoryUID) == "" {
for k := range in.FeedAttrKeys {
allowed[k] = struct{}{}
}
}
return allowed
}
return in.AllowedAttrKeys
}
// attrKeySet returns the canonical keys of attrs (see FilterAttributesByAllowed).
func attrKeySet(attrs map[string]any) map[string]struct{} {
out := make(map[string]struct{}, len(attrs))
for k := range attrs {
if canon := canonicalizeAttrKey(k); canon != "" {
out[canon] = struct{}{}
}
}
return out
}
// FilterAttributesByAllowed keeps coreCharacteristicAttrKeys plus keys present in
// allowed (after canonicalizeAttrKey). When allowed is nil, returns attrs unchanged.
func FilterAttributesByAllowed(attrs map[string]any, allowed map[string]struct{}) map[string]any {
+4 -8
View File
@@ -95,6 +95,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
}
}
attrs = SanitizeProductAttributes(parsed)
in.FeedAttrKeys = attrKeySet(attrs)
// Map feed/spec labels onto category_attributes (formula) keys early.
if allowed := enhanceAllowedAttrKeys(in, out.Category); allowed != nil {
attrs = MapAttrsOntoAllowedKeys(attrs, allowed)
@@ -225,11 +226,8 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
case StepCategorize:
// Vector (if enabled) then LLM taxonomy pick when category still empty.
// A category the model could not determine fails the product here, before
// enhance spends a call writing copy for the wrong category.
if err := runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy); err != nil {
return out, err
}
// An undetermined category leaves the product uncategorized; it still processes.
runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy)
case StepAIEnhance:
preservePriorEnhanceHash := func() {
@@ -569,9 +567,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
// Pipelines without StepCategorize (normalize_only) still run vector + LLM
// categorize when category is empty so downstream steps are not fed a blank.
if !stepsContain(steps, StepCategorize) {
if err := runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy); err != nil {
return out, err
}
runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy)
}
// Record why category stayed empty for every pipeline, including the ones that
// now categorize inside the loop (enhance / title / description).
@@ -0,0 +1,49 @@
package processing
import (
"context"
"testing"
)
// Supplier feeds without categories (pilot: Koopman, Trbovc Excel) must keep their
// own specs; the model may refine those keys but not invent new ones.
func TestRunSteps_uncategorizedKeepsSupplierSpecs(t *testing.T) {
t.Parallel()
e := &Engine{
Completer: stubCompleter{fn: func(system, user string) (Completion, error) {
return Completion{
Text: `{"name":"Advent wreath gold 41 cm","description":"<p>Gold wreath.</p>","attrs":{"volume_in_m3":"0.882","color":"gold","battery_life":"200 h"}}`,
TotalTokens: 5,
}, nil
}},
Vector: NoopVectorCategorizer{},
}
in := ProductInput{
GTIN: "8721461009242",
Name: "WREATH ADVENT 41CM GOLD",
Mapped: map[string]any{
"name": "WREATH ADVENT 41CM GOLD",
"specifications": map[string]any{"Volume in m3": "0.882", "Statistic no": "06049099"},
},
// Production job cache: taxonomy keys exist, but this product has no category.
CategoryAttrKeys: map[string]map[string]struct{}{},
}
out, err := e.RunSteps(context.Background(), "co", in, "full", nil, StepPolicy{AllowAI: true})
if err != nil {
t.Fatal(err)
}
if out.Category != "" {
t.Fatalf("Category=%q want empty", out.Category)
}
for _, want := range []string{"volume_in_m3", "statistic_no", "color"} {
if _, ok := out.Attributes[want]; !ok {
t.Fatalf("missing %q in %v", want, out.Attributes)
}
}
if _, ok := out.Attributes["battery_life"]; ok {
t.Fatalf("model-invented key persisted: %v", out.Attributes)
}
if got := persistAllowedAttrKeys(map[string]map[string]struct{}{}, ""); got != nil {
t.Fatalf("persist allowlist for uncategorized = %v want nil (already constrained)", got)
}
}