Compare commits

..

25 Commits

Author SHA1 Message Date
guke eb8641b551 Merge branch 'main' of https://gitea.shaguabijia.com/WonderableAI/shaguabijia-app-server into feat/inactivity-reset
# Conflicts:
#	docs/superpowers/specs/2026-07-16-inactivity-reset-design.md
2026-07-21 13:50:59 +08:00
guke 41f882098c docs(welfare): 同步 home_visible 事件名到 spec + 索引注释/docstring
- spec:活跃口径/§11 前端依赖等处 show+page=home、home_view 占位统一改 home_visible;
  修正 ACTIVE_EVENTS 说明(home_visible 是纯 event 名、已收进 ACTIVE_EVENTS)。
- analytics_event 索引注释 + 迁移 docstring:改单一 event=home_visible 过滤;
  注明 page 列是 show+home 组合遗留、现冗余(索引靠 event 前缀仍生效),可后续瘦成
  (event,user_id,created_at)。保留一句历史说明。纯注释/文档,无行为变更。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 13:45:26 +08:00
guke 9b6a4d83b6 fix(welfare): 不活跃验证脚本首页可见事件 show+home → home_visible
seed_inactivity_cases.py 仍发 event=show + page=home,改名 home_visible 后
active_event_condition 不再认它,"活跃兜底"用例会被误清/误警。改用共享常量
activity.HOME_VISIBLE_EVENT(单一 event 名,去掉 page),防止再次漂移。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 13:19:45 +08:00
guke 927f1f92f8 feat(welfare): 确认首页可见事件名 home_visible + 修测试手机号跨文件冲突
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 12:02:15 +08:00
guke 16414f1744 Merge branch 'main' into feat/inactivity-reset
main 已通过 #143 合入本功能的早期版本;拉 main 时功能文件(config / worker / inactivity /
tests / spec)冲突,一律以本分支为准(含 home_view→show+page=home、活跃口径复合索引、
迁移多头 merge、worker 常驻 + 默认 dry-run 等最新改动)。无关代码走 main 的自动合并。
alembic 单头、全量测试无新增失败。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 00:01:23 +08:00
guke 0cc2e9dec8 feat(welfare): 不活跃清零 worker 常驻 + 默认 dry-run(ENABLED=false 只记审计不清)
改 INACTIVITY_RESET_ENABLED 语义:worker 不再"关=不启动"、改为**常驻**;ENABLED 只控是否**真清**——
false(默认)= 只写审计名单(reason=inactive_Nd_dryrun)、不动钱不写流水、不预警(dry-run 灰度看名单);
true = 真清金币+现金 + 预警。

- clear_user(dry_run):写审计跳出账,按 streak 去重(reset_at>last_active)不重复记
- run_reset_once/run_once:透传 dry_run;dry-run 抑制预警(不通知一个不会发生的清零)
- worker:start 常驻(去掉 ENABLED 启动闸);_run_once_entry dry_run=not ENABLED;启动日志标 mode
- 测试:dry-run 只记审计/不清/不预警/dedup + worker ENABLED=false→dry-run;去掉过时 disabled 用例
- config/worker 注释 + spec §6/§13/误清防护 同步新语义

测试安全:lifespan 在测试里不跑(TestClient 非 with 形式),worker 常驻不影响用例。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 23:39:50 +08:00
guke 5fdf2b1ad3 chore(alembic): 合并 analytics_active_idx + phone_rebind_log 两 head(修复多头)
既有多头——135e79414fd0(不活跃两表)与 phone_rebind_log 同从 comparison_llm_cost 分叉——
导致 `alembic upgrade head` 多头报错。加一个空 merge 修订汇合两头,upgrade head 恢复单头正常。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 18:55:20 +08:00
guke fd1c1a5abc perf(analytics): analytics_event 活跃口径复合索引 (event,page,user_id,created_at)
active_event_condition 按 (event=show & page=home) ∪ 比价 ∪ 领券 过滤后 group by user_id、
max(created_at),是 worker 清零/预警 + admin 最近活跃的热点聚合;page 原无索引、show 又高频。
加覆盖索引 ix_analytics_event_active 让该聚合走 index-only。

⚠️ 分支迁移树既有多头(135e79414fd0 与 phone_rebind_log 同从 comparison_llm_cost 分叉,
`alembic upgrade head` 会多头报错)——既有问题、与本次无关。本迁移挂在 135e79414fd0 一侧,
dev 用 `alembic upgrade analytics_active_idx` 应用;集成 main 时需 alembic merge 合并 phone_rebind_log 头。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 18:31:15 +08:00
guke b4fe20aaca feat(welfare): 首页可见活跃信号定名 event=show + page=home(替换 home_view 占位)
前端确定"首页可见"埋点为 event=show + page=home(组合,非单一 event 名),故活跃口径
不能只改一个常量:

- activity.active_event_condition():首页可见(event=show & page=home)∪ 比价 ∪ 领券,
  worker 子查询(last_active_subqueries)与 admin _attach_last_active 共用(单一真源);
  ACTIVE_EVENTS 收窄为仅两个纯 event 名,HOME_VIEW_EVENT="show" + 新增 HOME_VIEW_PAGE="home"
