feat(barcode): admin barcode CRUD endpoints + UI; show extra barcodes publicly
CI / Python (ingestion) (pull_request) Successful in 10s
CI / Go (api) (pull_request) Failing after 15s
CI / Migrations (postgres) (pull_request) Failing after 11m35s

Wire the multi-barcode store layer to HTTP and the operator console:

- adminhandler: add POST /products/{id}/barcodes, DELETE
  /products/{id}/barcodes/{barcodeID}, and POST .../primary. A barcode
  owned by another product returns 409 with the conflicting product
  (gtin/product_id/product_name); an invalid GTIN returns 400.
- admin-frontend: BarcodesCard on the product detail page lists all
  barcodes (primary starred), adds with type/pack-level/region, sets
  primary, and deletes; audit labels for the new actions.
- public-frontend: product detail surfaces non-primary barcodes so a
  case/region code resolves and is visible to consumers.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
novaalphastrikeomegaz663
2026-06-20 07:06:07 +00:00
parent 1d5f775d33
commit 98b5f1575d
6 changed files with 286 additions and 0 deletions
+14
View File
@@ -86,6 +86,20 @@ export const api = {
request<{ status: string }>(`/products/${id}/msrp/${msrpId}`, {
method: "DELETE",
}),
addBarcode: (id: string, body: unknown) =>
request<import("./types").Barcode>(`/products/${id}/barcodes`, {
method: "POST",
body: JSON.stringify(body),
}),
deleteBarcode: (id: string, barcodeId: string) =>
request<{ status: string }>(`/products/${id}/barcodes/${barcodeId}`, {
method: "DELETE",
}),
setPrimaryBarcode: (id: string, barcodeId: string) =>
request<import("./types").Barcode>(
`/products/${id}/barcodes/${barcodeId}/primary`,
{ method: "POST" },
),
listBrands: () =>
request<{ items: import("./types").Brand[] }>("/brands"),
listCategories: () =>
@@ -14,8 +14,16 @@ import {
Trash2,
AlertCircle,
History,
Star,
} from "lucide-react";
const GTIN_TYPES = ["EAN13", "EAN8", "UPC", "ITF14", "GTIN14"];
const PACK_LEVELS: { value: string; label: string }[] = [
{ value: "each", label: "消费单元" },
{ value: "case", label: "箱" },
{ value: "pallet", label: "托盘" },
];
const NUTRIMENT_KEYS: { key: string; label: string }[] = [
{ key: "energy_kcal", label: "能量 (kcal)" },
{ key: "energy_kj", label: "能量 (kJ)" },
@@ -39,6 +47,9 @@ const ACTION_LABEL: Record<string, string> = {
delete_image: "删除图片",
add_msrp: "新增建议零售价",
delete_msrp: "删除建议零售价",
add_barcode: "新增条码",
delete_barcode: "删除条码",
set_primary_barcode: "设为主条码",
};
function Card({
@@ -400,6 +411,7 @@ export default function ProductDetail({
</div>
</Card>
<BarcodesCard product={d} onChange={reload} onError={setError} />
<ImagesCard
product={d}
onChange={reload}
@@ -435,6 +447,158 @@ export default function ProductDetail({
);
}
function BarcodesCard({
product,
onChange,
onError,
}: {
product: Detail;
onChange: () => void;
onError: (m: string) => void;
}) {
const [gtin, setGtin] = useState("");
const [gtinType, setGtinType] = useState("EAN13");
const [packLevel, setPackLevel] = useState("each");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
async function add() {
if (!gtin.trim()) return;
setBusy(true);
try {
await api.addBarcode(product.id, {
gtin: gtin.trim(),
gtin_type: gtinType,
pack_level: packLevel,
region: region.trim() || null,
is_primary: false,
});
setGtin("");
setRegion("");
onChange();
} catch (e) {
onError(e instanceof Error ? e.message : "添加失败");
} finally {
setBusy(false);
}
}
async function remove(barcodeId: string) {
try {
await api.deleteBarcode(product.id, barcodeId);
onChange();
} catch (e) {
onError(e instanceof Error ? e.message : "删除失败");
}
}
async function makePrimary(barcodeId: string) {
try {
await api.setPrimaryBarcode(product.id, barcodeId);
onChange();
} catch (e) {
onError(e instanceof Error ? e.message : "设置失败");
}
}
return (
<Card title="条码(一品多码,主条码镜像到 GTIN)">
<div className="mb-3 space-y-2">
{product.barcodes.length === 0 && (
<span className="text-sm text-gray-400"></span>
)}
{product.barcodes.map((b) => (
<div
key={b.id}
className="flex items-center gap-3 rounded border border-gray-100 bg-gray-50 px-3 py-2 text-sm"
>
<button
onClick={() => !b.is_primary && makePrimary(b.id)}
title={b.is_primary ? "主条码" : "设为主条码"}
disabled={b.is_primary}
className={
b.is_primary
? "text-amber-500"
: "text-gray-300 hover:text-amber-500"
}
>
<Star
className="h-4 w-4"
fill={b.is_primary ? "currentColor" : "none"}
/>
</button>
<span className="font-mono font-medium text-gray-800">
{b.gtin}
</span>
<span className="rounded bg-gray-200 px-1.5 py-0.5 text-[11px] text-gray-600">
{b.gtin_type}
</span>
<span className="text-gray-500">
{PACK_LEVELS.find((p) => p.value === b.pack_level)?.label ||
b.pack_level}
</span>
<span className="flex-1 text-gray-400">{b.region || ""}</span>
<button
onClick={() => remove(b.id)}
className="text-gray-400 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
))}
</div>
<div className="flex flex-wrap items-end gap-2">
<Field label="条码 (GTIN)">
<input
className="w-44 rounded border border-gray-300 px-3 py-2 text-sm"
value={gtin}
onChange={(e) => setGtin(e.target.value)}
placeholder="8/12/13/14 位"
/>
</Field>
<Field label="类型">
<select
className="rounded border border-gray-300 px-2 py-2 text-sm"
value={gtinType}
onChange={(e) => setGtinType(e.target.value)}
>
{GTIN_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</Field>
<Field label="包装层级">
<select
className="rounded border border-gray-300 px-2 py-2 text-sm"
value={packLevel}
onChange={(e) => setPackLevel(e.target.value)}
>
{PACK_LEVELS.map((p) => (
<option key={p.value} value={p.value}>
{p.label}
</option>
))}
</select>
</Field>
<Field label="地区(可选)">
<input
className="w-20 rounded border border-gray-300 px-3 py-2 text-sm"
value={region}
onChange={(e) => setRegion(e.target.value.toUpperCase())}
/>
</Field>
<button
onClick={add}
disabled={busy}
className="flex items-center gap-1 rounded bg-gray-700 px-3 py-2 text-sm text-white hover:bg-gray-800 disabled:opacity-60"
>
<Plus className="h-4 w-4" />
</button>
</div>
</Card>
);
}
function ImagesCard({
product,
onChange,
+10
View File
@@ -10,6 +10,15 @@ export interface ProductRow {
updated_at: string;
}
export interface Barcode {
id: string;
gtin: string;
gtin_type: string;
pack_level: string;
region: string | null;
is_primary: boolean;
}
export interface ProductImage {
id: string;
url: string;
@@ -47,6 +56,7 @@ export interface ProductDetail {
nutrition_basis: string | null;
serving_size: string | null;
nutri_score: string | null;
barcodes: Barcode[];
images: ProductImage[];
msrp: MSRP[];
missing: string[];
+66
View File
@@ -15,6 +15,7 @@ import (
"github.com/baicai2026-baicai/goods/api/internal/adminstore"
"github.com/baicai2026-baicai/goods/api/internal/auth"
"github.com/baicai2026-baicai/goods/api/internal/gtin"
)
// Handler holds the admin dependencies.
@@ -62,6 +63,9 @@ func (h *Handler) Router() http.Handler {
r.Delete("/api/products/{id}/images/{imageID}", h.DeleteImage)
r.Post("/api/products/{id}/msrp", h.AddMSRP)
r.Delete("/api/products/{id}/msrp/{msrpID}", h.DeleteMSRP)
r.Post("/api/products/{id}/barcodes", h.AddBarcode)
r.Delete("/api/products/{id}/barcodes/{barcodeID}", h.DeleteBarcode)
r.Post("/api/products/{id}/barcodes/{barcodeID}/primary", h.SetPrimaryBarcode)
r.Get("/api/brands", h.ListBrands)
r.Get("/api/categories", h.ListCategories)
@@ -231,6 +235,68 @@ func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
}
// ---------- barcodes ----------
// AddBarcode validates and attaches a barcode to a product. A code already
// owned by another product yields 409 with the conflicting product so the
// operator can de-duplicate; an invalid GTIN yields 400.
func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
var in adminstore.BarcodeInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "invalid body")
return
}
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
if h.handleBarcodeErr(w, err) {
return
}
writeJSON(w, http.StatusCreated, b)
}
// DeleteBarcode removes a barcode; a primary one is replaced automatically.
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()))
if h.handleErr(w, err) {
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
}
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
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()))
if h.handleErr(w, err) {
return
}
writeJSON(w, http.StatusOK, b)
}
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
// conflict) to client-facing statuses, falling back to handleErr otherwise.
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
if err == nil {
return false
}
var conflict *adminstore.ConflictError
if errors.As(err, &conflict) {
writeJSON(w, http.StatusConflict, map[string]any{
"error": map[string]string{"code": "barcode_conflict", "message": err.Error()},
"conflict": map[string]string{
"gtin": conflict.GTIN,
"product_id": conflict.ProductID,
"product_name": conflict.ProductName,
},
})
return true
}
if errors.Is(err, gtin.ErrEmpty) || errors.Is(err, gtin.ErrFormat) ||
errors.Is(err, gtin.ErrCheck) || errors.Is(err, gtin.ErrRestricted) {
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
return true
}
return h.handleErr(w, err)
}
// ListBrands returns brand options.
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
items, err := h.store.ListBrands(r.Context())
@@ -60,6 +60,29 @@ export default function ProductView({ id, onBack }: { id: string; onBack: () =>
<div className="mt-4">
<Row label="品牌" value={p.brand} />
<Row label="条码 (GTIN)" value={p.gtin} />
{(() => {
const others = (p.barcodes || []).filter(
(b) => !b.is_primary && b.gtin !== p.gtin,
);
return others.length ? (
<Row
label="其他条码"
value={
<div className="flex flex-wrap gap-1.5">
{others.map((b) => (
<span
key={b.gtin}
className="font-mono text-xs bg-gray-100 text-gray-600 rounded px-1.5 py-0.5"
title={`${b.gtin_type} · ${b.pack_level}`}
>
{b.gtin}
</span>
))}
</div>
}
/>
) : null;
})()}
<Row label="品类" value={p.category_path} />
<Row
label="净含量"
+9
View File
@@ -6,9 +6,18 @@ export interface ProductSummary {
category_path: string | null;
}
export interface Barcode {
gtin: string;
gtin_type: string;
pack_level: string;
region: string | null;
is_primary: boolean;
}
export interface Product {
id: string;
gtin: string | null;
barcodes?: Barcode[] | null;
name: string;
brand: string | null;
category_path: string | null;