fix(publish): 最终审查修复波——迁移索引口径 / 入库计数 / 仓储证据
C1(关键):2026-09-22-03 的街拍实体键索引改用最终表达式 (city, year, COALESCE(title, '')),与体检及 StreetSnapEntityState 口径一致。 此前索引按 (city, year) 比体检更窄,同城同年多专题的合法数据会通过体检、 再由索引抛原生 23505;04 退化为幂等兜底并在注释说明真正常态由 03 承载。 新增 db/migrations/README.md,写清迁移链执行顺序与各步前提/不可逆点。 I1:processRunway 的 image_count 改为按实际落库主图行数(countMainImages), 不再用 len(p.Looks)(空主图 / sha1 重复会被跳过,导致计数偏大且不再自愈)。 补 service 单测与「入库后 image_count == 存活主图行数」的 DB 断言。 I2:三个迁移文件不再把已删除的一次性搬迁脚本写成硬前置,改为写明取回方式 (git show c4bafc5:scripts/migrate_single_table/main.go,并须在旧代码树上运行)。 I3:新增 SetRecordStatus / SetStreetRecordStatus 仓储集成测试: pending 经仓储通过后在公开视图可见、驳回后不可见、不存在的 id 返回 ErrNotFound。 Minor:修正锁不住口径的走秀 image_count 测试(改为删主图、留细节图); 修正去重注释与事实不符(含 FindNearDuplicateImage 注释); ListRecords / ListStreetRecords 改用 Scope 杜绝 Count 后复用 *gorm.DB; dbtool 视图改 CREATE OR REPLACE 并重跑 dump(仍 4 视图、无草稿表); 删除挂在 Popular 上的「IDs 返回…」注释;README 改为单表 + status 现状; SetRecordStatus 注释写明有意不校验前置状态;规格补两条已知不一致。
This commit is contained in:
@ -81,7 +81,7 @@ internal/
|
||||
### 2.3 管理后台(8092)
|
||||
|
||||
- `/admin/login`、`/admin/logout`:后台登录(HttpOnly cookie 会话)。
|
||||
- `/admin/*`:品牌 / 走秀 / 街拍管理、草稿审核(通过晋升正式表 / 驳回)、入库任务监控与重试、用户管理(提级 VIP)。
|
||||
- `/admin/*`:品牌 / 走秀 / 街拍管理、内容审核(单表 + `status`:通过置 `published`、驳回置 `rejected`)、入库任务监控与重试、用户管理(提级 VIP)。
|
||||
- `/admin/internal/ingest`:爬虫上报入口,**HMAC-SHA256 验签 + nonce 防重放**(`INGEST_SECRET`)。
|
||||
|
||||
---
|
||||
@ -95,7 +95,7 @@ internal/
|
||||
- key 以内容 sha1 命名 → 重爬天然幂等、不产生孤儿文件。
|
||||
- 删除图集时按**跨表引用计数**判定孤儿,归零才真删对象;删除动作异步入队,不阻塞请求。
|
||||
- **图片去重**:`phash`(dHash 向量)近重复标记 + HNSW 索引加速;存储 key 用内容 sha1 寻址(重爬幂等、不产生孤儿文件)。
|
||||
- **爬虫入库管线**:`ingest_jobs` 队列 + worker(`SELECT ... FOR UPDATE SKIP LOCKED` 多实例安全)异步下载图、补季节码、写草稿表;后台人工审核通过后晋升正式表。失败按指数退避重试,单图失败整任务回滚。
|
||||
- **爬虫入库管线**:`ingest_jobs` 队列 + worker(`SELECT ... FOR UPDATE SKIP LOCKED` 多实例安全)异步下载图、补季节码、**直写正式表**(`status=pending`,已无草稿表);后台人工审核只改状态(`published` / `rejected`),不重建图片;公开读走 `public_*` 只读视图,未发布内容结构性不可见。失败按指数退避重试,单图失败整任务回滚。
|
||||
- **图片质量模型**(2026-09-11 起):所有用户同质量,统一走 CoreIX 公开样式(详情 `high` / 列表 `thumb`),付费墙已取消。
|
||||
|
||||
---
|
||||
@ -174,7 +174,7 @@ backend/
|
||||
│ └── dbdiag/ # 数据库诊断
|
||||
├── internal/
|
||||
│ ├── config/ # 配置加载
|
||||
│ ├── model/ # 实体(brand / runway / street_snap / user / 草稿 / ingest)
|
||||
│ ├── model/ # 实体(brand / runway / street_snap / user / ingest)
|
||||
│ ├── database/ # 连接池(结构由 dbtool 导出的 SQL 维护,不做 DDL)
|
||||
│ ├── repository/ # 数据访问接口 + GORM 实现
|
||||
│ ├── service/ # 业务逻辑
|
||||
|
||||
@ -476,10 +476,16 @@ func topoSortViews(names []string, deps map[string][]string) ([]string, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// writeCreateView 输出一个视图的 CREATE VIEW。
|
||||
// writeCreateView 输出一个视图的 CREATE OR REPLACE VIEW。
|
||||
// 定义来自 pg_get_viewdef(形如「 SELECT ...」),去掉前导空白后接到 AS 之后即可。
|
||||
//
|
||||
// 用 OR REPLACE 而非裸 CREATE:非 -clean 产物里其余语句都幂等(表 IF NOT EXISTS、
|
||||
// 约束/索引 DROP ... IF EXISTS、索引 IF NOT EXISTS),视图也应对齐,重复灌入不报
|
||||
// relation already exists。
|
||||
// 注意 OR REPLACE 不允许改变已有视图的列名 / 列序 / 类型 —— 视图列集被 SELECT * 冻结,
|
||||
// 给基表加列必须同批重建视图(见 db/migrations/2026-09-22-01 的备注)。
|
||||
func writeCreateView(w *bufio.Writer, v viewDef) {
|
||||
fmt.Fprintf(w, "CREATE VIEW %s AS\n%s;\n\n", qname(v.Name), v.Def)
|
||||
fmt.Fprintf(w, "CREATE OR REPLACE VIEW %s AS\n%s;\n\n", qname(v.Name), v.Def)
|
||||
}
|
||||
|
||||
// writeHeader 写文件头与几个会话设置。
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
-- 单表发布模型(方案 2):取消草稿表,审核态由 status 承载,公开读走只读视图。
|
||||
--
|
||||
-- 本文件只做三件事:加列 / 存量行置已发布 / 建视图。幂等,可重复执行。
|
||||
-- 数据搬迁见 scripts/migrate_single_table;删草稿表见 2026-09-22-02-drop-draft-tables.sql。
|
||||
-- 数据搬迁由一次性脚本 scripts/migrate_single_table/main.go 完成。该脚本已随本次改造从工作树删除
|
||||
--(它 import 已删除的草稿模型,无法在改造后的代码树上编译);取回方式与执行顺序见本目录 README.md。
|
||||
-- 删草稿表见 2026-09-22-02-drop-draft-tables.sql。
|
||||
|
||||
-- 1) 正式表补审核态与溯源列。默认 'pending' 是刻意的(fail-closed):
|
||||
-- 任何漏赋值的行默认不可见,而不是意外对外发布。
|
||||
@ -19,7 +21,7 @@ ALTER TABLE street_snaps
|
||||
|
||||
-- 2) 存量行置已发布**不在本文件里**:它是数据变更且只能执行一次,见同目录
|
||||
-- 2026-09-22-01b-publish-existing-rows.sql。
|
||||
-- 为什么必须拆开:数据搬迁(scripts/migrate_single_table)会把 pending 草稿连原 created_at
|
||||
-- 为什么必须拆开:数据搬迁(scripts/migrate_single_table/main.go)会把 pending 草稿连原 created_at
|
||||
-- 一起搬进正式表;若本文件含那条 UPDATE 且被重复执行(测试每次都会跑),
|
||||
-- 这些待审内容会被误刷成已发布 —— 恰好是本设计要防的泄漏。
|
||||
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
-- 一次性数据迁移:把存量正式行视为已发布。
|
||||
--
|
||||
-- ⚠️ 只执行一次;必须在部署本计划的新代码之前、且在 scripts/migrate_single_table 之前执行。
|
||||
-- ⚠️ 只执行一次;必须在部署本计划的新代码之前、且在一次性搬迁脚本
|
||||
-- scripts/migrate_single_table/main.go 之前执行。
|
||||
-- 该脚本已随本次改造从工作树删除(它 import 已删除的草稿模型);取回方式见本目录 README.md。
|
||||
-- 为什么单独成文件而不放进可重复执行的 2026-09-22-01:
|
||||
-- 数据搬迁会把 pending 草稿连同旧的 created_at 一起搬进正式表;
|
||||
-- 若这条 UPDATE 可被重复执行(集成测试每次都会跑 01 号文件),
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
-- 单表发布模型收尾:删除 4 张草稿表。
|
||||
--
|
||||
-- ⚠️ 执行前置条件:scripts/migrate_single_table 已跑完且校验通过(否则草稿数据会丢失)。
|
||||
-- ⚠️ 执行前置条件:一次性搬迁脚本 scripts/migrate_single_table/main.go(已随本次改造从工作树删除,
|
||||
-- 取回方式见本目录 README.md)已跑完且校验通过 —— 否则草稿数据会丢失。
|
||||
-- 本迁移不可逆:执行前请确认 db/backups 有可用备份。
|
||||
|
||||
DROP TABLE IF EXISTS brand_runway_draft_images;
|
||||
|
||||
@ -35,5 +35,13 @@ END $$;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_br_entity
|
||||
ON brand_runways (brand_id, season_code, collection_type) WHERE is_deleted = 0;
|
||||
|
||||
-- 索引表达式必须与上面的体检、以及 StreetSnapEntityState 的查重口径**逐字一致**:
|
||||
-- (city, year, COALESCE(title, ''))。早期版本这里误建成 (city, year) —— 比体检更窄,
|
||||
-- 于是体检放行「同城同年不同专题」的合法数据后,建索引才抛原生 23505
|
||||
-- (could not create unique index ... duplicate key)。COALESCE(title, '') 的取舍见 2026-09-22-04。
|
||||
--
|
||||
-- ⚠️ CREATE UNIQUE INDEX IF NOT EXISTS 只检查**索引名**是否存在:若库里已有一个同名的
|
||||
-- 旧 (city, year) 索引,本句会静默跳过、留下错误结构(这正是它一度掩盖问题的原因)。
|
||||
-- 纠正这类存量库由 2026-09-22-04 承担;全新库 / 重复执行由本文件承载最终表达式。
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_ss_entity
|
||||
ON street_snaps (city, year) WHERE is_deleted = 0;
|
||||
ON street_snaps (city, year, COALESCE(title, '')) WHERE is_deleted = 0;
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
-- 街拍实体键细化:由 (city, year) 改为 (city, year, title)。
|
||||
--
|
||||
-- ⚠️ 本文件是**幂等兜底**,最终表达式的常态承载在 2026-09-22-03(它已直接建同一表达式索引)。
|
||||
-- 之所以必须保留:03 的 `CREATE UNIQUE INDEX IF NOT EXISTS` 只按**索引名**判断存在性,
|
||||
-- 遇到「同名但口径更窄的旧 (city, year) 索引」会静默跳过、留下错误结构 ——
|
||||
-- 只有本文件的 `DROP INDEX IF EXISTS` + 重建能纠正这类存量库。
|
||||
-- 全新库上重跑本文件也只是 DROP 后原样重建,幂等无害。
|
||||
--
|
||||
-- 背景:同城同年可能有多个专题(如 London 2027 Day 2 / Day 3),原键把它们判为同一实体,
|
||||
-- 导致唯一索引不允许共存、且入库查重把第二个专题当成重复直接放弃。
|
||||
--
|
||||
|
||||
55
db/migrations/README.md
Normal file
55
db/migrations/README.md
Normal file
@ -0,0 +1,55 @@
|
||||
# 数据库迁移
|
||||
|
||||
本目录的 `.sql` 是**手工一次性迁移**(服务启动不做 DDL,结构由 `dbtool` 导出的 `db_dump.sql` 维护)。
|
||||
命名规则 `日期-序号-主题.sql`,**按文件名顺序执行**。
|
||||
|
||||
- 全新库:直接用 `db_dump.sql` 建库(见根目录 `README.md`「数据库」一节),**不需要**跑这些迁移。
|
||||
- 存量库升级:按下文顺序执行;大多语句幂等,但**数据变更类不可重放**(见各步说明)。
|
||||
|
||||
---
|
||||
|
||||
## 一、2026-09-21 系列(街拍主副图 / 重复检测 / 来源幂等)
|
||||
|
||||
| 顺序 | 文件 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 1 | `2026-09-21-01-street-main-detail.sql` | 草稿表与正式图片表加 `is_detail` / `parent_image_id`。全 `IF NOT EXISTS`,幂等。 |
|
||||
| 2 | `2026-09-21-02-duplicate-review.sql` | 新建 `image_duplicates`,街拍正式表加 `source` / `source_url` 及部分唯一索引 `uq_ss_source`。幂等。 |
|
||||
| 3 | `2026-09-21-03-ingest-source-idempotency.sql` | 两张**草稿表**加 `source` / `source_url` 及部分唯一索引。幂等。这些列会随 2026-09-22-02 删草稿表一并消失。 |
|
||||
|
||||
这三步属于更早的改造;对已经过它们的库重放无害。
|
||||
|
||||
---
|
||||
|
||||
## 二、2026-09-22 单表发布(草稿表 → 单表 + `status` + 公开只读视图)
|
||||
|
||||
**执行顺序:`01 → 01b → 搬迁脚本 → 02 → 03 → 04`**
|
||||
|
||||
| 顺序 | 对象 | 前提 / 幂等 / 不可逆点 |
|
||||
| --- | --- | --- |
|
||||
| 1 | `2026-09-22-01-single-table-publish.sql` | 给 `brand_runways` / `street_snaps` 加 `status` 等列、建状态索引、建 4 个 `public_*` 视图。**幂等**,可重复执行(集成测试每次都会跑它)。 |
|
||||
| 2 | `2026-09-22-01b-publish-existing-rows.sql` | 把存量正式行置 `published`。**只能执行一次**;且必须在新代码部署**之前**、搬迁脚本**之前**执行。理由:搬迁会把 pending 草稿连同旧 `created_at` 一起搬进来,若这条 UPDATE 可重放,待审内容会被误刷成已发布(本设计要防的就是这个泄漏)。 |
|
||||
| 3 | 搬迁脚本 `<见下>` | 把草稿表数据搬进正式表。**一次性**;先 `-dry-run` + 守恒校验,**校验不过绝不进入第 4 步**。 |
|
||||
| 4 | `2026-09-22-02-drop-draft-tables.sql` | 删除 4 张草稿表。**不可逆**;前提是第 3 步校验通过,且 `db/backups/` 有可用备份。 |
|
||||
| 5 | `2026-09-22-03-entity-key-unique.sql` | 实体键部分唯一索引 `uq_br_entity` / `uq_ss_entity`(街拍为最终表达式 `(city, year, COALESCE(title,''))`)。**幂等**;建索引前先体检,有重复就报可读错误而非原生 23505。 |
|
||||
| 6 | `2026-09-22-04-street-entity-key-title.sql` | 街拍索引的**幂等兜底**:`DROP INDEX IF EXISTS uq_ss_entity` 后按最终表达式重建。常态由 03 承载;本文件专治「库里已有同名旧 `(city, year)` 索引、03 因 `IF NOT EXISTS` 静默跳过」的存量库。 |
|
||||
|
||||
### 搬迁脚本的取回方式
|
||||
|
||||
`scripts/migrate_single_table/main.go` 是一次性工具,已随本次改造从工作树删除(它 `import` 了同批删除的
|
||||
草稿模型,无法在改造后的代码树上编译)。如需重放,从**它被删除前的最后一个提交**取回:
|
||||
|
||||
```bash
|
||||
# 取回脚本源码(c4bafc5 是删除提交 d68a570 的父提交,即脚本最后一次存在的版本)
|
||||
git show c4bafc5:scripts/migrate_single_table/main.go
|
||||
```
|
||||
|
||||
注意:脚本依赖草稿模型,必须在该提交(或更早)的代码树上运行,**不能**直接放进当前树。
|
||||
真正需要重放时,建议 `git worktree add ../old c4bafc5` 切出旧树再跑。
|
||||
|
||||
### 索引口径的一个坑
|
||||
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS` 只按**索引名**判断存在性,不比对表达式。因此:
|
||||
|
||||
- 若库里已有同名但口径更窄的旧 `uq_ss_entity (city, year)`,03 会静默跳过、留下错误结构;
|
||||
这时必须跑 04 纠正(04 的 `DROP` 正是为此)。
|
||||
- 反过来,若只跑 03 而库里已存在正确的同名索引,跳过是无害的。
|
||||
63
db_dump.sql
63
db_dump.sql
@ -1,5 +1,5 @@
|
||||
-- dbtool 导出:127.0.0.1:5432/fashion
|
||||
-- 生成时间:2026-09-23T14:06:13+08:00
|
||||
-- 生成时间:2026-09-23T15:56:58+08:00
|
||||
--
|
||||
-- 导入(二选一):
|
||||
-- dbtool import -in <本文件>
|
||||
@ -171,7 +171,7 @@ CREATE TABLE IF NOT EXISTS public."users" (
|
||||
"tier" character varying(16)
|
||||
);
|
||||
|
||||
CREATE VIEW public."public_brand_runway_images" AS
|
||||
CREATE OR REPLACE VIEW public."public_brand_runway_images" AS
|
||||
SELECT i.id,
|
||||
i.created_at,
|
||||
i.updated_at,
|
||||
@ -190,7 +190,7 @@ SELECT i.id,
|
||||
JOIN brand_runways r ON r.id = i.runway_id
|
||||
WHERE i.is_deleted = 0 AND r.status::text = 'published'::text AND r.is_deleted = 0;
|
||||
|
||||
CREATE VIEW public."public_brand_runways" AS
|
||||
CREATE OR REPLACE VIEW public."public_brand_runways" AS
|
||||
SELECT brand_runways.id,
|
||||
brand_runways.title_en,
|
||||
brand_runways.title_cn,
|
||||
@ -213,7 +213,7 @@ SELECT brand_runways.id,
|
||||
FROM brand_runways
|
||||
WHERE brand_runways.status::text = 'published'::text AND brand_runways.is_deleted = 0;
|
||||
|
||||
CREATE VIEW public."public_street_snap_images" AS
|
||||
CREATE OR REPLACE VIEW public."public_street_snap_images" AS
|
||||
SELECT i.id,
|
||||
i.snap_id,
|
||||
i.image,
|
||||
@ -231,7 +231,7 @@ SELECT i.id,
|
||||
JOIN street_snaps s ON s.id = i.snap_id
|
||||
WHERE i.is_deleted = 0 AND s.status::text = 'published'::text AND s.is_deleted = 0;
|
||||
|
||||
CREATE VIEW public."public_street_snaps" AS
|
||||
CREATE OR REPLACE VIEW public."public_street_snaps" AS
|
||||
SELECT street_snaps.id,
|
||||
street_snaps.title,
|
||||
street_snaps.year,
|
||||
@ -1200,28 +1200,6 @@ INSERT INTO public."ingest_nonces" ("nonce", "created_at") VALUES
|
||||
(E'7cac48bc88a16238f03a3c92eeded6e8', E'1789912739');
|
||||
|
||||
INSERT INTO public."refresh_tokens" ("id", "user_id", "token_hash", "expires_at", "revoked", "created_at") VALUES
|
||||
(E'1', E'7', E'a6d40efa41eb7184626615404d62eec90837387fd9c0fab4b2e4998f99116641', E'1790768077', E'1', E'1788176077'),
|
||||
(E'2', E'7', E'294f4f0e9a3933bc0a346a650e9c2229c73351f23073f4826de864c60aae7ab3', E'1790768092', E'1', E'1788176092'),
|
||||
(E'3', E'7', E'1b5cb599d3cb5f34e154e1a30ed531f6bb60899a0f4eb7baa1ece97a2b0b8922', E'1790769528', E'1', E'1788177528'),
|
||||
(E'4', E'7', E'4f53b8a0dcf701a2935e2616ca183e1538fab999fd2d282ec5efb347c130772f', E'1790769528', E'1', E'1788177528'),
|
||||
(E'9', E'7', E'43e9ab9901f7e3a3ca79e581195666c0a298a0cdaaa08655ccdd7b1e8995e68a', E'1790907621', E'1', E'1788315621'),
|
||||
(E'10', E'7', E'ee69982285607bcda68c297be3826cf17aebe16ee5d5eb354846d5f848ce1644', E'1790913746', E'1', E'1788321746'),
|
||||
(E'11', E'7', E'82980a5eb43432b294fe98e0ace622da74e8b60349a8a82be416972d19505017', E'1790913779', E'1', E'1788321779'),
|
||||
(E'12', E'7', E'2a28617d4931e139b76c6bece9ed89544984c14349e758163870dc38289b7279', E'1790923131', E'1', E'1788331131'),
|
||||
(E'13', E'7', E'4736dcf29020280cd3a7824ebbcea35cefa5e019bb6b9f2c9f98a596f4e09057', E'1790923500', E'1', E'1788331500'),
|
||||
(E'14', E'7', E'18627461e72af8e993f801933fd287a46f259f6fddd18dbd98a00730bf744b52', E'1790923558', E'1', E'1788331558'),
|
||||
(E'15', E'7', E'a25ae2038941445a00858015f043d04b9d2a25cfaf22020c30790d0054090b84', E'1790923951', E'1', E'1788331951'),
|
||||
(E'16', E'7', E'b1a72a023fb3ceb71534b5e91b53b98df197a1f807d0644746971075dc0d4135', E'1790923962', E'1', E'1788331962'),
|
||||
(E'17', E'7', E'876f4d75315a134c598aaf8afd5081f88489dc923a8fc5c23be6600c61625910', E'1790923982', E'1', E'1788331982'),
|
||||
(E'18', E'7', E'1f05e0f60671db96c68936b93dbbe3fd3f6444cd4b90867e0a8e8b450d97ea22', E'1790924007', E'1', E'1788332007'),
|
||||
(E'19', E'7', E'd2a0239104b52086cfd2cb6aec5ba64f967b4a4b1f61ce25cc3b32762c734561', E'1790924072', E'1', E'1788332072'),
|
||||
(E'20', E'7', E'fc81e702b009efee38d47f1dea0e9644885b4cbec52dac9e5c60c03f4858fa0e', E'1790924658', E'1', E'1788332658'),
|
||||
(E'21', E'7', E'bd55e380968376e1881fc6df846384c9fce9711290be367a65001c96f044799d', E'1790926919', E'1', E'1788334919'),
|
||||
(E'22', E'7', E'51cef85f469027417dc994e5d977efd1a318dc75ae0804bbfc3e019456248bd6', E'1790927021', E'1', E'1788335021'),
|
||||
(E'24', E'7', E'b180038e3448f8697f983c3ba2efb93acd7037df03fa27574ac9dceeba189f4c', E'1790928286', E'1', E'1788336286'),
|
||||
(E'29', E'7', E'22af98693b2caec27e958713b914414d8cf5f306101d53226c9d04dc6754b671', E'1790930929', E'1', E'1788338929'),
|
||||
(E'34', E'7', E'09bdc1a3388e2b09114339ac5a798b3b060a0d880d4d5a3b9e358a1a976dc703', E'1790934593', E'1', E'1788342593'),
|
||||
(E'35', E'7', E'a3ba322c3161d576afe7b2a3275cca4e215a91ee0768718f9aa841bc219f37bc', E'1790934604', E'0', E'1788342604'),
|
||||
(E'5', E'8', E'f1aea9e5697279b829720413ee5a3c76103518fe3e9dcb52174c183752df295c', E'1790822496', E'1', E'1788230496'),
|
||||
(E'6', E'8', E'338847c9c29f629e2a50e384a21b7bf29f43ccddb2a180581dd9e22f6a860b9a', E'1790824208', E'1', E'1788232208'),
|
||||
(E'7', E'8', E'9d554202fa31afdf13bf155e8115cbb3ee576d6ea7b5469de6709fbd73ad811c', E'1790848458', E'1', E'1788256458'),
|
||||
@ -1299,8 +1277,7 @@ INSERT INTO public."refresh_tokens" ("id", "user_id", "token_hash", "expires_at"
|
||||
(E'37', E'8', E'8c819c48e7f17a248791390937c488a94fd7c4c7822907900a80f24ff086e394', E'1790938015', E'1', E'1788346015'),
|
||||
(E'38', E'8', E'1e33cf9f6036efc21bbf28657577290087f8105d76c917f16f320d7cf25f8278', E'1790938336', E'1', E'1788346336'),
|
||||
(E'39', E'8', E'77962d61a0c55d79de83e31e4efded50e565ca0d09c2f4554c1108e4aecef547', E'1790939501', E'1', E'1788347501'),
|
||||
(E'40', E'8', E'c54cf2aececa5fd06701dd6fe2f9ee159f1046a5dd8818eec682498d7ec21a33', E'1790939520', E'1', E'1788347520');
|
||||
INSERT INTO public."refresh_tokens" ("id", "user_id", "token_hash", "expires_at", "revoked", "created_at") VALUES
|
||||
(E'40', E'8', E'c54cf2aececa5fd06701dd6fe2f9ee159f1046a5dd8818eec682498d7ec21a33', E'1790939520', E'1', E'1788347520'),
|
||||
(E'41', E'8', E'b02994a50c903252e72ea078dc052a535069fe0a814df4de30d4aec57392ed0e', E'1790940991', E'1', E'1788348991'),
|
||||
(E'42', E'8', E'0994a166bfe5a917d66da3d28e853991a724bad5ba2a56d0589b9f6e93f8ea8c', E'1790941592', E'1', E'1788349592'),
|
||||
(E'43', E'8', E'941b4c59118ba58915a02f0ae4250b9ba8a0816b62b9a57e2203374b8741b035', E'1790941855', E'1', E'1788349855'),
|
||||
@ -1318,7 +1295,31 @@ INSERT INTO public."refresh_tokens" ("id", "user_id", "token_hash", "expires_at"
|
||||
(E'113', E'8', E'6b6a514221de8aa4c0fda45fa6c9d6eab318aeb3ae8f72c37eec1100e11ffb73', E'1792114905', E'1', E'1789522905'),
|
||||
(E'114', E'8', E'68af59790a958f09d2fe65728fdae7cf01ea59b40b99f1cd69977a4eefce3919', E'1792415160', E'1', E'1789823160'),
|
||||
(E'115', E'8', E'6cc47083bd5373028aba68c89c0050ab2d691ee65e20993d50e8002cc500a1ba', E'1792415169', E'1', E'1789823169'),
|
||||
(E'119', E'8', E'1b965638435da6e428c9d3d3316ac77ea3dad74f3427eed61cfd1dcaed5c1856', E'1792666163', E'0', E'1790074163');
|
||||
(E'119', E'8', E'1b965638435da6e428c9d3d3316ac77ea3dad74f3427eed61cfd1dcaed5c1856', E'1792666163', E'0', E'1790074163'),
|
||||
(E'1', E'7', E'a6d40efa41eb7184626615404d62eec90837387fd9c0fab4b2e4998f99116641', E'1790768077', E'1', E'1788176077'),
|
||||
(E'2', E'7', E'294f4f0e9a3933bc0a346a650e9c2229c73351f23073f4826de864c60aae7ab3', E'1790768092', E'1', E'1788176092'),
|
||||
(E'3', E'7', E'1b5cb599d3cb5f34e154e1a30ed531f6bb60899a0f4eb7baa1ece97a2b0b8922', E'1790769528', E'1', E'1788177528'),
|
||||
(E'4', E'7', E'4f53b8a0dcf701a2935e2616ca183e1538fab999fd2d282ec5efb347c130772f', E'1790769528', E'1', E'1788177528');
|
||||
INSERT INTO public."refresh_tokens" ("id", "user_id", "token_hash", "expires_at", "revoked", "created_at") VALUES
|
||||
(E'9', E'7', E'43e9ab9901f7e3a3ca79e581195666c0a298a0cdaaa08655ccdd7b1e8995e68a', E'1790907621', E'1', E'1788315621'),
|
||||
(E'10', E'7', E'ee69982285607bcda68c297be3826cf17aebe16ee5d5eb354846d5f848ce1644', E'1790913746', E'1', E'1788321746'),
|
||||
(E'11', E'7', E'82980a5eb43432b294fe98e0ace622da74e8b60349a8a82be416972d19505017', E'1790913779', E'1', E'1788321779'),
|
||||
(E'12', E'7', E'2a28617d4931e139b76c6bece9ed89544984c14349e758163870dc38289b7279', E'1790923131', E'1', E'1788331131'),
|
||||
(E'13', E'7', E'4736dcf29020280cd3a7824ebbcea35cefa5e019bb6b9f2c9f98a596f4e09057', E'1790923500', E'1', E'1788331500'),
|
||||
(E'14', E'7', E'18627461e72af8e993f801933fd287a46f259f6fddd18dbd98a00730bf744b52', E'1790923558', E'1', E'1788331558'),
|
||||
(E'15', E'7', E'a25ae2038941445a00858015f043d04b9d2a25cfaf22020c30790d0054090b84', E'1790923951', E'1', E'1788331951'),
|
||||
(E'16', E'7', E'b1a72a023fb3ceb71534b5e91b53b98df197a1f807d0644746971075dc0d4135', E'1790923962', E'1', E'1788331962'),
|
||||
(E'17', E'7', E'876f4d75315a134c598aaf8afd5081f88489dc923a8fc5c23be6600c61625910', E'1790923982', E'1', E'1788331982'),
|
||||
(E'18', E'7', E'1f05e0f60671db96c68936b93dbbe3fd3f6444cd4b90867e0a8e8b450d97ea22', E'1790924007', E'1', E'1788332007'),
|
||||
(E'19', E'7', E'd2a0239104b52086cfd2cb6aec5ba64f967b4a4b1f61ce25cc3b32762c734561', E'1790924072', E'1', E'1788332072'),
|
||||
(E'20', E'7', E'fc81e702b009efee38d47f1dea0e9644885b4cbec52dac9e5c60c03f4858fa0e', E'1790924658', E'1', E'1788332658'),
|
||||
(E'21', E'7', E'bd55e380968376e1881fc6df846384c9fce9711290be367a65001c96f044799d', E'1790926919', E'1', E'1788334919'),
|
||||
(E'22', E'7', E'51cef85f469027417dc994e5d977efd1a318dc75ae0804bbfc3e019456248bd6', E'1790927021', E'1', E'1788335021'),
|
||||
(E'24', E'7', E'b180038e3448f8697f983c3ba2efb93acd7037df03fa27574ac9dceeba189f4c', E'1790928286', E'1', E'1788336286'),
|
||||
(E'29', E'7', E'22af98693b2caec27e958713b914414d8cf5f306101d53226c9d04dc6754b671', E'1790930929', E'1', E'1788338929'),
|
||||
(E'34', E'7', E'09bdc1a3388e2b09114339ac5a798b3b060a0d880d4d5a3b9e358a1a976dc703', E'1790934593', E'1', E'1788342593'),
|
||||
(E'35', E'7', E'a3ba322c3161d576afe7b2a3275cca4e215a91ee0768718f9aa841bc219f37bc', E'1790934604', E'1', E'1788342604'),
|
||||
(E'120', E'7', E'c74e517dc0d12b895e5867b241fde55c78b55fc9ee44a72501b8f2035d80528b', E'1792736601', E'0', E'1790144601');
|
||||
|
||||
INSERT INTO public."street_snap_images" ("id", "snap_id", "image", "name", "sort_order", "is_deleted", "created_at", "updated_at", "phash", "is_duplicate", "dup_of", "is_detail", "parent_image_id") VALUES
|
||||
(E'443', E'6', E'street/4928cc08576f7c041facc49a813f08fff0bc51da.jpg', E'Look 1', E'1', E'1', E'1790050749', E'1790075943', E'[1,1,1,0,1,0,1,0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,0,0]', E'0', E'0', E'0', E'0'),
|
||||
@ -3677,7 +3678,7 @@ INSERT INTO public."street_snaps" ("id", "title", "year", "city", "cover", "imag
|
||||
(E'146', E'London Street Style Spring 2027 Day 2', E'2027', E'London', E'street/a9c1b744df1a9aaf7067d2e88835aead98fb4003.jpg', E'329', E'0', E'1789914056', E'1789914056', E'', E'', E'pending', E'100', E'', E''),
|
||||
(E'147', E'The Best Street Style of Milan Fashion Week Fall 2026', E'2026', E'Milan', E'street/751fbc91e3e5fba3c4ca3420928cc829cbf1ad20.jpg', E'156', E'0', E'1789914679', E'1789914679', E'', E'', E'pending', E'101', E'', E''),
|
||||
(E'148', E'The Best Street Style of London Fashion Week Fall 2026', E'2026', E'London', E'street/1bdd3d1c5256a9601b24373934cad5d60661f301.jpg', E'81', E'0', E'1789915003', E'1789915003', E'', E'', E'pending', E'102', E'', E''),
|
||||
(E'149', E'The Best Street Style From Copenhagen Fashion Week', E'0', E'Copenhagen', E'street/697a793538c53668ff288073b8e361c73578478f.jpg', E'59', E'0', E'1789917788', E'1789917788', E'', E'', E'pending', E'104', E'', E'');
|
||||
(E'149', E'The Best Street Style From Copenhagen Fashion Week', E'0', E'Copenhagen', E'street/697a793538c53668ff288073b8e361c73578478f.jpg', E'59', E'0', E'1789917788', E'1790144662', E'', E'', E'published', E'104', E'admin', E'');
|
||||
|
||||
INSERT INTO public."users" ("id", "created_at", "updated_at", "username", "email", "password_hash", "is_deleted", "tier") VALUES
|
||||
(E'1', E'1785817977', E'1788599843', E'testuser', E'test@example.com', E'$2a$10$osJmeI6QuLTLobycj50zgOd9moBRQ6wzWbTwIHbrpLkmCNE8MQbAu', E'0', E'free'),
|
||||
|
||||
@ -101,14 +101,20 @@ const (
|
||||
```
|
||||
|
||||
- **通过**:`UPDATE ... SET status='published', reviewer=?` + 应用表单里的字段编辑。**不再触碰图片行**。
|
||||
- **驳回**:`UPDATE ... SET status='rejected', reviewer=?, reject_reason=?`。行保留。
|
||||
- **驳回**:`UPDATE ... SET status='rejected', reviewer=?, reject_reason=?`。行保留(备查)。
|
||||
- **驳回后重爬**:`rejected → pending`(复用同一行,见 §5 第 1 条第 2 支)。驳回不是永久黑名单。
|
||||
- 每条记录**只有一个实体键行**(runway: `brand_id+season_code+collection_type`;street: `city+year`),不存在"同实体的多条 pending 并存"。
|
||||
|
||||
## 5. 写入链路(ingest 直写正式表)
|
||||
|
||||
`internal/service/ingest_service.go` 的 `processRunway` / `processStreet`:
|
||||
|
||||
1. **实体键查重**:沿用 `RunwayIDByEntity` / `StreetSnapIDByEntity`(`WHERE 实体键 AND is_deleted=0`)。单表之后,该条件会同时匹配 `pending/published/rejected` 的任意行 —— 命中即整任务 `MarkDone` **直接放弃**(用户裁定),与现状对"已发布实体"的行为一致,且顺带把"重复爬取同一实体"也收敛掉。
|
||||
1. **实体键查重**(`RunwayIDByEntity` / `StreetSnapIDByEntity`,`WHERE 实体键 AND is_deleted=0`)。单表之后该条件会命中任意状态的行,因此必须**按命中行的状态分三支**:
|
||||
- 命中 `pending` / `published` → 整任务 `MarkDone`,**直接放弃**(用户裁定)。语义:该实体已收录或正在审核,不重复入库。
|
||||
- 命中 `rejected` → **复用该行**:覆盖内容字段(标题/描述/年份/季节/collection_type/season_code/cover)、软删其旧图片、写入本次抓取的图片、置回 `status='pending'` 并清空 `reviewer`/`reject_reason`。语义:驳回不是永久黑名单,重爬即重新送审。
|
||||
> ⚠️ 这一支是**必需的修正**:查重条件不带 status,若不特判 `rejected`,一条被驳回(甚至误驳)的记录会**永久挡住重爬**;而现状(草稿表)不会——查重只查正式表,驳回的草稿不挡路。
|
||||
- 未命中 → 新建 `pending` 记录。
|
||||
"同一实体只有一行"因此始终成立。
|
||||
2. **建记录**:`CreateRunwayDraft` → `CreateRunway`(写 `brand_runways`,`status='pending'`、`job_id`);`CreateStreetSnapDraft` → `CreateStreetSnap`(写 `street_snaps`)。
|
||||
3. **建图片**:把图直接写 `brand_runway_images` / `street_snap_images`。
|
||||
4. **图片去重**:`FindNearDuplicateImage` 的比对表从"草稿图 + 正式图"两张收敛为**一张正式图表**;`phash` / `is_duplicate` / `dup_of` 的写入位置不变。
|
||||
@ -175,8 +181,16 @@ CREATE VIEW public_street_snap_images AS
|
||||
|
||||
### 第 1 步:DDL + 视图(`db/migrations/2026-09-22-01-single-table-publish.sql`)
|
||||
1. §3.2 加列。
|
||||
2. 存量正式行视为已发布:`UPDATE brand_runways SET status='published' WHERE created_at < :迁移时刻;`(street 同理)。**带时间戳护栏**,避免脚本被重复执行时把新入库的 pending 行误刷成 published。
|
||||
3. 建 §6 的 4 个视图。
|
||||
2. 建 §6 的 4 个视图(视图定义必须幂等:`DROP VIEW IF EXISTS` 后重建)。
|
||||
|
||||
**存量行置已发布拆成独立的一次性文件**(`db/migrations/2026-09-22-01b-publish-existing-rows.sql`):
|
||||
|
||||
```sql
|
||||
UPDATE brand_runways SET status = 'published' WHERE status = 'pending';
|
||||
UPDATE street_snaps SET status = 'published' WHERE status = 'pending';
|
||||
```
|
||||
|
||||
为什么必须拆开:数据搬迁(第 2 步)会把 pending 草稿**连同旧的 `created_at`** 搬进正式表。若这条 UPDATE 留在可重复执行的迁移文件里(集成测试每次都会执行它),这些待审内容会被误刷成 `published` —— 恰好是本设计要防的泄漏。因此:结构 DDL 可重复执行,数据变更只执行一次,且**必须在第 2 步之前**执行。
|
||||
|
||||
> 本步必须在部署新代码**之前**应用(新代码开始写 `status`)。
|
||||
|
||||
@ -240,3 +254,5 @@ DROP TABLE IF EXISTS brand_runway_draft_images, brand_runway_drafts,
|
||||
1. `image_count` 口径:runway 只计主图,street 计全部图(含副图)。
|
||||
2. `favorites` 实建索引是 `uniq_user_target(target_uid)` 单列(代码注释写的是 `(user_id, target_uid)` 组合)——按现有 DDL,同一用户似乎只能收藏一条记录,疑似缺陷。
|
||||
3. `image_duplicates`、`image_embeddings` 两张表零引用;`street_snaps.source/source_url` 死列。可另起一个清理迁移删掉,与本次改造解耦。
|
||||
4. **标题漂移会被判为新实体**:街拍实体键含 `title`(`(city, year, COALESCE(title, ''))`),同一专题若标题只做空白 / 大小写 / 措辞微调,入库查重会当作新实体,从而多出一行(内容重复)。目前无标题归一化。
|
||||
5. **「图片 id 终身不变」不成立**:在「已发布 → 驳回下架 → 重爬复用」这条路径上,复用 `rejected` 行会软删旧图行并插入新行,图片行 id 随之变化。凡把图片 id 当稳定标识(收藏、外链、前端缓存键)的场景都需注意。
|
||||
|
||||
@ -466,8 +466,9 @@ func (r *ingestRepository) RetryJob(ctx context.Context, id uint32) error {
|
||||
// 算子用 pgvector 的 L2(<->);因 phash 是 {0,1}^64 向量,L2² == 汉明距离,故 L2 阈值 = sqrt(threshold)。
|
||||
// phashBits 为 vector(64) 二进制向量串;NULL 的 phash 不参与比较。
|
||||
//
|
||||
// 只比对未软删的行(is_deleted = 0):复用驳回行时去重先于软删旧图执行,
|
||||
// 否则重爬到的同一张图会命中「即将被软删的旧行」,留痕 dup_of 指向一条公开不可见的记录。
|
||||
// 只比对未软删的行(is_deleted = 0):已被软删(审核剔除 / 复用重审)的旧图不应再作为
|
||||
// 「重复」的参照。注意复用驳回行的时序 —— 去重发生在软删旧图**之前**,那一刻旧行仍是
|
||||
// is_deleted = 0、会被正常命中;dup_of 只是人工留痕,不承担可见性语义。
|
||||
// 本方法被 runway / street 两条入库路径共用,过滤对两者语义一致。
|
||||
func (r *ingestRepository) FindNearDuplicateImage(ctx context.Context, tables []string, phashBits string, threshold int) (uint32, bool, error) {
|
||||
// 汉明阈值转 L2 阈值:phash 为 {0,1}^64 向量,L2² == 汉明距离,故 L2 阈值 = sqrt(汉明阈值)。
|
||||
|
||||
@ -181,12 +181,14 @@ func TestIngestReuseRejectedRefusesPublished(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDedupIgnoresSoftDeletedImage 去重不得命中已软删的行:复用驳回行时去重先于软删旧图执行,
|
||||
// 若把「即将被软删的旧图」算进比对,重爬到的同一张图会被打上 dup_of=<旧行 id>,
|
||||
// 留痕指向一条随后公开不可见的记录。
|
||||
// TestDedupIgnoresSoftDeletedImage 去重只比对**未软删**的行(is_deleted = 0)。
|
||||
//
|
||||
// 用与探测向量完全相同的 phash(距离 0)插入软删行,保证修复前它必然是「最近一条」被返回,
|
||||
// 因此本断言在修复前确定性失败、修复后确定性通过,与库中其它数据无关。
|
||||
// 别把它误读成「复用驳回行时不会自我命中」:复用路径里去重发生在软删旧图**之前**,那一刻
|
||||
// 旧行仍是 is_deleted = 0、仍会被命中——dup_of 只是给人工看的留痕,不参与任何可见性判定。
|
||||
// 本用例锁的是另一条独立保证:**已经**软删的行不再被当作重复参照。
|
||||
//
|
||||
// 用与探测向量完全相同的 phash(距离 0)插入软删行,保证它若被纳入就必然是「最近一条」,
|
||||
// 从而确定性地验证 is_deleted = 0 过滤生效,与库中其它数据无关。
|
||||
func TestDedupIgnoresSoftDeletedImage(t *testing.T) {
|
||||
db := testDB(t)
|
||||
applyMigration(t, db, "2026-09-22-01-single-table-publish.sql")
|
||||
@ -213,3 +215,46 @@ func TestDedupIgnoresSoftDeletedImage(t *testing.T) {
|
||||
t.Fatalf("已软删的行(id=%d)不应参与近重复比对", row.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIngestImageCountMatchesAliveMainRows 入库后 image_count 必须等于该记录存活主图行数(is_detail = 0)。
|
||||
//
|
||||
// 与 service.processRunway 的 imageCount = countMainImages(images) 同口径,且与审核期
|
||||
// SoftDeleteRunwayImage 的重算口径一致:三处必须同源,否则公开卡片「N 张」角标与
|
||||
// FeaturedIDs 的 SUM(image_count) 热度会漂移(单表发布删掉了晋升重算的自愈路径)。
|
||||
func TestIngestImageCountMatchesAliveMainRows(t *testing.T) {
|
||||
db := testDB(t)
|
||||
applyMigration(t, db, "2026-09-22-01-single-table-publish.sql")
|
||||
repo := NewIngestRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
const season = "IC71"
|
||||
rw := newRunwayForIngest(70, 1, season, "rtw", "ic-main-a.jpg")
|
||||
rw.ImageCount = 2 // 2 张主图
|
||||
imgs := []model.BrandRunwayImage{
|
||||
{BrandID: 1, Image: "ic-main-a.jpg", Name: "Look 1", SortOrder: 1, IsDetail: 0},
|
||||
{BrandID: 1, Image: "ic-detail-a1.jpg", Name: "Look 1 — Detail 1", SortOrder: 2, IsDetail: 1},
|
||||
{BrandID: 1, Image: "ic-main-b.jpg", Name: "Look 2", SortOrder: 3, IsDetail: 0},
|
||||
}
|
||||
id, err := repo.CreateRunwayWithImages(ctx, rw, imgs)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateRunwayWithImages 出错: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
db.Exec("DELETE FROM brand_runway_images WHERE runway_id = ?", id)
|
||||
db.Exec("DELETE FROM brand_runways WHERE id = ?", id)
|
||||
})
|
||||
|
||||
var got struct {
|
||||
ImageCount uint16 `gorm:"column:image_count"`
|
||||
AliveMain int64 `gorm:"column:alive_main"`
|
||||
}
|
||||
if err := db.Raw(`SELECT r.image_count,
|
||||
(SELECT COUNT(*) FROM brand_runway_images i
|
||||
WHERE i.runway_id = r.id AND i.is_deleted = 0 AND i.is_detail = 0) AS alive_main
|
||||
FROM brand_runways r WHERE r.id = ?`, id).Scan(&got).Error; err != nil {
|
||||
t.Fatalf("读回计数失败: %v", err)
|
||||
}
|
||||
if int64(got.ImageCount) != got.AliveMain {
|
||||
t.Fatalf("入库后 image_count=%d 必须等于存活主图行数 %d", got.ImageCount, got.AliveMain)
|
||||
}
|
||||
}
|
||||
|
||||
@ -61,6 +61,21 @@ func NewReviewRepository(db *gorm.DB) ReviewRepository {
|
||||
return &reviewRepository{db: db}
|
||||
}
|
||||
|
||||
// reviewListScope 把「未软删 + 可选状态过滤」编译为 GORM Scope。
|
||||
//
|
||||
// 用 Scope 而非在 Count 之后复用同一个 *gorm.DB:GORM v2 中终结方法(Count 等)之后再复用
|
||||
// 同一实例会带上残留的 Statement 状态,Scope 每次作用于全新查询即可杜绝该隐患
|
||||
//(与 article_repository.filterScope 同一理由)。
|
||||
func reviewListScope(status string) func(*gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
db = db.Where("is_deleted = 0")
|
||||
if status != "" {
|
||||
db = db.Where("status = ?", status)
|
||||
}
|
||||
return db
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reviewRepository) ListRecords(ctx context.Context, status string, page, size int) ([]model.BrandRunway, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
@ -68,19 +83,17 @@ func (r *reviewRepository) ListRecords(ctx context.Context, status string, page,
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
q := r.db.WithContext(ctx).Model(&model.BrandRunway{}).Where("is_deleted = 0")
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
scope := reviewListScope(status)
|
||||
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Model(&model.BrandRunway{}).Scopes(scope).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if total == 0 {
|
||||
return []model.BrandRunway{}, 0, nil
|
||||
}
|
||||
var rows []model.BrandRunway
|
||||
if err := q.
|
||||
if err := r.db.WithContext(ctx).Model(&model.BrandRunway{}).Scopes(scope).
|
||||
Order("CASE status WHEN '" + model.StatusPending + "' THEN 0 ELSE 1 END ASC, id DESC").
|
||||
Offset((page - 1) * size).
|
||||
Limit(size).
|
||||
@ -143,6 +156,11 @@ func (r *reviewRepository) UpdateRecord(ctx context.Context, id uint32, fields m
|
||||
// SetRecordStatus 命中 0 行说明记录不存在,返回 ErrNotFound。
|
||||
// 否则「对不存在的 id 通过 / 驳回」会被当作成功:handler 只校验 id != 0,id 又来自 URL,
|
||||
// 竞态窗口(记录刚被删除)下会给出假成功 302。
|
||||
//
|
||||
// 有意**不校验前置状态**:允许把 rejected 直接置 published(或反向),不做状态机约束。
|
||||
// 列表页只对 pending 显示通过 / 驳回按钮,但 POST 端点本身不设防 —— 这是已知取舍
|
||||
//(幂等重放 / 管理端纠正误操作都依赖它);若日后要收紧,应改在 handler 或显式状态机里做,
|
||||
// 而不是悄悄在这个仓储方法里加限制。
|
||||
func (r *reviewRepository) SetRecordStatus(ctx context.Context, id uint32, status, reviewer, reason string) error {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&model.BrandRunway{}).
|
||||
@ -183,19 +201,17 @@ func (r *reviewRepository) ListStreetRecords(ctx context.Context, status string,
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
q := r.db.WithContext(ctx).Model(&model.StreetSnap{}).Where("is_deleted = 0")
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
scope := reviewListScope(status)
|
||||
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Model(&model.StreetSnap{}).Scopes(scope).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if total == 0 {
|
||||
return []model.StreetSnap{}, 0, nil
|
||||
}
|
||||
var rows []model.StreetSnap
|
||||
if err := q.
|
||||
if err := r.db.WithContext(ctx).Model(&model.StreetSnap{}).Scopes(scope).
|
||||
Order("CASE status WHEN '" + model.StatusPending + "' THEN 0 ELSE 1 END ASC, id DESC").
|
||||
Offset((page - 1) * size).
|
||||
Limit(size).
|
||||
@ -250,6 +266,7 @@ func (r *reviewRepository) UpdateStreetRecord(ctx context.Context, id uint32, fi
|
||||
}
|
||||
|
||||
// SetStreetRecordStatus 命中 0 行说明记录不存在,返回 ErrNotFound(理由同 SetRecordStatus)。
|
||||
// 同样有意不校验前置状态:允许 rejected 直接置 published,属已知取舍(见 SetRecordStatus)。
|
||||
func (r *reviewRepository) SetStreetRecordStatus(ctx context.Context, id uint32, status, reviewer, reason string) error {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&model.StreetSnap{}).
|
||||
|
||||
103
internal/repository/review_status_transition_integration_test.go
Normal file
103
internal/repository/review_status_transition_integration_test.go
Normal file
@ -0,0 +1,103 @@
|
||||
//go:build integration
|
||||
|
||||
// 集成测试:「通过 → 公开可见」这条单表发布主链路的**仓储级**证据。
|
||||
//
|
||||
// 背景:公开视图测试(TestPublicViewsHideUnpublished*)都是直接 `db.Model(...).Update("status", ...)`
|
||||
// 改库、绕过了 `Approve` 走的 SetRecordStatus / SetStreetRecordStatus,这两个仓储方法在全仓零直接引用。
|
||||
// 一旦它们改错列 / 漏写 status,那些测试仍会全绿、线上却无法通过审核。本文件补上这一段。
|
||||
//
|
||||
// 运行:go test -tags integration ./internal/repository/ -run TestSetRecordStatus -v
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"fashionapi/internal/model"
|
||||
)
|
||||
|
||||
// TestSetRecordStatusDrivesPublicVisibility 走秀:pending 经仓储置 published 后在公开视图可见;
|
||||
// 再置 rejected 后不可见;对不存在的 id 返回 ErrNotFound。
|
||||
func TestSetRecordStatusDrivesPublicVisibility(t *testing.T) {
|
||||
db := testDB(t)
|
||||
applyMigration(t, db, "2026-09-22-01-single-table-publish.sql")
|
||||
repo := NewReviewRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
id := seedRunway(t, db, model.StatusPending, 1991)
|
||||
publicCount := func() int64 {
|
||||
var n int64
|
||||
db.Table("public_brand_runways").Where("id = ?", id).Count(&n)
|
||||
return n
|
||||
}
|
||||
|
||||
if got := publicCount(); got != 0 {
|
||||
t.Fatalf("pending 不应出现在公开视图,实际 %d", got)
|
||||
}
|
||||
|
||||
if err := repo.SetRecordStatus(ctx, id, model.StatusPublished, "admin", ""); err != nil {
|
||||
t.Fatalf("SetRecordStatus(published) 出错: %v", err)
|
||||
}
|
||||
if got := publicCount(); got != 1 {
|
||||
t.Fatalf("经仓储通过后应出现在公开视图,实际 %d(仓储可能写错列)", got)
|
||||
}
|
||||
|
||||
if err := repo.SetRecordStatus(ctx, id, model.StatusRejected, "admin", "图片不对"); err != nil {
|
||||
t.Fatalf("SetRecordStatus(rejected) 出错: %v", err)
|
||||
}
|
||||
if got := publicCount(); got != 0 {
|
||||
t.Fatalf("经仓储驳回后不应出现在公开视图,实际 %d", got)
|
||||
}
|
||||
|
||||
// 审核痕迹应落库,便于列表页展示。
|
||||
var rw model.BrandRunway
|
||||
if err := db.Where("id = ?", id).First(&rw).Error; err != nil {
|
||||
t.Fatalf("读回记录失败: %v", err)
|
||||
}
|
||||
if rw.Status != model.StatusRejected || rw.Reviewer != "admin" || rw.RejectReason != "图片不对" {
|
||||
t.Fatalf("审核态与痕迹应落库,实际 status=%s reviewer=%s reason=%s", rw.Status, rw.Reviewer, rw.RejectReason)
|
||||
}
|
||||
|
||||
// 不存在的 id:必须返回 ErrNotFound,而不是假成功。
|
||||
if err := repo.SetRecordStatus(ctx, 4_294_967_290, model.StatusPublished, "admin", ""); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("对不存在 id 应返回 ErrNotFound,实际 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetStreetRecordStatusDrivesPublicVisibility 街拍:与走秀同形,覆盖另一组方法与视图。
|
||||
func TestSetStreetRecordStatusDrivesPublicVisibility(t *testing.T) {
|
||||
db := testDB(t)
|
||||
applyMigration(t, db, "2026-09-22-01-single-table-publish.sql")
|
||||
repo := NewReviewRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
id := seedStreetSnap(t, db, model.StatusPending, 1990)
|
||||
publicCount := func() int64 {
|
||||
var n int64
|
||||
db.Table("public_street_snaps").Where("id = ?", id).Count(&n)
|
||||
return n
|
||||
}
|
||||
|
||||
if got := publicCount(); got != 0 {
|
||||
t.Fatalf("pending 不应出现在公开视图,实际 %d", got)
|
||||
}
|
||||
|
||||
if err := repo.SetStreetRecordStatus(ctx, id, model.StatusPublished, "admin", ""); err != nil {
|
||||
t.Fatalf("SetStreetRecordStatus(published) 出错: %v", err)
|
||||
}
|
||||
if got := publicCount(); got != 1 {
|
||||
t.Fatalf("经仓储通过后应出现在公开视图,实际 %d(仓储可能写错列)", got)
|
||||
}
|
||||
|
||||
if err := repo.SetStreetRecordStatus(ctx, id, model.StatusRejected, "admin", "重复"); err != nil {
|
||||
t.Fatalf("SetStreetRecordStatus(rejected) 出错: %v", err)
|
||||
}
|
||||
if got := publicCount(); got != 0 {
|
||||
t.Fatalf("经仓储驳回后不应出现在公开视图,实际 %d", got)
|
||||
}
|
||||
|
||||
if err := repo.SetStreetRecordStatus(ctx, 4_294_967_290, model.StatusPublished, "admin", ""); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("对不存在 id 应返回 ErrNotFound,实际 %v", err)
|
||||
}
|
||||
}
|
||||
@ -271,8 +271,10 @@ func TestSoftDeleteStreetImageRecomputesCount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSoftDeleteRunwayImage 走秀 image_count 口径是「主图数」(与入库 imageCount = len(Looks) 一致):
|
||||
// 软删细节图不改计数;软删主图才减,且同样是重算(重放 / 跨记录不漂移)。
|
||||
// TestSoftDeleteRunwayImage 走秀 image_count 口径是「存活主图行数」(与入库 countMainImages 一致)。
|
||||
//
|
||||
// 关键断言在「软删一张主图、让细节图**仍存活**」这一步:重算必须排除 is_detail=1 的行。
|
||||
// 若先删细节图再删主图,过滤与否结果相同(旧写法就锁不住口径),故这里把顺序倒过来。
|
||||
func TestSoftDeleteRunwayImage(t *testing.T) {
|
||||
repo := NewReviewRepository(testDB(t))
|
||||
ctx := context.Background()
|
||||
@ -282,20 +284,21 @@ func TestSoftDeleteRunwayImage(t *testing.T) {
|
||||
main2 := seedMainDetailRunwayImage(t, repo, runwayID, "main2", 2, 0)
|
||||
detail := seedMainDetailRunwayImage(t, repo, runwayID, "detail1", 3, 1)
|
||||
|
||||
// 首次软删细节图:主图数仍为 2(若用 COUNT(*) 不排除 is_detail,会错算成 3)。
|
||||
if err := repo.SoftDeleteRunwayImage(ctx, runwayID, detail); err != nil {
|
||||
t.Fatalf("软删细节图失败: %v", err)
|
||||
}
|
||||
if got := runwayImageCount(t, repo, runwayID); got != 2 {
|
||||
t.Fatalf("image_count 只计主图,应为 2,实际 %d", got)
|
||||
}
|
||||
|
||||
// 软删一张主图 → 1。
|
||||
// 先软删一张主图,细节图此刻仍存活:只计主图 → 1(仅 main1)。
|
||||
// 若重算用 COUNT(*) 不排除 is_detail,会把存活的 detail 一并算进来得 2 —— 本断言锁得住。
|
||||
if err := repo.SoftDeleteRunwayImage(ctx, runwayID, main2); err != nil {
|
||||
t.Fatalf("软删主图失败: %v", err)
|
||||
}
|
||||
if got := runwayImageCount(t, repo, runwayID); got != 1 {
|
||||
t.Fatalf("软删一张主图后应为 1,实际 %d", got)
|
||||
t.Fatalf("image_count 只计存活主图,软删一张主图后应为 1(须排除仍存活的细节图),实际 %d", got)
|
||||
}
|
||||
|
||||
// 再软删细节图:主图数不变(细节图本就不计入)。
|
||||
if err := repo.SoftDeleteRunwayImage(ctx, runwayID, detail); err != nil {
|
||||
t.Fatalf("软删细节图失败: %v", err)
|
||||
}
|
||||
if got := runwayImageCount(t, repo, runwayID); got != 1 {
|
||||
t.Fatalf("软删细节图不应改变主图计数,实际 %d", got)
|
||||
}
|
||||
|
||||
// 重放(已软删)+ 跨记录:计数均不得变化。
|
||||
|
||||
@ -205,7 +205,6 @@ func (r *streetSnapRepository) ImagesBySnapIDs(ctx context.Context, ids []uint32
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// IDs 返回全部未删除街拍的 id(升序),供 SSG 构建期枚举详情页路径。
|
||||
// Popular 按图片数降序返回热度前 N 个街拍(SSG 首页热门街拍用)。
|
||||
func (r *streetSnapRepository) Popular(ctx context.Context, limit int) ([]model.StreetSnap, error) {
|
||||
var rows []model.StreetSnap
|
||||
|
||||
117
internal/service/ingest_image_count_test.go
Normal file
117
internal/service/ingest_image_count_test.go
Normal file
@ -0,0 +1,117 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"fashionapi/internal/dto"
|
||||
"fashionapi/internal/model"
|
||||
"fashionapi/internal/pkg/hashid"
|
||||
"fashionapi/internal/pkg/storage"
|
||||
"fashionapi/internal/repository"
|
||||
)
|
||||
|
||||
// captureIngestRepo 捕获 processRunway 交给仓储的「待落库」记录与图片行。
|
||||
// 只实现被测路径会用到的方法,其余由内嵌 nil 接口兜底(不应被调用)。
|
||||
type captureIngestRepo struct {
|
||||
repository.IngestRepository
|
||||
createdRW *model.BrandRunway
|
||||
createdImages []model.BrandRunwayImage
|
||||
}
|
||||
|
||||
func (c *captureIngestRepo) RunwayEntityState(ctx context.Context, brandID uint32, seasonCode, collectionType string) (uint32, string, bool, error) {
|
||||
return 0, "", false, nil // 实体键未命中 → 新建分支
|
||||
}
|
||||
|
||||
func (c *captureIngestRepo) CreateRunwayWithImages(ctx context.Context, rw *model.BrandRunway, imgs []model.BrandRunwayImage) (uint32, error) {
|
||||
c.createdRW = rw
|
||||
c.createdImages = imgs
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func (c *captureIngestRepo) FindNearDuplicateImage(ctx context.Context, tables []string, phashBits string, threshold int) (uint32, bool, error) {
|
||||
return 0, false, nil // 近重复不影响本用例
|
||||
}
|
||||
|
||||
func (c *captureIngestRepo) MarkDone(ctx context.Context, id uint32) error { return nil }
|
||||
|
||||
// fakeBrandRepo 品牌校验恒通过。
|
||||
type fakeBrandRepo struct{ repository.BrandRepository }
|
||||
|
||||
func (fakeBrandRepo) FindByID(ctx context.Context, id uint32) (*model.Brand, error) {
|
||||
return &model.Brand{}, nil
|
||||
}
|
||||
|
||||
// TestProcessRunwayImageCountEqualsAliveMainRows 回归 image_count 漂移:
|
||||
//
|
||||
// 旧实现取 imageCount = len(p.Looks),但 fetchLookImages 会跳过 look.Main == "" 的 look
|
||||
// 与 sha1 重复的行 —— 实际落库的主图行可能更少。旧流程靠晋升按实际行重算自愈,单表发布后
|
||||
// 该路径已删除,漂移会永久留在公开卡片的「N 张」角标与热度 SUM(image_count) 上。
|
||||
//
|
||||
// 本用例断言:入库时交给仓储的 image_count == 实际存活主图行数(is_detail = 0),
|
||||
// 且在数据触发跳过时**严格小于** len(Looks)。旧实现下 image_count 会是 4,确定性失败。
|
||||
func TestProcessRunwayImageCountEqualsAliveMainRows(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
local := storage.NewLocalUploader(dir, "/uploads")
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
// 按路径返回不同内容:Content 不同 → sha1 不同;同路径 → sha1 相同(触发批次内去重)。
|
||||
_, _ = w.Write([]byte("fake-bytes-for" + r.URL.Path))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
repo := &captureIngestRepo{}
|
||||
s := &IngestService{
|
||||
repo: repo,
|
||||
brandRepo: fakeBrandRepo{},
|
||||
uploader: local,
|
||||
local: local,
|
||||
httpClient: srv.Client(),
|
||||
}
|
||||
|
||||
p := dto.RunwayIngest{
|
||||
Kind: dto.IngestKindRunway,
|
||||
BrandUID: hashid.Encode(1),
|
||||
TitleEn: "image-count-test",
|
||||
Year: 2027,
|
||||
Season: "spring",
|
||||
CollectionType: "rtw",
|
||||
Looks: []dto.RunwayLook{
|
||||
// look 1:主图 a + 细节图 a1 → 1 主图
|
||||
{Main: srv.URL + "/img/a.jpg", Details: []string{srv.URL + "/img/a1.jpg"}},
|
||||
// look 2:空主图,只有细节图 b1 → 0 主图(旧实现仍按 1 计)
|
||||
{Details: []string{srv.URL + "/img/b1.jpg"}},
|
||||
// look 3:主图与 look 1 内容相同(sha1 重复)→ 被跳过,0 主图(旧实现仍按 1 计)
|
||||
{Main: srv.URL + "/img/a.jpg"},
|
||||
// look 4:主图 c → 1 主图
|
||||
{Main: srv.URL + "/img/c.jpg"},
|
||||
},
|
||||
}
|
||||
job := model.IngestJob{ID: 1, Kind: model.IngestKindCrawl}
|
||||
s.processRunway(context.Background(), job, p)
|
||||
|
||||
if repo.createdRW == nil {
|
||||
t.Fatal("未写入走秀记录")
|
||||
}
|
||||
|
||||
// 实际落库主图行:a、c → 2 张;细节图 a1、b1 → 2 张。
|
||||
var actualMain uint16
|
||||
for _, im := range repo.createdImages {
|
||||
if im.IsDetail == 0 {
|
||||
actualMain++
|
||||
}
|
||||
}
|
||||
if actualMain != 2 {
|
||||
t.Fatalf("前置:实际主图行应为 2,实际 %d(图片行=%+v)", actualMain, repo.createdImages)
|
||||
}
|
||||
if got := repo.createdRW.ImageCount; got != actualMain {
|
||||
t.Fatalf("入库 image_count 应等于存活主图行数 %d,实际 %d", actualMain, got)
|
||||
}
|
||||
if repo.createdRW.ImageCount >= uint16(len(p.Looks)) {
|
||||
t.Fatalf("本用例数据应让 image_count(%d) 严格小于 len(Looks)=%d,否则测不出漂移",
|
||||
repo.createdRW.ImageCount, len(p.Looks))
|
||||
}
|
||||
}
|
||||
@ -272,7 +272,11 @@ func (s *IngestService) processRunway(ctx context.Context, job model.IngestJob,
|
||||
var timing *fetchTiming
|
||||
if len(p.Looks) > 0 {
|
||||
cover, images, keys, imgFailed, timing = s.fetchLookImages(ctx, p.Looks, "runway")
|
||||
imageCount = uint16(len(p.Looks))
|
||||
// image_count 必须等于**实际落库的主图行数**,不能是 len(p.Looks):
|
||||
// fetchLookImages 会跳过 look.Main == "" 的 look 与 sha1 重复的行,实际主图行可能更少。
|
||||
// 旧流程靠晋升时按实际行重算自愈,该路径已随单表发布模型删除 —— 一旦用 len(Looks),
|
||||
// 漂移会永久留在公开卡片的「N 张」角标与 FeaturedIDs 的 SUM(image_count) 热度上。
|
||||
imageCount = countMainImages(images)
|
||||
} else {
|
||||
var fimgs []fetchedImage
|
||||
cover, fimgs, keys, imgFailed, timing = s.fetchImages(ctx, p.Images, "runway", dto.IngestKindRunway)
|
||||
@ -337,7 +341,8 @@ func (s *IngestService) processRunway(ctx context.Context, job model.IngestJob,
|
||||
// fetchLookImages 按 Looks 结构下载主图+细节图并上传到存储,返回可直接落正式图片表的
|
||||
// BrandRunwayImage 行(带 look_index / is_detail 分组)。任意一张下载/上传失败即把
|
||||
// failed 置 true,调用方据此把整条任务判失败并回滚本批已上传的 key,符合「单图失败=整任务失败」策略。
|
||||
// cover 取首个成功下载的主图;image_count(主图数)由调用方按 len(Looks) 计,不在此返回。
|
||||
// cover 取首个成功下载的主图;image_count 由调用方按返回行中 is_detail == 0 的数量计
|
||||
//(countMainImages),而不是 len(Looks):跳过空主图 / sha1 重复后实际行数可能更少。
|
||||
// 每张图入库前做去重:命中 dHash 近重复则仍入库但标记留痕。
|
||||
//
|
||||
// 实现:先把全部「主图 + 细节图」按原始顺序摊平成任务列表,用 concurrentFetch 并发完成
|
||||
@ -415,6 +420,18 @@ func (s *IngestService) fetchLookImages(ctx context.Context, looks []dto.RunwayL
|
||||
return cover, rows, keys, failed, timing
|
||||
}
|
||||
|
||||
// countMainImages 数一批待落库图片行中的主图(is_detail = 0)数量,即 image_count 的口径。
|
||||
// 与 SoftDeleteRunwayImage 审核期重算的口径一致(只计主图),保证入库值与后续重算值同源。
|
||||
func countMainImages(images []model.BrandRunwayImage) uint16 {
|
||||
var n uint16
|
||||
for i := range images {
|
||||
if images[i].IsDetail == 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// processStreet 街拍入库:实体键分三支(新建 / 放弃 / 复用驳回)→ 下载图 → 直写 street_snaps(无品牌)。
|
||||
func (s *IngestService) processStreet(ctx context.Context, job model.IngestJob, p dto.RunwayIngest) {
|
||||
// 1) 实体键查重并决定分支(单表模型,同 runway)。
|
||||
|
||||
@ -260,7 +260,6 @@ func (s *streetSnapService) buildSnapImages(imgs []model.StreetSnapImage) []dto.
|
||||
return out
|
||||
}
|
||||
|
||||
// IDs 返回全部街拍的编码 uid(供 SSG 枚举详情页路径使用,对外暴露的即编码串)。
|
||||
// Popular 返回热度前 N 个街拍(按图片数降序),供 SSG 首页热门街拍展示。
|
||||
func (s *streetSnapService) Popular(ctx context.Context, limit int) ([]dto.PublicStreetSnap, error) {
|
||||
rows, err := s.repo.Popular(ctx, limit)
|
||||
|
||||
Reference in New Issue
Block a user