diff --git a/api/internal/adminhandler/handler_db_test.go b/api/internal/adminhandler/handler_db_test.go index fb7525c..6ccf085 100644 --- a/api/internal/adminhandler/handler_db_test.go +++ b/api/internal/adminhandler/handler_db_test.go @@ -114,6 +114,17 @@ func adminAPIKeyJSON(t *testing.T, h *Handler, path string, body any, key string return rec } +func adminRawJSON(t *testing.T, h *Handler, path, body, token string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+token) + req.RemoteAddr = "127.0.0.1:12345" + rec := httptest.NewRecorder() + h.Router().ServeHTTP(rec, req) + return rec +} + func adminLogin(t *testing.T, h *Handler, username, password string) string { t.Helper() rec := adminJSON(t, h, http.MethodPost, "/ping/api/login", map[string]string{ @@ -341,6 +352,58 @@ func TestAdminByposImport(t *testing.T) { } } +func TestAdminByposImportJSONLAndMalformed(t *testing.T) { + h, pool, prefix, username, password := newTestAdminHandler(t) + token := adminLogin(t, h, username, password) + records := []adminstore.ByposRecord{ + { + Barcode: "6901234567885", + Name: prefix + "jsonl", + Status: "hit", + }, + { + Barcode: "invalid", + Name: prefix + "jsonl-invalid", + Status: "invalid", + }, + } + var lines strings.Builder + for _, record := range records { + lines.Write(mustJSON(t, record)) + lines.WriteByte('\n') + } + rec := adminRawJSON(t, h, "/ping/api/import/bypos", lines.String(), token) + if rec.Code != http.StatusOK { + t.Fatalf("JSONL bypos status = %d, body = %s", rec.Code, rec.Body.String()) + } + var result adminstore.ImportByposResult + if err := json.NewDecoder(rec.Body).Decode(&result); err != nil { + t.Fatalf("decode JSONL bypos response: %v", err) + } + if result.Loaded != 1 || result.Skipped != 1 || result.Errored != 0 { + t.Fatalf("JSONL bypos result = %+v", result) + } + + malformed := fmt.Sprintf( + "{\"barcode\":\"6901234567885\",\"name\":%q,\"status\":\"hit\"}\n{\"barcode\":", + prefix+"malformed", + ) + rec = adminRawJSON(t, h, "/ping/api/import/bypos", malformed, token) + if rec.Code != http.StatusBadRequest || + !strings.Contains(rec.Body.String(), `"code":"bad_request"`) || + !strings.Contains(rec.Body.String(), "请求体应为 JSON 数组或 JSONL") { + t.Fatalf("malformed JSONL response = %d, body = %s", rec.Code, rec.Body.String()) + } + var inserted int + if err := pool.QueryRow(context.Background(), + "SELECT count(*) FROM product WHERE name=$1", prefix+"malformed").Scan(&inserted); err != nil { + t.Fatalf("query malformed import product: %v", err) + } + if inserted != 0 { + t.Fatalf("malformed import inserted %d products, want 0", inserted) + } +} + func mustJSON(t *testing.T, value any) []byte { t.Helper() data, err := json.Marshal(value) diff --git a/api/internal/adminhandler/import_bypos.go b/api/internal/adminhandler/import_bypos.go index a3802b5..1b70464 100644 --- a/api/internal/adminhandler/import_bypos.go +++ b/api/internal/adminhandler/import_bypos.go @@ -1,7 +1,10 @@ package adminhandler import ( + "bufio" "encoding/json" + "errors" + "io" "net/http" "github.com/baicai2026-baicai/goods/api/internal/adminstore" @@ -9,13 +12,41 @@ import ( func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) { var records []adminstore.ByposRecord - dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 50<<20)) - if err := dec.Decode(&records); err != nil { - writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组") + reader := bufio.NewReader(http.MaxBytesReader(w, r.Body, 50<<20)) + first, err := firstNonWhitespace(reader) + if errors.Is(err, io.EOF) { + writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录") return } + if err != nil { + writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL") + return + } + dec := json.NewDecoder(reader) + if first == '[' { + if err := dec.Decode(&records); err != nil { + writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL") + return + } + var trailing any + if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) { + writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL") + return + } + } else { + for { + var record adminstore.ByposRecord + if err := dec.Decode(&record); errors.Is(err, io.EOF) { + break + } else if err != nil { + writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL") + return + } + records = append(records, record) + } + } if len(records) == 0 { - writeError(w, http.StatusBadRequest, "empty", "\u6ca1\u6709\u53ef\u5bfc\u5165\u7684\u8bb0\u5f55") + writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录") return } result, err := h.store.ImportByposRecords(r.Context(), records) @@ -25,3 +56,21 @@ func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) { } writeJSON(w, http.StatusOK, result) } + +func firstNonWhitespace(reader *bufio.Reader) (byte, error) { + for { + b, err := reader.ReadByte() + if err != nil { + return 0, err + } + switch b { + case ' ', '\t', '\r', '\n': + continue + default: + if err := reader.UnreadByte(); err != nil { + return 0, err + } + return b, nil + } + } +}