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)) } }