Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 916bdd9c7c | |||
| 98eb01f4ea | |||
| 51304d782a | |||
| 6e81a7eb36 |
@@ -28,6 +28,7 @@ export default function App() {
|
|||||||
const [tab, setTab] = useState<Tab>("products");
|
const [tab, setTab] = useState<Tab>("products");
|
||||||
const [pending, setPending] = useState<number | null>(null);
|
const [pending, setPending] = useState<number | null>(null);
|
||||||
const [view, setView] = useState<View>({ name: "list" });
|
const [view, setView] = useState<View>({ name: "list" });
|
||||||
|
const [navIds, setNavIds] = useState<string[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authed) return;
|
if (!authed) return;
|
||||||
@@ -190,9 +191,19 @@ export default function App() {
|
|||||||
) : tab === "submissions" ? (
|
) : tab === "submissions" ? (
|
||||||
<SubmissionsPage onPending={setPending} />
|
<SubmissionsPage onPending={setPending} />
|
||||||
) : view.name === "list" ? (
|
) : view.name === "list" ? (
|
||||||
<ProductList onOpen={(id) => setView({ name: "detail", id })} />
|
<ProductList
|
||||||
|
onOpen={(id, ids) => {
|
||||||
|
setNavIds(ids);
|
||||||
|
setView({ name: "detail", id });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<ProductDetail id={view.id} onBack={() => setView({ name: "list" })} />
|
<ProductDetail
|
||||||
|
id={view.id}
|
||||||
|
ids={navIds}
|
||||||
|
onNavigate={(id) => setView({ name: "detail", id })}
|
||||||
|
onBack={() => setView({ name: "list" })}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -124,6 +124,10 @@ export const api = {
|
|||||||
}),
|
}),
|
||||||
deleteBrand: (id: string) =>
|
deleteBrand: (id: string) =>
|
||||||
request<{ status: string }>(`/brands/${id}`, { method: "DELETE" }),
|
request<{ status: string }>(`/brands/${id}`, { method: "DELETE" }),
|
||||||
|
listKindFields: (kind: string) =>
|
||||||
|
request<{ items: import("./types").KindField[]; kind: string }>(
|
||||||
|
`/kind-fields?kind=${encodeURIComponent(kind)}`,
|
||||||
|
),
|
||||||
listCategories: () =>
|
listCategories: () =>
|
||||||
request<{ items: import("./types").Category[] }>("/categories"),
|
request<{ items: import("./types").Category[] }>("/categories"),
|
||||||
createCategory: (body: import("./types").CategoryInput) =>
|
createCategory: (body: import("./types").CategoryInput) =>
|
||||||
|
|||||||
@@ -5,10 +5,13 @@ import {
|
|||||||
Brand,
|
Brand,
|
||||||
Category,
|
Category,
|
||||||
FIELD_LABELS,
|
FIELD_LABELS,
|
||||||
|
KindField,
|
||||||
ProductDetail as Detail,
|
ProductDetail as Detail,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
Plus,
|
Plus,
|
||||||
Save,
|
Save,
|
||||||
Trash2,
|
Trash2,
|
||||||
@@ -88,10 +91,18 @@ const inputCls =
|
|||||||
export default function ProductDetail({
|
export default function ProductDetail({
|
||||||
id,
|
id,
|
||||||
onBack,
|
onBack,
|
||||||
|
ids = [],
|
||||||
|
onNavigate,
|
||||||
}: {
|
}: {
|
||||||
id: string;
|
id: string;
|
||||||
onBack: () => void;
|
onBack: () => void;
|
||||||
|
ids?: string[];
|
||||||
|
onNavigate?: (id: string) => void;
|
||||||
}) {
|
}) {
|
||||||
|
const navIndex = ids.indexOf(id);
|
||||||
|
const prevId = navIndex > 0 ? ids[navIndex - 1] : null;
|
||||||
|
const nextId =
|
||||||
|
navIndex >= 0 && navIndex < ids.length - 1 ? ids[navIndex + 1] : null;
|
||||||
const [d, setD] = useState<Detail | null>(null);
|
const [d, setD] = useState<Detail | null>(null);
|
||||||
const [brands, setBrands] = useState<Brand[]>([]);
|
const [brands, setBrands] = useState<Brand[]>([]);
|
||||||
const [categories, setCategories] = useState<Category[]>([]);
|
const [categories, setCategories] = useState<Category[]>([]);
|
||||||
@@ -117,6 +128,8 @@ export default function ProductDetail({
|
|||||||
const [basis, setBasis] = useState("");
|
const [basis, setBasis] = useState("");
|
||||||
const [serving, setServing] = useState("");
|
const [serving, setServing] = useState("");
|
||||||
const [nutriScore, setNutriScore] = useState("");
|
const [nutriScore, setNutriScore] = useState("");
|
||||||
|
const [kindFields, setKindFields] = useState<KindField[]>([]);
|
||||||
|
const [attrs, setAttrs] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
function hydrate(detail: Detail) {
|
function hydrate(detail: Detail) {
|
||||||
setD(detail);
|
setD(detail);
|
||||||
@@ -139,6 +152,13 @@ export default function ProductDetail({
|
|||||||
setBasis(detail.nutrition_basis || "");
|
setBasis(detail.nutrition_basis || "");
|
||||||
setServing(detail.serving_size || "");
|
setServing(detail.serving_size || "");
|
||||||
setNutriScore(detail.nutri_score || "");
|
setNutriScore(detail.nutri_score || "");
|
||||||
|
const am: Record<string, string> = {};
|
||||||
|
if (detail.attributes) {
|
||||||
|
for (const [k, v] of Object.entries(detail.attributes)) {
|
||||||
|
am[k] = v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setAttrs(am);
|
||||||
}
|
}
|
||||||
|
|
||||||
function reload() {
|
function reload() {
|
||||||
@@ -161,6 +181,41 @@ export default function ProductDetail({
|
|||||||
|
|
||||||
const missing = useMemo(() => d?.missing ?? [], [d]);
|
const missing = useMemo(() => d?.missing ?? [], [d]);
|
||||||
|
|
||||||
|
const selectedKind = useMemo(() => {
|
||||||
|
const c = categories.find((x) => x.id === categoryId);
|
||||||
|
return c?.archive_kind || d?.archive_kind || "generic";
|
||||||
|
}, [categories, categoryId, d]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedKind && selectedKind !== "food") {
|
||||||
|
api
|
||||||
|
.listKindFields(selectedKind)
|
||||||
|
.then((r) => setKindFields(r.items))
|
||||||
|
.catch(() => setKindFields([]));
|
||||||
|
} else {
|
||||||
|
setKindFields([]);
|
||||||
|
}
|
||||||
|
}, [selectedKind]);
|
||||||
|
|
||||||
|
const specGroups = useMemo(() => {
|
||||||
|
const groups: { label: string; fields: KindField[] }[] = [];
|
||||||
|
for (const f of kindFields) {
|
||||||
|
let g = groups.find((x) => x.label === f.group_label);
|
||||||
|
if (!g) {
|
||||||
|
g = { label: f.group_label, fields: [] };
|
||||||
|
groups.push(g);
|
||||||
|
}
|
||||||
|
g.fields.push(f);
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}, [kindFields]);
|
||||||
|
|
||||||
|
const attrLabels = useMemo(() => {
|
||||||
|
const m: Record<string, string> = {};
|
||||||
|
for (const f of kindFields) m[f.field_key] = f.label_zh;
|
||||||
|
return m;
|
||||||
|
}, [kindFields]);
|
||||||
|
|
||||||
function parseList(s: string): string[] {
|
function parseList(s: string): string[] {
|
||||||
return s
|
return s
|
||||||
.split(",")
|
.split(",")
|
||||||
@@ -177,6 +232,22 @@ export default function ProductDetail({
|
|||||||
const n = parseFloat(v);
|
const n = parseFloat(v);
|
||||||
if (!Number.isNaN(n)) nm[k] = n;
|
if (!Number.isNaN(n)) nm[k] = n;
|
||||||
}
|
}
|
||||||
|
let attributes: Record<string, unknown> | undefined;
|
||||||
|
if (selectedKind !== "food") {
|
||||||
|
attributes = {};
|
||||||
|
for (const f of kindFields) {
|
||||||
|
const raw = (attrs[f.field_key] ?? "").trim();
|
||||||
|
if (raw === "") continue;
|
||||||
|
if (f.field_type === "number") {
|
||||||
|
const n = parseFloat(raw);
|
||||||
|
if (!Number.isNaN(n)) attributes[f.field_key] = n;
|
||||||
|
} else if (f.field_type === "list") {
|
||||||
|
attributes[f.field_key] = parseList(raw);
|
||||||
|
} else {
|
||||||
|
attributes[f.field_key] = raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const body = {
|
const body = {
|
||||||
gtin: gtin.trim() || null,
|
gtin: gtin.trim() || null,
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
@@ -194,6 +265,7 @@ export default function ProductDetail({
|
|||||||
nutrition_basis: basis || null,
|
nutrition_basis: basis || null,
|
||||||
serving_size: serving.trim() || null,
|
serving_size: serving.trim() || null,
|
||||||
nutri_score: nutriScore || null,
|
nutri_score: nutriScore || null,
|
||||||
|
...(attributes !== undefined ? { attributes } : {}),
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const updated = await api.updateProduct(id, body);
|
const updated = await api.updateProduct(id, body);
|
||||||
@@ -226,12 +298,35 @@ export default function ProductDetail({
|
|||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-5xl space-y-5">
|
<div className="mx-auto max-w-5xl space-y-5">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<button
|
<div className="flex items-center gap-2">
|
||||||
onClick={onBack}
|
<button
|
||||||
className="flex items-center gap-1 text-sm text-gray-600 hover:text-gray-900"
|
onClick={onBack}
|
||||||
>
|
className="flex items-center gap-1 text-sm text-gray-600 hover:text-gray-900"
|
||||||
<ArrowLeft className="h-4 w-4" /> 返回列表
|
>
|
||||||
</button>
|
<ArrowLeft className="h-4 w-4" /> 返回列表
|
||||||
|
</button>
|
||||||
|
{ids.length > 1 && navIndex >= 0 && (
|
||||||
|
<div className="ml-2 flex items-center gap-1 text-sm">
|
||||||
|
<button
|
||||||
|
onClick={() => prevId && onNavigate?.(prevId)}
|
||||||
|
disabled={!prevId}
|
||||||
|
className="flex items-center gap-1 rounded border border-gray-300 px-2 py-1 text-gray-600 hover:bg-gray-50 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" /> 上一个
|
||||||
|
</button>
|
||||||
|
<span className="text-xs text-gray-400">
|
||||||
|
{navIndex + 1} / {ids.length}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => nextId && onNavigate?.(nextId)}
|
||||||
|
disabled={!nextId}
|
||||||
|
className="flex items-center gap-1 rounded border border-gray-300 px-2 py-1 text-gray-600 hover:bg-gray-50 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
下一个 <ChevronRight className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{msg && <span className="text-sm text-emerald-600">{msg}</span>}
|
{msg && <span className="text-sm text-emerald-600">{msg}</span>}
|
||||||
{error && <span className="text-sm text-red-600">{error}</span>}
|
{error && <span className="text-sm text-red-600">{error}</span>}
|
||||||
@@ -251,7 +346,8 @@ export default function ProductDetail({
|
|||||||
{missing.length > 0 && (
|
{missing.length > 0 && (
|
||||||
<div className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
|
<div className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
|
||||||
<AlertCircle className="h-4 w-4" />
|
<AlertCircle className="h-4 w-4" />
|
||||||
待补全字段:{missing.map((f) => FIELD_LABELS[f] || f).join("、")}
|
待补全字段:
|
||||||
|
{missing.map((f) => FIELD_LABELS[f] || attrLabels[f] || f).join("、")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -338,6 +434,7 @@ export default function ProductDetail({
|
|||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{selectedKind === "food" && (
|
||||||
<Card title="配料与营养">
|
<Card title="配料与营养">
|
||||||
<div className="mb-4 grid grid-cols-2 gap-4">
|
<div className="mb-4 grid grid-cols-2 gap-4">
|
||||||
<Field label="配料表">
|
<Field label="配料表">
|
||||||
@@ -410,6 +507,75 @@ export default function ProductDetail({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedKind !== "food" && kindFields.length > 0 && (
|
||||||
|
<Card title="规格参数">
|
||||||
|
{specGroups.map((grp) => (
|
||||||
|
<div key={grp.label} className="mb-4 last:mb-0">
|
||||||
|
{grp.label && (
|
||||||
|
<h4 className="mb-2 text-xs font-medium text-gray-500">
|
||||||
|
{grp.label}
|
||||||
|
</h4>
|
||||||
|
)}
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
{grp.fields.map((f) => (
|
||||||
|
<Field
|
||||||
|
key={f.field_key}
|
||||||
|
label={f.unit ? `${f.label_zh} (${f.unit})` : f.label_zh}
|
||||||
|
>
|
||||||
|
{f.field_type === "select" ? (
|
||||||
|
<select
|
||||||
|
className={inputCls}
|
||||||
|
value={attrs[f.field_key] ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setAttrs((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[f.field_key]: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">(未设置)</option>
|
||||||
|
{f.options.map((o) => (
|
||||||
|
<option key={o} value={o}>
|
||||||
|
{o}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : f.field_type === "textarea" ? (
|
||||||
|
<textarea
|
||||||
|
className={inputCls}
|
||||||
|
rows={3}
|
||||||
|
value={attrs[f.field_key] ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setAttrs((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[f.field_key]: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
className={inputCls}
|
||||||
|
type={f.field_type === "number" ? "number" : "text"}
|
||||||
|
step={f.field_type === "number" ? "any" : undefined}
|
||||||
|
placeholder={f.placeholder ?? undefined}
|
||||||
|
value={attrs[f.field_key] ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setAttrs((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[f.field_key]: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
<BarcodesCard product={d} onChange={reload} onError={setError} />
|
<BarcodesCard product={d} onChange={reload} onError={setError} />
|
||||||
<ImagesCard
|
<ImagesCard
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ function QualityBadge({ score }: { score: number }) {
|
|||||||
export default function ProductList({
|
export default function ProductList({
|
||||||
onOpen,
|
onOpen,
|
||||||
}: {
|
}: {
|
||||||
onOpen: (id: string) => void;
|
onOpen: (id: string, ids: string[]) => void;
|
||||||
}) {
|
}) {
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [input, setInput] = useState("");
|
const [input, setInput] = useState("");
|
||||||
@@ -165,7 +165,7 @@ export default function ProductList({
|
|||||||
onClose={() => setCreating(false)}
|
onClose={() => setCreating(false)}
|
||||||
onCreated={(id) => {
|
onCreated={(id) => {
|
||||||
setCreating(false);
|
setCreating(false);
|
||||||
onOpen(id);
|
onOpen(id, [id]);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -271,7 +271,7 @@ export default function ProductList({
|
|||||||
rows.map((r) => (
|
rows.map((r) => (
|
||||||
<tr
|
<tr
|
||||||
key={r.id}
|
key={r.id}
|
||||||
onClick={() => onOpen(r.id)}
|
onClick={() => onOpen(r.id, rows.map((x) => x.id))}
|
||||||
className={`cursor-pointer hover:bg-emerald-50/50 ${
|
className={`cursor-pointer hover:bg-emerald-50/50 ${
|
||||||
selected.has(r.id) ? "bg-emerald-50/60" : ""
|
selected.has(r.id) ? "bg-emerald-50/60" : ""
|
||||||
}`}
|
}`}
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ export interface ProductDetail {
|
|||||||
brand: string | null;
|
brand: string | null;
|
||||||
category_id: string | null;
|
category_id: string | null;
|
||||||
category_path: string | null;
|
category_path: string | null;
|
||||||
|
archive_kind: string;
|
||||||
|
attributes: Record<string, unknown>;
|
||||||
net_content_value: number | null;
|
net_content_value: number | null;
|
||||||
net_content_unit: string | null;
|
net_content_unit: string | null;
|
||||||
country_of_origin: string | null;
|
country_of_origin: string | null;
|
||||||
@@ -77,9 +79,23 @@ export interface Category {
|
|||||||
level: number;
|
level: number;
|
||||||
parent_id: string | null;
|
parent_id: string | null;
|
||||||
gpc_brick_code: string | null;
|
gpc_brick_code: string | null;
|
||||||
|
archive_kind: string;
|
||||||
product_count: number;
|
product_count: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface KindField {
|
||||||
|
kind: string;
|
||||||
|
field_key: string;
|
||||||
|
group_label: string;
|
||||||
|
label_zh: string;
|
||||||
|
field_type: string;
|
||||||
|
unit: string | null;
|
||||||
|
options: string[];
|
||||||
|
placeholder: string | null;
|
||||||
|
sort_order: number;
|
||||||
|
qualified: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CategoryInput {
|
export interface CategoryInput {
|
||||||
name_zh: string;
|
name_zh: string;
|
||||||
name_en?: string | null;
|
name_en?: string | null;
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ func (h *Handler) Router() http.Handler {
|
|||||||
r.Put("/api/brands/{id}", h.UpdateBrand)
|
r.Put("/api/brands/{id}", h.UpdateBrand)
|
||||||
r.Post("/api/brands/{id}/merge", h.MergeBrands)
|
r.Post("/api/brands/{id}/merge", h.MergeBrands)
|
||||||
r.Delete("/api/brands/{id}", h.DeleteBrand)
|
r.Delete("/api/brands/{id}", h.DeleteBrand)
|
||||||
|
r.Get("/api/kind-fields", h.ListKindFields)
|
||||||
r.Get("/api/categories", h.ListCategories)
|
r.Get("/api/categories", h.ListCategories)
|
||||||
r.Post("/api/categories", h.CreateCategory)
|
r.Post("/api/categories", h.CreateCategory)
|
||||||
r.Put("/api/categories/{id}", h.UpdateCategory)
|
r.Put("/api/categories/{id}", h.UpdateCategory)
|
||||||
@@ -423,6 +424,20 @@ func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListKindFields returns the editable spec field template for an archive kind.
|
||||||
|
func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
||||||
|
kind := strings.TrimSpace(r.URL.Query().Get("kind"))
|
||||||
|
if kind == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "bad_request", "缺少 kind 参数")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := h.store.ListKindFields(r.Context(), kind)
|
||||||
|
if h.handleErr(w, err) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
|
||||||
|
}
|
||||||
|
|
||||||
// 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())
|
||||||
|
|||||||
@@ -64,10 +64,15 @@ func (s *Store) ListProducts(ctx context.Context, q string, limit, offset int) (
|
|||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
qualified, err := s.kindQualifiedKeys(ctx, s.pool)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
args = append(args, limit, offset)
|
args = append(args, limit, offset)
|
||||||
sql := `
|
sql := `
|
||||||
SELECT p.id, p.gtin, p.name, b.name, c.path::text, p.status, p.quality_score,
|
SELECT p.id, p.gtin, p.name, b.name, c.path::text, p.status, p.quality_score,
|
||||||
p.updated_at,
|
p.updated_at, COALESCE(c.archive_kind, 'generic'), p.attributes,
|
||||||
(p.brand_id IS NOT NULL) AS has_brand,
|
(p.brand_id IS NOT NULL) AS has_brand,
|
||||||
(p.category_id IS NOT NULL) AS has_cat,
|
(p.category_id IS NOT NULL) AS has_cat,
|
||||||
(p.net_content_canonical IS NOT NULL) AS has_net,
|
(p.net_content_canonical IS NOT NULL) AS has_net,
|
||||||
@@ -91,13 +96,21 @@ LEFT JOIN food_detail f ON f.product_id = p.id ` + where +
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var r ProductRow
|
var r ProductRow
|
||||||
var hasBrand, hasCat, hasNet, hasCountry, hasNutri, hasIng, hasImg bool
|
var hasBrand, hasCat, hasNet, hasCountry, hasNutri, hasIng, hasImg bool
|
||||||
|
var kind string
|
||||||
|
var attributes []byte
|
||||||
var updated time.Time
|
var updated time.Time
|
||||||
if err := rows.Scan(&r.ID, &r.GTIN, &r.Name, &r.Brand, &r.CategoryPath, &r.Status,
|
if err := rows.Scan(&r.ID, &r.GTIN, &r.Name, &r.Brand, &r.CategoryPath, &r.Status,
|
||||||
&r.QualityScore, &updated, &hasBrand, &hasCat, &hasNet, &hasCountry,
|
&r.QualityScore, &updated, &kind, &attributes,
|
||||||
|
&hasBrand, &hasCat, &hasNet, &hasCountry,
|
||||||
&hasNutri, &hasIng, &hasImg); err != nil {
|
&hasNutri, &hasIng, &hasImg); err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
r.UpdatedAt = updated.Format(time.RFC3339)
|
r.UpdatedAt = updated.Format(time.RFC3339)
|
||||||
|
attrs := map[string]any{}
|
||||||
|
if len(attributes) > 0 {
|
||||||
|
_ = json.Unmarshal(attributes, &attrs)
|
||||||
|
}
|
||||||
|
qkeys := qualified[kind]
|
||||||
present := map[string]bool{
|
present := map[string]bool{
|
||||||
"name": r.Name != "",
|
"name": r.Name != "",
|
||||||
"gtin": r.GTIN != nil && *r.GTIN != "",
|
"gtin": r.GTIN != nil && *r.GTIN != "",
|
||||||
@@ -109,8 +122,11 @@ LEFT JOIN food_detail f ON f.product_id = p.id ` + where +
|
|||||||
"ingredients": hasIng,
|
"ingredients": hasIng,
|
||||||
"image": hasImg,
|
"image": hasImg,
|
||||||
}
|
}
|
||||||
|
for _, k := range qkeys {
|
||||||
|
present[k] = attrPresent(attrs, k)
|
||||||
|
}
|
||||||
r.Missing = []string{}
|
r.Missing = []string{}
|
||||||
for _, f := range CompletenessFields {
|
for _, f := range completenessKeys(kind, qkeys) {
|
||||||
if !present[f] {
|
if !present[f] {
|
||||||
r.Missing = append(r.Missing, f)
|
r.Missing = append(r.Missing, f)
|
||||||
}
|
}
|
||||||
@@ -150,6 +166,8 @@ type ProductDetail struct {
|
|||||||
Brand *string `json:"brand"`
|
Brand *string `json:"brand"`
|
||||||
CategoryID *string `json:"category_id"`
|
CategoryID *string `json:"category_id"`
|
||||||
CategoryPath *string `json:"category_path"`
|
CategoryPath *string `json:"category_path"`
|
||||||
|
ArchiveKind string `json:"archive_kind"`
|
||||||
|
Attributes map[string]any `json:"attributes"`
|
||||||
NetContentValue *float64 `json:"net_content_value"`
|
NetContentValue *float64 `json:"net_content_value"`
|
||||||
NetContentUnit *string `json:"net_content_unit"`
|
NetContentUnit *string `json:"net_content_unit"`
|
||||||
CountryOfOrigin *string `json:"country_of_origin"`
|
CountryOfOrigin *string `json:"country_of_origin"`
|
||||||
@@ -173,9 +191,11 @@ type ProductDetail struct {
|
|||||||
func (s *Store) GetProduct(ctx context.Context, id string) (*ProductDetail, error) {
|
func (s *Store) GetProduct(ctx context.Context, id string) (*ProductDetail, error) {
|
||||||
var d ProductDetail
|
var d ProductDetail
|
||||||
var nutriments []byte
|
var nutriments []byte
|
||||||
|
var attributes []byte
|
||||||
var updated time.Time
|
var updated time.Time
|
||||||
err := s.pool.QueryRow(ctx, `
|
err := s.pool.QueryRow(ctx, `
|
||||||
SELECT p.id, p.gtin, p.name, p.brand_id, b.name, p.category_id, c.path::text,
|
SELECT p.id, p.gtin, p.name, p.brand_id, b.name, p.category_id, c.path::text,
|
||||||
|
COALESCE(c.archive_kind, 'generic'), p.attributes,
|
||||||
p.net_content_value, p.net_content_unit, p.country_of_origin, p.status,
|
p.net_content_value, p.net_content_unit, p.country_of_origin, p.status,
|
||||||
p.quality_score, p.updated_at,
|
p.quality_score, p.updated_at,
|
||||||
f.ingredients_text, f.allergens, f.additives, f.nutriments,
|
f.ingredients_text, f.allergens, f.additives, f.nutriments,
|
||||||
@@ -186,6 +206,7 @@ LEFT JOIN category c ON c.id = p.category_id
|
|||||||
LEFT JOIN food_detail f ON f.product_id = p.id
|
LEFT JOIN food_detail f ON f.product_id = p.id
|
||||||
WHERE p.id = $1`, id).Scan(
|
WHERE p.id = $1`, id).Scan(
|
||||||
&d.ID, &d.GTIN, &d.Name, &d.BrandID, &d.Brand, &d.CategoryID, &d.CategoryPath,
|
&d.ID, &d.GTIN, &d.Name, &d.BrandID, &d.Brand, &d.CategoryID, &d.CategoryPath,
|
||||||
|
&d.ArchiveKind, &attributes,
|
||||||
&d.NetContentValue, &d.NetContentUnit, &d.CountryOfOrigin, &d.Status,
|
&d.NetContentValue, &d.NetContentUnit, &d.CountryOfOrigin, &d.Status,
|
||||||
&d.QualityScore, &updated,
|
&d.QualityScore, &updated,
|
||||||
&d.IngredientsText, &d.Allergens, &d.Additives, &nutriments,
|
&d.IngredientsText, &d.Allergens, &d.Additives, &nutriments,
|
||||||
@@ -198,6 +219,10 @@ WHERE p.id = $1`, id).Scan(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
d.UpdatedAt = updated.Format(time.RFC3339)
|
d.UpdatedAt = updated.Format(time.RFC3339)
|
||||||
|
d.Attributes = map[string]any{}
|
||||||
|
if len(attributes) > 0 {
|
||||||
|
_ = json.Unmarshal(attributes, &d.Attributes)
|
||||||
|
}
|
||||||
if len(nutriments) > 0 {
|
if len(nutriments) > 0 {
|
||||||
_ = json.Unmarshal(nutriments, &d.Nutriments)
|
_ = json.Unmarshal(nutriments, &d.Nutriments)
|
||||||
}
|
}
|
||||||
@@ -226,11 +251,15 @@ WHERE p.id = $1`, id).Scan(
|
|||||||
}
|
}
|
||||||
d.MSRP = msrps
|
d.MSRP = msrps
|
||||||
|
|
||||||
d.Missing = missingFromDetail(&d)
|
qualified, err := s.kindQualifiedKeys(ctx, s.pool)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
d.Missing = missingFromDetail(&d, qualified[d.ArchiveKind])
|
||||||
return &d, nil
|
return &d, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func missingFromDetail(d *ProductDetail) []string {
|
func missingFromDetail(d *ProductDetail, qualifiedAttrKeys []string) []string {
|
||||||
present := map[string]bool{
|
present := map[string]bool{
|
||||||
"name": d.Name != "",
|
"name": d.Name != "",
|
||||||
"gtin": d.GTIN != nil && *d.GTIN != "",
|
"gtin": d.GTIN != nil && *d.GTIN != "",
|
||||||
@@ -242,8 +271,11 @@ func missingFromDetail(d *ProductDetail) []string {
|
|||||||
"ingredients": d.IngredientsText != nil && *d.IngredientsText != "",
|
"ingredients": d.IngredientsText != nil && *d.IngredientsText != "",
|
||||||
"image": len(d.Images) > 0,
|
"image": len(d.Images) > 0,
|
||||||
}
|
}
|
||||||
|
for _, k := range qualifiedAttrKeys {
|
||||||
|
present[k] = attrPresent(d.Attributes, k)
|
||||||
|
}
|
||||||
missing := []string{}
|
missing := []string{}
|
||||||
for _, f := range CompletenessFields {
|
for _, f := range completenessKeys(d.ArchiveKind, qualifiedAttrKeys) {
|
||||||
if !present[f] {
|
if !present[f] {
|
||||||
missing = append(missing, f)
|
missing = append(missing, f)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,11 +96,12 @@ func (s *Store) CreateCategory(ctx context.Context, actor string, in CategoryInp
|
|||||||
|
|
||||||
parentPath := ""
|
parentPath := ""
|
||||||
parentLevel := -1
|
parentLevel := -1
|
||||||
|
kind := DefaultKind
|
||||||
var parentID *string
|
var parentID *string
|
||||||
if pid := trimPtr(in.ParentID); pid != nil {
|
if pid := trimPtr(in.ParentID); pid != nil {
|
||||||
var path string
|
var path string
|
||||||
var level int
|
var level int
|
||||||
err := s.pool.QueryRow(ctx, "SELECT path::text, level FROM category WHERE id = $1", *pid).Scan(&path, &level)
|
err := s.pool.QueryRow(ctx, "SELECT path::text, level, archive_kind FROM category WHERE id = $1", *pid).Scan(&path, &level, &kind)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, ErrInvalidParent
|
return nil, ErrInvalidParent
|
||||||
}
|
}
|
||||||
@@ -119,11 +120,11 @@ func (s *Store) CreateCategory(ctx context.Context, actor string, in CategoryInp
|
|||||||
|
|
||||||
var c Category
|
var c Category
|
||||||
err := s.pool.QueryRow(ctx, `
|
err := s.pool.QueryRow(ctx, `
|
||||||
INSERT INTO category (name_zh, name_en, parent_id, path, gpc_brick_code, level)
|
INSERT INTO category (name_zh, name_en, parent_id, path, gpc_brick_code, level, archive_kind)
|
||||||
VALUES ($1, $2, $3, $4::ltree, $5, $6)
|
VALUES ($1, $2, $3, $4::ltree, $5, $6, $7)
|
||||||
RETURNING id, name_zh, name_en, path::text, level, parent_id::text, gpc_brick_code, 0`,
|
RETURNING id, name_zh, name_en, path::text, level, parent_id::text, gpc_brick_code, archive_kind, 0`,
|
||||||
name, trimPtr(in.NameEN), parentID, path, trimPtr(in.GPCBrickCode), level).
|
name, trimPtr(in.NameEN), parentID, path, trimPtr(in.GPCBrickCode), level, kind).
|
||||||
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ProductCount)
|
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ArchiveKind, &c.ProductCount)
|
||||||
if isUniqueViolation(err) {
|
if isUniqueViolation(err) {
|
||||||
return nil, ErrDuplicatePath
|
return nil, ErrDuplicatePath
|
||||||
}
|
}
|
||||||
@@ -273,10 +274,10 @@ func (s *Store) getCategory(ctx context.Context, id string) (*Category, error) {
|
|||||||
var c Category
|
var c Category
|
||||||
err := s.pool.QueryRow(ctx, `
|
err := s.pool.QueryRow(ctx, `
|
||||||
SELECT c.id, c.name_zh, c.name_en, c.path::text, c.level, c.parent_id::text,
|
SELECT c.id, c.name_zh, c.name_en, c.path::text, c.level, c.parent_id::text,
|
||||||
c.gpc_brick_code,
|
c.gpc_brick_code, c.archive_kind,
|
||||||
(SELECT count(*) FROM product p WHERE p.category_id = c.id)
|
(SELECT count(*) FROM product p WHERE p.category_id = c.id)
|
||||||
FROM category c WHERE c.id = $1`, id).
|
FROM category c WHERE c.id = $1`, id).
|
||||||
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ProductCount)
|
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ArchiveKind, &c.ProductCount)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, ErrNotFound
|
return nil, ErrNotFound
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package adminstore
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
// DefaultKind is used for products whose category has no archive kind (or no
|
||||||
|
// category at all).
|
||||||
|
const DefaultKind = "generic"
|
||||||
|
|
||||||
|
// FoodKind keeps the mature, dedicated food_detail path; every other kind is
|
||||||
|
// driven generically by kind_field + product.attributes.
|
||||||
|
const FoodKind = "food"
|
||||||
|
|
||||||
|
// genericBaseFields are the core completeness fields for any non-food kind.
|
||||||
|
// Food keeps its own richer CompletenessFields list.
|
||||||
|
var genericBaseFields = []string{"name", "gtin", "brand", "category", "image"}
|
||||||
|
|
||||||
|
// KindField describes one editable spec field for an archive kind. It drives
|
||||||
|
// both the dynamic admin form and the kind-aware completeness computation.
|
||||||
|
type KindField struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
FieldKey string `json:"field_key"`
|
||||||
|
GroupLabel string `json:"group_label"`
|
||||||
|
LabelZH string `json:"label_zh"`
|
||||||
|
FieldType string `json:"field_type"`
|
||||||
|
Unit *string `json:"unit"`
|
||||||
|
Options []string `json:"options"`
|
||||||
|
Placeholder *string `json:"placeholder"`
|
||||||
|
SortOrder int `json:"sort_order"`
|
||||||
|
Qualified bool `json:"qualified"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListKindFields returns the ordered field template for one archive kind.
|
||||||
|
func (s *Store) ListKindFields(ctx context.Context, kind string) ([]KindField, error) {
|
||||||
|
rows, err := s.pool.Query(ctx, `
|
||||||
|
SELECT kind, field_key, group_label, label_zh, field_type, unit, options,
|
||||||
|
placeholder, sort_order, qualified
|
||||||
|
FROM kind_field WHERE kind = $1 ORDER BY sort_order, field_key`, kind)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []KindField{}
|
||||||
|
for rows.Next() {
|
||||||
|
var f KindField
|
||||||
|
if err := rows.Scan(&f.Kind, &f.FieldKey, &f.GroupLabel, &f.LabelZH,
|
||||||
|
&f.FieldType, &f.Unit, &f.Options, &f.Placeholder, &f.SortOrder,
|
||||||
|
&f.Qualified); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, f)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// kindQualifiedKeys returns, per kind, the attribute keys that count toward the
|
||||||
|
// completeness/qualified score. Loaded in one query so list views stay cheap.
|
||||||
|
func (s *Store) kindQualifiedKeys(ctx context.Context, q queryer) (map[string][]string, error) {
|
||||||
|
rows, err := s.pool.Query(ctx,
|
||||||
|
"SELECT kind, field_key FROM kind_field WHERE qualified ORDER BY sort_order, field_key")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
m := map[string][]string{}
|
||||||
|
for rows.Next() {
|
||||||
|
var kind, key string
|
||||||
|
if err := rows.Scan(&kind, &key); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m[kind] = append(m[kind], key)
|
||||||
|
}
|
||||||
|
return m, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// completenessKeys returns the ordered list of field keys that define a full
|
||||||
|
// archive for the given kind.
|
||||||
|
func completenessKeys(kind string, qualifiedAttrKeys []string) []string {
|
||||||
|
if kind == FoodKind {
|
||||||
|
return CompletenessFields
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(genericBaseFields)+len(qualifiedAttrKeys))
|
||||||
|
keys = append(keys, genericBaseFields...)
|
||||||
|
keys = append(keys, qualifiedAttrKeys...)
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
// attrPresent reports whether an attribute value is meaningfully filled in.
|
||||||
|
func attrPresent(attrs map[string]any, key string) bool {
|
||||||
|
v, ok := attrs[key]
|
||||||
|
if !ok || v == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch t := v.(type) {
|
||||||
|
case string:
|
||||||
|
return t != ""
|
||||||
|
case []any:
|
||||||
|
return len(t) > 0
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package adminstore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// contains reports whether s holds v.
|
||||||
|
func contains(s []string, v string) bool {
|
||||||
|
for _, x := range s {
|
||||||
|
if x == v {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// electronicsCategoryID returns the seeded electronics.phone category id,
|
||||||
|
// skipping the test when the archive-kind migration is not applied.
|
||||||
|
func electronicsCategoryID(t *testing.T, s *Store) string {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
var hasTable bool
|
||||||
|
if err := s.pool.QueryRow(ctx, "SELECT to_regclass('public.kind_field') IS NOT NULL").Scan(&hasTable); err != nil || !hasTable {
|
||||||
|
t.Skip("archive-kind migration not applied (kind_field missing)")
|
||||||
|
}
|
||||||
|
var id string
|
||||||
|
err := s.pool.QueryRow(ctx, "SELECT id FROM category WHERE path = 'electronics.phone'::ltree").Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("electronics.phone category not seeded: %v", err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListKindFieldsElectronics(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
electronicsCategoryID(t, s) // ensures migration applied
|
||||||
|
fields, err := s.ListKindFields(context.Background(), "electronics")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list kind fields: %v", err)
|
||||||
|
}
|
||||||
|
if len(fields) == 0 {
|
||||||
|
t.Fatal("expected seeded electronics fields, got none")
|
||||||
|
}
|
||||||
|
var sawQualified bool
|
||||||
|
for _, f := range fields {
|
||||||
|
if f.FieldKey == "model_number" && f.Qualified {
|
||||||
|
sawQualified = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !sawQualified {
|
||||||
|
t.Fatal("expected model_number to be a qualified field")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestElectronicsArchiveKind verifies a non-food product uses the electronics
|
||||||
|
// completeness rules: food fields (nutriments/ingredients) are not required,
|
||||||
|
// and qualified spec fields drive both "missing" and the quality score.
|
||||||
|
func TestElectronicsArchiveKind(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
catID := electronicsCategoryID(t, s)
|
||||||
|
|
||||||
|
created, err := s.CreateProduct(ctx, "tester", ProductInput{
|
||||||
|
Name: "测试手机 " + randomHex(6),
|
||||||
|
CategoryID: &catID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create product: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _, _ = s.pool.Exec(ctx, "DELETE FROM product WHERE id = $1", created.ID) })
|
||||||
|
|
||||||
|
if created.ArchiveKind != "electronics" {
|
||||||
|
t.Fatalf("archive_kind = %q, want electronics", created.ArchiveKind)
|
||||||
|
}
|
||||||
|
// Food-only completeness fields must not be required for electronics.
|
||||||
|
if contains(created.Missing, "nutriments") || contains(created.Missing, "ingredients") {
|
||||||
|
t.Fatalf("electronics product should not require food fields: missing=%v", created.Missing)
|
||||||
|
}
|
||||||
|
// Qualified spec fields should appear as missing while empty.
|
||||||
|
for _, k := range []string{"model_number", "ccc_cert", "screen_size"} {
|
||||||
|
if !contains(created.Missing, k) {
|
||||||
|
t.Fatalf("expected %q in missing, got %v", k, created.Missing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scoreBefore := created.QualityScore
|
||||||
|
|
||||||
|
gtin := "69" + randomHex(11)
|
||||||
|
brand := "TestPhoneCo"
|
||||||
|
updated, err := s.UpdateProduct(ctx, created.ID, "tester", ProductInput{
|
||||||
|
Name: created.Name,
|
||||||
|
GTIN: >in,
|
||||||
|
BrandName: &brand,
|
||||||
|
CategoryID: &catID,
|
||||||
|
Status: "active",
|
||||||
|
Attributes: map[string]any{
|
||||||
|
"model_number": "X-100",
|
||||||
|
"ccc_cert": "2024010101234567",
|
||||||
|
"screen_size": "6.1",
|
||||||
|
"color": "黑色",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("update product: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := updated.Attributes["model_number"]; got != "X-100" {
|
||||||
|
t.Fatalf("attributes not persisted: %v", updated.Attributes)
|
||||||
|
}
|
||||||
|
for _, k := range []string{"model_number", "ccc_cert", "screen_size"} {
|
||||||
|
if contains(updated.Missing, k) {
|
||||||
|
t.Fatalf("%q should be filled, still missing: %v", k, updated.Missing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if updated.QualityScore <= scoreBefore {
|
||||||
|
t.Fatalf("quality should rise after filling fields: before=%v after=%v", scoreBefore, updated.QualityScore)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package adminstore
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"math"
|
"math"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -58,35 +59,56 @@ func (s *Store) computeQuality(ctx context.Context, q queryer, productID string)
|
|||||||
var netCanonical *float64
|
var netCanonical *float64
|
||||||
var ingredients *string
|
var ingredients *string
|
||||||
var hasNutri, hasImage bool
|
var hasNutri, hasImage bool
|
||||||
|
var kind string
|
||||||
|
var attributes []byte
|
||||||
err := q.QueryRow(ctx, `
|
err := q.QueryRow(ctx, `
|
||||||
SELECT p.name, p.gtin, p.brand_id, p.category_id, p.net_content_canonical,
|
SELECT p.name, p.gtin, p.brand_id, p.category_id, p.net_content_canonical,
|
||||||
p.country_of_origin, f.ingredients_text,
|
p.country_of_origin, COALESCE(c.archive_kind, 'generic'), p.attributes,
|
||||||
|
f.ingredients_text,
|
||||||
(f.nutriments IS NOT NULL AND f.nutriments::text <> '{}'),
|
(f.nutriments IS NOT NULL AND f.nutriments::text <> '{}'),
|
||||||
EXISTS (SELECT 1 FROM product_image pi WHERE pi.product_id = p.id)
|
EXISTS (SELECT 1 FROM product_image pi WHERE pi.product_id = p.id)
|
||||||
FROM product p LEFT JOIN food_detail f ON f.product_id = p.id
|
FROM product p
|
||||||
|
LEFT JOIN category c ON c.id = p.category_id
|
||||||
|
LEFT JOIN food_detail f ON f.product_id = p.id
|
||||||
WHERE p.id = $1`, productID).Scan(
|
WHERE p.id = $1`, productID).Scan(
|
||||||
&name, >in, &brandID, &categoryID, &netCanonical, &country,
|
&name, >in, &brandID, &categoryID, &netCanonical, &country,
|
||||||
&ingredients, &hasNutri, &hasImage)
|
&kind, &attributes, &ingredients, &hasNutri, &hasImage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
attrs := map[string]any{}
|
||||||
|
if len(attributes) > 0 {
|
||||||
|
_ = json.Unmarshal(attributes, &attrs)
|
||||||
|
}
|
||||||
|
qualified, err := s.kindQualifiedKeys(ctx, s.pool)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
qkeys := qualified[kind]
|
||||||
|
|
||||||
|
known := map[string]bool{
|
||||||
|
"name": name != nil && *name != "",
|
||||||
|
"gtin": gtin != nil && *gtin != "",
|
||||||
|
"brand": brandID != nil,
|
||||||
|
"category": categoryID != nil,
|
||||||
|
"net_content": netCanonical != nil,
|
||||||
|
"country_of_origin": country != nil && *country != "",
|
||||||
|
"nutriments": hasNutri,
|
||||||
|
"ingredients": ingredients != nil && *ingredients != "",
|
||||||
|
"image": hasImage,
|
||||||
|
}
|
||||||
|
for _, k := range qkeys {
|
||||||
|
known[k] = attrPresent(attrs, k)
|
||||||
|
}
|
||||||
|
keys := completenessKeys(kind, qkeys)
|
||||||
present := 0
|
present := 0
|
||||||
bump := func(ok bool) {
|
for _, k := range keys {
|
||||||
if ok {
|
if known[k] {
|
||||||
present++
|
present++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
bump(name != nil && *name != "")
|
completeness := float64(present) / float64(len(keys))
|
||||||
bump(gtin != nil && *gtin != "")
|
|
||||||
bump(brandID != nil)
|
|
||||||
bump(categoryID != nil)
|
|
||||||
bump(netCanonical != nil)
|
|
||||||
bump(country != nil && *country != "")
|
|
||||||
bump(hasNutri)
|
|
||||||
bump(ingredients != nil && *ingredients != "")
|
|
||||||
bump(hasImage)
|
|
||||||
completeness := float64(present) / float64(len(CompletenessFields))
|
|
||||||
|
|
||||||
var sourceCount int
|
var sourceCount int
|
||||||
var sourceTrust *float64
|
var sourceTrust *float64
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ type ProductInput struct {
|
|||||||
NutritionBasis *string `json:"nutrition_basis"`
|
NutritionBasis *string `json:"nutrition_basis"`
|
||||||
ServingSize *string `json:"serving_size"`
|
ServingSize *string `json:"serving_size"`
|
||||||
NutriScore *string `json:"nutri_score"`
|
NutriScore *string `json:"nutri_score"`
|
||||||
|
// Attributes carries non-food spec values (driven by kind_field) for the
|
||||||
|
// generic archive kinds. Nil means "leave unchanged".
|
||||||
|
Attributes map[string]any `json:"attributes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func normBrand(name string) string { return strings.Join(strings.Fields(strings.ToLower(name)), " ") }
|
func normBrand(name string) string { return strings.Join(strings.Fields(strings.ToLower(name)), " ") }
|
||||||
@@ -86,10 +89,11 @@ func (s *Store) UpdateProduct(ctx context.Context, id, actor string, in ProductI
|
|||||||
brandID = &bid
|
brandID = &bid
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve category gpc brick code.
|
// Resolve category gpc brick code + archive kind.
|
||||||
var gpc *string
|
var gpc *string
|
||||||
|
kind := DefaultKind
|
||||||
if in.CategoryID != nil && *in.CategoryID != "" {
|
if in.CategoryID != nil && *in.CategoryID != "" {
|
||||||
if err := tx.QueryRow(ctx, "SELECT gpc_brick_code FROM category WHERE id = $1", *in.CategoryID).Scan(&gpc); err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
if err := tx.QueryRow(ctx, "SELECT gpc_brick_code, archive_kind FROM category WHERE id = $1", *in.CategoryID).Scan(&gpc, &kind); err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,19 +120,28 @@ WHERE id=$11`,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var nutriJSON []byte
|
// Non-food spec values live in product.attributes (nil means unchanged).
|
||||||
if in.Nutriments != nil {
|
if in.Attributes != nil {
|
||||||
nutriJSON, _ = json.Marshal(in.Nutriments)
|
attrJSON, _ := json.Marshal(in.Attributes)
|
||||||
|
if _, err = tx.Exec(ctx, "UPDATE product SET attributes=$1 WHERE id=$2", attrJSON, id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
allergens := in.Allergens
|
|
||||||
if allergens == nil {
|
if kind == FoodKind {
|
||||||
allergens = []string{}
|
var nutriJSON []byte
|
||||||
}
|
if in.Nutriments != nil {
|
||||||
additives := in.Additives
|
nutriJSON, _ = json.Marshal(in.Nutriments)
|
||||||
if additives == nil {
|
}
|
||||||
additives = []string{}
|
allergens := in.Allergens
|
||||||
}
|
if allergens == nil {
|
||||||
_, err = tx.Exec(ctx, `
|
allergens = []string{}
|
||||||
|
}
|
||||||
|
additives := in.Additives
|
||||||
|
if additives == nil {
|
||||||
|
additives = []string{}
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(ctx, `
|
||||||
INSERT INTO food_detail (product_id, ingredients_text, allergens, additives,
|
INSERT INTO food_detail (product_id, ingredients_text, allergens, additives,
|
||||||
nutriments, nutrition_basis, serving_size, nutri_score)
|
nutriments, nutrition_basis, serving_size, nutri_score)
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
|
||||||
@@ -140,10 +153,11 @@ ON CONFLICT (product_id) DO UPDATE SET
|
|||||||
nutrition_basis=EXCLUDED.nutrition_basis,
|
nutrition_basis=EXCLUDED.nutrition_basis,
|
||||||
serving_size=EXCLUDED.serving_size,
|
serving_size=EXCLUDED.serving_size,
|
||||||
nutri_score=EXCLUDED.nutri_score`,
|
nutri_score=EXCLUDED.nutri_score`,
|
||||||
id, in.IngredientsText, allergens, additives,
|
id, in.IngredientsText, allergens, additives,
|
||||||
nutriJSON, in.NutritionBasis, in.ServingSize, in.NutriScore)
|
nutriJSON, in.NutritionBasis, in.ServingSize, in.NutriScore)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := s.recomputeQualityTx(ctx, tx, id); err != nil {
|
if _, err := s.recomputeQualityTx(ctx, tx, id); err != nil {
|
||||||
@@ -284,6 +298,9 @@ func diffFields(a, b *ProductDetail) []string {
|
|||||||
add("nutrition_basis", strEq(a.NutritionBasis, b.NutritionBasis))
|
add("nutrition_basis", strEq(a.NutritionBasis, b.NutritionBasis))
|
||||||
add("serving_size", strEq(a.ServingSize, b.ServingSize))
|
add("serving_size", strEq(a.ServingSize, b.ServingSize))
|
||||||
add("nutri_score", strEq(a.NutriScore, b.NutriScore))
|
add("nutri_score", strEq(a.NutriScore, b.NutriScore))
|
||||||
|
aa, _ := json.Marshal(a.Attributes)
|
||||||
|
ab, _ := json.Marshal(b.Attributes)
|
||||||
|
add("attributes", string(aa) == string(ab))
|
||||||
return changed
|
return changed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -442,6 +459,7 @@ type Category struct {
|
|||||||
Level int `json:"level"`
|
Level int `json:"level"`
|
||||||
ParentID *string `json:"parent_id"`
|
ParentID *string `json:"parent_id"`
|
||||||
GPCBrickCode *string `json:"gpc_brick_code"`
|
GPCBrickCode *string `json:"gpc_brick_code"`
|
||||||
|
ArchiveKind string `json:"archive_kind"`
|
||||||
ProductCount int `json:"product_count"`
|
ProductCount int `json:"product_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -450,7 +468,7 @@ type Category struct {
|
|||||||
func (s *Store) ListCategories(ctx context.Context) ([]Category, error) {
|
func (s *Store) ListCategories(ctx context.Context) ([]Category, error) {
|
||||||
rows, err := s.pool.Query(ctx, `
|
rows, err := s.pool.Query(ctx, `
|
||||||
SELECT c.id, c.name_zh, c.name_en, c.path::text, c.level, c.parent_id::text,
|
SELECT c.id, c.name_zh, c.name_en, c.path::text, c.level, c.parent_id::text,
|
||||||
c.gpc_brick_code,
|
c.gpc_brick_code, c.archive_kind,
|
||||||
(SELECT count(*) FROM product p WHERE p.category_id = c.id) AS product_count
|
(SELECT count(*) FROM product p WHERE p.category_id = c.id) AS product_count
|
||||||
FROM category c
|
FROM category c
|
||||||
ORDER BY c.path`)
|
ORDER BY c.path`)
|
||||||
@@ -462,7 +480,7 @@ ORDER BY c.path`)
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var c Category
|
var c Category
|
||||||
if err := rows.Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level,
|
if err := rows.Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level,
|
||||||
&c.ParentID, &c.GPCBrickCode, &c.ProductCount); err != nil {
|
&c.ParentID, &c.GPCBrickCode, &c.ArchiveKind, &c.ProductCount); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
out = append(out, c)
|
out = append(out, c)
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ package store
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
@@ -56,6 +58,15 @@ type Barcode struct {
|
|||||||
IsPrimary bool `json:"is_primary"`
|
IsPrimary bool `json:"is_primary"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProductSpec is one labeled spec line for a non-food product, rendered from
|
||||||
|
// the product's attributes JSONB against its archive kind's field template.
|
||||||
|
type ProductSpec struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
Unit string `json:"unit,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// Product is the full public view of a product.
|
// Product is the full public view of a product.
|
||||||
type Product struct {
|
type Product struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -64,11 +75,13 @@ type Product struct {
|
|||||||
Brand *string `json:"brand"`
|
Brand *string `json:"brand"`
|
||||||
CategoryPath *string `json:"category_path"`
|
CategoryPath *string `json:"category_path"`
|
||||||
GPCBrickCode *string `json:"gpc_brick_code"`
|
GPCBrickCode *string `json:"gpc_brick_code"`
|
||||||
|
ArchiveKind string `json:"archive_kind"`
|
||||||
NetContentValue *float64 `json:"net_content_value"`
|
NetContentValue *float64 `json:"net_content_value"`
|
||||||
NetContentUnit *string `json:"net_content_unit"`
|
NetContentUnit *string `json:"net_content_unit"`
|
||||||
CountryOfOrigin *string `json:"country_of_origin"`
|
CountryOfOrigin *string `json:"country_of_origin"`
|
||||||
QualityScore float64 `json:"quality_score"`
|
QualityScore float64 `json:"quality_score"`
|
||||||
Barcodes []Barcode `json:"barcodes"`
|
Barcodes []Barcode `json:"barcodes"`
|
||||||
|
Specs []ProductSpec `json:"specs,omitempty"`
|
||||||
Nutriments map[string]any `json:"nutriments,omitempty"`
|
Nutriments map[string]any `json:"nutriments,omitempty"`
|
||||||
NutritionBasis *string `json:"nutrition_basis,omitempty"`
|
NutritionBasis *string `json:"nutrition_basis,omitempty"`
|
||||||
NutriScore *string `json:"nutri_score,omitempty"`
|
NutriScore *string `json:"nutri_score,omitempty"`
|
||||||
@@ -120,6 +133,7 @@ type SearchFilters struct {
|
|||||||
|
|
||||||
const productSelect = `
|
const productSelect = `
|
||||||
SELECT p.id, p.gtin, p.name, b.name, c.path::text, p.gpc_brick_code,
|
SELECT p.id, p.gtin, p.name, b.name, c.path::text, p.gpc_brick_code,
|
||||||
|
COALESCE(c.archive_kind, 'generic'), p.attributes,
|
||||||
p.net_content_value, p.net_content_unit, p.country_of_origin, p.quality_score,
|
p.net_content_value, p.net_content_unit, p.country_of_origin, p.quality_score,
|
||||||
f.nutriments, f.nutrition_basis, f.nutri_score, f.ingredients_text,
|
f.nutriments, f.nutrition_basis, f.nutri_score, f.ingredients_text,
|
||||||
f.allergens, f.additives
|
f.allergens, f.additives
|
||||||
@@ -129,21 +143,81 @@ LEFT JOIN category c ON c.id = p.category_id
|
|||||||
LEFT JOIN food_detail f ON f.product_id = p.id
|
LEFT JOIN food_detail f ON f.product_id = p.id
|
||||||
`
|
`
|
||||||
|
|
||||||
func scanProduct(row pgx.Row) (*Product, error) {
|
func scanProduct(row pgx.Row) (*Product, []byte, error) {
|
||||||
var p Product
|
var p Product
|
||||||
|
var attributes []byte
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
&p.ID, &p.GTIN, &p.Name, &p.Brand, &p.CategoryPath, &p.GPCBrickCode,
|
&p.ID, &p.GTIN, &p.Name, &p.Brand, &p.CategoryPath, &p.GPCBrickCode,
|
||||||
|
&p.ArchiveKind, &attributes,
|
||||||
&p.NetContentValue, &p.NetContentUnit, &p.CountryOfOrigin, &p.QualityScore,
|
&p.NetContentValue, &p.NetContentUnit, &p.CountryOfOrigin, &p.QualityScore,
|
||||||
&p.Nutriments, &p.NutritionBasis, &p.NutriScore, &p.Ingredients,
|
&p.Nutriments, &p.NutritionBasis, &p.NutriScore, &p.Ingredients,
|
||||||
&p.Allergens, &p.Additives,
|
&p.Allergens, &p.Additives,
|
||||||
)
|
)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, ErrNotFound
|
return nil, nil, ErrNotFound
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return &p, attributes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildSpecs renders the labeled, ordered spec list for a non-food product from
|
||||||
|
// its attributes JSONB against its archive kind's field template.
|
||||||
|
func (s *Store) buildSpecs(ctx context.Context, kind string, attributes []byte) ([]ProductSpec, error) {
|
||||||
|
if kind == "" || kind == "food" || len(attributes) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
attrs := map[string]any{}
|
||||||
|
if err := json.Unmarshal(attributes, &attrs); err != nil || len(attrs) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
rows, err := s.pool.Query(ctx,
|
||||||
|
"SELECT field_key, label_zh, COALESCE(unit, '') FROM kind_field WHERE kind = $1 ORDER BY sort_order, field_key", kind)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &p, nil
|
defer rows.Close()
|
||||||
|
specs := []ProductSpec{}
|
||||||
|
for rows.Next() {
|
||||||
|
var key, label, unit string
|
||||||
|
if err := rows.Scan(&key, &label, &unit); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v, ok := attrs[key]
|
||||||
|
if !ok || v == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val := stringifyAttr(v)
|
||||||
|
if val == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
specs = append(specs, ProductSpec{Key: key, Label: label, Value: val, Unit: unit})
|
||||||
|
}
|
||||||
|
return specs, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// stringifyAttr renders a JSON attribute value as display text.
|
||||||
|
func stringifyAttr(v any) string {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case string:
|
||||||
|
return t
|
||||||
|
case float64:
|
||||||
|
return strconv.FormatFloat(t, 'f', -1, 64)
|
||||||
|
case bool:
|
||||||
|
if t {
|
||||||
|
return "是"
|
||||||
|
}
|
||||||
|
return "否"
|
||||||
|
case []any:
|
||||||
|
parts := make([]string, 0, len(t))
|
||||||
|
for _, e := range t {
|
||||||
|
parts = append(parts, stringifyAttr(e))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "、")
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProductByGTIN looks up an active product by any of its barcodes.
|
// ProductByGTIN looks up an active product by any of its barcodes.
|
||||||
@@ -154,26 +228,32 @@ func (s *Store) ProductByGTIN(ctx context.Context, gtin string) (*Product, error
|
|||||||
SELECT 1 FROM product_barcode pb
|
SELECT 1 FROM product_barcode pb
|
||||||
WHERE pb.product_id = p.id AND pb.gtin = $1))
|
WHERE pb.product_id = p.id AND pb.gtin = $1))
|
||||||
LIMIT 1`, gtin)
|
LIMIT 1`, gtin)
|
||||||
p, err := scanProduct(row)
|
p, attrs, err := scanProduct(row)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if p.Specs, err = s.buildSpecs(ctx, p.ArchiveKind, attrs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return p, nil
|
return p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProductByID looks up a product by its UUID.
|
// ProductByID looks up a product by its UUID.
|
||||||
func (s *Store) ProductByID(ctx context.Context, id string) (*Product, error) {
|
func (s *Store) ProductByID(ctx context.Context, id string) (*Product, error) {
|
||||||
row := s.pool.QueryRow(ctx, productSelect+" WHERE p.id = $1", id)
|
row := s.pool.QueryRow(ctx, productSelect+" WHERE p.id = $1", id)
|
||||||
p, err := scanProduct(row)
|
p, attrs, err := scanProduct(row)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if p.Specs, err = s.buildSpecs(ctx, p.ArchiveKind, attrs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return p, nil
|
return p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Detach any products from the seeded 3C categories, then remove them.
|
||||||
|
UPDATE product SET category_id = NULL
|
||||||
|
WHERE category_id IN (SELECT id FROM category WHERE path <@ 'electronics');
|
||||||
|
|
||||||
|
DELETE FROM category WHERE path <@ 'electronics';
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS kind_field;
|
||||||
|
|
||||||
|
ALTER TABLE category DROP COLUMN IF EXISTS archive_kind;
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
-- Generic, extensible "archive kind" (档案模式) framework.
|
||||||
|
-- Instead of a dedicated detail table per domain (food/electronics/drug/...),
|
||||||
|
-- each category belongs to an archive_kind, and a metadata table (kind_field)
|
||||||
|
-- describes the editable spec fields for that kind. Non-food spec values live
|
||||||
|
-- in the existing product.attributes JSONB. Adding a new domain later (drug,
|
||||||
|
-- machinery, ...) is just: seed kind_field rows + a category subtree.
|
||||||
|
|
||||||
|
ALTER TABLE category ADD COLUMN archive_kind VARCHAR(24) NOT NULL DEFAULT 'generic';
|
||||||
|
|
||||||
|
-- The existing seeded tree is the food domain.
|
||||||
|
UPDATE category SET archive_kind = 'food' WHERE path <@ 'food';
|
||||||
|
|
||||||
|
-- Field template per archive kind: drives the dynamic admin form and the
|
||||||
|
-- kind-aware completeness/qualified computation.
|
||||||
|
CREATE TABLE kind_field (
|
||||||
|
kind VARCHAR(24) NOT NULL,
|
||||||
|
field_key VARCHAR(64) NOT NULL,
|
||||||
|
group_label TEXT NOT NULL DEFAULT '',
|
||||||
|
label_zh TEXT NOT NULL,
|
||||||
|
field_type VARCHAR(16) NOT NULL DEFAULT 'text',
|
||||||
|
unit TEXT,
|
||||||
|
options TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
placeholder TEXT,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
qualified BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
PRIMARY KEY (kind, field_key),
|
||||||
|
CONSTRAINT kind_field_type_chk CHECK (field_type IN ('text','number','textarea','select','list'))
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Seed the electronics (3C) field template.
|
||||||
|
INSERT INTO kind_field (kind, field_key, group_label, label_zh, field_type, unit, sort_order, qualified) VALUES
|
||||||
|
('electronics','model_number', '基础规格','型号', 'text', NULL, 10, true),
|
||||||
|
('electronics','ccc_cert', '基础规格','3C认证号(CCC)','text', NULL, 20, true),
|
||||||
|
('electronics','color', '基础规格','颜色', 'text', NULL, 30, false),
|
||||||
|
('electronics','release_year', '基础规格','发布年份', 'number', NULL, 40, false),
|
||||||
|
('electronics','warranty_months','基础规格','保修期', 'number', '月', 50, false),
|
||||||
|
('electronics','dimensions', '外形','尺寸(长x宽x高)', 'text', 'mm', 60, false),
|
||||||
|
('electronics','weight', '外形','重量', 'number', 'g', 70, false),
|
||||||
|
('electronics','power', '外形','电源/功率', 'text', NULL, 80, false),
|
||||||
|
('electronics','os', '关键参数','操作系统', 'text', NULL, 90, false),
|
||||||
|
('electronics','cpu', '关键参数','处理器', 'text', NULL, 100, false),
|
||||||
|
('electronics','ram', '关键参数','内存', 'text', NULL, 110, false),
|
||||||
|
('electronics','storage', '关键参数','存储', 'text', NULL, 120, false),
|
||||||
|
('electronics','screen_size', '关键参数','屏幕尺寸', 'text', NULL, 130, true),
|
||||||
|
('electronics','battery', '关键参数','电池容量', 'text', NULL, 140, false),
|
||||||
|
('electronics','ports', '关键参数','接口', 'text', NULL, 150, false);
|
||||||
|
|
||||||
|
-- Seed the 3C category tree.
|
||||||
|
INSERT INTO category (name_zh, name_en, parent_id, path, level, archive_kind)
|
||||||
|
VALUES ('电子数码', 'Electronics', NULL, 'electronics', 0, 'electronics');
|
||||||
|
|
||||||
|
INSERT INTO category (name_zh, name_en, parent_id, path, level, archive_kind)
|
||||||
|
SELECT v.name_zh, v.name_en, c.id, v.path::ltree, 1, 'electronics'
|
||||||
|
FROM (VALUES
|
||||||
|
('手机', 'Smartphone', 'electronics.phone'),
|
||||||
|
('笔记本电脑', 'Laptop', 'electronics.laptop'),
|
||||||
|
('平板电脑', 'Tablet', 'electronics.tablet'),
|
||||||
|
('智能手表', 'Smartwatch', 'electronics.watch'),
|
||||||
|
('耳机', 'Headphone', 'electronics.headphone'),
|
||||||
|
('相机', 'Camera', 'electronics.camera'),
|
||||||
|
('电视', 'TV', 'electronics.tv'),
|
||||||
|
('家用电器', 'Home appliance', 'electronics.appliance')
|
||||||
|
) AS v(name_zh, name_en, path)
|
||||||
|
JOIN category c ON c.path = 'electronics';
|
||||||
@@ -106,6 +106,23 @@ export default function ProductView({ id, onBack }: { id: string; onBack: () =>
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{p.specs && p.specs.length > 0 && (
|
||||||
|
<div className="bg-white border rounded-lg p-5 mt-4">
|
||||||
|
<h2 className="font-medium text-gray-700 mb-2">规格参数</h2>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
|
||||||
|
{p.specs.map((s) => (
|
||||||
|
<div key={s.key} className="bg-gray-50 rounded px-3 py-2">
|
||||||
|
<div className="text-gray-400 text-xs">{s.label}</div>
|
||||||
|
<div className="text-gray-800">
|
||||||
|
{s.value}
|
||||||
|
{s.unit ? ` ${s.unit}` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{nutriEntries.length > 0 && (
|
{nutriEntries.length > 0 && (
|
||||||
<div className="bg-white border rounded-lg p-5 mt-4">
|
<div className="bg-white border rounded-lg p-5 mt-4">
|
||||||
<h2 className="font-medium text-gray-700 mb-2">
|
<h2 className="font-medium text-gray-700 mb-2">
|
||||||
|
|||||||
@@ -17,6 +17,13 @@ export interface Barcode {
|
|||||||
is_primary: boolean;
|
is_primary: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProductSpec {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
unit?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Product {
|
export interface Product {
|
||||||
id: string;
|
id: string;
|
||||||
gtin: string | null;
|
gtin: string | null;
|
||||||
@@ -24,6 +31,8 @@ export interface Product {
|
|||||||
name: string;
|
name: string;
|
||||||
brand: string | null;
|
brand: string | null;
|
||||||
category_path: string | null;
|
category_path: string | null;
|
||||||
|
archive_kind?: string;
|
||||||
|
specs?: ProductSpec[] | null;
|
||||||
net_content_value: number | null;
|
net_content_value: number | null;
|
||||||
net_content_unit: string | null;
|
net_content_unit: string | null;
|
||||||
country_of_origin: string | null;
|
country_of_origin: string | null;
|
||||||
|
|||||||
Reference in New Issue
Block a user