- 测试:新增 show/home 算活跃、show/其他页不算的用例;_add_event 支持 page;口径常量断言更新
- seed 脚本 / spec / plan 同步 home_view → show+page=home

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 18:04:29 +08:00
guke 69a79f9852 Merge branch 'main' of https://gitea.shaguabijia.com/WonderableAI/shaguabijia-app-server into feat/inactivity-reset 2026-07-18 17:34:36 +08:00
guke aeaf4b1fd1 chore(scripts): 不活跃清零 人工验证造号脚本(排列组合 + 审计核对)
按金币/现金/邀请排列组合 + 活跃/新用户对照造号;--check 核对 worker 清零/预警结果、
--clean 清理。仅本地验证用,不参与生产逻辑。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:33:14 +08:00
guke ece498876f docs(welfare): 不活跃清零 设计/计划对齐"邀请金不清" + inactivity 两表字典
- spec/plan:清零范围改两桶、run_warn 逐用户隔离不阻塞清零、stats 增 warn_failed
- docs/database:新增 inactivity_reset_log / inactivity_notification_log 条目 + README 索引

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:33:04 +08:00
guke 40c99afd92 feat(welfare): 完成不活跃清零-邀请金不清 + 预警编排 + worker + admin口径统一
- 清零改两桶(金币 + 折算现金);邀请奖励金物理隔离、不清(产品红线),仅快照入审计
- 预警编排 select_warn_candidates / run_warn_once / run_once(分档 + streak 去重);
  notifier.warn 去掉 invite 参数(邀请金不清、不预警)
- 预警逐用户 try/except 隔离 + run_once 保证预警故障绝不阻塞清零(接真推送前必备)
- 每日 worker inactivity_reset_worker(文件锁 + 北京日守卫 + RUN_HOUR 门槛 + 总闸默认关)
  + main.py lifespan 接线
- admin 最近活跃口径改用共享 activity(移除 last_login_at、纳入 home_view 占位)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:32:52 +08:00
guke eb15018322 test(welfare): 不活跃测试加 autouse 隔离夹具(清零余额+清活跃事件/审计),去掉临时 band-aid
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 19:13:25 +08:00
guke a6cfef64a8 feat(welfare): 不活跃清零-选取与逐用户清零(三桶归零+审计+流水) 2026-07-16 18:54:40 +08:00
guke 7802aeb163 feat(welfare): 可插拔不活跃预警通知器 + LogNotifier 占位
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-16 18:47:50 +08:00
guke f843e68d0f feat(welfare): INACTIVITY_* 配置项 + warn stages 解析
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-16 18:47:02 +08:00
guke 108c175142 feat(welfare): 活跃口径共享模块-子查询与 last_active_expr 2026-07-16 18:40:36 +08:00
guke e6f467a935 feat(welfare): 活跃口径共享模块-常量与北京0点cutoff助手 2026-07-16 18:39:51 +08:00
guke 708e454959 feat(welfare): 迁移新增 inactivity_reset_log / inactivity_notification_log 两表
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-16 18:34:07 +08:00
guke 0ec6b2bc56 feat(welfare): inactivity_reset_log + inactivity_notification_log 模型 2026-07-16 18:23:20 +08:00
guke 23e4671312 docs(welfare): 15天不活跃清零 实现计划(11 任务, TDD 分解)
从已定稿 spec 拆出可执行计划:模型/迁移/活跃口径共享模块/配置/通知器/清零+预警业务逻辑/
每日 worker/admin 重构/表字典。每任务含失败测试→实现→通过→提交的 bite-sized 步骤,含完整代码。
活跃口径 = created_at 基线 + home_view/比价/领券(不含 last_login_at);home_view 事件名以
HOME_VIEW_EVENT 常量占位(前端明天定名);总闸默认关。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 18:16:47 +08:00
guke b3ed66d4eb docs(welfare): 活跃口径移除 last_login_at 改用 created_at 基线;home_view 事件名待定
按评审结论定稿:
- ① 彻底移除 last_login_at:活跃口径 = max(home_view, 比价, 领券);登录/re-login 不再计为活跃
- 连带:用 User.created_at 接替"恒非空基线"位(注册即第1日活跃,只有真实使用才推进)。
  无任何信号的用户 = 注册满 15 天即清,新用户有 15 天宽限
- ② home_view 事件名待前端明天加埋点时定,后端以 HOME_VIEW_EVENT 常量占位
- 连带影响:共享口径 admin 侧同步(移除 last_login_at + created_at 基线 + 纳入 home_view),
  admin 最近活跃/DAU 口径随之变化,回归测试按新口径更新预期
