package catalog import ( "bytes" "encoding/csv" "encoding/json" "fmt" "io" "sort" "strings" ) // JSONImportAsCSV maps JSON arrays (including wrapped nested arrays) onto the // same validated batch import pipeline as CSV. Data must fit the catalog upload // limit. All rows are processed by the normal company-scoped upsert routines. func JSONImportAsCSV(r io.Reader, kind string) (io.Reader, error) { source, err := io.ReadAll(io.LimitReader(r, (6<<20)+1)) if err != nil { return nil, err } if len(source) > 6<<20 { return nil, ClientMsg("JSON catalog import exceeds 6 MiB") } var doc any dec := json.NewDecoder(bytes.NewReader(source)) dec.UseNumber() if err := dec.Decode(&doc); err != nil { return nil, ClientMsg("invalid JSON import: " + err.Error()) } items := findImportJSONArray(doc, kind, 0) if len(items) == 0 { return nil, ClientMsg("JSON must contain an array of " + kind) } header := []string{} switch kind { case "categories": header = []string{"name", "unique_id", "parent_unique_id", "description"} case "attributes": header = []string{"attribute_key", "name", "value_type", "unit", "example", "parent_key", "category_id"} case "products": header = []string{"gtin", "product_id", "name", "category", "description", "status"} default: return nil, ClientMsg("invalid catalog import kind") } // Keep original JSON keys too; importer uses known column names (GTIN/EAN, etc). keys := map[string]struct{}{} for _, k := range header { keys[k] = struct{}{} } for _, v := range items { if m, ok := v.(map[string]any); ok { for k := range m { keys[k] = struct{}{} } } } extras := make([]string, 0, len(keys)) for k := range keys { found := false for _, h := range header { if k == h { found = true break } } if !found { extras = append(extras, k) } } sort.Strings(extras) header = append(header, extras...) var buf bytes.Buffer cw := csv.NewWriter(&buf) if err := cw.Write(header); err != nil { return nil, err } for _, v := range items { m, ok := v.(map[string]any) if !ok { continue } rec := make([]string, len(header)) for j, k := range header { val, exists := m[k] if !exists && (k == "gtin" || k == "product_id" || k == "name" || k == "unique_id" || k == "attribute_key") { aliases := map[string][]string{"gtin": {"ean", "barcode", "gtin"}, "product_id": {"sku", "productno", "productno2", "id"}, "name": {"title", "product", "product_name", "productname"}, "unique_id": {"id", "category_id", "uniqueId"}, "attribute_key": {"key", "attributeKey", "id"}} for _, alias := range aliases[k] { for source, value := range m { if strings.EqualFold(source, alias) && value != nil { val = value exists = true break } } if exists { break } } } if !exists { for source, value := range m { if strings.EqualFold(source, k) { val = value break } } } if val == nil { continue } switch x := val.(type) { case string: rec[j] = x case json.Number: rec[j] = string(x) case bool: rec[j] = fmt.Sprint(x) default: b, _ := json.Marshal(x) rec[j] = string(b) } } if err := cw.Write(rec); err != nil { return nil, err } } cw.Flush() if err := cw.Error(); err != nil { return nil, err } return bytes.NewReader(buf.Bytes()), nil } func findImportJSONArray(doc any, kind string, depth int) []any { if depth > 6 { return nil } if items, ok := doc.([]any); ok { if len(items) > 0 { if _, ok := items[0].(map[string]any); ok { return items } } return nil } m, ok := doc.(map[string]any) if !ok { return nil } keys := []string{kind, "items", "results", "data", "records", "rows"} if kind == "products" { keys = append([]string{"SHOPITEM", "products", "product"}, keys...) } if kind == "categories" { keys = append([]string{"categories", "category"}, keys...) } if kind == "attributes" { keys = append([]string{"attributes", "specifications"}, keys...) } for _, k := range keys { for actual, value := range m { if strings.EqualFold(actual, k) { if a := findImportJSONArray(value, kind, depth+1); len(a) > 0 { return a } } } } if len(m) == 1 { for _, v := range m { return findImportJSONArray(v, kind, depth+1) } } return nil }