feat: 可扩展档案模式框架 + 内置 3C(电子) 模式
- 新增 category.archive_kind 与 kind_field 字段模板表(迁移 0010) - 种子 electronics 字段模板 + 3C 品类树(手机/笔记本/平板等) - 后端按档案模式动态计算完整度/合格:食品沿用 food_detail, 其它模式走 product.attributes + kind_field - 新增 GET /api/kind-fields?kind= 接口 - 后台编辑页按品类模式动态渲染规格参数表单 - 公开详情页/接口输出带标签的规格表 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
@@ -84,6 +84,7 @@ func (h *Handler) Router() http.Handler {
|
||||
r.Put("/api/brands/{id}", h.UpdateBrand)
|
||||
r.Post("/api/brands/{id}/merge", h.MergeBrands)
|
||||
r.Delete("/api/brands/{id}", h.DeleteBrand)
|
||||
r.Get("/api/kind-fields", h.ListKindFields)
|
||||
r.Get("/api/categories", h.ListCategories)
|
||||
r.Post("/api/categories", h.CreateCategory)
|
||||
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})
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
|
||||
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
|
||||
}
|
||||
|
||||
qualified, err := s.kindQualifiedKeys(ctx, s.pool)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
args = append(args, limit, offset)
|
||||
sql := `
|
||||
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.category_id IS NOT NULL) AS has_cat,
|
||||
(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() {
|
||||
var r ProductRow
|
||||
var hasBrand, hasCat, hasNet, hasCountry, hasNutri, hasIng, hasImg bool
|
||||
var kind string
|
||||
var attributes []byte
|
||||
var updated time.Time
|
||||
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 {
|
||||
return nil, 0, err
|
||||
}
|
||||
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{
|
||||
"name": r.Name != "",
|
||||
"gtin": r.GTIN != nil && *r.GTIN != "",
|
||||
@@ -109,8 +122,11 @@ LEFT JOIN food_detail f ON f.product_id = p.id ` + where +
|
||||
"ingredients": hasIng,
|
||||
"image": hasImg,
|
||||
}
|
||||
for _, k := range qkeys {
|
||||
present[k] = attrPresent(attrs, k)
|
||||
}
|
||||
r.Missing = []string{}
|
||||
for _, f := range CompletenessFields {
|
||||
for _, f := range completenessKeys(kind, qkeys) {
|
||||
if !present[f] {
|
||||
r.Missing = append(r.Missing, f)
|
||||
}
|
||||
@@ -150,6 +166,8 @@ type ProductDetail struct {
|
||||
Brand *string `json:"brand"`
|
||||
CategoryID *string `json:"category_id"`
|
||||
CategoryPath *string `json:"category_path"`
|
||||
ArchiveKind string `json:"archive_kind"`
|
||||
Attributes map[string]any `json:"attributes"`
|
||||
NetContentValue *float64 `json:"net_content_value"`
|
||||
NetContentUnit *string `json:"net_content_unit"`
|
||||
CountryOfOrigin *string `json:"country_of_origin"`
|
||||
@@ -173,9 +191,11 @@ type ProductDetail struct {
|
||||
func (s *Store) GetProduct(ctx context.Context, id string) (*ProductDetail, error) {
|
||||
var d ProductDetail
|
||||
var nutriments []byte
|
||||
var attributes []byte
|
||||
var updated time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
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.quality_score, p.updated_at,
|
||||
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
|
||||
WHERE p.id = $1`, id).Scan(
|
||||
&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.QualityScore, &updated,
|
||||
&d.IngredientsText, &d.Allergens, &d.Additives, &nutriments,
|
||||
@@ -198,6 +219,10 @@ WHERE p.id = $1`, id).Scan(
|
||||
return nil, err
|
||||
}
|
||||
d.UpdatedAt = updated.Format(time.RFC3339)
|
||||
d.Attributes = map[string]any{}
|
||||
if len(attributes) > 0 {
|
||||
_ = json.Unmarshal(attributes, &d.Attributes)
|
||||
}
|
||||
if len(nutriments) > 0 {
|
||||
_ = json.Unmarshal(nutriments, &d.Nutriments)
|
||||
}
|
||||
@@ -226,11 +251,15 @@ WHERE p.id = $1`, id).Scan(
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func missingFromDetail(d *ProductDetail) []string {
|
||||
func missingFromDetail(d *ProductDetail, qualifiedAttrKeys []string) []string {
|
||||
present := map[string]bool{
|
||||
"name": d.Name != "",
|
||||
"gtin": d.GTIN != nil && *d.GTIN != "",
|
||||
@@ -242,8 +271,11 @@ func missingFromDetail(d *ProductDetail) []string {
|
||||
"ingredients": d.IngredientsText != nil && *d.IngredientsText != "",
|
||||
"image": len(d.Images) > 0,
|
||||
}
|
||||
for _, k := range qualifiedAttrKeys {
|
||||
present[k] = attrPresent(d.Attributes, k)
|
||||
}
|
||||
missing := []string{}
|
||||
for _, f := range CompletenessFields {
|
||||
for _, f := range completenessKeys(d.ArchiveKind, qualifiedAttrKeys) {
|
||||
if !present[f] {
|
||||
missing = append(missing, f)
|
||||
}
|
||||
|
||||
@@ -96,11 +96,12 @@ func (s *Store) CreateCategory(ctx context.Context, actor string, in CategoryInp
|
||||
|
||||
parentPath := ""
|
||||
parentLevel := -1
|
||||
kind := DefaultKind
|
||||
var parentID *string
|
||||
if pid := trimPtr(in.ParentID); pid != nil {
|
||||
var path string
|
||||
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) {
|
||||
return nil, ErrInvalidParent
|
||||
}
|
||||
@@ -119,11 +120,11 @@ func (s *Store) CreateCategory(ctx context.Context, actor string, in CategoryInp
|
||||
|
||||
var c Category
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO category (name_zh, name_en, parent_id, path, gpc_brick_code, level)
|
||||
VALUES ($1, $2, $3, $4::ltree, $5, $6)
|
||||
RETURNING id, name_zh, name_en, path::text, level, parent_id::text, gpc_brick_code, 0`,
|
||||
name, trimPtr(in.NameEN), parentID, path, trimPtr(in.GPCBrickCode), level).
|
||||
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ProductCount)
|
||||
INSERT INTO category (name_zh, name_en, parent_id, path, gpc_brick_code, level, archive_kind)
|
||||
VALUES ($1, $2, $3, $4::ltree, $5, $6, $7)
|
||||
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, kind).
|
||||
Scan(&c.ID, &c.NameZH, &c.NameEN, &c.Path, &c.Level, &c.ParentID, &c.GPCBrickCode, &c.ArchiveKind, &c.ProductCount)
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrDuplicatePath
|
||||
}
|
||||
@@ -273,10 +274,10 @@ func (s *Store) getCategory(ctx context.Context, id string) (*Category, error) {
|
||||
var c Category
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
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)
|
||||
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) {
|
||||
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 (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
@@ -58,35 +59,56 @@ func (s *Store) computeQuality(ctx context.Context, q queryer, productID string)
|
||||
var netCanonical *float64
|
||||
var ingredients *string
|
||||
var hasNutri, hasImage bool
|
||||
var kind string
|
||||
var attributes []byte
|
||||
err := q.QueryRow(ctx, `
|
||||
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 <> '{}'),
|
||||
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(
|
||||
&name, >in, &brandID, &categoryID, &netCanonical, &country,
|
||||
&ingredients, &hasNutri, &hasImage)
|
||||
&kind, &attributes, &ingredients, &hasNutri, &hasImage)
|
||||
if err != nil {
|
||||
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
|
||||
bump := func(ok bool) {
|
||||
if ok {
|
||||
for _, k := range keys {
|
||||
if known[k] {
|
||||
present++
|
||||
}
|
||||
}
|
||||
bump(name != nil && *name != "")
|
||||
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))
|
||||
completeness := float64(present) / float64(len(keys))
|
||||
|
||||
var sourceCount int
|
||||
var sourceTrust *float64
|
||||
|
||||
@@ -27,6 +27,9 @@ type ProductInput struct {
|
||||
NutritionBasis *string `json:"nutrition_basis"`
|
||||
ServingSize *string `json:"serving_size"`
|
||||
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)), " ") }
|
||||
@@ -86,10 +89,11 @@ func (s *Store) UpdateProduct(ctx context.Context, id, actor string, in ProductI
|
||||
brandID = &bid
|
||||
}
|
||||
|
||||
// Resolve category gpc brick code.
|
||||
// Resolve category gpc brick code + archive kind.
|
||||
var gpc *string
|
||||
kind := DefaultKind
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -116,19 +120,28 @@ WHERE id=$11`,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var nutriJSON []byte
|
||||
if in.Nutriments != nil {
|
||||
nutriJSON, _ = json.Marshal(in.Nutriments)
|
||||
// Non-food spec values live in product.attributes (nil means unchanged).
|
||||
if in.Attributes != nil {
|
||||
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 {
|
||||
allergens = []string{}
|
||||
}
|
||||
additives := in.Additives
|
||||
if additives == nil {
|
||||
additives = []string{}
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
|
||||
if kind == FoodKind {
|
||||
var nutriJSON []byte
|
||||
if in.Nutriments != nil {
|
||||
nutriJSON, _ = json.Marshal(in.Nutriments)
|
||||
}
|
||||
allergens := in.Allergens
|
||||
if allergens == nil {
|
||||
allergens = []string{}
|
||||
}
|
||||
additives := in.Additives
|
||||
if additives == nil {
|
||||
additives = []string{}
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO food_detail (product_id, ingredients_text, allergens, additives,
|
||||
nutriments, nutrition_basis, serving_size, nutri_score)
|
||||
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,
|
||||
serving_size=EXCLUDED.serving_size,
|
||||
nutri_score=EXCLUDED.nutri_score`,
|
||||
id, in.IngredientsText, allergens, additives,
|
||||
nutriJSON, in.NutritionBasis, in.ServingSize, in.NutriScore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
id, in.IngredientsText, allergens, additives,
|
||||
nutriJSON, in.NutritionBasis, in.ServingSize, in.NutriScore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
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("serving_size", strEq(a.ServingSize, b.ServingSize))
|
||||
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
|
||||
}
|
||||
|
||||
@@ -442,6 +459,7 @@ type Category struct {
|
||||
Level int `json:"level"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
GPCBrickCode *string `json:"gpc_brick_code"`
|
||||
ArchiveKind string `json:"archive_kind"`
|
||||
ProductCount int `json:"product_count"`
|
||||
}
|
||||
|
||||
@@ -450,7 +468,7 @@ type Category struct {
|
||||
func (s *Store) ListCategories(ctx context.Context) ([]Category, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
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
|
||||
FROM category c
|
||||
ORDER BY c.path`)
|
||||
@@ -462,7 +480,7 @@ ORDER BY c.path`)
|
||||
for rows.Next() {
|
||||
var c Category
|
||||
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
|
||||
}
|
||||
out = append(out, c)
|
||||
|
||||
@@ -4,8 +4,10 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -56,6 +58,15 @@ type Barcode struct {
|
||||
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.
|
||||
type Product struct {
|
||||
ID string `json:"id"`
|
||||
@@ -64,11 +75,13 @@ type Product struct {
|
||||
Brand *string `json:"brand"`
|
||||
CategoryPath *string `json:"category_path"`
|
||||
GPCBrickCode *string `json:"gpc_brick_code"`
|
||||
ArchiveKind string `json:"archive_kind"`
|
||||
NetContentValue *float64 `json:"net_content_value"`
|
||||
NetContentUnit *string `json:"net_content_unit"`
|
||||
CountryOfOrigin *string `json:"country_of_origin"`
|
||||
QualityScore float64 `json:"quality_score"`
|
||||
Barcodes []Barcode `json:"barcodes"`
|
||||
Specs []ProductSpec `json:"specs,omitempty"`
|
||||
Nutriments map[string]any `json:"nutriments,omitempty"`
|
||||
NutritionBasis *string `json:"nutrition_basis,omitempty"`
|
||||
NutriScore *string `json:"nutri_score,omitempty"`
|
||||
@@ -120,6 +133,7 @@ type SearchFilters struct {
|
||||
|
||||
const productSelect = `
|
||||
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,
|
||||
f.nutriments, f.nutrition_basis, f.nutri_score, f.ingredients_text,
|
||||
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
|
||||
`
|
||||
|
||||
func scanProduct(row pgx.Row) (*Product, error) {
|
||||
func scanProduct(row pgx.Row) (*Product, []byte, error) {
|
||||
var p Product
|
||||
var attributes []byte
|
||||
err := row.Scan(
|
||||
&p.ID, &p.GTIN, &p.Name, &p.Brand, &p.CategoryPath, &p.GPCBrickCode,
|
||||
&p.ArchiveKind, &attributes,
|
||||
&p.NetContentValue, &p.NetContentUnit, &p.CountryOfOrigin, &p.QualityScore,
|
||||
&p.Nutriments, &p.NutritionBasis, &p.NutriScore, &p.Ingredients,
|
||||
&p.Allergens, &p.Additives,
|
||||
)
|
||||
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 {
|
||||
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.
|
||||
@@ -154,26 +228,32 @@ func (s *Store) ProductByGTIN(ctx context.Context, gtin string) (*Product, error
|
||||
SELECT 1 FROM product_barcode pb
|
||||
WHERE pb.product_id = p.id AND pb.gtin = $1))
|
||||
LIMIT 1`, gtin)
|
||||
p, err := scanProduct(row)
|
||||
p, attrs, err := scanProduct(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Specs, err = s.buildSpecs(ctx, p.ArchiveKind, attrs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// ProductByID looks up a product by its UUID.
|
||||
func (s *Store) ProductByID(ctx context.Context, id string) (*Product, error) {
|
||||
row := s.pool.QueryRow(ctx, productSelect+" WHERE p.id = $1", id)
|
||||
p, err := scanProduct(row)
|
||||
p, attrs, err := scanProduct(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Barcodes, err = s.ProductBarcodes(ctx, p.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Specs, err = s.buildSpecs(ctx, p.ArchiveKind, attrs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user