- 同步 §3/§4/§9/§10/§11/§12/§13/§14

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 17:58:45 +08:00
guke c9c35a4350 docs(welfare): 明确不活跃清零的时间边界(北京自然日, 第16日0点)
补充清零日界定义:末次活跃日记为第1日,从末次活跃起「第16日0点」(北京)清零
= 北京 00:00 of (last_active_date + 15天),按自然日 0 点对齐,非从末次活跃时刻滚动 15×24h。
- 应清零 ⟺ (cn_today() − last_active_date).days ≥ RESET_DAYS
- SQL cutoff = 北京 00:00 of (cn_today() − (RESET_DAYS−1)),新增 activity.reset_cutoff() 辅助
- 资格边界(第16日0点)与 worker 执行点 RUN_HOUR 解耦;inactive_days 改按北京自然日
- 同步更新 §4/§6/§8/§10

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 17:50:03 +08:00
guke 5f1d1a5e5f docs(welfare): 15天不活跃清零金币/现金 设计文档(spec)
连续15天不活跃自动清零金币+折算现金+邀请现金,清零前可配置节奏预警,全程留审计以备纠纷排查。

关键决策:
- 活跃口径复用"用户管理"并抽共享模块 activity.py(admin 一并重构);新增 home_view 埋点代表"进首页",last_login_at 仅作灰度期兜底
- 审计双写:inactivity_reset_log 专表(记清零前三桶余额)+ 钱包流水 biz_type=inactivity_reset
- 预警:可插拔通知器 + 日志占位(v1),后续接 JPush/短信
- 触发:进程内每日 worker(仿 daily_exchange_worker),总闸默认关

