Compare commits

...

6 Commits

Author SHA1 Message Date
guke 07bed2f114 Merge branch 'main' of https://gitea.shaguabijia.com/WonderableAI/shaguabijia-app-server into feat/aliyun-oneclick-login 2026-07-28 18:27:31 +08:00
linkeyu 90c6fe599a 修复:统一用户Draw信息流eCPM统计口径 (#190)
## 问题

业务收益详情的平均 Draw eCPM 仅平均成功发奖记录,会排除未发奖的真实展示,导致数值系统性偏高,且与广告收益页口径不一致。

## 修复

- `feed_avg_ecpm` 改为从 `ad_ecpm_record` 的全部 `draw/feed` 实际展示计算
- 成功发奖、未发奖展示均纳入,每次展示等权
- 日期、正式/测试环境、业务代码位、领券/比价场景支持与广告收益页对齐
- 奖励份数仍基于成功发奖表,不混用展示数据源
- 复用广告收益报表的业务代码位集合

## 线上数据复算

2026-07-25、正式业务、用户 #33:

- 旧口径(只看成功发奖):`29.9117 元/千次`
- 新口径(333 次真实展示):`19.9926 元/千次`
- 新值与广告收益报表一致

## 验证

- 新增成功/未发奖、场景、环境、业务代码位回归用例
- `tests/test_admin_read.py` + `tests/test_admin_ad_revenue_scope.py`:29 项全通过
- Ruff 改动文件检查通过

## 上线顺序

本 PR 需先于管理后台配套 PR 上线。

---------

Co-authored-by: guke <guke@wonderable.ai>
Co-authored-by: unknown <798648091@qq.com>
Reviewed-on: #190
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-28 17:58:23 +08:00
linkeyu e529112a90 修复中途退出比价的 LLM 成本回填 (#191)
## 问题

比价记录进入中途退出后未触发 LLM 成本回填,周期补偿也未扫描 cancelled,导致实际已有 LLM 调用的记录长期显示成本、LLM、TOKEN 为空。

## 修改

- finalize 落库后立即追加 LLM 成本回填
- 周期补偿范围加入 cancelled
- 保持无有效调用和全调用失败记录不伪造成本
- 增加即时回填和周期补偿回归测试

## 验证

- ruff 检查通过
- 相关测试 28 项通过
- 全仓 626 项通过;主干既有失败已在未修改的 origin/main 复现

---------

Co-authored-by: unknown <798648091@qq.com>
Reviewed-on: #191
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-28 17:57:52 +08:00
guke b02cf0f73a docs(auth): 后端一键登录实施计划补执行状态说明
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 17:13:58 +08:00
guke f161d07615 feat(auth): 后端接入阿里云一键登录 provider(门面+GetMobile换号+契约+配置)
新增 aliyun_onekey(Dypnsapi GetMobile 换号,无 RSA)+ oneclick 门面(按 provider 分派 jiguang/aliyun);jverify-login 与微信绑号两处换号改走门面 + JverifyLoginRequest 加 provider 字段 + ALIYUN_ONEKEY 配置。新增 15 单测(aliyun_onekey/oneclick/端点),微信绑号回归修 2 处桩。真机端到端验证通过。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 17:13:57 +08:00
guke 84a20d353e docs(auth): 阿里云一键登录后端实施计划(M1)
aliyun_onekey(Dypnsapi GetMobile 换号) + oneclick 门面注册 aliyun + jverify-login/微信绑号接入门面 + provider 契约字段 + ALIYUN_ONEKEY 配置 + 测试

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 11:23:56 +08:00
20 changed files with 1027 additions and 42 deletions
+5
View File
@@ -64,6 +64,11 @@ CHUANGLAN_SMS_TEMPLATE_ID=1022457679
CHUANGLAN_SMS_SIGNATURE=
CHUANGLAN_SMS_ENDPOINT=https://smssh.253.com/msg/sms/v2/tpl/send
CHUANGLAN_SMS_TIMEOUT_SEC=10
# --- 阿里云号码认证·一键登录(Dypnsapi GetMobile 换号)。同账号可填与 ALIYUN_SMS_ACCESS_KEY_* 相同的值 ---
ALIYUN_ONEKEY_ACCESS_KEY_ID=
ALIYUN_ONEKEY_ACCESS_KEY_SECRET=
ALIYUN_ONEKEY_ENDPOINT=dypnsapi.aliyuncs.com
ALIYUN_ONEKEY_TIMEOUT_SEC=15
# ===== 测试账号(release 包全流程联调用)=====
# 配一个固定测试手机号,专供无 SIM 卡 / 不走一键登录时打通全流程:该号登录【免短信验证码】
+5 -5
View File
@@ -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_code_ids: set[str] | None = None
business_ids: set[str] | None = None
if revenue_scope == "business":
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]
business_ids = business_code_ids(db, app_env)
events = [e for e in events if e.get("our_code_id") in business_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_code_ids,
our_code_ids=business_ids,
)
if pangle_aggs:
by_date = {a["date"]: a for a in pangle_aggs}
+57 -14
View File
@@ -14,6 +14,7 @@ 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
@@ -1257,11 +1258,15 @@ 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 累加);
平均 eCPM 用原始分值(分/千次)按记录取算术平均;各「提现」= 该来源累计金币折现。
口径:激励视频/信息流奖励数量只统计 granted;数量——视频按条数、信息流按份数(unit_count 累加)
平均 Draw eCPM 与广告收益报表一致:基于 ad_ecpm_record 的全部 draw/feed 展示记录计算,
不以是否发奖为筛选条件。各「提现」= 该来源累计金币折现。
传统任务 = 窗口内正向金币中,排除广告(reward_video/feed_ad_reward)与人工调整后的折现。
"""
withdraw_source_conds = (
@@ -1296,30 +1301,68 @@ 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(
AdRewardRecord.user_id == user_id,
AdRewardRecord.reward_scene == "reward_video",
AdRewardRecord.status == "granted",
*_window_conds(AdRewardRecord.created_at, date_from, date_to),
*rv_conds,
)
).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 = db.execute(
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(
select(
AdFeedRewardRecord.unit_count,
AdFeedRewardRecord.ecpm_raw,
AdFeedRewardRecord.coin,
).where(
AdFeedRewardRecord.user_id == user_id,
AdFeedRewardRecord.status == "granted",
*_window_conds(AdFeedRewardRecord.created_at, date_from, date_to),
*feed_reward_conds,
)
).all()
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)
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]
trad_coins = db.execute(
select(func.coalesce(func.sum(CoinTransaction.amount), 0)).where(
@@ -1338,7 +1381,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)),
"feed_count": int(sum(f.unit_count for f in feed_rewards)),
"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),
}
+8
View File
@@ -88,6 +88,11 @@ 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):
@@ -99,6 +104,9 @@ 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 -1
View File
@@ -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 # 平均信息流广告 eCPM(分/千次)
feed_avg_ecpm: float # 全部 Draw/feed 实际展示的平均 eCPM(分/千次,含未发奖展示)
feed_cash_cents: int # 信息流广告提现(金币折现)
+13 -12
View File
@@ -33,7 +33,7 @@ from app.core.security import (
issue_token_pair,
)
from app.integrations import wxpay
from app.integrations.jiguang import JiguangError, mask_phone, verify_and_get_phone
from app.integrations.oneclick import OneClickError, mask_phone, verify_and_get_phone
from app.integrations.sms import SmsError, send_code, verify_code
from app.repositories import onboarding as onboarding_repo
from app.repositories import phone_rebind as rebind_repo
@@ -110,14 +110,15 @@ def jverify_login(req: JverifyLoginRequest, request: Request, db: DbSession) ->
):
raise HTTPException(status_code=403, detail="当前设备环境异常,暂无法登录")
logger.info(
"jverify_login operator=%s token_len=%d",
"jverify_login provider=%s operator=%s token_len=%d",
req.provider or "-",
req.operator or "-",
len(req.login_token),
)
try:
phone = verify_and_get_phone(req.login_token)
except JiguangError as e:
phone = verify_and_get_phone(req.provider, req.login_token)
except OneClickError as e:
risk_repo.record_behavior_event(
db,
event_type=risk_repo.EVENT_ONECLICK_LOGIN,
@@ -128,11 +129,11 @@ def jverify_login(req: JverifyLoginRequest, request: Request, db: DbSession) ->
client_ip=_client_ip(request),
outcome="failed",
reason=str(e),
details={"operator": req.operator or None},
details={"operator": req.operator or None, "provider": req.provider or None},
evaluate_rule=risk_repo.RULE_ONECLICK_DAILY,
)
logger.error("[JG] verify+decrypt failed: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail=f"jiguang verify failed: {e}") from e
logger.error("[oneclick] verify+decrypt failed: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail=f"oneclick verify failed: {e}") from e
user = user_repo.upsert_user_for_login(db, phone=phone, register_channel="jverify")
risk_repo.record_behavior_event(
@@ -146,7 +147,7 @@ def jverify_login(req: JverifyLoginRequest, request: Request, db: DbSession) ->
phone=phone,
client_ip=_client_ip(request),
outcome="success",
details={"operator": req.operator or None},
details={"operator": req.operator or None, "provider": req.provider or None},
evaluate_rule=risk_repo.RULE_ONECLICK_DAILY,
)
if user.status != "active":
@@ -492,10 +493,10 @@ def wechat_bind_phone_jverify(
raise HTTPException(status_code=401, detail="授权已过期,请重新用微信登录") from e
try:
phone = verify_and_get_phone(req.login_token)
except JiguangError as e:
logger.error("[JG] verify+decrypt failed: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail=f"jiguang verify failed: {e}") from e
phone = verify_and_get_phone("jiguang", req.login_token)
except OneClickError as e:
logger.error("[oneclick] verify+decrypt failed: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail=f"oneclick verify failed: {e}") from e
return _finish_wechat_bind(
db,
+11 -3
View File
@@ -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,
) -> None:
) -> int | 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,6 +118,7 @@ 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(
@@ -291,7 +292,10 @@ async def trace_epilogue(
@router.post("/trace/finalize", summary="比价 trace 收尾上云 (透传 + 夭折落库)")
async def trace_finalize(
request: Request, user: OptionalUser, db: DbSession
request: Request,
background_tasks: BackgroundTasks,
user: OptionalUser,
db: DbSession,
) -> dict[str, Any]:
_ensure_compare_allowed(user, db)
# 用户终止 / Phase1 未识别没到 done 帧: pricebot 打包半截上云返回 {trace_url};
@@ -302,12 +306,16 @@ async def trace_finalize(
request, "/api/trace/finalize", user, harvest_first_frame=False,
)
try:
await run_in_threadpool(
record_id = 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
+15
View File
@@ -165,6 +165,14 @@ class Settings(BaseSettings):
CHUANGLAN_SMS_ENDPOINT: str = "https://smssh.253.com/msg/sms/v2/tpl/send"
CHUANGLAN_SMS_TIMEOUT_SEC: int = 10 # httpx 读/连超时秒
# ===== 阿里云号码认证·一键登录(Dypnsapi GetMobile 换号)=====
# 与短信同属 dypnsapi 产品:同一阿里云账号可复用 ALIYUN_SMS_ACCESS_KEY_*,默认独立字段解耦。
# 缺凭证 → provider=aliyun 换号抛错→502,不启动崩(见 aliyun_oneclick_configured)。
ALIYUN_ONEKEY_ACCESS_KEY_ID: str = ""
ALIYUN_ONEKEY_ACCESS_KEY_SECRET: str = ""
ALIYUN_ONEKEY_ENDPOINT: str = "dypnsapi.aliyuncs.com"
ALIYUN_ONEKEY_TIMEOUT_SEC: int = 15 # 阿里云 API 读/连超时秒
@property
def aliyun_sms_configured(self) -> bool:
"""阿里云短信凭证齐全(缺则 SMS_PROVIDER=aliyun 时 /sms/* 返 503,而非启动崩)。"""
@@ -175,6 +183,13 @@ class Settings(BaseSettings):
and self.ALIYUN_SMS_TEMPLATE_CODE
)
@property
def aliyun_oneclick_configured(self) -> bool:
"""阿里云一键登录凭证齐全(缺则 provider=aliyun 换号抛错→502,而非启动崩)。"""
return bool(
self.ALIYUN_ONEKEY_ACCESS_KEY_ID and self.ALIYUN_ONEKEY_ACCESS_KEY_SECRET
)
@property
def chuanglan_sms_configured(self) -> bool:
"""创蓝短信凭证齐全(缺则 SMS_PROVIDER=chuanglan 时 /sms/send 返 503,而非启动崩)。"""
+89
View File
@@ -0,0 +1,89 @@
"""阿里云号码认证·一键登录服务端换号(Dypnsapi GetMobile)。
链路:
Android 阿里云 SDK getLoginToken → spToken(access_token)
→ 本服务调 Dypnsapi GetMobile(AccessToken=spToken)
→ 阿里云直接返回明文手机号(无需 RSA/AES,比极光/创蓝少一步解密)
与 jiguang 对齐:对外暴露 verify_and_get_phone(login_token)->str,失败抛 AliyunOneClickError,
由 oneclick.py 门面统一 catch。
SDK 交互隔离在 _call_get_mobile 薄封装(惰性 import + 惰性建 client,仿 sms/aliyun.py),
单测 monkeypatch 它即可,不触真 SDK/网络。凭证复用/独立见 config.ALIYUN_ONEKEY_*。
"""
from __future__ import annotations
import logging
from app.core.config import settings
logger = logging.getLogger("shagua.aliyun.onekey")
_client = None # 惰性构建的 dypnsapi client(模块级缓存)
class AliyunOneClickError(Exception):
"""阿里云取号失败的统一异常,由 oneclick 门面 catch 翻成 4xx/5xx。"""
def verify_and_get_phone(login_token: str) -> str:
"""对外唯一函数:loginToken(access_token) → 明文手机号。失败抛 AliyunOneClickError。"""
if not settings.aliyun_oneclick_configured:
raise AliyunOneClickError("ALIYUN_ONEKEY_ACCESS_KEY_ID/SECRET not configured")
result = _call_get_mobile(login_token)
if not (result["success"] and result["code"] == "OK"):
logger.error(
"[ALIYUN-ONEKEY] get_mobile failed code=%s msg=%s",
result["code"], result["message"],
)
raise AliyunOneClickError(f"aliyun get_mobile failed code={result['code']}")
phone = (result["mobile"] or "").strip()
if not (phone.isdigit() and len(phone) == 11):
logger.error("[ALIYUN-ONEKEY] unexpected mobile format: %r", phone)
raise AliyunOneClickError("aliyun get_mobile returned non-phone")
return phone
# ==================== SDK 接缝(单测 monkeypatch 这个)====================
def _get_client():
"""惰性构建 dypnsapi client(仿 sms/aliyun.py:jiguang-only 部署不加载 alibabacloud)。"""
global _client
if _client is None:
from alibabacloud_dypnsapi20170525.client import Client
from alibabacloud_tea_openapi import models as open_api_models
cfg = open_api_models.Config(
access_key_id=settings.ALIYUN_ONEKEY_ACCESS_KEY_ID,
access_key_secret=settings.ALIYUN_ONEKEY_ACCESS_KEY_SECRET,
read_timeout=settings.ALIYUN_ONEKEY_TIMEOUT_SEC * 1000, # SDK 单位 ms
connect_timeout=settings.ALIYUN_ONEKEY_TIMEOUT_SEC * 1000,
)
cfg.endpoint = settings.ALIYUN_ONEKEY_ENDPOINT
_client = Client(cfg)
return _client
def _call_get_mobile(login_token: str) -> dict:
"""调 GetMobile。返回归一化 {success, code, message, mobile};import/建 client/调用任一失败抛 AliyunOneClickError。
⚠️ GetMobile 响应体字段名以实际 SDK 为准(code=="OK"、get_mobile_result_dto.mobile)。接真号联调时
若字段不同,只需改本函数末尾归一化,verify_and_get_phone 及单测不动。
"""
try:
from alibabacloud_dypnsapi20170525 import models as dypns_models
req = dypns_models.GetMobileRequest(access_token=login_token)
body = _get_client().get_mobile(req).body
except Exception as e:
logger.exception("[ALIYUN-ONEKEY] get_mobile 调用异常")
raise AliyunOneClickError("aliyun get_mobile 调用异常") from e
dto = getattr(body, "get_mobile_result_dto", None)
mobile = getattr(dto, "mobile", None) if dto else None
return {
"success": (body.code == "OK"),
"code": body.code,
"message": body.message,
"mobile": mobile,
}
+41
View File
@@ -0,0 +1,41 @@
"""一键登录换号门面:按 provider 分派到极光/阿里云, 统一异常与手机号脱敏。
为什么要门面:一键登录 token 与「拉授权页的那家 SDK」强绑定 —— 客户端用极光 SDK 拉的
token 只能用极光换号, 阿里云的只能用阿里云换号。所以 provider 必须由客户端如实上报, 服务端
按此分派、不能猜。老客户端不带 provider → 默认极光(向后兼容)。
用法(api 层):
from app.integrations import oneclick
try:
phone = oneclick.verify_and_get_phone(req.provider, req.login_token)
except oneclick.OneClickError as e:
raise HTTPException(502, ...) from e
"""
from __future__ import annotations
# 用「模块属性访问」而非 from ... import 函数:保证 monkeypatch 各家实现时门面能拿到替身。
from app.integrations import aliyun_onekey, jiguang
from app.integrations.jiguang import mask_phone # 复用脱敏, 从门面转出供 api 层用
__all__ = ["OneClickError", "mask_phone", "verify_and_get_phone"]
PROVIDER_JIGUANG = "jiguang"
PROVIDER_ALIYUN = "aliyun"
class OneClickError(Exception):
"""换号失败统一异常(不区分厂商), api 层 catch → 502。"""
def verify_and_get_phone(provider: str, login_token: str) -> str:
"""按 provider 换取明文手机号。失败(任一厂商)抛 OneClickError。
provider 大小写不敏感;空 / 未知值兜底走极光(主家), 不因客户端传错值而拒登。
"""
p = (provider or PROVIDER_JIGUANG).strip().lower()
try:
if p == PROVIDER_ALIYUN:
return aliyun_onekey.verify_and_get_phone(login_token)
return jiguang.verify_and_get_phone(login_token)
except (jiguang.JiguangError, aliyun_onekey.AliyunOneClickError) as e:
raise OneClickError(f"[{p}] {e}") from e
+5
View File
@@ -67,6 +67,11 @@ class JverifyLoginRequest(BaseModel):
device_model: str = Field(
"", max_length=128, description="客户端设备型号快照,用于登录安全审计"
)
provider: str = Field(
"jiguang",
description="一键登录厂商:jiguang(默认)/aliyun。决定后端用哪家换号,"
"必须与客户端拉授权页的 SDK 一致。老客户端不带→默认极光(向后兼容)。",
)
# ===== 短信验证码 =====
+1 -1
View File
@@ -135,7 +135,7 @@ def repair_missing_comparison_llm_costs(
select(ComparisonRecord.id, ComparisonRecord.trace_id)
.where(
*date_conditions,
ComparisonRecord.status.in_(("success", "failed")),
ComparisonRecord.status.in_(("success", "failed", "cancelled")),
ComparisonRecord.llm_cost_yuan.is_(None),
)
.order_by(ComparisonRecord.created_at.desc(), ComparisonRecord.id.desc())
@@ -0,0 +1,479 @@
# 阿里云一键登录 · 后端实施计划 (M1)
> **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:**`POST /api/v1/auth/jverify-login` 支持 `provider=aliyun`,用客户端 loginToken 调阿里云 Dypnsapi `GetMobile` 换明文手机号完成登录;极光/创蓝不受影响。
**Architecture:** 复用已存在的 `app/integrations/oneclick.py` 门面(按 provider 分派)。新增 `aliyun_onekey.py` 换号 provider(结构仿 `chuanglan_onekey.py`SDK 调用仿 `sms/aliyun.py` 的惰性 client)。把端点从直连 `jiguang` 改走门面并读 `req.provider`(这一步会让已存在但未接线的 `tests/test_jverify_login_endpoint.py` 转绿)。
**Tech Stack:** FastAPI + Pydantic v2 + pytest + `alibabacloud_dypnsapi20170525`(短信侧已引)。
**参考规范:** `../specs/2026-07-28-aliyun-oneclick-login-design.md`(在 android 仓)。
**运行测试:** `.venv/Scripts/python -m pytest tests/test_oneclick.py tests/test_aliyun_onekey.py tests/test_jverify_login_endpoint.py -q`。(conftest 用临时文件 SQLite,端点测试**无需 PG**`SGB_TEST_SKIP_DB` 未被 conftest 使用。)
> **执行状态(2026-07-28):M1 已实施并验证通过(未提交,待授权)。**
> 实施中发现原计划前提有误:`oneclick.py` 门面 / `chuanglan_onekey.py` / `test_oneclick.py` / `test_jverify_login_endpoint.py` 均为**未提交的创蓝评估 WIP,已清除,git 全程无记录**——门面并不存在。遂按「建小 facadejiguang+aliyun,弃创蓝)」重做,顺序:配置 → aliyun_onekey → **新建** oneclick 门面 → 接线 auth.py 两处 + provider 字段 → **新建**端点测试。
> 验证:新增 15 单测全绿(aliyun_onekey 4 / oneclick 8 / 端点 3+ 微信绑号回归绿;全量 `pytest` 与改动前逐一对照——同样 8 个既有失败(compare/coupon/invite/withdraw_tiers/notification,均与本次无关:SQLite/顺序依赖),本次 **0 新增失败**617→632 passed)。
> 下方 B1–B5 为实现参考(代码与落地一致);「已存在的门面/测试转绿」等措辞按本节修正理解,实际是先建 aliyun_onekey/facade 再接线。
---
### Task B1: 端点接入 oneclick 门面 + 加 `provider` 字段
已存在的 `tests/test_jverify_login_endpoint.py` 已按「门面已接线」写(monkeypatch `auth.verify_and_get_phone` 为 2 参、POST 带 `provider`),但线上 `auth.py` 仍直连 jiguang。本任务把它接上,使这些测试转绿。
**Files:**
- Modify: `app/schemas/auth.py:60-69``JverifyLoginRequest``provider`
- Modify: `app/api/v1/auth.py:36`import 改门面)、`:112-157``jverify_login` 调用/异常/埋点)、`:495-498`(微信 `bind-phone/jverify` 端点同一 `verify_and_get_phone`/`JiguangError`,一并改)
- Test: `tests/test_jverify_login_endpoint.py`(已存在,勿改,作为验收);回归 `tests/test_wechat_login.py``tests/test_wechat_conflict.py`(都覆盖微信绑号极光换号路径)
> ⚠️ `auth.py` 有**两处**用 `verify_and_get_phone` + `JiguangError``jverify_login`(119) 和微信 `bind-phone/jverify`(495)。换 import 会同时影响两处,必须都改;否则微信绑号编译/运行报错。
- [ ] **Step 1: 跑现有端点测试确认基线**
Run: `pytest tests/test_jverify_login_endpoint.py -v`
Expected: 3 条用例 **FAIL**(当前端点用 1 参 `verify_and_get_phone(req.login_token)`,被 monkeypatch 成 2 参后 `TypeError`)或在无 PG 时 **SKIP**。任一情况都说明「尚未接线」。
- [ ] **Step 2: schema 加 `provider` 字段**
`app/schemas/auth.py``JverifyLoginRequest`(当前 60-69 行)末尾加一个字段:
```python
class JverifyLoginRequest(BaseModel):
login_token: str = Field(..., description="客户端 loginAuth 拿到的 loginToken", min_length=1)
operator: str = Field("", description="CM/CU/CT,用于日志,可选")
device_id: str = Field(
"", max_length=64,
description="硬件级设备标识(Android ANDROID_ID),用于新手引导按 设备+账号 去重;空=按未完成处理",
)
device_model: str = Field(
"", max_length=128, description="客户端设备型号快照,用于登录安全审计"
)
provider: str = Field(
"jiguang",
description="一键登录厂商:jiguang(默认)/aliyun/chuanglan。决定后端用哪家换号,"
"必须与客户端拉授权页的 SDK 一致。老客户端不带→默认极光(向后兼容)。",
)
```
- [ ] **Step 3: 端点改走门面**
`app/api/v1/auth.py` 第 36 行的 import 从 jiguang 换成门面:
```python
# 旧: from app.integrations.jiguang import JiguangError, mask_phone, verify_and_get_phone
from app.integrations.oneclick import OneClickError, mask_phone, verify_and_get_phone
```
`jverify_login`(当前 102-157 行)里的换号调用与异常分支改为:
```python
try:
phone = verify_and_get_phone(req.provider, req.login_token)
except OneClickError as e:
risk_repo.record_behavior_event(
db,
event_type=risk_repo.EVENT_ONECLICK_LOGIN,
subject_type="device",
subject_id=subject_id,
device_id=req.device_id or None,
device_model=req.device_model or None,
client_ip=_client_ip(request),
outcome="failed",
reason=str(e),
details={"operator": req.operator or None, "provider": req.provider or None},
evaluate_rule=risk_repo.RULE_ONECLICK_DAILY,
)
logger.error("[oneclick] verify+decrypt failed: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail=f"oneclick verify failed: {e}") from e
```
并把该函数里成功埋点的 `details={"operator": req.operator or None}`(约 149 行)同样补上 `"provider": req.provider or None`;日志行(约 112-116)改成打印 `req.provider`
换 import 后 `JiguangError` 不再被引用,从第 36 行 import 去掉(只留 `OneClickError, mask_phone, verify_and_get_phone`)。
- [ ] **Step 3b: 微信 `bind-phone/jverify` 端点同步改(否则编译/运行报错)**
`auth.py` 第 495-498 行的第二处换号(微信登录·本机号极光绑定)也走门面。该请求体 `WechatBindPhoneJverifyRequest` **无** `provider` 字段,M1 保持极光不变,显式传字面量 `"jiguang"`
```python
try:
phone = verify_and_get_phone("jiguang", req.login_token)
except OneClickError as e:
raise HTTPException(status_code=502, detail=f"oneclick verify failed: {e}") from e
```
> 说明:当客户端 `WECHAT_BIND` 皮肤改用阿里云后,此端点 + `WechatBindPhoneJverifyRequest` 也要加 `provider`(否则阿里云 token 被极光换号必失败)。这属**后续增强**,不在 M1;已在 spec 待办登记。
- [ ] **Step 4: 跑端点测试转绿**
Run: `pytest tests/test_jverify_login_endpoint.py -v`(有 PG
Expected: 3 条全 **PASS**(默认 provider 建号、provider 原样透传、OneClickError→502)。
- [ ] **Step 5: 跑门面 + 微信绑号测试不回归**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_oneclick.py -v`(门面本就 2 参,未动 → PASS)
Run(有 PG: `pytest tests/test_wechat_login.py tests/test_wechat_conflict.py -v`
Expected: 全 **PASS**(微信绑号极光换号路径改走门面后行为不变)。
- [ ] **Step 6: Commit**
```bash
git add app/schemas/auth.py app/api/v1/auth.py
git commit -m "feat(auth): 一键登录/微信绑号接入 oneclick 门面并支持 provider 字段"
```
---
### Task B2: 阿里云一键登录配置项
**Files:**
- Modify: `app/core/config.py`(极光段 68-70 之后、或阿里云短信段 149-158 附近加一段)
- Modify: `.env.example`
- [ ] **Step 1: 加配置字段 + 已配置属性**
`app/core/config.py``Settings` 类里新增(放在阿里云短信段落之后,与 `aliyun_sms_configured` 属性相邻):
```python
# ===== 阿里云号码认证·一键登录(Dypnsapi GetMobile 换号)=====
# 与短信同属 dypnsapi 产品:同一阿里云账号时可复用 ALIYUN_SMS_ACCESS_KEY_*,
# 默认独立字段解耦(见 spec §2 决策)。缺凭证 → provider=aliyun 换号抛错→502,不启动崩。
ALIYUN_ONEKEY_ACCESS_KEY_ID: str = ""
ALIYUN_ONEKEY_ACCESS_KEY_SECRET: str = ""
ALIYUN_ONEKEY_ENDPOINT: str = "dypnsapi.aliyuncs.com"
ALIYUN_ONEKEY_TIMEOUT_SEC: int = 15
```
并在 `aliyun_sms_configured` 属性下方加:
```python
@property
def aliyun_oneclick_configured(self) -> bool:
"""阿里云一键登录凭证齐全(缺则 provider=aliyun 换号抛错→502,而非启动崩)。"""
return bool(
self.ALIYUN_ONEKEY_ACCESS_KEY_ID and self.ALIYUN_ONEKEY_ACCESS_KEY_SECRET
)
```
- [ ] **Step 2: 补 `.env.example`**
`.env.example` 里对应位置追加(值留空,注释说明可复用短信 AK/SK):
```dotenv
# 阿里云号码认证·一键登录(Dypnsapi GetMobile)。同账号可填与 ALIYUN_SMS_ACCESS_KEY_* 相同的值。
ALIYUN_ONEKEY_ACCESS_KEY_ID=
ALIYUN_ONEKEY_ACCESS_KEY_SECRET=
ALIYUN_ONEKEY_ENDPOINT=dypnsapi.aliyuncs.com
ALIYUN_ONEKEY_TIMEOUT_SEC=15
```
- [ ] **Step 3: 冒烟导入不报错**
Run: `SGB_TEST_SKIP_DB=1 python -c "from app.core.config import settings; print(settings.aliyun_oneclick_configured)"`
Expected: 打印 `False`(默认空凭证)。
- [ ] **Step 4: Commit**
```bash
git add app/core/config.py .env.example
git commit -m "feat(config): 增加阿里云一键登录换号配置项"
```
---
### Task B3: 实现 `aliyun_onekey` 换号 providerTDD
**Files:**
- Create: `app/integrations/aliyun_onekey.py`
- Test: `tests/test_aliyun_onekey.py`
- [ ] **Step 1: 写失败测试**
Create `tests/test_aliyun_onekey.py`
```python
"""阿里云一键登录换号 provider 单测:monkeypatch SDK 接缝 _call_get_mobile,不触真 SDK/网络。
SGB_TEST_SKIP_DB=1 pytest tests/test_aliyun_onekey.py
"""
from __future__ import annotations
import pytest
from app.core.config import settings
from app.integrations import aliyun_onekey
def _configure(monkeypatch):
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_ID", "ak")
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_SECRET", "sk")
def test_get_phone_success(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": True, "code": "OK", "message": "OK", "mobile": "13800138000"},
)
assert aliyun_onekey.verify_and_get_phone("tok") == "13800138000"
def test_api_failure_raises(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": False, "code": "MobileNumberIllegal", "message": "x", "mobile": None},
)
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
def test_non_phone_result_raises(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": True, "code": "OK", "message": "OK", "mobile": "not-a-phone"},
)
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
def test_not_configured_raises(monkeypatch):
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_ID", "")
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_SECRET", "")
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
```
- [ ] **Step 2: 跑测试确认失败**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_aliyun_onekey.py -v`
Expected: FAIL`ModuleNotFoundError: app.integrations.aliyun_onekey`
- [ ] **Step 3: 实现 provider**
Create `app/integrations/aliyun_onekey.py`
```python
"""阿里云号码认证·一键登录服务端换号(Dypnsapi GetMobile)。
链路:
Android 阿里云 SDK getLoginToken → spToken(access_token)
→ 本服务调 Dypnsapi GetMobile(AccessToken=spToken)
→ 阿里云直接返回明文手机号(无需 RSA/AES,比极光/创蓝少一步解密)
与 jiguang/chuanglan 对齐:对外暴露 verify_and_get_phone(login_token)->str,
失败抛 AliyunOneClickError,由 oneclick.py 门面统一 catch。
SDK 交互隔离在 _call_get_mobile 薄封装(惰性 import + 惰性建 client,仿 sms/aliyun.py),
单测 monkeypatch 它即可。凭证复用/独立见 config.ALIYUN_ONEKEY_*。
"""
from __future__ import annotations
import logging
from app.core.config import settings
logger = logging.getLogger("shagua.aliyun.onekey")
_client = None # 惰性构建的 dypnsapi client(模块级缓存)
class AliyunOneClickError(Exception):
"""阿里云取号失败的统一异常,由 oneclick 门面 catch 翻成 4xx/5xx。"""
def verify_and_get_phone(login_token: str) -> str:
"""对外唯一函数:loginToken(access_token) → 明文手机号。失败抛 AliyunOneClickError。"""
if not settings.aliyun_oneclick_configured:
raise AliyunOneClickError("ALIYUN_ONEKEY_ACCESS_KEY_ID/SECRET not configured")
result = _call_get_mobile(login_token)
if not (result["success"] and result["code"] == "OK"):
logger.error(
"[ALIYUN-ONEKEY] get_mobile failed code=%s msg=%s",
result["code"], result["message"],
)
raise AliyunOneClickError(f"aliyun get_mobile failed code={result['code']}")
phone = (result["mobile"] or "").strip()
if not (phone.isdigit() and len(phone) == 11):
logger.error("[ALIYUN-ONEKEY] unexpected mobile format: %r", phone)
raise AliyunOneClickError("aliyun get_mobile returned non-phone")
return phone
# ==================== SDK 接缝(单测 monkeypatch 这个)====================
def _get_client():
"""惰性构建 dypnsapi client(仿 sms/aliyun.py:jiguang-only 部署不加载 alibabacloud)。"""
global _client
if _client is None:
from alibabacloud_dypnsapi20170525.client import Client
from alibabacloud_tea_openapi import models as open_api_models
cfg = open_api_models.Config(
access_key_id=settings.ALIYUN_ONEKEY_ACCESS_KEY_ID,
access_key_secret=settings.ALIYUN_ONEKEY_ACCESS_KEY_SECRET,
read_timeout=settings.ALIYUN_ONEKEY_TIMEOUT_SEC * 1000, # SDK 单位 ms
connect_timeout=settings.ALIYUN_ONEKEY_TIMEOUT_SEC * 1000,
)
cfg.endpoint = settings.ALIYUN_ONEKEY_ENDPOINT
_client = Client(cfg)
return _client
def _call_get_mobile(login_token: str) -> dict:
"""调 GetMobile。返回归一化 {success, code, message, mobile};import/建 client/调用任一失败抛 AliyunOneClickError。"""
try:
from alibabacloud_dypnsapi20170525 import models as dypns_models
req = dypns_models.GetMobileRequest(access_token=login_token)
body = _get_client().get_mobile(req).body
except Exception as e:
logger.exception("[ALIYUN-ONEKEY] get_mobile 调用异常")
raise AliyunOneClickError("aliyun get_mobile 调用异常") from e
dto = getattr(body, "get_mobile_result_dto", None)
mobile = getattr(dto, "mobile", None) if dto else None
return {
"success": (body.code == "OK"),
"code": body.code,
"message": body.message,
"mobile": mobile,
}
```
> 注:`GetMobile` 响应体字段名以实际 SDK 为准(`code`=="OK"、`get_mobile_result_dto.mobile`)。接真号联调时若字段名不同(如 `mobile` 在别的 dto 下),只需改 `_call_get_mobile` 的最后归一化,`verify_and_get_phone` 及测试不动。
- [ ] **Step 4: 跑测试转绿**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_aliyun_onekey.py -v`
Expected: 4 条全 **PASS**
- [ ] **Step 5: Commit**
```bash
git add app/integrations/aliyun_onekey.py tests/test_aliyun_onekey.py
git commit -m "feat(auth): 新增阿里云一键登录换号 provider(Dypnsapi GetMobile)"
```
---
### Task B4: 门面注册 aliyun 分派(TDD
**Files:**
- Modify: `app/integrations/oneclick.py`
- Test: `tests/test_oneclick.py`(加两条)
- [ ] **Step 1: 加失败测试**
`tests/test_oneclick.py` 顶部 import 加 `aliyun_onekey`
```python
from app.integrations import aliyun_onekey, chuanglan_onekey, jiguang, oneclick
```
文件末尾追加:
```python
def test_dispatch_aliyun(monkeypatch):
seen = {}
def fake_al(t):
seen["al"] = t
return "13855555555"
monkeypatch.setattr(aliyun_onekey, "verify_and_get_phone", fake_al)
assert oneclick.verify_and_get_phone("aliyun", "tok") == "13855555555"
assert seen["al"] == "tok"
def test_aliyun_error_wrapped_as_oneclick_error(monkeypatch):
def boom(_t):
raise aliyun_onekey.AliyunOneClickError("aliyun down")
monkeypatch.setattr(aliyun_onekey, "verify_and_get_phone", boom)
with pytest.raises(oneclick.OneClickError):
oneclick.verify_and_get_phone("aliyun", "tok")
```
- [ ] **Step 2: 跑确认失败**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_oneclick.py::test_dispatch_aliyun -v`
Expected: FAIL`aliyun` 未注册 → 走默认极光 → `13855555555` 不匹配 / `seen``al`)。
- [ ] **Step 3: 注册 aliyun 分派**
`app/integrations/oneclick.py` 三处改动:
```python
# import(第 17 行)加入 aliyun_onekey:
from app.integrations import aliyun_onekey, chuanglan_onekey, jiguang
# 常量段加:
PROVIDER_ALIYUN = "aliyun"
# verify_and_get_phone 分派与异常 catch:
def verify_and_get_phone(provider: str, login_token: str) -> str:
p = (provider or PROVIDER_JIGUANG).strip().lower()
try:
if p == PROVIDER_CHUANGLAN:
return chuanglan_onekey.verify_and_get_phone(login_token)
if p == PROVIDER_ALIYUN:
return aliyun_onekey.verify_and_get_phone(login_token)
return jiguang.verify_and_get_phone(login_token)
except (
jiguang.JiguangError,
chuanglan_onekey.ChuanglanError,
aliyun_onekey.AliyunOneClickError,
) as e:
raise OneClickError(f"[{p}] {e}") from e
```
- [ ] **Step 4: 跑门面测试全绿**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_oneclick.py -v`
Expected: 全 **PASS**(含新增两条 + 原有创蓝/极光分派不回归)。
- [ ] **Step 5: Commit**
```bash
git add app/integrations/oneclick.py tests/test_oneclick.py
git commit -m "feat(auth): oneclick 门面注册阿里云 provider 分派"
```
---
### Task B5: 全量回归 + 真号联调冒烟
- [ ] **Step 1: 全量单测**
Run: `SGB_TEST_SKIP_DB=1 pytest tests/test_oneclick.py tests/test_aliyun_onekey.py -v` 及(有 PG`pytest tests/test_jverify_login_endpoint.py -v`
Expected: 全 PASS。
- [ ] **Step 2: 填真实凭证冒烟(联调期)**
`.env``ALIYUN_ONEKEY_ACCESS_KEY_ID/SECRET`(阿里云控制台号码认证方案对应账号 AK/SK),起服务,用客户端真机取到的 loginToken
Run:
```bash
curl -s -X POST http://127.0.0.1:8770/api/v1/auth/jverify-login \
-H 'Content-Type: application/json' \
-d '{"login_token":"<真机取到的token>","provider":"aliyun","device_id":"smoke"}'
```
Expected: 200 + `user.phone` 为真实手机号 + `access_token` 非空。失败看日志 `shagua.aliyun.onekey``GetMobile failed code=...`)。
- [ ] **Step 3: 无凭证降级冒烟**
清空 `ALIYUN_ONEKEY_*` 重启,`provider=aliyun` 请求应 **502**`OneClickError [aliyun] ... not configured`),且极光 `provider` 省略仍 200。
---
## 自检清单(实现者跑完对照)
- [ ] `provider` 缺省 = jiguang,老客户端不改也能登(B1)。
- [ ] `provider=aliyun` 端到端换号 200B5 Step2)。
- [ ] 任一厂商换号失败 → 502,不建号(B1 tests)。
- [ ] 缺阿里云凭证不 crash 启动,仅该 provider 502B2 property + B5 Step3)。
- [ ] 极光/创蓝分派与端点原行为不回归(B4 Step4 / B1 Step5)。
+109
View File
@@ -219,6 +219,115 @@ 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 返回 awareSQLite/历史转换可能返回 naive,二者必须可混排。"""
naive = datetime(2038, 1, 1, 8, 0)
+51
View File
@@ -0,0 +1,51 @@
"""阿里云一键登录换号 provider 单测:monkeypatch SDK 接缝 _call_get_mobile,不触真 SDK/网络。
SGB_TEST_SKIP_DB=1 pytest tests/test_aliyun_onekey.py
"""
from __future__ import annotations
import pytest
from app.core.config import settings
from app.integrations import aliyun_onekey
def _configure(monkeypatch):
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_ID", "ak")
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_SECRET", "sk")
def test_get_phone_success(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": True, "code": "OK", "message": "OK", "mobile": "13800138000"},
)
assert aliyun_onekey.verify_and_get_phone("tok") == "13800138000"
def test_api_failure_raises(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": False, "code": "MobileNumberIllegal", "message": "x", "mobile": None},
)
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
def test_non_phone_result_raises(monkeypatch):
_configure(monkeypatch)
monkeypatch.setattr(
aliyun_onekey, "_call_get_mobile",
lambda t: {"success": True, "code": "OK", "message": "OK", "mobile": "not-a-phone"},
)
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
def test_not_configured_raises(monkeypatch):
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_ID", "")
monkeypatch.setattr(settings, "ALIYUN_ONEKEY_ACCESS_KEY_SECRET", "")
with pytest.raises(aliyun_onekey.AliyunOneClickError):
aliyun_onekey.verify_and_get_phone("tok")
+4 -1
View File
@@ -263,7 +263,9 @@ 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:
with p, patch(
"app.api.v1.compare.backfill_comparison_llm_cost"
) as backfill:
r = client.post("/api/v1/trace/finalize",
json={"trace_id": tid, "status": "cancelled", "reason": "用户终止"})
assert r.status_code == 200
@@ -271,6 +273,7 @@ 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:
+4
View File
@@ -72,6 +72,7 @@ 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 = [
{
@@ -96,12 +97,15 @@ 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)
+50
View File
@@ -0,0 +1,50 @@
"""jverify-login 端点:provider 分派 + 错误映射(端到端:换号 → 建号 → 签 JWT)。
需要 DB(建号)本机无 PG client fixture 会自动 skip(SGB_TEST_SKIP_DB=1);
PG 环境(CI 或本地起 Docker)完整跑换号一步 monkeypatch , 只验端点编排:
provider 是否原样传给门面成功建号OneClickError 502
"""
from __future__ import annotations
from app.api.v1 import auth
from app.integrations.oneclick import OneClickError
def test_jverify_login_default_provider_builds_account(client, monkeypatch):
"""不带 provider 的老客户端 → 门面按默认(极光)换号, 建号登录成功。"""
monkeypatch.setattr(auth, "verify_and_get_phone", lambda provider, token: "13500000000")
r = client.post("/api/v1/auth/jverify-login", json={"login_token": "tok-old"})
assert r.status_code == 200
body = r.json()
assert body["user"]["phone"] == "13500000000"
assert body["access_token"]
def test_jverify_login_passes_provider_to_facade(client, monkeypatch):
"""provider=aliyun 必须原样传给门面(它决定用哪家换号)。"""
captured: dict = {}
def fake(provider, token):
captured["provider"] = provider
captured["token"] = token
return "13500000001"
monkeypatch.setattr(auth, "verify_and_get_phone", fake)
r = client.post(
"/api/v1/auth/jverify-login",
json={"login_token": "tok-al", "provider": "aliyun"},
)
assert r.status_code == 200
assert captured["provider"] == "aliyun"
assert captured["token"] == "tok-al"
def test_jverify_login_oneclick_error_maps_to_502(client, monkeypatch):
"""任一厂商换号失败(OneClickError) → 502, 不建号。"""
def boom(provider, token):
raise OneClickError("verify failed")
monkeypatch.setattr(auth, "verify_and_get_phone", boom)
r = client.post("/api/v1/auth/jverify-login", json={"login_token": "tok"})
assert r.status_code == 502
+74
View File
@@ -0,0 +1,74 @@
"""一键登录换号门面 oneclick 单测:按 provider 分派到极光/阿里云, 统一异常。
纯函数(monkeypatch 掉两家的 verify_and_get_phone), 不碰 DB本机可跑:
SGB_TEST_SKIP_DB=1 pytest tests/test_oneclick.py
"""
from __future__ import annotations
import pytest
from app.integrations import aliyun_onekey, jiguang, oneclick
def test_dispatch_defaults_to_jiguang_when_blank(monkeypatch):
"""provider 为空 = 老客户端 → 走极光(向后兼容)。"""
seen = {}
def fake_jg(t):
seen["jg"] = t
return "13800000000"
monkeypatch.setattr(jiguang, "verify_and_get_phone", fake_jg)
assert oneclick.verify_and_get_phone("", "tok") == "13800000000"
assert seen["jg"] == "tok"
def test_dispatch_jiguang_explicit(monkeypatch):
monkeypatch.setattr(jiguang, "verify_and_get_phone", lambda t: "13811111111")
assert oneclick.verify_and_get_phone("jiguang", "tok") == "13811111111"
def test_dispatch_aliyun(monkeypatch):
seen = {}
def fake_al(t):
seen["al"] = t
return "13822222222"
monkeypatch.setattr(aliyun_onekey, "verify_and_get_phone", fake_al)
assert oneclick.verify_and_get_phone("aliyun", "tok") == "13822222222"
assert seen["al"] == "tok"
def test_provider_is_case_insensitive(monkeypatch):
monkeypatch.setattr(aliyun_onekey, "verify_and_get_phone", lambda t: "13844444444")
assert oneclick.verify_and_get_phone("Aliyun", "tok") == "13844444444"
def test_unknown_provider_falls_back_to_jiguang(monkeypatch):
"""未知 provider 兜底走极光(主家), 不因客户端传错值而拒登。"""
monkeypatch.setattr(jiguang, "verify_and_get_phone", lambda t: "13833333333")
assert oneclick.verify_and_get_phone("weird-value", "tok") == "13833333333"
def test_jiguang_error_wrapped_as_oneclick_error(monkeypatch):
def boom(_t):
raise jiguang.JiguangError("jg down")
monkeypatch.setattr(jiguang, "verify_and_get_phone", boom)
with pytest.raises(oneclick.OneClickError):
oneclick.verify_and_get_phone("jiguang", "tok")
def test_aliyun_error_wrapped_as_oneclick_error(monkeypatch):
def boom(_t):
raise aliyun_onekey.AliyunOneClickError("aliyun down")
monkeypatch.setattr(aliyun_onekey, "verify_and_get_phone", boom)
with pytest.raises(oneclick.OneClickError):
oneclick.verify_and_get_phone("aliyun", "tok")
def test_mask_phone_reexported():
"""auth 层只依赖 oneclick, 脱敏函数从门面转出。"""
assert oneclick.mask_phone("13800138000") == "138****00"
+5 -5
View File
@@ -147,8 +147,8 @@ def test_wechat_bind_jverify_creates_account(client, monkeypatch) -> None:
"""本机号(极光)绑定路径:verify_and_get_phone 拦掉,未占用 → 建号登入。"""
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_jv_5", "极光用户", None))
phone = "13900139005"
# 极光 loginToken→手机号 在 auth 模块命名空间打桩(auth.py 顶部 from ...jiguang import verify_and_get_phone)
monkeypatch.setattr(auth, "verify_and_get_phone", lambda token: phone)
# loginToken→手机号 在 auth 模块命名空间打桩(auth.py 顶部 from ...oneclick import verify_and_get_phone,2 参 provider/token)
monkeypatch.setattr(auth, "verify_and_get_phone", lambda provider, token: phone)
ticket = client.post(
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devE"}
@@ -181,11 +181,11 @@ def test_wechat_bind_jverify_expired_ticket_returns_401(client, monkeypatch) ->
def test_wechat_bind_jverify_jiguang_error_returns_502(client, monkeypatch) -> None:
"""极光核验失败(JiguangError)→ 502。"""
"""换号失败(OneClickError)→ 502。"""
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_jv_err"))
def _raise(token: str) -> str:
raise auth.JiguangError("mock jg failure")
def _raise(provider: str, token: str) -> str:
raise auth.OneClickError("mock oneclick failure")
monkeypatch.setattr(auth, "verify_and_get_phone", _raise)
ticket = client.post(