fixes
This commit is contained in:
1 parent
c347d2418f
commit
1ad180a052
49 files changed
+6339
-89
No files matched your search
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user