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

+9
View File
@@ -11,6 +11,8 @@ require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.10.0
github.com/microcosm-cc/bluemonday v1.0.27
github.com/pbnjay/grate v0.0.0-20231006022435-3f8e65d74a14
github.com/xuri/excelize/v2 v2.11.0
golang.org/x/crypto v0.54.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -22,8 +24,15 @@ require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/richardlehane/mscfb v1.0.7 // indirect
github.com/richardlehane/msoleps v1.0.6 // indirect
github.com/tiendc/go-deepcopy v1.7.2 // indirect
github.com/xuri/efp v0.0.1 // indirect
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
golang.org/x/net v0.57.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
)
replace github.com/pbnjay/grate => ./third_party/grate
+14
View File
@@ -43,6 +43,10 @@ github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwX
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/+EB0=
github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -55,12 +59,22 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG88=
github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak=
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+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)
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Jeremy Jay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+13
View File
@@ -0,0 +1,13 @@
# Vendored github.com/pbnjay/grate
Upstream: github.com/pbnjay/grate v0.0.0-20231006022435-3f8e65d74a14 (MIT, see LICENSE).
Only the packages used for legacy `.xls` feed import are kept (root, `commonxl`, `xls`);
tests, `xlsx`, `simple` and `cmd` were dropped. Wired in via `replace` in `apps/api/go.mod`.
Local fixes (search for `descrybe patch`), found with real supplier workbooks:
- `commonxl/sheet.go` `Put`: text cells are no longer coerced to the column's numeric
format (a `0`-formatted `Šifra` header was read as `0`).
- `xls/sheets.go` formula `String` records: 8-bit characters decode as Latin-1 instead of
raw bytes (invalid UTF-8 for č/ž/é…).
- `xls/sheets.go` `HLink`: the cell keeps the link URL instead of `text <url>`.
+463
View File
@@ -0,0 +1,463 @@
package commonxl
import (
"fmt"
"math"
"net/url"
"strconv"
"time"
"unicode/utf16"
)
// CellType annotates the type of data extracted in the cell.
type CellType uint16
// CellType annotations for various cell value types.
const (
BlankCell CellType = iota
IntegerCell
FloatCell
StringCell
BooleanCell
DateCell
HyperlinkStringCell // internal type to separate URLs
StaticCell // placeholder, internal use only
)
// String returns a string description of the cell data type.
func (c CellType) String() string {
switch c {
case BlankCell:
return "blank"
case IntegerCell:
return "integer"
case FloatCell:
return "float"
case BooleanCell:
return "boolean"
case DateCell:
return "date"
case HyperlinkStringCell:
return "hyperlink"
case StaticCell:
return "static"
default: // StringCell, StaticCell
return "string"
}
}
// Cell represents a single cell value.
type Cell []interface{}
// internally, it is a slice sized 2 or 3
// [Value, CellType] or [Value, CellType, FormatNumber]
// where FormatNumber is a uint16 if not 0
// Value returns the contents as a generic interface{}.
func (c Cell) Value() interface{} {
if len(c) == 0 {
return ""
}
return c[0]
}
// SetURL adds a URL hyperlink to the cell.
func (c *Cell) SetURL(link string) {
(*c)[1] = HyperlinkStringCell
if len(*c) == 2 {
*c = append(*c, uint16(0), link)
} else { // len = 3 already
*c = append(*c, link)
}
}
// URL returns the parsed URL when a cell contains a hyperlink.
func (c Cell) URL() (*url.URL, bool) {
if c.Type() == HyperlinkStringCell && len(c) >= 4 {
u, err := url.Parse(c[3].(string))
return u, err == nil
}
return nil, false
}
// Type returns the CellType of the value.
func (c Cell) Type() CellType {
if len(c) < 2 {
return BlankCell
}
return c[1].(CellType)
}
// FormatNo returns the NumberFormat used for display.
func (c Cell) FormatNo() uint16 {
if len(c) == 3 {
return c[2].(uint16)
}
return 0
}
// Clone returns the new copy of this Cell.
func (c Cell) Clone() Cell {
c2 := make([]interface{}, len(c))
for i, x := range c {
c2[i] = x
}
return c2
}
///////
var boolStrings = map[string]bool{
"yes": true, "true": true, "t": true, "y": true, "1": true, "on": true,
"no": false, "false": false, "f": false, "n": false, "0": false, "off": false,
"YES": true, "TRUE": true, "T": true, "Y": true, "1.0": true, "ON": true,
"NO": false, "FALSE": false, "F": false, "N": false, "0.0": false, "OFF": false,
}
// NewCellWithType creates a new cell value with the given type, coercing as necessary.
func NewCellWithType(value interface{}, t CellType, f *Formatter) Cell {
c := NewCell(value)
if c[1] == t {
// fast path if it was already typed correctly
return c
}
if c[1] == BooleanCell {
if t == IntegerCell {
if c[0].(bool) {
c[0] = int64(1)
} else {
c[0] = int64(0)
}
c[1] = IntegerCell
} else if t == FloatCell {
if c[0].(bool) {
c[0] = float64(1.0)
} else {
c[0] = float64(0.0)
}
c[1] = FloatCell
} else if t == StringCell {
if c[0].(bool) {
c[0] = "TRUE"
} else {
c[0] = "FALSE"
}
c[1] = FloatCell
}
}
if c[1] == FloatCell {
if t == IntegerCell {
c[0] = int64(c[0].(float64))
c[1] = IntegerCell
} else if t == BooleanCell {
c[0] = c[0].(float64) != 0.0
c[1] = BooleanCell
}
}
if c[1] == IntegerCell {
if t == FloatCell {
c[0] = float64(c[0].(int64))
c[1] = FloatCell
} else if t == BooleanCell {
c[0] = c[0].(int64) != 0
c[1] = BooleanCell
}
}
if c[1] == StringCell {
if t == IntegerCell {
x, _ := strconv.ParseInt(c[0].(string), 10, 64)
c[0] = x
c[1] = IntegerCell
} else if t == FloatCell {
x, _ := strconv.ParseFloat(c[0].(string), 64)
c[0] = x
c[1] = FloatCell
} else if t == BooleanCell {
c[0] = boolStrings[c[0].(string)]
c[1] = BooleanCell
}
}
if t == StringCell {
c[0] = fmt.Sprint(c[0])
c[1] = StringCell
}
if t == DateCell {
if c[1] == FloatCell {
c[0] = f.ConvertToDate(c[0].(float64))
} else if c[1] == IntegerCell {
c[0] = f.ConvertToDate(float64(c[0].(int64)))
}
c[1] = DateCell
}
return c
}
// NewCell creates a new cell value from any builtin type.
func NewCell(value interface{}) Cell {
c := make([]interface{}, 2)
switch v := value.(type) {
case bool:
c[0] = v
c[1] = BooleanCell
case int:
c[0] = int64(v)
c[1] = IntegerCell
case int8:
c[0] = int64(v)
c[1] = IntegerCell
case int16:
c[0] = int64(v)
c[1] = IntegerCell
case int32:
c[0] = int64(v)
c[1] = IntegerCell
case int64:
c[0] = int64(v)
c[1] = IntegerCell
case uint8:
c[0] = int64(v)
c[1] = IntegerCell
case uint16:
c[0] = int64(v)
c[1] = IntegerCell
case uint32:
c[0] = int64(v)
c[1] = IntegerCell
case uint:
if int64(v) > int64(math.MaxInt64) {
c[0] = float64(v)
c[1] = FloatCell
} else {
c[0] = int64(v)
c[1] = IntegerCell
}
case uint64:
if v > math.MaxInt64 {
c[0] = float64(v)
c[1] = FloatCell
} else {
c[0] = int64(v)
c[1] = IntegerCell
}
case float32:
c[0] = float64(v)
c[1] = FloatCell
case float64:
c[0] = float64(v)
c[1] = FloatCell
case string:
if len(v) == 0 {
c[0] = nil
c[1] = BlankCell
} else {
c[0] = v
c[1] = StringCell
}
case []byte:
if len(v) == 0 {
c[0] = nil
c[1] = BlankCell
} else {
c[0] = string(v)
c[1] = StringCell
}
case []uint16:
if len(v) == 0 {
c[0] = nil
c[1] = BlankCell
} else {
c[0] = string(utf16.Decode(v))
c[1] = StringCell
}
case []rune:
if len(v) == 0 {
c[0] = nil
c[1] = BlankCell
} else {
c[0] = string(v)
c[1] = StringCell
}
case time.Time:
c[0] = v
c[1] = DateCell
case fmt.Stringer:
s := v.String()
if len(s) == 0 {
c[0] = nil
c[1] = BlankCell
} else {
c[0] = s
c[1] = StringCell
}
default:
panic("grate: data type not handled")
}
return Cell(c)
}
// SetFormatNumber changes the number format stored with the cell.
func (c *Cell) SetFormatNumber(f uint16) {
if f == 0 {
*c = (*c)[:2]
return
}
if len(*c) == 2 {
*c = append(*c, f)
} else {
(*c)[2] = f
}
}
func (c Cell) Equal(other Cell) bool {
if c.Type() == FloatCell || other.Type() == FloatCell ||
c.Type() == IntegerCell || other.Type() == IntegerCell {
v1, ok := c[0].(float64)
v1x, okx := c[0].(int64)
if okx {
v1 = float64(v1x)
ok = true
}
if !ok {
fmt.Sscanf(fmt.Sprint(c[0]), "%g", &v1)
}
v2, ok := other[0].(float64)
v2x, okx := other[0].(int64)
if okx {
v2 = float64(v2x)
ok = true
}
if !ok {
fmt.Sscanf(fmt.Sprint(c[0]), "%g", &v2)
}
return v1 == v2
}
return c.Less(other) == other.Less(c)
}
func (c Cell) Less(other Cell) bool {
if len(c) == 0 {
return false
}
switch v1 := c[0].(type) {
case nil:
return false
case bool:
// F < T = T
// F < F = F
// T < T = F
// T < F = F
if v1 {
return false
}
// if v2 is truthy, return true
switch v2 := other[0].(type) {
case nil:
return false
case bool:
return v2
case int64:
return v2 != 0
case float64:
return v2 != 0.0
case string:
return boolStrings[v2]
}
case int64:
// v1 < v2
switch v2 := other[0].(type) {
case nil:
return false
case bool:
x := int64(0)
if v2 {
x = 1
}
return v1 < x
case int64:
return v1 < v2
case float64:
if v2 < math.MinInt64 {
return false
}
if v2 > math.MaxInt64 {
return true
}
return float64(v1) < v2
case string:
var x int64
_, err := fmt.Sscanf(v2, "%d", &x)
if err == nil {
return v1 < x
}
return fmt.Sprint(v1) < v2
}
case float64:
switch v2 := other[0].(type) {
case nil:
return false
case bool:
x := float64(0.0)
if v2 {
x = 1.0
}
return v1 < x
case int64:
if v1 < math.MinInt64 {
return true
}
if v1 > math.MaxInt64 {
return false
}
return v1 < float64(v2)
case float64:
return v1 < v2
case string:
var x float64
_, err := fmt.Sscanf(v2, "%g", &x)
if err == nil {
return v1 < x
}
return fmt.Sprint(v1) < v2
}
case string:
//return v1 < fmt.Sprint(other[0])
switch v2 := other[0].(type) {
case nil:
return false
case bool:
return v2 && !boolStrings[v1]
case int64:
var x int64
_, err := fmt.Sscanf(v1, "%d", &x)
if err == nil {
return x < v2
}
return v1 < fmt.Sprint(v2)
case float64:
var x float64
_, err := fmt.Sscanf(v1, "%g", &x)
if err == nil {
return x < v2
}
return v1 < fmt.Sprint(v2)
case string:
return v1 < v2
}
}
panic("unable to compare cells (invalid internal type)")
}
+78
View File
@@ -0,0 +1,78 @@
package commonxl
import (
"strings"
"time"
)
// ConvertToDate converts a floating-point value using the
// Excel date serialization conventions.
func (x *Formatter) ConvertToDate(val float64) time.Time {
// http://web.archive.org/web/20190808062235/http://aa.usno.navy.mil/faq/docs/JD_Formula.php
v := int(val)
if v < 61 {
jdate := val + 0.5
if (x.flags & fMode1904) != 0 {
jdate += 2416480.5
} else {
jdate += 2415018.5
}
JD := int(jdate)
frac := jdate - float64(JD)
L := JD + 68569
N := 4 * L / 146097
L = L - (146097*N+3)/4
I := 4000 * (L + 1) / 1461001
L = L - 1461*I/4 + 31
J := 80 * L / 2447
day := L - 2447*J/80
L = J / 11
month := time.Month(J + 2 - 12*L)
year := 100*(N-49) + I + L
t := time.Duration(float64(time.Hour*24) * frac)
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(t)
}
frac := val - float64(v)
date := time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)
if (x.flags & fMode1904) == 0 {
date = time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
}
t := time.Duration(float64(time.Hour*24) * frac)
return date.AddDate(0, 0, v).Add(t)
}
func timeFmtFunc(f string) FmtFunc {
return func(x *Formatter, v interface{}) string {
t, ok := v.(time.Time)
if !ok {
fval, ok := convertToFloat64(v)
if !ok {
return "MUST BE time.Time OR numeric TO FORMAT CORRECTLY"
}
t = x.ConvertToDate(fval)
}
//log.Println("formatting date", t, "with", f, "=", t.Format(f))
return t.Format(f)
}
}
// same as above but replaces "AM" and "PM" with chinese translations.
// TODO: implement others
func cnTimeFmtFunc(f string) FmtFunc {
return func(x *Formatter, v interface{}) string {
t, ok := v.(time.Time)
if !ok {
fval, ok := convertToFloat64(v)
if !ok {
return "MUST BE time.Time OR numeric TO FORMAT CORRECTLY"
}
t = x.ConvertToDate(fval)
}
s := t.Format(f)
s = strings.Replace(s, `AM`, `上午`, 1)
return strings.Replace(s, `PM`, `下午`, 1)
}
}
+303
View File
@@ -0,0 +1,303 @@
package commonxl
import (
"fmt"
"strconv"
"strings"
)
// FmtFunc will format a value according to the designated style.
type FmtFunc func(*Formatter, interface{}) string
func staticFmtFunc(s string) FmtFunc {
return func(x *Formatter, v interface{}) string {
return s
}
}
func surround(pre string, ff FmtFunc, post string) FmtFunc {
return func(x *Formatter, v interface{}) string {
return pre + ff(x, v) + post
}
}
func addNegParens(ff FmtFunc) FmtFunc {
return func(x *Formatter, v interface{}) string {
s1 := ff(x, v)
if s1[0] == '-' {
return "(" + s1[1:] + ")"
}
return s1
}
}
func addCommas(ff FmtFunc) FmtFunc {
return func(x *Formatter, v interface{}) string {
s1 := ff(x, v)
isNeg := false
if s1[0] == '-' {
isNeg = true
s1 = s1[1:]
}
endIndex := strings.IndexAny(s1, ".eE")
if endIndex < 0 {
endIndex = len(s1)
}
for endIndex > 3 {
endIndex -= 3
s1 = s1[:endIndex] + "," + s1[endIndex:]
}
if isNeg {
return "-" + s1
}
return s1
}
}
func identFunc(x *Formatter, v interface{}) string {
switch x := v.(type) {
case bool:
if x {
return "TRUE"
}
return "FALSE"
case int64:
s := strconv.FormatInt(x, 10)
if len(s) <= 11 {
return s
}
case float64:
s := strconv.FormatFloat(x, 'f', -1, 64)
if len(s) <= 11 || (len(s) == 12 && x < 0) {
return s
}
s = strconv.FormatFloat(x, 'g', 6, 64)
if len(s) <= 11 {
return s
}
case string:
return x
case fmt.Stringer:
return x.String()
}
return fmt.Sprint(v)
}
func sprintfFunc(fs string, mul int) FmtFunc {
wantInt64 := strings.Contains(fs, "%d")
return func(x *Formatter, v interface{}) string {
switch val := v.(type) {
case int, uint, int64, uint64, int32, uint32, uint16, int16:
return fmt.Sprintf(fs, v)
case float64:
val *= float64(mul)
if wantInt64 {
v2 := int64(val)
return fmt.Sprintf(fs, v2)
}
return fmt.Sprintf(fs, val)
}
return fmt.Sprint(v)
}
}
func convertToInt64(v interface{}) (int64, bool) {
x, ok := convertToFloat64(v)
return int64(x), ok
}
func convertToFloat64(v interface{}) (float64, bool) {
switch val := v.(type) {
case float64:
return val, true
case bool:
if val {
return 1.0, true
}
return 0.0, true
case int:
return float64(val), true
case int8:
return float64(val), true
case int16:
return float64(val), true
case int32:
return float64(val), true
case int64:
return float64(val), true
case uint:
return float64(val), true
case uint8:
return float64(val), true
case uint16:
return float64(val), true
case uint32:
return float64(val), true
case uint64:
return float64(val), true
case float32:
return float64(val), true
case string:
nf, err := strconv.ParseFloat(val, 64)
return nf, err == nil
default:
return 0.0, false
}
}
// replaces a zero with a dash
func zeroDashFunc(ff FmtFunc) FmtFunc {
return func(x *Formatter, v interface{}) string {
fval, ok := convertToFloat64(v)
if !ok {
// strings etc returned as-is
return fmt.Sprint(v)
}
if fval == 0.0 {
return "-"
}
return ff(x, v)
}
}
func fracFmtFunc(n int) FmtFunc {
return func(x *Formatter, v interface{}) string {
f, ok := convertToFloat64(v)
if !ok {
return "MUST BE numeric TO FORMAT CORRECTLY"
}
w, n, d := DecimalToWholeFraction(f, n, n)
if n == 0 {
return fmt.Sprintf("%d", w)
}
if w == 0 {
if f < 0 && n > 0 {
n = -n
}
return fmt.Sprintf("%d/%d", n, d)
}
return fmt.Sprintf("%d %d/%d", w, n, d)
}
}
// handle (up to) all four format cases:
// positive;negative;zero;other
func switchFmtFunc(pos FmtFunc, others ...FmtFunc) FmtFunc {
stringFF := identFunc
zeroFF := pos
negFF := pos
if len(others) > 0 {
negFF = others[0]
if len(others) > 1 {
zeroFF = others[1]
if len(others) > 2 {
stringFF = others[2]
}
}
}
return func(x *Formatter, v interface{}) string {
val, ok := convertToFloat64(v)
if !ok {
return stringFF(x, v)
}
if val == 0.0 {
return zeroFF(x, v)
}
if val < 0.0 {
return negFF(x, v)
}
return pos(x, v)
}
}
// mapping of standard built-ins to Go date format funcs.
var goFormatters = map[uint16]FmtFunc{
0: identFunc, // FIXME: better "general" formatter
49: identFunc,
14: timeFmtFunc(`01-02-06`),
15: timeFmtFunc(`2-Jan-06`),
16: timeFmtFunc(`2-Jan`),
17: timeFmtFunc(`Jan-06`),
20: timeFmtFunc(`15:04`),
21: timeFmtFunc(`15:04:05`),
22: timeFmtFunc(`1/2/06 15:04`),
45: timeFmtFunc(`04:05`),
46: timeFmtFunc(`3:04:05`),
47: timeFmtFunc(`0405.9`),
27: timeFmtFunc(`2006"年"1"月"`),
28: timeFmtFunc(`1"月"2"日"`),
29: timeFmtFunc(`1"月"2"日"`),
30: timeFmtFunc(`1-2-06`),
31: timeFmtFunc(`2006"年"1"月"2"日"`),
32: timeFmtFunc(`15"时"04"分"`),
33: timeFmtFunc(`15"时"04"分"05"秒"`),
36: timeFmtFunc(`2006"年"2"月"`),
50: timeFmtFunc(`2006"年"2"月"`),
51: timeFmtFunc(`1"月"2"日"`),
52: timeFmtFunc(`2006"年"1"月"`),
53: timeFmtFunc(`1"月"2"日"`),
54: timeFmtFunc(`1"月"2"日"`),
57: timeFmtFunc(`2006"年"1"月"`),
58: timeFmtFunc(`1"月"2"日"`),
71: timeFmtFunc(`2/1/2006`),
72: timeFmtFunc(`2-Jan-06`),
73: timeFmtFunc(`2-Jan`),
74: timeFmtFunc(`Jan-06`),
75: timeFmtFunc(`15:04`),
76: timeFmtFunc(`15:04:05`),
77: timeFmtFunc(`2/1/2006 15:04`),
78: timeFmtFunc(`04:05`),
79: timeFmtFunc(`15:04:05`),
80: timeFmtFunc(`04:05.9`),
81: timeFmtFunc(`2/1/06`),
18: timeFmtFunc(`3:04 PM`),
19: timeFmtFunc(`3:04:05 PM`),
34: cnTimeFmtFunc(`PM 3"时"04"分"`),
35: cnTimeFmtFunc(`PM 3"时"04"分"05"秒"`),
55: cnTimeFmtFunc(`PM 3"时"04"分"`),
56: cnTimeFmtFunc(`PM 3"时"04"分"05"秒`),
12: fracFmtFunc(1),
13: fracFmtFunc(2),
69: fracFmtFunc(1),
70: fracFmtFunc(2),
1: sprintfFunc(`%d`, 1),
2: sprintfFunc(`%4.2f`, 1),
59: sprintfFunc(`%d`, 1),
60: sprintfFunc(`%4.2f`, 1),
9: sprintfFunc(`%d%%`, 100),
10: sprintfFunc(`%4.2f%%`, 100),
67: sprintfFunc(`%d%%`, 100),
68: sprintfFunc(`%4.2f%%`, 100),
3: addCommas(sprintfFunc("%d", 1)),
61: addCommas(sprintfFunc("%d", 1)),
37: addNegParens(addCommas(sprintfFunc("%d", 1))),
38: addNegParens(addCommas(sprintfFunc("%d", 1))),
4: addCommas(sprintfFunc("%4.2f", 1)),
62: addCommas(sprintfFunc("%4.2f", 1)),
39: addNegParens(addCommas(sprintfFunc("%4.2f", 1))),
40: addNegParens(addCommas(sprintfFunc("%4.2f", 1))),
11: sprintfFunc(`%4.2E`, 1),
48: sprintfFunc(`%3.1E`, 1),
41: zeroDashFunc(addCommas(sprintfFunc("%d", 1))),
43: zeroDashFunc(addCommas(sprintfFunc("%4.2f", 1))),
42: switchFmtFunc(
surround("$", addCommas(sprintfFunc("%d", 1)), ""),
surround("$(", addCommas(sprintfFunc("%d", 1)), ")"),
staticFmtFunc("$-")),
44: switchFmtFunc(
surround("$", addCommas(sprintfFunc("%4.2f", 1)), ""),
surround("$(", addCommas(sprintfFunc("%4.2f", 1)), ")"),
staticFmtFunc("$-")),
}
+382
View File
@@ -0,0 +1,382 @@
package commonxl
import (
"errors"
"fmt"
"regexp"
"strings"
)
// Formatter contains formatting methods common to Excel spreadsheets.
type Formatter struct {
flags uint64
customCodes map[uint16]FmtFunc
customCodeTypes map[uint16]CellType
}
const (
fMode1904 uint64 = 1
)
// Mode1904 indicates that dates start on Jan 1, 1904
// this setting was used in early MacOS Excel applications.
func (x *Formatter) Mode1904(enabled bool) {
if enabled {
x.flags |= fMode1904
} else {
x.flags = x.flags &^ fMode1904
}
}
// Add a custom number format to the formatter.
func (x *Formatter) Add(fmtID uint16, formatCode string) error {
if x.customCodes == nil {
x.customCodes = make(map[uint16]FmtFunc)
x.customCodeTypes = make(map[uint16]CellType)
}
if strings.ToLower(formatCode) == "general" {
x.customCodes[fmtID] = goFormatters[0]
return nil
}
_, ok := goFormatters[fmtID]
if ok {
return errors.New("grate/commonxl: cannot replace default number formats")
}
_, ok2 := x.customCodes[fmtID]
if ok2 {
return errors.New("grate/commonxl: cannot replace existing number formats")
}
x.customCodes[fmtID], x.customCodeTypes[fmtID] = makeFormatter(formatCode)
return nil
}
func (x *Formatter) getCellType(fmtID uint16) (CellType, bool) {
if ct, ok := builtInFormatTypes[fmtID]; ok {
return ct, true
}
if x.customCodeTypes != nil {
ct, ok := x.customCodeTypes[fmtID]
return ct, ok
}
return 0, false
}
var (
minsMatch = regexp.MustCompile("h.*m.*s")
nonEsc = regexp.MustCompile(`([^"]|^)"`)
squash = regexp.MustCompile(`[*_].`)
fixEsc = regexp.MustCompile(`\\(.)`)
formatMatchBrackets = regexp.MustCompile(`\[[^\]]*\]`)
formatMatchTextLiteral = regexp.MustCompile(`"[^"]*"`)
)
func makeFormatter(s string) (FmtFunc, CellType) {
//log.Printf("makeFormatter('%s')", s)
// remove any coloring marks
s = formatMatchBrackets.ReplaceAllString(s, "")
if strings.Contains(s, ";") {
parts := strings.Split(s, ";")
posFF, ctypePos := makeFormatter(parts[0])
rem := make([]FmtFunc, len(parts)-1)
for i, ps := range parts[1:] {
rem[i], _ = makeFormatter(ps)
}
return switchFmtFunc(posFF, rem...), ctypePos
}
// escaped characters, and quoted text
s2 := fixEsc.ReplaceAllString(s, "")
s2 = formatMatchTextLiteral.ReplaceAllString(s, "")
if strings.ContainsAny(s2, "ymdhs") {
// it's a date/time format
if loc := minsMatch.FindStringIndex(s); loc != nil {
// m or mm in loc[0]:loc[1] is a minute format
inner := s[loc[0]:loc[1]]
inner = strings.Replace(inner, "mm", "04", 1)
inner = strings.Replace(inner, "m", "4", 1)
s = s[:loc[0]] + inner + s[loc[1]:]
}
dfreps := [][]string{
{"hh", "15"}, {"h", "15"},
{"ss", "05"}, {"s", "5"},
{"mmmmm", "Jan"}, // super ambiguous, replace with 3-letter month
{"mmmm", "January"}, {"mmm", "Jan"},
{"mm", "01"}, {"m", "1"},
{"dddd", "Monday"}, {"ddd", "Mon"},
{"dd", "02"}, {"d", "2"},
{"yyyy", "2006"}, {"yy", "06"},
}
if strings.Contains(s, "AM") || strings.Contains(s, "PM") {
dfreps[0][1] = "03"
dfreps[1][1] = "3"
}
for _, dfr := range dfreps {
s = strings.Replace(s, dfr[0], dfr[1], 1)
}
s = nonEsc.ReplaceAllString(s, `$1`)
s = squash.ReplaceAllString(s, ``)
s = fixEsc.ReplaceAllString(s, `$1`)
//log.Printf(" made time formatter '%s'", s)
return timeFmtFunc(s), DateCell
}
var ff FmtFunc
var ctype CellType
if strings.ContainsAny(s, ".Ee") {
verb := "f"
if strings.ContainsAny(s, "Ee") {
verb = "E"
}
s = regexp.MustCompile("[eE]+[+-]0+").ReplaceAllString(s, "")
s2 := strings.ReplaceAll(s, ",", "")
i1 := strings.IndexAny(s2, "0")
i2 := strings.IndexByte(s2, '.')
i3 := strings.LastIndexAny(s2, "0.")
mul := 1
if strings.Contains(s2, "%") {
mul = 100
}
sf := fmt.Sprintf("%%%d.%d%s", i3-i1, i3-i2, verb)
//log.Printf(" made float formatter '%s'", sf)
ff = sprintfFunc(sf, mul)
ctype = FloatCell
} else {
s2 := strings.ReplaceAll(s, ",", "")
i1 := strings.IndexAny(s2, "0")
i2 := strings.LastIndexAny(s2, "0.")
mul := 1
if strings.Contains(s2, "%") {
mul = 100
}
sf := fmt.Sprintf("%%%dd", i2-i1)
if (i2 - i1) == 0 {
sf = "%d"
}
//log.Printf(" made int formatter '%s'", sf)
ff = sprintfFunc(sf, mul)
ctype = IntegerCell
}
if strings.Contains(s, ",") {
ff = addCommas(ff)
//log.Printf(" added commas")
}
surReg := regexp.MustCompile(`[0#?,.]+`)
prepost := surReg.Split(s, 2)
if len(prepost) > 0 && len(prepost[0]) > 0 {
prepost[0] = nonEsc.ReplaceAllString(prepost[0], `$1`)
prepost[0] = squash.ReplaceAllString(prepost[0], ``)
prepost[0] = fixEsc.ReplaceAllString(prepost[0], `$1`)
}
if len(prepost) == 1 {
if prepost[0] == "@" {
return identFunc, StringCell
}
//log.Printf(" added static ('%s')", prepost[0])
return staticFmtFunc(prepost[0]), StringCell
}
if len(prepost[0]) > 0 || len(prepost[1]) > 0 {
prepost[1] = nonEsc.ReplaceAllString(prepost[1], `$1`)
prepost[1] = squash.ReplaceAllString(prepost[1], ``)
prepost[1] = fixEsc.ReplaceAllString(prepost[1], `$1`)
ff = surround(prepost[0], ff, prepost[1])
//log.Printf(" added surround ('%s' ... '%s')", prepost[0], prepost[1])
}
return ff, ctype
}
// Get the number format func to use for formatting values,
// it returns false when fmtID is unknown.
func (x *Formatter) Get(fmtID uint16) (FmtFunc, bool) {
ff, ok := goFormatters[fmtID]
if !ok {
fs, ok2 := x.customCodes[fmtID]
if ok2 {
return fs, true
}
ff = identFunc
}
return ff, ok
}
// Apply the specified number format to the value.
// Returns false when fmtID is unknown.
func (x *Formatter) Apply(fmtID uint16, val interface{}) (string, bool) {
ff, ok := goFormatters[fmtID]
if !ok {
fs, ok2 := x.customCodes[fmtID]
if ok2 {
return fs(x, val), true
}
}
return ff(x, val), ok
}
// builtInFormats are all the built-in number formats for XLS/XLSX.
var builtInFormats = map[uint16]string{
0: `General`,
1: `0`,
2: `0.00`,
3: `#,##0`,
4: `#,##0.00`,
9: `0%`,
10: `0.00%`,
11: `0.00E+00`,
12: `# ?/?`,
13: `# ??/??`,
14: `mm-dd-yy`,
15: `d-mmm-yy`,
16: `d-mmm`,
17: `mmm-yy`,
18: `h:mm AM/PM`,
19: `h:mm:ss AM/PM`,
20: `h:mm`,
21: `h:mm:ss`,
22: `m/d/yy h:mm`,
37: `#,##0 ;(#,##0)`,
38: `#,##0 ;[Red](#,##0)`,
39: `#,##0.00;(#,##0.00)`,
40: `#,##0.00;[Red](#,##0.00)`,
41: `_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)`,
42: `_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)`,
43: `_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)`,
44: `_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)`,
45: `mm:ss`,
46: `[h]:mm:ss`,
47: `mmss.0`,
48: `##0.0E+0`,
49: `@`,
// zh-cn format codes
27: `yyyy"年"m"月"`,
28: `m"月"d"日"`,
29: `m"月"d"日"`,
30: `m-d-yy`,
31: `yyyy"年"m"月"d"日"`,
32: `h"时"mm"分"`,
33: `h"时"mm"分"ss"秒"`,
34: `上午/下午 h"时"mm"分"`,
35: `上午/下午 h"时"mm"分"ss"秒"`,
36: `yyyy"年"m"月"`,
50: `yyyy"年"m"月"`,
51: `m"月"d"日"`,
52: `yyyy"年"m"月"`,
53: `m"月"d"日"`,
54: `m"月"d"日"`,
55: `上午/下午 h"时"mm"分"`,
56: `上午/下午 h"时"mm"分"ss"秒`,
57: `yyyy"年"m"月"`,
58: `m"月"d"日"`,
// th-th format codes (in the spec these have a "t" prefix?)
59: `0`,
60: `0.00`,
61: `#,##0`,
62: `#,##0.00`,
67: `0%`,
68: `0.00%`,
69: `# ?/?`,
70: `# ??/??`,
// th format code, but translated to aid the parser
71: `d/m/yyyy`, // `ว/ด/ปปปป`,
72: `d-mmm-yy`, // `ว-ดดด-ปป`,
73: `d-mmm`, // `ว-ดดด`,
74: `mmm-yy`, // `ดดด-ปป`,
75: `h:mm`, // `ช:นน`,
76: `h:mm:ss`, // `ช:นน:ทท`,
77: `d/m/yyyy h:mm`, // `ว/ด/ปปปป ช:นน`,
78: `mm:ss`, // `นน:ทท`,
79: `[h]:mm:ss`, // `[ช]:นน:ทท`,
80: `mm:ss.0`, // `นน:ทท.0`,
81: `d/m/bb`, // `d/m/bb`,
}
// builtInFormatTypes are the underlying datatypes for built-in number formats in XLS/XLSX.
var builtInFormatTypes = map[uint16]CellType{
// 0 has no defined type
1: IntegerCell,
2: FloatCell,
3: IntegerCell,
4: FloatCell,
9: FloatCell,
10: FloatCell,
11: FloatCell,
12: FloatCell,
13: FloatCell,
14: DateCell,
15: DateCell,
16: DateCell,
17: DateCell,
18: DateCell,
19: DateCell,
20: DateCell,
21: DateCell,
22: DateCell,
37: IntegerCell,
38: IntegerCell,
39: FloatCell,
40: FloatCell,
41: IntegerCell,
42: IntegerCell,
43: FloatCell,
44: FloatCell,
45: DateCell, // Durations?
46: DateCell,
47: DateCell,
48: FloatCell,
49: StringCell,
27: DateCell,
28: DateCell,
29: DateCell,
30: DateCell,
31: DateCell,
32: DateCell,
33: DateCell,
34: DateCell,
35: DateCell,
36: DateCell,
50: DateCell,
51: DateCell,
52: DateCell,
53: DateCell,
54: DateCell,
55: DateCell,
56: DateCell,
57: DateCell,
58: DateCell,
59: IntegerCell,
60: FloatCell,
61: IntegerCell,
62: FloatCell,
67: FloatCell,
68: FloatCell,
69: FloatCell,
70: FloatCell,
71: DateCell,
72: DateCell,
73: DateCell,
74: DateCell,
75: DateCell,
76: DateCell,
77: DateCell,
78: DateCell,
79: DateCell,
80: DateCell,
81: DateCell,
}
+74
View File
@@ -0,0 +1,74 @@
package commonxl
import (
"math"
)
// DecimalToWholeFraction converts a floating point value into a whole
// number and fraction approximation with at most nn digits in the numerator
// and nd digits in the denominator.
func DecimalToWholeFraction(val float64, nn, nd int) (whole, num, den int) {
wholeF, part := math.Modf(val)
if part == 0.0 {
return int(wholeF), 0, 1
}
if part < 0.0 {
part = -part
}
whole = int(wholeF)
num, den = DecimalToFraction(part, nn, nd)
return
}
// DecimalToFraction converts a floating point value into a fraction
// approximation with at most nn digits in the numerator and nd
// digits in the denominator.
func DecimalToFraction(val float64, nn, nd int) (num, den int) {
// http://web.archive.org/web/20111027100847/http://homepage.smc.edu/kennedy_john/DEC2FRAC.PDF
sign := 1
z := val
if val < 0 {
sign = -1
z = -val
}
if nn == 0 {
nn = 2
}
if nd == 0 {
nd = 2
}
maxn := math.Pow(10.0, float64(nn)) // numerator with nn digits
maxd := math.Pow(10.0, float64(nd)) // denominator with nd digits
_, fracPart := math.Modf(val)
if fracPart == 0.0 {
return int(z) * sign, 1
}
if fracPart < 1e-9 {
return sign, int(1e9)
}
if fracPart > 1e9 {
return int(1e9) * sign, 1
}
diff := 1.0
denom := 1.0
numer := 0.0
var lastDenom, lastNumer float64
for diff > 1e-10 && z != math.Floor(z) {
z = 1 / (z - math.Floor(z))
tmp := denom
denom = (denom * math.Floor(z)) + lastDenom
lastDenom = tmp
lastNumer = numer
numer = math.Round(val * denom)
if numer >= maxn || denom >= maxd {
return sign * int(lastNumer), int(lastDenom)
}
diff = val - (numer / denom)
if diff < 0.0 {
diff = -diff
}
}
return sign * int(numer), int(denom)
}
+237
View File
@@ -0,0 +1,237 @@
package commonxl
import (
"fmt"
"log"
"time"
"github.com/pbnjay/grate"
)
// Sheet holds raw and rendered values for a spreadsheet.
type Sheet struct {
Formatter *Formatter
NumRows int
NumCols int
Rows [][]Cell
CurRow int
}
// Resize the sheet for the number of rows and cols given.
// Newly added cells default to blank.
func (s *Sheet) Resize(rows, cols int) {
for i := range s.Rows {
if i > rows {
break
}
n := cols - len(s.Rows[i])
if n <= 0 {
continue
}
s.Rows[i] = append(s.Rows[i], make([]Cell, n)...)
}
if rows <= 0 {
rows = 1
}
if cols <= 0 {
cols = 1
}
s.CurRow = 0
s.NumRows = rows
s.NumCols = cols
for rows >= len(s.Rows) {
s.Rows = append(s.Rows, make([]Cell, cols))
}
}
// Put the value at the cell location given.
func (s *Sheet) Put(row, col int, value interface{}, fmtNum uint16) {
//log.Println(row, col, value, fmtNum)
if row >= s.NumRows || col >= s.NumCols {
if grate.Debug {
log.Printf("grate: cell out of bounds row %d>=%d, col %d>=%d",
row, s.NumRows, col, s.NumCols)
}
// per the spec, this is an invalid Excel file
// but we'll resize in place instead of crashing out
if row >= s.NumRows {
s.NumRows = row + 1
}
if col >= s.NumCols {
s.NumCols = col + 1
}
s.Resize(s.NumRows, s.NumCols)
}
if spec, ok := value.(string); ok {
if spec == grate.EndRowMerged || spec == grate.EndColumnMerged || spec == grate.ContinueRowMerged || spec == grate.ContinueColumnMerged {
s.Rows[row][col] = NewCell(value)
s.Rows[row][col][1] = StaticCell
return
}
}
ct, ok := s.Formatter.getCellType(fmtNum)
// descrybe patch: Excel shows text as-is under a numeric format; upstream coerced it
// (a "0"-formatted "Šifra" header became int 0).
if _, isText := value.(string); isText && ct != StringCell {
ok = false
}
if !ok || fmtNum == 0 {
s.Rows[row][col] = NewCell(value)
} else {
s.Rows[row][col] = NewCellWithType(value, ct, s.Formatter)
}
s.Rows[row][col].SetFormatNumber(fmtNum)
}
// Set changes the value in an existing cell location.
// NB Currently only used for populating string results for formulas.
func (s *Sheet) Set(row, col int, value interface{}) {
if row > s.NumRows || col > s.NumCols {
log.Println("grate: cell out of bounds")
return
}
s.Rows[row][col][0] = value
s.Rows[row][col][1] = StringCell
}
// SetURL adds a hyperlink to an existing cell location.
func (s *Sheet) SetURL(row, col int, link string) {
if row > s.NumRows || col > s.NumCols {
log.Println("grate: cell out of bounds")
return
}
s.Rows[row][col].SetURL(link)
}
// Next advances to the next record of content.
// It MUST be called prior to any Scan().
func (s *Sheet) Next() bool {
if (s.CurRow + 1) > len(s.Rows) {
return false
}
s.CurRow++
return true
}
// Raw extracts the raw Cell interfaces underlying the current row.
func (s *Sheet) Raw() []Cell {
rr := make([]Cell, s.NumCols)
for i, cell := range s.Rows[s.CurRow-1] {
rr[i] = cell.Clone()
}
return rr
}
// Strings extracts values from the current record into a list of strings.
func (s *Sheet) Strings() []string {
res := make([]string, s.NumCols)
for i, cell := range s.Rows[s.CurRow-1] {
if cell.Type() == BlankCell {
res[i] = ""
continue
}
if cell.Type() == StaticCell {
res[i] = cell.Value().(string)
continue
}
val := cell.Value()
fs, ok := s.Formatter.Apply(cell.FormatNo(), val)
if !ok {
fs = fmt.Sprint(val)
}
res[i] = fs
}
return res
}
// Types extracts the data types from the current record into a list.
// options: "boolean", "integer", "float", "string", "date",
// and special cases: "blank", "hyperlink" which are string types
func (s *Sheet) Types() []string {
res := make([]string, s.NumCols)
for i, cell := range s.Rows[s.CurRow-1] {
res[i] = cell.Type().String()
}
return res
}
// Formats extracts the format code for the current record into a list.
func (s *Sheet) Formats() []string {
ok := true
res := make([]string, s.NumCols)
for i, cell := range s.Rows[s.CurRow-1] {
res[i], ok = builtInFormats[cell.FormatNo()]
if !ok {
res[i] = fmt.Sprint(cell.FormatNo())
}
}
return res
}
// Scan extracts values from the current record into the provided arguments
// Arguments must be pointers to one of 5 supported types:
// bool, int64, float64, string, or time.Time
// If invalid, returns ErrInvalidScanType
func (s *Sheet) Scan(args ...interface{}) error {
row := s.Rows[s.CurRow-1]
for i, a := range args {
val := row[i].Value()
switch v := a.(type) {
case bool, int64, float64, string, time.Time:
return fmt.Errorf("scan destinations must be pointer (arg %d is not)", i)
case *bool:
if x, ok := val.(bool); ok {
*v = x
} else {
return fmt.Errorf("scan destination %d expected *%T, not *bool", i, val)
}
case *int64:
if x, ok := val.(int64); ok {
*v = x
} else {
return fmt.Errorf("scan destination %d expected *%T, not *int64", i, val)
}
case *float64:
if x, ok := val.(float64); ok {
*v = x
} else {
return fmt.Errorf("scan destination %d expected *%T, not *float64", i, val)
}
case *string:
if x, ok := val.(string); ok {
*v = x
} else {
return fmt.Errorf("scan destination %d expected *%T, not *string", i, val)
}
case *time.Time:
if x, ok := val.(time.Time); ok {
*v = x
} else {
return fmt.Errorf("scan destination %d expected *%T, not *time.Time", i, val)
}
default:
return fmt.Errorf("scan destination for arg %d is not supported (%T)", i, a)
}
}
return nil
}
// IsEmpty returns true if there are no data values.
func (s *Sheet) IsEmpty() bool {
return (s.NumCols <= 1 && s.NumRows <= 1)
}
// Err returns the last error that occured.
func (s *Sheet) Err() error {
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package grate
import "errors"
var (
// configure at build time by adding go build arguments:
// -ldflags="-X github.com/pbnjay/grate.loglevel=debug"
loglevel string = "warn"
// Debug should be set to true to expose detailed logging.
Debug bool = (loglevel == "debug")
)
// ErrInvalidScanType is returned by Scan for invalid arguments.
var ErrInvalidScanType = errors.New("grate: Scan only supports *bool, *int, *float64, *string, *time.Time arguments")
// ErrNotInFormat is used to auto-detect file types using the defined OpenFunc
// It is returned by OpenFunc when the code does not detect correct file formats.
var ErrNotInFormat = errors.New("grate: file is not in this format")
// ErrUnknownFormat is used when grate does not know how to open a file format.
var ErrUnknownFormat = errors.New("grate: file format is not known/supported")
type errx struct {
errs []error
}
func (e errx) Error() string {
return e.errs[0].Error()
}
func (e errx) Unwrap() error {
if len(e.errs) > 1 {
return e.errs[1]
}
return nil
}
// WrapErr wraps a set of errors.
func WrapErr(e ...error) error {
if len(e) == 1 {
return e[0]
}
return errx{errs: e}
}
+3
View File
@@ -0,0 +1,3 @@
module github.com/pbnjay/grate
go 1.16
+104
View File
@@ -0,0 +1,104 @@
// Package grate opens tabular data files (such as spreadsheets and delimited plaintext files)
// and allows programmatic access to the data contents in a consistent interface.
package grate
import (
"errors"
"log"
"sort"
)
// Source represents a set of data collections.
type Source interface {
// List the individual data tables within this source.
List() ([]string, error)
// Get a Collection from the source by name.
Get(name string) (Collection, error)
// Close the source and discard memory.
Close() error
}
// Collection represents an iterable collection of records.
type Collection interface {
// Next advances to the next record of content.
// It MUST be called prior to any Scan().
Next() bool
// Strings extracts values from the current record into a list of strings.
Strings() []string
// Types extracts the data types from the current record into a list.
// options: "boolean", "integer", "float", "string", "date",
// and special cases: "blank", "hyperlink" which are string types
Types() []string
// Formats extracts the format codes for the current record into a list.
Formats() []string
// Scan extracts values from the current record into the provided arguments
// Arguments must be pointers to one of 5 supported types:
// bool, int64, float64, string, or time.Time
// If invalid, returns ErrInvalidScanType
Scan(args ...interface{}) error
// IsEmpty returns true if there are no data values.
IsEmpty() bool
// Err returns the last error that occured.
Err() error
}
// OpenFunc defines a Source's instantiation function.
// It should return ErrNotInFormat immediately if filename is not of the correct file type.
type OpenFunc func(filename string) (Source, error)
// Open a tabular data file and return a Source for accessing it's contents.
func Open(filename string) (Source, error) {
for _, o := range srcTable {
src, err := o.op(filename)
if err == nil {
return src, nil
}
if !errors.Is(err, ErrNotInFormat) {
return nil, err
}
if Debug {
log.Println(" ", filename, "is not in", o.name, "format")
}
}
return nil, ErrUnknownFormat
}
type srcOpenTab struct {
name string
pri int
op OpenFunc
}
var srcTable = make([]*srcOpenTab, 0, 20)
// Register the named source as a grate datasource implementation.
func Register(name string, priority int, opener OpenFunc) error {
if Debug {
log.Println("Registering the", name, "format at priority", priority)
}
srcTable = append(srcTable, &srcOpenTab{name: name, pri: priority, op: opener})
sort.Slice(srcTable, func(i, j int) bool {
return srcTable[i].pri < srcTable[j].pri
})
return nil
}
const (
// ContinueColumnMerged marks a continuation column within a merged cell.
ContinueColumnMerged = "→"
// EndColumnMerged marks the last column of a merged cell.
EndColumnMerged = "⇥"
// ContinueRowMerged marks a continuation row within a merged cell.
ContinueRowMerged = "↓"
// EndRowMerged marks the last row of a merged cell.
EndRowMerged = "⤓"
)
+363
View File
@@ -0,0 +1,363 @@
// Package cfb implements the Microsoft Compound File Binary File Format.
package cfb
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/53989ce4-7b05-4f8d-829b-d08d6148375b
// Note for myself:
// Storage = Directory
// Stream = File
import (
"bytes"
"encoding/binary"
"errors"
"io"
"io/ioutil"
"log"
"unicode/utf16"
"github.com/pbnjay/grate"
)
const fullAssertions = true
const (
secFree uint32 = 0xFFFFFFFF // FREESECT
secEndOfChain uint32 = 0xFFFFFFFE // ENDOFCHAIN
secFAT uint32 = 0xFFFFFFFD // FATSECT
secDIFAT uint32 = 0xFFFFFFFC // DIFSECT
secReserved uint32 = 0xFFFFFFFB
secMaxRegular uint32 = 0xFFFFFFFA // MAXREGSECT
)
// Header of the Compound File MUST be at the beginning of the file (offset 0).
type header struct {
Signature uint64 // Identification signature for the compound file structure, and MUST be set to the value 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1.
ClassID [2]uint64 // Reserved and unused class ID that MUST be set to all zeroes (CLSID_NULL).
MinorVersion uint16 // Version number for nonbreaking changes. This field SHOULD be set to 0x003E if the major version field is either 0x0003 or 0x0004.
MajorVersion uint16 // Version number for breaking changes. This field MUST be set to either 0x0003 (version 3) or 0x0004 (version 4).
ByteOrder uint16 // This field MUST be set to 0xFFFE. This field is a byte order mark for all integer fields, specifying little-endian byte order.
SectorShift uint16 // This field MUST be set to 0x0009, or 0x000c, depending on the Major Version field. This field specifies the sector size of the compound file as a power of 2.
MiniSectorShift uint16 // This field MUST be set to 0x0006. This field specifies the sector size of the Mini Stream as a power of 2. The sector size of the Mini Stream MUST be 64 bytes.
Reserved1 [6]byte // This field MUST be set to all zeroes.
NumDirectorySectors int32 // This integer field contains the count of the number of directory sectors in the compound file.
NumFATSectors int32 // This integer field contains the count of the number of FAT sectors in the compound file.
FirstDirectorySectorLocation uint32 // This integer field contains the starting sector number for the directory stream.
TransactionSignature int32 // This integer field MAY contain a sequence number that is incremented every time the compound file is saved by an implementation that supports file transactions. This is the field that MUST be set to all zeroes if file transactions are not implemented.<1>
MiniStreamCutoffSize int32 // This integer field MUST be set to 0x00001000. This field specifies the maximum size of a user-defined data stream that is allocated from the mini FAT and mini stream, and that cutoff is 4,096 bytes. Any user-defined data stream that is greater than or equal to this cutoff size must be allocated as normal sectors from the FAT.
FirstMiniFATSectorLocation uint32 // This integer field contains the starting sector number for the mini FAT.
NumMiniFATSectors int32 // This integer field contains the count of the number of mini FAT sectors in the compound file.
FirstDIFATSectorLocation uint32 // This integer field contains the starting sector number for the DIFAT.
NumDIFATSectors int32 // This integer field contains the count of the number of DIFAT sectors in the compound file.
DIFAT [109]uint32 // This array of 32-bit integer fields contains the first 109 FAT sector locations of the compound file.
}
type objectType byte
const (
typeUnknown objectType = 0x00
typeStorage objectType = 0x01
typeStream objectType = 0x02
typeRootStorage objectType = 0x05
)
type directory struct {
Name [32]uint16 // 32 utf16 characters
NameByteLen int16 // length of Name in bytes
ObjectType objectType
ColorFlag byte // 0=red, 1=black
LeftSiblingID uint32 // stream ids
RightSiblingID uint32
ChildID uint32
ClassID [2]uint64 // GUID
StateBits uint32
CreationTime int64
ModifiedTime int64
StartingSectorLocation int32
StreamSize uint64
}
func (d *directory) String() string {
if (d.NameByteLen&1) == 1 || d.NameByteLen > 64 {
return "<invalid utf16 string>"
}
r16 := utf16.Decode(d.Name[:int(d.NameByteLen)/2])
// trim off null terminator
return string(r16[:len(r16)-1])
}
// Document represents a Compound File Binary Format document.
type Document struct {
// the entire file, loaded into memory
data []byte
// pre-parsed info
header *header
dir []*directory
// lookup tables for all the sectors
fat []uint32
minifat []uint32
ministreamstart uint32
ministreamsize uint32
}
func (d *Document) load(rx io.ReadSeeker) error {
var err error
d.data, err = ioutil.ReadAll(rx)
if err != nil {
return err
}
br := bytes.NewReader(d.data)
h := &header{}
err = binary.Read(br, binary.LittleEndian, h)
if h.Signature != 0xe11ab1a1e011cfd0 {
return grate.ErrNotInFormat // errors.New("ole2: invalid format")
}
if h.ByteOrder != 0xFFFE {
return grate.ErrNotInFormat //errors.New("ole2: invalid format")
}
if fullAssertions {
if h.ClassID[0] != 0 || h.ClassID[1] != 0 {
return grate.ErrNotInFormat //errors.New("ole2: invalid CLSID")
}
if h.MajorVersion != 3 && h.MajorVersion != 4 {
return errors.New("ole2: unknown major version")
}
if h.MinorVersion != 0x3B && h.MinorVersion != 0x3E {
log.Printf("WARNING MinorVersion = 0x%02x NOT 0x3E", h.MinorVersion)
//return errors.New("ole2: unknown minor version")
}
for _, v := range h.Reserved1 {
if v != 0 {
return errors.New("ole2: reserved section is non-zero")
}
}
if h.MajorVersion == 3 {
if h.SectorShift != 9 {
return errors.New("ole2: invalid sector size")
}
if h.NumDirectorySectors != 0 {
return errors.New("ole2: version 3 does not support directory sectors")
}
}
if h.MajorVersion == 4 {
if h.SectorShift != 12 {
return errors.New("ole2: invalid sector size")
}
}
if h.MiniSectorShift != 6 {
return errors.New("ole2: invalid mini sector size")
}
if h.MiniStreamCutoffSize != 0x00001000 {
return errors.New("ole2: invalid mini sector cutoff")
}
}
d.header = h
numFATentries := (1 << (h.SectorShift - 2))
le := binary.LittleEndian
d.fat = make([]uint32, 0, numFATentries*int(1+d.header.NumFATSectors))
d.minifat = make([]uint32, 0, numFATentries*int(1+h.NumMiniFATSectors))
// step 1: read the DIFAT sector list
for i := 0; i < 109; i++ {
sid := h.DIFAT[i]
if sid == secFree {
break
}
offs := int64(1+sid) << int32(h.SectorShift)
if offs >= int64(len(d.data)) {
return errors.New("xls/cfb: unable to load file")
}
sector := d.data[offs:]
for j := 0; j < numFATentries; j++ {
sid2 := le.Uint32(sector)
d.fat = append(d.fat, sid2)
sector = sector[4:]
}
}
if h.NumDIFATSectors > 0 {
sid1 := h.FirstDIFATSectorLocation
for sid1 != secEndOfChain {
offs := int64(1+sid1) << int32(h.SectorShift)
difatSector := d.data[offs:]
for i := 0; i < numFATentries-1; i++ {
sid2 := le.Uint32(difatSector)
if sid2 == secFree || sid2 == secEndOfChain {
difatSector = difatSector[4:]
continue
}
offs := int64(1+sid2) << int32(h.SectorShift)
if offs >= int64(len(d.data)) {
return errors.New("xls/cfb: unable to load file")
}
sector := d.data[offs:]
for j := 0; j < numFATentries; j++ {
sid3 := le.Uint32(sector)
d.fat = append(d.fat, sid3)
sector = sector[4:]
}
difatSector = difatSector[4:]
}
// chain the next DIFAT sector
sid1 = le.Uint32(difatSector)
}
}
// step 2: read the mini FAT
sid := h.FirstMiniFATSectorLocation
for sid != secEndOfChain {
offs := int64(1+sid) << int32(h.SectorShift)
if offs >= int64(len(d.data)) {
return errors.New("xls/cfb: unable to load file")
}
sector := d.data[offs:]
for j := 0; j < numFATentries; j++ {
sid = le.Uint32(sector)
d.minifat = append(d.minifat, sid)
sector = sector[4:]
}
if len(d.minifat) >= int(h.NumMiniFATSectors) {
break
}
// chain the next mini FAT sector
sid = le.Uint32(sector)
}
// step 3: read the Directory Entries
err = d.buildDirs(br)
return err
}
func (d *Document) buildDirs(br *bytes.Reader) error {
h := d.header
le := binary.LittleEndian
// step 2: read the Directory
sid := h.FirstDirectorySectorLocation
offs := int64(1+sid) << int64(h.SectorShift)
br.Seek(offs, io.SeekStart)
for j := 0; j < 4; j++ {
dirent := &directory{}
binary.Read(br, le, dirent)
if d.header.MajorVersion == 3 {
// mask out upper 32bits
dirent.StreamSize = dirent.StreamSize & 0xFFFFFFFF
}
switch dirent.ObjectType {
case typeRootStorage:
d.ministreamstart = uint32(dirent.StartingSectorLocation)
d.ministreamsize = uint32(dirent.StreamSize)
case typeStorage:
//log.Println("got a storage? what to do now?")
case typeStream:
/*
var freader io.Reader
if dirent.StreamSize < uint64(d.header.MiniStreamCutoffSize) {
freader = d.getMiniStreamReader(uint32(dirent.StartingSectorLocation), dirent.StreamSize)
} else if dirent.StreamSize != 0 {
freader = d.getStreamReader(uint32(dirent.StartingSectorLocation), dirent.StreamSize)
}
*/
case typeUnknown:
return nil
}
d.dir = append(d.dir, dirent)
}
return nil
}
func (d *Document) getStreamReader(sid uint32, size uint64) (io.ReadSeeker, error) {
// NB streamData is a slice of slices of the raw data, so this is the
// only allocation - for the (much smaller) list of sector slices
streamData := make([][]byte, 1+(size>>d.header.SectorShift))
x := 0
secSize := int64(1) << int32(d.header.SectorShift)
for sid != secEndOfChain && sid != secFree {
offs := int64(1+sid) << int64(d.header.SectorShift)
if offs > int64(len(d.data)) {
return nil, errors.New("ole2: corrupt data format")
}
slice := d.data[offs : offs+secSize]
if size < uint64(len(slice)) {
slice = slice[:size]
size = 0
} else {
size -= uint64(len(slice))
}
streamData[x] = slice
if size == 0 {
break
}
sid = d.fat[sid]
x++
}
if size != 0 {
return nil, errors.New("ole2: incomplete read")
}
return &SliceReader{Data: streamData}, nil
}
func (d *Document) getMiniStreamReader(sid uint32, size uint64) (io.ReadSeeker, error) {
// TODO: move into a separate cache so we don't recalculate it each time
fatStreamData := make([][]byte, 1+(d.ministreamsize>>d.header.SectorShift))
// NB streamData is a slice of slices of the raw data, so this is the
// only allocation - for the (much smaller) list of sector slices
streamData := make([][]byte, 1+(size>>d.header.MiniSectorShift))
x := 0
fsid := d.ministreamstart
fsize := uint64(d.ministreamsize)
secSize := int64(1) << int64(d.header.SectorShift)
for fsid != secEndOfChain && fsid != secFree {
offs := int64(1+fsid) << int64(d.header.SectorShift)
slice := d.data[offs : offs+secSize]
if fsize < uint64(len(slice)) {
slice = slice[:fsize]
fsize = 0
} else {
fsize -= uint64(len(slice))
}
fatStreamData[x] = slice
x++
fsid = d.fat[fsid]
}
x = 0
miniSecSize := int64(1) << int64(d.header.MiniSectorShift)
for sid != secEndOfChain && sid != secFree {
offs := int64(sid) << int64(d.header.MiniSectorShift)
so, si := offs/secSize, offs%secSize
data := fatStreamData[so]
slice := data[si : si+miniSecSize]
if size < uint64(len(slice)) {
slice = slice[:size]
size = 0
} else {
size -= uint64(len(slice))
}
streamData[x] = slice
x++
sid = d.minifat[sid]
}
return &SliceReader{Data: streamData}, nil
}
+46
View File
@@ -0,0 +1,46 @@
package cfb
import (
"fmt"
"io"
"os"
)
// Open a Compound File Binary Format document.
func Open(filename string) (*Document, error) {
d := &Document{}
f, err := os.Open(filename)
if err != nil {
return nil, err
}
err = d.load(f)
if err != nil {
return nil, err
}
return d, nil
}
// List the streams contained in the document.
func (d *Document) List() ([]string, error) {
var res []string
for _, e := range d.dir {
if e.ObjectType == typeStream {
res = append(res, e.String())
}
}
return res, nil
}
// Open the named stream contained in the document.
func (d *Document) Open(name string) (io.ReadSeeker, error) {
for _, e := range d.dir {
if e.String() == name && e.ObjectType == typeStream {
if e.StreamSize < uint64(d.header.MiniStreamCutoffSize) {
return d.getMiniStreamReader(uint32(e.StartingSectorLocation), e.StreamSize)
} else if e.StreamSize != 0 {
return d.getStreamReader(uint32(e.StartingSectorLocation), e.StreamSize)
}
}
}
return nil, fmt.Errorf("cfb: stream '%s' not found", name)
}
+101
View File
@@ -0,0 +1,101 @@
package cfb
import (
"errors"
"io"
)
// SliceReader wraps a list of slices as a io.ReadSeeker that
// can transparently merge them into a single coherent stream.
type SliceReader struct {
CSize []int64
Data [][]byte
Index uint
Offset uint
}
// Read implements the io.Reader interface.
func (s *SliceReader) Read(b []byte) (int, error) {
if s.Index >= uint(len(s.Data)) {
return 0, io.EOF
}
n := copy(b, s.Data[s.Index][s.Offset:])
if n > 0 {
s.Offset += uint(n)
if s.Offset == uint(len(s.Data[s.Index])) {
s.Offset = 0
s.Index++
}
return n, nil
}
return 0, io.EOF
}
var x io.Seeker
// Seek implements the io.Seeker interface.
func (s *SliceReader) Seek(offset int64, whence int) (int64, error) {
if len(s.CSize) != len(s.Data) {
// calculate the cumulative block size cache
s.CSize = make([]int64, len(s.Data))
sz := int64(0)
for i, d := range s.Data {
s.CSize[i] = sz
sz += int64(len(d))
}
}
if s.Index >= uint(len(s.CSize)) {
s.Index = uint(len(s.CSize) - 1)
s.Offset = uint(len(s.Data[s.Index]))
}
// current offset in stream
trueOffset := int64(s.Offset) + s.CSize[int(s.Index)]
if offset == 0 && whence == io.SeekCurrent {
// just asking for current position
return trueOffset, nil
}
switch whence {
case io.SeekStart:
if offset < 0 {
return -1, errors.New("xls: invalid seek offset")
}
s.Index = 0
s.Offset = 0
trueOffset = 0
case io.SeekEnd:
if offset > 0 {
return -1, errors.New("xls: invalid seek offset")
}
s.Index = uint(len(s.Data) - 1)
s.Offset = uint(len(s.Data[s.Index]))
trueOffset = int64(s.Offset) + s.CSize[s.Index]
default:
// current position already defined
}
wantOffset := offset + trueOffset
for trueOffset != wantOffset {
loOffset := s.CSize[int(s.Index)]
hiOffset := s.CSize[int(s.Index)] + int64(len(s.Data[s.Index]))
if wantOffset > loOffset && wantOffset < hiOffset {
s.Offset = uint(wantOffset - loOffset)
return wantOffset, nil
}
if trueOffset > wantOffset {
s.Index--
s.Offset = 0
trueOffset = s.CSize[int(s.Index)]
} else if trueOffset < wantOffset {
s.Index++
s.Offset = 0
trueOffset = s.CSize[int(s.Index)]
}
}
return wantOffset, nil
}
+103
View File
@@ -0,0 +1,103 @@
// Package crypto implements excel encryption algorithms from the
// MS-OFFCRYPTO design specs. Currently only standard/basic RC4
// "obfuscation" is supported.
package crypto
import (
"bytes"
"encoding/binary"
"fmt"
)
// Decryptor describes methods to decrypt an excel sheet.
type Decryptor interface {
// SetPassword for the decryption.
SetPassword(password []byte)
// Read implements the io.Reader interface.
Read(p []byte) (n int, err error)
// Write implements the io.Writer interface.
Write(p []byte) (n int, err error)
// Bytes returns the decrypted data.
Bytes() []byte
// Flush tells the decryptor to decrypt the latest block.
Flush()
// Reset the decryptor, and clear all written and readable data.
Reset()
}
// Algorithms designed based on specs in MS-OFFCRYPTO:
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/3c34d72a-1a61-4b52-a893-196f9157f083
// Important notes from MS-XLS section 2.2.10:
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06
// When obfuscating or encrypting BIFF records in these streams the record type and
// record size components MUST NOT be obfuscated or encrypted.
// In addition the following records MUST NOT be obfuscated or encrypted:
// BOF (section 2.4.21), FilePass (section 2.4.117), UsrExcl (section 2.4.339),
// FileLock (section 2.4.116), InterfaceHdr (section 2.4.146), RRDInfo (section 2.4.227),
// and RRDHead (section 2.4.226). Additionally, the lbPlyPos field of the BoundSheet8
// record (section 2.4.28) MUST NOT be encrypted.
// For RC4 encryption and RC4 CryptoAPI encryption, the Unicode password string is used
// to generate the encryption key as specified in [MS-OFFCRYPTO] section 2.3.6.2 or
// [MS-OFFCRYPTO] section 2.3.5.2 depending on the RC4 algorithm used. The record data
// is then encrypted by the specific RC4 algorithm in 1024-byte blocks. The block number
// is set to zero at the beginning of every BIFF record stream, and incremented by one
// at each 1024-byte boundary. Bytes to be encrypted are passed into the RC4 encryption
// function and then written to the stream. For unencrypted records and the record
// headers consisting of the record type and record size, a byte buffer of all zeros,
// of the same size as the section of unencrypted bytes, is passed into the RC4
// encryption function. The results are then ignored and the unencrypted bytes are
// written to the stream.
// DefaultXLSPassword is the default encryption password defined by note
// <100> Section 2.4.191: If the value of the wPassword field of the Password record in
// the Globals Substream is not 0x0000, Excel 97, Excel 2000, Excel 2002, Office Excel
// 2003, Office Excel 2007, and Excel 2010 encrypt the document as specified in [MS-OFFCRYPTO],
// section 2.3. If an encryption password is not specified or the workbook or sheet is only
// protected, the document is encrypted with the default password of:
// DefaultXLSPassword is the default Excel encryption password.
var DefaultXLSPassword = "VelvetSweatshop"
/////////////
// 2.3.6.1
type basicRC4Encryption struct {
MajorVersion uint16
MinorVersion uint16
Salt [16]byte
Verifier [16]byte
VerifierHash [16]byte
}
// NewBasicRC4 implements the standard RC4 decryption.
func NewBasicRC4(data []byte) (Decryptor, error) {
h := basicRC4Encryption{}
b := bytes.NewReader(data)
err := binary.Read(b, binary.LittleEndian, &h)
if err != nil {
return nil, err
}
if h.MinorVersion != 1 {
return nil, fmt.Errorf("xls: unknown basic-RC4 minor version %d (%d byte record)",
h.MinorVersion, len(data))
}
if len(data) != 52 {
return nil, fmt.Errorf("xls: data length is invalid (expected 52 bytes, got %d)",
len(data))
}
d := &rc4Writer{
Salt: make([]byte, len(h.Salt)),
}
copy(d.Salt, h.Salt[:])
return d, d.Verify(h.Verifier[:], h.VerifierHash[:])
}
+155
View File
@@ -0,0 +1,155 @@
package crypto
import (
"bytes"
"crypto/md5"
"crypto/rc4"
"encoding/binary"
"fmt"
)
var _ Decryptor = &rc4Writer{}
func (d *rc4Writer) Write(data []byte) (n int, err error) {
x := len(data)
for len(data) > 0 {
n := copy(d.bytes[d.offset:], data)
d.offset += n
if d.offset >= 1024 {
if d.offset != 1024 {
panic("invalid offset from write")
}
d.Flush()
}
data = data[n:]
}
return x, nil
}
func (d *rc4Writer) Read(data []byte) (n int, err error) {
return d.buf.Read(data)
}
// Reset to block 0, and clear all written and readable data.
func (d *rc4Writer) Reset() {
d.block = 0
d.offset = 0
d.buf.Reset()
}
// Flush tells the decryptor to decrypt the latest block.
func (d *rc4Writer) Flush() {
var zeros [1024]byte
endpad := 0
if d.offset < 1024 {
endpad = copy(d.bytes[d.offset:], zeros[:])
d.offset += endpad
}
if d.offset != 1024 {
panic("invalid offset fill")
}
// decrypt and write results to output buffer
d.startBlock()
d.dec.XORKeyStream(d.bytes[:], d.bytes[:])
d.buf.Write(d.bytes[:1024-endpad])
d.offset = 0
d.block++
}
// SetPassword for the decryption.
func (d *rc4Writer) SetPassword(password []byte) {
d.Password = make([]rune, len(password))
for i, p := range password {
d.Password[i] = rune(p)
}
/// compute the first part of the encryption key
result := generateStd97Key(d.Password, d.Salt)
d.encKey = make([]byte, len(result))
copy(d.encKey, result)
}
type rc4Writer struct {
block uint32
offset int
bytes [1024]byte
// records the decrypted data
buf bytes.Buffer
///////
// decrypter for RC4 content streams
dec *rc4.Cipher
cipherKey []byte // H1 per 2.3.6.2
encKey []byte // Hfinal per 2.3.6.2
Salt []byte
Password []rune
}
func (d *rc4Writer) Bytes() []byte {
return d.buf.Bytes()
}
func (d *rc4Writer) Verify(everifier, everifierHash []byte) error {
d.Reset()
d.startBlock()
var temp1 [16]byte
var temp2 [16]byte
d.dec.XORKeyStream(temp1[:], everifier)
d.dec.XORKeyStream(temp2[:], everifierHash)
newhash := md5.Sum(temp1[:])
for i, c := range newhash {
if temp2[i] != c {
return fmt.Errorf("verification failed")
}
}
return nil
}
/////////////////////
func (d *rc4Writer) startBlock() {
if d.encKey == nil {
d.SetPassword([]byte(DefaultXLSPassword))
}
d.cipherKey = make([]byte, 16)
copy(d.cipherKey, d.encKey[:5])
binary.LittleEndian.PutUint32(d.cipherKey[5:], d.block)
mhash := md5.Sum(d.cipherKey[:9])
d.dec, _ = rc4.NewCipher(mhash[:])
}
func generateStd97Key(passData []rune, salt []byte) []byte {
if len(passData) == 0 || len(salt) != 16 {
panic("invalid keygen material")
}
passBytes := make([]byte, len(passData)*2)
for i, c := range passData {
binary.LittleEndian.PutUint16(passBytes[2*i:], uint16(c))
}
// digest the IV then copy back into pKeyData
h0 := md5.Sum(passBytes)
// now do the final set of keygen ops
msum := md5.New()
for i := 0; i < 16; i++ {
msum.Write(h0[:5])
msum.Write(salt)
}
// return H1
temp := make([]byte, 0, 16)
temp = msum.Sum(temp)
return temp
}
+146
View File
@@ -0,0 +1,146 @@
package xls
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"unicode/utf16"
)
func decodeHyperlinks(raw []byte) (displayText, linkText string, err error) {
raw = raw[16:] // skip classid
slen := binary.LittleEndian.Uint32(raw[:4])
if slen != 2 {
return "", "", errors.New("xls: unknown hyperlink version")
}
flags := binary.LittleEndian.Uint32(raw[4:8])
raw = raw[8:]
if (flags & hlstmfHasDisplayName) != 0 {
slen = binary.LittleEndian.Uint32(raw[:4])
raw = raw[4:]
us := make([]uint16, slen)
for i := 0; i < int(slen); i++ {
us[i] = binary.LittleEndian.Uint16(raw)
raw = raw[2:]
}
displayText = string(utf16.Decode(us))
}
if (flags & hlstmfHasFrameName) != 0 {
// skip a HyperlinkString containing target Frame
slen = binary.LittleEndian.Uint32(raw[:4])
raw = raw[4+(slen*2):]
}
if (flags & hlstmfHasMoniker) != 0 {
if (flags & hlstmfMonikerSavedAsStr) != 0 {
// read HyperlinkString containing the URL
slen = binary.LittleEndian.Uint32(raw[:4])
raw = raw[4:]
us := make([]uint16, slen)
for i := 0; i < int(slen); i++ {
us[i] = binary.LittleEndian.Uint16(raw)
raw = raw[2:]
}
linkText = string(utf16.Decode(us))
} else {
n := 0
var err error
linkText, n, err = parseHyperlinkMoniker(raw)
raw = raw[n:]
if err != nil {
return "", "", err
}
}
}
if (flags & hlstmfHasLocationStr) != 0 {
slen = binary.LittleEndian.Uint32(raw[:4])
raw = raw[4:]
us := make([]uint16, slen)
for i := 0; i < int(slen); i++ {
us[i] = binary.LittleEndian.Uint16(raw)
raw = raw[2:]
}
linkText = string(utf16.Decode(us))
}
linkText = strings.Trim(linkText, " \v\f\t\r\n\x00")
displayText = strings.Trim(displayText, " \v\f\t\r\n\x00")
return
}
func parseHyperlinkMoniker(raw []byte) (string, int, error) {
classid := raw[:16]
no := 16
isURLMoniker := true
isFileMoniker := true
urlMonikerClassID := [16]byte{0xE0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B}
fileMonikerClassID := [16]byte{0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}
for i, b := range classid {
if urlMonikerClassID[i] != b {
isURLMoniker = false
}
if fileMonikerClassID[i] != b {
isFileMoniker = false
}
}
if isURLMoniker {
length := binary.LittleEndian.Uint32(raw[no:])
no += 4
length /= 2
buf := make([]uint16, length)
for i := 0; i < int(length); i++ {
buf[i] = binary.LittleEndian.Uint16(raw[no:])
no += 2
}
if length > 12 && buf[length-13] == 0 {
buf = buf[:length-12]
}
return string(utf16.Decode(buf)), no, nil
}
if isFileMoniker {
//x := binary.LittleEndian.Uint16(raw[no:]) //cAnti
length := binary.LittleEndian.Uint32(raw[no+2:]) //ansiLength
no += 6
buf := raw[no : no+int(length)]
// skip 24 more bytes for misc fixed properties
no += int(length) + 24
length = binary.LittleEndian.Uint32(raw[no:]) // cbUnicodePathSize
no += 4
if length > 0 {
no += 6
length -= 6
buf2 := make([]uint16, length/2)
for i := 0; i < int(length/2); i++ {
buf2[i] = binary.LittleEndian.Uint16(raw[no:])
no += 2
}
return string(utf16.Decode(buf2)), no, nil
}
return string(buf), no, nil
}
return "", 0, fmt.Errorf("xls: unknown moniker classid")
}
// HLink flags
const (
hlstmfHasMoniker = uint32(0x001)
hlstmfIsAbsolute = uint32(0x002)
hlstmfSiteGaveDisplayName = uint32(0x004)
hlstmfHasLocationStr = uint32(0x008)
hlstmfHasDisplayName = uint32(0x010)
hlstmfHasGUID = uint32(0x020)
hlstmfHasCreationTime = uint32(0x040)
hlstmfHasFrameName = uint32(0x080)
hlstmfMonikerSavedAsStr = uint32(0x100)
hlstmfAbsFromGetdataRel = uint32(0x200)
)
File diff suppressed because it is too large. Load diff
+463
View File
@@ -0,0 +1,463 @@
package xls
import (
"encoding/binary"
"errors"
"log"
"math"
"unicode/utf16"
"github.com/pbnjay/grate"
"github.com/pbnjay/grate/commonxl"
)
// List (visible) sheet names from the workbook.
func (b *WorkBook) List() ([]string, error) {
res := make([]string, 0, len(b.sheets))
for _, s := range b.sheets {
if (s.HiddenState & 0x03) == 0 {
res = append(res, s.Name)
}
}
return res, nil
}
// ListHidden sheet names in the workbook.
func (b *WorkBook) ListHidden() ([]string, error) {
res := make([]string, 0, len(b.sheets))
for _, s := range b.sheets {
if (s.HiddenState & 0x03) != 0 {
res = append(res, s.Name)
}
}
return res, nil
}
// Get opens the named worksheet and return an iterator for its contents.
func (b *WorkBook) Get(sheetName string) (grate.Collection, error) {
for _, s := range b.sheets {
if s.Name == sheetName {
ss := b.pos2substream[int64(s.Position)]
return b.parseSheet(s, ss)
}
}
return nil, errors.New("xls: sheet not found")
}
func (b *WorkBook) parseSheet(s *boundSheet, ss int) (*commonxl.Sheet, error) {
res := &commonxl.Sheet{
Formatter: &b.nfmt,
}
var minRow, maxRow uint32
var minCol, maxCol uint16
// temporary string buffer
us := make([]uint16, 8224)
inSubstream := 0
for idx, r := range b.substreams[ss] {
if inSubstream > 0 {
if r.RecType == RecTypeEOF {
inSubstream--
}
continue
}
switch r.RecType {
case RecTypeBOF:
// a BOF inside a sheet usually means embedded content like a chart
// (which we aren't interested in). So we we set a flag and wait
// for the EOF for that content block.
if idx > 0 {
inSubstream++
continue
}
case RecTypeWsBool:
if (r.Data[1] & 0x10) != 0 {
// it's a dialog
return nil, nil
}
case RecTypeDimensions:
// max = 0-based index of the row AFTER the last valid index
minRow = binary.LittleEndian.Uint32(r.Data[:4])
maxRow = binary.LittleEndian.Uint32(r.Data[4:8]) // max = 0x010000
minCol = binary.LittleEndian.Uint16(r.Data[8:10])
maxCol = binary.LittleEndian.Uint16(r.Data[10:12]) // max = 0x000100
if grate.Debug {
log.Printf(" Sheet dimensions (%d, %d) - (%d,%d)",
minCol, minRow, maxCol, maxRow)
}
if minRow > 0x0000FFFF || maxRow > 0x00010000 {
log.Println("invalid dimensions")
}
if minCol > 0x00FF || maxCol > 0x0100 {
log.Println("invalid dimensions")
}
// pre-allocate cells
res.Resize(int(maxRow), int(maxCol))
}
}
inSubstream = 0
var formulaRow, formulaCol uint16
for ridx, r := range b.substreams[ss] {
if inSubstream > 0 {
if r.RecType == RecTypeEOF {
inSubstream--
} else if grate.Debug {
log.Println(" Unhandled sheet substream record type:", r.RecType, ridx)
}
continue
}
// sec 2.1.7.20.6 Common Productions ABNF:
/*
CELLTABLE = 1*(1*Row *CELL 1*DBCell) *EntExU2
CELL = FORMULA / Blank / MulBlank / RK / MulRk / BoolErr / Number / LabelSst
FORMULA = [Uncalced] Formula [Array / Table / ShrFmla / SUB] [String *Continue]
Not parsed form the list above:
DBCell, EntExU2, Uncalced, Array, Table,ShrFmla
NB: no idea what "SUB" is
*/
switch r.RecType {
case RecTypeBOF:
if ridx > 0 {
inSubstream++
continue
}
case RecTypeBoolErr:
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
if r.Data[7] == 0 {
// Boolean value
bv := false
if r.Data[6] == 1 {
bv = true
}
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
res.Put(rowIndex, colIndex, bv, fno)
//log.Printf("bool/error spec: %d %d %+v", rowIndex, colIndex, bv)
} else {
// it's an error, load the label
be, ok := berrLookup[r.Data[6]]
if !ok {
be = "<unknown error>"
}
res.Put(rowIndex, colIndex, be, 0)
//log.Printf("bool/error spec: %d %d %s", rowIndex, colIndex, be)
}
case RecTypeMulRk:
// MulRk encodes multiple RK values in a row
nrk := int((r.RecSize - 6) / 6)
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
for i := 0; i < nrk; i++ {
off := 4 + i*6
ixfe := int(binary.LittleEndian.Uint16(r.Data[off:]))
value := RKNumber(binary.LittleEndian.Uint32(r.Data[off+2:]))
var rval interface{}
if value.IsInteger() {
rval = value.Int()
} else {
rval = value.Float64()
}
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
res.Put(rowIndex, colIndex+i, rval, fno)
}
//log.Printf("mulrow spec: %+v", *mr)
case RecTypeNumber:
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
xnum := binary.LittleEndian.Uint64(r.Data[6:])
value := math.Float64frombits(xnum)
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
res.Put(rowIndex, colIndex, value, fno)
//log.Printf("Number spec: %d %d = %f", rowIndex, colIndex, value)
case RecTypeRK:
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:]))
value := RKNumber(binary.LittleEndian.Uint32(r.Data[6:]))
var rval interface{}
if value.IsInteger() {
rval = value.Int()
} else {
rval = value.Float64()
}
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
res.Put(rowIndex, colIndex, rval, fno)
//log.Printf("RK spec: %d %d = %+v", rowIndex, colIndex, rval)
case RecTypeFormula:
formulaRow = binary.LittleEndian.Uint16(r.Data[:2])
formulaCol = binary.LittleEndian.Uint16(r.Data[2:4])
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
fdata := r.Data[6:]
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
if fdata[6] == 0xFF && fdata[7] == 0xFF {
switch fdata[0] {
case 0:
// string in next record
// put placeholder now to record the numFmt
res.Put(int(formulaRow), int(formulaCol), "", fno)
case 1:
// boolean
bv := false
if fdata[2] != 0 {
bv = true
}
res.Put(int(formulaRow), int(formulaCol), bv, fno)
case 2:
// error value
be, ok := berrLookup[fdata[2]]
if !ok {
be = "<unknown error>"
}
res.Put(int(formulaRow), int(formulaCol), be, 0)
case 3:
// blank string
default:
log.Printf("unknown formula value type %d", fdata[0])
}
} else {
xnum := binary.LittleEndian.Uint64(fdata)
value := math.Float64frombits(xnum)
res.Put(int(formulaRow), int(formulaCol), value, fno)
}
//log.Printf("formula spec: %d %d ~~ %+v", formulaRow, formulaCol, r.Data)
case RecTypeString:
// String is the previously rendered value of a formula
// NB similar to the workbook SST, this can continue over
// addition records up to 32k characters. A 1-byte flag
// at each gap indicates if the encoding switches
// to/from 8/16-bit characters.
charCount := binary.LittleEndian.Uint16(r.Data[:2])
flags := r.Data[2]
fstr := ""
if (flags & 1) == 0 {
fstr = latin1String(r.Data[3:]) // descrybe patch: compressed chars are Latin-1, not UTF-8
} else {
raw := r.Data[3:]
if int(charCount) > cap(us) {
us = make([]uint16, charCount)
}
us = us[:charCount]
for i := 0; i < int(charCount); i++ {
us[i] = binary.LittleEndian.Uint16(raw)
raw = raw[2:]
}
fstr = string(utf16.Decode(us))
}
if (ridx + 1) < len(b.substreams[ss]) {
ridx2 := ridx + 1
nrecs := len(b.substreams[ss])
for ridx2 < nrecs {
r2 := b.substreams[ss][ridx2]
if r2.RecType != RecTypeContinue {
break
}
if (r2.Data[0] & 1) == 0 {
fstr += latin1String(r2.Data[1:])
} else {
raw := r2.Data[1:]
slen := len(raw) / 2
us = us[:slen]
for i := 0; i < slen; i++ {
us[i] = binary.LittleEndian.Uint16(raw)
raw = raw[2:]
}
fstr += string(utf16.Decode(us))
}
ridx2++
}
}
res.Set(int(formulaRow), int(formulaCol), fstr)
//log.Printf("String direct: %d %d '%s'", int(formulaRow), int(formulaCol), fstr)
case RecTypeLabelSst:
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
sstIndex := int(binary.LittleEndian.Uint32(r.Data[6:]))
if sstIndex > len(b.strings) {
return nil, errors.New("xls: invalid sst index")
}
var fno uint16
if ixfe < len(b.xfs) {
fno = b.xfs[ixfe]
}
if b.strings[sstIndex] != "" {
res.Put(rowIndex, colIndex, b.strings[sstIndex], fno)
}
//log.Printf("SST spec: %d %d = [%d] '%s' %d", rowIndex, colIndex, sstIndex, b.strings[sstIndex], fno)
case RecTypeHLink:
firstRow := binary.LittleEndian.Uint16(r.Data[:2])
lastRow := binary.LittleEndian.Uint16(r.Data[2:4])
firstCol := binary.LittleEndian.Uint16(r.Data[4:6])
lastCol := binary.LittleEndian.Uint16(r.Data[6:])
if int(firstCol) > int(maxCol) {
//log.Println("invalid hyperlink column")
continue
}
if int(firstRow) > int(maxRow) {
//log.Println("invalid hyperlink row")
continue
}
if lastRow == 0xFFFF { // placeholder value indicate "last"
lastRow = uint16(maxRow) - 1
}
if lastCol == 0xFF { // placeholder value indicate "last"
lastCol = uint16(maxCol) - 1
}
// decode the hyperlink datastructure and try to find the
// display text and separate the URL itself.
displayText, linkText, err := decodeHyperlinks(r.Data[8:])
if err != nil {
log.Println(err)
continue
}
// apply merge cell rules (see RecTypeMergeCells below)
for rn := int(firstRow); rn <= int(lastRow); rn++ {
for cn := int(firstCol); cn <= int(lastCol); cn++ {
if rn == int(firstRow) && cn == int(firstCol) {
// TODO: provide custom hooks for how to handle links in output
// descrybe patch: keep the URL itself (upstream wrote "text <url>").
if linkText == "" {
linkText = displayText
}
res.Put(rn, cn, linkText, 0)
} else if cn == int(firstCol) {
// first and last column MAY be the same
if rn == int(lastRow) {
res.Put(rn, cn, grate.EndRowMerged, 0)
} else {
res.Put(rn, cn, grate.ContinueRowMerged, 0)
}
} else if cn == int(lastCol) {
// first and last column are NOT the same
res.Put(rn, cn, grate.EndColumnMerged, 0)
} else {
res.Put(rn, cn, grate.ContinueColumnMerged, 0)
}
}
}
case RecTypeMergeCells:
// To keep cells aligned, Merged cells are handled by placing
// special characters in each cell covered by the merge block.
//
// The contents of the cell are always in the top left position.
// A "down arrow" (↓) indicates the left side of the merge block, and a
// "down arrow with stop line" (⤓) indicates the last row of the merge.
// A "right arrow" (→) indicates that the columns span horizontally,
// and a "right arrow with stop line" (⇥) indicates the rightmost
// column of the merge.
//
cmcs := binary.LittleEndian.Uint16(r.Data[:2])
raw := r.Data[2:]
for i := 0; i < int(cmcs); i++ {
firstRow := binary.LittleEndian.Uint16(raw[:2])
lastRow := binary.LittleEndian.Uint16(raw[2:4])
firstCol := binary.LittleEndian.Uint16(raw[4:6])
lastCol := binary.LittleEndian.Uint16(raw[6:])
raw = raw[8:]
if lastRow == 0xFFFF { // placeholder value indicate "last"
lastRow = uint16(maxRow) - 1
}
if lastCol == 0xFF { // placeholder value indicate "last"
lastCol = uint16(maxCol) - 1
}
for rn := int(firstRow); rn <= int(lastRow); rn++ {
for cn := int(firstCol); cn <= int(lastCol); cn++ {
if rn == int(firstRow) && cn == int(firstCol) {
// should be a value there already!
} else if cn == int(firstCol) {
// first and last column MAY be the same
if rn == int(lastRow) {
res.Put(rn, cn, grate.EndRowMerged, 0)
} else {
res.Put(rn, cn, grate.ContinueRowMerged, 0)
}
} else if cn == int(lastCol) {
// first and last column are NOT the same
res.Put(rn, cn, grate.EndColumnMerged, 0)
} else {
res.Put(rn, cn, grate.ContinueColumnMerged, 0)
}
}
}
}
/*
case RecTypeBlank, RecTypeMulBlank:
// cells default value is blank, no need for these
case RecTypeContinue:
// the only situation so far is when used in RecTypeString above
case RecTypeRow, RecTypeDimensions, RecTypeEOF, RecTypeWsBool:
// handled in initial pass
default:
if grate.Debug {
log.Println(" Unhandled sheet record type:", r.RecType, ridx)
}
*/
}
}
return res, nil
}
var berrLookup = map[byte]string{
0x00: "#NULL!",
0x07: "#DIV/0!",
0x0F: "#VALUE!",
0x17: "#REF!",
0x1D: "#NAME?",
0x24: "#NUM!",
0x2A: "#N/A",
0x2B: "#GETTING_DATA",
}
// latin1String decodes BIFF8 compressed (8-bit) characters. descrybe patch.
func latin1String(b []byte) string {
r := make([]rune, len(b))
for i, c := range b {
r[i] = rune(c)
}
return string(r)
}
+246
View File
@@ -0,0 +1,246 @@
package xls
import (
"encoding/binary"
"errors"
"io"
"io/ioutil"
"unicode/utf16"
)
// 2.5.240
func decodeShortXLUnicodeString(raw []byte) (string, int, error) {
// identical to decodeXLUnicodeString except for cch=8bits instead of 16
cch := int(raw[0])
flags := raw[1]
raw = raw[2:]
content := make([]uint16, cch)
if (flags & 0x1) == 0 {
// 16-bit characters but only the bottom 8bits
contentBytes := raw[:cch]
for i, x := range contentBytes {
content[i] = uint16(x)
}
cch += 2 // to return the offset
} else {
// 16-bit characters
for i := 0; i < cch; i++ {
content[i] = binary.LittleEndian.Uint16(raw[:2])
raw = raw[2:]
}
cch += cch + 2 // to return the offset
}
return string(utf16.Decode(content)), cch, nil
}
// 2.5.294
func decodeXLUnicodeString(raw []byte) (string, int, error) {
// identical to decodeShortXLUnicodeString except for cch=16bits instead of 8
cch := int(binary.LittleEndian.Uint16(raw[:2]))
flags := raw[2]
raw = raw[3:]
content := make([]uint16, cch)
if (flags & 0x1) == 0 {
// 16-bit characters but only the bottom 8bits
contentBytes := raw[:cch]
for i, x := range contentBytes {
content[i] = uint16(x)
}
cch += 3 // to return the offset
} else {
// 16-bit characters
for i := 0; i < cch; i++ {
content[i] = binary.LittleEndian.Uint16(raw[:2])
raw = raw[2:]
}
cch += cch + 3 // to return the offset
}
return string(utf16.Decode(content)), cch, nil
}
// 2.5.293
func decodeXLUnicodeRichExtendedString(r io.Reader) (string, error) {
var cch, cRun uint16
var flags uint8
var cbExtRs int32
err := binary.Read(r, binary.LittleEndian, &cch)
if err != nil {
return "", err
}
err = binary.Read(r, binary.LittleEndian, &flags)
if err != nil {
return "", err
}
if (flags & 0x8) != 0 {
// rich formating data is present
err = binary.Read(r, binary.LittleEndian, &cRun)
if err != nil {
return "", err
}
}
if (flags & 0x4) != 0 {
// phonetic string data is present
err = binary.Read(r, binary.LittleEndian, &cbExtRs)
if err != nil {
return "", err
}
}
content := make([]uint16, cch)
if (flags & 0x1) == 0 {
// 16-bit characters but only the bottom 8bits
contentBytes := make([]byte, cch)
n, err2 := io.ReadFull(r, contentBytes)
if n == 0 && err2 != io.ErrUnexpectedEOF {
err = err2
}
if uint16(n) < cch {
contentBytes = contentBytes[:n]
content = content[:n]
}
for i, x := range contentBytes {
content[i] = uint16(x)
}
} else {
// 16-bit characters
err = binary.Read(r, binary.LittleEndian, content)
}
if err != nil {
return "", err
}
//////
if cRun > 0 {
// rich formating data is present
_, err = io.CopyN(ioutil.Discard, r, int64(cRun)*4)
if err != nil {
return "", err
}
}
if cbExtRs > 0 {
// phonetic string data is present
_, err = io.CopyN(ioutil.Discard, r, int64(cbExtRs))
if err != nil {
return "", err
}
}
//////
return string(utf16.Decode(content)), nil
}
// read in an array of XLUnicodeRichExtendedString s
func parseSST(recs []*rec) ([]string, error) {
// The quirky thing about this code is that when strings cross a record
// boundary, there's an intervening flags byte that MAY change the string
// from an 8-bit encoding to 16-bit or vice versa.
//totalRefs := binary.LittleEndian.Uint32(recs[0].Data[0:4])
numStrings := binary.LittleEndian.Uint32(recs[0].Data[4:8])
all := make([]string, 0, numStrings)
current := make([]uint16, 32*1024)
buf := recs[0].Data[8:]
for i := 0; i < len(recs); {
var cRunBytes int
var flags byte
var cbExtRs uint32
for len(buf) > 0 {
slen := binary.LittleEndian.Uint16(buf)
buf = buf[2:]
flags = buf[0]
buf = buf[1:]
if (flags & 0x8) != 0 {
// rich formating data is present
cRun := binary.LittleEndian.Uint16(buf)
cRunBytes = int(cRun) * 4
buf = buf[2:]
}
if (flags & 0x4) != 0 {
// phonetic string data is present
cbExtRs = binary.LittleEndian.Uint32(buf)
buf = buf[4:]
}
///////
blx := len(buf)
bly := len(buf) - 5
if blx > 5 {
blx = 5
}
if bly < 0 {
bly = 0
}
// this block will read the string data, but transparently
// handle continuing across records
if int(slen) > cap(current) {
current = make([]uint16, slen)
} else {
current = current[:slen]
}
for j := 0; j < int(slen); j++ {
if len(buf) == 0 {
i++
if (recs[i].Data[0] & 1) == 0 {
flags &= 0xFE
} else {
flags |= 1
}
buf = recs[i].Data[1:]
}
if (flags & 1) == 0 { //8-bit
current[j] = uint16(buf[0])
buf = buf[1:]
} else { //16-bit
current[j] = uint16(binary.LittleEndian.Uint16(buf[:2]))
buf = buf[2:]
if len(buf) == 1 {
return nil, errors.New("xls: off by one")
}
}
}
s := string(utf16.Decode(current))
all = append(all, s)
///////
for cRunBytes > 0 {
if len(buf) >= int(cRunBytes) {
buf = buf[cRunBytes:]
cRunBytes = 0
} else {
cRunBytes -= len(buf)
i++
buf = recs[i].Data
}
}
for cbExtRs > 0 {
if len(buf) >= int(cbExtRs) {
buf = buf[cbExtRs:]
cbExtRs = 0
} else {
cbExtRs -= uint32(len(buf))
i++
buf = recs[i].Data
}
}
}
i++
if i < len(recs) {
buf = recs[i].Data
}
}
return all, nil
}
+107
View File
@@ -0,0 +1,107 @@
package xls
import (
"fmt"
"math"
)
type header struct {
Version uint16 // An unsigned integer that specifies the BIFF version of the file. The value MUST be 0x0600.
DocType uint16 //An unsigned integer that specifies the document type of the substream of records following this record. For more information about the layout of the sub-streams in the workbook stream see File Structure.
RupBuild uint16 // An unsigned integer that specifies the build identifier.
RupYear uint16 // An unsigned integer that specifies the year when this BIFF version was first created. The value MUST be 0x07CC or 0x07CD.
MiscBits uint64 // lots of miscellaneous bits and flags we're not going to check
}
// 2.1.4
type rec struct {
RecType recordType //
RecSize uint16 // must be between 0 and 8224
Data []byte // len(rec.data) = rec.recsize
}
type boundSheet struct {
Position uint32 // A FilePointer as specified in [MS-OSHARED] section 2.2.1.5 that specifies the stream position of the start of the BOF record for the sheet.
HiddenState byte // (2 bits) An unsigned integer that specifies the hidden state of the sheet. MUST be a value from the following table:
SheetType byte // An unsigned integer that specifies the sheet type. 00=worksheet
Name string
}
///////
type shRow struct {
RowIndex uint16 // 0-based
FirstCol uint16 // 0-based
LastCol uint16 // 1-based!
Height uint16
Reserved uint32
Flags uint32
}
type shRef8 struct {
FirstRow uint16 // 0-based
LastRow uint16 // 0-based
FirstCol uint16 // 0-based
LastCol uint16 // 0-based
}
type shMulRK struct {
RowIndex uint16 // 0-based
FirstCol uint16 // 0-based
Values []RkRec
LastCol uint16 // 0-based?
}
type RkRec struct {
IXFCell uint16
Value RKNumber
}
type shRK struct {
RowIndex uint16 // 0-based
Col uint16 // 0-based
IXFCell uint16
Value RKNumber
}
type RKNumber uint32
func (r RKNumber) IsInteger() bool {
if (r & 1) != 0 {
// has 2 decimals
return false
}
if (r & 2) == 0 {
// is part of a float
return false
}
return true
}
func (r RKNumber) Int() int {
val := int32(r) >> 2
if (r&1) == 0 && (r&2) != 0 {
return int(val)
}
if (r&1) != 0 && (r&2) != 0 {
return int(val / 100)
}
return 0
}
func (r RKNumber) Float64() float64 {
val := int32(r) >> 2
v2 := math.Float64frombits(uint64(val) << 34)
if (r&1) == 0 && (r&2) == 0 {
return v2
}
if (r&1) != 0 && (r&2) == 0 {
return v2 / 100.0
}
return 0.0
}
func (r RKNumber) String() string {
if r.IsInteger() {
return fmt.Sprint(r.Int())
}
return fmt.Sprint(r.Float64())
}
+360
View File
@@ -0,0 +1,360 @@
// Package xls implements the Microsoft Excel Binary File Format (.xls) Structure.
// More specifically, it contains just enough detail to extract cell contents,
// data types, and last-calculated formula values. In particular, it does NOT
// implement formatting or formula calculations.
package xls
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06
import (
"context"
"encoding/binary"
"errors"
"io"
"log"
"sync"
"github.com/pbnjay/grate"
"github.com/pbnjay/grate/commonxl"
"github.com/pbnjay/grate/xls/cfb"
"github.com/pbnjay/grate/xls/crypto"
)
var _ = grate.Register("xls", 1, Open)
// WorkBook represents an Excel workbook containing 1 or more sheets.
type WorkBook struct {
filename string
ctx context.Context
doc *cfb.Document
prot bool
h *header
sheets []*boundSheet
codepage uint16
dateMode uint16
strings []string
password string
substreams [][]*rec
fpos int64
pos2substream map[int64]int
nfmt commonxl.Formatter
xfs []uint16
}
func (b *WorkBook) IsProtected() bool {
return b.prot
}
func Open(filename string) (grate.Source, error) {
doc, err := cfb.Open(filename)
if err != nil {
return nil, err
}
b := &WorkBook{
filename: filename,
doc: doc,
pos2substream: make(map[int64]int, 16),
xfs: make([]uint16, 0, 128),
}
rdr, err := doc.Open("Workbook")
if err != nil {
return nil, grate.WrapErr(err, grate.ErrNotInFormat)
}
raw, err := io.ReadAll(rdr)
if err != nil {
return nil, err
}
err = b.loadFromStream(raw)
return b, err
}
func (b *WorkBook) loadFromStream(raw []byte) error {
return b.loadFromStream2(raw, false)
}
func (b *WorkBook) loadFromStreamWithDecryptor(raw []byte, dec crypto.Decryptor) error {
// interestingly (insecurely) BIFF8 keeps Record Types and sizes in the clear,
// has a few records that are not encrypted, and has 1 record type that does
// not encrypt the 32bit integer position at the beginning (while encrypting
// the rest). It also resets the encryption block counter every 1024 bytes
// (counting all the "skipped" bytes described above).
//
// So this code streams the records through the decryption, but also records
// a set of overlays applied to the final result which restore the
// "cleartext" contents in line with the decrypted content.
if grate.Debug {
log.Println(" Decrypting xls stream with standard RC4")
}
pos := 0
zeros := [8224]byte{}
type overlay struct {
Pos int
RecType recordType
DataBytes uint16
Data []byte // NB len() not necessarily = DataBytes
}
replaceBlocks := []overlay{}
var err error
for err == nil && len(raw[pos:]) > 4 {
o := overlay{}
o.Pos = pos
o.RecType = recordType(binary.LittleEndian.Uint16(raw[pos : pos+2]))
o.DataBytes = binary.LittleEndian.Uint16(raw[pos+2 : pos+4])
pos += 4
// copy to output and decryption stream
binary.Write(dec, binary.LittleEndian, o.RecType)
binary.Write(dec, binary.LittleEndian, o.DataBytes)
tocopy := int(o.DataBytes)
switch o.RecType {
case RecTypeBOF, RecTypeFilePass, RecTypeUsrExcl, RecTypeFileLock, RecTypeInterfaceHdr, RecTypeRRDInfo, RecTypeRRDHead:
// untouched data goes directly into output
o.Data = raw[pos : pos+int(o.DataBytes)]
pos += int(o.DataBytes)
dec.Write(zeros[:int(o.DataBytes)])
tocopy = 0
case RecTypeBoundSheet8:
// copy 32-bit position to output
o.Data = raw[pos : pos+4]
pos += 4
dec.Write(zeros[:4])
tocopy -= 4
}
if tocopy > 0 {
_, err = dec.Write(raw[pos : pos+tocopy])
pos += tocopy
}
replaceBlocks = append(replaceBlocks, o)
}
dec.Flush()
alldata := dec.Bytes()
for _, o := range replaceBlocks {
offs := int(o.Pos)
binary.LittleEndian.PutUint16(alldata[offs:], uint16(o.RecType))
binary.LittleEndian.PutUint16(alldata[offs+2:], uint16(o.DataBytes))
if len(o.Data) > 0 {
offs += 4
copy(alldata[offs:], o.Data)
}
}
// recurse into the stream parser now that things are decrypted
return b.loadFromStream2(alldata, true)
}
func (b *WorkBook) Close() error {
// return records to the pool for reuse
for i, sub := range b.substreams {
for _, r := range sub {
r.Data = nil // allow GC
recPool.Put(r)
}
b.substreams[i] = b.substreams[i][:0]
}
b.substreams = b.substreams[:0]
return nil
}
func (b *WorkBook) loadFromStream2(raw []byte, isDecrypted bool) error {
b.h = &header{}
substr := -1
nestedBOF := 0
b.pos2substream = make(map[int64]int, 10)
b.fpos = 0
// IMPORTANT: if there are any existing records, we need to return them to the pool
for i, sub := range b.substreams {
for _, r := range sub {
recPool.Put(r)
}
b.substreams[i] = b.substreams[i][:0]
}
b.substreams = b.substreams[:0]
rawfull := raw
nr, no, err := b.nextRecord(raw)
for err == nil {
raw = raw[no:]
switch nr.RecType {
case RecTypeEOF:
nestedBOF--
case RecTypeBOF:
// when substreams are nested, keep them in the same grouping
if nestedBOF == 0 {
substr = len(b.substreams)
b.substreams = append(b.substreams, []*rec{})
b.pos2substream[b.fpos] = substr
}
nestedBOF++
}
b.fpos += int64(4 + len(nr.Data))
// if there's a FilePass record, the data is encrypted
if nr.RecType == RecTypeFilePass && !isDecrypted {
etype := binary.LittleEndian.Uint16(nr.Data)
switch etype {
case 1:
dec, err := crypto.NewBasicRC4(nr.Data[2:])
if err != nil {
log.Println("xls: rc4 encryption failed to set up", err)
return err
}
return b.loadFromStreamWithDecryptor(rawfull, dec)
case 2, 3, 4:
log.Println("need Crypto API RC4 decryptor")
return errors.New("xls: unsupported Crypto API encryption method")
default:
return errors.New("xls: unsupported encryption method")
}
}
b.substreams[substr] = append(b.substreams[substr], nr)
nr, no, err = b.nextRecord(raw)
}
if err == io.EOF {
err = nil
}
if err != nil {
return err
}
for ss, records := range b.substreams {
if grate.Debug {
log.Printf(" Processing substream %d/%d (%d records)", ss, len(b.substreams), len(records))
}
for i, nr := range records {
if len(nr.Data) == 0 {
continue
}
switch nr.RecType {
case RecTypeSST:
// Shared String Table is often continued across multiple records,
// so we want to gather them all before starting to parse (some
// strings may span the gap between records)
recSet := []*rec{nr}
lastIndex := i
for len(records) > (lastIndex+1) && records[lastIndex+1].RecType == RecTypeContinue {
lastIndex++
recSet = append(recSet, records[lastIndex])
}
b.strings, err = parseSST(recSet)
if err != nil {
return err
}
case RecTypeContinue:
// no-op (used above)
case RecTypeEOF:
// done
case RecTypeBOF:
b.h = &header{
Version: binary.LittleEndian.Uint16(nr.Data[0:2]),
DocType: binary.LittleEndian.Uint16(nr.Data[2:4]),
RupBuild: binary.LittleEndian.Uint16(nr.Data[4:6]),
RupYear: binary.LittleEndian.Uint16(nr.Data[6:8]),
MiscBits: binary.LittleEndian.Uint64(nr.Data[8:16]),
}
if b.h.Version != 0x0600 {
return errors.New("xls: invalid file version")
}
if b.h.RupYear != 0x07CC && b.h.RupYear != 0x07CD {
return errors.New("xls: unsupported biff version")
}
/*
if b.h.DocType != 0x0005 && b.h.DocType != 0x0010 {
// we only support the workbook or worksheet substreams
log.Println("xls: unsupported document type")
//break
}
*/
case RecTypeCodePage:
// BIFF8 is entirely UTF-16LE so this is actually ignored
b.codepage = binary.LittleEndian.Uint16(nr.Data)
case RecTypeDate1904:
b.dateMode = binary.LittleEndian.Uint16(nr.Data)
case RecTypeFormat:
// Format maps a format ID to a code string
fmtNo := binary.LittleEndian.Uint16(nr.Data)
formatStr, _, err := decodeXLUnicodeString(nr.Data[2:])
if err != nil {
log.Println("fail2", err)
return err
}
b.nfmt.Add(fmtNo, formatStr)
case RecTypeXF:
// XF records merge multiple style and format directives to one ID
// ignore font id at nr.Data[0:2]
fmtNo := binary.LittleEndian.Uint16(nr.Data[2:])
b.xfs = append(b.xfs, fmtNo)
case RecTypeBoundSheet8:
// Identifies the postition within the stream, visibility state,
// and name of a worksheet
bs := &boundSheet{}
bs.Position = binary.LittleEndian.Uint32(nr.Data[:4])
bs.HiddenState = nr.Data[4]
bs.SheetType = nr.Data[5]
bs.Name, _, err = decodeShortXLUnicodeString(nr.Data[6:])
if err != nil {
return err
}
b.sheets = append(b.sheets, bs)
default:
if grate.Debug && ss == 0 {
log.Println(" Unhandled record type:", nr.RecType, i)
}
}
}
}
return err
}
var recPool = sync.Pool{
New: func() interface{} {
return &rec{}
},
}
func (b *WorkBook) nextRecord(raw []byte) (*rec, int, error) {
if len(raw) < 4 {
return nil, 0, io.EOF
}
rec := recPool.Get().(*rec)
rec.RecType = recordType(binary.LittleEndian.Uint16(raw[:2]))
rec.RecSize = binary.LittleEndian.Uint16(raw[2:4])
if len(raw[4:]) < int(rec.RecSize) {
recPool.Put(rec)
return nil, 4, io.ErrUnexpectedEOF
}
rec.Data = raw[4 : 4+rec.RecSize]
return rec, int(4 + rec.RecSize), nil
}
+2 -2
View File
@@ -1962,7 +1962,7 @@ export const en: MessageDict = {
"feeds.field.type": "Type",
"feeds.field.file": "CSV file",
"feeds.fileHint":
"Max 5 MiB. After creating the feed, map columns and then sync, just as with URL feeds.",
"CSV, XML, JSON or Excel (.xls, .xlsx, .xlsm; zip several workbooks to import them as one feed). Max 32 MiB. After creating the feed, map columns and then sync, just as with URL feeds.",
"feeds.field.interval": "Auto-sync interval (minutes)",
"feeds.field.intervalHint":
"How often Descrybe should pull this feed automatically while it is active. Use Sync on the feed list for a one-off pull; that does not change this schedule.",
@@ -2684,7 +2684,7 @@ export const en: MessageDict = {
"flash.campaign.scheduleFailed": "Schedule failed",
"flash.campaign.saveFailed": "Save failed",
"flash.feed.copyFailed": "Could not copy URL",
"flash.feed.csvRequired": "Please choose a .csv file.",
"flash.feed.csvRequired": "Please choose a CSV, XML, JSON or Excel file.",
"flash.feed.csvFileRequired": "Please choose a CSV file.",
"flash.feed.urlRequired": "Feed URL is required.",
"flash.feed.updated": "Feed updated.",
@@ -94,6 +94,9 @@
"description",
"processed_name",
"processed_description",
"short_description",
"meta_title",
"meta_description",
"status",
"feed_id",
"gtin",
+15 -5
View File
@@ -527,10 +527,18 @@ function openAdd(source: "url" | "file" = "url") {
}
}
function fileFeedType(name: string): "csv" | "xml" | "json" | "excel" {
const lower = name.toLowerCase();
if (lower.endsWith(".json")) return "json";
if (lower.endsWith(".xml")) return "xml";
if (/\.(xlsx?|xlsm|zip)$/.test(lower)) return "excel";
return "csv";
}
function onCsvSelected(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0] ?? null;
if (file && !/\.(csv|json|xml)$/i.test(file.name)) {
if (file && !/\.(csv|json|xml|xlsx?|xlsm|zip)$/i.test(file.name)) {
formFile = null;
input.value = "";
error = i18n.t("flash.feed.csvRequired");
@@ -570,7 +578,7 @@ function openAdd(source: "url" | "file" = "url") {
}
const body = new FormData();
body.append("name", formName.trim());
body.append("feed_type", formFile?.name.toLowerCase().endsWith(".json") ? "json" : formFile?.name.toLowerCase().endsWith(".xml") ? "xml" : "csv");
body.append("feed_type", fileFeedType(formFile.name));
body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval)));
body.append("content_language", formLanguage);
body.append("file", formFile);
@@ -599,7 +607,7 @@ function openAdd(source: "url" | "file" = "url") {
showAdd = false;
const createdId = created?.id != null ? String(created.id) : "";
trackEvent("feed_created", {
feed_type: formSource === "file" ? "csv" : formType
feed_type: formSource === "file" && formFile ? fileFeedType(formFile.name) : formType
});
success = createdId ? i18n.t("feeds.createdMapHint") : i18n.t("feeds.createdPlain");
notifySuccess(i18n.t("toast.feed.created"), {
@@ -1282,10 +1290,11 @@ function openAdd(source: "url" | "file" = "url") {
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
<option value="excel">Excel</option>
</Select>
</div>
{#if formType === "json"}<p class="text-xs text-muted-foreground">JSON arrays and nested products/results/items are supported. Map a record path if needed.</p>{:else}
<FeedFormatHelp format={formType === "csv" ? "csv" : "xml"} />{/if}
<FeedFormatHelp format={formType === "csv" || formType === "excel" ? "csv" : "xml"} />{/if}
<div class="space-y-2 rounded-md border p-3">
<p class="text-sm font-medium">Optional HTTP authentication</p>
<Select bind:value={formAuthType}><option value="bearer">Bearer token</option><option value="header">API key / custom header</option></Select>
@@ -1303,7 +1312,7 @@ function openAdd(source: "url" | "file" = "url") {
id="add-feed-file"
bind:this={formFileInput}
type="file"
accept=".csv,.xml,.json,text/csv,application/xml,application/json"
accept=".csv,.xml,.json,.xls,.xlsx,.xlsm,.zip,text/csv,application/xml,application/json,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.sheet.macroEnabled.12,application/zip"
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-sm file:font-medium"
onchange={onCsvSelected}
required={formSource === "file"}
@@ -1405,6 +1414,7 @@ function openAdd(source: "url" | "file" = "url") {
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
<option value="excel">Excel</option>
</Select>
{#if editing && isFileFeed(editing)}
<p class="text-xs text-muted-foreground">{i18n.t("feeds.csvTypeLocked")}</p>
@@ -167,6 +167,7 @@
const isCsv = $derived(
schemaFormat === "csv" ||
schemaFormat === "excel" ||
String(feed?.feed_type ?? "").toLowerCase() === "csv" ||
String(feed?.feed_type ?? "").toLowerCase() === "excel"
);