仅设计文档,尚未实现。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 17:39:10 +08:00
11 changed files with 15 additions and 441 deletions
@@ -1,52 +0,0 @@
"""add composite index (user_id, created_at, id) on comparison_record
C 端「我的比价记录」列表(GET /api/v1/compare/records)是
`WHERE user_id=? ORDER BY created_at DESC, id DESC LIMIT n` —— 原来只有单列 user_id 索引,
过滤完还要把该用户的**全部**记录取出来排序才能拿前 n 条,重度用户随记录数线性变慢。
本复合索引的反向扫恰好等于 (created_at DESC, id DESC),规划器直接取前 n 条、免排序。
列序 (user_id, created_at, id) 与查询一一对应,不要调整。
Revision ID: comparison_user_created_idx
Revises: merge_active_phone
Create Date: 2026-07-21
"""
from __future__ import annotations
from alembic import op
revision = "comparison_user_created_idx"
down_revision = "merge_active_phone"
branch_labels = None
depends_on = None
INDEX_NAME = "ix_comparison_user_created"
COLUMNS = ["user_id", "created_at", "id"]
def upgrade() -> None:
bind = op.get_bind()
if bind.dialect.name == "postgresql":
# 线上 comparison_record 已有数据量,普通 CREATE INDEX 持表写锁会阻塞比价 harvest 写入;
# 用 CONCURRENTLY 不锁表(须脱离事务,autocommit_block 切到自动提交)。
# 同 comparison_status_created_idx 的做法。
with op.get_context().autocommit_block():
op.create_index(
INDEX_NAME, "comparison_record", COLUMNS,
unique=False, postgresql_concurrently=True,
)
else:
op.create_index(INDEX_NAME, "comparison_record", COLUMNS, unique=False)
def downgrade() -> None:
bind = op.get_bind()
if bind.dialect.name == "postgresql":
with op.get_context().autocommit_block():
op.drop_index(
INDEX_NAME, table_name="comparison_record",
postgresql_concurrently=True,
)
else:
op.drop_index(INDEX_NAME, table_name="comparison_record")
+3 -7
View File
@@ -281,10 +281,7 @@ def ecpm_report(payload: EcpmReportIn, user: CurrentUser, db: DbSession) -> Ecpm
丢一两条不影响业务(穿山甲后台报表是结算权威)。eCPM 与发奖(S2S)是两条独立流,不逐条关联。
"""
attributed_trace_id = crud_ecpm.attributable_trace_id(
db,
feed_scene=payload.feed_scene,
trace_id=payload.trace_id,
exposure_ms=payload.exposure_ms,
db, feed_scene=payload.feed_scene, trace_id=payload.trace_id
)
if payload.trace_id and attributed_trace_id is None:
logger.info(
@@ -299,12 +296,11 @@ def ecpm_report(payload: EcpmReportIn, user: CurrentUser, db: DbSession) -> Ecpm
feed_scene=payload.feed_scene,
trace_id=attributed_trace_id,
app_env=payload.app_env, our_code_id=payload.our_code_id,
exposure_ms=payload.exposure_ms,
)
logger.info(
"ad ecpm report user_id=%d type=%s scene=%s session=%s ecpm=%s exposure_ms=%s adn=%s slot=%s app=%s code=%s",
"ad ecpm report user_id=%d type=%s scene=%s session=%s ecpm=%s adn=%s slot=%s app=%s code=%s",
user.id, payload.ad_type, payload.feed_scene, payload.ad_session_id, payload.ecpm,
payload.exposure_ms, payload.adn, payload.slot_id, payload.app_env, payload.our_code_id,
payload.adn, payload.slot_id, payload.app_env, payload.our_code_id,
)
return EcpmReportOut(ok=True)
+1 -10
View File
@@ -115,22 +115,13 @@ def list_records(
db: DbSession,
limit: int = Query(20, ge=1, le=100),
cursor: int | None = Query(None, description="上一页末条 id"),
ordered: bool | None = Query(
None,
description="true=只看「已下单」(店名命中本人真实下单)的记录;不传=全部",
),
keyword: str | None = Query(
None,
max_length=64,
description="按店名 / 菜名模糊搜索,忽略大小写;空白串等同不传",
),
include_trace: bool = Query(
False,
description="客户端开了本机 agent 调试模式时带 true,放行本人记录的 trace_url",
),
) -> ComparisonRecordPage:
items, next_cursor = crud_compare.list_records(
db, user.id, limit=limit, cursor=cursor, ordered=ordered, keyword=keyword
db, user.id, limit=limit, cursor=cursor
)
outs = [ComparisonRecordOut.model_validate(it) for it in items]
# 权限闸:未开 debug_trace_enabled 的用户不下发 trace_url(列表页「复制调试链接」靠它)。
-4
View File
@@ -45,10 +45,6 @@ class ComparisonRecord(Base):
# 首页轮播 / 省钱战绩聚合都按 status='success' 过滤 + created_at 近期排序;
# 复合索引避免随数据量增大退化成全表扫(单列 created_at 索引不含 status)。
Index("ix_comparison_status_created", "status", "created_at"),
# C 端「我的比价记录」列表:WHERE user_id=? ORDER BY created_at DESC, id DESC LIMIT n。
# 单列 user_id 索引只能过滤,排序仍要把该用户全部记录取出来排一遍;这条复合索引的**反向扫**
# 恰好等于 (created_at DESC, id DESC),PG 直接取前 n 条、免排序。列序不能动。
Index("ix_comparison_user_created", "user_id", "created_at", "id"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
+3 -22
View File
@@ -15,22 +15,9 @@ from app.core.rewards import cn_today
from app.models.ad_ecpm import AdEcpmRecord
from app.models.coupon_state import CouponSession
MIN_REVENUE_EXPOSURE_MS = 1000
def effective_ecpm_raw(ecpm_raw: str, exposure_ms: int | None) -> str:
"""曝光不足一秒时保留展示记录,但把该条有效 eCPM 归零。"""
if exposure_ms is not None and exposure_ms < MIN_REVENUE_EXPOSURE_MS:
return "0"
return ecpm_raw
def attributable_trace_id(
db: Session,
*,
feed_scene: str | None,
trace_id: str | None,
exposure_ms: int | None = None,
db: Session, *, feed_scene: str | None, trace_id: str | None
) -> str | None:
"""返回广告展示允许归属的业务 trace。
@@ -44,12 +31,7 @@ def attributable_trace_id(
session_status = db.execute(
select(CouponSession.status).where(CouponSession.trace_id == trace_id)
).scalar_one_or_none()
if session_status not in {"failed", "abandoned"}:
return trace_id
# 已真实上墙但不足一秒的曝光要在终态明细中明确显示 0,而不是被误判成“未填充”。
if exposure_ms is not None and exposure_ms < MIN_REVENUE_EXPOSURE_MS:
return trace_id
return None
return None if session_status in {"failed", "abandoned"} else trace_id
def create_ecpm_record(
@@ -65,7 +47,6 @@ def create_ecpm_record(
trace_id: str | None = None,
app_env: str | None = None,
our_code_id: str | None = None,
exposure_ms: int | None = None,
) -> AdEcpmRecord:
"""落一条 eCPM 上报记录。report_date 用北京时间当天,供按天聚合。
@@ -86,7 +67,7 @@ def create_ecpm_record(
trace_id=trace_id,
app_env=app_env,
our_code_id=our_code_id,
ecpm_raw=effective_ecpm_raw(ecpm_raw, exposure_ms),
ecpm_raw=ecpm_raw,
report_date=cn_today().isoformat(),
)
db.add(rec)
+8 -83
View File
@@ -7,8 +7,8 @@ from __future__ import annotations
from datetime import datetime
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session, defer
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from app.core.rewards import CN_TZ
from app.models.ad_feed_reward import AdFeedRewardRecord
@@ -375,48 +375,19 @@ def harvest_abort(
return rec
def _ordered_shop_name_select(user_id: int):
"""该用户「真实下单」(source='compare')覆盖到的店名 select,给「已下单」筛选当子查询
口径与 [_ordered_shop_names] 完全一致,只是时机不同:那边是**拿到本页之后**按 candidates
反查打标;这边是**分页之前**就要过滤,拿不到 candidates,只能整段下推成子查询。
没有先捞成集合再展开 IN (...) 字面量 —— 重度用户下单过的店名可能上千,展开会撞 SQLite
的绑定变量上限,而且又变回了那个「随下单量线性变慢」的老写法。
"""
return select(SavingsRecord.shop_name).where(
SavingsRecord.user_id == user_id,
SavingsRecord.source == "compare",
SavingsRecord.shop_name.is_not(None),
)
def _like_escape(kw: str) -> str:
"""转义 LIKE 通配符(百分号 / 下划线 / 反斜杠),让用户输入只按字面量匹配(配合 escape 参数)。
不转义的话搜一个「%」就等于把整表拉回来。
"""
return kw.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
def _ordered_shop_names(db: Session, user_id: int, candidates: set[str]) -> set[str]:
"""[candidates] 里哪些店名被该用户「真实下单」(source='compare')覆盖过,用来打「已下单」。
def _ordered_shop_names(db: Session, user_id: int) -> set[str]:
"""该用户「真实下单」(source='compare')覆盖到的店名集合,用来给比价记录打「已下单」
只认 compare(归因命中后真实上报),demo 演示数据不算。下单上报不带 trace_id,
只能按店名对齐——两边店名同源(都来自比价意图识别阶段的门店名 query),精确相等即视为同店。
语义=店级:同一家店比价过多次,这些记录会一并标「已下单」。
⚠️ 只查**本页出现过的店名**(candidates ≤ limit 条),不再把该用户全部下单店名捞回内存:
老写法随下单量线性增长,重度用户几千行全读一遍只为跟 50 条记录取交集。空集合直接返回
(避免 IN () 非法)。
"""
if not candidates:
return set()
rows = db.execute(
select(SavingsRecord.shop_name).where(
SavingsRecord.user_id == user_id,
SavingsRecord.source == "compare",
SavingsRecord.shop_name.in_(candidates),
).distinct()
SavingsRecord.shop_name.is_not(None),
)
).scalars().all()
return {s for s in rows if s}
@@ -444,60 +415,17 @@ def _ad_coins_by_trace(db: Session, user_id: int, trace_ids: list[str]) -> dict[
return {tid: int(coin) for tid, coin in rows if tid}
# 列表出参(ComparisonRecordOut)根本不读、但 select(ORM) 默认会一并捞回来的重型 JSON 列:
# - raw_payload:done.params 上报体全量,**每条记录都有**(harvest 与 POST 两条写路径都落)。
# 单条几 KB~几十 KB,一页 50 条就是稳定几百 KB~几 MB 的白读 + 白反序列化。
# - llm_calls:每次 LLM 调用的 input_messages + output 全文。只有走老客户端 POST /compare/record
# 的记录才有(_backfill_llm_calls 回填;harvest 路径不落),但有的时候单条就能到 MB 级 —— 一页里
# 混进几条这种记录,整个请求就被它们拖住。
# - llm_price_snapshot:逐模型单价快照,同样只在回填时落。
# 三列全部读出来再被 pydantic 丢掉,是「比价记录/全部记录」页慢的主要来源。
# ⚠️ defer 的列一旦在别处被读到会触发**逐行**懒加载(N+1);列表这条链路(ComparisonRecordOut
# 不声明这三个字段 → 不会 getattr 到)是安全的。详情接口 get_record 不 defer,raw_payload 照常返回。
_LIST_DEFERRED = (
ComparisonRecord.raw_payload,
ComparisonRecord.llm_calls,
ComparisonRecord.llm_price_snapshot,
)
def list_records(
db: Session,
user_id: int,
*,
limit: int = 20,
cursor: int | None = None,
ordered: bool | None = None,
keyword: str | None = None,
) -> tuple[list[ComparisonRecord], int | None]:
"""比价记录分页(按创建时间倒序、id 兜底,游标式)。附「已下单」店级标记 + 「看广告赚的金币」(瞬态,不写库)。"""
stmt = (
select(ComparisonRecord)
.where(ComparisonRecord.user_id == user_id)
.options(*(defer(col) for col in _LIST_DEFERRED))
)
stmt = select(ComparisonRecord).where(ComparisonRecord.user_id == user_id)
if cursor is not None:
stmt = stmt.where(ComparisonRecord.id < cursor)
# 「已下单」tab 与搜索框的过滤都下推到这里,不能留给客户端对整页结果 filter ——
# 分页之后一页里可能一条都不命中,列表看着就是空的/卡住的,得翻很多页才蹦出一条。
if ordered:
stmt = stmt.where(
ComparisonRecord.store_name.in_(_ordered_shop_name_select(user_id))
)
kw = (keyword or "").strip()
if kw:
# product_names 是写路径从 items[].name 派生的普通文本列(items 本身是 JSON,SQLite 下
# 中文被 ensure_ascii 转义,没法直接 LIKE)—— 搜「菜名」靠的就是它。
# ilike:PG 原生 ILIKE,SQLite 渲染成 lower() LIKE lower(),两边都忽略大小写。
pattern = f"%{_like_escape(kw)}%"
stmt = stmt.where(
or_(
ComparisonRecord.store_name.ilike(pattern, escape="\\"),
ComparisonRecord.product_names.ilike(pattern, escape="\\"),
)
)
# 排序与 ix_comparison_user_created(user_id, created_at, id)对齐 —— DESC/DESC 正好是该索引的
# 反向扫,PG 免排序直接取前 limit 条。改排序方向前先想清楚索引还吃不吃得上。
stmt = stmt.order_by(ComparisonRecord.created_at.desc(), ComparisonRecord.id.desc()).limit(limit)
items = list(db.execute(stmt).scalars().all())
@@ -505,10 +433,7 @@ def list_records(
# 「已下单」标记:本页记录的 store_name 若落在该用户真实下单的店名集合里即 True。
# ordered / ad_coins_earned 均非 ORM 列,仅挂实例上供 ComparisonRecordOut(from_attributes) 读出,不持久化。
page_shops = {it.store_name for it in items if it.store_name}
# ordered=True 时上面已按同一口径(_ordered_shop_name_select)筛过,本页必然全是已下单,
# 省掉这次反查;其余情况照旧按本页店名反查 savings。
ordered_shops = page_shops if ordered else _ordered_shop_names(db, user_id, page_shops)
ordered_shops = _ordered_shop_names(db, user_id)
# 「本次比价看广告赚的金币」:按本页 trace_id 一次性聚合(同 ordered 范式)。
ad_coins = _ad_coins_by_trace(db, user_id, [it.trace_id for it in items])
for it in items:
-6
View File
@@ -69,12 +69,6 @@ class EcpmReportIn(BaseModel):
description="本次比价/领券 trace_id(信息流场景带上):把这条展示收益归属到对应比价/领券,"
"供领券数据/比价记录看板聚合本场广告收益;激励视频/福利为空",
)
exposure_ms: int | None = Field(
None,
ge=0,
le=86_400_000,
description="本条广告真实在屏曝光毫秒数;小于 1000ms 时收益强制按 0 计算。旧客户端不传则保持原口径",
)
app_env: str | None = Field(
None, max_length=16, description="我们的穿山甲应用环境:prod(傻瓜比价正式) / test(测试应用)"
)
-12
View File
@@ -25,18 +25,6 @@ server {
# (纯文字反馈体积小、不受影响 → 呈现为「时好时坏」)。根治仍需客户端上传前压缩。
client_max_body_size 32m;
# JSON 响应压缩。nginx 默认 gzip off,且就算 on 了 gzip_types 也只含 text/html、
# gzip_proxied 默认 off(反代来的响应一律不压)—— 三个默认值凑一起 = 我们所有接口都在裸奔。
# 比价记录列表这种一次 50 条、字段名 + 中文店名/菜名高度重复的 JSON,gzip 压缩比稳定在 8~10 倍
# (几百 KB → 几十 KB),弱网下省的就是首屏那几秒。
# 只压 JSON:APK 直链(/media/shaguabijia.apk)、图片本身已是压缩格式,再压纯浪费 CPU。
gzip on;
gzip_proxied any; # 反代响应也压(默认 off = 对我们这套反代等于没开)
gzip_types application/json;
gzip_min_length 1024; # 小响应压了反而更大(gzip 头开销),不值当
gzip_comp_level 5; # 5 是体积/CPU 的常用折中点,再往上收益递减
gzip_vary on; # 给 CDN/中间缓存正确按 Accept-Encoding 分桶
location / {
proxy_pass http://127.0.0.1:8770;
proxy_http_version 1.1;
-9
View File
@@ -10,12 +10,6 @@
|---|---|---|---|---|
| `limit` | int | ❌ | 20 | 1100 |
| `cursor` | int | ❌ | null | 上一页末条 `id`,首页不传 |
| `ordered` | bool | ❌ | null | `true`=只出「已下单」(店名命中本人真实下单)的记录;不传=不筛 |
| `keyword` | string | ❌ | null | 按店名 / 菜名模糊搜索,忽略大小写,≤64 字符;纯空白等同不传 |
| `include_trace` | bool | ❌ | false | 客户端开了本机 agent 调试模式时带 `true`,放行**本人**记录的 `trace_url` |
`ordered` / `keyword` 都在服务端过滤后再分页,客户端不要拿一页结果自己 filter ——
分页之后一页里可能一条都不命中,列表会看着像空的。
## 出参
响应 `200``{ items: ComparisonRecordOut[], next_cursor: int|null }`(分页见 [索引#游标分页约定](./README.md#游标分页约定)
@@ -44,9 +38,6 @@
| `items` | object[] | 下单菜品 `{name, qty, specs?}` |
| `comparison_results` | object[] | 逐平台对比(price 单位元,已按 rank 升序) |
| `skipped_dish_names` | string[] | 被跳过的菜名 |
| `ordered` | bool | 「已下单」店级标记:店名命中本人 `source='compare'` 的下单记录即 `true`。**瞬态字段,不在表里**,每次查询现算 |
| `ad_coins_earned` | int | 本次比价看信息流广告实发的金币(按 `trace_id` 聚合)。同为瞬态字段 |
| `trace_url` | string \| null | pricebot 调试链接。未开 `debug_trace_enabled` 且未带 `include_trace=true` 时为 `null` |
| `created_at` | datetime | 时间 |
## 错误
-32
View File
@@ -58,32 +58,6 @@ def test_revenue_yuan_by_trace_empty() -> None:
db.close()
def test_short_exposure_keeps_record_with_zero_revenue() -> None:
"""不足一秒仍落展示记录,以便后台显示 0 而不是未填充。"""
db = SessionLocal()
try:
rec = crud_ecpm.create_ecpm_record(
db, 1, ad_type="draw", ecpm_raw="350",
ad_session_id="sess-short-exposure", feed_scene="coupon",
trace_id="trace-short-exposure", exposure_ms=999,
)
assert rec.ecpm_raw == "0"
assert crud_ecpm.revenue_yuan_by_trace(db, ["trace-short-exposure"]) == {
"trace-short-exposure": 0.0
}
finally:
db.execute(delete(AdEcpmRecord).where(
AdEcpmRecord.ad_session_id == "sess-short-exposure"
))
db.commit()
db.close()
def test_one_second_exposure_keeps_original_ecpm() -> None:
assert crud_ecpm.effective_ecpm_raw("350", 1000) == "350"
assert crud_ecpm.effective_ecpm_raw("350", None) == "350"
def test_terminal_coupon_trace_is_not_attributable_to_late_impression() -> None:
"""领券失败或被放弃后才到达的广告展示保留收益记录,但不再关联死亡 trace。"""
db = SessionLocal()
@@ -106,12 +80,6 @@ def test_terminal_coupon_trace_is_not_attributable_to_late_impression() -> None:
assert crud_ecpm.attributable_trace_id(
db, feed_scene="coupon", trace_id="abandoned-before-ad"
) is None
assert crud_ecpm.attributable_trace_id(
db, feed_scene="coupon", trace_id="failed-before-ad", exposure_ms=999
) == "failed-before-ad"
assert crud_ecpm.attributable_trace_id(
db, feed_scene="coupon", trace_id="abandoned-before-ad", exposure_ms=999
) == "abandoned-before-ad"
assert crud_ecpm.attributable_trace_id(
db, feed_scene="comparison", trace_id="failed-before-ad"
) == "failed-before-ad"
-204
View File
@@ -222,210 +222,6 @@ def test_stats_compare_count_and_saved(client) -> None:
assert s2["compare_count"] == 2 # 仍 2(failed 不计)
def test_records_ordered_flag(client) -> None:
"""「已下单」店级标记:店名命中该用户 source='compare' 的下单记录才 True。
覆盖 list_records 只按**本页店名**反查 savings 的写法(原来是把该用户全部下单店名捞回内存
再取交集,随下单量线性变慢)两种写法结果必须一致,故这里按店名逐条断言
"""
token = _login(client, "13800002010")
# 两条比价记录:一条海底捞(稍后会有对应下单),一条没下过单的店
client.post("/api/v1/compare/record", json=_food_payload("ord-1"), headers=_auth(token))
other = _food_payload("ord-2")
other["store_name"] = "没下过单的店"
client.post("/api/v1/compare/record", json=other, headers=_auth(token))
# 下单前:两条都不该带「已下单」
items = client.get("/api/v1/compare/records", headers=_auth(token)).json()["items"]
assert {it["store_name"]: it["ordered"] for it in items} == {
"海底捞(朝阳店)": False,
"没下过单的店": False,
}
# 对海底捞真实下单一笔(order/report 写 source='compare' 的 savings_record)
r = client.post(
"/api/v1/order/report",
json={
"client_event_id": "evt-ordered-flag",
"platform": "美团",
"platform_package": "com.sankuai.meituan",
"pay_channel": "wechat",
"compared_price_cents": 12350,
"paid_amount_cents": 12350,
"shop_name": "海底捞(朝阳店)",
"original_price_cents": 12850,
},
headers=_auth(token),
)
assert r.status_code == 200, r.text
# 下单后:只有同店名那条翻成 True,另一条不受影响
items = client.get("/api/v1/compare/records", headers=_auth(token)).json()["items"]
assert {it["store_name"]: it["ordered"] for it in items} == {
"海底捞(朝阳店)": True,
"没下过单的店": False,
}
# 别人的下单不该影响本人标记(_ordered_shop_names 按 user_id 过滤)
token_b = _login(client, "13800002011")
client.post("/api/v1/compare/record", json=_food_payload("ord-b"), headers=_auth(token_b))
items_b = client.get("/api/v1/compare/records", headers=_auth(token_b)).json()["items"]
assert [it["ordered"] for it in items_b] == [False]
def test_records_list_omits_raw_payload(client) -> None:
"""列表出参不含 raw_payload(仓库层 defer 掉了重型 JSON 列);详情接口照常返回。
defer 的列一旦被 ORM 实例读到会触发逐行懒加载(N+1),而列表 schema 本就不该带 raw_payload
这条同时守住列表不泄露上报体全量没人不小心把它加回出参
"""
token = _login(client, "13800002012")
rid = client.post(
"/api/v1/compare/record", json=_food_payload("no-raw"), headers=_auth(token)
).json()["id"]
items = client.get("/api/v1/compare/records", headers=_auth(token)).json()["items"]
assert len(items) == 1
assert "raw_payload" not in items[0]
# 概要字段照常齐全(defer 没误伤列表要用的列)
assert items[0]["store_name"] == "海底捞(朝阳店)"
assert items[0]["best_platform_id"] == "meituan"
assert items[0]["comparison_results"] and items[0]["items"]
# 详情不 defer:raw_payload 全量还在
d = client.get(f"/api/v1/compare/records/{rid}", headers=_auth(token)).json()
assert d["raw_payload"]["trace_id"] == "no-raw"
def test_records_ordered_filter(client) -> None:
"""ordered=true 只出「已下单」的记录,且过滤结果自身能翻页。
这个筛选必须在服务端做:客户端早先是对已经拉回来的那一页 filter,分页之后一页里
很可能一条已下单都没有 已下单tab 就会看着像空的,得手动翻很多页才蹦出一条
"""
token = _login(client, "13800002013")
# 3 条「下过单的店」+ 2 条没下过单的店,交错写入,确保过滤不是靠顺序碰巧对上
for i in range(3):
p = _food_payload(f"of-ordered-{i}")
p["store_name"] = "下过单的店"
client.post("/api/v1/compare/record", json=p, headers=_auth(token))
if i < 2:
q = _food_payload(f"of-plain-{i}")
q["store_name"] = "没下过单的店"
client.post("/api/v1/compare/record", json=q, headers=_auth(token))
client.post(
"/api/v1/order/report",
json={
"client_event_id": "evt-ordered-filter",
"platform": "美团",
"platform_package": "com.sankuai.meituan",
"pay_channel": "wechat",
"compared_price_cents": 12350,
"paid_amount_cents": 12350,
"shop_name": "下过单的店",
"original_price_cents": 12850,
},
headers=_auth(token),
)
# 不传 ordered:5 条全出(「全部记录」tab 口径不变)
assert len(client.get("/api/v1/compare/records", headers=_auth(token)).json()["items"]) == 5
# ordered=true:只出那 3 条,且每条都自带 ordered=True
page = client.get("/api/v1/compare/records?ordered=true", headers=_auth(token)).json()
assert [it["store_name"] for it in page["items"]] == ["下过单的店"] * 3
assert all(it["ordered"] for it in page["items"])
assert page["next_cursor"] is None
# 游标只在「已下单」集合内走 —— 不会把没下单的记录算进一页的 limit 里
p1 = client.get(
"/api/v1/compare/records?ordered=true&limit=2", headers=_auth(token)
).json()
assert len(p1["items"]) == 2
assert p1["next_cursor"] is not None
p2 = client.get(
f"/api/v1/compare/records?ordered=true&limit=2&cursor={p1['next_cursor']}",
headers=_auth(token),
).json()
assert [it["store_name"] for it in p2["items"]] == ["下过单的店"]
# 两页不重叠,合起来正好 3 条
assert len({it["id"] for it in p1["items"] + p2["items"]}) == 3
# 别人的下单不该让本人记录进「已下单」
token_b = _login(client, "13800002014")
pb = _food_payload("of-b")
pb["store_name"] = "下过单的店"
client.post("/api/v1/compare/record", json=pb, headers=_auth(token_b))
assert client.get(
"/api/v1/compare/records?ordered=true", headers=_auth(token_b)
).json()["items"] == []
def test_records_keyword_search(client) -> None:
"""keyword 按店名 / 菜名模糊搜(忽略大小写),LIKE 通配符只当字面量;搜索结果也能翻页。
菜名走写路径派生的 product_names 文本列 items JSON,SQLite 下中文被 ensure_ascii
转义,直接 LIKE 搜不到
"""
token = _login(client, "13800002015")
b = _food_payload("kw-b")
b["store_name"] = "Pizza Hut"
b["items"] = [{"name": "榴莲比萨", "qty": 1}]
client.post("/api/v1/compare/record", json=b, headers=_auth(token))
c = _food_payload("kw-c")
c["store_name"] = "100%纯牛肉汉堡"
c["items"] = [{"name": "双层牛肉堡", "qty": 1}]
client.post("/api/v1/compare/record", json=c, headers=_auth(token))
# 默认 payload 的店名是「海底捞(朝阳店)」
client.post("/api/v1/compare/record", json=_food_payload("kw-a"), headers=_auth(token))
def _search(kw: str, **extra) -> list[str]:
r = client.get(
"/api/v1/compare/records",
params={"keyword": kw, **extra},
headers=_auth(token),
)
assert r.status_code == 200, r.text
return [it["store_name"] for it in r.json()["items"]]
assert _search("海底捞") == ["海底捞(朝阳店)"] # 店名命中
assert _search("榴莲") == ["Pizza Hut"] # 菜名命中(product_names)
assert _search("pizza") == ["Pizza Hut"] # 忽略大小写
assert _search("PIZZA") == ["Pizza Hut"]
assert _search("不存在的店") == [] # 没命中就是空
# 通配符只当普通字符:搜 % 不该把整表拉回来,搜 _ 也不该匹配任意单字符
assert _search("%") == ["100%纯牛肉汉堡"]
assert _search("_") == []
# 纯空白等同不传 → 不过滤
assert len(_search(" ")) == 3
# 搜索结果自身可翻页
for i in range(3):
p = _food_payload(f"kw-page-{i}")
p["store_name"] = "连锁烤鱼店"
client.post("/api/v1/compare/record", json=p, headers=_auth(token))
p1 = client.get(
"/api/v1/compare/records",
params={"keyword": "烤鱼", "limit": 2},
headers=_auth(token),
).json()
assert len(p1["items"]) == 2
assert p1["next_cursor"] is not None
p2 = client.get(
"/api/v1/compare/records",
params={"keyword": "烤鱼", "limit": 2, "cursor": p1["next_cursor"]},
headers=_auth(token),
).json()
assert [it["store_name"] for it in p2["items"]] == ["连锁烤鱼店"]
assert len({it["id"] for it in p1["items"] + p2["items"]}) == 3
def test_requires_auth(client) -> None:
"""不带 token 统一 401。"""
assert client.post("/api/v1/compare/record", json={"trace_id": "t"}).status_code == 401