Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a29423451 | ||
|
|
36f9c95fa7 | ||
|
|
9ee83e3535 | ||
|
|
53ade9eeea | ||
|
|
313bc84cb0 | ||
|
|
8c8df2b8a2 | ||
|
|
f04891d0b9 | ||
|
|
3a5575f51b |
@@ -10,3 +10,4 @@ MINIO_ROOT_PASSWORD=change-me
|
|||||||
GOODS_ADMIN_USER=admin
|
GOODS_ADMIN_USER=admin
|
||||||
GOODS_ADMIN_PASSWORD=change-me
|
GOODS_ADMIN_PASSWORD=change-me
|
||||||
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
|
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
|
||||||
|
GOODS_BACKFLOW_RATE_PER_HOUR=30
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
@@ -32,6 +33,10 @@ func main() {
|
|||||||
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
|
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
|
||||||
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
|
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
|
||||||
username := getenv("GOODS_ADMIN_USER", "admin")
|
username := getenv("GOODS_ADMIN_USER", "admin")
|
||||||
|
backflowRate, err := strconv.Atoi(getenv("GOODS_BACKFLOW_RATE_PER_HOUR", "30"))
|
||||||
|
if err != nil || backflowRate < 1 {
|
||||||
|
log.Fatalf("invalid GOODS_BACKFLOW_RATE_PER_HOUR: must be a positive integer")
|
||||||
|
}
|
||||||
|
|
||||||
// Password: prefer a bcrypt hash; otherwise hash a plaintext password.
|
// Password: prefer a bcrypt hash; otherwise hash a plaintext password.
|
||||||
var passwordHash []byte
|
var passwordHash []byte
|
||||||
@@ -72,7 +77,8 @@ func main() {
|
|||||||
authn := auth.New(username, passwordHash, secret, 12*time.Hour)
|
authn := auth.New(username, passwordHash, secret, 12*time.Hour)
|
||||||
usage := ratelimit.New(getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0"))
|
usage := ratelimit.New(getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0"))
|
||||||
h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()).
|
h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()).
|
||||||
WithUsage(usage)
|
WithUsage(usage).
|
||||||
|
WithBackflowRate(backflowRate)
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ type apiKeyView struct {
|
|||||||
// ListAPIKeys returns all issued keys with usage stats merged in.
|
// ListAPIKeys returns all issued keys with usage stats merged in.
|
||||||
func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||||
keys, err := h.store.ListAPIKeys(r.Context())
|
keys, err := h.store.ListAPIKeys(r.Context())
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
views := make([]apiKeyView, 0, len(keys))
|
views := make([]apiKeyView, 0, len(keys))
|
||||||
@@ -51,7 +51,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context()))
|
plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, map[string]any{
|
writeJSON(w, http.StatusCreated, map[string]any{
|
||||||
@@ -63,7 +63,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// RevokeAPIKey disables a key. Subsequent requests with it are rejected.
|
// RevokeAPIKey disables a key. Subsequent requests with it are rejected.
|
||||||
func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, err) {
|
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package adminhandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
|
||||||
|
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeUsageLimiter struct {
|
||||||
|
result ratelimit.Result
|
||||||
|
key string
|
||||||
|
limit int
|
||||||
|
window time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeUsageLimiter) Allow(_ context.Context, key string, limit int, window time.Duration) ratelimit.Result {
|
||||||
|
f.key = key
|
||||||
|
f.limit = limit
|
||||||
|
f.window = window
|
||||||
|
return f.result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*fakeUsageLimiter) Usage(context.Context, string) ratelimit.UsageStat {
|
||||||
|
return ratelimit.UsageStat{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackflowRateLimitReturnsRetryAfter(t *testing.T) {
|
||||||
|
usage := &fakeUsageLimiter{
|
||||||
|
result: ratelimit.Result{
|
||||||
|
Allowed: false,
|
||||||
|
ResetUnix: time.Now().Add(2 * time.Minute).Unix(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
h := New(nil, nil, "/ping", nil)
|
||||||
|
h.usage = usage
|
||||||
|
h.WithBackflowRate(7)
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/public/backflow", nil)
|
||||||
|
if h.allowBackflow(recorder, req, "key-id") {
|
||||||
|
t.Fatal("allowBackflow returned true for a denied request")
|
||||||
|
}
|
||||||
|
if recorder.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
|
||||||
|
}
|
||||||
|
retryAfter, err := strconv.Atoi(recorder.Header().Get("Retry-After"))
|
||||||
|
if err != nil || retryAfter <= 0 {
|
||||||
|
t.Fatalf("Retry-After = %q, want positive integer", recorder.Header().Get("Retry-After"))
|
||||||
|
}
|
||||||
|
if usage.key != "backflow:key-id" || usage.limit != 7 || usage.window != time.Hour {
|
||||||
|
t.Fatalf("Allow called with key=%q limit=%d window=%v", usage.key, usage.limit, usage.window)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInternalErrorDoesNotExposeDetailsAndLogsRequestID(t *testing.T) {
|
||||||
|
var logs bytes.Buffer
|
||||||
|
previousOutput := log.Writer()
|
||||||
|
log.SetOutput(&logs)
|
||||||
|
t.Cleanup(func() { log.SetOutput(previousOutput) })
|
||||||
|
|
||||||
|
h := New(nil, nil, "/ping", nil)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/ping/api/products", nil)
|
||||||
|
req.Header.Set(middleware.RequestIDHeader, "request-123")
|
||||||
|
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h.handleErr(w, r, errors.New("sensitive database detail"))
|
||||||
|
}))
|
||||||
|
handler.ServeHTTP(recorder, req)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusInternalServerError {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
if strings.Contains(recorder.Body.String(), "sensitive database detail") {
|
||||||
|
t.Fatalf("response exposed internal error: %s", recorder.Body.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(recorder.Body.String(), "服务器内部错误") || !strings.Contains(recorder.Body.String(), "internal_error") {
|
||||||
|
t.Fatalf("response missing generic internal error: %s", recorder.Body.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(logs.String(), "sensitive database detail") || !strings.Contains(logs.String(), "request-123") {
|
||||||
|
t.Fatalf("log missing error or request ID: %s", logs.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,10 +3,13 @@
|
|||||||
package adminhandler
|
package adminhandler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -27,7 +30,13 @@ type Handler struct {
|
|||||||
basePath string
|
basePath string
|
||||||
spa fs.FS
|
spa fs.FS
|
||||||
submitLimit *rateLimiter
|
submitLimit *rateLimiter
|
||||||
usage *ratelimit.Limiter
|
usage usageLimiter
|
||||||
|
backflowRate int
|
||||||
|
}
|
||||||
|
|
||||||
|
type usageLimiter interface {
|
||||||
|
Allow(context.Context, string, int, time.Duration) ratelimit.Result
|
||||||
|
Usage(context.Context, string) ratelimit.UsageStat
|
||||||
}
|
}
|
||||||
|
|
||||||
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
|
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
|
||||||
@@ -39,6 +48,7 @@ func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, sp
|
|||||||
basePath: basePath,
|
basePath: basePath,
|
||||||
spa: spa,
|
spa: spa,
|
||||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||||
|
backflowRate: 30,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,6 +59,12 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithBackflowRate configures the per-key hourly backflow request limit.
|
||||||
|
func (h *Handler) WithBackflowRate(n int) *Handler {
|
||||||
|
h.backflowRate = n
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
// Router builds the HTTP handler.
|
// Router builds the HTTP handler.
|
||||||
func (h *Handler) Router() http.Handler {
|
func (h *Handler) Router() http.Handler {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
@@ -176,7 +192,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
|||||||
order := r.URL.Query().Get("order")
|
order := r.URL.Query().Get("order")
|
||||||
page, size := pageParams(r)
|
page, size := pageParams(r)
|
||||||
items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size)
|
items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
@@ -188,7 +204,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
|||||||
// GetProduct returns full editable detail.
|
// GetProduct returns full editable detail.
|
||||||
func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) {
|
||||||
d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id"))
|
d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id"))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, d)
|
writeJSON(w, http.StatusOK, d)
|
||||||
@@ -211,7 +227,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用")
|
writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, d)
|
writeJSON(w, http.StatusCreated, d)
|
||||||
@@ -220,7 +236,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Stats returns the dashboard overview counters.
|
// Stats returns the dashboard overview counters.
|
||||||
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
||||||
st, err := h.store.Stats(r.Context())
|
st, err := h.store.Stats(r.Context())
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, st)
|
writeJSON(w, http.StatusOK, st)
|
||||||
@@ -230,7 +246,7 @@ func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
|||||||
func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) {
|
||||||
page, size := pageParams(r)
|
page, size := pageParams(r)
|
||||||
items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size)
|
items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
@@ -281,7 +297,7 @@ func (h *Handler) BulkProducts(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品")
|
writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected})
|
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected})
|
||||||
@@ -299,7 +315,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, d)
|
writeJSON(w, http.StatusOK, d)
|
||||||
@@ -308,7 +324,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
|||||||
// ListAudit returns audit history for a product.
|
// ListAudit returns audit history for a product.
|
||||||
func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) {
|
||||||
items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100)
|
items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||||
@@ -325,7 +341,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind)
|
im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, im)
|
writeJSON(w, http.StatusCreated, im)
|
||||||
@@ -334,7 +350,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
|||||||
// DeleteImage removes an image.
|
// DeleteImage removes an image.
|
||||||
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
|
||||||
err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context()))
|
err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
@@ -348,7 +364,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, m)
|
writeJSON(w, http.StatusCreated, m)
|
||||||
@@ -357,7 +373,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
|||||||
// DeleteMSRP removes an MSRP snapshot.
|
// DeleteMSRP removes an MSRP snapshot.
|
||||||
func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
|
||||||
err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context()))
|
err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
@@ -375,7 +391,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||||
if h.handleBarcodeErr(w, err) {
|
if h.handleBarcodeErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, b)
|
writeJSON(w, http.StatusCreated, b)
|
||||||
@@ -384,7 +400,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
|||||||
// DeleteBarcode removes a barcode; a primary one is replaced automatically.
|
// DeleteBarcode removes a barcode; a primary one is replaced automatically.
|
||||||
func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
||||||
err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
@@ -393,7 +409,7 @@ func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
|||||||
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
|
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
|
||||||
func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
||||||
b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, b)
|
writeJSON(w, http.StatusOK, b)
|
||||||
@@ -401,7 +417,7 @@ func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
|
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
|
||||||
// conflict) to client-facing statuses, falling back to handleErr otherwise.
|
// conflict) to client-facing statuses, falling back to handleErr otherwise.
|
||||||
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -422,13 +438,13 @@ func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
|||||||
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
|
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return h.handleErr(w, err)
|
return h.handleErr(w, r, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListBrands returns brand options.
|
// ListBrands returns brand options.
|
||||||
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
|
||||||
items, err := h.store.ListBrands(r.Context())
|
items, err := h.store.ListBrands(r.Context())
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||||
@@ -442,7 +458,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, err := h.store.ListKindFields(r.Context(), kind)
|
items, err := h.store.ListKindFields(r.Context(), kind)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
|
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
|
||||||
@@ -451,7 +467,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
|||||||
// ListCategories returns category options.
|
// ListCategories returns category options.
|
||||||
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
|
||||||
items, err := h.store.ListCategories(r.Context())
|
items, err := h.store.ListCategories(r.Context())
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||||
@@ -469,7 +485,7 @@ func (h *Handler) CreateCategory(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in)
|
c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in)
|
||||||
if h.handleCategoryErr(w, err) {
|
if h.handleCategoryErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, c)
|
writeJSON(w, http.StatusCreated, c)
|
||||||
@@ -487,7 +503,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||||
if h.handleCategoryErr(w, err) {
|
if h.handleCategoryErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, c)
|
writeJSON(w, http.StatusOK, c)
|
||||||
@@ -496,7 +512,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
|||||||
// DeleteCategory removes a leaf category that no product uses.
|
// DeleteCategory removes a leaf category that no product uses.
|
||||||
func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||||||
err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||||
if h.handleCategoryErr(w, err) {
|
if h.handleCategoryErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
@@ -504,7 +520,7 @@ func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// handleCategoryErr maps category-specific errors to client statuses, falling
|
// handleCategoryErr maps category-specific errors to client statuses, falling
|
||||||
// back to handleErr otherwise.
|
// back to handleErr otherwise.
|
||||||
func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
func (h *Handler) handleCategoryErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -522,7 +538,7 @@ func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
|||||||
writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)")
|
writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return h.handleErr(w, err)
|
return h.handleErr(w, r, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
type brandInput struct {
|
type brandInput struct {
|
||||||
@@ -545,7 +561,7 @@ func (h *Handler) CreateBrand(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name)
|
b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name)
|
||||||
if h.handleBrandErr(w, err) {
|
if h.handleBrandErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, b)
|
writeJSON(w, http.StatusCreated, b)
|
||||||
@@ -563,7 +579,7 @@ func (h *Handler) UpdateBrand(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name)
|
b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name)
|
||||||
if h.handleBrandErr(w, err) {
|
if h.handleBrandErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, b)
|
writeJSON(w, http.StatusOK, b)
|
||||||
@@ -581,7 +597,7 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context()))
|
b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context()))
|
||||||
if h.handleBrandErr(w, err) {
|
if h.handleBrandErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, b)
|
writeJSON(w, http.StatusOK, b)
|
||||||
@@ -590,14 +606,14 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
|||||||
// DeleteBrand removes a brand no product references.
|
// DeleteBrand removes a brand no product references.
|
||||||
func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) {
|
||||||
err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||||
if h.handleBrandErr(w, err) {
|
if h.handleBrandErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleBrandErr maps brand-specific errors to client statuses.
|
// handleBrandErr maps brand-specific errors to client statuses.
|
||||||
func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
func (h *Handler) handleBrandErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -612,7 +628,7 @@ func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
|||||||
writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)")
|
writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return h.handleErr(w, err)
|
return h.handleErr(w, r, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- submissions ----------
|
// ---------- submissions ----------
|
||||||
@@ -634,7 +650,7 @@ func (h *Handler) CreateSubmission(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
id, err := h.store.CreateSubmission(r.Context(), in, realIP(r))
|
id, err := h.store.CreateSubmission(r.Context(), in, realIP(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
internalError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"})
|
writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"})
|
||||||
@@ -653,12 +669,16 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效")
|
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw)); err != nil {
|
key, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw))
|
||||||
|
if err != nil {
|
||||||
if errors.Is(err, adminstore.ErrNotFound) {
|
if errors.Is(err, adminstore.ErrNotFound) {
|
||||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销")
|
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
internalError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !h.allowBackflow(w, r, key.ID) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -679,12 +699,29 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r))
|
sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
internalError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, sum)
|
writeJSON(w, http.StatusOK, sum)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) allowBackflow(w http.ResponseWriter, r *http.Request, keyID string) bool {
|
||||||
|
if h.usage == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
res := h.usage.Allow(r.Context(), "backflow:"+keyID, h.backflowRate, time.Hour)
|
||||||
|
if res.Allowed {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
retryAfter := res.ResetUnix - time.Now().Unix()
|
||||||
|
if retryAfter < 1 {
|
||||||
|
retryAfter = 1
|
||||||
|
}
|
||||||
|
w.Header().Set("Retry-After", strconv.FormatInt(retryAfter, 10))
|
||||||
|
writeError(w, http.StatusTooManyRequests, "rate_limited", "回流请求超过每小时限制")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// presentedAPIKey extracts a public API key from X-API-Key or a Bearer token.
|
// presentedAPIKey extracts a public API key from X-API-Key or a Bearer token.
|
||||||
func presentedAPIKey(r *http.Request) string {
|
func presentedAPIKey(r *http.Request) string {
|
||||||
if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" {
|
if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" {
|
||||||
@@ -701,7 +738,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
|||||||
status := r.URL.Query().Get("status")
|
status := r.URL.Query().Get("status")
|
||||||
page, size := pageParams(r)
|
page, size := pageParams(r)
|
||||||
items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size)
|
items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pending, _ := h.store.PendingSubmissionCount(r.Context())
|
pending, _ := h.store.PendingSubmissionCount(r.Context())
|
||||||
@@ -713,7 +750,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
|||||||
// GetSubmission returns full submission detail (admin).
|
// GetSubmission returns full submission detail (admin).
|
||||||
func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
||||||
d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id"))
|
d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id"))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, d)
|
writeJSON(w, http.StatusOK, d)
|
||||||
@@ -722,7 +759,7 @@ func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
|||||||
// ApproveSubmission applies a contribution to the product store (admin).
|
// ApproveSubmission applies a contribution to the product store (admin).
|
||||||
func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) {
|
||||||
d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, d)
|
writeJSON(w, http.StatusOK, d)
|
||||||
@@ -735,7 +772,7 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||||
err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note)
|
err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note)
|
||||||
if h.handleErr(w, err) {
|
if h.handleErr(w, r, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"})
|
||||||
@@ -756,7 +793,12 @@ func realIP(r *http.Request) string {
|
|||||||
return r.RemoteAddr
|
return r.RemoteAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
func internalError(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
log.Printf("adminhandler: internal error request_id=%s: %v", middleware.GetReqID(r.Context()), err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "internal_error", "服务器内部错误")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) handleErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -768,7 +810,7 @@ func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
|||||||
writeError(w, http.StatusConflict, "conflict", "该投稿已被处理")
|
writeError(w, http.StatusConflict, "conflict", "该投稿已被处理")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
internalError(w, r, err)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
result, err := h.store.ImportByposRecords(r.Context(), records)
|
result, err := h.store.ImportByposRecords(r.Context(), records)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "import_error", err.Error())
|
internalError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, result)
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/baicai2026-baicai/goods/api/internal/gtin"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -76,8 +77,20 @@ func (s *Store) CreateBackflowSubmissions(ctx context.Context, items []Submissio
|
|||||||
if g == "" {
|
if g == "" {
|
||||||
in.GTIN = nil
|
in.GTIN = nil
|
||||||
} else {
|
} else {
|
||||||
in.GTIN = &g
|
// Validate/normalize so a malformed barcode is reported as an
|
||||||
|
// invalid item instead of aborting the batch (the gtin column
|
||||||
|
// is varchar(14) and only GS1 codes are archived).
|
||||||
|
norm, err := gtin.Normalize(g)
|
||||||
|
if err != nil {
|
||||||
res.GTIN = &g
|
res.GTIN = &g
|
||||||
|
res.Status = "invalid"
|
||||||
|
res.Reason = err.Error()
|
||||||
|
sum.Invalid++
|
||||||
|
sum.Results = append(sum.Results, res)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
in.GTIN = &norm
|
||||||
|
res.GTIN = &norm
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -119,6 +119,7 @@ curl "https://goods.tangshasha.com/api/v1/products/barcode/5449000000996"
|
|||||||
### `POST /api/public/backflow` — 批量回流未收录商品
|
### `POST /api/public/backflow` — 批量回流未收录商品
|
||||||
|
|
||||||
- 鉴权:请求头携带 `X-API-Key: og_live_xxxxxxxx`(或 `Authorization: Bearer og_live_xxxxxxxx`)。缺失/无效/已吊销返回 `401`。
|
- 鉴权:请求头携带 `X-API-Key: og_live_xxxxxxxx`(或 `Authorization: Bearer og_live_xxxxxxxx`)。缺失/无效/已吊销返回 `401`。
|
||||||
|
- 限速:按 API key 使用每小时固定窗口,默认每小时 30 次,可通过 `GOODS_BACKFLOW_RATE_PER_HOUR` 配置。超限返回 `429` 和 `Retry-After`;Redis 不可用时按现有策略放行。
|
||||||
- 请求体:商品对象**数组**(与公众投稿同结构),单次最多 `1000` 条。常用字段:
|
- 请求体:商品对象**数组**(与公众投稿同结构),单次最多 `1000` 条。常用字段:
|
||||||
|
|
||||||
| 字段 | 必填 | 说明 |
|
| 字段 | 必填 | 说明 |
|
||||||
|
|||||||
@@ -1,28 +1,8 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Search, PlusCircle, Code2, ScanBarcode, ShieldCheck, ArrowRight } from "lucide-react";
|
import { Search, PlusCircle, ArrowRight } from "lucide-react";
|
||||||
import { api } from "../api";
|
import { api } from "../api";
|
||||||
import type { ProductSummary } from "../types";
|
import type { ProductSummary } from "../types";
|
||||||
|
|
||||||
const EXAMPLES = ["可乐", "Nutella", "牛奶", "5449000000996"];
|
|
||||||
|
|
||||||
const FEATURES = [
|
|
||||||
{
|
|
||||||
icon: Search,
|
|
||||||
title: "客观可查",
|
|
||||||
desc: "按名称或条码检索商品的成分、营养、规格等官方事实。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: ShieldCheck,
|
|
||||||
title: "可溯源",
|
|
||||||
desc: "每条资料标注数据来源与质量分,公开透明、人人可核。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Code2,
|
|
||||||
title: "开放 API",
|
|
||||||
desc: "免鉴权只读 REST 接口,开发者可直接接入商品档案。",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export default function Home({
|
export default function Home({
|
||||||
onOpen,
|
onOpen,
|
||||||
onContribute,
|
onContribute,
|
||||||
@@ -57,47 +37,47 @@ export default function Home({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="animate-fade-up">
|
<div className="animate-fade-up">
|
||||||
<section className="relative overflow-hidden rounded-3xl border border-gray-100 bg-gradient-to-b from-white to-brand-50/40 px-6 py-14 text-center shadow-card">
|
<section
|
||||||
<div
|
className={`flex flex-col items-center px-4 text-center ${
|
||||||
aria-hidden
|
searched
|
||||||
className="pointer-events-none absolute -top-24 left-1/2 h-72 w-[42rem] -translate-x-1/2 rounded-full bg-brand-200/30 blur-3xl"
|
? "pt-2 pb-6"
|
||||||
/>
|
: "min-h-[calc(100vh-12rem)] justify-center"
|
||||||
<div className="relative">
|
}`}
|
||||||
<span className="inline-flex items-center gap-1.5 rounded-full border border-brand-200 bg-white/70 px-3 py-1 text-xs font-medium text-brand-700">
|
>
|
||||||
<ShieldCheck className="w-3.5 h-3.5" /> 公益 · 开放 · 可溯源
|
<h1
|
||||||
</span>
|
className={`font-medium tracking-tight text-gray-800 ${
|
||||||
<h1 className="mt-5 text-4xl sm:text-5xl font-extrabold tracking-tight text-gray-900">
|
searched ? "text-3xl" : "text-6xl sm:text-7xl"
|
||||||
天<span className="bg-gradient-to-r from-brand-600 to-emerald-500 bg-clip-text text-transparent">工</span>
|
}`}
|
||||||
|
>
|
||||||
|
天<span className="text-brand-600">工</span>
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mx-auto mt-3 max-w-xl text-gray-500">
|
|
||||||
输入商品名称或条码,检索客观、可溯源的商品资料。人人可查,人人可贡献。
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<form onSubmit={(e) => run(undefined, e)} className="mx-auto mt-7 flex max-w-2xl gap-2">
|
<form
|
||||||
<div className="flex flex-1 items-center gap-2 rounded-xl border border-gray-200 bg-white px-3.5 shadow-sm transition focus-within:border-brand-400 focus-within:ring-4 focus-within:ring-brand-500/10">
|
onSubmit={(e) => run(undefined, e)}
|
||||||
|
className="mx-auto mt-8 w-full max-w-xl"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 rounded-full border border-gray-200 bg-white px-5 py-3 shadow-sm transition hover:shadow-md focus-within:shadow-md">
|
||||||
<Search className="h-5 w-5 shrink-0 text-gray-400" />
|
<Search className="h-5 w-5 shrink-0 text-gray-400" />
|
||||||
<input
|
<input
|
||||||
autoFocus
|
autoFocus
|
||||||
value={q}
|
value={q}
|
||||||
onChange={(e) => setQ(e.target.value)}
|
onChange={(e) => setQ(e.target.value)}
|
||||||
placeholder="例如:可乐、Nutella、5449000000996"
|
placeholder="搜索商品名称或条码"
|
||||||
className="flex-1 bg-transparent py-3.5 outline-none"
|
className="flex-1 bg-transparent outline-none"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" disabled={loading} className="btn-primary px-7">
|
{!searched && (
|
||||||
|
<div className="mt-8">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="rounded-md border border-gray-200 bg-gray-50 px-6 py-2.5 text-sm text-gray-700 transition hover:border-gray-300 hover:shadow-sm"
|
||||||
|
>
|
||||||
{loading ? "检索中…" : "检索"}
|
{loading ? "检索中…" : "检索"}
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-4 flex flex-wrap items-center justify-center gap-2">
|
|
||||||
<span className="text-xs text-gray-400">试试:</span>
|
|
||||||
{EXAMPLES.map((ex) => (
|
|
||||||
<button key={ex} type="button" className="chip" onClick={() => run(ex)}>
|
|
||||||
<ScanBarcode className="w-3 h-3" /> {ex}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -106,7 +86,7 @@ export default function Home({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{searched ? (
|
{searched && (
|
||||||
<div className="mt-8">
|
<div className="mt-8">
|
||||||
<div className="mb-3 text-sm text-gray-500">
|
<div className="mb-3 text-sm text-gray-500">
|
||||||
共 <span className="font-semibold text-gray-700">{total}</span> 条结果
|
共 <span className="font-semibold text-gray-700">{total}</span> 条结果
|
||||||
@@ -154,18 +134,6 @@ export default function Home({
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
|
||||||
<div className="mt-8 grid gap-4 sm:grid-cols-3">
|
|
||||||
{FEATURES.map(({ icon: Icon, title, desc }) => (
|
|
||||||
<div key={title} className="card p-5 transition hover:shadow-card-hover">
|
|
||||||
<span className="grid h-10 w-10 place-items-center rounded-xl bg-brand-50 text-brand-600">
|
|
||||||
<Icon className="h-5 w-5" />
|
|
||||||
</span>
|
|
||||||
<h3 className="mt-3 font-semibold text-gray-800">{title}</h3>
|
|
||||||
<p className="mt-1 text-sm leading-relaxed text-gray-500">{desc}</p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user