fix(admin): bypos 导入同时支持 JSON 数组和 JSONL (#47)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 01:00:55 +00:00
co-authored by Devin AI
parent 003543d6e2
commit 2e88efd604
2 changed files with 116 additions and 4 deletions
@@ -114,6 +114,17 @@ func adminAPIKeyJSON(t *testing.T, h *Handler, path string, body any, key string
return rec 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 { func adminLogin(t *testing.T, h *Handler, username, password string) string {
t.Helper() t.Helper()
rec := adminJSON(t, h, http.MethodPost, "/ping/api/login", map[string]string{ 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 { func mustJSON(t *testing.T, value any) []byte {
t.Helper() t.Helper()
data, err := json.Marshal(value) data, err := json.Marshal(value)
+53 -4
View File
@@ -1,7 +1,10 @@
package adminhandler package adminhandler
import ( import (
"bufio"
"encoding/json" "encoding/json"
"errors"
"io"
"net/http" "net/http"
"github.com/baicai2026-baicai/goods/api/internal/adminstore" "github.com/baicai2026-baicai/goods/api/internal/adminstore"
@@ -9,13 +12,41 @@ import (
func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) { func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) {
var records []adminstore.ByposRecord var records []adminstore.ByposRecord
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 50<<20)) reader := bufio.NewReader(http.MaxBytesReader(w, r.Body, 50<<20))
if err := dec.Decode(&records); err != nil { first, err := firstNonWhitespace(reader)
writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组") if errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录")
return 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 { if len(records) == 0 {
writeError(w, http.StatusBadRequest, "empty", "\u6ca1\u6709\u53ef\u5bfc\u5165\u7684\u8bb0\u5f55") writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录")
return return
} }
result, err := h.store.ImportByposRecords(r.Context(), records) 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) 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
}
}
}