Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f449d3600 | |||
| c9ef4464f6 | |||
| e052fb778b | |||
| b0482ec157 | |||
| 0aee9d4dd0 | |||
| c6309f0f74 | |||
| 3b90e2f212 | |||
| b2ea6c727c | |||
| 5e706fd003 | |||
| 9c55344e85 | |||
| 4d3b73ae70 | |||
| 5dff56bbb2 | |||
| c734c00742 | |||
| 886e781a4f |
+11
-8
@@ -6,8 +6,17 @@ APP_NAME=shaguabijia-app-server
|
||||
APP_DEBUG=true
|
||||
|
||||
# ===== 数据库 =====
|
||||
# SQLite 本地文件路径。生产环境用 /opt/shaguabijia-app-server/data.db
|
||||
DATABASE_URL=sqlite:///./data/app.db
|
||||
# 本地开发/测试统一用 Docker PostgreSQL:run.bat/run.sh 会自动拉起容器
|
||||
# (docker-compose.yml + scripts/ensure_pg.py)。详见 docs/database/postgres-migration.md。
|
||||
# 生产用原生 PG,由 scripts/init_postgres.py 写入强随机密码的连接串。
|
||||
# ⚠️ scheme 必须是 postgresql+psycopg://(psycopg3);不要写成 postgresql://(会去找未装的 psycopg2)。
|
||||
DATABASE_URL=postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia
|
||||
# Docker 自动定位:run.bat/run.sh 会自动找 Docker Desktop 并启动——优先从 PATH 上的 docker CLI 反推
|
||||
# 安装目录(装在 D 盘等非默认盘符也能找到),再退到注册表 / 常见目录。仅当你的安装位置极特殊、自动
|
||||
# 探测失败时,才需下面这行显式指到 exe(值可含空格,直接写到行尾即可,无需引号):
|
||||
# DOCKER_DESKTOP_EXE=D:\Program Files\Docker\Docker\Docker Desktop.exe
|
||||
# 实在不想装/启 Docker → 把上面 DATABASE_URL 改成 sqlite 可降级跑(仅救急,PG 专有 SQL/严格性不被验证):
|
||||
# DATABASE_URL=sqlite:///./data/app.db
|
||||
|
||||
# ===== JWT =====
|
||||
# 生产部署务必改成随机长字符串,可用:python -c "import secrets; print(secrets.token_urlsafe(64))"
|
||||
@@ -175,9 +184,3 @@ PANGLE_REPORT_SITE_ID_TEST=5832303
|
||||
# APPLOG_MAX_BATCH=500 # 单批最大条数(超 → 422;导入期常量,改需重启)
|
||||
# APPLOG_MAX_BODY_BYTES=2097152 # 请求体上限 2MB(超 → 413;运行期可调)
|
||||
# APPLOG_MAX_MSG_BYTES=8192 # 单条 msg 超此字节数截断
|
||||
|
||||
# ===== 华为 Push =====
|
||||
HUAWEI_PUSH_APP_ID=
|
||||
HUAWEI_PUSH_APP_SECRET=
|
||||
# 0=正式消息(默认);1=测试消息(仅开发联调,生产必须保持 0)
|
||||
HUAWEI_PUSH_TARGET_USER_TYPE=0
|
||||
|
||||
@@ -60,3 +60,6 @@ tests/meituan_coupon_bj.tsv
|
||||
tests/meituan_coupon_data.tsv
|
||||
tests/meituan_coupon_fz.tsv
|
||||
tests/meituan_coupon_xm.tsv
|
||||
|
||||
# git worktrees (superpowers 隔离工作区)
|
||||
.worktrees/
|
||||
|
||||
@@ -76,8 +76,8 @@ Endpoints under `app/api/internal/` are for server-to-server communication (pric
|
||||
|
||||
## Database
|
||||
|
||||
- **Dev**: SQLite (`sqlite:///./data/app.db`), `check_same_thread=False`, no connection pool.
|
||||
- **Prod**: PostgreSQL — just change `DATABASE_URL` in `.env`. Pool size 10 + max overflow 20, pool_recycle 3600.
|
||||
- **Dev/Test**: Docker PostgreSQL 16 — `run.sh`/`run.bat` auto-start it via `scripts/ensure_pg.py` + `docker-compose.yml`; `.env.example` ships the PG URL by default; pytest uses the same container's `shaguabijia_test` DB. **Local no longer uses SQLite** (the SQLite branch in `db/session.py` is retained as a fallback only).
|
||||
- **Prod**: native PostgreSQL — bootstrap with `scripts/init_postgres.py` (no Docker). Pool size 10 + max overflow 20, pool_recycle 3600.
|
||||
- **Migrations**: Alembic with `render_as_batch` for SQLite compatibility. ~60+ migration files in `alembic/versions/` (filenames are descriptive, not hex prefixes). Migration chain uses `down_revision` within each file.
|
||||
- **New models**: Define in `app/models/`, import in `app/models/__init__.py`, then run `alembic revision --autogenerate`.
|
||||
|
||||
@@ -89,7 +89,7 @@ All config via `pydantic-settings` in `app/core/config.py`. Single `Settings` cl
|
||||
|
||||
## Testing
|
||||
|
||||
- `tests/conftest.py`: Sets env vars BEFORE imports, creates temp SQLite file, builds all tables with `Base.metadata.create_all()`, tears down with `drop_all()` + unlink.
|
||||
- `tests/conftest.py`: Sets env vars BEFORE imports, ensures the Docker PG `shaguabijia_test` DB via `scripts/ensure_pg.py`, builds all tables with `Base.metadata.create_all()` (drop+create for a clean start), tears down with `drop_all()`.
|
||||
- External integrations are monkeypatched in tests (e.g., WeChat Pay, Jiguang, Pangle callbacks) — tests never make real HTTP calls.
|
||||
- `TestClient` from FastAPI is used for all tests. Rate limiting is disabled globally in tests.
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
"""merge comparison platforms + fail_reason heads
|
||||
|
||||
Revision ID: 6d2309208549
|
||||
Revises: comparison_platforms_col, comparison_record_fail_reason
|
||||
Create Date: 2026-07-29 01:48:41.868083
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '6d2309208549'
|
||||
down_revision: Union[str, Sequence[str], None] = ('comparison_platforms_col', 'comparison_record_fail_reason')
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -1,47 +0,0 @@
|
||||
"""add platforms unified array column to comparison_record
|
||||
|
||||
展示模型统一数组(pricebot done.params.platforms 原样存): 每平台一行、自带
|
||||
status/is_best/display, 记录页据此直接渲染, 不再靠 comparison_results + 客户端合并 + 前端派生。
|
||||
纯新增列, 老记录为空 → 前端回退老 comparison_results。
|
||||
|
||||
Revision ID: comparison_platforms_col
|
||||
Revises: user_manual_risk_fields
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision: str = "comparison_platforms_col"
|
||||
down_revision: str | None = "user_manual_risk_fields"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 幂等: 线上为了提前给历史数据补 platforms(2026-07-29), 已手动
|
||||
# `ALTER TABLE comparison_record ADD COLUMN IF NOT EXISTS platforms jsonb
|
||||
# NOT NULL DEFAULT '[]'::jsonb`(与本 migration 定义一致)。列已存在时跳过,
|
||||
# 否则上线 alembic upgrade head 会撞 DuplicateColumn 直接部署失败。
|
||||
bind = op.get_bind()
|
||||
cols = {c["name"] for c in sa.inspect(bind).get_columns("comparison_record")}
|
||||
if "platforms" in cols:
|
||||
return
|
||||
with op.batch_alter_table("comparison_record") as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"platforms", _JSON, nullable=False,
|
||||
server_default=sa.text("'[]'"),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("comparison_record") as batch_op:
|
||||
batch_op.drop_column("platforms")
|
||||
@@ -1,49 +0,0 @@
|
||||
"""comparison_record.fail_reason (失败卡展示原因)
|
||||
|
||||
Revision ID: comparison_record_fail_reason
|
||||
Revises: user_manual_risk_fields
|
||||
Create Date: 2026-07-28 12:00:00.000000
|
||||
|
||||
失败记录的展示原因:information 具体则=它;笼统则由写路径从 platform_results 捞出的
|
||||
业务原因;纯系统失败为 None(端侧品牌兜底)。见 repositories.comparison._derive_fail_display。
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'comparison_record_fail_reason'
|
||||
down_revision: Union[str, Sequence[str], None] = 'user_manual_risk_fields'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('comparison_record', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fail_reason', sa.String(length=256), nullable=True))
|
||||
# 回填老失败记录:information 具体的直接搬过来(笼统/系统失败留 None → 端侧品牌兜底)。
|
||||
# 新记录由写路径 _derive_fail_display 落库(含 platform_results 救援/补判),不走这条。
|
||||
# platform_results 只在 raw_payload 里,SQL 里不易解析,故老记录不做救援/补判(可接受:
|
||||
# 老 mixed/打烊记录回退品牌兜底);具体 information 的老记录本次即可显示真实原因。
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE comparison_record
|
||||
SET fail_reason = information
|
||||
WHERE status = 'failed'
|
||||
AND information IS NOT NULL
|
||||
AND information <> ''
|
||||
AND information NOT IN (
|
||||
'比价过程出错,请稍后重试',
|
||||
'比价出错',
|
||||
'比价未完成',
|
||||
'done 参数缺少可验证的目标平台结果'
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('comparison_record', schema=None) as batch_op:
|
||||
batch_op.drop_column('fail_reason')
|
||||
@@ -1,31 +0,0 @@
|
||||
"""guide video play count is independent for coupon and comparison
|
||||
|
||||
Revision ID: guide_video_scene_unique
|
||||
Revises: 6d2309208549
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
revision = "guide_video_scene_unique"
|
||||
down_revision = "6d2309208549"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_index("uq_guide_video_play_user_seq", table_name="guide_video_play")
|
||||
op.create_index(
|
||||
"uq_guide_video_play_user_scene_seq",
|
||||
"guide_video_play",
|
||||
["user_id", "scene", "seq"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("uq_guide_video_play_user_scene_seq", table_name="guide_video_play")
|
||||
op.create_index(
|
||||
"uq_guide_video_play_user_seq",
|
||||
"guide_video_play",
|
||||
["user_id", "seq"],
|
||||
unique=True,
|
||||
)
|
||||
@@ -1,164 +0,0 @@
|
||||
"""guide video prepare/start/ten-circle reward state machine
|
||||
|
||||
Revision ID: guide_video_ten_circle_v2
|
||||
Revises: guide_video_scene_unique
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "guide_video_ten_circle_v2"
|
||||
down_revision = "guide_video_scene_unique"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _backfill_configs(connection) -> None:
|
||||
from app.core import media
|
||||
from app.core.config import settings
|
||||
|
||||
for key in ("coupon_guide_video", "comparison_guide_video"):
|
||||
row = connection.execute(
|
||||
sa.text("SELECT value FROM app_config WHERE key = :key"), {"key": key}
|
||||
).first()
|
||||
if not row:
|
||||
continue
|
||||
raw = row[0]
|
||||
value = json.loads(raw) if isinstance(raw, str) else dict(raw or {})
|
||||
if value.get("guide_video_v2_migrated") is True:
|
||||
continue
|
||||
maximum = int(value.get("max_plays", 3) or 0)
|
||||
reward = int(value.get("reward_coin", 100) or 0)
|
||||
video_url = str(value.get("video_url") or "")
|
||||
error = None
|
||||
analysis = None
|
||||
if not 1 <= maximum <= 50:
|
||||
error = "旧播放次数不符合 1~50 约束"
|
||||
elif not 10 <= reward <= 10_000 or reward % 10:
|
||||
error = "旧金币总价不符合 10~10000 且为 10 的倍数约束"
|
||||
elif not video_url:
|
||||
error = "尚未上传视频"
|
||||
else:
|
||||
prefix = f"{settings.MEDIA_URL_PREFIX}/guide_video/"
|
||||
if not video_url.startswith(prefix):
|
||||
error = "旧视频不是服务端托管文件,请重新上传"
|
||||
else:
|
||||
path = Path(settings.MEDIA_ROOT) / "guide_video" / video_url[len(prefix):]
|
||||
if not path.is_file():
|
||||
error = "旧视频文件缺失,请重新上传"
|
||||
else:
|
||||
try:
|
||||
analysis = media._probe_guide_video(path)
|
||||
except media.MediaError as exc:
|
||||
error = str(exc)
|
||||
value["config_version"] = int(value.get("config_version", 0) or 0) + 1
|
||||
value["guide_video_v2_migrated"] = True
|
||||
if analysis:
|
||||
value.update(analysis)
|
||||
else:
|
||||
value.update(
|
||||
enabled=False,
|
||||
duration_ms=None,
|
||||
video_codec=None,
|
||||
audio_codec=None,
|
||||
analysis_status="invalid" if video_url else "missing",
|
||||
analysis_error=error,
|
||||
)
|
||||
statement = sa.text(
|
||||
"UPDATE app_config SET value = :value WHERE key = :key"
|
||||
).bindparams(sa.bindparam("value", type_=sa.JSON()))
|
||||
connection.execute(statement, {"key": key, "value": value})
|
||||
|
||||
|
||||
def _seal_legacy_plays(connection) -> None:
|
||||
"""旧整笔发奖 token 永久封口;旧未发奖会话终止但仍保留计次行。"""
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE guide_video_play
|
||||
SET status = CASE WHEN status = 'granted' THEN 'legacy_completed' ELSE 'legacy_closed' END,
|
||||
settled_circles = CASE WHEN status = 'granted' THEN 10 ELSE 0 END,
|
||||
prepared_at = started_at,
|
||||
expires_at = started_at
|
||||
WHERE status IN ('granted', 'playing')
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _prepare_downgrade(connection) -> None:
|
||||
"""清除未起播计划,并把所有保留 token 封成旧版不可再领奖的 granted。"""
|
||||
connection.execute(
|
||||
sa.text("DELETE FROM guide_video_play WHERE status = 'prepared'")
|
||||
)
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE guide_video_play
|
||||
SET status = 'granted',
|
||||
completed = CASE WHEN settled_circles >= 10 THEN 1 ELSE completed END,
|
||||
granted_at = CASE
|
||||
WHEN settled_circles >= 10 AND granted_at IS NULL THEN started_at
|
||||
ELSE granted_at
|
||||
END
|
||||
WHERE status IN (
|
||||
'started', 'completed', 'legacy_completed', 'legacy_closed'
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
# 防御未知/中间状态:宁可删除,也绝不让旧应用把它当 playing 整笔发奖。
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
DELETE FROM guide_video_play
|
||||
WHERE seq IS NULL OR started_at IS NULL OR status != 'granted'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("guide_video_play") as batch:
|
||||
batch.alter_column("seq", existing_type=sa.Integer(), nullable=True)
|
||||
batch.alter_column("started_at", existing_type=sa.DateTime(timezone=True), nullable=True)
|
||||
batch.add_column(sa.Column("duration_ms", sa.Integer(), nullable=False, server_default="0"))
|
||||
batch.add_column(sa.Column("config_version", sa.Integer(), nullable=False, server_default="0"))
|
||||
batch.add_column(sa.Column("settled_circles", sa.Integer(), nullable=False, server_default="0"))
|
||||
batch.add_column(
|
||||
sa.Column("prepared_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now())
|
||||
)
|
||||
batch.add_column(sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True))
|
||||
batch.alter_column("status", existing_type=sa.String(length=16), type_=sa.String(length=24))
|
||||
op.create_index("ix_guide_video_play_expires_at", "guide_video_play", ["expires_at"])
|
||||
op.create_index(
|
||||
"ux_coin_transaction_guide_video_ref",
|
||||
"coin_transaction",
|
||||
["user_id", "biz_type", "ref_id"],
|
||||
unique=True,
|
||||
sqlite_where=sa.text("biz_type = 'guide_video' AND ref_id IS NOT NULL"),
|
||||
postgresql_where=sa.text("biz_type = 'guide_video' AND ref_id IS NOT NULL"),
|
||||
)
|
||||
connection = op.get_bind()
|
||||
_seal_legacy_plays(connection)
|
||||
_backfill_configs(connection)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_prepare_downgrade(op.get_bind())
|
||||
op.drop_index("ux_coin_transaction_guide_video_ref", table_name="coin_transaction")
|
||||
op.drop_index("ix_guide_video_play_expires_at", table_name="guide_video_play")
|
||||
with op.batch_alter_table("guide_video_play") as batch:
|
||||
batch.alter_column("status", existing_type=sa.String(length=24), type_=sa.String(length=16))
|
||||
batch.drop_column("expires_at")
|
||||
batch.drop_column("prepared_at")
|
||||
batch.drop_column("settled_circles")
|
||||
batch.drop_column("config_version")
|
||||
batch.drop_column("duration_ms")
|
||||
batch.alter_column("started_at", existing_type=sa.DateTime(timezone=True), nullable=False)
|
||||
batch.alter_column("seq", existing_type=sa.Integer(), nullable=False)
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
"""Admin 后台 FastAPI app(独立进程)。
|
||||
|
||||
启动:uvicorn app.admin.main:admin_app --host 127.0.0.1 --port 8773
|
||||
启动:uvicorn app.admin.main:admin_app --host 127.0.0.1 --port 8771
|
||||
复用 App 的 DB/models/repositories/integrations;鉴权独立(admin JWT,见 app/admin/security.py)。
|
||||
现有 app.main:app 不 import 本模块,两进程互不影响。
|
||||
"""
|
||||
@@ -71,8 +71,8 @@ admin_app = FastAPI(
|
||||
|
||||
# admin 前端独立部署。生产同域(nginx)无需 CORS;本地 next dev 跨域需放行开发源。
|
||||
_dev_origins = [
|
||||
"http://localhost:3002",
|
||||
"http://127.0.0.1:3002",
|
||||
"http://localhost:3001",
|
||||
"http://127.0.0.1:3001",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
]
|
||||
|
||||
@@ -43,7 +43,7 @@ _KNOWN_PROD_BUSINESS_CODE_IDS = frozenset({"104098712", "104099389"})
|
||||
_TEST_BUSINESS_CODE_IDS = frozenset({"104127529", "104127626", "104137445"})
|
||||
|
||||
|
||||
def business_code_ids(db: Session, app_env: str | None) -> set[str]:
|
||||
def _business_code_ids(db: Session, app_env: str | None) -> set[str]:
|
||||
"""返回指定应用环境下可用于业务收益对账的 GroMore 聚合代码位。"""
|
||||
prod_config = app_config.get_ad_config(db)
|
||||
prod_ids = set(_KNOWN_PROD_BUSINESS_CODE_IDS) | {
|
||||
@@ -320,10 +320,10 @@ def ad_revenue_report(
|
||||
|
||||
# 业务口径仅保留正式配置/测试业务链路实际使用的代码位。穿山甲“全量”还包含广告测试
|
||||
# demo、插屏等没有客户端收益上报的曝光,两边直接比较会天然产生假差额。
|
||||
business_ids: set[str] | None = None
|
||||
business_code_ids: set[str] | None = None
|
||||
if revenue_scope == "business":
|
||||
business_ids = business_code_ids(db, app_env)
|
||||
events = [e for e in events if e.get("our_code_id") in business_ids]
|
||||
business_code_ids = _business_code_ids(db, app_env)
|
||||
events = [e for e in events if e.get("our_code_id") in business_code_ids]
|
||||
|
||||
# 排序:time=按时间倒序(新→旧);ecpm=按 eCPM 数值倒序(eCPM 原值是字符串「分」,转数值排;
|
||||
# 纯发奖行用其发奖采用的 eCPM,缺失/非法计 0 排末尾)。
|
||||
@@ -381,7 +381,7 @@ def ad_revenue_report(
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
app_env=app_env,
|
||||
our_code_ids=business_ids,
|
||||
our_code_ids=business_code_ids,
|
||||
)
|
||||
if pangle_aggs:
|
||||
by_date = {a["date"]: a for a in pangle_aggs}
|
||||
|
||||
@@ -14,7 +14,6 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.core import rewards
|
||||
from app.core.config import settings
|
||||
from app.models.ad_ecpm import AdEcpmRecord
|
||||
from app.models.ad_feed_reward import AdFeedRewardRecord
|
||||
from app.models.ad_reward import AdRewardRecord
|
||||
from app.models.admin import AdminAuditLog
|
||||
@@ -1258,15 +1257,11 @@ def user_reward_stats(
|
||||
date_from: datetime | None = None,
|
||||
date_to: datetime | None = None,
|
||||
withdraw_source: str | None = None,
|
||||
app_env: str | None = None,
|
||||
revenue_scope: str = "all",
|
||||
feed_scene: str | None = None,
|
||||
) -> dict:
|
||||
"""提现详情「用户统计区」10 项。窗口作用于除「现金余额」外的所有项(余额是当前快照)。
|
||||
|
||||
口径:激励视频/信息流奖励数量只统计 granted;数量——视频按条数、信息流按份数(unit_count 累加)。
|
||||
平均 Draw eCPM 与广告收益报表一致:基于 ad_ecpm_record 的全部 draw/feed 展示记录计算,
|
||||
不以是否发奖为筛选条件。各「提现」= 该来源累计金币折现。
|
||||
口径:激励视频/信息流只统计 granted;数量——视频按条数、信息流按份数(unit_count 累加);
|
||||
平均 eCPM 用原始分值(分/千次)按记录取算术平均;各「提现」= 该来源累计金币折现。
|
||||
传统任务 = 窗口内正向金币中,排除广告(reward_video/feed_ad_reward)与人工调整后的折现。
|
||||
"""
|
||||
withdraw_source_conds = (
|
||||
@@ -1301,68 +1296,30 @@ def user_reward_stats(
|
||||
|
||||
# 只投影本统计实际使用的列。避免滚动发布或旧本地库尚未补齐无关新列时,
|
||||
# SQLAlchemy 因 select(ORM) 自动展开整表字段而让提现详情整体 500。
|
||||
business_ids: set[str] | None = None
|
||||
if revenue_scope == "business":
|
||||
# 与广告收益报表共用正式/测试业务代码位集合,避免两个页面随配置切换后再次漂移。
|
||||
from app.admin.repositories.ad_revenue import business_code_ids
|
||||
|
||||
business_ids = business_code_ids(db, app_env)
|
||||
|
||||
rv_conds = [
|
||||
AdRewardRecord.user_id == user_id,
|
||||
AdRewardRecord.reward_scene == "reward_video",
|
||||
AdRewardRecord.status == "granted",
|
||||
*_window_conds(AdRewardRecord.created_at, date_from, date_to),
|
||||
]
|
||||
if app_env is not None:
|
||||
rv_conds.append(AdRewardRecord.app_env == app_env)
|
||||
if business_ids is not None:
|
||||
rv_conds.append(AdRewardRecord.our_code_id.in_(business_ids))
|
||||
rv = db.execute(
|
||||
select(AdRewardRecord.ecpm_raw, AdRewardRecord.coin).where(
|
||||
*rv_conds,
|
||||
AdRewardRecord.user_id == user_id,
|
||||
AdRewardRecord.reward_scene == "reward_video",
|
||||
AdRewardRecord.status == "granted",
|
||||
*_window_conds(AdRewardRecord.created_at, date_from, date_to),
|
||||
)
|
||||
).all()
|
||||
rv_ecpms = [rewards.parse_ecpm_fen(r.ecpm_raw) for r in rv if r.ecpm_raw]
|
||||
rv_coins = sum(r.coin for r in rv)
|
||||
|
||||
feed_reward_conds = [
|
||||
AdFeedRewardRecord.user_id == user_id,
|
||||
AdFeedRewardRecord.status == "granted",
|
||||
*_window_conds(AdFeedRewardRecord.created_at, date_from, date_to),
|
||||
]
|
||||
if app_env is not None:
|
||||
feed_reward_conds.append(AdFeedRewardRecord.app_env == app_env)
|
||||
if feed_scene is not None:
|
||||
feed_reward_conds.append(AdFeedRewardRecord.feed_scene == feed_scene)
|
||||
if business_ids is not None:
|
||||
feed_reward_conds.append(AdFeedRewardRecord.our_code_id.in_(business_ids))
|
||||
feed_rewards = db.execute(
|
||||
feed = db.execute(
|
||||
select(
|
||||
AdFeedRewardRecord.unit_count,
|
||||
AdFeedRewardRecord.ecpm_raw,
|
||||
AdFeedRewardRecord.coin,
|
||||
).where(
|
||||
*feed_reward_conds,
|
||||
AdFeedRewardRecord.user_id == user_id,
|
||||
AdFeedRewardRecord.status == "granted",
|
||||
*_window_conds(AdFeedRewardRecord.created_at, date_from, date_to),
|
||||
)
|
||||
).all()
|
||||
feed_coins = sum(f.coin for f in feed_rewards)
|
||||
|
||||
feed_impression_conds = [
|
||||
AdEcpmRecord.user_id == user_id,
|
||||
AdEcpmRecord.ad_type.in_(("draw", "feed")),
|
||||
*_window_conds(AdEcpmRecord.created_at, date_from, date_to),
|
||||
]
|
||||
if app_env is not None:
|
||||
feed_impression_conds.append(AdEcpmRecord.app_env == app_env)
|
||||
if feed_scene is not None:
|
||||
feed_impression_conds.append(AdEcpmRecord.feed_scene == feed_scene)
|
||||
if business_ids is not None:
|
||||
feed_impression_conds.append(AdEcpmRecord.our_code_id.in_(business_ids))
|
||||
feed_impressions = db.execute(
|
||||
select(AdEcpmRecord.ecpm_raw).where(*feed_impression_conds)
|
||||
).all()
|
||||
# 与 ad_revenue.category_stats 相同:每次展示权重相同,非法原值按 parse_ecpm_fen 记 0。
|
||||
feed_ecpms = [rewards.parse_ecpm_fen(row.ecpm_raw) for row in feed_impressions]
|
||||
feed_ecpms = [rewards.parse_ecpm_fen(f.ecpm_raw) for f in feed if f.ecpm_raw]
|
||||
feed_coins = sum(f.coin for f in feed)
|
||||
|
||||
trad_coins = db.execute(
|
||||
select(func.coalesce(func.sum(CoinTransaction.amount), 0)).where(
|
||||
@@ -1381,7 +1338,7 @@ def user_reward_stats(
|
||||
"reward_video_count": len(rv),
|
||||
"reward_video_avg_ecpm": round(sum(rv_ecpms) / len(rv_ecpms), 2) if rv_ecpms else 0.0,
|
||||
"reward_video_cash_cents": _coins_to_cents(rv_coins),
|
||||
"feed_count": int(sum(f.unit_count for f in feed_rewards)),
|
||||
"feed_count": int(sum(f.unit_count for f in feed)),
|
||||
"feed_avg_ecpm": round(sum(feed_ecpms) / len(feed_ecpms), 2) if feed_ecpms else 0.0,
|
||||
"feed_cash_cents": _coins_to_cents(feed_coins),
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""admin 反馈工单:列表筛选 + 审核采纳/拒绝(带金币发放与审计)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
@@ -26,8 +25,6 @@ from app.models.feedback import Feedback
|
||||
from app.repositories import wallet as wallet_repo
|
||||
from app.services import notification_events
|
||||
|
||||
logger = logging.getLogger("shagua.admin.feedback")
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/admin/api/feedbacks",
|
||||
tags=["admin-feedback"],
|
||||
@@ -49,24 +46,10 @@ def _approve_feedback(
|
||||
*,
|
||||
bulk: bool = False,
|
||||
) -> FeedbackOut:
|
||||
logger.info(
|
||||
"feedback approve started feedback_id=%s admin_id=%s bulk=%s",
|
||||
feedback_id, admin.id, bulk,
|
||||
)
|
||||
fb = db.get(Feedback, feedback_id, with_for_update=True)
|
||||
if fb is None:
|
||||
logger.warning(
|
||||
"feedback approve rejected not found feedback_id=%s admin_id=%s bulk=%s",
|
||||
feedback_id, admin.id, bulk,
|
||||
)
|
||||
raise HTTPException(status_code=404, detail="反馈不存在")
|
||||
if fb.status not in {"pending", "new"}:
|
||||
logger.warning(
|
||||
"feedback approve rejected invalid status feedback_id=%s user_id=%s "
|
||||
"admin_id=%s status=%s bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, fb.status, bulk,
|
||||
)
|
||||
_ensure_pending(fb)
|
||||
_ensure_pending(fb)
|
||||
|
||||
before = fb.status
|
||||
mutations.review_feedback(
|
||||
@@ -108,18 +91,8 @@ def _approve_feedback(
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(fb)
|
||||
logger.info(
|
||||
"feedback approve committed feedback_id=%s user_id=%s admin_id=%s "
|
||||
"before=%s after=%s reward_coins=%s bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, before, fb.status, payload.reward_coins, bulk,
|
||||
)
|
||||
out = FeedbackOut.model_validate(fb)
|
||||
notification_events.notify_feedback_reward(db, fb)
|
||||
logger.info(
|
||||
"feedback approve notification dispatch returned feedback_id=%s user_id=%s "
|
||||
"admin_id=%s notification_type=feedback_reward bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, bulk,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@@ -132,24 +105,10 @@ def _reject_feedback(
|
||||
*,
|
||||
bulk: bool = False,
|
||||
) -> FeedbackOut:
|
||||
logger.info(
|
||||
"feedback reject started feedback_id=%s admin_id=%s bulk=%s",
|
||||
feedback_id, admin.id, bulk,
|
||||
)
|
||||
fb = db.get(Feedback, feedback_id, with_for_update=True)
|
||||
if fb is None:
|
||||
logger.warning(
|
||||
"feedback reject rejected not found feedback_id=%s admin_id=%s bulk=%s",
|
||||
feedback_id, admin.id, bulk,
|
||||
)
|
||||
raise HTTPException(status_code=404, detail="反馈不存在")
|
||||
if fb.status not in {"pending", "new"}:
|
||||
logger.warning(
|
||||
"feedback reject rejected invalid status feedback_id=%s user_id=%s "
|
||||
"admin_id=%s status=%s bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, fb.status, bulk,
|
||||
)
|
||||
_ensure_pending(fb)
|
||||
_ensure_pending(fb)
|
||||
|
||||
before = fb.status
|
||||
mutations.review_feedback(
|
||||
@@ -183,18 +142,8 @@ def _reject_feedback(
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(fb)
|
||||
logger.info(
|
||||
"feedback reject committed feedback_id=%s user_id=%s admin_id=%s "
|
||||
"before=%s after=%s bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, before, fb.status, bulk,
|
||||
)
|
||||
out = FeedbackOut.model_validate(fb)
|
||||
notification_events.notify_feedback_reply(db, fb)
|
||||
logger.info(
|
||||
"feedback reject notification dispatch returned feedback_id=%s user_id=%s "
|
||||
"admin_id=%s notification_type=feedback_reply bulk=%s",
|
||||
feedback_id, fb.user_id, admin.id, bulk,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@@ -252,10 +201,6 @@ def bulk_approve_feedbacks(
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
) -> FeedbackBulkResult:
|
||||
logger.info(
|
||||
"feedback bulk approve started admin_id=%s item_count=%s",
|
||||
admin.id, len(body.ids),
|
||||
)
|
||||
results: list[FeedbackBulkItemResult] = []
|
||||
ip = get_client_ip(request)
|
||||
for feedback_id in body.ids:
|
||||
@@ -264,24 +209,11 @@ def bulk_approve_feedbacks(
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=True, status=out.status))
|
||||
except HTTPException as exc:
|
||||
db.rollback()
|
||||
logger.warning(
|
||||
"feedback bulk approve item failed feedback_id=%s admin_id=%s error=%s",
|
||||
feedback_id, admin.id, exc.detail,
|
||||
)
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=False, error=str(exc.detail)))
|
||||
except Exception: # noqa: BLE001 - 单笔失败不打断整批
|
||||
db.rollback()
|
||||
logger.exception(
|
||||
"feedback bulk approve item failed feedback_id=%s admin_id=%s",
|
||||
feedback_id, admin.id,
|
||||
)
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=False, error="系统异常"))
|
||||
result = _bulk_result(results)
|
||||
logger.info(
|
||||
"feedback bulk approve completed admin_id=%s total=%s success=%s failed=%s",
|
||||
admin.id, result.total, result.success, result.failed,
|
||||
)
|
||||
return result
|
||||
return _bulk_result(results)
|
||||
|
||||
|
||||
@router.post("/bulk/reject", response_model=FeedbackBulkResult, summary="批量拒绝采纳反馈")
|
||||
@@ -291,10 +223,6 @@ def bulk_reject_feedbacks(
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
) -> FeedbackBulkResult:
|
||||
logger.info(
|
||||
"feedback bulk reject started admin_id=%s item_count=%s",
|
||||
admin.id, len(body.ids),
|
||||
)
|
||||
results: list[FeedbackBulkItemResult] = []
|
||||
ip = get_client_ip(request)
|
||||
for feedback_id in body.ids:
|
||||
@@ -303,24 +231,11 @@ def bulk_reject_feedbacks(
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=True, status=out.status))
|
||||
except HTTPException as exc:
|
||||
db.rollback()
|
||||
logger.warning(
|
||||
"feedback bulk reject item failed feedback_id=%s admin_id=%s error=%s",
|
||||
feedback_id, admin.id, exc.detail,
|
||||
)
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=False, error=str(exc.detail)))
|
||||
except Exception: # noqa: BLE001 - 单笔失败不打断整批
|
||||
db.rollback()
|
||||
logger.exception(
|
||||
"feedback bulk reject item failed feedback_id=%s admin_id=%s",
|
||||
feedback_id, admin.id,
|
||||
)
|
||||
results.append(FeedbackBulkItemResult(id=feedback_id, ok=False, error="系统异常"))
|
||||
result = _bulk_result(results)
|
||||
logger.info(
|
||||
"feedback bulk reject completed admin_id=%s total=%s success=%s failed=%s",
|
||||
admin.id, result.total, result.success, result.failed,
|
||||
)
|
||||
return result
|
||||
return _bulk_result(results)
|
||||
|
||||
|
||||
@router.post("/{feedback_id}/handle", response_model=OkResponse, summary="标记反馈已处理")
|
||||
@@ -343,16 +258,7 @@ def approve_feedback(
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
) -> FeedbackOut:
|
||||
try:
|
||||
return _approve_feedback(db, admin, feedback_id, payload, get_client_ip(request))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"feedback approve failed feedback_id=%s admin_id=%s",
|
||||
feedback_id, admin.id,
|
||||
)
|
||||
raise
|
||||
return _approve_feedback(db, admin, feedback_id, payload, get_client_ip(request))
|
||||
|
||||
|
||||
@router.post("/{feedback_id}/reject", response_model=FeedbackOut, summary="拒绝采纳反馈")
|
||||
@@ -363,13 +269,4 @@ def reject_feedback(
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
) -> FeedbackOut:
|
||||
try:
|
||||
return _reject_feedback(db, admin, feedback_id, payload, get_client_ip(request))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"feedback reject failed feedback_id=%s admin_id=%s",
|
||||
feedback_id, admin.id,
|
||||
)
|
||||
raise
|
||||
return _reject_feedback(db, admin, feedback_id, payload, get_client_ip(request))
|
||||
|
||||
@@ -9,7 +9,7 @@ client_max_body_size,见 shaguabijia-admin-web/deploy/nginx/admin.shaguabijia.co
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated, Literal
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||
|
||||
@@ -27,16 +27,14 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
GuideScene = Literal["coupon", "comparison"]
|
||||
|
||||
|
||||
def _out(db: AdminDb, scene: GuideScene) -> GuideVideoConfigOut:
|
||||
return GuideVideoConfigOut(scene=scene, **guide_video.get_config(db, scene))
|
||||
def _out(db: AdminDb) -> GuideVideoConfigOut:
|
||||
"""配置 + 播放统计合成响应(四个写接口都以最新状态返回,前端一次同步到位)。"""
|
||||
return GuideVideoConfigOut(**guide_video.get_config(db), **guide_video.play_stats(db))
|
||||
|
||||
|
||||
@router.get("", response_model=GuideVideoConfigOut, summary="新手引导视频配置(领券浮层)")
|
||||
def get_config(db: AdminDb, scene: GuideScene = "coupon") -> GuideVideoConfigOut:
|
||||
return _out(db, scene)
|
||||
def get_config(db: AdminDb) -> GuideVideoConfigOut:
|
||||
return _out(db)
|
||||
|
||||
|
||||
@router.patch("", response_model=GuideVideoConfigOut, summary="改开关/次数/金币(带审计)")
|
||||
@@ -45,26 +43,21 @@ def update_config(
|
||||
request: Request,
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
scene: GuideScene = "coupon",
|
||||
) -> GuideVideoConfigOut:
|
||||
try:
|
||||
before, after = guide_video.update_config(
|
||||
db,
|
||||
enabled=body.enabled,
|
||||
max_plays=body.max_plays,
|
||||
reward_coin=body.reward_coin,
|
||||
scene=scene,
|
||||
admin_id=admin.id,
|
||||
commit=False,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
before, after = guide_video.update_config(
|
||||
db,
|
||||
enabled=body.enabled,
|
||||
max_plays=body.max_plays,
|
||||
reward_coin=body.reward_coin,
|
||||
admin_id=admin.id,
|
||||
commit=False,
|
||||
)
|
||||
write_audit(
|
||||
db, admin, action="guide_video.update", target_type="guide_video", target_id=None,
|
||||
detail={"scene": scene, "before": before, "after": after}, ip=get_client_ip(request), commit=False,
|
||||
detail={"before": before, "after": after}, ip=get_client_ip(request), commit=False,
|
||||
)
|
||||
db.commit()
|
||||
return _out(db, scene)
|
||||
return _out(db)
|
||||
|
||||
|
||||
@router.post("/video", response_model=GuideVideoConfigOut, summary="上传新手引导视频(MP4,带审计)")
|
||||
@@ -72,40 +65,23 @@ async def upload_video(
|
||||
request: Request,
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
file: Annotated[UploadFile, File()],
|
||||
scene: GuideScene = "coupon",
|
||||
file: UploadFile = File(...),
|
||||
) -> GuideVideoConfigOut:
|
||||
data = await file.read()
|
||||
url: str | None = None
|
||||
try:
|
||||
url, analysis = media.save_guide_video(data)
|
||||
url = media.save_guide_video(data)
|
||||
except media.MediaError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
try:
|
||||
before, after = guide_video.set_video(
|
||||
db, url, analysis=analysis, scene=scene, admin_id=admin.id, commit=False
|
||||
)
|
||||
write_audit(
|
||||
db, admin, action="guide_video.set_video", target_type="guide_video", target_id=None,
|
||||
detail={
|
||||
"scene": scene,
|
||||
"before": before.get("video_url"),
|
||||
"after": url,
|
||||
"bytes": len(data),
|
||||
"duration_ms": analysis["duration_ms"],
|
||||
"video_codec": analysis["video_codec"],
|
||||
"audio_codec": analysis["audio_codec"],
|
||||
},
|
||||
ip=get_client_ip(request), commit=False,
|
||||
)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
media.delete_guide_video(url)
|
||||
raise
|
||||
# 旧文件仍可能被 prepare/已起播快照引用,不能在这里立即删除。
|
||||
guide_video.cleanup_old_videos(db)
|
||||
return _out(db, scene)
|
||||
before, after = guide_video.set_video(db, url, admin_id=admin.id, commit=False)
|
||||
write_audit(
|
||||
db, admin, action="guide_video.set_video", target_type="guide_video", target_id=None,
|
||||
detail={"before": before.get("video_url"), "after": url, "bytes": len(data)},
|
||||
ip=get_client_ip(request), commit=False,
|
||||
)
|
||||
db.commit()
|
||||
# 提交成功后再删旧片,避免新片没落库就把旧片丢了
|
||||
media.delete_guide_video(before.get("video_url"))
|
||||
return _out(db)
|
||||
|
||||
|
||||
@router.delete("/video", response_model=GuideVideoConfigOut, summary="移除新手引导视频(带审计)")
|
||||
@@ -113,17 +89,13 @@ def delete_video(
|
||||
request: Request,
|
||||
admin: Annotated[AdminUser, Depends(require_role("operator"))],
|
||||
db: AdminDb,
|
||||
scene: GuideScene = "coupon",
|
||||
) -> GuideVideoConfigOut:
|
||||
"""移除后 /guide-video/start 一律返回 should_play=false,领券浮层回到「只放广告」。"""
|
||||
before, after = guide_video.set_video(
|
||||
db, None, scene=scene, admin_id=admin.id, commit=False
|
||||
)
|
||||
before, after = guide_video.set_video(db, None, admin_id=admin.id, commit=False)
|
||||
write_audit(
|
||||
db, admin, action="guide_video.delete_video", target_type="guide_video", target_id=None,
|
||||
detail={"scene": scene, "before": before.get("video_url")}, ip=get_client_ip(request), commit=False,
|
||||
detail={"before": before.get("video_url")}, ip=get_client_ip(request), commit=False,
|
||||
)
|
||||
db.commit()
|
||||
# 旧文件由保护期清理任务处理,避免破坏有效计划与已起播快照。
|
||||
guide_video.cleanup_old_videos(db)
|
||||
return _out(db, scene)
|
||||
media.delete_guide_video(before.get("video_url"))
|
||||
return _out(db)
|
||||
|
||||
@@ -88,11 +88,6 @@ def get_user_reward_stats(
|
||||
withdraw_source: Annotated[
|
||||
str | None, Query(pattern="^(coin_cash|invite_cash)$")
|
||||
] = None,
|
||||
app_env: Annotated[str | None, Query(pattern="^(prod|test)$")] = None,
|
||||
revenue_scope: Annotated[str, Query(pattern="^(business|all)$")] = "all",
|
||||
feed_scene: Annotated[
|
||||
str | None, Query(pattern="^(comparison|coupon|welfare)$")
|
||||
] = None,
|
||||
) -> UserRewardStats:
|
||||
"""提现详情抽屉「用户统计区」。date_from/date_to 都不传 = 注册至今(全量)。"""
|
||||
if not user_repo.user_exists(db, user_id):
|
||||
@@ -104,9 +99,6 @@ def get_user_reward_stats(
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
withdraw_source=withdraw_source,
|
||||
app_env=app_env,
|
||||
revenue_scope=revenue_scope,
|
||||
feed_scene=feed_scene,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1,44 +1,25 @@
|
||||
"""后台引导视频配置协议。"""
|
||||
"""admin 新手引导视频配置 schemas(开关 / 视频地址 / 前几次 / 每次金币)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.repositories.guide_video import (
|
||||
MAX_PLAYS_LIMIT,
|
||||
MIN_PLAYS,
|
||||
MIN_REWARD_COIN,
|
||||
REWARD_COIN_LIMIT,
|
||||
)
|
||||
from app.repositories.guide_video import MAX_PLAYS_LIMIT, REWARD_COIN_LIMIT
|
||||
|
||||
|
||||
class GuideVideoConfigOut(BaseModel):
|
||||
scene: str
|
||||
enabled: bool
|
||||
video_url: str | None = None
|
||||
video_url: str | None = None # 相对地址 /media/guide_video/xxx.mp4;未配片 = None
|
||||
max_plays: int
|
||||
reward_coin: int
|
||||
duration_ms: int | None = None
|
||||
circle_count: int = 10
|
||||
circle_duration_ms: float | None = None
|
||||
reward_per_circle: int
|
||||
video_codec: str | None = None
|
||||
audio_codec: str | None = None
|
||||
analysis_status: str
|
||||
analysis_error: str | None = None
|
||||
config_version: int
|
||||
updated_at: str | None = None
|
||||
# 只读统计,后台展示用:已有多少次播放、其中已发币多少次。
|
||||
total_plays: int = 0
|
||||
granted_plays: int = 0
|
||||
|
||||
|
||||
class GuideVideoConfigUpdate(BaseModel):
|
||||
enabled: bool | None = None
|
||||
max_plays: int | None = Field(default=None, ge=MIN_PLAYS, le=MAX_PLAYS_LIMIT)
|
||||
reward_coin: int | None = Field(
|
||||
default=None, ge=MIN_REWARD_COIN, le=REWARD_COIN_LIMIT
|
||||
)
|
||||
"""部分更新:只改传入(非 None)字段。视频文件走 /video 上传接口。"""
|
||||
|
||||
@field_validator("reward_coin")
|
||||
@classmethod
|
||||
def reward_must_be_multiple_of_ten(cls, value: int | None) -> int | None:
|
||||
if value is not None and value % 10:
|
||||
raise ValueError("金币总价必须是 10 的倍数")
|
||||
return value
|
||||
enabled: bool | None = None
|
||||
max_plays: int | None = Field(default=None, ge=0, le=MAX_PLAYS_LIMIT)
|
||||
reward_coin: int | None = Field(default=None, ge=0, le=REWARD_COIN_LIMIT)
|
||||
|
||||
@@ -60,7 +60,7 @@ class UserRewardStats(BaseModel):
|
||||
reward_video_avg_ecpm: float # 平均激励视频 eCPM(分/千次)
|
||||
reward_video_cash_cents: int # 激励视频提现(金币折现)
|
||||
feed_count: int # 累计信息流广告数(granted 份数,unit_count 累加)
|
||||
feed_avg_ecpm: float # 全部 Draw/feed 实际展示的平均 eCPM(分/千次,含未发奖展示)
|
||||
feed_avg_ecpm: float # 平均信息流广告 eCPM(分/千次)
|
||||
feed_cash_cents: int # 信息流广告提现(金币折现)
|
||||
|
||||
|
||||
|
||||
+3
-11
@@ -108,7 +108,7 @@ def _harvest_done_blocking(
|
||||
|
||||
def _harvest_abort_blocking(
|
||||
trace_id: str, status_hint: str, reason: str | None, trace_url: str | None,
|
||||
) -> int | None:
|
||||
) -> None:
|
||||
with SessionLocal() as db:
|
||||
rec = crud_compare.harvest_abort(
|
||||
db, trace_id=trace_id, status=status_hint, reason=reason, trace_url=trace_url,
|
||||
@@ -118,7 +118,6 @@ def _harvest_abort_blocking(
|
||||
extra={"phase": "harvest_abort",
|
||||
"status": (rec.status if rec else None), "reason": reason},
|
||||
)
|
||||
return rec.id if rec is not None else None
|
||||
|
||||
|
||||
async def _forward(
|
||||
@@ -292,10 +291,7 @@ async def trace_epilogue(
|
||||
|
||||
@router.post("/trace/finalize", summary="比价 trace 收尾上云 (透传 + 夭折落库)")
|
||||
async def trace_finalize(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
user: OptionalUser,
|
||||
db: DbSession,
|
||||
request: Request, user: OptionalUser, db: DbSession
|
||||
) -> dict[str, Any]:
|
||||
_ensure_compare_allowed(user, db)
|
||||
# 用户终止 / Phase1 未识别没到 done 帧: pricebot 打包半截上云返回 {trace_url};
|
||||
@@ -306,16 +302,12 @@ async def trace_finalize(
|
||||
request, "/api/trace/finalize", user, harvest_first_frame=False,
|
||||
)
|
||||
try:
|
||||
record_id = await run_in_threadpool(
|
||||
await run_in_threadpool(
|
||||
_harvest_abort_blocking, trace_id,
|
||||
(meta.get("status") or "cancelled"),
|
||||
(meta.get("reason") or meta.get("information")),
|
||||
(resp.get("trace_url") if isinstance(resp, dict) else None),
|
||||
)
|
||||
if record_id is not None:
|
||||
background_tasks.add_task(
|
||||
backfill_comparison_llm_cost, record_id, trace_id
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("harvest_abort failed trace=%s: %s", trace_id, e)
|
||||
return resp
|
||||
|
||||
+27
-42
@@ -1,16 +1,22 @@
|
||||
"""引导视频 prepare/start/reward 客户端 API。"""
|
||||
"""新手引导视频(领券等候浮层前 N 次替代广告)。
|
||||
|
||||
路由前缀 `/api/v1/guide-video`(均需 Bearer):
|
||||
POST /start 这次浮层放引导视频还是放广告?命中则**当场计次**并下发 play_token
|
||||
POST /reward 播完 / 中途关闭都调,按 play_token 幂等发固定金币
|
||||
|
||||
发币额度以**服务端配置**为准(运营后台可改),客户端只报"播完/关闭",报不了金额,
|
||||
所以被破解也刷不到超额金币;次数上限由 guide_video_play 行数(按账号)硬卡。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.core.ratelimit import rate_limit
|
||||
from app.repositories import guide_video as crud_guide
|
||||
from app.schemas.guide_video import (
|
||||
GuideVideoPrepareIn,
|
||||
GuideVideoPrepareOut,
|
||||
GuideVideoRewardIn,
|
||||
GuideVideoRewardOut,
|
||||
GuideVideoStartIn,
|
||||
@@ -18,41 +24,25 @@ from app.schemas.guide_video import (
|
||||
)
|
||||
|
||||
logger = logging.getLogger("shagua.guide_video")
|
||||
|
||||
router = APIRouter(prefix="/api/v1/guide-video", tags=["guide-video"])
|
||||
|
||||
|
||||
@router.post(
|
||||
"/prepare",
|
||||
response_model=GuideVideoPrepareOut,
|
||||
dependencies=[Depends(rate_limit(60, 60, "guide-video-prepare"))],
|
||||
)
|
||||
def prepare(
|
||||
payload: GuideVideoPrepareIn, user: CurrentUser, db: DbSession
|
||||
) -> GuideVideoPrepareOut:
|
||||
result = crud_guide.prepare_play(db, user.id, scene=payload.scene)
|
||||
logger.info(
|
||||
"guide video prepare user_id=%d scene=%s should_play=%s reason=%s",
|
||||
user.id, payload.scene, result["should_play"], result["reason"],
|
||||
)
|
||||
return GuideVideoPrepareOut(**result)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/start",
|
||||
response_model=GuideVideoStartOut,
|
||||
summary="领券浮层是否放新手引导视频(命中即计次)",
|
||||
dependencies=[Depends(rate_limit(60, 60, "guide-video-start"))],
|
||||
)
|
||||
def start(
|
||||
payload: GuideVideoStartIn, user: CurrentUser, db: DbSession
|
||||
) -> GuideVideoStartOut:
|
||||
try:
|
||||
result = crud_guide.start_play(db, user.id, play_token=payload.play_token)
|
||||
except crud_guide.PlayStateError as exc:
|
||||
status_code = 404 if exc.code == "play_not_found" else 409
|
||||
raise HTTPException(status_code=status_code, detail=exc.detail()) from exc
|
||||
def start(payload: GuideVideoStartIn, user: CurrentUser, db: DbSession) -> GuideVideoStartOut:
|
||||
"""开播即计数:返回 should_play=True 时服务端已写下这一次,客户端必须真的播。
|
||||
|
||||
没配视频 / 开关关 / 次数用完 → should_play=False,客户端照旧走广告链路(行为不变)。
|
||||
"""
|
||||
result = crud_guide.start_play(db, user.id, scene=payload.scene or "coupon")
|
||||
logger.info(
|
||||
"guide video start user_id=%d token=%s status=%s seq=%d",
|
||||
user.id, payload.play_token[:12], result["status"], result["seq"],
|
||||
"guide video start user_id=%d scene=%s should_play=%s seq=%d remaining=%d",
|
||||
user.id, payload.scene, result["should_play"], result["seq"], result["remaining"],
|
||||
)
|
||||
return GuideVideoStartOut(**result)
|
||||
|
||||
@@ -60,20 +50,15 @@ def start(
|
||||
@router.post(
|
||||
"/reward",
|
||||
response_model=GuideVideoRewardOut,
|
||||
dependencies=[Depends(rate_limit(120, 60, "guide-video-reward"))],
|
||||
summary="引导视频发金币(播完/中途关闭都发,play_token 幂等)",
|
||||
dependencies=[Depends(rate_limit(60, 60, "guide-video-reward"))],
|
||||
)
|
||||
def reward(
|
||||
payload: GuideVideoRewardIn, user: CurrentUser, db: DbSession
|
||||
) -> GuideVideoRewardOut:
|
||||
result = crud_guide.grant_circle(
|
||||
db,
|
||||
user.id,
|
||||
play_token=payload.play_token,
|
||||
circle=payload.circle,
|
||||
def reward(payload: GuideVideoRewardIn, user: CurrentUser, db: DbSession) -> GuideVideoRewardOut:
|
||||
result = crud_guide.grant_play(
|
||||
db, user.id, play_token=payload.play_token, completed=payload.completed
|
||||
)
|
||||
logger.info(
|
||||
"guide video reward user_id=%d token=%s circle=%d status=%s granted=%s",
|
||||
user.id, payload.play_token[:12], payload.circle,
|
||||
result["status"], result["granted"],
|
||||
"guide video reward user_id=%d token=%s completed=%s granted=%s coin=%d",
|
||||
user.id, payload.play_token[:12], payload.completed, result["granted"], result["coin"],
|
||||
)
|
||||
return GuideVideoRewardOut(**result)
|
||||
|
||||
@@ -88,8 +88,6 @@ class Settings(BaseSettings):
|
||||
# (OAuth 换 token 时 client_id 即 AppId)。发送走 v1 messages:send,成功码 80000000。
|
||||
HUAWEI_PUSH_APP_ID: str = ""
|
||||
HUAWEI_PUSH_APP_SECRET: str = ""
|
||||
# 0=正式消息(默认,受正式消息频控);1=测试消息(仅开发联调,勿用于生产)。
|
||||
HUAWEI_PUSH_TARGET_USER_TYPE: int = Field(default=0, ge=0, le=1)
|
||||
HUAWEI_PUSH_TOKEN_ENDPOINT: str = "https://oauth-login.cloud.huawei.com/oauth2/v3/token"
|
||||
HUAWEI_PUSH_SEND_ENDPOINT_TEMPLATE: str = (
|
||||
"https://push-api.cloud.huawei.com/v1/{app_id}/messages:send"
|
||||
@@ -438,7 +436,6 @@ class Settings(BaseSettings):
|
||||
# 运营后台上传的新手引导视频上限。视频比图片大一个量级,单独一档;
|
||||
# ⚠️ 改大时同步放宽网关 client_max_body_size(实测 QA 4MiB / prod 32MiB),否则 nginx 先挡下。
|
||||
GUIDE_VIDEO_MAX_BYTES: int = 100 * 1024 * 1024 # 引导视频最大 100MB
|
||||
FFPROBE_BINARY: str = "ffprobe"
|
||||
|
||||
# ===== 邀请好友 =====
|
||||
# 分享落地页(二维码 / 分享链接指向这里;扫码 → 落地页 → 引导浏览器下载 APK)。
|
||||
|
||||
+9
-76
@@ -10,13 +10,8 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
@@ -86,91 +81,29 @@ def _sniff_video_ext(data: bytes) -> str | None:
|
||||
"""按魔数判定视频类型,返回扩展名;非支持类型返回 None。
|
||||
|
||||
只认 MP4 家族(ISO BMFF):`....ftyp` 在偏移 4。Android ExoPlayer 与浏览器 <video>
|
||||
支持 H.264 或 HEVC/H.265 视频及 AAC 音频;放开 mkv/avi 只会让端上放不出来,
|
||||
不如在入口就挡掉。
|
||||
都稳吃 H.264/AAC 的 mp4;放开 mkv/avi 只会让端上放不出来,不如在入口就挡掉。
|
||||
"""
|
||||
if len(data) >= 12 and data[4:8] == b"ftyp":
|
||||
return ".mp4"
|
||||
return None
|
||||
|
||||
|
||||
def _probe_guide_video(path: Path) -> dict[str, Any]:
|
||||
"""用 ffprobe 读取服务端可信的时长/编码信息。"""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[
|
||||
settings.FFPROBE_BINARY,
|
||||
"-v", "error",
|
||||
"-show_format",
|
||||
"-show_streams",
|
||||
"-of", "json",
|
||||
str(path),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
raise MediaError("服务器未安装 ffprobe,暂时无法分析视频") from exc
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise MediaError("ffprobe 分析视频失败") from exc
|
||||
if proc.returncode != 0:
|
||||
raise MediaError("无法分析视频,请确认文件是有效的 MP4")
|
||||
try:
|
||||
payload = json.loads(proc.stdout)
|
||||
streams = payload.get("streams") or []
|
||||
video = next(s for s in streams if s.get("codec_type") == "video")
|
||||
audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
|
||||
raw_duration = (
|
||||
(payload.get("format") or {}).get("duration")
|
||||
or video.get("duration")
|
||||
)
|
||||
duration_ms = int(
|
||||
(Decimal(str(raw_duration)) * 1000).quantize(Decimal("1"), rounding=ROUND_HALF_UP)
|
||||
)
|
||||
except (StopIteration, TypeError, ValueError, InvalidOperation) as exc:
|
||||
raise MediaError("视频缺少可识别的视频轨或时长") from exc
|
||||
video_codec = str(video.get("codec_name") or "").lower()
|
||||
audio_codec = str(audio.get("codec_name") or "").lower() if audio else None
|
||||
if not 30_000 <= duration_ms <= 180_000:
|
||||
raise MediaError("视频时长必须在 30~180 秒之间")
|
||||
if video_codec not in ("h264", "hevc", "h265"):
|
||||
raise MediaError("视频编码必须为 H.264 或 HEVC/H.265")
|
||||
if audio_codec not in (None, "aac"):
|
||||
raise MediaError("音频编码必须为 AAC")
|
||||
return {
|
||||
"duration_ms": duration_ms,
|
||||
"video_codec": video_codec,
|
||||
"audio_codec": audio_codec,
|
||||
"analysis_status": "valid",
|
||||
"analysis_error": None,
|
||||
}
|
||||
def save_guide_video(data: bytes) -> str:
|
||||
"""保存新手引导视频(运营后台上传的运营素材),返回相对 URL(`/media/guide_video/<file>`)。
|
||||
|
||||
|
||||
def save_guide_video(data: bytes) -> tuple[str, dict[str, Any]]:
|
||||
"""临时落盘、ffprobe 校验后原子发布,返回 URL 与分析结果。"""
|
||||
与图片分开一套校验:体积上限走 [settings.GUIDE_VIDEO_MAX_BYTES],类型只认 MP4。
|
||||
"""
|
||||
if not data:
|
||||
raise MediaError("空文件")
|
||||
limit = settings.GUIDE_VIDEO_MAX_BYTES
|
||||
if len(data) > limit:
|
||||
raise MediaError(f"视频过大(上限 {limit // (1024 * 1024)}MB)")
|
||||
if _sniff_video_ext(data) is None:
|
||||
raise MediaError("仅支持 MP4 视频(H.264 或 HEVC/H.265 编码)")
|
||||
raise MediaError("仅支持 MP4 视频(H.264 编码)")
|
||||
|
||||
directory = _media_dir("guide_video")
|
||||
stem = f"guide_{secrets.token_hex(8)}"
|
||||
temp_path = directory / f".{stem}.upload"
|
||||
final_path = directory / f"{stem}.mp4"
|
||||
try:
|
||||
temp_path.write_bytes(data)
|
||||
analysis = _probe_guide_video(temp_path)
|
||||
os.replace(temp_path, final_path)
|
||||
except Exception:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
final_path.unlink(missing_ok=True)
|
||||
raise
|
||||
return f"{settings.MEDIA_URL_PREFIX}/guide_video/{final_path.name}", analysis
|
||||
fname = f"guide_{secrets.token_hex(8)}.mp4"
|
||||
(_media_dir("guide_video") / fname).write_bytes(data)
|
||||
return f"{settings.MEDIA_URL_PREFIX}/guide_video/{fname}"
|
||||
|
||||
|
||||
def save_cps_image(admin_id: int, data: bytes) -> str:
|
||||
|
||||
+46
-455
@@ -22,7 +22,7 @@ import uuid
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import quote, urlsplit
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -31,7 +31,6 @@ from app.core.config import settings
|
||||
logger = logging.getLogger("shagua.vendor_push")
|
||||
|
||||
TYPE_ACCESSIBILITY_DISABLED = "accessibility_disabled"
|
||||
DATA_EVENT_NOTIFICATION_CREATED = "notification_created"
|
||||
SUPPORTED_VENDORS = frozenset({"honor", "huawei", "vivo", "xiaomi", "oppo"})
|
||||
|
||||
# vendor key → 中文名(测试/配置状态接口展示用)
|
||||
@@ -70,18 +69,6 @@ class _CachedToken:
|
||||
|
||||
_token_cache: dict[str, _CachedToken] = {}
|
||||
|
||||
_LOG_SUMMARY_MAX_CHARS = 1500
|
||||
_LOG_STRING_MAX_CHARS = 200
|
||||
_SENSITIVE_LOG_KEYS = {
|
||||
"accesstoken",
|
||||
"appkey",
|
||||
"authtoken",
|
||||
"authorization",
|
||||
"clientsecret",
|
||||
"mastersecret",
|
||||
"sign",
|
||||
}
|
||||
|
||||
|
||||
def normalize_vendor(push_vendor: str | None) -> str | None:
|
||||
if not push_vendor:
|
||||
@@ -128,16 +115,8 @@ def send_notification(
|
||||
|
||||
if mock:
|
||||
logger.info(
|
||||
"vendor push mock vendor=%s request=%s",
|
||||
vendor,
|
||||
_log_summary(
|
||||
{
|
||||
"push_token": token,
|
||||
"title": title,
|
||||
"body": body,
|
||||
"extras": extras,
|
||||
}
|
||||
),
|
||||
"[mock push] vendor=%s token=%s... title=%s body=%s extras=%s",
|
||||
vendor, token[:12], title, body, extras,
|
||||
)
|
||||
return {
|
||||
"mock": True,
|
||||
@@ -154,28 +133,7 @@ def send_notification(
|
||||
"xiaomi": _send_xiaomi,
|
||||
"oppo": _send_oppo,
|
||||
}
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
result = dispatch[vendor](token, title, body, extras)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"vendor push dispatch failed vendor=%s token=%s notification_type=%s "
|
||||
"elapsed_ms=%.1f",
|
||||
vendor,
|
||||
token,
|
||||
extras.get("type", ""),
|
||||
_elapsed_ms(started),
|
||||
)
|
||||
raise
|
||||
logger.info(
|
||||
"vendor push dispatch succeeded vendor=%s token=%s notification_type=%s "
|
||||
"elapsed_ms=%.1f",
|
||||
vendor,
|
||||
token,
|
||||
extras.get("type", ""),
|
||||
_elapsed_ms(started),
|
||||
)
|
||||
return result
|
||||
return dispatch[vendor](token, title, body, extras)
|
||||
|
||||
|
||||
def send_accessibility_disabled(
|
||||
@@ -195,188 +153,19 @@ def send_accessibility_disabled(
|
||||
)
|
||||
|
||||
|
||||
def send_data_event(
|
||||
push_vendor: str,
|
||||
push_token: str,
|
||||
*,
|
||||
event: str,
|
||||
notification_id: str,
|
||||
mock: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""发送无界面的轻量事件;当前只允许站内消息创建事件。"""
|
||||
vendor = normalize_vendor(push_vendor)
|
||||
token = push_token.strip() if push_token else ""
|
||||
if not vendor or vendor not in SUPPORTED_VENDORS:
|
||||
raise VendorPushError(f"unsupported push vendor: {push_vendor}")
|
||||
if not token:
|
||||
raise VendorPushError("push token is empty")
|
||||
if event != DATA_EVENT_NOTIFICATION_CREATED:
|
||||
raise VendorPushError(f"unsupported data event: {event}")
|
||||
if not notification_id:
|
||||
raise VendorPushError("notification_id is empty")
|
||||
|
||||
payload = {"event": event, "notificationId": str(notification_id)}
|
||||
if mock:
|
||||
return {"mock": True, "vendor": vendor, "payload": payload}
|
||||
|
||||
# vivo 的通知已设置 foregroundShow=false:App 在前台时必走
|
||||
# onForegroundMessageArrived,正好就是本事件需要的刷新信号;不重复占用一次推送配额。
|
||||
if vendor == "vivo":
|
||||
return {"skipped": True, "reason": "foreground notification callback"}
|
||||
|
||||
# OPush 当前只支持通知栏消息,没有服务端透传单推接口。
|
||||
# 客户端在 OPPO 首页可见时轮询未读数;这里必须安全跳过,不能请求不存在的
|
||||
# /message/transparent/unicast(该地址会稳定返回 HTTP 404)。
|
||||
if vendor == "oppo":
|
||||
return {"skipped": True, "reason": "oppo does not support data messages"}
|
||||
|
||||
dispatch: dict[str, Callable[[str, dict[str, str]], dict[str, Any]]] = {
|
||||
"honor": _send_honor_data,
|
||||
"huawei": _send_huawei_data,
|
||||
"xiaomi": _send_xiaomi_data,
|
||||
}
|
||||
return dispatch[vendor](token, payload)
|
||||
|
||||
|
||||
def _require(value: str, name: str) -> str:
|
||||
if not value:
|
||||
raise VendorPushError(f"{name} not configured")
|
||||
return value
|
||||
|
||||
|
||||
def _elapsed_ms(started: float) -> float:
|
||||
return (time.perf_counter() - started) * 1000
|
||||
|
||||
|
||||
def _redacted_value(value: Any) -> str:
|
||||
raw = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
|
||||
digest = hashlib.sha256(raw.encode()).hexdigest()[:10]
|
||||
return f"<redacted len={len(raw)} sha256={digest}>"
|
||||
|
||||
|
||||
def _sanitize_for_log(value: Any, *, key: str = "", depth: int = 0) -> Any:
|
||||
"""生成有排障价值、但不暴露服务端鉴权凭据的紧凑日志摘要。"""
|
||||
normalized_key = "".join(char for char in key.lower() if char.isalnum())
|
||||
if normalized_key in _SENSITIVE_LOG_KEYS or normalized_key.endswith("secret"):
|
||||
return _redacted_value(value)
|
||||
if depth >= 10:
|
||||
return f"<{type(value).__name__}>"
|
||||
if isinstance(value, dict):
|
||||
items = list(value.items())
|
||||
sanitized = {
|
||||
str(item_key): _sanitize_for_log(item_value, key=str(item_key), depth=depth + 1)
|
||||
for item_key, item_value in items[:30]
|
||||
}
|
||||
if len(items) > 30:
|
||||
sanitized["<omitted_keys>"] = len(items) - 30
|
||||
return sanitized
|
||||
if isinstance(value, (list, tuple)):
|
||||
items = list(value)
|
||||
sanitized = [_sanitize_for_log(item, key=key, depth=depth + 1) for item in items[:20]]
|
||||
if len(items) > 20:
|
||||
sanitized.append(f"<omitted_items={len(items) - 20}>")
|
||||
return sanitized
|
||||
if isinstance(value, str):
|
||||
if value.lstrip().startswith(("{", "[")):
|
||||
try:
|
||||
decoded = json.loads(value)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
return _sanitize_for_log(decoded, key=key, depth=depth + 1)
|
||||
if len(value) > _LOG_STRING_MAX_CHARS:
|
||||
return f"{value[:_LOG_STRING_MAX_CHARS]}…<len={len(value)}>"
|
||||
return value
|
||||
|
||||
|
||||
def _log_summary(value: Any) -> str:
|
||||
rendered = json.dumps(
|
||||
_sanitize_for_log(value),
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
default=str,
|
||||
)
|
||||
if len(rendered) > _LOG_SUMMARY_MAX_CHARS:
|
||||
return f"{rendered[:_LOG_SUMMARY_MAX_CHARS]}…<len={len(rendered)}>"
|
||||
return rendered
|
||||
|
||||
|
||||
def _raw_log_summary(value: Any) -> str:
|
||||
"""厂商响应摘要:保留原始字段和值,仅限制单条日志长度。"""
|
||||
rendered = json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
default=str,
|
||||
)
|
||||
if len(rendered) > _LOG_SUMMARY_MAX_CHARS:
|
||||
return f"{rendered[:_LOG_SUMMARY_MAX_CHARS]}…<len={len(rendered)}>"
|
||||
return rendered
|
||||
|
||||
|
||||
def _endpoint_for_log(url: str) -> str:
|
||||
parsed = urlsplit(url)
|
||||
return f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
|
||||
|
||||
def _request_summary(kwargs: dict[str, Any]) -> str:
|
||||
summary: dict[str, Any] = {}
|
||||
if "json" in kwargs:
|
||||
summary["body_type"] = "json"
|
||||
summary["request_payload"] = kwargs["json"]
|
||||
elif "data" in kwargs:
|
||||
summary["body_type"] = "form"
|
||||
summary["request_payload"] = kwargs["data"]
|
||||
if kwargs.get("params"):
|
||||
summary["params"] = kwargs["params"]
|
||||
if kwargs.get("headers"):
|
||||
summary["headers"] = kwargs["headers"]
|
||||
return _log_summary(summary)
|
||||
|
||||
|
||||
def _response_summary(resp: Any, parsed: Any | None = None) -> str:
|
||||
if parsed is None:
|
||||
try:
|
||||
parsed = resp.json()
|
||||
except ValueError:
|
||||
pass
|
||||
if parsed is not None:
|
||||
return _raw_log_summary(parsed)
|
||||
return _raw_log_summary(getattr(resp, "text", ""))
|
||||
|
||||
|
||||
def _vendor_response_failed(vendor: str, data: dict[str, Any]) -> bool:
|
||||
"""识别 HTTP 200 中明确的厂商业务失败,避免将失败请求记录成 success。"""
|
||||
if data.get("error") or data.get("success") is False:
|
||||
return True
|
||||
if vendor == "xiaomi":
|
||||
code = data.get("code")
|
||||
result = str(data.get("result", "ok")).lower()
|
||||
return code not in (0, "0", None) or result not in ("ok", "success")
|
||||
if vendor == "oppo" and data.get("code") is not None:
|
||||
return int(data["code"]) != 0
|
||||
if vendor == "vivo" and data.get("result") is not None:
|
||||
return int(data["result"]) != 0
|
||||
if vendor == "honor" and data.get("code") is not None:
|
||||
return int(data["code"]) != 200
|
||||
if vendor == "huawei" and data.get("code") is not None:
|
||||
return str(data["code"]) != "80000000"
|
||||
return False
|
||||
|
||||
|
||||
def _request_json(
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
vendor: str,
|
||||
operation: str,
|
||||
expected_status: tuple[int, ...] = (200,),
|
||||
**kwargs: Any,
|
||||
) -> dict[str, Any]:
|
||||
started = time.perf_counter()
|
||||
request_summary = _request_summary(kwargs)
|
||||
try:
|
||||
resp = httpx.request(
|
||||
method,
|
||||
@@ -385,85 +174,41 @@ def _request_json(
|
||||
**kwargs,
|
||||
)
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(
|
||||
"vendor push http completed vendor=%s operation=%s method=%s endpoint=%s "
|
||||
"outcome=network_error request=%s response=%s elapsed_ms=%.1f error=%s",
|
||||
vendor,
|
||||
operation,
|
||||
method,
|
||||
_endpoint_for_log(url),
|
||||
request_summary,
|
||||
"<no_response>",
|
||||
_elapsed_ms(started),
|
||||
type(e).__name__,
|
||||
)
|
||||
raise VendorPushError(f"push http error: {e}") from e
|
||||
|
||||
if resp.status_code not in expected_status:
|
||||
logger.error(
|
||||
"vendor push http completed vendor=%s operation=%s method=%s endpoint=%s "
|
||||
"outcome=http_error http_status=%s request=%s response=%s elapsed_ms=%.1f",
|
||||
vendor,
|
||||
operation,
|
||||
method,
|
||||
_endpoint_for_log(url),
|
||||
resp.status_code,
|
||||
request_summary,
|
||||
_response_summary(resp),
|
||||
_elapsed_ms(started),
|
||||
)
|
||||
logger.error("vendor push http failed url=%s http=%s body=%s", url, resp.status_code, resp.text[:500])
|
||||
raise VendorPushError(f"push http {resp.status_code}")
|
||||
try:
|
||||
data = resp.json()
|
||||
return resp.json()
|
||||
except ValueError as e:
|
||||
logger.error(
|
||||
"vendor push http completed vendor=%s operation=%s method=%s endpoint=%s "
|
||||
"outcome=invalid_json http_status=%s request=%s response=%s elapsed_ms=%.1f",
|
||||
vendor,
|
||||
operation,
|
||||
method,
|
||||
_endpoint_for_log(url),
|
||||
resp.status_code,
|
||||
request_summary,
|
||||
_response_summary(resp),
|
||||
_elapsed_ms(started),
|
||||
)
|
||||
raise VendorPushError(f"push invalid json: {resp.text[:200]}") from e
|
||||
vendor_failed = _vendor_response_failed(vendor, data)
|
||||
log = logger.warning if vendor_failed else logger.info
|
||||
log(
|
||||
"vendor push http completed vendor=%s operation=%s method=%s endpoint=%s "
|
||||
"outcome=%s http_status=%s request=%s response=%s elapsed_ms=%.1f",
|
||||
vendor,
|
||||
operation,
|
||||
method,
|
||||
_endpoint_for_log(url),
|
||||
"vendor_error" if vendor_failed else "success",
|
||||
resp.status_code,
|
||||
request_summary,
|
||||
_response_summary(resp, data),
|
||||
_elapsed_ms(started),
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def _request_form(
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
vendor: str,
|
||||
operation: str,
|
||||
expected_status: tuple[int, ...] = (200,),
|
||||
**kwargs: Any,
|
||||
) -> dict[str, Any]:
|
||||
return _request_json(
|
||||
method,
|
||||
url,
|
||||
vendor=vendor,
|
||||
operation=operation,
|
||||
expected_status=expected_status,
|
||||
**kwargs,
|
||||
)
|
||||
try:
|
||||
resp = httpx.request(
|
||||
method,
|
||||
url,
|
||||
timeout=settings.PUSH_REQUEST_TIMEOUT_SEC,
|
||||
**kwargs,
|
||||
)
|
||||
except httpx.HTTPError as e:
|
||||
raise VendorPushError(f"push http error: {e}") from e
|
||||
|
||||
if resp.status_code not in expected_status:
|
||||
logger.error("vendor push http failed url=%s http=%s body=%s", url, resp.status_code, resp.text[:500])
|
||||
raise VendorPushError(f"push http {resp.status_code}")
|
||||
try:
|
||||
return resp.json()
|
||||
except ValueError as e:
|
||||
raise VendorPushError(f"push invalid json: {resp.text[:200]}") from e
|
||||
|
||||
|
||||
def _cache_get(key: str) -> str | None:
|
||||
@@ -489,8 +234,6 @@ def _honor_access_token() -> str:
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.HONOR_PUSH_TOKEN_ENDPOINT,
|
||||
vendor="honor",
|
||||
operation="authenticate",
|
||||
data={
|
||||
"grant_type": "client_credentials",
|
||||
"client_id": client_id,
|
||||
@@ -500,22 +243,16 @@ def _honor_access_token() -> str:
|
||||
)
|
||||
token = data.get("access_token")
|
||||
if not token:
|
||||
raise VendorPushError(f"honor auth failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"honor auth failed: {data}")
|
||||
return _cache_put(cache_key, str(token), data.get("expires_in"))
|
||||
|
||||
|
||||
def _send_honor(token: str, title: str, body: str, extras: dict[str, str]) -> dict[str, Any]:
|
||||
app_id = _require(settings.HONOR_PUSH_APP_ID, "HONOR_PUSH_APP_ID")
|
||||
access_token = _honor_access_token()
|
||||
click_action: dict[str, Any]
|
||||
if extras.get("notificationId"):
|
||||
# type=3 只负责打开首页,不保证 data 会变成目标 Activity 的 extras。消息中心通知必须
|
||||
# 用自定义页面(type=1)+ intent URI,把 notificationId/type/feedbackId 等直接带给
|
||||
# MainActivity;否则华为/荣耀系统能展示通知,但用户点击后客户端收不到任何导航参数。
|
||||
click_action = {"type": 1, "intent": _click_intent_uri(extras)}
|
||||
else:
|
||||
click_action = {"type": 3}
|
||||
payload = {
|
||||
# clickAction type=3(打开应用首页)时,荣耀点击会把 data JSON 的键值对注入启动 intent 的
|
||||
# extras(与 HMS 同机制)→ MainActivity.consumeNavTarget 读 notif_id/notif_type 直达落地。
|
||||
"data": json.dumps(_click_extras(extras), ensure_ascii=False),
|
||||
"notification": {"title": title, "body": body},
|
||||
"android": {
|
||||
@@ -524,7 +261,7 @@ def _send_honor(token: str, title: str, body: str, extras: dict[str, str]) -> di
|
||||
"notification": {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"clickAction": click_action,
|
||||
"clickAction": {"type": 3},
|
||||
"importance": "NORMAL",
|
||||
},
|
||||
},
|
||||
@@ -533,8 +270,6 @@ def _send_honor(token: str, title: str, body: str, extras: dict[str, str]) -> di
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.HONOR_PUSH_SEND_ENDPOINT_TEMPLATE.format(app_id=app_id),
|
||||
vendor="honor",
|
||||
operation="send_notification",
|
||||
json=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
@@ -544,28 +279,7 @@ def _send_honor(token: str, title: str, body: str, extras: dict[str, str]) -> di
|
||||
)
|
||||
code = data.get("code")
|
||||
if code is not None and int(code) != 200:
|
||||
raise VendorPushError(f"honor push failed: {_raw_log_summary(data)}")
|
||||
return data
|
||||
|
||||
|
||||
def _send_honor_data(token: str, payload: dict[str, str]) -> dict[str, Any]:
|
||||
app_id = _require(settings.HONOR_PUSH_APP_ID, "HONOR_PUSH_APP_ID")
|
||||
access_token = _honor_access_token()
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.HONOR_PUSH_SEND_ENDPOINT_TEMPLATE.format(app_id=app_id),
|
||||
vendor="honor",
|
||||
operation="send_data_event",
|
||||
json={"data": json.dumps(payload, ensure_ascii=False), "token": [token]},
|
||||
headers={
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"timestamp": str(int(time.time() * 1000)),
|
||||
},
|
||||
)
|
||||
code = data.get("code")
|
||||
if code is not None and int(code) != 200:
|
||||
raise VendorPushError(f"honor data push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"honor push failed: {data}")
|
||||
return data
|
||||
|
||||
|
||||
@@ -580,8 +294,6 @@ def _huawei_access_token() -> str:
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.HUAWEI_PUSH_TOKEN_ENDPOINT,
|
||||
vendor="huawei",
|
||||
operation="authenticate",
|
||||
data={
|
||||
"grant_type": "client_credentials",
|
||||
"client_id": app_id,
|
||||
@@ -591,7 +303,7 @@ def _huawei_access_token() -> str:
|
||||
)
|
||||
token = data.get("access_token")
|
||||
if not token:
|
||||
raise VendorPushError(f"huawei auth failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"huawei auth failed: {data}")
|
||||
return _cache_put(cache_key, str(token), data.get("expires_in"))
|
||||
|
||||
|
||||
@@ -600,24 +312,18 @@ def _send_huawei(token: str, title: str, body: str, extras: dict[str, str]) -> d
|
||||
'80100000' 为部分成功(单 token 场景仍视为失败,错误里带原始响应便于排障)。"""
|
||||
app_id = _require(settings.HUAWEI_PUSH_APP_ID, "HUAWEI_PUSH_APP_ID")
|
||||
access_token = _huawei_access_token()
|
||||
click_action: dict[str, Any]
|
||||
if extras.get("notificationId"):
|
||||
# type=3 只打开首页,Mate 20/EMUI 不会把 message.data 自动拆成启动 Intent extras。
|
||||
# type=1 的自定义 intent 才能稳定携带反馈记录 id,且冷启动/onNewIntent 都走同一路由。
|
||||
click_action = {"type": 1, "intent": _click_intent_uri(extras)}
|
||||
else:
|
||||
click_action = {"type": 3}
|
||||
payload = {
|
||||
"validate_only": False,
|
||||
"message": {
|
||||
# click_action type=3(打开应用首页)时,HMS 点击会把 data JSON 的键值对注入启动 intent
|
||||
# 的 extras → MainActivity.consumeNavTarget 读 notif_id/notif_type 直达落地。
|
||||
"data": json.dumps(_click_extras(extras), ensure_ascii=False),
|
||||
"android": {
|
||||
"target_user_type": settings.HUAWEI_PUSH_TARGET_USER_TYPE,
|
||||
"ttl": f"{settings.PUSH_TIME_TO_LIVE_SEC}s",
|
||||
"notification": {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"click_action": click_action,
|
||||
"click_action": {"type": 3},
|
||||
"importance": "NORMAL",
|
||||
},
|
||||
},
|
||||
@@ -627,8 +333,6 @@ def _send_huawei(token: str, title: str, body: str, extras: dict[str, str]) -> d
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.HUAWEI_PUSH_SEND_ENDPOINT_TEMPLATE.format(app_id=app_id),
|
||||
vendor="huawei",
|
||||
operation="send_notification",
|
||||
json=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
@@ -636,32 +340,7 @@ def _send_huawei(token: str, title: str, body: str, extras: dict[str, str]) -> d
|
||||
},
|
||||
)
|
||||
if str(data.get("code", "")) != "80000000":
|
||||
raise VendorPushError(f"huawei push failed: {_raw_log_summary(data)}")
|
||||
return data
|
||||
|
||||
|
||||
def _send_huawei_data(token: str, payload: dict[str, str]) -> dict[str, Any]:
|
||||
app_id = _require(settings.HUAWEI_PUSH_APP_ID, "HUAWEI_PUSH_APP_ID")
|
||||
access_token = _huawei_access_token()
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.HUAWEI_PUSH_SEND_ENDPOINT_TEMPLATE.format(app_id=app_id),
|
||||
vendor="huawei",
|
||||
operation="send_data_event",
|
||||
json={
|
||||
"validate_only": False,
|
||||
"message": {
|
||||
"data": json.dumps(payload, ensure_ascii=False),
|
||||
"token": [token],
|
||||
},
|
||||
},
|
||||
headers={
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
},
|
||||
)
|
||||
if str(data.get("code", "")) != "80000000":
|
||||
raise VendorPushError(f"huawei data push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"huawei push failed: {data}")
|
||||
return data
|
||||
|
||||
|
||||
@@ -678,8 +357,6 @@ def _vivo_auth_token() -> str:
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.VIVO_PUSH_AUTH_ENDPOINT,
|
||||
vendor="vivo",
|
||||
operation="authenticate",
|
||||
json={
|
||||
"appId": app_id,
|
||||
"appKey": app_key,
|
||||
@@ -689,10 +366,10 @@ def _vivo_auth_token() -> str:
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
if int(data.get("result", -1)) != 0:
|
||||
raise VendorPushError(f"vivo auth failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"vivo auth failed: {data}")
|
||||
token = data.get("authToken")
|
||||
if not token:
|
||||
raise VendorPushError(f"vivo auth missing authToken: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"vivo auth missing authToken: {data}")
|
||||
return _cache_put(cache_key, str(token), 24 * 3600)
|
||||
|
||||
|
||||
@@ -708,22 +385,15 @@ def _send_vivo(token: str, title: str, body: str, extras: dict[str, str]) -> dic
|
||||
"timeToLive": settings.PUSH_TIME_TO_LIVE_SEC,
|
||||
"requestId": uuid.uuid4().hex,
|
||||
"pushMode": settings.VIVO_PUSH_MODE,
|
||||
# vivo SDK 4.1.5 只有在前台展示关闭时才调用
|
||||
# OpenClientPushMessageReceiver.onForegroundMessageArrived。
|
||||
# App 在该回调中刷新服务端未读数并补发一条本地通知;后台/锁屏时仍由
|
||||
# vivo 系统展示,因而任何场景都只会出现一条通知。
|
||||
"foregroundShow": False,
|
||||
# vivo 官方 VPush 角标字段:离线收到通知时先由桌面自动 +1;
|
||||
# App 启动/同步后再由统一未读数通过系统 API 精确校准。
|
||||
"addBadge": True,
|
||||
"clientCustomMap": extras,
|
||||
}
|
||||
# vivo Push SDK 480+ 已不再回调 skipType=3;必须使用 skipType=4 的完整 Intent URI。
|
||||
# URI 同时包含 data/scheme、显式 component 和 S. extras,OriginOS 才会把业务参数
|
||||
# 原样交给 MainActivity(仅靠隐式 deeplink 会打开 App,但可能剥掉 extras)。
|
||||
# 点击落地:消息中心推送(带 notificationId)→ skipType=4 + skipContent=intent uri,由 vivo
|
||||
# 系统直启 MainActivity 并携带 S. extras(与小米 notify_effect=2 同机制)。不依赖客户端
|
||||
# VivoPushReceiver.onNotificationMessageClicked 里的后台 startActivity——Android 10+ BAL
|
||||
# 会静默拦掉,receiver 路径仅作兜底。无 notificationId 的召回类保持 skipType=1 仅打开首页。
|
||||
if extras.get("notificationId"):
|
||||
payload["skipType"] = 4
|
||||
payload["skipContent"] = _vivo_click_intent_uri(extras)
|
||||
payload["skipContent"] = _click_intent_uri(extras)
|
||||
else:
|
||||
payload["skipType"] = 1
|
||||
if settings.VIVO_PUSH_CATEGORY:
|
||||
@@ -731,37 +401,14 @@ def _send_vivo(token: str, title: str, body: str, extras: dict[str, str]) -> dic
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.VIVO_PUSH_SEND_ENDPOINT,
|
||||
vendor="vivo",
|
||||
operation="send_notification",
|
||||
json=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"authToken": auth_token,
|
||||
},
|
||||
)
|
||||
# 10089 = 当前 vivo 应用尚未开通 VPush「离线自动角标」能力。
|
||||
# 角标只是通知中心未读数的镜像,不能因此让整条通知发送失败:去掉 addBadge
|
||||
# 原样重试,通知到达/应用同步后仍由客户端系统 API 按统一未读数精确设置。
|
||||
if int(data.get("result", -1)) == 10089:
|
||||
logger.warning("vivo VPush badge not enabled (10089); retrying without addBadge")
|
||||
fallback_payload = dict(payload)
|
||||
fallback_payload.pop("addBadge", None)
|
||||
fallback_payload["requestId"] = uuid.uuid4().hex
|
||||
data = _request_json(
|
||||
"POST",
|
||||
settings.VIVO_PUSH_SEND_ENDPOINT,
|
||||
vendor="vivo",
|
||||
operation="send_notification",
|
||||
json=fallback_payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"authToken": auth_token,
|
||||
},
|
||||
)
|
||||
if int(data.get("result", -1)) == 0:
|
||||
data = {**data, "badgeFallback": True}
|
||||
if int(data.get("result", -1)) != 0:
|
||||
raise VendorPushError(f"vivo push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"vivo push failed: {data}")
|
||||
return data
|
||||
|
||||
|
||||
@@ -799,43 +446,14 @@ def _send_xiaomi(token: str, title: str, body: str, extras: dict[str, str]) -> d
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.XIAOMI_PUSH_SEND_ENDPOINT,
|
||||
vendor="xiaomi",
|
||||
operation="send_notification",
|
||||
data=form,
|
||||
headers={"Authorization": f"key={app_secret}"},
|
||||
)
|
||||
code = data.get("code")
|
||||
if code not in (0, "0", None):
|
||||
raise VendorPushError(f"xiaomi push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"xiaomi push failed: {data}")
|
||||
if str(data.get("result", "ok")).lower() not in ("ok", "success"):
|
||||
raise VendorPushError(f"xiaomi push failed: {_raw_log_summary(data)}")
|
||||
return data
|
||||
|
||||
|
||||
def _send_xiaomi_data(token: str, payload: dict[str, str]) -> dict[str, Any]:
|
||||
app_secret = _require(settings.XIAOMI_PUSH_APP_SECRET, "XIAOMI_PUSH_APP_SECRET")
|
||||
form = {
|
||||
"registration_id": token,
|
||||
"restricted_package_name": settings.ANDROID_PACKAGE_NAME,
|
||||
"payload": json.dumps(payload, ensure_ascii=False),
|
||||
"pass_through": "1",
|
||||
"time_to_live": str(settings.PUSH_TIME_TO_LIVE_SEC * 1000),
|
||||
}
|
||||
if settings.XIAOMI_PUSH_CHANNEL_ID.strip():
|
||||
form["extra.channel_id"] = settings.XIAOMI_PUSH_CHANNEL_ID.strip()
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.XIAOMI_PUSH_SEND_ENDPOINT,
|
||||
vendor="xiaomi",
|
||||
operation="send_data_event",
|
||||
data=form,
|
||||
headers={"Authorization": f"key={app_secret}"},
|
||||
)
|
||||
code = data.get("code")
|
||||
if code not in (0, "0", None):
|
||||
raise VendorPushError(f"xiaomi data push failed: {_raw_log_summary(data)}")
|
||||
if str(data.get("result", "ok")).lower() not in ("ok", "success"):
|
||||
raise VendorPushError(f"xiaomi data push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"xiaomi push failed: {data}")
|
||||
return data
|
||||
|
||||
|
||||
@@ -872,24 +490,6 @@ def _click_intent_uri(extras: dict[str, str]) -> str:
|
||||
return ";".join(parts)
|
||||
|
||||
|
||||
def _vivo_click_intent_uri(extras: dict[str, str]) -> str:
|
||||
"""vivo skipType=4 使用官方要求的完整 intent deeplink 形态。
|
||||
|
||||
`?#Intent` 中的问号不能省;OriginOS 对缺少它的 URI 会退化为“仅打开应用”,
|
||||
不把 S. 参数交给目标 Activity。
|
||||
"""
|
||||
pkg = settings.ANDROID_PACKAGE_NAME
|
||||
parts = [
|
||||
"intent://push/detail?#Intent",
|
||||
"scheme=shaguabijia",
|
||||
f"component={pkg}/{pkg}.MainActivity",
|
||||
"launchFlags=0x14000000",
|
||||
]
|
||||
parts += [f"S.{key}={quote(str(value), safe='')}" for key, value in _click_extras(extras).items()]
|
||||
parts.append("end")
|
||||
return ";".join(parts)
|
||||
|
||||
|
||||
def _xiaomi_template_param(title: str, alert: str) -> str:
|
||||
rendered = (
|
||||
settings.XIAOMI_PUSH_TEMPLATE_PARAM_JSON
|
||||
@@ -922,8 +522,6 @@ def _oppo_auth_token() -> str:
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.OPPO_PUSH_AUTH_ENDPOINT,
|
||||
vendor="oppo",
|
||||
operation="authenticate",
|
||||
data={
|
||||
"app_key": app_key,
|
||||
"timestamp": timestamp,
|
||||
@@ -932,10 +530,10 @@ def _oppo_auth_token() -> str:
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
if int(data.get("code", -1)) != 0:
|
||||
raise VendorPushError(f"oppo auth failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"oppo auth failed: {data}")
|
||||
token = (data.get("data") or {}).get("auth_token") or data.get("auth_token")
|
||||
if not token:
|
||||
raise VendorPushError(f"oppo auth missing auth_token: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"oppo auth missing auth_token: {data}")
|
||||
return _cache_put(cache_key, str(token), 24 * 3600)
|
||||
|
||||
|
||||
@@ -950,11 +548,6 @@ def _send_oppo(token: str, title: str, body: str, extras: dict[str, str]) -> dic
|
||||
"off_line_ttl": ttl_hours,
|
||||
"action_parameters": json.dumps(_click_extras(extras), ensure_ascii=False),
|
||||
}
|
||||
if extras.get("notificationId"):
|
||||
# 只有已落库的站内消息才计入角标;保活提醒等临时推送不应留下无法消除的未读数。
|
||||
# 客户端打开/已读后会按服务端真实未读总数覆盖,避免长期漂移。
|
||||
notification["badge_operation_type"] = 1
|
||||
notification["badge_message_count"] = 1
|
||||
# 点击落地:OPPO SDK 没有点击回调,参数只能靠服务端点击动作配置送达——action_parameters 的
|
||||
# 键值对仅在 click_action_type=1/4 时才会注入目标 Activity 的 intent extras(type=0「启动应用」
|
||||
# 会忽略它,extras 全丢 → 点了没反应,与小米 notify_effect=1 同款坑)。
|
||||
@@ -980,8 +573,6 @@ def _send_oppo(token: str, title: str, body: str, extras: dict[str, str]) -> dic
|
||||
data = _request_form(
|
||||
"POST",
|
||||
settings.OPPO_PUSH_SEND_ENDPOINT,
|
||||
vendor="oppo",
|
||||
operation="send_notification",
|
||||
data={
|
||||
"auth_token": auth_token,
|
||||
"message": json.dumps(message, ensure_ascii=False),
|
||||
@@ -989,5 +580,5 @@ def _send_oppo(token: str, title: str, body: str, extras: dict[str, str]) -> dic
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
if int(data.get("code", -1)) != 0:
|
||||
raise VendorPushError(f"oppo push failed: {_raw_log_summary(data)}")
|
||||
raise VendorPushError(f"oppo push failed: {data}")
|
||||
return data
|
||||
|
||||
@@ -102,21 +102,12 @@ class ComparisonRecord(Base):
|
||||
# done 帧 information 文案。成功:"在美团找到同店,到手价 ¥X…";
|
||||
# 失败:具体原因(如"美团、京东外卖均未找到该商品")。前端在比价失败时当原因展示。
|
||||
information: Mapped[str | None] = mapped_column(String(256), nullable=True)
|
||||
# 失败卡「原因」行的展示文案(仅 status=failed 时非空):information 具体则=它;笼统则从
|
||||
# platform_results 捞出的业务原因(打烊/未起送/找不到店或菜/单点不配送);纯系统失败为 None
|
||||
# → 端侧显示品牌兜底「网络开小差…」。写路径(harvest_done / upsert_record)落库时派生。
|
||||
# 见 repositories.comparison._derive_fail_display。
|
||||
fail_reason: Mapped[str | None] = mapped_column(String(256), nullable=True)
|
||||
|
||||
# ===== 明细(JSON,越详细越好)=====
|
||||
# 下单菜品 [{name, qty, specs?}]
|
||||
items: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 逐平台对比 [{platform_id, platform_name, package, price, is_source, rank, coupon_saved, coupon_name, applied_coupons}](price/coupon_saved 单位:元,原样存;coupon_name=优惠来源名;applied_coupons=[{name,amount}] 多券明细)
|
||||
comparison_results: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 展示模型统一数组(pricebot done.params.platforms 原样存): 每平台一行、自带
|
||||
# status/is_best/display/display_order, 记录页据此直接渲染, 不再靠 comparison_results
|
||||
# + 客户端合并 + 前端派生。老记录/旧客户端为空 → 前端回退老 comparison_results 渲染。
|
||||
platforms: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 目标平台未找到、跳过的菜名
|
||||
skipped_dish_names: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 客户端上报的原始 payload(calibration + done.params 全量),未来取数兜底
|
||||
|
||||
+41
-25
@@ -1,4 +1,20 @@
|
||||
"""引导视频待播放计划、起播快照与逐圈结算状态。"""
|
||||
"""新手引导视频播放记录(领券浮层前 N 次用它替代广告)。
|
||||
|
||||
产品规则(2026-07 拍板):新用户点「一键自动领取」后的等候浮层,**前 3 次**不放广告,
|
||||
改放运营后台上传的引导视频;每次固定 120 金币,中途关闭也算看完照发。
|
||||
|
||||
口径:
|
||||
- **计次按账号**(user_id),与设备无关 —— 换设备不重新送 3 次。
|
||||
- **开播即计数**:客户端每次要展示浮层时调 `/api/v1/guide-video/start`,服务端当场
|
||||
写一行(status='playing')并返回 play_token;`COUNT(*)` 即已用次数。用户中途 kill
|
||||
App 也算用掉一次(产品选定口径,防反复进出刷金币)。
|
||||
- **发币幂等**靠 play_token 定位 + `status='playing'` 条件更新:并发两次上报只有一次
|
||||
改到行(另一次 rowcount=0),所以只发一次币。光有 play_token 唯一键挡不住 —— 发币走的是
|
||||
UPDATE,不 INSERT,撞不到任何唯一键。
|
||||
- **次数上限**靠 (user_id, seq) 唯一键兜底,防并发 /start 绕过 COUNT 判定(见下)。
|
||||
|
||||
与广告收益(ad_feed_reward_record)彻底分离:引导视频不是广告,不该进广告收益报表。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
@@ -10,48 +26,48 @@ from app.db.base import Base
|
||||
|
||||
|
||||
class GuideVideoPlay(Base):
|
||||
"""一次引导视频播放一行。开播时建(status='playing'),发币后置 'granted'。"""
|
||||
|
||||
__tablename__ = "guide_video_play"
|
||||
__table_args__ = (
|
||||
# 客户端幂等键:同一次播放重复上报奖励只发一次。
|
||||
UniqueConstraint("play_token", name="uq_guide_video_play_token"),
|
||||
Index(
|
||||
"uq_guide_video_play_user_scene_seq",
|
||||
"user_id",
|
||||
"scene",
|
||||
"seq",
|
||||
unique=True,
|
||||
),
|
||||
# 次数上限的**硬约束**:start_play 是无锁 check-then-insert(读 COUNT 算 seq 再插),
|
||||
# N 个并发 /start 会都读到同一个已用次数、算出同一个 seq,不拦就能各拿一个 token、
|
||||
# 各发一次金币,3 次上限形同虚设(改包即可无限刷)。seq 唯一 → 并发同 seq 必撞,
|
||||
# start_play 捕获 IntegrityError 降级成"这次不放视频"。
|
||||
# 用 unique Index 而非 UniqueConstraint:与迁移里的 create_index 对齐(SQLite 加约束
|
||||
# 要整表重建),autogenerate 才不会每次报一条假 diff。
|
||||
Index("uq_guide_video_play_user_seq", "user_id", "seq", unique=True),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("user.id"), index=True, nullable=False
|
||||
)
|
||||
# 服务端生成下发给客户端的幂等键(uuid hex)。
|
||||
play_token: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 触发场景:目前只有 coupon(领券等候浮层);留字段以便日后比价等场景复用。
|
||||
scene: Mapped[str] = mapped_column(String(16), nullable=False, default="coupon")
|
||||
# prepare 不占次数,seq=NULL;start 成功才写入 1-based seq。
|
||||
seq: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
# 本账号第几次(1-based),= 建行时已有行数 + 1。日常判定仍以 COUNT 为准,但 (user_id, seq)
|
||||
# 唯一键让并发 /start 只能成一个 —— 见 __table_args__。
|
||||
seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||
# 当次下发的视频地址(运营换片后能回溯用户当时看的是哪支)。
|
||||
video_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
# 实发金币;未发时 0。
|
||||
coin: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
duration_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
config_version: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
settled_circles: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# prepared / started / completed / legacy_completed / legacy_closed
|
||||
status: Mapped[str] = mapped_column(String(24), nullable=False, default="prepared")
|
||||
# playing(已开播未发币) / granted(已发币)。
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="playing")
|
||||
# 客户端上报时是否播完(true=自然播完 / false=中途关闭)。仅留痕:两者都发币。
|
||||
completed: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
prepared_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
expires_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), index=True, nullable=True
|
||||
)
|
||||
started_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), index=True, nullable=True
|
||||
started_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), index=True, nullable=False
|
||||
)
|
||||
granted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return (
|
||||
f"<GuideVideoPlay user={self.user_id} scene={self.scene} seq={self.seq} "
|
||||
f"{self.status} circles={self.settled_circles}>"
|
||||
f"<GuideVideoPlay user={self.user_id} seq={self.seq} "
|
||||
f"{self.status} coin={self.coin}>"
|
||||
)
|
||||
|
||||
@@ -60,15 +60,6 @@ class CoinTransaction(Base):
|
||||
sqlite_where=text("biz_type LIKE 'task%' AND ref_id IS NOT NULL"),
|
||||
postgresql_where=text("biz_type LIKE 'task%' AND ref_id IS NOT NULL"),
|
||||
),
|
||||
Index(
|
||||
"ux_coin_transaction_guide_video_ref",
|
||||
"user_id",
|
||||
"biz_type",
|
||||
"ref_id",
|
||||
unique=True,
|
||||
sqlite_where=text("biz_type = 'guide_video' AND ref_id IS NOT NULL"),
|
||||
postgresql_where=text("biz_type = 'guide_video' AND ref_id IS NOT NULL"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
|
||||
+12
-199
@@ -52,81 +52,6 @@ def _product_names_from_items(items: list | None) -> str | None:
|
||||
return joined[:500] or None
|
||||
|
||||
|
||||
# ---- 失败记录的展示文案(记录页失败卡「原因」行)------------------------------
|
||||
# information 具体就直出;笼统(_GENERIC_INFO)则从 platform_results 捞一条用户可读的业务
|
||||
# 原因;捞不到 → None(端侧显示品牌兜底「网络开小差…」)。pricebot 把 store_closed /
|
||||
# no_delivery 漏成了 status=failed,这里按 reason 关键字补判;打烊类 reason 常带一坨脏店名
|
||||
# (店名+月售+起送+配送…),统一成简短模板。自动化黑话(搜索失败/读价失败/购物车残留/裸
|
||||
# FAILED…)不给用户看 → 归入品牌兜底。
|
||||
|
||||
# pricebot 组不出具体原因时的笼统 information(线上统计的大头),一律走品牌兜底。
|
||||
_GENERIC_INFO = {
|
||||
"比价过程出错,请稍后重试",
|
||||
"比价出错",
|
||||
"比价未完成",
|
||||
"done 参数缺少可验证的目标平台结果",
|
||||
}
|
||||
# 干净业务结局 status(直接可信),按展示优先级(越靠前越先选)。
|
||||
_BIZ_STATUS_PRIORITY = (
|
||||
"below_minimum",
|
||||
"no_delivery",
|
||||
"store_closed",
|
||||
"items_not_found",
|
||||
"store_not_found",
|
||||
)
|
||||
|
||||
|
||||
def _store_closed_text(reason: str | None) -> str:
|
||||
"""打烊/暂停营业/休息类 reason 常带脏店名元数据 → 只留结论,套简短模板。"""
|
||||
r = reason or ""
|
||||
if "暂停营业" in r:
|
||||
state = "暂停营业"
|
||||
elif "休息" in r:
|
||||
state = "休息中"
|
||||
else:
|
||||
state = "已打烊"
|
||||
return f"门店{state},无法比价"
|
||||
|
||||
|
||||
def _target_display_reason(platform_results: dict | None) -> str | None:
|
||||
"""从逐平台结果里挑一条"可展示给用户"的失败原因;挑不到返回 None。
|
||||
① status 命中干净业务结局集 → 直接采信(打烊套模板,其余用 reason);
|
||||
② 补判 pricebot 漏成 status=failed 的两类:打烊(套模板)、单点不配送(reason 本身干净);
|
||||
自动化黑话(搜索失败/读价失败/购物车残留/裸 FAILED…)一律不展示 → None。"""
|
||||
pr = platform_results or {}
|
||||
targets = [
|
||||
v for v in pr.values() if isinstance(v, dict) and not v.get("is_source")
|
||||
]
|
||||
for want in _BIZ_STATUS_PRIORITY: # ① 干净 status 优先
|
||||
for v in targets:
|
||||
if v.get("status") == want:
|
||||
if want == "store_closed":
|
||||
return _store_closed_text(v.get("reason"))
|
||||
if v.get("reason"):
|
||||
return v["reason"]
|
||||
for v in targets: # ② 漏成 failed 的业务结局补判
|
||||
if v.get("status") != "failed":
|
||||
continue
|
||||
reason = (v.get("reason") or "").strip()
|
||||
if any(k in reason for k in ("打烊", "暂停营业", "休息")):
|
||||
return _store_closed_text(reason)
|
||||
if "单点不配送" in reason:
|
||||
return reason
|
||||
return None
|
||||
|
||||
|
||||
def _derive_fail_display(
|
||||
information: str | None, platform_results: dict | None
|
||||
) -> str | None:
|
||||
"""失败记录展示文案:information 具体则直出;笼统则从 platform_results 捞/补判;
|
||||
都拿不到 → None(端侧品牌兜底)。仅在 status=failed 时调用。"""
|
||||
info = (information or "").strip()
|
||||
text = info if (info and info not in _GENERIC_INFO) else _target_display_reason(
|
||||
platform_results
|
||||
)
|
||||
return text[:256] if text else None
|
||||
|
||||
|
||||
def _derive(payload: ComparisonRecordIn) -> dict:
|
||||
"""从上报 payload 派生结构化列(best/saved/is_source_best/status)。"""
|
||||
results = payload.comparison_results
|
||||
@@ -164,9 +89,8 @@ def _derive(payload: ComparisonRecordIn) -> dict:
|
||||
|
||||
is_source_best = best.is_source if best is not None else None
|
||||
|
||||
# status:优先 pricebot record_status(区分 below_minimum/store_closed) → 客户端显式 status
|
||||
# → 兜底"非源且有价"=success/否则 failed。record_status 让"未满起送"不再塌缩成 failed。
|
||||
status = payload.record_status or payload.status
|
||||
# status:客户端显式给了就用;否则有"非源且有价"的结果=success,否则 failed
|
||||
status = payload.status
|
||||
if status is None:
|
||||
has_valid_target = any(
|
||||
(not r.is_source) and r.price is not None for r in results
|
||||
@@ -181,11 +105,6 @@ def _derive(payload: ComparisonRecordIn) -> dict:
|
||||
"saved_amount_cents": saved_amount_cents,
|
||||
"is_source_best": is_source_best,
|
||||
"status": status,
|
||||
"fail_reason": (
|
||||
_derive_fail_display(payload.information, _pr)
|
||||
if status == "failed"
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -198,35 +117,16 @@ def upsert_record(
|
||||
灰度期老客户端 POST /compare/record 走这条,与后端 harvest 按 trace_id reconcile;
|
||||
新客户端不再 POST(改由 compare.py 透传壳 harvest 落库)。
|
||||
"""
|
||||
# 单源派生: 与 harvest_done 一致, payload 带 platforms 时从它派生(唯一真相源
|
||||
# _derive_from_platforms), 老客户端不带 platforms 时回退 _derive(从 comparison_results)。
|
||||
if payload.platforms:
|
||||
derived = _derive_from_platforms(payload.platforms, payload.record_status)
|
||||
# 对齐 _derive 返回键(#189 fail_reason): 两路径 fields 键集一致, 覆盖已有行时不残留旧值
|
||||
derived["fail_reason"] = (
|
||||
_derive_fail_display(payload.information, payload.platform_results or {})
|
||||
if derived["status"] == "failed"
|
||||
else None
|
||||
)
|
||||
# 单源派生取自 platforms 源行(常无源平台元数据/店名)→ 空则用 payload 兜底不丢字段。
|
||||
# 下面 fields 不再显式写这四个键, 统一由 derived 提供(否则 dict(store_name=..., **derived)
|
||||
# 与 _derive_from_platforms 同名键撞键 TypeError)。
|
||||
for _k in ("store_name", "source_platform_id", "source_platform_name", "source_package"):
|
||||
if not derived.get(_k):
|
||||
derived[_k] = getattr(payload, _k)
|
||||
else:
|
||||
derived = _derive(payload)
|
||||
# _derive 只从 comparison_results 派生, 不含源平台四件套 / store_name → 从 payload 补,
|
||||
# 与上面 platforms 分支键集对齐(fields 统一靠 **derived 提供这些列)。
|
||||
for _k in ("store_name", "source_platform_id", "source_platform_name", "source_package"):
|
||||
derived[_k] = getattr(payload, _k)
|
||||
derived = _derive(payload)
|
||||
items = [it.model_dump(exclude_none=True) for it in payload.items]
|
||||
fields = dict(
|
||||
device_id=payload.device_id,
|
||||
business_type=payload.business_type,
|
||||
store_name=payload.store_name,
|
||||
product_names=_product_names_from_items(items),
|
||||
# store_name / source_platform_id / source_platform_name / source_package 统一由
|
||||
# derived 提供(见上方两分支补齐), 不在此显式写 —— 否则与 _derive_from_platforms 撞键。
|
||||
source_platform_id=payload.source_platform_id,
|
||||
source_platform_name=payload.source_platform_name,
|
||||
source_package=payload.source_package,
|
||||
information=payload.information,
|
||||
best_deeplink=payload.best_deeplink,
|
||||
trace_url=payload.trace_url,
|
||||
@@ -234,7 +134,6 @@ def upsert_record(
|
||||
skipped_dish_count=payload.skipped_dish_count,
|
||||
items=items,
|
||||
comparison_results=[r.model_dump() for r in payload.comparison_results],
|
||||
platforms=list(payload.platforms or []),
|
||||
skipped_dish_names=list(payload.skipped_dish_names),
|
||||
# 客户端环境 / 性能(debug,客户端上报;旧客户端为 None)
|
||||
device_model=payload.device_model,
|
||||
@@ -307,8 +206,7 @@ def upsert_record(
|
||||
|
||||
|
||||
def _derive_from_results(
|
||||
results: list[dict], platform_results: dict | None = None,
|
||||
record_status: str | None = None,
|
||||
results: list[dict], platform_results: dict | None = None
|
||||
) -> dict:
|
||||
"""从 done 帧 comparison_results(pricebot 原始 dict 列表)派生结构化列。
|
||||
等价 _derive,但吃原始字段(is_source/price/rank/platform_id/store_name...)而非 pydantic 对象。
|
||||
@@ -356,63 +254,7 @@ def _derive_from_results(
|
||||
"saved_amount_cents": saved_amount_cents,
|
||||
"is_source_best": best.get("is_source") if best else None,
|
||||
"store_name": (src_row or {}).get("store_name") or None,
|
||||
# 记录级结局: 优先用 pricebot 下发的 record_status(区分 below_minimum/store_closed,
|
||||
# 不再把"未满起送"塌缩成 failed → 记录页不再误报"网络开小差"); 旧 pricebot 未下发时
|
||||
# 回退老的 success/failed 二态派生, 向后兼容。
|
||||
"status": record_status or ("success" if has_valid_target else "failed"),
|
||||
}
|
||||
|
||||
|
||||
def _derive_from_platforms(
|
||||
platforms: list, record_status: str | None = None,
|
||||
) -> dict:
|
||||
"""从 done 帧 platforms(每平台一行、渲染就绪)派生结构化列——**单一真相源**。
|
||||
|
||||
best_* 直接取 platforms 里 is_best 的那一行、source_* 取 role=source 行,与前端读的
|
||||
platforms 天然一致(不再像 _derive_from_results 那样从 comparison_results 二次评最优,
|
||||
消除"标量列 vs platforms"双源不一致)。platforms 非空时优先走这里;老 pricebot 无
|
||||
platforms 时调用方回退 _derive_from_results(向后兼容)。"""
|
||||
rows = [p for p in (platforms or []) if isinstance(p, dict)]
|
||||
src = next((p for p in rows if p.get("role") == "source"), None)
|
||||
best = next((p for p in rows if p.get("is_best")), None)
|
||||
if best is None:
|
||||
# pricebot 没标 is_best(如全平台 has_dish_diff「相似替换/仅供参考」→ 不认定权威最低价)
|
||||
# 但仍有有价行 → 兜底取有价行里最低价当参考 best,避免记录级 best_*/saved 整条落 NULL
|
||||
# (否则首页价 0.00 / 记录页无最低红框 / 省额丢失 /「累计发现可省」漏计)。**候选含源**:
|
||||
# 源常年全菜、价可信,源本身最便宜时 best 回落源(saved=0、is_source_best=True),与 _derive
|
||||
# 「全目标缺菜回落源、不虚报省」同一语义;若排除源强选更贵目标,saved 会变负、倒扣「累计
|
||||
# 发现可省」(get_stats 对 saved_amount_cents 求和不带 >0 过滤)。
|
||||
priced = [p for p in rows if p.get("price") is not None]
|
||||
if priced:
|
||||
best = min(priced, key=lambda p: (p["price"], p.get("display_order") or 0))
|
||||
source_price_cents = _yuan_to_cents(src.get("price")) if src else None
|
||||
best_price_cents = _yuan_to_cents(best.get("price")) if best else None
|
||||
saved_amount_cents = None
|
||||
if source_price_cents is not None and best_price_cents is not None:
|
||||
saved_amount_cents = source_price_cents - best_price_cents
|
||||
has_valid_target = any(
|
||||
p.get("role") != "source" and p.get("price") is not None for p in rows
|
||||
)
|
||||
# store_name: 优先源行; recompare 场景源平台自己当目标、源行被目标覆盖(pricebot
|
||||
# _build_platform_rows 有意去重, platforms 无 role=source 行)→ 回退 best 行 → 首个有店名
|
||||
# 的行(显示现场实际比到的店), 免得记录页店名空掉兜底显示成"比价"。正常比价有源行不走回退。
|
||||
store_name = (
|
||||
(src or {}).get("store_name")
|
||||
or (best or {}).get("store_name")
|
||||
or next((p.get("store_name") for p in rows if p.get("store_name")), None)
|
||||
)
|
||||
return {
|
||||
"source_platform_id": (src or {}).get("platform_id"),
|
||||
"source_platform_name": (src or {}).get("platform_name"),
|
||||
"source_package": (src or {}).get("package"),
|
||||
"source_price_cents": source_price_cents,
|
||||
"best_platform_id": (best or {}).get("platform_id"),
|
||||
"best_platform_name": (best or {}).get("platform_name"),
|
||||
"best_price_cents": best_price_cents,
|
||||
"saved_amount_cents": saved_amount_cents,
|
||||
"is_source_best": (best.get("role") == "source") if best else None,
|
||||
"store_name": store_name or None,
|
||||
"status": record_status or ("success" if has_valid_target else "failed"),
|
||||
"status": "success" if has_valid_target else "failed",
|
||||
}
|
||||
|
||||
|
||||
@@ -571,40 +413,12 @@ def harvest_done(
|
||||
返回 (记录, 是否本次**新**落成 success)——供调用方据此幂等发一次邀请奖。
|
||||
行不存在(理论上帧0已建;防御)则新建。"""
|
||||
results = done_params.get("comparison_results") or []
|
||||
# 展示模型统一数组(pricebot 新增, 每平台一行自带 status/is_best): 原样存, 记录页据此直渲染。
|
||||
# record_status: 记录级结局(success/below_minimum/store_closed/failed), 覆盖老二态派生。
|
||||
platforms = done_params.get("platforms") or []
|
||||
record_status = done_params.get("record_status")
|
||||
# 单源派生: platforms(含 pricebot 权威 is_best)是唯一真相源, best_*/source_*/saved/status
|
||||
# 全从它取 → 与前端读的 platforms 天然一致; 菜品也取 platforms 源行。老 pricebot 无
|
||||
# platforms 时回退从 comparison_results 派生(向后兼容)。
|
||||
if platforms:
|
||||
derived = _derive_from_platforms(platforms, record_status)
|
||||
# 菜品优先源行; recompare 无源行 → 回退 best 行 → 首个有菜品的行(同 store_name 回退)
|
||||
_item_row = (
|
||||
next((p for p in platforms if isinstance(p, dict) and p.get("role") == "source"), None)
|
||||
or next((p for p in platforms if isinstance(p, dict) and p.get("is_best")), None)
|
||||
or next((p for p in platforms if isinstance(p, dict) and p.get("items")), None)
|
||||
)
|
||||
items = (_item_row or {}).get("items") or []
|
||||
else:
|
||||
derived = _derive_from_results(
|
||||
results, done_params.get("platform_results"), record_status
|
||||
)
|
||||
# pricebot 已把源单菜品塞进 comparison_results[源行].items
|
||||
items = next((r.get("items") or [] for r in results if r.get("is_source")), [])
|
||||
# 失败展示原因(#189): platforms / results 两个派生分支的 status 都可能 failed, 统一在此算
|
||||
fail_reason = (
|
||||
_derive_fail_display(
|
||||
done_params.get("information"), done_params.get("platform_results")
|
||||
)
|
||||
if derived["status"] == "failed"
|
||||
else None
|
||||
)
|
||||
derived = _derive_from_results(results, done_params.get("platform_results"))
|
||||
# 菜品:pricebot 已把源单菜品塞进 comparison_results[源行].items
|
||||
items = next((r.get("items") or [] for r in results if r.get("is_source")), [])
|
||||
fields = dict(
|
||||
business_type=business_type or "food",
|
||||
information=done_params.get("information") or None,
|
||||
fail_reason=fail_reason,
|
||||
# best_deeplink 来自客户端剪贴板采集,harvest 拿不到 → 留空(灰度期 fromComparison 会补;
|
||||
# 纯 harvest 行「再次比价」退化为按 package 拉起 App。要精确深链需客户端另传,后续)。
|
||||
trace_url=trace_url or done_params.get("trace_url"),
|
||||
@@ -612,7 +426,6 @@ def harvest_done(
|
||||
skipped_dish_count=done_params.get("skipped_dish_count"),
|
||||
skipped_dish_names=list(done_params.get("skipped_dish_names") or []),
|
||||
comparison_results=results,
|
||||
platforms=platforms,
|
||||
items=items,
|
||||
product_names=_product_names_from_items(items),
|
||||
raw_payload=done_params,
|
||||
|
||||
+184
-390
@@ -1,130 +1,95 @@
|
||||
"""双场景引导视频配置与 prepare/start/reward 状态机。"""
|
||||
"""新手引导视频:运营配置读写 + 播放计次 + 发币。
|
||||
|
||||
**配置**(开关 / 视频地址 / 前几次 / 每次金币)整体作为一个 JSON 存进通用 app_config 表
|
||||
(key=coupon_guide_video),写法完全对齐 feedback_qr —— 不进 CONFIG_DEFS,所以不会污染
|
||||
系统配置页的通用列表,由本模块独占维护。
|
||||
|
||||
**计次**按账号(user_id)、**开播即计数**:客户端每次要展示领券等候浮层时调
|
||||
`/api/v1/guide-video/start`,命中则当场写一行 guide_video_play(status='playing')。
|
||||
已用次数 = 该账号的行数,达到 max_plays 后不再下发,客户端改放广告(原逻辑)。
|
||||
COUNT 判定本身无锁,真正卡住次数上限的是 (user_id, seq) 唯一键:并发 /start 只能成一个。
|
||||
|
||||
**发币**幂等键是 play_token,落地方式是 `status='playing' → 'granted'` 的**条件更新**:
|
||||
同一次播放重复上报只入账一次(网络重试 / 关闭与播完同时触发都靠它挡住)。
|
||||
中途关闭也照发 —— 产品拍板「中途关闭也算看完」。
|
||||
|
||||
两处都是直接铸币的路径,改动前先看 `start_play` / `grant_play` 上的并发注释。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core import media, rewards
|
||||
from app.core.config import settings
|
||||
from app.core import rewards
|
||||
from app.models.app_config import AppConfig
|
||||
from app.models.guide_video import GuideVideoPlay
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import wallet as crud_wallet
|
||||
|
||||
SCENES = ("coupon", "comparison")
|
||||
_KEY_BY_SCENE = {
|
||||
"coupon": "coupon_guide_video",
|
||||
"comparison": "comparison_guide_video",
|
||||
}
|
||||
_KEY = "coupon_guide_video"
|
||||
|
||||
#: 金币流水 biz_type。客户端收益明细按它显示「新手引导视频奖励」。
|
||||
BIZ_TYPE = "guide_video"
|
||||
CIRCLE_COUNT = 10
|
||||
PLAN_TTL = timedelta(minutes=10)
|
||||
MIN_PLAYS = 1
|
||||
|
||||
# 默认值 = 「运营还没配」时的行为:video_url 为空 → 一律不下发引导视频,浮层维持现状(放广告)。
|
||||
# 所以本功能上线后**不配视频就等于没上线**,不会影响存量用户。
|
||||
_DEFAULTS: dict[str, Any] = {
|
||||
"enabled": True,
|
||||
"video_url": None, # None/空 = 未配片 → 不下发,浮层照旧放广告
|
||||
"max_plays": 3, # 每个账号前 N 次浮层放引导视频
|
||||
"reward_coin": 120, # 每次固定金币
|
||||
}
|
||||
|
||||
_FIELDS = tuple(_DEFAULTS.keys())
|
||||
|
||||
# 后台可配范围的护栏:防手滑把次数/金币填成天文数字(配置直接决定发币)。
|
||||
MAX_PLAYS_LIMIT = 50
|
||||
MIN_REWARD_COIN = 10
|
||||
REWARD_COIN_LIMIT = 10_000
|
||||
|
||||
_DEFAULTS: dict[str, Any] = {
|
||||
"enabled": False,
|
||||
"video_url": None,
|
||||
"max_plays": 3,
|
||||
"reward_coin": 100,
|
||||
"duration_ms": None,
|
||||
"video_codec": None,
|
||||
"audio_codec": None,
|
||||
"analysis_status": "missing",
|
||||
"analysis_error": None,
|
||||
"config_version": 0,
|
||||
}
|
||||
_FIELDS = tuple(_DEFAULTS)
|
||||
|
||||
|
||||
class PlayStateError(Exception):
|
||||
def __init__(self, code: str, message: str, *, reprepare_required: bool = False):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.reprepare_required = reprepare_required
|
||||
|
||||
def detail(self) -> dict[str, Any]:
|
||||
return {
|
||||
"code": self.code,
|
||||
"message": self.message,
|
||||
"retryable": False,
|
||||
"reprepare_required": self.reprepare_required,
|
||||
}
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(rewards.CN_TZ).replace(tzinfo=None)
|
||||
|
||||
|
||||
def _config_key(scene: str) -> str:
|
||||
if scene not in _KEY_BY_SCENE:
|
||||
raise ValueError(f"unsupported guide video scene: {scene}")
|
||||
return _KEY_BY_SCENE[scene]
|
||||
# ===== 配置 =====
|
||||
|
||||
|
||||
def _merge(raw: Any) -> dict[str, Any]:
|
||||
"""DB 里(可能不全的)dict 叠加到默认上,得到完整配置(4 个字段,无 updated_at)。"""
|
||||
out = dict(_DEFAULTS)
|
||||
if isinstance(raw, dict):
|
||||
for key in _FIELDS:
|
||||
if key in raw and raw[key] is not None:
|
||||
out[key] = raw[key]
|
||||
for k in _FIELDS:
|
||||
v = raw.get(k)
|
||||
if v is not None:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
def _public_config(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
duration = int(cfg.get("duration_ms") or 0)
|
||||
reward = int(cfg.get("reward_coin") or 0)
|
||||
return {
|
||||
**cfg,
|
||||
"duration_ms": duration or None,
|
||||
"circle_count": CIRCLE_COUNT,
|
||||
"circle_duration_ms": duration / CIRCLE_COUNT if duration else None,
|
||||
"reward_per_circle": reward // CIRCLE_COUNT,
|
||||
}
|
||||
|
||||
|
||||
def get_config(db: Session, scene: str = "coupon") -> dict[str, Any]:
|
||||
row = db.get(AppConfig, _config_key(scene))
|
||||
cfg = _public_config(_merge(row.value if row is not None else None))
|
||||
def get_config(db: Session) -> dict[str, Any]:
|
||||
"""完整配置 + updated_at(admin 读 / 业务读共用)。"""
|
||||
row = db.get(AppConfig, _KEY)
|
||||
cfg = _merge(row.value if row is not None else None)
|
||||
cfg["updated_at"] = row.updated_at.isoformat() if row is not None and row.updated_at else None
|
||||
return cfg
|
||||
|
||||
|
||||
def _validate_settings(max_plays: int, reward_coin: int) -> None:
|
||||
if not MIN_PLAYS <= max_plays <= MAX_PLAYS_LIMIT:
|
||||
raise ValueError(f"播放次数必须在 {MIN_PLAYS}~{MAX_PLAYS_LIMIT} 之间")
|
||||
if not MIN_REWARD_COIN <= reward_coin <= REWARD_COIN_LIMIT:
|
||||
raise ValueError(f"金币总价必须在 {MIN_REWARD_COIN}~{REWARD_COIN_LIMIT} 之间")
|
||||
if reward_coin % CIRCLE_COUNT:
|
||||
raise ValueError("金币总价必须是 10 的倍数")
|
||||
|
||||
|
||||
def _write(
|
||||
db: Session, value: dict[str, Any], *, scene: str, admin_id: int, commit: bool
|
||||
) -> dict[str, Any]:
|
||||
key = _config_key(scene)
|
||||
row = db.get(AppConfig, key)
|
||||
def _write(db: Session, value: dict[str, Any], *, admin_id: int, commit: bool) -> dict[str, Any]:
|
||||
"""整体覆写该行(value 须为完整字段 dict),返回合并后的完整配置(含 updated_at)。"""
|
||||
row = db.get(AppConfig, _KEY)
|
||||
if row is None:
|
||||
row = AppConfig(key=key, value=value, updated_by_admin_id=admin_id)
|
||||
row = AppConfig(key=_KEY, value=value, updated_by_admin_id=admin_id)
|
||||
db.add(row)
|
||||
else:
|
||||
row.value = value
|
||||
row.value = value # 整体重新赋值,SQLAlchemy 才侦测得到变更
|
||||
row.updated_by_admin_id = admin_id
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
else:
|
||||
db.flush()
|
||||
return get_config(db, scene)
|
||||
out = _merge(row.value)
|
||||
out["updated_at"] = row.updated_at.isoformat() if row.updated_at else None
|
||||
return out
|
||||
|
||||
|
||||
def update_config(
|
||||
@@ -133,364 +98,193 @@ def update_config(
|
||||
enabled: bool | None = None,
|
||||
max_plays: int | None = None,
|
||||
reward_coin: int | None = None,
|
||||
scene: str = "coupon",
|
||||
admin_id: int,
|
||||
commit: bool = True,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
before = get_config(db, scene)
|
||||
raw = {key: before[key] for key in _FIELDS}
|
||||
candidate_plays = int(max_plays if max_plays is not None else raw["max_plays"])
|
||||
candidate_reward = int(reward_coin if reward_coin is not None else raw["reward_coin"])
|
||||
_validate_settings(candidate_plays, candidate_reward)
|
||||
if enabled is True and (
|
||||
not raw.get("video_url")
|
||||
or raw.get("analysis_status") != "valid"
|
||||
or not raw.get("duration_ms")
|
||||
):
|
||||
raise ValueError("请先上传并通过分析的视频,再启用")
|
||||
"""改开关 / 次数 / 金币(只改传了的字段;视频走 set_video)。返回 (before, after) 供审计。"""
|
||||
row = db.get(AppConfig, _KEY)
|
||||
before = _merge(row.value if row is not None else None)
|
||||
new_value = {k: before[k] for k in _FIELDS}
|
||||
if enabled is not None:
|
||||
raw["enabled"] = enabled
|
||||
raw["max_plays"] = candidate_plays
|
||||
raw["reward_coin"] = candidate_reward
|
||||
raw["config_version"] = int(raw.get("config_version") or 0) + 1
|
||||
after = _write(db, raw, scene=scene, admin_id=admin_id, commit=commit)
|
||||
new_value["enabled"] = enabled
|
||||
if max_plays is not None:
|
||||
new_value["max_plays"] = max(0, min(int(max_plays), MAX_PLAYS_LIMIT))
|
||||
if reward_coin is not None:
|
||||
new_value["reward_coin"] = max(0, min(int(reward_coin), REWARD_COIN_LIMIT))
|
||||
after = _write(db, new_value, admin_id=admin_id, commit=commit)
|
||||
return before, after
|
||||
|
||||
|
||||
def set_video(
|
||||
db: Session,
|
||||
video_url: str | None,
|
||||
*,
|
||||
analysis: dict[str, Any] | None = None,
|
||||
scene: str = "coupon",
|
||||
admin_id: int,
|
||||
commit: bool = True,
|
||||
db: Session, video_url: str | None, *, admin_id: int, commit: bool = True
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
before = get_config(db, scene)
|
||||
raw = {key: before[key] for key in _FIELDS}
|
||||
raw["video_url"] = video_url
|
||||
if video_url:
|
||||
if not analysis or analysis.get("analysis_status") != "valid":
|
||||
raise ValueError("视频必须先完成服务端分析")
|
||||
for key in (
|
||||
"duration_ms", "video_codec", "audio_codec",
|
||||
"analysis_status", "analysis_error",
|
||||
):
|
||||
raw[key] = analysis.get(key)
|
||||
else:
|
||||
raw.update(
|
||||
duration_ms=None,
|
||||
video_codec=None,
|
||||
audio_codec=None,
|
||||
analysis_status="missing",
|
||||
analysis_error=None,
|
||||
)
|
||||
raw["enabled"] = False
|
||||
raw["config_version"] = int(raw.get("config_version") or 0) + 1
|
||||
after = _write(db, raw, scene=scene, admin_id=admin_id, commit=commit)
|
||||
"""设置/清空引导视频地址。返回 (before, after);before['video_url'] 供调用方删旧文件。"""
|
||||
row = db.get(AppConfig, _KEY)
|
||||
before = _merge(row.value if row is not None else None)
|
||||
new_value = {k: before[k] for k in _FIELDS}
|
||||
new_value["video_url"] = video_url
|
||||
after = _write(db, new_value, admin_id=admin_id, commit=commit)
|
||||
return before, after
|
||||
|
||||
|
||||
def used_plays(db: Session, user_id: int, scene: str = "coupon") -> int:
|
||||
# ===== 播放计次 =====
|
||||
|
||||
|
||||
def used_plays(db: Session, user_id: int) -> int:
|
||||
"""该账号已用掉的引导视频次数(开播即算,含未发币的)。"""
|
||||
return int(
|
||||
db.execute(
|
||||
select(func.count()).select_from(GuideVideoPlay).where(
|
||||
GuideVideoPlay.user_id == user_id,
|
||||
GuideVideoPlay.scene == scene,
|
||||
GuideVideoPlay.status != "prepared",
|
||||
GuideVideoPlay.user_id == user_id
|
||||
)
|
||||
).scalar_one()
|
||||
)
|
||||
|
||||
|
||||
def _prepare_miss(scene: str, reason: str, cfg: dict[str, Any], used: int) -> dict[str, Any]:
|
||||
maximum = int(cfg.get("max_plays") or 0)
|
||||
return {
|
||||
"should_play": False,
|
||||
"reason": reason,
|
||||
"scene": scene,
|
||||
"video_url": None,
|
||||
"play_token": "",
|
||||
"config_version": int(cfg.get("config_version") or 0),
|
||||
"duration_ms": 0,
|
||||
"circle_count": CIRCLE_COUNT,
|
||||
"circle_duration_ms": 0,
|
||||
"reward_coin": int(cfg.get("reward_coin") or 0),
|
||||
"reward_per_circle": int(cfg.get("reward_coin") or 0) // CIRCLE_COUNT,
|
||||
"seq": used,
|
||||
"remaining": max(0, maximum - used),
|
||||
"expires_at": None,
|
||||
}
|
||||
def play_stats(db: Session) -> dict[str, int]:
|
||||
"""全站播放统计(admin 页展示):总播放次数 / 其中已发币次数。"""
|
||||
total = int(
|
||||
db.execute(select(func.count()).select_from(GuideVideoPlay)).scalar_one()
|
||||
)
|
||||
granted = int(
|
||||
db.execute(
|
||||
select(func.count()).select_from(GuideVideoPlay).where(
|
||||
GuideVideoPlay.status == "granted"
|
||||
)
|
||||
).scalar_one()
|
||||
)
|
||||
return {"total_plays": total, "granted_plays": granted}
|
||||
|
||||
|
||||
def prepare_play(db: Session, user_id: int, *, scene: str = "coupon") -> dict[str, Any]:
|
||||
cfg = get_config(db, scene)
|
||||
used = used_plays(db, user_id, scene)
|
||||
video_url = str(cfg.get("video_url") or "").strip()
|
||||
duration = int(cfg.get("duration_ms") or 0)
|
||||
maximum = int(cfg.get("max_plays") or 0)
|
||||
if not cfg.get("enabled"):
|
||||
return _prepare_miss(scene, "disabled", cfg, used)
|
||||
if not video_url or cfg.get("analysis_status") != "valid" or duration <= 0:
|
||||
return _prepare_miss(scene, "video_unavailable", cfg, used)
|
||||
if used >= maximum:
|
||||
return _prepare_miss(scene, "play_limit_reached", cfg, used)
|
||||
def start_play(
|
||||
db: Session, user_id: int, *, scene: str = "coupon", commit: bool = True
|
||||
) -> dict[str, Any]:
|
||||
"""决定这次浮层是否放引导视频;命中则**当场计次**并返回 play_token。
|
||||
|
||||
now = _now()
|
||||
返回 dict:
|
||||
should_play 是否放引导视频(False → 客户端照旧放广告)
|
||||
video_url 相对地址(/media/...);客户端自行拼 BASE_URL
|
||||
play_token 发币幂等键(should_play=False 时为空串)
|
||||
reward_coin 播完/中途关闭都发的固定金币
|
||||
seq / remaining 第几次 / 发完这次还剩几次(仅展示与排查用)
|
||||
"""
|
||||
cfg = get_config(db)
|
||||
video_url = (cfg.get("video_url") or "").strip()
|
||||
max_plays = int(cfg.get("max_plays") or 0)
|
||||
reward_coin = int(cfg.get("reward_coin") or 0)
|
||||
used = used_plays(db, user_id)
|
||||
|
||||
def _miss(used_now: int) -> dict[str, Any]:
|
||||
return {
|
||||
"should_play": False,
|
||||
"video_url": None,
|
||||
"play_token": "",
|
||||
"reward_coin": reward_coin,
|
||||
"seq": used_now,
|
||||
"remaining": max(0, max_plays - used_now),
|
||||
}
|
||||
|
||||
if not cfg.get("enabled") or not video_url or max_plays <= 0 or used >= max_plays:
|
||||
return _miss(used)
|
||||
|
||||
seq = used + 1
|
||||
play = GuideVideoPlay(
|
||||
user_id=user_id,
|
||||
play_token=uuid.uuid4().hex,
|
||||
scene=scene,
|
||||
seq=None,
|
||||
seq=seq,
|
||||
video_url=video_url,
|
||||
coin=int(cfg["reward_coin"]),
|
||||
duration_ms=duration,
|
||||
config_version=int(cfg["config_version"]),
|
||||
settled_circles=0,
|
||||
status="prepared",
|
||||
coin=0,
|
||||
status="playing",
|
||||
completed=0,
|
||||
prepared_at=now,
|
||||
expires_at=now + PLAN_TTL,
|
||||
started_at=None,
|
||||
started_at=datetime.now(rewards.CN_TZ).replace(tzinfo=None),
|
||||
)
|
||||
db.add(play)
|
||||
db.commit()
|
||||
# 上面的 COUNT 判定是无锁 check-then-insert:并发 /start 会都算出同一个 seq。
|
||||
# (user_id, seq) 唯一键让只有一个能落库,其余撞键 → 回滚后按"这次不放视频"降级,
|
||||
# 客户端照旧走广告链路。没有它,并发就能绕过 max_plays 无限刷金币。
|
||||
try:
|
||||
if commit:
|
||||
db.commit()
|
||||
else:
|
||||
db.flush()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
return _miss(used_plays(db, user_id))
|
||||
return {
|
||||
"should_play": True,
|
||||
"reason": "ready",
|
||||
"scene": scene,
|
||||
"video_url": video_url,
|
||||
"play_token": play.play_token,
|
||||
"config_version": play.config_version,
|
||||
"duration_ms": duration,
|
||||
"circle_count": CIRCLE_COUNT,
|
||||
"circle_duration_ms": duration / CIRCLE_COUNT,
|
||||
"reward_coin": play.coin,
|
||||
"reward_per_circle": play.coin // CIRCLE_COUNT,
|
||||
"seq": used + 1,
|
||||
"remaining": max(0, maximum - used - 1),
|
||||
"expires_at": play.expires_at.isoformat(),
|
||||
"reward_coin": reward_coin,
|
||||
"seq": seq,
|
||||
"remaining": max(0, max_plays - seq),
|
||||
}
|
||||
|
||||
|
||||
def _find_play(db: Session, user_id: int, token: str) -> GuideVideoPlay | None:
|
||||
"""按 (play_token, user_id) 取播放行 —— 带 user_id 是防拿别人的 token 来兑。"""
|
||||
return db.execute(
|
||||
select(GuideVideoPlay).where(
|
||||
GuideVideoPlay.play_token == token.strip(),
|
||||
GuideVideoPlay.play_token == token,
|
||||
GuideVideoPlay.user_id == user_id,
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
def _start_out(play: GuideVideoPlay, maximum: int, status: str) -> dict[str, Any]:
|
||||
assert play.started_at is not None and play.seq is not None and play.video_url
|
||||
return {
|
||||
"started": True,
|
||||
"status": status,
|
||||
"play_token": play.play_token,
|
||||
"scene": play.scene,
|
||||
"video_url": play.video_url,
|
||||
"config_version": play.config_version,
|
||||
"duration_ms": play.duration_ms,
|
||||
"circle_count": CIRCLE_COUNT,
|
||||
"circle_duration_ms": play.duration_ms / CIRCLE_COUNT,
|
||||
"reward_coin": play.coin,
|
||||
"reward_per_circle": play.coin // CIRCLE_COUNT,
|
||||
"seq": play.seq,
|
||||
"remaining": max(0, maximum - play.seq),
|
||||
"started_at": play.started_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def start_play(db: Session, user_id: int, *, play_token: str) -> dict[str, Any]:
|
||||
play = _find_play(db, user_id, play_token)
|
||||
if play is None:
|
||||
raise PlayStateError("play_not_found", "播放计划不存在")
|
||||
cfg = get_config(db, play.scene)
|
||||
maximum = int(cfg["max_plays"])
|
||||
if play.status in {"started", "completed"}:
|
||||
return _start_out(play, maximum, "already_started")
|
||||
if play.status != "prepared":
|
||||
raise PlayStateError("play_not_found", "播放计划不可用")
|
||||
now = _now()
|
||||
if play.expires_at is None or now > play.expires_at:
|
||||
raise PlayStateError(
|
||||
"plan_expired", "播放计划已过期,请重新获取",
|
||||
reprepare_required=True,
|
||||
)
|
||||
if int(cfg["config_version"]) != play.config_version:
|
||||
raise PlayStateError(
|
||||
"config_changed", "视频配置已变化,请重新获取",
|
||||
reprepare_required=True,
|
||||
)
|
||||
used = used_plays(db, user_id, play.scene)
|
||||
if used >= maximum:
|
||||
raise PlayStateError("play_limit_reached", "播放次数已用完")
|
||||
play.seq = used + 1
|
||||
play.status = "started"
|
||||
play.started_at = now
|
||||
try:
|
||||
db.commit()
|
||||
db.refresh(play)
|
||||
except IntegrityError as exc:
|
||||
db.rollback()
|
||||
raise PlayStateError("play_limit_reached", "并发起播冲突,请重新获取") from exc
|
||||
return _start_out(play, maximum, "started")
|
||||
|
||||
|
||||
def _coin_balance(db: Session, user_id: int) -> int:
|
||||
account = db.get(CoinAccount, user_id)
|
||||
return int(account.coin_balance if account else 0)
|
||||
|
||||
|
||||
def grant_circle(
|
||||
db: Session, user_id: int, *, play_token: str, circle: int
|
||||
def grant_play(
|
||||
db: Session, user_id: int, *, play_token: str, completed: bool
|
||||
) -> dict[str, Any]:
|
||||
play = _find_play(db, user_id, play_token)
|
||||
balance = _coin_balance(db, user_id)
|
||||
base = {
|
||||
"granted": False,
|
||||
"retryable": False,
|
||||
"retry_after_ms": 0,
|
||||
"circle": circle,
|
||||
"granted_coin": 0,
|
||||
"settled_circles": int(play.settled_circles if play else 0),
|
||||
"coin_balance": balance,
|
||||
}
|
||||
if play is None:
|
||||
return {**base, "status": "not_found"}
|
||||
if play.status not in {"started", "completed"} or play.started_at is None:
|
||||
return {**base, "status": "not_started"}
|
||||
settled = int(play.settled_circles)
|
||||
if circle <= settled:
|
||||
return {
|
||||
**base,
|
||||
"status": "already_granted",
|
||||
"granted_coin": play.coin // CIRCLE_COUNT,
|
||||
"settled_circles": settled,
|
||||
}
|
||||
if settled >= CIRCLE_COUNT:
|
||||
return {**base, "status": "finished", "settled_circles": settled}
|
||||
if circle != settled + 1:
|
||||
return {
|
||||
**base,
|
||||
"status": "out_of_order",
|
||||
"retryable": True,
|
||||
"settled_circles": settled,
|
||||
}
|
||||
# 向上取整到毫秒,绝不让第 N 圈早于精确 N/10 边界发奖。
|
||||
boundary_ms = (circle * play.duration_ms + CIRCLE_COUNT - 1) // CIRCLE_COUNT
|
||||
elapsed_ms = max(0, int((_now() - play.started_at).total_seconds() * 1000))
|
||||
if elapsed_ms < boundary_ms:
|
||||
return {
|
||||
**base,
|
||||
"status": "too_early",
|
||||
"retryable": True,
|
||||
"retry_after_ms": boundary_ms - elapsed_ms,
|
||||
"settled_circles": settled,
|
||||
}
|
||||
"""按 play_token 发这次引导视频的金币(幂等)。播完 / 中途关闭都发。
|
||||
|
||||
final = circle == CIRCLE_COUNT
|
||||
返回 {granted, coin, status}:granted=True 表示**本次调用真的入账了**;
|
||||
重复上报返回 granted=False + 已发金币(客户端据此不重复累加 toast 金额)。
|
||||
"""
|
||||
token = (play_token or "").strip()
|
||||
# 金币额度以**服务端配置**为准,不信客户端(客户端只上报"播完/关闭")。
|
||||
coin = int(get_config(db).get("reward_coin") or 0)
|
||||
|
||||
# 幂等核心:把 status 放进 WHERE 做条件更新(compare-and-set),而不是"先读再判再写"。
|
||||
# 「播完」与「✕ 关闭」抢跑、或客户端超时重试时,两个请求会都读到 status='playing',
|
||||
# 无锁的话就都往下发币、都 commit,金币入账两次(不用恶意,重试就会中招)。改成条件更新后
|
||||
# 并发里只有一条 rowcount=1,另一条拿 0 → 按已发返回,不二次铸币。
|
||||
# (PG READ COMMITTED 下后到的 UPDATE 阻塞到对手提交,再按新版本重判 status;SQLite 写串行。)
|
||||
#
|
||||
# 别指望 IntegrityError 兜底:这里只 UPDATE 不 INSERT,撞不到 uq_guide_video_play_token;
|
||||
# 而 biz_type='guide_video' 的金币流水也不在 ux_coin_transaction_task_ref 的谓词
|
||||
# (biz_type LIKE 'task%')覆盖范围内 —— 两个唯一键在这条路径上都是不生效的。
|
||||
won = db.execute(
|
||||
update(GuideVideoPlay)
|
||||
.where(
|
||||
GuideVideoPlay.id == play.id,
|
||||
GuideVideoPlay.status == "started",
|
||||
GuideVideoPlay.settled_circles == settled,
|
||||
GuideVideoPlay.play_token == token,
|
||||
GuideVideoPlay.user_id == user_id,
|
||||
GuideVideoPlay.status == "playing",
|
||||
)
|
||||
.values(
|
||||
settled_circles=circle,
|
||||
status="completed" if final else "started",
|
||||
completed=1 if final else 0,
|
||||
granted_at=_now() if final else None,
|
||||
status="granted",
|
||||
coin=coin,
|
||||
completed=1 if completed else 0,
|
||||
granted_at=datetime.now(rewards.CN_TZ).replace(tzinfo=None),
|
||||
)
|
||||
.execution_options(synchronize_session=False)
|
||||
).rowcount
|
||||
|
||||
if not won:
|
||||
# 没抢到:token 不存在 / 不是本人的 / 已被另一次上报发过。回滚拿干净快照再区分两者
|
||||
# (对手此时必然已提交 —— 我们就是被它挡下的,所以读得到它写的 coin)。
|
||||
db.rollback()
|
||||
fresh = _find_play(db, user_id, play_token)
|
||||
fresh_settled = int(fresh.settled_circles if fresh else 0)
|
||||
return {
|
||||
**base,
|
||||
"status": "already_granted" if circle <= fresh_settled else "out_of_order",
|
||||
"retryable": circle > fresh_settled,
|
||||
"granted_coin": (
|
||||
play.coin // CIRCLE_COUNT if circle <= fresh_settled else 0
|
||||
),
|
||||
"settled_circles": fresh_settled,
|
||||
"coin_balance": _coin_balance(db, user_id),
|
||||
}
|
||||
play = _find_play(db, user_id, token)
|
||||
if play is None:
|
||||
return {"granted": False, "coin": 0, "status": "not_found"}
|
||||
return {"granted": False, "coin": play.coin, "status": "already_granted"}
|
||||
|
||||
per_circle = play.coin // CIRCLE_COUNT
|
||||
account, _ = crud_wallet.grant_coins(
|
||||
db,
|
||||
user_id,
|
||||
per_circle,
|
||||
biz_type=BIZ_TYPE,
|
||||
ref_id=f"{play.play_token}:{circle}",
|
||||
remark=f"新手引导视频第{circle}圈奖励",
|
||||
)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
# 流水唯一键是第二道幂等保险;若撞键,回滚后返回权威状态。
|
||||
db.rollback()
|
||||
fresh = _find_play(db, user_id, play_token)
|
||||
return {
|
||||
**base,
|
||||
"status": "already_granted",
|
||||
"granted_coin": play.coin // CIRCLE_COUNT,
|
||||
"settled_circles": int(fresh.settled_circles if fresh else settled),
|
||||
"coin_balance": _coin_balance(db, user_id),
|
||||
}
|
||||
return {
|
||||
**base,
|
||||
"granted": True,
|
||||
"status": "granted",
|
||||
"granted_coin": per_circle,
|
||||
"settled_circles": circle,
|
||||
"coin_balance": int(account.coin_balance),
|
||||
}
|
||||
|
||||
|
||||
def cleanup_old_videos(db: Session, *, protection: timedelta = PLAN_TTL) -> int:
|
||||
"""清理超过保护期且未被当前配置/有效计划/近期起播引用的托管旧片。"""
|
||||
now = _now()
|
||||
protected_urls: set[str] = set()
|
||||
for scene in SCENES:
|
||||
url = get_config(db, scene).get("video_url")
|
||||
if url:
|
||||
protected_urls.add(str(url))
|
||||
protected_urls.update(
|
||||
str(url)
|
||||
for url in db.execute(
|
||||
select(GuideVideoPlay.video_url).where(
|
||||
GuideVideoPlay.video_url.is_not(None),
|
||||
(
|
||||
(
|
||||
(GuideVideoPlay.status == "prepared")
|
||||
& (GuideVideoPlay.expires_at >= now)
|
||||
)
|
||||
| (
|
||||
(GuideVideoPlay.status == "started")
|
||||
& (GuideVideoPlay.started_at >= now - protection)
|
||||
)
|
||||
),
|
||||
)
|
||||
).scalars()
|
||||
if url
|
||||
)
|
||||
directory = Path(settings.MEDIA_ROOT) / "guide_video"
|
||||
if not directory.is_dir():
|
||||
return 0
|
||||
cutoff = now.timestamp() - protection.total_seconds()
|
||||
removed = 0
|
||||
for path in directory.glob("guide_*.mp4"):
|
||||
url = f"{settings.MEDIA_URL_PREFIX}/guide_video/{path.name}"
|
||||
try:
|
||||
if url not in protected_urls and path.stat().st_mtime <= cutoff:
|
||||
media.delete_guide_video(url)
|
||||
removed += 1
|
||||
except OSError:
|
||||
continue
|
||||
return removed
|
||||
if coin > 0:
|
||||
crud_wallet.grant_coins(
|
||||
db,
|
||||
user_id,
|
||||
coin,
|
||||
biz_type=BIZ_TYPE,
|
||||
ref_id=token,
|
||||
remark="新手引导视频奖励",
|
||||
)
|
||||
db.commit()
|
||||
return {"granted": True, "coin": coin, "status": "granted"}
|
||||
|
||||
@@ -132,20 +132,10 @@ def get_or_create_account(
|
||||
) -> CoinAccount:
|
||||
"""取用户金币账户,不存在则建一个空账户。
|
||||
|
||||
lock=True 时对已存在的账户行加 SELECT FOR UPDATE,并强制刷新 identity map 中可能
|
||||
缓存的旧余额;所有金币写入口都会使用它。SQLite 下 FOR UPDATE 为 no-op。
|
||||
lock=True 时对已存在的账户行加 SELECT FOR UPDATE(读-算-写余额的调用方串行化,防并发
|
||||
双写余额错位,如 admin set 模式连点);默认 False 不改 C 端发奖行为。SQLite 下为 no-op。
|
||||
"""
|
||||
if lock:
|
||||
# populate_existing 很关键:同一 Session 可能早已缓存旧余额。只加 FOR UPDATE 而
|
||||
# 继续复用 identity map 里的旧对象,仍会在另一笔发奖提交后把余额覆盖回去。
|
||||
acc = db.execute(
|
||||
select(CoinAccount)
|
||||
.where(CoinAccount.user_id == user_id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
).scalar_one_or_none()
|
||||
else:
|
||||
acc = db.get(CoinAccount, user_id)
|
||||
acc = db.get(CoinAccount, user_id, with_for_update=True) if lock else db.get(CoinAccount, user_id)
|
||||
if acc is None:
|
||||
acc = CoinAccount(
|
||||
user_id=user_id,
|
||||
@@ -175,9 +165,7 @@ def grant_coins(
|
||||
|
||||
返回 (account, transaction)。调用方负责 commit。
|
||||
"""
|
||||
# 所有金币来源统一遵守账户行锁协议;否则 guide 锁了账户,广告/签到等未锁路径
|
||||
# 仍可拿旧余额做 ORM 读改写,最终余额会小于流水累计。
|
||||
acc = get_or_create_account(db, user_id, commit=False, lock=True)
|
||||
acc = get_or_create_account(db, user_id, commit=False)
|
||||
acc.coin_balance += amount
|
||||
if amount > 0:
|
||||
acc.total_coin_earned += amount
|
||||
@@ -210,7 +198,7 @@ def grant_cash(
|
||||
与 [grant_coins] 同模式(运营手动调现金 / 测试发现金用)。返回 (account, transaction),
|
||||
调用方负责 commit。不在此校验扣成负——由调用方(admin router)按业务保护。
|
||||
"""
|
||||
acc = get_or_create_account(db, user_id, commit=False, lock=True)
|
||||
acc = get_or_create_account(db, user_id, commit=False)
|
||||
acc.cash_balance_cents += amount_cents
|
||||
|
||||
txn = CashTransaction(
|
||||
@@ -240,7 +228,7 @@ def grant_invite_cash(
|
||||
invite_cash_transaction,不 commit。与金币兑换的 cash_balance_cents **物理隔离**
|
||||
(产品红线:邀请奖励金 ≠ 金币现金,两本账不可累加)。返回 (account, transaction),
|
||||
调用方负责 commit。不在此校验扣成负——由调用方按业务保护。"""
|
||||
acc = get_or_create_account(db, user_id, commit=False, lock=True)
|
||||
acc = get_or_create_account(db, user_id, commit=False)
|
||||
acc.invite_cash_balance_cents += amount_cents
|
||||
|
||||
txn = InviteCashTransaction(
|
||||
@@ -298,8 +286,7 @@ def exchange_coins_to_cash(
|
||||
if coin_amount < floor_min or coin_amount % COIN_PER_CENT != 0:
|
||||
raise InvalidExchangeAmountError
|
||||
|
||||
# 余额充足校验必须和扣减遵守同一账户锁,否则并发消费都可能通过旧余额校验。
|
||||
acc = get_or_create_account(db, user_id, commit=False, lock=True)
|
||||
acc = get_or_create_account(db, user_id, commit=False)
|
||||
if acc.coin_balance < coin_amount:
|
||||
raise InsufficientCoinError
|
||||
|
||||
|
||||
@@ -107,13 +107,6 @@ class ComparisonRecordIn(BaseModel):
|
||||
# 明细
|
||||
items: list[ComparisonItemIn] = Field(default_factory=list)
|
||||
comparison_results: list[ComparisonResultIn] = Field(default_factory=list)
|
||||
# 展示模型统一数组(pricebot done.params.platforms 原样透传): 每平台一行、自带
|
||||
# status/is_best/display/display_order,记录页据此直渲染。宽松 list[dict] 存(结构由
|
||||
# pricebot 定,server 只原样落库),前端读它、老记录空时回退 comparison_results。
|
||||
platforms: list[dict] = Field(default_factory=list)
|
||||
# 记录级结局(pricebot 下发): success/below_minimum/store_closed/failed。让"未满起送"不再
|
||||
# 被塌缩成 failed。_derive 优先用它、其次客户端 status、再兜底二态派生。
|
||||
record_status: str | None = None
|
||||
# 逐平台结局摘要(含失败平台的细分原因 status: store_not_found/items_not_found/below_minimum/
|
||||
# unsupported/...)。来自 done.params.platform_results,客户端透传;落 raw_payload(不单列),
|
||||
# admin「卡在哪一步」从这里读。dict{platform_id: {...}} 宽松存(结构由 pricebot 定——是
|
||||
@@ -180,13 +173,8 @@ class ComparisonRecordOut(BaseModel):
|
||||
skipped_dish_count: int | None = None
|
||||
status: str
|
||||
information: str | None = None
|
||||
# 失败卡「原因」文案:具体失败给具体原因,纯系统失败为 None(端侧品牌兜底)。见模型 fail_reason。
|
||||
fail_reason: str | None = None
|
||||
items: list = []
|
||||
comparison_results: list = []
|
||||
# 展示模型统一数组(每平台一行、自带 status/is_best/display/display_order): 记录页据此
|
||||
# 直渲染, 不再靠 comparison_results + 前端派生。老记录为空 → 前端回退 comparison_results。
|
||||
platforms: list = []
|
||||
skipped_dish_names: list = []
|
||||
total_ms: int | None = None
|
||||
# 「已下单」(店级):该店名在该用户真实下单(source='compare')里出现过即 True。
|
||||
|
||||
+20
-56
@@ -1,72 +1,36 @@
|
||||
"""客户端引导视频三阶段协议。"""
|
||||
from typing import Literal
|
||||
"""新手引导视频(领券等候浮层前 N 次替代广告)的客户端请求/响应契约。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
GuideScene = Literal["coupon", "comparison"]
|
||||
|
||||
|
||||
class GuideVideoPrepareIn(BaseModel):
|
||||
scene: GuideScene = "coupon"
|
||||
|
||||
|
||||
class GuideVideoPrepareOut(BaseModel):
|
||||
should_play: bool
|
||||
reason: str
|
||||
scene: GuideScene
|
||||
video_url: str | None = None
|
||||
play_token: str = ""
|
||||
config_version: int = 0
|
||||
duration_ms: int = 0
|
||||
circle_count: int = 10
|
||||
circle_duration_ms: float = 0
|
||||
reward_coin: int = 0
|
||||
reward_per_circle: int = 0
|
||||
seq: int = 0
|
||||
remaining: int = 0
|
||||
expires_at: str | None = None
|
||||
|
||||
|
||||
class GuideVideoStartIn(BaseModel):
|
||||
play_token: str = Field(min_length=1, max_length=64)
|
||||
"""开播询问。scene 目前只有 coupon(领券浮层);预留给日后比价等场景。"""
|
||||
|
||||
scene: str = Field(default="coupon", max_length=16)
|
||||
|
||||
|
||||
class GuideVideoStartOut(BaseModel):
|
||||
started: bool
|
||||
status: Literal["started", "already_started"]
|
||||
play_token: str
|
||||
scene: GuideScene
|
||||
video_url: str
|
||||
config_version: int
|
||||
duration_ms: int
|
||||
circle_count: int = 10
|
||||
circle_duration_ms: float
|
||||
reward_coin: int
|
||||
reward_per_circle: int
|
||||
seq: int
|
||||
remaining: int
|
||||
started_at: str
|
||||
"""should_play=False 时客户端照旧走广告链路,其余字段无意义。"""
|
||||
|
||||
should_play: bool
|
||||
video_url: str | None = None # 相对地址 /media/...;客户端自行拼 BASE_URL
|
||||
play_token: str = "" # 发奖幂等键
|
||||
reward_coin: int = 0 # 播完/中途关闭都发的固定金币
|
||||
seq: int = 0 # 本账号第几次
|
||||
remaining: int = 0 # 发完这次还剩几次
|
||||
|
||||
|
||||
class GuideVideoRewardIn(BaseModel):
|
||||
"""播完或中途关闭都调这个;completed 只做留痕,两者都发币。"""
|
||||
|
||||
play_token: str = Field(min_length=1, max_length=64)
|
||||
circle: int = Field(ge=1, le=10)
|
||||
completed: bool = False
|
||||
|
||||
|
||||
class GuideVideoRewardOut(BaseModel):
|
||||
"""granted=True 表示本次调用真的入账(重复上报为 False,coin 是已发金额)。"""
|
||||
|
||||
granted: bool
|
||||
status: Literal[
|
||||
"granted",
|
||||
"already_granted",
|
||||
"too_early",
|
||||
"out_of_order",
|
||||
"not_started",
|
||||
"not_found",
|
||||
"finished",
|
||||
]
|
||||
retryable: bool = False
|
||||
retry_after_ms: int = 0
|
||||
circle: int
|
||||
granted_coin: int = 0
|
||||
settled_circles: int = 0
|
||||
coin_balance: int = 0
|
||||
coin: int
|
||||
status: str
|
||||
|
||||
@@ -135,7 +135,7 @@ def repair_missing_comparison_llm_costs(
|
||||
select(ComparisonRecord.id, ComparisonRecord.trace_id)
|
||||
.where(
|
||||
*date_conditions,
|
||||
ComparisonRecord.status.in_(("success", "failed", "cancelled")),
|
||||
ComparisonRecord.status.in_(("success", "failed")),
|
||||
ComparisonRecord.llm_cost_yuan.is_(None),
|
||||
)
|
||||
.order_by(ComparisonRecord.created_at.desc(), ComparisonRecord.id.desc())
|
||||
|
||||
@@ -85,10 +85,6 @@ def _dispatch(
|
||||
push_vars: dict[str, str] | None = None,
|
||||
) -> Notification | None:
|
||||
"""落一条站内消息并向该用户设备直推。返回落库行;去重命中/失败返回 None。"""
|
||||
logger.info(
|
||||
"notification dispatch started user_id=%s type=%s dedup_key=%s",
|
||||
user_id, type_key, dedup_key,
|
||||
)
|
||||
try:
|
||||
row = notif_repo.create_notification(
|
||||
db,
|
||||
@@ -115,10 +111,6 @@ def _dispatch(
|
||||
logger.exception("rollback after notification failure also failed")
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
"notification created user_id=%s type=%s notification_id=%s dedup_key=%s",
|
||||
user_id, type_key, row.id, dedup_key,
|
||||
)
|
||||
_push_to_user_devices(db, row, push_vars)
|
||||
return row
|
||||
|
||||
@@ -132,95 +124,29 @@ def _push_to_user_devices(db: Session, row: Notification, push_vars: dict[str, s
|
||||
extras.update({str(k): str(v) for k, v in (row.extra or {}).items()})
|
||||
extras["notificationId"] = str(row.id)
|
||||
|
||||
targets = device_repo.list_push_targets(db, user_id=row.user_id)
|
||||
logger.info(
|
||||
"push targets resolved user_id=%s type=%s notification_id=%s target_count=%s",
|
||||
row.user_id, row.type, row.id, len(targets),
|
||||
)
|
||||
if not targets:
|
||||
logger.warning(
|
||||
"push skipped no targets user_id=%s type=%s notification_id=%s",
|
||||
row.user_id, row.type, row.id,
|
||||
)
|
||||
return
|
||||
|
||||
sent = failed = skipped = data_sent = data_failed = 0
|
||||
for dev in targets:
|
||||
for dev in device_repo.list_push_targets(db, user_id=row.user_id):
|
||||
vendor = vendor_push.normalize_vendor(dev.push_vendor)
|
||||
if not vendor or vendor not in vendor_push.SUPPORTED_VENDORS:
|
||||
skipped += 1
|
||||
logger.warning(
|
||||
"push target skipped unsupported vendor user_id=%s type=%s "
|
||||
"notification_id=%s device_id=%s raw_vendor=%s normalized_vendor=%s",
|
||||
row.user_id, row.type, row.id, dev.device_id, dev.push_vendor, vendor,
|
||||
)
|
||||
continue
|
||||
missing = vendor_push.missing_settings(vendor)
|
||||
if missing:
|
||||
skipped += 1
|
||||
if vendor_push.missing_settings(vendor):
|
||||
# 本地/测试环境凭据不齐 → 只落站内消息,不发真推送(与 push/vendors 的报缺口径一致)
|
||||
logger.warning(
|
||||
"push target skipped vendor not configured user_id=%s type=%s "
|
||||
"notification_id=%s device_id=%s vendor=%s missing_settings=%s",
|
||||
row.user_id, row.type, row.id, dev.device_id, vendor, missing,
|
||||
logger.info(
|
||||
"skip push (vendor %s not configured) user_id=%s type=%s",
|
||||
vendor, row.user_id, row.type,
|
||||
)
|
||||
continue
|
||||
logger.info(
|
||||
"push send started user_id=%s type=%s notification_id=%s "
|
||||
"device_id=%s vendor=%s",
|
||||
row.user_id, row.type, row.id, dev.device_id, vendor,
|
||||
)
|
||||
try:
|
||||
response = vendor_push.send_notification(
|
||||
vendor_push.send_notification(
|
||||
vendor, dev.push_token, title=title, body=body, extras=extras
|
||||
)
|
||||
if vendor == "huawei" and row.type in {"feedback_reply", "feedback_reward"}:
|
||||
# 华为反馈推送联调日志:保留厂商返回码/requestId 等排障信息,
|
||||
# 请求本身的 token、Authorization 和应用密钥不会进入 response。
|
||||
logger.info(
|
||||
"huawei feedback push response user_id=%s type=%s "
|
||||
"notification_id=%s response=%s",
|
||||
row.user_id, row.type, row.id, response,
|
||||
)
|
||||
logger.info(
|
||||
"push sent user_id=%s type=%s vendor=%s notification_id=%s device_id=%s",
|
||||
row.user_id, row.type, vendor, row.id, dev.device_id,
|
||||
)
|
||||
sent += 1
|
||||
except vendor_push.VendorPushError as e:
|
||||
failed += 1
|
||||
logger.warning(
|
||||
"push failed user_id=%s type=%s vendor=%s notification_id=%s "
|
||||
"device_id=%s error=%s",
|
||||
row.user_id, row.type, vendor, row.id, dev.device_id, e,
|
||||
)
|
||||
try:
|
||||
data_response = vendor_push.send_data_event(
|
||||
vendor,
|
||||
dev.push_token,
|
||||
event=vendor_push.DATA_EVENT_NOTIFICATION_CREATED,
|
||||
notification_id=str(row.id),
|
||||
)
|
||||
data_sent += 1
|
||||
logger.info(
|
||||
"push data event completed user_id=%s type=%s vendor=%s "
|
||||
"notification_id=%s device_id=%s response=%s",
|
||||
row.user_id, row.type, vendor, row.id, dev.device_id, data_response,
|
||||
"push sent user_id=%s type=%s vendor=%s notification_id=%s",
|
||||
row.user_id, row.type, vendor, row.id,
|
||||
)
|
||||
except vendor_push.VendorPushError as e:
|
||||
data_failed += 1
|
||||
# 透传只负责前台铃铛实时刷新,失败不能影响通知栏消息或站内消息。
|
||||
logger.warning(
|
||||
"push data event failed user_id=%s type=%s vendor=%s notification_id=%s "
|
||||
"device_id=%s error=%s",
|
||||
row.user_id, row.type, vendor, row.id, dev.device_id, e,
|
||||
"push failed user_id=%s type=%s vendor=%s: %s", row.user_id, row.type, vendor, e
|
||||
)
|
||||
logger.info(
|
||||
"push dispatch completed user_id=%s type=%s notification_id=%s targets=%s "
|
||||
"sent=%s failed=%s skipped=%s data_sent=%s data_failed=%s",
|
||||
row.user_id, row.type, row.id, len(targets),
|
||||
sent, failed, skipped, data_sent, data_failed,
|
||||
)
|
||||
except Exception: # noqa: BLE001 — 渲染/查设备等意外失败同样不外抛
|
||||
logger.exception("push notification failed user_id=%s type=%s", row.user_id, row.type)
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# 本地开发/测试用 PostgreSQL。生产用原生 PG(scripts/init_postgres.py),不使用本文件。
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: shaguabijia-pg
|
||||
environment:
|
||||
POSTGRES_USER: shaguabijia_app
|
||||
POSTGRES_PASSWORD: shaguabijia_dev_pw
|
||||
POSTGRES_DB: shaguabijia
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./docker/initdb:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U shaguabijia_app -d shaguabijia"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,3 @@
|
||||
-- 仅在 pgdata 卷首次初始化时执行一次(以 shaguabijia_app 连 shaguabijia 库运行)。
|
||||
-- 幂等兜底见 scripts/ensure_pg.py 的 _ensure_test_db()。
|
||||
CREATE DATABASE shaguabijia_test OWNER shaguabijia_app;
|
||||
@@ -27,7 +27,21 @@ PG 默认上 16 版(工具链最齐),驱动用 **psycopg3**(SQLAlchemy 2.0 时
|
||||
|
||||
## 1. 本地起 PG + 跑通空库(半天)
|
||||
|
||||
### 1.1 装 PG
|
||||
### 1.0 推荐:Docker 一键起(本地开发/测试)
|
||||
|
||||
本地开发不必手动装 PG。已提供 `docker-compose.yml` + `scripts/ensure_pg.py`:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # DATABASE_URL 默认已是 Docker PG 连接串
|
||||
./run.sh # 或 run.bat;会自动:探测 PG → 没起则启 Docker → 起 PG 容器 → 建库 → alembic → uvicorn
|
||||
pytest # conftest 自动引导同一容器的 shaguabijia_test 库
|
||||
```
|
||||
|
||||
容器:`postgres:16-alpine`(名 `shaguabijia-pg`,端口 5432,命名卷 `pgdata` 持久化),
|
||||
首启即建业务库 `shaguabijia` 与测试库 `shaguabijia_test`。下面 1.1-1.5 的手动装 PG 步骤仅在
|
||||
不用 Docker 时才需要;生产仍走 §4 的原生 PG。
|
||||
|
||||
### 1.1 装 PG(不用 Docker 时的手动方式)
|
||||
|
||||
macOS:
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,740 @@
|
||||
# 本地开发切 Docker PostgreSQL 实现计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 让 app-server 本地开发运行与 pytest 都跑在 Docker 化的 PostgreSQL 16 上,退掉 SQLite,`run.bat`/`run.sh` 启动时自动检测并拉起 PG(必要时先启 Docker Desktop、缺镜像先拉)。
|
||||
|
||||
**Architecture:** 新增 `docker-compose.yml`(声明 PG 服务/卷/健康检查)+ `scripts/ensure_pg.py`(跨平台引导:探测→启 Docker→compose up→等就绪→幂等建测试库),由 `run.sh`/`run.bat`/`tests/conftest.py` 三处共用。`.env.example` 默认切 PG。`app/db/session.py` 与 `alembic/env.py` 已天然支持 PG,无需改。
|
||||
|
||||
**Tech Stack:** Docker Compose、`postgres:16-alpine`、Python 3.10+ 标准库(`socket`/`subprocess`/`urllib.parse`)、psycopg3(已装)、SQLAlchemy 2.0 + Alembic、pytest。
|
||||
|
||||
**工作目录:** 本计划在 worktree `.worktrees/local-dev-postgres-docker`(分支 `chore/local-dev-postgres-docker`,基于 `main`)内执行。下面所有路径相对该 worktree 根(= 仓库根)。
|
||||
|
||||
**设计依据:** [docs/superpowers/specs/2026-07-08-local-dev-postgres-docker-design.md](../specs/2026-07-08-local-dev-postgres-docker-design.md)
|
||||
|
||||
**连接参数(全程固定值):**
|
||||
- 镜像 `postgres:16-alpine`,容器名 `shaguabijia-pg`,宿主端口 `5432`
|
||||
- 用户 `shaguabijia_app`,dev 密码 `shaguabijia_dev_pw`(本地非机密)
|
||||
- 业务库 `shaguabijia`,测试库 `shaguabijia_test`,命名卷 `pgdata`
|
||||
- dev URL:`postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia`
|
||||
- test URL:`...@localhost:5432/shaguabijia_test`
|
||||
|
||||
**前置:** 执行机已安装 Docker Desktop。
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Docker Compose + 测试库 initdb 脚本
|
||||
|
||||
**Files:**
|
||||
- Create: `docker-compose.yml`
|
||||
- Create: `docker/initdb/01-create-test-db.sql`
|
||||
|
||||
- [ ] **Step 1: 写 `docker-compose.yml`**
|
||||
|
||||
```yaml
|
||||
# 本地开发/测试用 PostgreSQL。生产用原生 PG(scripts/init_postgres.py),不使用本文件。
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: shaguabijia-pg
|
||||
environment:
|
||||
POSTGRES_USER: shaguabijia_app
|
||||
POSTGRES_PASSWORD: shaguabijia_dev_pw
|
||||
POSTGRES_DB: shaguabijia
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./docker/initdb:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U shaguabijia_app -d shaguabijia"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 写 `docker/initdb/01-create-test-db.sql`**
|
||||
|
||||
```sql
|
||||
-- 仅在 pgdata 卷首次初始化时执行一次(以 shaguabijia_app 连 shaguabijia 库运行)。
|
||||
-- 幂等兜底见 scripts/ensure_pg.py 的 _ensure_test_db()。
|
||||
CREATE DATABASE shaguabijia_test OWNER shaguabijia_app;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 起容器验证**
|
||||
|
||||
Run: `docker compose up -d`
|
||||
Expected: 拉取 `postgres:16-alpine`(首次)后 `Container shaguabijia-pg Started`。
|
||||
|
||||
- [ ] **Step 4: 验证两个库都在 + 健康**
|
||||
|
||||
Run: `docker compose exec -T postgres psql -U shaguabijia_app -d shaguabijia -tAc "SELECT datname FROM pg_database WHERE datname IN ('shaguabijia','shaguabijia_test') ORDER BY 1"`
|
||||
Expected 输出:
|
||||
```
|
||||
shaguabijia
|
||||
shaguabijia_test
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 验证 `.worktrees/` 与 `data/` 忽略不受影响、compose 无落盘到项目目录**
|
||||
|
||||
Run: `git status --short`
|
||||
Expected: 只列出本任务新增的 `docker-compose.yml`、`docker/initdb/01-create-test-db.sql`(数据在命名卷 `pgdata`,不在项目目录;`.worktrees/` 已忽略)。
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add docker-compose.yml docker/initdb/01-create-test-db.sql
|
||||
git commit -m "feat(dev): docker-compose 起本地 PostgreSQL(含测试库 initdb)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: `scripts/ensure_pg.py` 引导脚本(TDD)
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/ensure_pg.py`
|
||||
- Test: `tests/test_ensure_pg.py`
|
||||
|
||||
> 说明:纯函数(URL 解析 / sqlite 判定 / 端口探测 / 平台命令映射 / sqlite 守卫 / 端口通时短路)走 TDD 单测;真正拉 Docker 的编排 `ensure()` 全链路靠 Task 3/5 的运行来验证(需真 Docker,不做单测)。此时 `conftest.py` 仍是 SQLite,不依赖 PG,单测可独立跑。
|
||||
|
||||
- [ ] **Step 1: 写失败测试 `tests/test_ensure_pg.py`**
|
||||
|
||||
```python
|
||||
"""scripts/ensure_pg.py 纯函数单测(不需要 Docker/PG)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
|
||||
from scripts.ensure_pg import (
|
||||
_docker_desktop_cmd,
|
||||
_is_sqlite,
|
||||
_parse_host_port,
|
||||
_port_open,
|
||||
ensure,
|
||||
)
|
||||
|
||||
|
||||
def test_is_sqlite():
|
||||
assert _is_sqlite("sqlite:///./data/app.db")
|
||||
assert _is_sqlite(" SQLite:///x ")
|
||||
assert not _is_sqlite("postgresql+psycopg://u:p@localhost:5432/db")
|
||||
|
||||
|
||||
def test_parse_host_port_full():
|
||||
assert _parse_host_port(
|
||||
"postgresql+psycopg://u:p@localhost:5432/shaguabijia"
|
||||
) == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_parse_host_port_defaults():
|
||||
# 缺端口 → 5432
|
||||
assert _parse_host_port("postgresql+psycopg://u:p@db.example/x")[1] == 5432
|
||||
# 缺 host → localhost
|
||||
assert _parse_host_port("postgresql+psycopg:///x") == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_parse_host_port_testdb():
|
||||
assert _parse_host_port(
|
||||
"postgresql+psycopg://u:p@localhost:5432/shaguabijia_test"
|
||||
) == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_port_open_true():
|
||||
srv = socket.socket()
|
||||
srv.bind(("127.0.0.1", 0))
|
||||
srv.listen(1)
|
||||
port = srv.getsockname()[1]
|
||||
try:
|
||||
assert _port_open("127.0.0.1", port, timeout=1.0)
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
|
||||
def test_port_open_false():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close() # 释放端口,无人监听 → 连接应失败
|
||||
assert not _port_open("127.0.0.1", port, timeout=0.3)
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_windows():
|
||||
cmd = _docker_desktop_cmd("win32", r"C:\Program Files")
|
||||
assert cmd is not None
|
||||
assert cmd[0].endswith("Docker Desktop.exe")
|
||||
assert "Docker" in cmd[0]
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_darwin():
|
||||
assert _docker_desktop_cmd("darwin", "") == ["open", "-a", "Docker"]
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_linux():
|
||||
assert _docker_desktop_cmd("linux", "") is None
|
||||
|
||||
|
||||
def test_ensure_rejects_sqlite():
|
||||
# dev 守卫:sqlite 直接 False(不碰 Docker)
|
||||
assert ensure("sqlite:///./data/app.db") is False
|
||||
|
||||
|
||||
def test_ensure_shortcircuits_when_pg_up(monkeypatch):
|
||||
# 端口通 → 直接 True,绝不触碰 docker
|
||||
monkeypatch.setattr("scripts.ensure_pg._port_open", lambda *a, **k: True)
|
||||
|
||||
def _boom():
|
||||
raise AssertionError("端口通时不应调用 docker")
|
||||
|
||||
monkeypatch.setattr("scripts.ensure_pg._docker_cli_ok", _boom)
|
||||
assert ensure("postgresql+psycopg://u:p@localhost:5432/shaguabijia") is True
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 跑测试确认失败**
|
||||
|
||||
Run: `pytest tests/test_ensure_pg.py -v`
|
||||
Expected: FAIL —— `ModuleNotFoundError: No module named 'scripts.ensure_pg'`(还没建)。
|
||||
|
||||
- [ ] **Step 3: 写实现 `scripts/ensure_pg.py`**
|
||||
|
||||
```python
|
||||
"""确保本地 PostgreSQL 就绪(开发/测试统一用 Docker PG)。
|
||||
|
||||
被三处复用:
|
||||
- run.sh / run.bat:`python -m scripts.ensure_pg`(CLI,失败退非 0)
|
||||
- tests/conftest.py:`from scripts.ensure_pg import ensure; ensure(test_url)`
|
||||
|
||||
流程:读 DATABASE_URL → TCP 探测 → 没起就(必要时启 Docker Desktop)→
|
||||
`docker compose up -d` → 等 PG ready → 幂等确保测试库存在。全程无 SQLite 兜底。
|
||||
|
||||
生产用原生 PG(scripts/init_postgres.py),不走本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
# 日志里可能含 emoji(如 ✅);Windows GBK 控制台(cmd.exe)无法编码会抛 UnicodeEncodeError → 脚本崩、
|
||||
# run.bat 误判 ensure_pg 失败。用 backslashreplace 保底:中文仍正常,仅不可编码字符被转义,不崩。
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_stream.reconfigure(errors="backslashreplace")
|
||||
except (AttributeError, ValueError):
|
||||
pass
|
||||
|
||||
APP_DB = "shaguabijia"
|
||||
TEST_DB = "shaguabijia_test"
|
||||
DB_USER = "shaguabijia_app"
|
||||
COMPOSE_SERVICE = "postgres"
|
||||
|
||||
DOCKER_START_TIMEOUT = int(os.environ.get("ENSURE_PG_DOCKER_TIMEOUT", "120"))
|
||||
PG_READY_TIMEOUT = int(os.environ.get("ENSURE_PG_READY_TIMEOUT", "60"))
|
||||
POLL_INTERVAL = 3.0
|
||||
|
||||
SQLITE_FIX_HINT = (
|
||||
"postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia"
|
||||
)
|
||||
|
||||
|
||||
def _log(msg: str) -> None:
|
||||
print(f"[ensure_pg] {msg}", flush=True)
|
||||
|
||||
|
||||
def _is_sqlite(url: str) -> bool:
|
||||
return url.strip().lower().startswith("sqlite")
|
||||
|
||||
|
||||
def _parse_host_port(url: str) -> tuple[str, int]:
|
||||
"""从 SQLAlchemy URL 取 host/port,缺省 localhost:5432。"""
|
||||
parts = urlsplit(url)
|
||||
return (parts.hostname or "localhost"), (parts.port or 5432)
|
||||
|
||||
|
||||
def _port_open(host: str, port: int, timeout: float = 1.0) -> bool:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _docker_desktop_cmd(platform: str, program_files: str) -> list[str] | None:
|
||||
"""按平台给出启动 Docker Desktop 的命令;Linux 返回 None(daemon 需 sudo,让用户手动)。"""
|
||||
if platform.startswith("win"):
|
||||
return [str(Path(program_files) / "Docker" / "Docker" / "Docker Desktop.exe")]
|
||||
if platform == "darwin":
|
||||
return ["open", "-a", "Docker"]
|
||||
return None
|
||||
|
||||
|
||||
def _docker_ok(subcmd: str) -> bool:
|
||||
"""`docker version`(CLI 在不在)/`docker info`(daemon 起没起)成功与否。"""
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", subcmd],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return True
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return False
|
||||
|
||||
|
||||
def _docker_cli_ok() -> bool:
|
||||
return _docker_ok("version")
|
||||
|
||||
|
||||
def _docker_daemon_ok() -> bool:
|
||||
return _docker_ok("info")
|
||||
|
||||
|
||||
def _start_docker_daemon() -> bool:
|
||||
"""守护进程没起时按平台拉起,轮询到就绪。返回是否成功。"""
|
||||
if _docker_daemon_ok():
|
||||
return True
|
||||
cmd = _docker_desktop_cmd(
|
||||
sys.platform, os.environ.get("ProgramFiles", r"C:\Program Files")
|
||||
)
|
||||
if cmd is None:
|
||||
_log("Docker 守护进程未运行。Linux 请手动:sudo systemctl start docker,然后重试。")
|
||||
return False
|
||||
if sys.platform.startswith("win") and not Path(cmd[0]).exists():
|
||||
_log(f"找不到 Docker Desktop:{cmd[0]}。请手动启动 Docker Desktop 后重试。")
|
||||
return False
|
||||
_log(f"启动 Docker Desktop(首次冷启可能 30-60s)…")
|
||||
try:
|
||||
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except OSError as e:
|
||||
_log(f"启动 Docker Desktop 失败:{e}")
|
||||
return False
|
||||
deadline = time.monotonic() + DOCKER_START_TIMEOUT
|
||||
while time.monotonic() < deadline:
|
||||
if _docker_daemon_ok():
|
||||
_log("Docker 守护进程已就绪。")
|
||||
return True
|
||||
_log("等待 Docker 守护进程…")
|
||||
time.sleep(POLL_INTERVAL)
|
||||
_log(f"等待 Docker 守护进程超时({DOCKER_START_TIMEOUT}s)。")
|
||||
return False
|
||||
|
||||
|
||||
def _compose_up() -> bool:
|
||||
_log("docker compose up -d(镜像缺失会自动拉取,首用约几十秒)…")
|
||||
try:
|
||||
subprocess.run(["docker", "compose", "up", "-d"], cwd=ROOT, check=True)
|
||||
return True
|
||||
except (OSError, subprocess.CalledProcessError) as e:
|
||||
_log(f"docker compose up 失败:{e}")
|
||||
return False
|
||||
|
||||
|
||||
def _pg_isready() -> bool:
|
||||
r = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"pg_isready", "-U", DB_USER, "-d", APP_DB],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
return r.returncode == 0
|
||||
|
||||
|
||||
def _wait_pg_ready(host: str, port: int) -> bool:
|
||||
deadline = time.monotonic() + PG_READY_TIMEOUT
|
||||
while time.monotonic() < deadline:
|
||||
if _port_open(host, port) and _pg_isready():
|
||||
_log("PostgreSQL 已就绪。")
|
||||
return True
|
||||
_log("等待 PostgreSQL 就绪…")
|
||||
time.sleep(POLL_INTERVAL)
|
||||
_log(f"等待 PostgreSQL 就绪超时({PG_READY_TIMEOUT}s)。")
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_test_db() -> None:
|
||||
"""幂等建测试库(兼容老 pgdata 卷首启没跑 initdb 的情况)。"""
|
||||
check = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"psql", "-U", DB_USER, "-d", APP_DB, "-tAc",
|
||||
f"SELECT 1 FROM pg_database WHERE datname='{TEST_DB}'"],
|
||||
cwd=ROOT, capture_output=True, text=True,
|
||||
)
|
||||
if check.returncode == 0 and check.stdout.strip() == "1":
|
||||
return
|
||||
_log(f"建测试库 {TEST_DB}…")
|
||||
subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"psql", "-U", DB_USER, "-d", APP_DB, "-c",
|
||||
f"CREATE DATABASE {TEST_DB} OWNER {DB_USER}"],
|
||||
cwd=ROOT, check=False,
|
||||
)
|
||||
|
||||
|
||||
def ensure(database_url: str | None = None) -> bool:
|
||||
"""确保 PG 就绪,返回 True/False。database_url 缺省从 settings 读(尊重 .env)。"""
|
||||
if database_url is None:
|
||||
from app.core.config import settings # 延迟导入,避免过早固化 settings
|
||||
|
||||
database_url = settings.DATABASE_URL
|
||||
|
||||
if _is_sqlite(database_url):
|
||||
_log("检测到 DATABASE_URL 仍是 SQLite。本地开发/测试已切 PostgreSQL,请改成:")
|
||||
_log(f" DATABASE_URL={SQLITE_FIX_HINT}")
|
||||
return False
|
||||
|
||||
host, port = _parse_host_port(database_url)
|
||||
|
||||
if _port_open(host, port):
|
||||
_log(f"✅ PostgreSQL 已在 {host}:{port} 运行,跳过 Docker。")
|
||||
return True
|
||||
|
||||
_log(f"{host}:{port} 无 PostgreSQL,准备用 Docker 拉起…")
|
||||
|
||||
if not _docker_cli_ok():
|
||||
_log("未检测到 docker 命令。请先安装 Docker Desktop:")
|
||||
_log(" https://www.docker.com/products/docker-desktop/")
|
||||
return False
|
||||
if not _start_docker_daemon():
|
||||
return False
|
||||
if not _compose_up():
|
||||
return False
|
||||
if not _wait_pg_ready(host, port):
|
||||
return False
|
||||
|
||||
_ensure_test_db()
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(0 if ensure() else 1)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 跑测试确认通过**
|
||||
|
||||
Run: `pytest tests/test_ensure_pg.py -v`
|
||||
Expected: 11 passed。
|
||||
|
||||
- [ ] **Step 5: 手动冒烟(PG 已在跑时应秒过短路)**
|
||||
|
||||
Run: `python -m scripts.ensure_pg`
|
||||
Expected: 打印 `[ensure_pg] ✅ PostgreSQL 已在 localhost:5432 运行,跳过 Docker。`,退出码 0。
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add scripts/ensure_pg.py tests/test_ensure_pg.py
|
||||
git commit -m "feat(dev): scripts/ensure_pg.py 探测/拉起本地 Docker PostgreSQL"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: `run.sh` / `run.bat` 接入 ensure_pg
|
||||
|
||||
**Files:**
|
||||
- Modify: `run.sh`(在 `alembic upgrade head` 前插一步)
|
||||
- Modify: `run.bat`(同上)
|
||||
|
||||
- [ ] **Step 1: 改 `run.sh`**
|
||||
|
||||
在 `mkdir -p data` 之后、`"$PY" -m alembic upgrade head` 之前插入:
|
||||
|
||||
```bash
|
||||
"$PY" -m scripts.ensure_pg # 确保本地 Docker PostgreSQL 就绪(没起会自动拉起;失败即退出)
|
||||
```
|
||||
|
||||
(`set -e` 已在文件顶部,ensure_pg 失败会自动终止脚本。)
|
||||
|
||||
- [ ] **Step 2: 改 `run.bat`**
|
||||
|
||||
在 `if not exist data mkdir data` 之后、`call "%PY%" -m alembic upgrade head` 之前插入:
|
||||
|
||||
```bat
|
||||
REM 确保本地 Docker PostgreSQL 就绪(没起会自动拉起 Docker + PG 容器)
|
||||
call "%PY%" -m scripts.ensure_pg
|
||||
if errorlevel 1 (
|
||||
echo [X] ensure_pg failed ^(PostgreSQL 未就绪^)
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 验证 `run.sh`(PG 已在跑,应短路后继续 alembic + uvicorn)**
|
||||
|
||||
Run(Git Bash):`bash run.sh 8770`
|
||||
Expected: 依次出现 `[ensure_pg] ✅ PostgreSQL 已在 localhost:5432 运行` → alembic 无报错 → uvicorn `Application startup complete`。`Ctrl-C` 停。
|
||||
|
||||
- [ ] **Step 4: 验证 `run.bat`(同上,Windows 原生)**
|
||||
|
||||
Run(cmd/PowerShell):`.\run.bat 8770`
|
||||
Expected: 同 Step 3。`Ctrl-C` 停。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add run.sh run.bat
|
||||
git commit -m "feat(dev): run.sh/run.bat 启动前确保 Docker PostgreSQL 就绪"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: `.env.example` 默认切 PostgreSQL
|
||||
|
||||
**Files:**
|
||||
- Modify: `.env.example`(第 8-10 行「数据库」段)
|
||||
|
||||
- [ ] **Step 1: 改 `.env.example` 的 DATABASE_URL**
|
||||
|
||||
把:
|
||||
```ini
|
||||
# ===== 数据库 =====
|
||||
# SQLite 本地文件路径。生产环境用 /opt/shaguabijia-app-server/data.db
|
||||
DATABASE_URL=sqlite:///./data/app.db
|
||||
```
|
||||
改成:
|
||||
```ini
|
||||
# ===== 数据库 =====
|
||||
# 本地开发/测试统一用 Docker PostgreSQL:run.bat/run.sh 会自动拉起容器
|
||||
# (docker-compose.yml + scripts/ensure_pg.py)。详见 docs/database/postgres-migration.md。
|
||||
# 生产用原生 PG,由 scripts/init_postgres.py 写入强随机密码的连接串。
|
||||
# ⚠️ scheme 必须是 postgresql+psycopg://(psycopg3);不要写成 postgresql://(会去找未装的 psycopg2)。
|
||||
DATABASE_URL=postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 验证(新 .env 从模板复制后能起服务)**
|
||||
|
||||
Run: `cp .env.example /tmp/env.check && grep '^DATABASE_URL=' /tmp/env.check`
|
||||
Expected: `DATABASE_URL=postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia`
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add .env.example
|
||||
git commit -m "feat(dev): .env.example 默认 DATABASE_URL 切 Docker PostgreSQL"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: `tests/conftest.py` 切 PostgreSQL 测试库
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/conftest.py`(整体替换:去掉临时 SQLite,改指 `shaguabijia_test` + 调 ensure_pg + fixture 改 drop/create)
|
||||
|
||||
- [ ] **Step 1: 整体替换 `tests/conftest.py`**
|
||||
|
||||
```python
|
||||
"""测试用 fixtures。
|
||||
|
||||
测试库用 Docker PG 的 shaguabijia_test(与 dev 业务库 shaguabijia 隔离)。
|
||||
顺序(必须):设 test DATABASE_URL(在 import app.* 之前)→ ensure PG 就绪 →
|
||||
import app → 建表。持久卷可能残留上次的表 → session 开头先 drop 再 create。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
|
||||
# 1) 测试库连接串——必须在 import app.* 之前设好(app.db.session 在 import 期建 engine)
|
||||
_TEST_DB_URL = (
|
||||
"postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia_test"
|
||||
)
|
||||
os.environ["DATABASE_URL"] = _TEST_DB_URL
|
||||
os.environ.setdefault("JWT_SECRET_KEY", "test-secret-please-ignore-this-is-only-for-pytest-not-real")
|
||||
os.environ.setdefault("ADMIN_JWT_SECRET", "test-admin-secret-please-ignore-only-for-pytest-not-real")
|
||||
os.environ.setdefault("JG_APP_KEY", "test-key")
|
||||
os.environ.setdefault("JG_MASTER_SECRET", "test-secret")
|
||||
os.environ.setdefault("SMS_MOCK", "true")
|
||||
os.environ.setdefault("APP_ENV", "dev")
|
||||
os.environ.setdefault("APP_DEBUG", "false") # 测试不打 SQL 日志
|
||||
os.environ.setdefault("WECHAT_APP_ID", "wxtest0000000000")
|
||||
os.environ.setdefault("WECHAT_APP_SECRET", "test-secret")
|
||||
os.environ.setdefault("WXPAY_MCH_ID", "test-mch")
|
||||
os.environ.setdefault("WXPAY_MCH_SERIAL_NO", "test-serial")
|
||||
os.environ.setdefault("WXPAY_PUBLIC_KEY_ID", "test-pubkey-id")
|
||||
os.environ.setdefault("RATE_LIMIT_ENABLED", "false")
|
||||
os.environ.setdefault("PANGLE_CALLBACK_ENABLED", "true")
|
||||
os.environ.setdefault("PANGLE_REWARD_SECRET", "test-pangle-secret-only-for-pytest")
|
||||
|
||||
# 2) 保证 Docker PG 就绪 + 测试库存在(必须在 import app.db.session 建 engine 之前)
|
||||
from scripts.ensure_pg import ensure
|
||||
|
||||
if not ensure(_TEST_DB_URL):
|
||||
raise RuntimeError(
|
||||
"测试需要 Docker PostgreSQL 就绪。请确认已装 Docker Desktop;"
|
||||
"或先跑一次 run.bat/run.sh 把 PG 拉起,再重试 pytest。"
|
||||
)
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.db.base import Base
|
||||
from app.db.session import engine
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _setup_db() -> Iterator[None]:
|
||||
# 持久卷可能残留上次跑崩后的表/数据 → 先 drop 再 create,保证干净起点
|
||||
Base.metadata.drop_all(engine)
|
||||
Base.metadata.create_all(engine)
|
||||
yield
|
||||
Base.metadata.drop_all(engine)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 验证 conftest 能引导 PG 并收集用例(选一个不涉 DB 的测试文件)**
|
||||
|
||||
Run: `pytest tests/test_ensure_pg.py -v`
|
||||
Expected: conftest 先打印 `[ensure_pg] ✅ PostgreSQL 已在 localhost:5432 运行`(或拉起过程),随后 12 passed。说明「测试走 PG 引导」链路通、且纯函数测试不受影响。
|
||||
|
||||
- [ ] **Step 3: 验证建表落到 PG 测试库(跑一个 DB 相关用例)**
|
||||
|
||||
Run: `pytest tests/test_invite.py -v`
|
||||
Expected: 用例在 `shaguabijia_test` 上建表并执行(可能有个别红,留待 Task 6);关键是不再出现 SQLite 临时文件、engine 连的是 PG。
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/conftest.py
|
||||
git commit -m "test(dev): conftest 切 shaguabijia_test(Docker PG),引导+drop/create"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: 全量跑 pytest on PG,逐个修红用例
|
||||
|
||||
> SQLite 宽松、PG 严格,切库会暴露一批真 bug(迁移指南 §2.2 已列)。本任务是**发现驱动**:先跑全量、按类别归因、按下述配方修,直到全绿。修改范围限被测业务/模型代码,不改测试来掩盖真 bug(除非测试本身依赖 SQLite 特性,如秒级时间精度)。
|
||||
|
||||
**Files:**
|
||||
- Modify: 视失败而定(常见:`app/models/*.py`、`app/**/repositories/*.py`、少量 `tests/*.py`)
|
||||
|
||||
- [ ] **Step 1: 全量跑,拿到失败清单**
|
||||
|
||||
Run: `pytest -q`
|
||||
Expected: 大部分通过;记录所有 FAIL 的用例名与报错文本,按下面类别归因。
|
||||
|
||||
- [ ] **Step 2: 修「naive datetime / 时区」类**
|
||||
|
||||
定位:`git grep -n "utcnow()" app/`。把 `datetime.utcnow()` 改成 `datetime.now(timezone.utc)`(并 `from datetime import timezone`)。
|
||||
症状:PG `TIMESTAMPTZ` 与 naive datetime 比较/写入报错或结果错位;`tests/test_cps_admin.py` 已注释过 SQLite 忽略 tzinfo 的行为。
|
||||
|
||||
例:
|
||||
```python
|
||||
# 改前
|
||||
from datetime import datetime
|
||||
ts = datetime.utcnow()
|
||||
# 改后
|
||||
from datetime import datetime, timezone
|
||||
ts = datetime.now(timezone.utc)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 修「字符串/整数隐式比较」类**
|
||||
|
||||
症状:SQLite 允许 `WHERE phone = 13800138000`(自动转型),PG 直接报类型错。定位报错用例引用的查询,确保比较两侧类型一致(手机号等一律按字符串传参 `:phone`,不要传裸 int)。
|
||||
|
||||
- [ ] **Step 3.5: 修「事务已中止」类**
|
||||
|
||||
症状:某用例后续报 `current transaction is aborted, commands ignored until end of transaction block`,根因是前一句 SQL 出错后业务代码缺 `db.rollback()`/`db.commit()` 边界。补上正确的 commit/rollback。
|
||||
|
||||
- [ ] **Step 4: 修「测试依赖 SQLite 特性」类(仅此类可改测试)**
|
||||
|
||||
症状:测试断言依赖 SQLite 秒级时间精度或 FK 不强制(见 `test_invite.py:328`、`test_compare_harvest.py:153` 的注释)。PG 下时间精度更高/FK 更严——调整测试数据(如手动拉开时间间隔、用合法 FK)使断言在 PG 下成立,不改业务逻辑。
|
||||
|
||||
- [ ] **Step 5: 反复跑到全绿**
|
||||
|
||||
Run: `pytest -q`
|
||||
Expected: `N passed`(0 failed)。若仍有红,回到 Step 2-4 继续归因。
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix(db): 测试套件切 PostgreSQL 后修复严格性暴露的用例"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: 文档更新
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/database/postgres-migration.md`(§1 增「本地 Docker 一键起」小节)
|
||||
- Modify: `CLAUDE.md`(DB 段注明 dev/test = Docker PG)
|
||||
- Modify: `scripts/init_postgres.py`(顶部注释区分生产/本地)
|
||||
|
||||
- [ ] **Step 1: `postgres-migration.md` 在「## 1. 本地起 PG」开头插入推荐做法**
|
||||
|
||||
在 `## 1. 本地起 PG + 跑通空库(半天)` 标题下、`### 1.1 装 PG` 之前插入:
|
||||
|
||||
```markdown
|
||||
### 1.0 推荐:Docker 一键起(本地开发/测试)
|
||||
|
||||
本地开发不必手动装 PG。已提供 `docker-compose.yml` + `scripts/ensure_pg.py`:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # DATABASE_URL 默认已是 Docker PG 连接串
|
||||
./run.sh # 或 run.bat;会自动:探测 PG → 没起则启 Docker → 起 PG 容器 → 建库 → alembic → uvicorn
|
||||
pytest # conftest 自动引导同一容器的 shaguabijia_test 库
|
||||
```
|
||||
|
||||
容器:`postgres:16-alpine`(名 `shaguabijia-pg`,端口 5432,命名卷 `pgdata` 持久化),
|
||||
首启即建业务库 `shaguabijia` 与测试库 `shaguabijia_test`。下面 1.1-1.5 的手动装 PG 步骤仅在
|
||||
不用 Docker 时才需要;生产仍走 §4 的原生 PG。
|
||||
```
|
||||
|
||||
- [ ] **Step 2: `CLAUDE.md` DB 段补充**
|
||||
|
||||
找到 DB 相关行(`**Prod**: PostgreSQL — just change DATABASE_URL...`)所在段,在其上方加一行:
|
||||
|
||||
```markdown
|
||||
- **Dev/Test**: Docker PostgreSQL 16 — `run.sh`/`run.bat` 经 `scripts/ensure_pg.py` + `docker-compose.yml` 自动拉起;`.env.example` 默认即 PG 连接串;pytest 用同容器的 `shaguabijia_test` 库。**本地不再用 SQLite**。
|
||||
```
|
||||
|
||||
- [ ] **Step 3: `scripts/init_postgres.py` 顶部注释区分场景**
|
||||
|
||||
把模块 docstring 第一行下方(`新机器初始化用。前置:...` 那行)改为:
|
||||
|
||||
```python
|
||||
新机器初始化用(面向【生产原生 PG】:apt/systemd 装好的 PostgreSQL)。
|
||||
本地开发/测试请改用 docker-compose.yml + scripts/ensure_pg.py(run.sh/run.bat 自动拉起),不必跑本脚本。
|
||||
前置:已装 PostgreSQL 16 + 知道 postgres 超级用户密码。
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 验证无坏链接/格式**
|
||||
|
||||
Run: `git diff --stat`
|
||||
Expected: 三个文档文件有改动,无其他文件被误改。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add docs/database/postgres-migration.md CLAUDE.md scripts/init_postgres.py
|
||||
git commit -m "docs(dev): 记录本地 Docker PostgreSQL 用法,区分生产原生 PG 路径"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 完成标准(对齐 spec §8 验收)
|
||||
|
||||
- [ ] 全新机器(装了 Docker Desktop、`.env` 从 `.env.example` 复制)跑 `run.bat`/`run.sh` 全自动拉起 PG 并起服务,无手动装 PG。
|
||||
- [ ] `docker ps` 见 `shaguabijia-pg` healthy;`shaguabijia` 与 `shaguabijia_test` 两库都在。
|
||||
- [ ] PG 已在跑时再跑 `run`,ensure_pg 秒过短路。
|
||||
- [ ] `pytest -q` 全绿(连 `shaguabijia_test`)。
|
||||
- [ ] `.env` 改回 sqlite 时,`python -m scripts.ensure_pg` 硬失败并打印正确 PG 串。
|
||||
- [ ] 能在 `admin/repositories` 写一段 PG 专有聚合(如 `count(*) FILTER (WHERE ...)`),`run` 手动跑通且相应 pytest 通过。
|
||||
|
||||
## Self-Review 记录(计划作者已核)
|
||||
|
||||
- **Spec 覆盖:** spec §9 待实现清单 8 项 → Task 1(compose+initdb)、Task 2(ensure_pg)、Task 3(run 接线)、Task 4(.env.example)、Task 5(conftest)、Task 6(修红用例)、Task 7(文档);「session.py 无需改」在 Header 与 spec §4.7 说明;「data/ 忽略」在 Task 1 Step 5 验证。无遗漏。
|
||||
- **占位符:** 全部步骤含真实代码/命令/期望输出。Task 6 是发现驱动,已用「类别+具体转换配方+定位命令」代替不可预知的逐条 diff——非占位。
|
||||
- **类型/命名一致:** `ensure(database_url=None)` 签名在 Task 2 定义,Task 5 以 `ensure(_TEST_DB_URL)` 调用一致;库名/用户/密码/端口全程为 Header 固定值;compose 服务名 `postgres` 与 ensure_pg `COMPOSE_SERVICE` 一致;`shaguabijia_test` 在 initdb SQL、`_ensure_test_db()`、conftest 三处一致。
|
||||
@@ -0,0 +1,281 @@
|
||||
# 本地开发切 Docker PostgreSQL —— 设计文档
|
||||
|
||||
> 让本地开发与测试统一跑在 Docker 化的 PostgreSQL 上,彻底退掉 SQLite。
|
||||
> `run.bat` / `run.sh` 启动时自动检测本机 PG,没起就拉起 Docker → 起 PG 容器(镜像缺失先拉),
|
||||
> 目的是让开发/大模型能放心用 PG 专有的高效聚合函数,不再为兼容 SQLite 而退化成"取基础数据后内存聚合"。
|
||||
>
|
||||
> 状态:已定稿(待用户复核)。作者对话日期:2026-07-08。
|
||||
> 关联:[postgres-migration.md](../../database/postgres-migration.md)(切引擎完整步骤)、`scripts/init_postgres.py`(生产原生 PG 初始化)。
|
||||
> ⚠️ **2026-07-27 增补(见 §10)**:D4 已从「sqlite 硬失败」松为「显式 SQLite 逃生舱」。§1-9 描述的是初版「彻底退掉 SQLite」设计;凡涉及「无 Docker / DATABASE_URL 是 sqlite 时如何处理」,**以 §10 为准**(测试仍只跑 PG 不变)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
### 问题
|
||||
当前开发环境默认用 SQLite(`DATABASE_URL=sqlite:///./data/app.db`),生产用 PostgreSQL 16。两套引擎并存,导致写数据访问代码时(尤其 `app/admin/repositories/` 的报表聚合)为了"两边都能跑",放弃 PG 专有能力(窗口函数、`FILTER`、`JSONB` 操作符、`GROUPING SETS` 等),改成"先查基础数据、再在 Python 内存里聚合"——既慢又啰嗦。
|
||||
|
||||
### 目标
|
||||
本地开发与测试都跑在 PG 上,SQLite 退出本地开发闭环。之后写 PG 专有 SQL 时:
|
||||
- 开发运行时(`run.bat`/`run.sh`)直接连 PG,手动验证可行;
|
||||
- `pytest` 也连 PG,PG 专有 SQL 在被测代码路径里也安全,不会因 SQLite 而挂——**这是"双库兼容代码彻底消失"的必要条件**。
|
||||
|
||||
### 非目标(本期不做)
|
||||
- 不动**生产**部署(生产仍是原生 PG16 + systemd,无 Docker;`init_postgres.py` 保持不变)。
|
||||
- 不做数据搬迁(MVP 阶段无真实用户数据,详见迁移指南背景假设)。
|
||||
- 不接 CI(仓库当前无 `.github/workflows`;若将来加 CI,再单独让 CI 起 PG service)。
|
||||
- 不引入 Redis / testcontainers / 连接池中间件。
|
||||
|
||||
---
|
||||
|
||||
## 2. 决策记录(本次对话已拍板)
|
||||
|
||||
| # | 决策点 | 结论 | 理由 |
|
||||
|---|---|---|---|
|
||||
| D1 | PG 覆盖范围 | **dev 运行 + 测试都切 PG** | 只切运行时的话,被 SQLite 测试覆盖的代码路径(如 `test_cps_admin.py` 覆盖的 `admin/repositories/cps.py`)仍不能用 PG 专有 SQL,双库代码不会真正消失 |
|
||||
| D2 | 打包方式 | **方案 A:Compose + `scripts/ensure_pg.py`** | 唯一真正需要定制的部分(启动 Docker 守护进程、等 PG 就绪)集中到一个跨平台模块,`run.bat`/`run.sh`/`conftest.py` 共用;声明式的容器/卷/健康检查交给 Compose |
|
||||
| D3 | 宿主端口 | **5432**(与生产/文档一致) | 边界:若本机已有原生 PG 占 5432,`ensure_pg` 会探测到"PG 已在"直接复用它(可能连到不带业务库的实例)——见 §7 风险,文档提示 |
|
||||
| D4 | dev 下 `DATABASE_URL` 仍是 sqlite | **硬失败**(打印一行 fix 后非 0 退出) | 彻底断掉 SQLite 退路,符合"让大家都用 PG"的目标 |
|
||||
| D5 | dev 数据库密码 | 固定 `shaguabijia_dev_pw`,写进 compose + `.env.example` | 本地容器仅绑 `localhost`,非机密;保证 `.env.example` 复制即可用。生产密码另由 `init_postgres.py` 强随机生成,不复用 |
|
||||
| D6 | 改哪些启动脚本 | `run.bat` 与 `run.sh` **都改** | 仓库一贯保持两者同步 |
|
||||
| D7 | 镜像 | `postgres:16-alpine` | 对齐生产 PG16;alpine 体积小 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 现状(改动前)
|
||||
|
||||
- **配置**:`app/core/config.py` `DATABASE_URL` 默认 `sqlite:///./data/app.db`,pydantic-settings 从 `.env` 读(环境变量优先级高于 `.env` 文件)。
|
||||
- **引擎**:`app/db/session.py` 用 `_is_sqlite = DATABASE_URL.startswith("sqlite")` 分流——SQLite 加 `check_same_thread=False`、不建池;非 SQLite 加 `pool_size=10/max_overflow=20/pool_recycle=3600`。**已天然支持 PG,无需改。**
|
||||
- **迁移**:`alembic/env.py` 从 `settings.DATABASE_URL` 读连接串,`render_as_batch` 仅对 sqlite 开;PG 下自动关。**无 psycopg2 硬编码,切 PG 无需改。**
|
||||
- **驱动**:`pyproject.toml` 已装 `psycopg[binary]>=3.1`(psycopg3)。URL scheme 必须 `postgresql+psycopg://`(裸 `postgresql://` 会被 SQLAlchemy 路由到未安装的 psycopg2 → ModuleNotFoundError)。
|
||||
- **测试**:`tests/conftest.py` 在 import app 前把 `DATABASE_URL` 设成临时文件 SQLite;session 级 autouse fixture 做 `Base.metadata.create_all(engine)` / 结束 `drop_all`(schema 来自 model 而非 alembic,无逐用例 rollback,全会话共享一个库)。
|
||||
- **启动脚本**:`run.bat` / `run.sh` 均为:校验 `.env` 存在 → `mkdir data` → `alembic upgrade head` → uvicorn 监听 `0.0.0.0:8770`(`.sh` 带 `--reload --reload-dir app`)。
|
||||
- **现有 PG 资产**:`scripts/init_postgres.py`(交互式:建用户/建库/授权/写 .env/跑迁移,面向**已装好的原生 PG**)、`docs/database/postgres-migration.md`(切引擎完整步骤,含 §2 测试切 PG、§2.2 会暴露的真 bug 清单)。
|
||||
- **CI**:无(`.github/workflows` 不存在),故测试切 PG 无 CI 联动负担。
|
||||
|
||||
---
|
||||
|
||||
## 4. 方案详解
|
||||
|
||||
### 4.1 新增 `docker-compose.yml`(app-server 根目录)
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: shaguabijia-pg
|
||||
environment:
|
||||
POSTGRES_USER: shaguabijia_app
|
||||
POSTGRES_PASSWORD: shaguabijia_dev_pw
|
||||
POSTGRES_DB: shaguabijia
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./docker/initdb:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U shaguabijia_app -d shaguabijia"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
volumes:
|
||||
pgdata:
|
||||
```
|
||||
- `POSTGRES_USER` 设定后,该用户以超级用户身份创建并拥有 `POSTGRES_DB`,故能再建测试库。
|
||||
- 首启 initdb 脚本建测试库(见 4.2)。命名卷 `pgdata` 让数据跨重启留存。
|
||||
|
||||
### 4.2 新增 `docker/initdb/01-create-test-db.sql`
|
||||
```sql
|
||||
-- 仅在 pgdata 卷首次初始化时执行一次。以 shaguabijia_app(超级用户)连 shaguabijia 库运行。
|
||||
CREATE DATABASE shaguabijia_test OWNER shaguabijia_app;
|
||||
```
|
||||
|
||||
### 4.3 新增 `scripts/ensure_pg.py`(纯标准库 + docker CLI,跨平台)
|
||||
对外同时暴露**可导入函数** `ensure()`(供 `conftest.py` 直接调)和 **CLI 入口** `if __name__ == "__main__": sys.exit(0 if ensure() else 1)`(供 `run` 以 `python -m scripts.ensure_pg` 跑)。`ensure()` 从 `app.core.config.settings` 读 `DATABASE_URL`,解析 host/port,主流程:
|
||||
1. **sqlite 守卫**:若 `DATABASE_URL` 以 `sqlite` 开头 → 打印"dev 已切 PG,请把 .env 的 DATABASE_URL 改成 `postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia`"→ 非 0 退出(D4)。
|
||||
2. **TCP 探测** `host:port`(stdlib `socket`,超时 1s)。通 → 打印"✅ PG 已就绪"直接返回(幂等:PG 已在跑时开销≈一次握手)。
|
||||
3. 不通 → `docker version` 探 CLI;缺失 → 中文报错"请先安装 Docker Desktop:https://www.docker.com/products/docker-desktop/" → 非 0 退出。
|
||||
4. `docker info` 探守护进程;不通 → 按平台启动:
|
||||
- Windows:`start "" "%ProgramFiles%\Docker\Docker\Docker Desktop.exe"`(找不到则报错让用户手动开)
|
||||
- macOS:`open -a Docker`
|
||||
- Linux:不自动 sudo,打印 `sudo systemctl start docker` 让用户执行后重试
|
||||
然后轮询 `docker info` 直到就绪或超时(默认 120s,每 3s 一次,打印进度)。
|
||||
5. `docker compose up -d`(Compose 在镜像缺失时**自动拉取**,首用拉 alpine ~90MB;有进度输出)。
|
||||
6. 轮询 healthcheck(`docker inspect` 的 health 状态)/ TCP 直到 PG 接受连接(默认 60s 超时)。
|
||||
7. **幂等确保测试库存在**(兼容"老 pgdata 卷没跑过 initdb"的情况):
|
||||
`docker compose exec -T postgres psql -U shaguabijia_app -tc "SELECT 1 FROM pg_database WHERE datname='shaguabijia_test'"`,不存在则 `CREATE DATABASE shaguabijia_test OWNER shaguabijia_app`。
|
||||
|
||||
失败即清晰中文报错 + 非 0 退出,**全程不回退 SQLite**。所有超时可用环境变量覆盖(如 `ENSURE_PG_DOCKER_TIMEOUT`)。
|
||||
|
||||
### 4.4 `run.bat` / `run.sh` 接线
|
||||
在 `alembic upgrade head` **之前**插一行调用,失败即退出:
|
||||
- `run.sh`:`"$PY" -m scripts.ensure_pg`(`set -e` 已在,失败自动退出)
|
||||
- `run.bat`:`call "%PY%" -m scripts.ensure_pg` + `if errorlevel 1 exit /b 1`
|
||||
|
||||
其余逻辑不动(`mkdir data` 保留给 media 等落盘目录)。
|
||||
|
||||
### 4.5 `.env.example` 默认切 PG
|
||||
把
|
||||
```ini
|
||||
DATABASE_URL=sqlite:///./data/app.db
|
||||
```
|
||||
改为
|
||||
```ini
|
||||
# 本地开发/测试统一用 Docker PG(run.bat/run.sh 会自动拉起容器;详见 docs/database/postgres-migration.md §本地 Docker 一键起)。
|
||||
# 生产用原生 PG,由 scripts/init_postgres.py 写入强随机密码的连接串。
|
||||
DATABASE_URL=postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia
|
||||
```
|
||||
|
||||
### 4.6 `tests/conftest.py` 切 PG
|
||||
调整顶部顺序(仍必须在 `import app.*` 之前完成 env 设定):
|
||||
1. 设 `os.environ["DATABASE_URL"] = "postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia_test"`(测试库,永不碰 dev 业务库)。
|
||||
2. 调 `scripts.ensure_pg.ensure()`(保证容器在 + 测试库在;PG 已在时几乎零开销)。
|
||||
3. `import app...`。
|
||||
session 级 autouse fixture:改为 **`Base.metadata.drop_all(engine)` → `create_all(engine)`(开头先清干净,防持久卷里上一次跑残留的表/数据)→ yield → 结束 `drop_all`**;删掉临时 SQLite 文件相关代码。
|
||||
|
||||
> 预期:部分用例会因 PG 的严格性变红(SQLite 宽松、PG 严格),按迁移指南 §2.2 逐个修——常见为:字符串/整数隐式比较、`datetime.utcnow()` naive vs `TIMESTAMPTZ`、事务边界(`current transaction is aborted`)。这既是工作量也是本次改造的**直接收益**(暴露真 bug)。实现阶段需为"跑 pytest 并修红用例"单列步骤。
|
||||
|
||||
### 4.7 `app/db/session.py`
|
||||
**无需改动**——`_is_sqlite` 为假时自动走 PG 池化分支。
|
||||
|
||||
### 4.8 文档
|
||||
- `docs/database/postgres-migration.md` 增一节「本地 Docker 一键起 PG(推荐)」,指向 compose + `ensure_pg`,并说明它替代了 §1.1 的手动 brew/apt 装 PG。
|
||||
- `CLAUDE.md` 的 DB 段注明:dev/test = Docker PG(`run` 自动拉起);prod = 原生 PG(`init_postgres.py`)。
|
||||
- `scripts/init_postgres.py` 顶部注释补一句"本脚本面向生产原生 PG;本地开发用 docker-compose + scripts/ensure_pg"。
|
||||
|
||||
---
|
||||
|
||||
## 5. 连接参数汇总
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 镜像 | `postgres:16-alpine` |
|
||||
| 容器名 | `shaguabijia-pg` |
|
||||
| 宿主端口 | `5432` |
|
||||
| 超级/业务用户 | `shaguabijia_app` |
|
||||
| dev 密码 | `shaguabijia_dev_pw`(本地非机密) |
|
||||
| 业务库(dev 运行) | `shaguabijia` |
|
||||
| 测试库(pytest) | `shaguabijia_test` |
|
||||
| dev `DATABASE_URL` | `postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia` |
|
||||
| test `DATABASE_URL` | `postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia_test` |
|
||||
| 数据持久化 | 命名卷 `pgdata` |
|
||||
|
||||
---
|
||||
|
||||
## 6. 失败处理矩阵(无 SQLite 兜底)
|
||||
|
||||
| 情形 | ensure_pg 行为 |
|
||||
|---|---|
|
||||
| `DATABASE_URL` 是 sqlite | 打印应改成的 PG 串 → 非 0 退出 |
|
||||
| PG 已在跑(TCP 通) | 打印"已就绪" → 返回 0(跳过 docker) |
|
||||
| 无 docker CLI | 提示装 Docker Desktop + 官网链接 → 非 0 退出 |
|
||||
| docker 守护进程未起 | 尝试按平台启动 Docker Desktop,轮询到就绪;超时则报错 → 非 0 退出 |
|
||||
| 镜像缺失 | `docker compose up -d` 自动拉取(不额外处理) |
|
||||
| 容器起了但 PG 未 ready | 轮询 healthcheck 到超时;超时报错 → 非 0 退出 |
|
||||
| 老 pgdata 卷缺测试库 | 幂等 `CREATE DATABASE shaguabijia_test` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 风险与边界
|
||||
|
||||
- **端口占用(原生 PG 撞 5432)**:D3 选了 5432。若开发机已有原生 PG 监听 5432,step 2 的 TCP 探测会判"PG 已在"并复用它——但那个实例可能没有 `shaguabijia`/`shaguabijia_test` 库或用户,后续 `alembic upgrade head` / 测试会报连不上库或认证失败。**缓解**:文档提示"本机别再单独跑原生 PG";报错信息里提示检查是不是撞了原生 PG。
|
||||
- **首次启动慢**:首用需 Docker Desktop 冷启(~30–60s)+ 拉镜像(~数十秒~数分钟,视网络)。`ensure_pg` 全程打印进度,超时可配。
|
||||
- **`DATABASE_URL` 环境变量优先级**:pydantic-settings 里 shell 环境变量优先于 `.env`。若开发者 shell 残留旧的 `DATABASE_URL`(如指向 sqlite),会盖过 `.env`。sqlite 守卫(D4)能挡住 sqlite 残留;但若残留的是另一个 PG 串,则以它为准——文档提示。
|
||||
- **持久卷脏状态**:测试用 drop_all→create_all 开头清库,避免上次崩溃残留污染;dev 业务库随卷留存(符合预期)。
|
||||
- **Docker 未安装/公司网络拉镜像受限**:硬失败并给出明确指引;不提供 SQLite 退路是刻意选择(D4/目标)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 验收标准
|
||||
|
||||
1. 全新机器(装了 Docker Desktop、`.env` 从 `.env.example` 复制)执行 `run.bat`(或 `run.sh`):自动拉起 Docker→起 PG 容器→建库→`alembic upgrade head`→uvicorn 起在 8770,无手动装 PG 步骤。
|
||||
2. `docker ps` 见 `shaguabijia-pg` 健康;`psql`/客户端能连 `shaguabijia` 与 `shaguabijia_test` 两个库。
|
||||
3. PG 已在跑时再次 `run`,`ensure_pg` 秒过(不重复拉容器)。
|
||||
4. `pytest` 连 `shaguabijia_test` 跑;红用例全部修绿(PG 严格性暴露的问题)。
|
||||
5. `.env` 的 `DATABASE_URL` 改回 sqlite 时,`run`/`pytest` 硬失败并打印正确的 PG 串。
|
||||
6. 能在 `admin/repositories/` 里写一段 PG 专有聚合 SQL(如带 `FILTER (WHERE ...)` 的聚合),`run` 下手动跑通、相应 pytest 也通过——即"双库兼容负担消失"的实证。
|
||||
|
||||
---
|
||||
|
||||
## 9. 待实现清单(供 writing-plans 拆解)
|
||||
|
||||
- [ ] 新增 `docker-compose.yml`
|
||||
- [ ] 新增 `docker/initdb/01-create-test-db.sql`
|
||||
- [ ] 新增 `scripts/ensure_pg.py`(TCP 探测 / 启 Docker Desktop 轮询 / compose up / 等 healthy / 幂等建测试库 / sqlite 守卫)
|
||||
- [ ] `run.sh`、`run.bat` 接入 `ensure_pg`
|
||||
- [ ] `.env.example` 的 `DATABASE_URL` 切 PG
|
||||
- [ ] `tests/conftest.py` 切 `shaguabijia_test` + 调 `ensure_pg` + fixture 改 drop/create
|
||||
- [ ] 跑 `pytest`,按迁移指南 §2.2 修红用例
|
||||
- [ ] 文档:`postgres-migration.md` 增「本地 Docker 一键起」节;`CLAUDE.md` DB 段;`init_postgres.py` 注释
|
||||
- [ ] `.gitignore` 确认 `data/` 已忽略(compose 用命名卷,不落项目目录,无需额外忽略)
|
||||
|
||||
---
|
||||
|
||||
## 10. 增补(2026-07-27):D4 反转 —— 显式 SQLite 逃生舱
|
||||
|
||||
> 背景:§2 的 D4 定为「dev 下 `DATABASE_URL` 仍是 sqlite → 硬失败」,目的是彻底断掉 SQLite 退路。实践中这对「本机装不了 Docker」的开发者过于刚性——直接被卡死、连跑都跑不起来。本次(2026-07-27 对话)把 D4 从「硬失败」松成「**显式逃生舱**」:工具**从不替你静默切库**,但会在没 Docker 时告诉你怎么手动降级,且降级时每次启动都醒目告警。
|
||||
|
||||
### 10.1 决策更新
|
||||
|
||||
| # | 原决策 | 新决策 | 理由 |
|
||||
|---|---|---|---|
|
||||
| D4′ | dev sqlite URL → 硬失败退出 | **放行 + 每次打印醒目降级横幅**(仍非静默) | 已手动改 `.env`=sqlite = 开发者的显式选择,尊重它;但吼一嗓子防止忘了自己在降级、把 PG 专有 SQL 提交上去 |
|
||||
| D8(新) | (无) | 无 docker CLI 时,报错里**追加逃生舱指路**(改 `.env`=sqlite),但仍非 0 退出 | 「显式」的关键:工具不替你切库,只指路;开发者改完 `.env` 再跑一次才真正降级 |
|
||||
|
||||
**未变**:D1(测试仍只跑 PG)、D2-D3、D5-D7 全部保留。逃生舱**只作用于 `run.sh`/`run.bat` 运行时**;`pytest` 仍写死连 PG 测试库(`conftest.py` 传 PG URL,sqlite 分支根本不触发),没 Docker 就 `raise`、跑不了完整套件——这正是 D1「测试上 PG 才能暴露真 bug」的初衷,刻意不给逃生舱。
|
||||
|
||||
### 10.2 代码改动(仅 `scripts/ensure_pg.py` 的 `ensure()`)
|
||||
|
||||
1. **sqlite 分支**(原 `return False`)→ 打印多行降级横幅后 `return True`。横幅点明:PG 专有 SQL/严格类型在此模式**不被验证**、提交前须在有 Docker 的机器上用 PG 复跑、装好 Docker 后把 `DATABASE_URL` 改回 PG 串。
|
||||
2. **无 docker CLI 分支**(原仅提示装 Docker + `return False`)→ 追加一句「装不了 Docker?把 `.env` 的 `DATABASE_URL` 改成 `sqlite:///./data/app.db` 可降级运行」;**仍 `return False`**(run 脚本照常退出,开发者需显式改 .env 再跑)。
|
||||
3. **常量**:新增 `SQLITE_URL = "sqlite:///./data/app.db"`(逃生舱指路用);`SQLITE_FIX_HINT` 重命名 `PG_URL`(降级横幅"改回 PG"引用)。
|
||||
4. 更新模块 docstring 中「全程无 SQLite 兜底」一句,改述为「无 Docker/sqlite URL 时【显式】降级 SQLite(带醒目告警),测试侧不降级」。
|
||||
|
||||
**其余全不动**:`run.sh`/`run.bat`(sqlite 下 `ensure` 返 True → 照常 `alembic upgrade head` + uvicorn)、`docker-compose.yml`、`app/db/session.py`(SQLite 引擎分支本就保留为 fallback)、`tests/conftest.py`、`.env.example`(默认仍 PG)。
|
||||
|
||||
### 10.3 改完后行为矩阵(覆盖用户列的 5 场景)
|
||||
|
||||
| 场景 | `DATABASE_URL` | ensure_pg 行为 |
|
||||
|---|---|---|
|
||||
| ① 无 Docker | PG(默认) | 报错 + 指逃生舱 → 退出;开发者改 `.env`=sqlite → 再跑 → **放行 + 降级横幅**,alembic/uvicorn 跑 SQLite |
|
||||
| ② 有 Docker 未启动 | PG | 启 Docker Desktop → `compose up` → 等 ready → 建测试库(**不变**) |
|
||||
| ③ 有 Docker 已启动 | PG | `compose up` → 等 ready(**不变**) |
|
||||
| ④ PG 已在跑 | PG | TCP 通 → 秒过跳过 Docker(**不变**) |
|
||||
| ⑤ PG 起来后 | 任意 | run 脚本 `alembic upgrade head`(**不变**;SQLite 走 `render_as_batch`) |
|
||||
|
||||
### 10.4 风险
|
||||
|
||||
- **降级被忽视**:横幅仅在 `run` 启动时打印一次;若开发者用 IDE 直接起 uvicorn(绕过 run 脚本)则看不到。缓解:横幅足够醒目 + 文档强调;**不**引入 app 启动期重复告警(YAGNI)。
|
||||
- **测试无 Docker 跑不了**:刻意保留(D1)。文档提示无 Docker 者:要么装 Docker 跑全量测试,要么只在 CI/有 Docker 的机器上验证 PG 相关改动。
|
||||
|
||||
### 10.5 Redis 前瞻(不在本次)
|
||||
|
||||
§2 未涉及 Redis。②③ 场景未来若加 Redis 实例:在 `docker-compose.yml` 增 `redis` 服务即可,`docker compose up -d` 天然带起;仅当启动期有组件依赖 Redis 才需给 `ensure_pg` 加 redis readiness 探测。本次不做,方案对它友好。
|
||||
|
||||
### 10.6 附带修复:`_docker_cli_ok` 守护进程误判(2026-07-27)
|
||||
|
||||
诊断「装了 Docker Desktop 却报未检测到 docker」时发现的真 bug:`_docker_cli_ok()` 原用 `docker version`
|
||||
判断 CLI 是否存在,但该命令**要连 daemon**,守护进程没起时退非零 → 把「Docker 装了但没启动」
|
||||
误判成「没装 CLI」,`ensure()` 直接打印"请安装 Docker Desktop"并 `return False`,**绕过了专为需求②
|
||||
写的 `_start_docker_daemon()` 自动拉起逻辑**——需求②(有 Docker 未启动 → 自动启动)因此从未真正生效。
|
||||
修复:改用 `docker --version`(纯客户端、不连 daemon、退 0)。`_docker_daemon_ok()` 仍用 `docker info`
|
||||
(正确,该检查本就依赖 daemon)。实测机器:Docker Desktop 20.10.12 已装但引擎未起,修复前 `_docker_cli_ok()`
|
||||
误报 False,修复后 True。
|
||||
|
||||
### 10.7 附带修复:固定 compose 项目名 + 清理残留同名容器(2026-07-27)
|
||||
|
||||
诊断「`docker compose up` 报 `container name "/shaguabijia-pg" already in use`」时发现的又一 bug:compose
|
||||
项目名默认取运行目录 basename,在不同目录/worktree(如 `local-dev-postgres-docker` vs `shaguabijia-app-server`)
|
||||
之间切换会各自成一个项目;而 `docker-compose.yml` 写死了 `container_name: shaguabijia-pg`(全局唯一名),
|
||||
于是新项目 `up` 时要创建同名容器 → 撞上旧项目留下的那个 → 冲突。副作用:`pgdata` 卷也按项目名分裂
|
||||
成 `local-dev-postgres-docker_pgdata` / `shaguabijia-app-server_pgdata`,数据被切成两半。
|
||||
|
||||
修复(均在 `scripts/ensure_pg.py`,`docker-compose.yml` 不动、容器名仍是 `shaguabijia-pg`):
|
||||
1. 模块级 `os.environ.setdefault("COMPOSE_PROJECT_NAME", "shaguabijia")` —— 钉死项目名,无论从哪个
|
||||
目录/worktree 跑都是同一个项目、同一个卷 `shaguabijia_pgdata`,所有 `docker compose up/exec` 一致。
|
||||
2. `_compose_up()` 前置 `_remove_stale_container()`:若存在「同名但不属于本项目」的残留容器,先 `docker rm -f`
|
||||
再 up(靠 `docker ps --filter name/label` 判归属;数据在命名卷里,删容器不丢)。旧目录/worktree 留下的
|
||||
残留容器就此自动清掉,不需手动干预。
|
||||
|
||||
影响:本次修复后首跑,旧的 `shaguabijia-pg`(属项目 `local-dev-postgres-docker`)会被自动删除、在项目
|
||||
`shaguabijia` 下重建,挂载全新的 `shaguabijia_pgdata`(空库,`alembic upgrade head` 重建表)。旧数据仍留在
|
||||
`local-dev-postgres-docker_pgdata` 卷里(未删,可恢复);确认不需要后可 `docker volume rm` 清理两个旧卷。
|
||||
@@ -30,7 +30,14 @@ if not exist .env (
|
||||
|
||||
if not exist data mkdir data
|
||||
|
||||
REM Build/upgrade SQLite schema (idempotent; no-op if already at head)
|
||||
REM Ensure local Docker PostgreSQL is up (auto-starts Docker + PG container if needed)
|
||||
call "%PY%" -m scripts.ensure_pg
|
||||
if errorlevel 1 (
|
||||
echo [X] ensure_pg failed ^(PostgreSQL not ready^)
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
REM Build/upgrade schema (idempotent; no-op if already at head)
|
||||
call "%PY%" -m alembic upgrade head
|
||||
if errorlevel 1 (
|
||||
echo [X] alembic upgrade head failed
|
||||
|
||||
@@ -18,7 +18,8 @@ if [ ! -f .env ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p data # sqlite 文件所在目录
|
||||
mkdir -p data # 运行期落盘目录(媒体上传等)
|
||||
"$PY" -m scripts.ensure_pg # 确保本地 Docker PostgreSQL 就绪(没起会自动拉起;失败即退出)
|
||||
"$PY" -m alembic upgrade head # 确保表已建(幂等,已是最新则 no-op)
|
||||
|
||||
# --reload 只盯源码目录 app/:别去监视 logs/(日志写入触发"检测→再写日志"回环)和
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
@echo off
|
||||
REM Admin backend startup (Windows) - the :8771 peer of run.bat.
|
||||
REM
|
||||
REM Usage:
|
||||
REM cd shaguabijia-app-server
|
||||
REM run8771.bat
|
||||
REM
|
||||
REM Runs the ADMIN FastAPI app (app.admin.main:admin_app) on 127.0.0.1:8771 —
|
||||
REM a SEPARATE process from run.bat (which runs app.main:app on 8770). The admin
|
||||
REM web frontend (Next.js :3001) points at http://localhost:8771. Auto-reload on
|
||||
REM code change.
|
||||
REM
|
||||
REM Prerequisite (first time):
|
||||
REM conda activate pricebot ^&^& pip install -e .
|
||||
REM copy .env.example .env ^&^& fill JWT_SECRET_KEY
|
||||
REM
|
||||
REM Tip: shaguabijia-admin-web\start.bat starts user-api(8770) + admin-api(8771)
|
||||
REM + frontend(3001) in one go, if you prefer a single command.
|
||||
|
||||
cd /d "%~dp0"
|
||||
|
||||
REM Prefer the project virtualenv (.venv) so we never inherit a wrong
|
||||
REM global/conda interpreter. FastAPI<0.115 on Pydantic 2.12 crashes at import
|
||||
REM with "'FieldInfo' object has no attribute 'in_'". Falls back to PATH python.
|
||||
set "PY=python"
|
||||
if exist "%~dp0.venv\Scripts\python.exe" set "PY=%~dp0.venv\Scripts\python.exe"
|
||||
|
||||
if not exist .env (
|
||||
echo [X] Missing .env. Run: copy .env.example .env and fill JWT_SECRET_KEY ^(plus MT_CPS_* if you test Meituan^)
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if not exist data mkdir data
|
||||
|
||||
REM Ensure local Docker PostgreSQL is up (auto-starts Docker + PG container if needed)
|
||||
call "%PY%" -m scripts.ensure_pg
|
||||
if errorlevel 1 (
|
||||
echo [X] ensure_pg failed ^(PostgreSQL not ready^)
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
REM Build/upgrade schema (idempotent; no-op if already at head)
|
||||
call "%PY%" -m alembic upgrade head
|
||||
if errorlevel 1 (
|
||||
echo [X] alembic upgrade head failed
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
REM Long-running foreground process. Ctrl+C to stop.
|
||||
"%PY%" -m uvicorn app.admin.main:admin_app --host 127.0.0.1 --port 8771 --reload
|
||||
@@ -0,0 +1,394 @@
|
||||
"""确保本地 PostgreSQL 就绪(开发/测试统一用 Docker PG)。
|
||||
|
||||
被三处复用:
|
||||
- run.sh / run.bat:`python -m scripts.ensure_pg`(CLI,失败退非 0)
|
||||
- tests/conftest.py:`from scripts.ensure_pg import ensure; ensure(test_url)`
|
||||
|
||||
流程:读 DATABASE_URL → TCP 探测 → 没起就(必要时启 Docker Desktop)→
|
||||
`docker compose up -d` → 等 PG ready → 幂等确保测试库存在。
|
||||
|
||||
运行时(run.sh/run.bat)支持【显式】SQLite 逃生舱:DATABASE_URL 设为 sqlite → 放行并打印
|
||||
醒目降级横幅(绝不静默替你切库);无 docker CLI 时报错里也指路该逃生舱。测试侧
|
||||
(conftest 传 PG URL)不降级——sqlite 分支不触发,没 PG 直接 raise。详见设计文档 §10。
|
||||
|
||||
生产用原生 PG(scripts/init_postgres.py),不走本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path, PureWindowsPath
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
# 日志里可能含 emoji(如 ✅);Windows GBK 控制台(cmd.exe)无法编码会抛 UnicodeEncodeError → 脚本崩、
|
||||
# run.bat 误判 ensure_pg 失败。用 backslashreplace 保底:中文仍正常,仅不可编码字符被转义,不崩。
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_stream.reconfigure(errors="backslashreplace")
|
||||
except (AttributeError, ValueError):
|
||||
pass
|
||||
|
||||
APP_DB = "shaguabijia"
|
||||
TEST_DB = "shaguabijia_test"
|
||||
DB_USER = "shaguabijia_app"
|
||||
COMPOSE_SERVICE = "postgres"
|
||||
CONTAINER_NAME = "shaguabijia-pg" # 必须与 docker-compose.yml 的 container_name 一致
|
||||
|
||||
# 钉死 compose 项目名:否则它默认取运行目录 basename,在不同目录/worktree 之间切会各自
|
||||
# 成一个项目 → 同一个固定 container_name 撞名报错、pgdata 卷还会按项目名分裂成多份。
|
||||
# 钉成 app 名后,无论从哪个目录/worktree 跑都是同一个项目、同一个卷。setdefault:尊重外部覆盖。
|
||||
os.environ.setdefault("COMPOSE_PROJECT_NAME", "shaguabijia")
|
||||
|
||||
DOCKER_START_TIMEOUT = int(os.environ.get("ENSURE_PG_DOCKER_TIMEOUT", "120"))
|
||||
PG_READY_TIMEOUT = int(os.environ.get("ENSURE_PG_READY_TIMEOUT", "60"))
|
||||
# 单条 docker 探测/exec 命令的超时:防 Docker 守护进程半死(尤其 Windows 冷启)时
|
||||
# docker info / exec 无限挂起、绕过上面的总超时。
|
||||
DOCKER_CMD_TIMEOUT = int(os.environ.get("ENSURE_PG_CMD_TIMEOUT", "15"))
|
||||
POLL_INTERVAL = 3.0
|
||||
|
||||
PG_URL = (
|
||||
"postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia"
|
||||
)
|
||||
SQLITE_URL = "sqlite:///./data/app.db" # 无 Docker 时的显式降级逃生舱(仅 run 运行时)
|
||||
|
||||
|
||||
def _log(msg: str) -> None:
|
||||
print(f"[ensure_pg] {msg}", flush=True)
|
||||
|
||||
|
||||
def _is_sqlite(url: str) -> bool:
|
||||
return url.strip().lower().startswith("sqlite")
|
||||
|
||||
|
||||
def _parse_host_port(url: str) -> tuple[str, int]:
|
||||
"""从 SQLAlchemy URL 取 host/port,缺省 localhost:5432。"""
|
||||
parts = urlsplit(url)
|
||||
return (parts.hostname or "localhost"), (parts.port or 5432)
|
||||
|
||||
|
||||
def _port_open(host: str, port: int, timeout: float = 1.0) -> bool:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _win_docker_desktop_candidates(
|
||||
env: Mapping[str, str], docker_cli: str | None
|
||||
) -> list[PureWindowsPath]:
|
||||
"""Windows 上 Docker Desktop.exe 的候选路径(按优先级)。纯函数:不碰文件系统、不读注册表。
|
||||
|
||||
用 PureWindowsPath 解析,故在任意 OS 上跑单测都按 Windows 语义(反斜杠分隔),行为确定。
|
||||
优先级:
|
||||
① 环境变量 DOCKER_DESKTOP_EXE 显式指定(终极逃生舱,盘符随你);
|
||||
② 从 PATH 上的 docker CLI 反推——Docker Desktop 的 CLI 在
|
||||
<安装目录>\\resources\\bin\\docker.exe,往上几级即安装目录,天然跟随实际盘符
|
||||
(装在 D 盘就反推出 D 盘,不再写死 C 盘);多取几级容忍未来目录布局微调;
|
||||
③ 各 Program Files 变体下的标准安装路径兜底(覆盖常规 C 盘装)。
|
||||
调用方按序取第一个真实存在的。
|
||||
"""
|
||||
out: list[PureWindowsPath] = []
|
||||
override = (env.get("DOCKER_DESKTOP_EXE") or "").strip().strip('"')
|
||||
if override:
|
||||
out.append(PureWindowsPath(override))
|
||||
if docker_cli:
|
||||
for parent in list(PureWindowsPath(docker_cli).parents)[:4]:
|
||||
out.append(parent / "Docker Desktop.exe")
|
||||
for var in ("ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"):
|
||||
root = env.get(var)
|
||||
if root:
|
||||
out.append(PureWindowsPath(root) / "Docker" / "Docker" / "Docker Desktop.exe")
|
||||
return out
|
||||
|
||||
|
||||
def _docker_desktop_from_registry() -> Path | None:
|
||||
"""从注册表尽力取 Docker Desktop.exe 位置(best-effort;非 Windows / 任何异常都当没找到)。
|
||||
|
||||
比路径猜测更权威且完全跟随实际盘符。探两处:
|
||||
- App Paths\\Docker Desktop.exe 的默认值(通常就是 exe 全路径);
|
||||
- Uninstall\\Docker Desktop 的 InstallLocation(安装目录,需再拼 exe 名)。
|
||||
"""
|
||||
try:
|
||||
import winreg
|
||||
except ImportError: # 非 Windows
|
||||
return None
|
||||
probes = (
|
||||
(winreg.HKEY_LOCAL_MACHINE,
|
||||
r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Docker Desktop.exe", "", False),
|
||||
(winreg.HKEY_LOCAL_MACHINE,
|
||||
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Docker Desktop",
|
||||
"InstallLocation", True),
|
||||
)
|
||||
for hive, subkey, value_name, join_exe in probes:
|
||||
try:
|
||||
with winreg.OpenKey(hive, subkey) as key:
|
||||
val, _ = winreg.QueryValueEx(key, value_name)
|
||||
except OSError:
|
||||
continue # 键不存在/无权限 → 下一个
|
||||
if not val:
|
||||
continue
|
||||
exe = Path(val) / "Docker Desktop.exe" if join_exe else Path(val)
|
||||
if exe.exists():
|
||||
return exe
|
||||
return None
|
||||
|
||||
|
||||
def _find_docker_desktop_exe() -> Path | None:
|
||||
"""Windows 上尽力定位【真实存在】的 Docker Desktop.exe;遍历候选 + 注册表兜底,找不到返回 None。"""
|
||||
for cand in _win_docker_desktop_candidates(os.environ, shutil.which("docker")):
|
||||
if Path(cand).exists():
|
||||
return Path(cand)
|
||||
return _docker_desktop_from_registry()
|
||||
|
||||
|
||||
def _docker_desktop_cmd(platform: str) -> list[str] | None:
|
||||
"""按平台给出启动 Docker Desktop 的命令。
|
||||
|
||||
Windows:智能定位 exe(见 _find_docker_desktop_exe),找不到 → None。
|
||||
macOS:交给 `open -a Docker`。Linux:None(daemon 需 sudo,让用户手动)。
|
||||
"""
|
||||
if platform.startswith("win"):
|
||||
exe = _find_docker_desktop_exe()
|
||||
return [str(exe)] if exe else None
|
||||
if platform == "darwin":
|
||||
return ["open", "-a", "Docker"]
|
||||
return None
|
||||
|
||||
|
||||
def _docker_ok(subcmd: str) -> bool:
|
||||
"""`docker --version`(CLI 在不在,纯客户端)/`docker info`(daemon 起没起)成功与否。"""
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", subcmd],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
return True
|
||||
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
|
||||
|
||||
def _docker_cli_ok() -> bool:
|
||||
# 必须用 `docker --version`(纯客户端,不连 daemon)而非 `docker version`
|
||||
# (后者要连 daemon,守护进程没起时退非零)——否则「装了 Docker 但没启动」
|
||||
# 会被误判成「没装 CLI」,直接绕过下面 _start_docker_daemon() 的自动拉起(需求②)。
|
||||
return _docker_ok("--version")
|
||||
|
||||
|
||||
def _docker_daemon_ok() -> bool:
|
||||
return _docker_ok("info")
|
||||
|
||||
|
||||
def _start_docker_daemon() -> bool:
|
||||
"""守护进程没起时按平台拉起,轮询到就绪。返回是否成功。"""
|
||||
if _docker_daemon_ok():
|
||||
return True
|
||||
cmd = _docker_desktop_cmd(sys.platform)
|
||||
if cmd is None:
|
||||
if sys.platform.startswith("win"):
|
||||
# docker CLI 在 PATH 上(否则走不到这)、却定位不到 Docker Desktop.exe:多为非标准安装位置
|
||||
_log("找不到 Docker Desktop.exe(已试:PATH 上 docker CLI 反推、注册表、常见安装目录)。")
|
||||
_log(" 确已安装 → 设环境变量 DOCKER_DESKTOP_EXE=<Docker Desktop.exe 全路径> 再重试,"
|
||||
"或先手动启动 Docker Desktop。")
|
||||
_log(f" 不想折腾 → 把 .env 的 DATABASE_URL 改成 {SQLITE_URL} 可降级用 SQLite 跑(仅救急)。")
|
||||
else:
|
||||
_log("Docker 守护进程未运行。Linux 请手动:sudo systemctl start docker,然后重试。")
|
||||
return False
|
||||
_log(f"启动 Docker Desktop(首次冷启可能 30-60s):{cmd[0]}")
|
||||
try:
|
||||
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except OSError as e:
|
||||
_log(f"启动 Docker Desktop 失败:{e}")
|
||||
return False
|
||||
deadline = time.monotonic() + DOCKER_START_TIMEOUT
|
||||
while time.monotonic() < deadline:
|
||||
if _docker_daemon_ok():
|
||||
_log("Docker 守护进程已就绪。")
|
||||
return True
|
||||
_log("等待 Docker 守护进程…")
|
||||
time.sleep(POLL_INTERVAL)
|
||||
_log(f"等待 Docker 守护进程超时({DOCKER_START_TIMEOUT}s)。")
|
||||
return False
|
||||
|
||||
|
||||
def _ps_names(*filters: str) -> str:
|
||||
"""docker ps -a 按 filter 查容器名(每行一个);失败返回空串。"""
|
||||
args = ["docker", "ps", "-a", "--format", "{{.Names}}"]
|
||||
for f in filters:
|
||||
args += ["--filter", f]
|
||||
try:
|
||||
r = subprocess.run(
|
||||
args, cwd=ROOT, capture_output=True, text=True, timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return ""
|
||||
return r.stdout if r.returncode == 0 else ""
|
||||
|
||||
|
||||
def _remove_stale_container() -> None:
|
||||
"""删掉「同名但不属于本 compose 项目」的残留容器(旧目录/worktree 建的)。
|
||||
|
||||
固定的 container_name 是全局唯一名:若旧项目留下一个同名容器,`docker compose up`
|
||||
会因撞名报 "container name already in use" 而失败。这里在 up 之前主动清掉它。
|
||||
数据在命名卷(<project>_pgdata)里,删容器不删卷、不丢数据。
|
||||
"""
|
||||
project = os.environ.get("COMPOSE_PROJECT_NAME", "")
|
||||
name_filter = f"name=^{CONTAINER_NAME}$"
|
||||
if CONTAINER_NAME not in _ps_names(name_filter).split():
|
||||
return # 没有同名容器
|
||||
ours = _ps_names(name_filter, f"label=com.docker.compose.project={project}")
|
||||
if CONTAINER_NAME in ours.split():
|
||||
return # 就是本项目的容器,compose 会自己 start/复用,别删
|
||||
_log(f"发现残留同名容器 {CONTAINER_NAME}(非本项目 '{project}'),删除以避免撞名"
|
||||
f"(数据在卷里,不丢)…")
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", "rm", "-f", CONTAINER_NAME], cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
_log(f"⚠️ 删除残留容器失败,可手动: docker rm -f {CONTAINER_NAME}")
|
||||
|
||||
|
||||
def _compose_up() -> bool:
|
||||
_remove_stale_container()
|
||||
_log("docker compose up -d(镜像缺失会自动拉取,首用约几十秒)…")
|
||||
try:
|
||||
subprocess.run(["docker", "compose", "up", "-d"], cwd=ROOT, check=True)
|
||||
return True
|
||||
except (OSError, subprocess.CalledProcessError) as e:
|
||||
_log(f"docker compose up 失败:{e}")
|
||||
return False
|
||||
|
||||
|
||||
def _pg_isready() -> bool:
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"pg_isready", "-U", DB_USER, "-d", APP_DB],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return r.returncode == 0
|
||||
|
||||
|
||||
def _wait_pg_ready(host: str, port: int) -> bool:
|
||||
deadline = time.monotonic() + PG_READY_TIMEOUT
|
||||
while time.monotonic() < deadline:
|
||||
if _port_open(host, port) and _pg_isready():
|
||||
_log("PostgreSQL 已就绪。")
|
||||
return True
|
||||
_log("等待 PostgreSQL 就绪…")
|
||||
time.sleep(POLL_INTERVAL)
|
||||
_log(f"等待 PostgreSQL 就绪超时({PG_READY_TIMEOUT}s)。")
|
||||
return False
|
||||
|
||||
|
||||
def _test_db_exists() -> bool:
|
||||
"""测试库是否已存在(连业务库 shaguabijia 查 pg_database)。"""
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"psql", "-U", DB_USER, "-d", APP_DB, "-tAc",
|
||||
f"SELECT 1 FROM pg_database WHERE datname='{TEST_DB}'"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return r.returncode == 0 and r.stdout.strip() == "1"
|
||||
|
||||
|
||||
def ensure_test_db() -> bool:
|
||||
"""幂等建测试库(兼容老 pgdata 卷首启没跑 initdb 的情况)。返回测试库是否就绪。
|
||||
|
||||
公开给 conftest 单独调用:ensure() 在「端口已通」时会短路返回、不建测试库,
|
||||
所以测试侧需在 ensure() 之后再显式补一刀(best-effort)。
|
||||
"""
|
||||
if _test_db_exists():
|
||||
return True
|
||||
_log(f"建测试库 {TEST_DB}…")
|
||||
try:
|
||||
create = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", COMPOSE_SERVICE,
|
||||
"psql", "-U", DB_USER, "-d", APP_DB, "-c",
|
||||
f"CREATE DATABASE {TEST_DB} OWNER {DB_USER}"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=DOCKER_CMD_TIMEOUT,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as e:
|
||||
_log(f"⚠️ 建测试库 {TEST_DB} 失败:{e}")
|
||||
return False
|
||||
# returncode==0=建成功;非 0 但库已存在=与并发创建者竞争失败(42P04),仍算就绪
|
||||
if create.returncode == 0 or _test_db_exists():
|
||||
return True
|
||||
_log(f"⚠️ 建测试库 {TEST_DB} 失败:{(create.stderr or '').strip()}")
|
||||
return False
|
||||
|
||||
|
||||
def _warn_sqlite_degraded() -> None:
|
||||
"""DATABASE_URL 是 SQLite 时打印醒目降级横幅(显式逃生舱,非静默切库)。"""
|
||||
for line in (
|
||||
"⚠️ ================= 降级模式(SQLite) =================",
|
||||
"⚠️ DATABASE_URL 是 SQLite,不是 PostgreSQL。",
|
||||
"⚠️ PG 专有 SQL(窗口函数/FILTER/JSONB)与严格类型在此模式【不被验证】。",
|
||||
"⚠️ 提交前请在装了 Docker 的机器上用 PG 复跑;装好后把 DATABASE_URL 改回:",
|
||||
f"⚠️ {PG_URL}",
|
||||
"⚠️ ===================================================",
|
||||
):
|
||||
_log(line)
|
||||
|
||||
|
||||
def ensure(database_url: str | None = None) -> bool:
|
||||
"""确保 PG 就绪,返回 True/False。database_url 缺省从 settings 读(尊重 .env)。
|
||||
|
||||
运行时若 DATABASE_URL 是 SQLite → 打印降级横幅并返回 True(显式逃生舱);
|
||||
conftest 传的是 PG URL,故测试侧永不走此分支。
|
||||
"""
|
||||
if database_url is None:
|
||||
from app.core.config import settings # 延迟导入,避免过早固化 settings
|
||||
|
||||
database_url = settings.DATABASE_URL
|
||||
|
||||
if _is_sqlite(database_url):
|
||||
_warn_sqlite_degraded()
|
||||
return True
|
||||
|
||||
host, port = _parse_host_port(database_url)
|
||||
|
||||
if _port_open(host, port):
|
||||
_log(f"✅ PostgreSQL 已在 {host}:{port} 运行,跳过 Docker。")
|
||||
return True
|
||||
|
||||
_log(f"{host}:{port} 无 PostgreSQL,准备用 Docker 拉起…")
|
||||
|
||||
if not _docker_cli_ok():
|
||||
_log("未检测到 docker 命令。请先安装 Docker Desktop:")
|
||||
_log(" https://www.docker.com/products/docker-desktop/")
|
||||
_log(f"装不了 Docker?把 .env 的 DATABASE_URL 改成 {SQLITE_URL} 可降级用 SQLite 跑")
|
||||
_log(" (PG 专有 SQL/严格性不被验证,仅救急);改完重跑 run.sh/run.bat。")
|
||||
return False
|
||||
if not _start_docker_daemon():
|
||||
return False
|
||||
if not _compose_up():
|
||||
return False
|
||||
if not _wait_pg_ready(host, port):
|
||||
return False
|
||||
if not ensure_test_db():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(0 if ensure() else 1)
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Bootstrap PostgreSQL: 建用户 + 建库 + 授权 + 写 .env + 跑迁移。
|
||||
|
||||
新机器初始化用。前置:已装 PostgreSQL 16 + 知道 postgres 超级用户密码。
|
||||
新机器初始化用(面向【生产原生 PG】:apt/systemd 装好的 PostgreSQL)。
|
||||
本地开发/测试请改用 docker-compose.yml + scripts/ensure_pg.py(run.sh/run.bat 自动拉起),不必跑本脚本。
|
||||
前置:已装 PostgreSQL 16 + 知道 postgres 超级用户密码。
|
||||
|
||||
用法:
|
||||
python scripts/init_postgres.py
|
||||
|
||||
+22
-15
@@ -1,22 +1,19 @@
|
||||
"""测试用 fixtures。
|
||||
|
||||
测试 DB 用临时文件 SQLite。
|
||||
- 不用 in-memory:in-memory 默认 per-connection,跨连接看不到表。
|
||||
- 用临时文件保证 SessionLocal 每次新连都看到同一份 schema。
|
||||
|
||||
顺序:set env(必须在 import app.* 之前) → import app → 建表 → TestClient
|
||||
测试库用 Docker PostgreSQL 的 shaguabijia_test(与 dev 业务库 shaguabijia 隔离)。
|
||||
顺序(必须):设 test DATABASE_URL(在 import app.* 之前)→ ensure PG 就绪 + 测试库存在 →
|
||||
import app → 建表。持久卷可能残留上次的表 → session 开头先 drop 再 create。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from collections.abc import Iterator
|
||||
|
||||
# 临时 db 文件路径,进程退出后清理
|
||||
_tmp_db = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
|
||||
_tmp_db.close()
|
||||
|
||||
os.environ["DATABASE_URL"] = f"sqlite:///{_tmp_db.name}"
|
||||
# 1) 测试库连接串——必须在 import app.* 之前设好(app.db.session 在 import 期就建 engine)
|
||||
_TEST_DB_URL = (
|
||||
"postgresql+psycopg://shaguabijia_app:shaguabijia_dev_pw@localhost:5432/shaguabijia_test"
|
||||
)
|
||||
os.environ["DATABASE_URL"] = _TEST_DB_URL
|
||||
os.environ.setdefault("JWT_SECRET_KEY", "test-secret-please-ignore-this-is-only-for-pytest-not-real")
|
||||
os.environ.setdefault("ADMIN_JWT_SECRET", "test-admin-secret-please-ignore-only-for-pytest-not-real")
|
||||
os.environ.setdefault("JG_APP_KEY", "test-key")
|
||||
@@ -35,6 +32,18 @@ os.environ.setdefault("RATE_LIMIT_ENABLED", "false") # 限流内存计数会跨
|
||||
os.environ.setdefault("PANGLE_CALLBACK_ENABLED", "true")
|
||||
os.environ.setdefault("PANGLE_REWARD_SECRET", "test-pangle-secret-only-for-pytest")
|
||||
|
||||
# 2) 保证 Docker PG 就绪(必须在 import app.db.session 建 engine 之前)。
|
||||
# ensure() 在「端口已通」时会短路、不建测试库,故随后再显式补一刀 ensure_test_db()。
|
||||
from scripts.ensure_pg import ensure, ensure_test_db
|
||||
|
||||
if not ensure(_TEST_DB_URL):
|
||||
raise RuntimeError(
|
||||
"测试需要 Docker PostgreSQL 就绪。请确认已装 Docker Desktop;"
|
||||
"或先跑一次 run.bat/run.sh 把 PG 拉起,再重试 pytest。"
|
||||
)
|
||||
# best-effort 兜底建测试库(PG 已在跑但测试库缺失=老卷)。真缺库时下面 create_all 会明确报错。
|
||||
ensure_test_db()
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -45,13 +54,11 @@ from app.main import app
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _setup_db() -> Iterator[None]:
|
||||
# 持久卷可能残留上次跑崩后的表/数据 → 先 drop 再 create,保证干净起点
|
||||
Base.metadata.drop_all(engine)
|
||||
Base.metadata.create_all(engine)
|
||||
yield
|
||||
Base.metadata.drop_all(engine)
|
||||
try:
|
||||
os.unlink(_tmp_db.name)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
|
||||
@@ -219,115 +219,6 @@ def test_user_reward_stats_can_scope_withdrawals_by_account(
|
||||
assert invite.json()["cash_balance_cents"] == 456
|
||||
|
||||
|
||||
def test_user_reward_stats_draw_ecpm_uses_all_filtered_impressions(
|
||||
admin_client: TestClient, admin_token: str
|
||||
) -> None:
|
||||
"""Draw 平均 eCPM 应与收益报表一致,不能只平均成功发奖记录。"""
|
||||
from app.models.ad_ecpm import AdEcpmRecord
|
||||
from app.models.ad_feed_reward import AdFeedRewardRecord
|
||||
|
||||
uid = _seed_user_with_data("13800000024")
|
||||
created_at = datetime(2038, 1, 15, 4, tzinfo=UTC)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db.add_all(
|
||||
[
|
||||
AdFeedRewardRecord(
|
||||
client_event_id="reward-stats-granted-high",
|
||||
ad_session_id="reward-stats-granted-high",
|
||||
user_id=uid,
|
||||
reward_date="2038-01-15",
|
||||
duration_seconds=10,
|
||||
unit_count=1,
|
||||
ecpm_raw="9000",
|
||||
ad_type="draw",
|
||||
feed_scene="coupon",
|
||||
app_env="prod",
|
||||
our_code_id="104098712",
|
||||
coin=9,
|
||||
status="granted",
|
||||
created_at=created_at,
|
||||
),
|
||||
AdEcpmRecord(
|
||||
user_id=uid,
|
||||
ad_type="draw",
|
||||
feed_scene="coupon",
|
||||
ad_session_id="reward-stats-impression-low",
|
||||
app_env="prod",
|
||||
our_code_id="104098712",
|
||||
ecpm_raw="1000",
|
||||
report_date="2038-01-15",
|
||||
created_at=created_at,
|
||||
),
|
||||
AdEcpmRecord(
|
||||
user_id=uid,
|
||||
ad_type="feed",
|
||||
feed_scene="coupon",
|
||||
ad_session_id="reward-stats-impression-mid",
|
||||
app_env="prod",
|
||||
our_code_id="104098712",
|
||||
ecpm_raw="3000",
|
||||
report_date="2038-01-15",
|
||||
created_at=created_at,
|
||||
),
|
||||
# 同用户但不同场景/环境/非业务代码位,均不应进入本次详情筛选。
|
||||
AdEcpmRecord(
|
||||
user_id=uid,
|
||||
ad_type="draw",
|
||||
feed_scene="comparison",
|
||||
ad_session_id="reward-stats-other-scene",
|
||||
app_env="prod",
|
||||
our_code_id="104098712",
|
||||
ecpm_raw="7000",
|
||||
report_date="2038-01-15",
|
||||
created_at=created_at,
|
||||
),
|
||||
AdEcpmRecord(
|
||||
user_id=uid,
|
||||
ad_type="draw",
|
||||
feed_scene="coupon",
|
||||
ad_session_id="reward-stats-test-env",
|
||||
app_env="test",
|
||||
our_code_id="104127529",
|
||||
ecpm_raw="8000",
|
||||
report_date="2038-01-15",
|
||||
created_at=created_at,
|
||||
),
|
||||
AdEcpmRecord(
|
||||
user_id=uid,
|
||||
ad_type="draw",
|
||||
feed_scene="coupon",
|
||||
ad_session_id="reward-stats-non-business",
|
||||
app_env="prod",
|
||||
our_code_id="demo-slot",
|
||||
ecpm_raw="9000",
|
||||
report_date="2038-01-15",
|
||||
created_at=created_at,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
response = admin_client.get(
|
||||
f"/admin/api/users/{uid}/reward-stats",
|
||||
params={
|
||||
"date_from": "2038-01-15T00:00:00Z",
|
||||
"date_to": "2038-01-15T23:59:59Z",
|
||||
"app_env": "prod",
|
||||
"revenue_scope": "business",
|
||||
"feed_scene": "coupon",
|
||||
},
|
||||
headers=_auth(admin_token),
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
data = response.json()
|
||||
assert data["feed_count"] == 1
|
||||
# 全部真实展示 (1000 + 3000) / 2;不能返回成功发奖记录的 9000。
|
||||
assert data["feed_avg_ecpm"] == 2000.0
|
||||
|
||||
|
||||
def test_user_coin_record_sort_accepts_mixed_timezone_datetimes() -> None:
|
||||
"""线上 PostgreSQL 返回 aware,SQLite/历史转换可能返回 naive,二者必须可混排。"""
|
||||
naive = datetime(2038, 1, 1, 8, 0)
|
||||
|
||||
+18
-107
@@ -18,6 +18,7 @@ from sqlalchemy import select
|
||||
from app.db.session import SessionLocal
|
||||
from app.models.comparison import ComparisonRecord
|
||||
from app.repositories import comparison as crud
|
||||
from app.repositories.user import get_user_by_phone
|
||||
from app.schemas.compare_record import ComparisonRecordIn
|
||||
|
||||
|
||||
@@ -46,6 +47,17 @@ def _get(db, trace_id: str) -> ComparisonRecord | None:
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
def _make_user(client, phone: str) -> int:
|
||||
"""登录建号并返回其真实 user_id。
|
||||
|
||||
PG 强制 comparison_record.user_id → user.id 外键,须引用真实存在的用户;
|
||||
用本用例自己登录出的用户,不会与别的用例撞。
|
||||
"""
|
||||
client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"})
|
||||
with SessionLocal() as db:
|
||||
return get_user_by_phone(db, phone).id
|
||||
|
||||
|
||||
# ============================================================
|
||||
# repo 层
|
||||
# ============================================================
|
||||
@@ -102,7 +114,6 @@ def test_harvest_done_derives_and_newly_success_once(client) -> None:
|
||||
assert rec.is_source_best is False
|
||||
assert rec.store_name == "测试店"
|
||||
assert rec.information == "美团更便宜"
|
||||
assert rec.fail_reason is None # 成功记录不派生失败原因
|
||||
assert rec.items == [{"name": "肥牛饭", "qty": 1}]
|
||||
assert rec.trace_url.endswith("/done/")
|
||||
# 再来一次(重试 done)→ 已 success,newly_success=False(发奖不重复触发)
|
||||
@@ -111,104 +122,6 @@ def test_harvest_done_derives_and_newly_success_once(client) -> None:
|
||||
assert newly2 is False
|
||||
|
||||
|
||||
def test_harvest_done_failed_derives_fail_reason(client) -> None:
|
||||
"""failed 记录:记录级 information 笼统,但 fail_reason 从 platform_results 救出具体原因
|
||||
(id 3030 型:美团系统失败 + 京东 items_not_found → 展示京东那条)。"""
|
||||
tid = _tid()
|
||||
done_failed = {
|
||||
"comparison_results": [
|
||||
{"platform_id": "taobao_flash", "platform_name": "淘宝闪购",
|
||||
"package": "com.taobao.taobao", "price": 23.04, "is_source": True, "rank": 1,
|
||||
"items": [{"name": "肥牛饭", "qty": 1}]},
|
||||
],
|
||||
"platform_results": {
|
||||
"taobao_flash": {"is_source": True, "status": "source", "price": 23.04},
|
||||
"meituan_waimai": {"is_source": False, "status": "failed",
|
||||
"reason": "搜索店铺失败, 无法跳转到搜索页"},
|
||||
"jd_waimai_standalone": {"is_source": False, "status": "items_not_found",
|
||||
"reason": "京东外卖此店内未找到这些菜品"},
|
||||
},
|
||||
"information": "比价过程出错,请稍后重试",
|
||||
}
|
||||
with SessionLocal() as db:
|
||||
crud.harvest_running(db, trace_id=tid, user_id=None)
|
||||
rec, newly = crud.harvest_done(db, trace_id=tid, user_id=None,
|
||||
done_params=done_failed)
|
||||
assert newly is False # 没落成 success
|
||||
assert rec.status == "failed"
|
||||
assert rec.fail_reason == "京东外卖此店内未找到这些菜品"
|
||||
assert rec.information == "比价过程出错,请稍后重试" # 原文案仍留存
|
||||
|
||||
|
||||
def _done_params_platforms_no_isbest() -> dict:
|
||||
"""id 3304 型:done 帧 platforms 全平台「相似替换/仅供参考」(has_dish_diff),pricebot
|
||||
一个 is_best 都没标,但有有价目标(美团 57.8 < 源淘宝闪购 60.8)。"""
|
||||
return {
|
||||
"platforms": [
|
||||
{"role": "source", "platform_id": "eleme", "platform_name": "淘宝闪购",
|
||||
"package": "me.ele", "price": 60.8, "is_best": False, "has_dish_diff": False,
|
||||
"store_name": "窑鸡王", "items": [{"name": "招牌窑鸡 整只-香辣", "qty": 1}]},
|
||||
{"role": "target", "platform_id": "meituan_waimai", "platform_name": "美团外卖",
|
||||
"package": "com.sankuai.meituan.takeoutnew", "price": 57.8, "is_best": False,
|
||||
"has_dish_diff": True},
|
||||
{"role": "target", "platform_id": "jd_waimai_standalone", "platform_name": "京东外卖",
|
||||
"package": "com.jd.waimai", "price": 74.9, "is_best": False, "has_dish_diff": True},
|
||||
],
|
||||
"information": "美团更便宜(含相似商品替换)",
|
||||
}
|
||||
|
||||
|
||||
def test_harvest_done_platforms_no_isbest_falls_back_to_cheapest_target(client) -> None:
|
||||
"""回归(id 3304):platforms 全无 is_best(全平台相似替换)但有有价目标 → best 应兜底取
|
||||
有价目标里最低那家,不能让 best_*/saved 整条落 NULL(否则首页价 0.00 / 记录页无最低红框 /
|
||||
省额丢失)。"""
|
||||
tid = _tid()
|
||||
with SessionLocal() as db:
|
||||
crud.harvest_running(db, trace_id=tid, user_id=None)
|
||||
rec, _ = crud.harvest_done(db, trace_id=tid, user_id=None,
|
||||
done_params=_done_params_platforms_no_isbest())
|
||||
assert rec.status == "success"
|
||||
assert rec.best_platform_id == "meituan_waimai" # 有价目标里最低
|
||||
assert rec.best_price_cents == 5780 # 57.8 元
|
||||
assert rec.source_price_cents == 6080 # 源淘宝闪购 60.8
|
||||
assert rec.saved_amount_cents == 300 # 60.8 - 57.8
|
||||
assert rec.is_source_best is False # 兜底选的是目标,非源
|
||||
|
||||
|
||||
def _done_params_no_isbest_source_cheapest() -> dict:
|
||||
"""无 is_best 且源本身最便宜:源淘宝闪购 50.0 < 全部 dish-diff 目标(美团 57.8 / 京东 74.9)。
|
||||
此时不能强选更贵的目标当 best(否则 saved 变负、污染「累计发现可省」),应回落源。"""
|
||||
return {
|
||||
"platforms": [
|
||||
{"role": "source", "platform_id": "eleme", "platform_name": "淘宝闪购",
|
||||
"package": "me.ele", "price": 50.0, "is_best": False, "has_dish_diff": False,
|
||||
"store_name": "窑鸡王", "items": [{"name": "招牌窑鸡 整只-香辣", "qty": 1}]},
|
||||
{"role": "target", "platform_id": "meituan_waimai", "platform_name": "美团外卖",
|
||||
"package": "com.sankuai.meituan.takeoutnew", "price": 57.8, "is_best": False,
|
||||
"has_dish_diff": True},
|
||||
{"role": "target", "platform_id": "jd_waimai_standalone", "platform_name": "京东外卖",
|
||||
"package": "com.jd.waimai", "price": 74.9, "is_best": False, "has_dish_diff": True},
|
||||
],
|
||||
"information": "源平台已是最低(其余为相似替换)",
|
||||
}
|
||||
|
||||
|
||||
def test_harvest_done_no_isbest_source_cheapest_falls_back_to_source(client) -> None:
|
||||
"""回归:无 is_best 且源最便宜 → best 回落源(与 _derive「全目标缺菜回落源、不虚报省」同语义),
|
||||
saved=0、is_source_best=True,绝不因强选更贵目标而让 saved 变负、倒扣「累计发现可省」。"""
|
||||
tid = _tid()
|
||||
with SessionLocal() as db:
|
||||
crud.harvest_running(db, trace_id=tid, user_id=None)
|
||||
rec, _ = crud.harvest_done(db, trace_id=tid, user_id=None,
|
||||
done_params=_done_params_no_isbest_source_cheapest())
|
||||
assert rec.status == "success"
|
||||
assert rec.best_platform_id == "eleme" # 回落到源(源最便宜)
|
||||
assert rec.best_price_cents == 5000 # 源 50.0
|
||||
assert rec.source_price_cents == 5000
|
||||
assert rec.saved_amount_cents == 0 # 没省到,绝不为负
|
||||
assert rec.is_source_best is True # 源就是最便宜
|
||||
|
||||
|
||||
def test_harvest_abort_cancels_running(client) -> None:
|
||||
tid = _tid()
|
||||
with SessionLocal() as db:
|
||||
@@ -242,17 +155,18 @@ def test_harvest_abort_missing_row_returns_none(client) -> None:
|
||||
def test_upsert_record_no_downgrade_after_harvest_success(client) -> None:
|
||||
"""harvest 落 success 后,老客户端 fromFailure 的 cancelled 上报不许把它盖回去。"""
|
||||
tid = _tid()
|
||||
# PG 强制 comparison_record.user_id → user.id 外键(SQLite 不强制,老写法用合成 id
|
||||
# 987654)。用本用例自己登录出的真实用户,既满足外键、又不与别的用例撞。
|
||||
uid = _make_user(client, "13800007701")
|
||||
with SessionLocal() as db:
|
||||
crud.harvest_done(db, trace_id=tid, user_id=None, done_params=_done_params())
|
||||
payload = ComparisonRecordIn(
|
||||
trace_id=tid, business_type="food", status="cancelled",
|
||||
information="用户终止", comparison_results=[],
|
||||
)
|
||||
# 用一个不会与顺序自增用户撞的合成 id(SQLite 测试库 FK 不强制;别用小整数,
|
||||
# 否则会撞上别的测试 login 出来的真实 user_id → 记录混进那个用户的列表)。
|
||||
rec = crud.upsert_record(db, user_id=987654, payload=payload)
|
||||
rec = crud.upsert_record(db, user_id=uid, payload=payload)
|
||||
assert rec.status == "success" # 不降级
|
||||
assert rec.user_id == 987654 # 但补上了 user_id(原为 None)
|
||||
assert rec.user_id == uid # 但补上了 user_id(原为 None)
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -332,9 +246,7 @@ def test_trace_finalize_harvests_abort(client) -> None:
|
||||
with SessionLocal() as db: # 先有 running 行(帧0建的)
|
||||
crud.harvest_running(db, trace_id=tid, user_id=None)
|
||||
p, _cap = _mock_pricebot({"trace_url": "https://price.shaguabijia.com/traces/fin/"})
|
||||
with p, patch(
|
||||
"app.api.v1.compare.backfill_comparison_llm_cost"
|
||||
) as backfill:
|
||||
with p:
|
||||
r = client.post("/api/v1/trace/finalize",
|
||||
json={"trace_id": tid, "status": "cancelled", "reason": "用户终止"})
|
||||
assert r.status_code == 200
|
||||
@@ -342,7 +254,6 @@ def test_trace_finalize_harvests_abort(client) -> None:
|
||||
rec = _get(db, tid)
|
||||
assert rec is not None and rec.status == "cancelled"
|
||||
assert rec.trace_url.endswith("/fin/")
|
||||
backfill.assert_called_once_with(rec.id, tid)
|
||||
|
||||
|
||||
def test_price_step_binds_user_when_authed(client) -> None:
|
||||
|
||||
@@ -72,7 +72,6 @@ def test_backfill_retries_then_persists_cost(monkeypatch):
|
||||
|
||||
def test_repair_batch_only_targets_terminal_missing_rows(monkeypatch):
|
||||
missing_id = _record("llm-repair-missing")
|
||||
cancelled_id = _record("llm-repair-cancelled", status="cancelled")
|
||||
running_id = _record("llm-repair-running", status="running")
|
||||
calls = [
|
||||
{
|
||||
@@ -97,15 +96,12 @@ def test_repair_batch_only_targets_terminal_missing_rows(monkeypatch):
|
||||
)
|
||||
assert result["repaired"] >= 1
|
||||
assert "llm-repair-missing" in seen
|
||||
assert "llm-repair-cancelled" in seen
|
||||
assert "llm-repair-running" not in seen
|
||||
with SessionLocal() as db:
|
||||
assert db.get(ComparisonRecord, missing_id).llm_cost_yuan is not None
|
||||
assert db.get(ComparisonRecord, cancelled_id).llm_cost_yuan is not None
|
||||
assert db.get(ComparisonRecord, running_id).llm_cost_yuan is None
|
||||
finally:
|
||||
_delete(missing_id)
|
||||
_delete(cancelled_id)
|
||||
_delete(running_id)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""scripts/ensure_pg.py 纯函数单测(不需要 Docker/PG)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
|
||||
from scripts.ensure_pg import (
|
||||
_docker_desktop_cmd,
|
||||
_docker_desktop_from_registry,
|
||||
_is_sqlite,
|
||||
_parse_host_port,
|
||||
_port_open,
|
||||
_win_docker_desktop_candidates,
|
||||
ensure,
|
||||
)
|
||||
|
||||
|
||||
def test_is_sqlite():
|
||||
assert _is_sqlite("sqlite:///./data/app.db")
|
||||
assert _is_sqlite(" SQLite:///x ")
|
||||
assert not _is_sqlite("postgresql+psycopg://u:p@localhost:5432/db")
|
||||
|
||||
|
||||
def test_parse_host_port_full():
|
||||
assert _parse_host_port(
|
||||
"postgresql+psycopg://u:p@localhost:5432/shaguabijia"
|
||||
) == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_parse_host_port_defaults():
|
||||
# 缺端口 → 5432
|
||||
assert _parse_host_port("postgresql+psycopg://u:p@db.example/x")[1] == 5432
|
||||
# 缺 host → localhost
|
||||
assert _parse_host_port("postgresql+psycopg:///x") == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_parse_host_port_testdb():
|
||||
assert _parse_host_port(
|
||||
"postgresql+psycopg://u:p@localhost:5432/shaguabijia_test"
|
||||
) == ("localhost", 5432)
|
||||
|
||||
|
||||
def test_port_open_true():
|
||||
srv = socket.socket()
|
||||
srv.bind(("127.0.0.1", 0))
|
||||
srv.listen(1)
|
||||
port = srv.getsockname()[1]
|
||||
try:
|
||||
assert _port_open("127.0.0.1", port, timeout=1.0)
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
|
||||
def test_port_open_false():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close() # 释放端口,无人监听 → 连接应失败
|
||||
assert not _port_open("127.0.0.1", port, timeout=0.3)
|
||||
|
||||
|
||||
def test_win_candidates_override_wins():
|
||||
env = {
|
||||
"DOCKER_DESKTOP_EXE": r"X:\custom\Docker Desktop.exe",
|
||||
"ProgramFiles": r"C:\Program Files",
|
||||
}
|
||||
cands = [str(p) for p in _win_docker_desktop_candidates(env, None)]
|
||||
assert cands[0] == r"X:\custom\Docker Desktop.exe"
|
||||
|
||||
|
||||
def test_win_candidates_follow_cli_drive():
|
||||
# 核心:docker CLI 在 D 盘 → 反推出 D 盘的 Docker Desktop.exe(不再写死 C 盘)
|
||||
env = {"ProgramFiles": r"C:\Program Files"}
|
||||
cli = r"D:\Docker\Docker\resources\bin\docker.exe"
|
||||
cands = [str(p) for p in _win_docker_desktop_candidates(env, cli)]
|
||||
assert r"D:\Docker\Docker\Docker Desktop.exe" in cands
|
||||
# 兜底的 C 盘常见路径也仍在
|
||||
assert r"C:\Program Files\Docker\Docker\Docker Desktop.exe" in cands
|
||||
|
||||
|
||||
def test_win_candidates_no_cli_uses_program_files():
|
||||
env = {"ProgramFiles": r"C:\Program Files"}
|
||||
cands = [str(p) for p in _win_docker_desktop_candidates(env, None)]
|
||||
assert cands == [r"C:\Program Files\Docker\Docker\Docker Desktop.exe"]
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_windows_found(monkeypatch, tmp_path):
|
||||
exe = tmp_path / "Docker Desktop.exe"
|
||||
exe.write_text("") # 真实存在
|
||||
monkeypatch.setattr("scripts.ensure_pg._find_docker_desktop_exe", lambda: exe)
|
||||
assert _docker_desktop_cmd("win32") == [str(exe)]
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_windows_not_found(monkeypatch):
|
||||
monkeypatch.setattr("scripts.ensure_pg._find_docker_desktop_exe", lambda: None)
|
||||
assert _docker_desktop_cmd("win32") is None
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_darwin():
|
||||
assert _docker_desktop_cmd("darwin") == ["open", "-a", "Docker"]
|
||||
|
||||
|
||||
def test_docker_desktop_cmd_linux():
|
||||
assert _docker_desktop_cmd("linux") is None
|
||||
|
||||
|
||||
def test_registry_probe_never_raises():
|
||||
# best-effort:无论平台/有无键,只返回 Path 或 None,绝不抛
|
||||
r = _docker_desktop_from_registry()
|
||||
assert r is None or hasattr(r, "exists")
|
||||
|
||||
|
||||
def test_ensure_sqlite_escape_hatch(monkeypatch):
|
||||
# sqlite 是【显式降级逃生舱】:打印横幅、返回 True,且绝不触碰 docker
|
||||
def _boom():
|
||||
raise AssertionError("sqlite 分支不应调用 docker")
|
||||
|
||||
monkeypatch.setattr("scripts.ensure_pg._docker_cli_ok", _boom)
|
||||
assert ensure("sqlite:///./data/app.db") is True
|
||||
|
||||
|
||||
def test_ensure_shortcircuits_when_pg_up(monkeypatch):
|
||||
# 端口通 → 直接 True,绝不触碰 docker
|
||||
monkeypatch.setattr("scripts.ensure_pg._port_open", lambda *a, **k: True)
|
||||
|
||||
def _boom():
|
||||
raise AssertionError("端口通时不应调用 docker")
|
||||
|
||||
monkeypatch.setattr("scripts.ensure_pg._docker_cli_ok", _boom)
|
||||
assert ensure("postgresql+psycopg://u:p@localhost:5432/shaguabijia") is True
|
||||
@@ -1,122 +0,0 @@
|
||||
"""失败卡展示原因派生(repositories.comparison._derive_fail_display)单元测试。
|
||||
|
||||
用例取自线上真实 failed 记录(platform_results 形态),覆盖:
|
||||
- information 具体 → 直出
|
||||
- information 笼统 + platform_results 有干净业务结局 → 救援出该原因(id 3030/2964 型)
|
||||
- information 笼统 + 仅系统失败(搜索失败等黑话)→ None(端侧品牌兜底,id 3027 型)
|
||||
- store_closed / no_delivery 被 pricebot 漏成 status=failed → 按 reason 关键字补判
|
||||
- 打烊类脏店名 blob → 统一简短模板
|
||||
- platform_results 为空 / 非对象 → None
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.repositories import comparison as crud
|
||||
|
||||
|
||||
def test_specific_information_passthrough() -> None:
|
||||
# information 本身具体(未达起送/找不到菜等)→ 直出,不看 platform_results
|
||||
assert (
|
||||
crud._derive_fail_display("淘宝闪购未达起送门槛,可加菜凑单后下单", {})
|
||||
== "淘宝闪购未达起送门槛,可加菜凑单后下单"
|
||||
)
|
||||
assert crud._derive_fail_display("未识别到商品", {}) == "未识别到商品"
|
||||
|
||||
|
||||
def test_generic_info_rescued_from_items_not_found() -> None:
|
||||
# id 3030 型:美团系统失败 + 京东 items_not_found,记录级 information 笼统 → 救出京东那条
|
||||
pr = {
|
||||
"eleme": {"is_source": True, "status": "source", "price": 23.04},
|
||||
"meituan_waimai": {
|
||||
"is_source": False, "status": "failed",
|
||||
"reason": "搜索店铺失败, 无法跳转到搜索页",
|
||||
},
|
||||
"jd_waimai_standalone": {
|
||||
"is_source": False, "status": "items_not_found",
|
||||
"reason": "京东外卖此店内未找到这些菜品",
|
||||
},
|
||||
}
|
||||
assert (
|
||||
crud._derive_fail_display("比价过程出错,请稍后重试", pr)
|
||||
== "京东外卖此店内未找到这些菜品"
|
||||
)
|
||||
|
||||
|
||||
def test_generic_info_rescued_from_store_not_found() -> None:
|
||||
# id 2964 型:美团系统失败 + 京东 store_not_found → 救出京东相似店铺文案
|
||||
pr = {
|
||||
"taobao_flash": {"is_source": True, "status": "source", "price": 127.98},
|
||||
"meituan": {
|
||||
"is_source": False, "status": "failed",
|
||||
"reason": "比价过程出错,请稍后重试",
|
||||
},
|
||||
"jd_waimai": {
|
||||
"is_source": False, "status": "store_not_found",
|
||||
"reason": "未在京东找到「黔珍味·贵州牛肉蘸水健康菜 (望京店)」相似店铺",
|
||||
},
|
||||
}
|
||||
assert (
|
||||
crud._derive_fail_display("比价过程出错,请稍后重试", pr)
|
||||
== "未在京东找到「黔珍味·贵州牛肉蘸水健康菜 (望京店)」相似店铺"
|
||||
)
|
||||
|
||||
|
||||
def test_generic_info_pure_system_failure_returns_none() -> None:
|
||||
# id 3027 型:唯一目标平台是自动化黑话失败 → 不给用户看 → None(端侧品牌兜底)
|
||||
pr = {
|
||||
"eleme": {"is_source": True, "status": "source", "price": 18.83},
|
||||
"meituan_waimai": {
|
||||
"is_source": False, "status": "failed",
|
||||
"reason": "搜索店铺失败, 无法跳转到搜索页",
|
||||
},
|
||||
}
|
||||
assert crud._derive_fail_display("比价过程出错,请稍后重试", pr) is None
|
||||
|
||||
|
||||
def test_store_closed_leaked_to_failed_is_rescued_and_cleaned() -> None:
|
||||
# 打烊被漏成 status=failed;reason 常带脏店名 blob → 统一简短模板
|
||||
pr = {
|
||||
"jd_waimai": {"is_source": True, "status": "source", "price": 25},
|
||||
"taobao_flash": {
|
||||
"is_source": False, "status": "failed",
|
||||
"reason": "淘宝闪购「沙胆彪炭炉牛杂煲(...),蜂鸟准时达,月售300+,起送¥20」本店已休息,无法比价",
|
||||
},
|
||||
}
|
||||
assert crud._derive_fail_display("比价过程出错,请稍后重试", pr) == "门店休息中,无法比价"
|
||||
|
||||
pr2 = {
|
||||
"taobao_flash": {"is_source": True, "status": "source", "price": 31.83},
|
||||
"meituan": {
|
||||
"is_source": False, "status": "failed",
|
||||
"reason": "美团「奈雪的茶(北京王府井奥莱·香江」门店已打烊,无法比价",
|
||||
},
|
||||
}
|
||||
assert crud._derive_fail_display("比价出错", pr2) == "门店已打烊,无法比价"
|
||||
|
||||
|
||||
def test_no_delivery_leaked_to_failed_is_rescued() -> None:
|
||||
# 单点不配送被漏成 status=failed;reason 本身干净 → 直接用
|
||||
reason = "京东外卖该商家所选商品单点不配送,无法进入结算比价"
|
||||
pr = {
|
||||
"taobao_flash": {"is_source": True, "status": "source", "price": 20.1},
|
||||
"jd_waimai_standalone": {
|
||||
"is_source": False, "status": "failed", "reason": reason,
|
||||
},
|
||||
}
|
||||
assert crud._derive_fail_display("比价过程出错,请稍后重试", pr) == reason
|
||||
|
||||
|
||||
def test_empty_or_missing_platform_results_returns_none() -> None:
|
||||
# 「比价出错」+ 空 {} / None / 非对象:引擎早夭,无可展示原因 → None
|
||||
assert crud._derive_fail_display("比价出错", {}) is None
|
||||
assert crud._derive_fail_display("比价过程出错,请稍后重试", None) is None
|
||||
assert crud._derive_fail_display("比价出错", []) is None # 老 array 形态,防御
|
||||
|
||||
|
||||
def test_clean_status_wins_over_priority_order() -> None:
|
||||
# 多个业务结局同现时按 _BIZ_STATUS_PRIORITY 选(below_minimum 优先于 store_not_found)
|
||||
pr = {
|
||||
"src": {"is_source": True, "status": "source", "price": 30},
|
||||
"a": {"is_source": False, "status": "store_not_found", "reason": "未找到店铺A"},
|
||||
"b": {"is_source": False, "status": "below_minimum", "reason": "B未达起送门槛"},
|
||||
}
|
||||
assert crud._derive_fail_display("比价过程出错,请稍后重试", pr) == "B未达起送门槛"
|
||||
@@ -201,7 +201,7 @@ def test_start_loses_seq_race_degrades_to_ad(client, guide_configured, monkeypat
|
||||
assert first["should_play"] is True and first["seq"] == 1
|
||||
|
||||
# 本次请求读到的是过期计数 → 仍会算出 seq=1
|
||||
monkeypatch.setattr(crud_guide, "used_plays", lambda db, user_id, scene="coupon": 0)
|
||||
monkeypatch.setattr(crud_guide, "used_plays", lambda db, user_id: 0)
|
||||
with SessionLocal() as db:
|
||||
result = crud_guide.start_play(db, uid)
|
||||
|
||||
|
||||
@@ -7,9 +7,7 @@ mock/真发/变量覆盖/站内联动/设备反查/参数校验。厂商 HTTP
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -112,99 +110,6 @@ def test_huawei_non_success_code_raises(monkeypatch) -> None:
|
||||
vendor_push.send_notification("huawei", "bad-token", title="t", body="b")
|
||||
|
||||
|
||||
def test_vendor_http_logs_device_token_raw_response_and_elapsed(monkeypatch, caplog) -> None:
|
||||
vendor_push._token_cache.clear()
|
||||
|
||||
def _fake_request(method, url, **kwargs): # noqa: ANN001
|
||||
if url == vendor_push.settings.HUAWEI_PUSH_TOKEN_ENDPOINT:
|
||||
return _Resp({"access_token": "raw-access-token", "expires_in": 3600})
|
||||
return _Resp({"code": "80000000", "msg": "Success", "requestId": "vendor-request-1"})
|
||||
|
||||
monkeypatch.setattr(vendor_push.settings, "HUAWEI_PUSH_APP_ID", "10086001")
|
||||
monkeypatch.setattr(vendor_push.settings, "HUAWEI_PUSH_APP_SECRET", "raw-app-secret")
|
||||
monkeypatch.setattr(vendor_push.httpx, "request", _fake_request)
|
||||
|
||||
with caplog.at_level(logging.INFO, logger=vendor_push.logger.name):
|
||||
vendor_push.send_notification(
|
||||
"huawei",
|
||||
"raw-device-token",
|
||||
title="需要进入日志的标题",
|
||||
body="需要进入日志的正文",
|
||||
extras={"type": "withdraw_success", "notificationId": "90001"},
|
||||
)
|
||||
|
||||
messages = "\n".join(record.getMessage() for record in caplog.records)
|
||||
assert "operation=authenticate" in messages
|
||||
assert "operation=send_notification" in messages
|
||||
assert "request=" in messages
|
||||
assert "response=" in messages
|
||||
assert "elapsed_ms=" in messages
|
||||
assert "vendor-request-1" in messages
|
||||
assert "withdraw_success" in messages
|
||||
assert "raw-access-token" in messages
|
||||
assert "raw-device-token" in messages
|
||||
assert "需要进入日志的标题" in messages
|
||||
assert "需要进入日志的正文" in messages
|
||||
assert "<redacted" in messages
|
||||
assert "raw-app-secret" not in messages
|
||||
send_http_log = next(
|
||||
record.getMessage()
|
||||
for record in caplog.records
|
||||
if "operation=send_notification" in record.getMessage()
|
||||
and "vendor push http completed" in record.getMessage()
|
||||
)
|
||||
assert "raw-device-token" in send_http_log
|
||||
assert "raw-access-token" not in send_http_log # 请求头中的厂商鉴权 token 仍脱敏
|
||||
|
||||
|
||||
def test_vendor_http_network_error_logs_request_context(monkeypatch, caplog) -> None:
|
||||
def _fake_request(*args, **kwargs): # noqa: ANN002, ANN003
|
||||
raise httpx.ConnectError("connection refused")
|
||||
|
||||
monkeypatch.setattr(vendor_push.settings, "XIAOMI_PUSH_APP_SECRET", "raw-xiaomi-secret")
|
||||
monkeypatch.setattr(vendor_push.httpx, "request", _fake_request)
|
||||
|
||||
with (
|
||||
caplog.at_level(logging.ERROR, logger=vendor_push.logger.name),
|
||||
pytest.raises(vendor_push.VendorPushError, match="push http error"),
|
||||
):
|
||||
vendor_push.send_notification(
|
||||
"xiaomi",
|
||||
"raw-xiaomi-token",
|
||||
title="title",
|
||||
body="body",
|
||||
extras={"type": "push_test"},
|
||||
)
|
||||
|
||||
messages = "\n".join(record.getMessage() for record in caplog.records)
|
||||
assert "outcome=network_error" in messages
|
||||
assert "response=<no_response>" in messages
|
||||
assert "operation=send_notification" in messages
|
||||
assert "elapsed_ms=" in messages
|
||||
assert "raw-xiaomi-secret" not in messages
|
||||
assert "raw-xiaomi-token" in messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("request_kwargs", "device_token"),
|
||||
[
|
||||
({"json": {"token": ["honor-device-token"]}}, "honor-device-token"),
|
||||
({"json": {"message": {"token": ["huawei-device-token"]}}}, "huawei-device-token"),
|
||||
({"json": {"regId": "vivo-device-token"}}, "vivo-device-token"),
|
||||
({"data": {"registration_id": "xiaomi-device-token"}}, "xiaomi-device-token"),
|
||||
(
|
||||
{"data": {"message": '{"target_value":"oppo-device-token"}'}},
|
||||
"oppo-device-token",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_all_vendor_device_token_fields_remain_visible_in_request_summary(
|
||||
request_kwargs, device_token
|
||||
) -> None:
|
||||
summary = vendor_push._request_summary(request_kwargs)
|
||||
assert device_token in summary
|
||||
|
||||
|
||||
def test_vendor_aliases_normalize() -> None:
|
||||
assert vendor_push.normalize_vendor("华为") == "huawei"
|
||||
assert vendor_push.normalize_vendor("HMS") == "huawei"
|
||||
|
||||
Reference in New Issue
Block a user