Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff83f90007 |
@@ -1,68 +0,0 @@
|
||||
"""add inactivity tables
|
||||
|
||||
Revision ID: 135e79414fd0
|
||||
Revises: comparison_llm_cost
|
||||
Create Date: 2026-07-16 18:31:02.105929
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '135e79414fd0'
|
||||
down_revision: Union[str, Sequence[str], None] = 'comparison_llm_cost'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"inactivity_reset_log",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("coin_balance_before", sa.Integer(), nullable=False),
|
||||
sa.Column("cash_balance_cents_before", sa.Integer(), nullable=False),
|
||||
sa.Column("invite_cash_balance_cents_before", sa.Integer(), nullable=False),
|
||||
sa.Column("last_active_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("inactive_days", sa.Integer(), nullable=False),
|
||||
sa.Column("reason", sa.String(length=32), nullable=False),
|
||||
sa.Column("reset_at", sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
with op.batch_alter_table("inactivity_reset_log", schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f("ix_inactivity_reset_log_user_id"), ["user_id"], unique=False)
|
||||
batch_op.create_index(batch_op.f("ix_inactivity_reset_log_reset_at"), ["reset_at"], unique=False)
|
||||
|
||||
op.create_table(
|
||||
"inactivity_notification_log",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("stage", sa.Integer(), nullable=False),
|
||||
sa.Column("inactive_days", sa.Integer(), nullable=False),
|
||||
sa.Column("coin_balance", sa.Integer(), nullable=False),
|
||||
sa.Column("cash_balance_cents", sa.Integer(), nullable=False),
|
||||
sa.Column("invite_cash_balance_cents", sa.Integer(), nullable=False),
|
||||
sa.Column("channel", sa.String(length=16), nullable=False),
|
||||
sa.Column("status", sa.String(length=16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
with op.batch_alter_table("inactivity_notification_log", schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f("ix_inactivity_notification_log_user_id"), ["user_id"], unique=False)
|
||||
batch_op.create_index(batch_op.f("ix_inactivity_notification_log_created_at"), ["created_at"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("inactivity_notification_log", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_inactivity_notification_log_created_at"))
|
||||
batch_op.drop_index(batch_op.f("ix_inactivity_notification_log_user_id"))
|
||||
op.drop_table("inactivity_notification_log")
|
||||
with op.batch_alter_table("inactivity_reset_log", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_inactivity_reset_log_reset_at"))
|
||||
batch_op.drop_index(batch_op.f("ix_inactivity_reset_log_user_id"))
|
||||
op.drop_table("inactivity_reset_log")
|
||||
@@ -1,36 +0,0 @@
|
||||
"""analytics_event 活跃口径复合索引
|
||||
|
||||
Revision ID: analytics_active_idx
|
||||
Revises: 135e79414fd0
|
||||
Create Date: 2026-07-18 17:35:00.000000
|
||||
|
||||
给 analytics_event 加活跃口径热点复合索引 (event, page, user_id, created_at):
|
||||
activity.active_event_condition 按 (event=show & page=home) ∪ 比价 ∪ 领券 过滤后
|
||||
group by user_id、max(created_at)。覆盖索引让该聚合走 index-only,避免高频 show 事件全表扫。
|
||||
|
||||
⚠️ 本分支迁移树有**既有多头**:135e79414fd0(不活跃两表)与 phone_rebind_log 同从
|
||||
comparison_llm_cost 分叉,`alembic upgrade head` 会多头报错。本迁移挂在 135e79414fd0
|
||||
一侧;集成到 main 时需 `alembic merge` 合并 phone_rebind_log 那个头(与本迁移无关的既有问题)。
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "analytics_active_idx"
|
||||
down_revision: Union[str, Sequence[str], None] = "135e79414fd0"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_index(
|
||||
"ix_analytics_event_active",
|
||||
"analytics_event",
|
||||
["event", "page", "user_id", "created_at"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_analytics_event_active", table_name="analytics_event")
|
||||
@@ -1,25 +0,0 @@
|
||||
"""merge inactivity(analytics_active_idx) + phone_rebind_log heads
|
||||
|
||||
Revision ID: merge_active_phone
|
||||
Revises: analytics_active_idx, phone_rebind_log
|
||||
Create Date: 2026-07-18 18:52:34.001148
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'merge_active_phone'
|
||||
down_revision: Union[str, Sequence[str], None] = ('analytics_active_idx', 'phone_rebind_log')
|
||||
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,32 +0,0 @@
|
||||
"""phone_rebind_log 表(M2 换绑 30 天限制台账)
|
||||
|
||||
Revision ID: phone_rebind_log
|
||||
Revises: comparison_llm_cost
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "phone_rebind_log"
|
||||
down_revision = "comparison_llm_cost"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"phone_rebind_log",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("phone", sa.String(length=20), nullable=False),
|
||||
sa.Column("old_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("new_user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("source", sa.String(length=32), nullable=False, server_default="wechat_conflict"),
|
||||
sa.Column("rebound_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_index("ix_phone_rebind_log_phone", "phone_rebind_log", ["phone"])
|
||||
op.create_index("ix_phone_rebind_log_rebound_at", "phone_rebind_log", ["rebound_at"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_phone_rebind_log_rebound_at", table_name="phone_rebind_log")
|
||||
op.drop_index("ix_phone_rebind_log_phone", table_name="phone_rebind_log")
|
||||
op.drop_table("phone_rebind_log")
|
||||
@@ -11,6 +11,7 @@ from zoneinfo import ZoneInfo
|
||||
from sqlalchemy import Select, asc, case, desc, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.admin.repositories.stats import COMPARE_START_EVENT, COUPON_START_EVENT
|
||||
from app.core import rewards
|
||||
from app.core.config import settings
|
||||
from app.models.ad_feed_reward import AdFeedRewardRecord
|
||||
@@ -31,7 +32,10 @@ from app.models.wallet import (
|
||||
InviteCashTransaction,
|
||||
WithdrawOrder,
|
||||
)
|
||||
from app.repositories import activity, ad_ecpm
|
||||
from app.repositories import ad_ecpm
|
||||
|
||||
# 「最近活跃」计入的行为事件(与大盘 DAU/留存活跃口径一致:开始比价 + 开始领券)
|
||||
_ACTIVE_EVENTS = (COMPARE_START_EVENT, COUPON_START_EVENT)
|
||||
|
||||
# 折算成可提现现金时,非广告金币来源的排除集(广告单独统计、人工调整不算"赚取")
|
||||
_NON_TASK_BIZ_TYPES = ("reward_video", "feed_ad_reward", "admin_grant", "admin_deduct")
|
||||
@@ -84,6 +88,49 @@ def offset_paginate(
|
||||
return items, next_cursor, total
|
||||
|
||||
|
||||
def _last_active_parts():
|
||||
"""「最近活跃」的两个按 user_id 预聚合派生表(最近开始比价/领券事件、最近领券发起)。
|
||||
|
||||
活跃口径与大盘 DAU/留存一致(2026-07-05 产品定:进入 App≈登录 last_login_at +
|
||||
发起比价 real_compare_start + 发起领券 real_coupon_start/claim_started)。
|
||||
用 LEFT JOIN 预聚合而非相关标量子查询:后者在 PG 上对 users 每行各跑一个 SubPlan
|
||||
(排序键、range 筛选、offset_paginate 的 count 三处叠加),埋点表大了会拖垮列表接口;
|
||||
预聚合借 analytics_event.event 索引只扫两类 start 事件,每次查询聚合一次。
|
||||
"""
|
||||
ev_agg = (
|
||||
select(
|
||||
AnalyticsEvent.user_id.label("user_id"),
|
||||
func.max(AnalyticsEvent.created_at).label("last_at"),
|
||||
)
|
||||
.where(
|
||||
AnalyticsEvent.user_id.is_not(None),
|
||||
AnalyticsEvent.event.in_(_ACTIVE_EVENTS),
|
||||
)
|
||||
.group_by(AnalyticsEvent.user_id)
|
||||
.subquery()
|
||||
)
|
||||
eng_agg = (
|
||||
select(
|
||||
CouponPromptEngagement.user_id.label("user_id"),
|
||||
func.max(CouponPromptEngagement.created_at).label("last_at"),
|
||||
)
|
||||
.where(
|
||||
CouponPromptEngagement.user_id.is_not(None),
|
||||
CouponPromptEngagement.engage_type == "claim_started",
|
||||
)
|
||||
.group_by(CouponPromptEngagement.user_id)
|
||||
.subquery()
|
||||
)
|
||||
return ev_agg, eng_agg
|
||||
|
||||
|
||||
def _norm_utc(dt: datetime | None) -> datetime | None:
|
||||
"""naive 视为 UTC 补 tzinfo(SQLite 读回 naive、PG 读回 aware,混着 max() 会 TypeError)。"""
|
||||
if dt is None:
|
||||
return None
|
||||
return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _attach_last_active(db: Session, users: list[User]) -> None:
|
||||
"""给本页用户瞬态挂 last_active_at(非 DB 列,供 AdminUserListItem from_attributes 读)。
|
||||
|
||||
@@ -97,7 +144,7 @@ def _attach_last_active(db: Session, users: list[User]) -> None:
|
||||
select(AnalyticsEvent.user_id, func.max(AnalyticsEvent.created_at))
|
||||
.where(
|
||||
AnalyticsEvent.user_id.in_(uids),
|
||||
activity.active_event_condition(),
|
||||
AnalyticsEvent.event.in_(_ACTIVE_EVENTS),
|
||||
)
|
||||
.group_by(AnalyticsEvent.user_id)
|
||||
).all()
|
||||
@@ -114,9 +161,9 @@ def _attach_last_active(db: Session, users: list[User]) -> None:
|
||||
)
|
||||
for u in users:
|
||||
candidates = [
|
||||
activity.norm_utc(u.created_at), # baseline 由 last_login_at 改为 created_at(登录不算活跃)
|
||||
activity.norm_utc(ev_map.get(u.id)),
|
||||
activity.norm_utc(eng_map.get(u.id)),
|
||||
_norm_utc(u.last_login_at),
|
||||
_norm_utc(ev_map.get(u.id)),
|
||||
_norm_utc(eng_map.get(u.id)),
|
||||
]
|
||||
u.last_active_at = max((c for c in candidates if c is not None), default=None)
|
||||
|
||||
@@ -144,12 +191,16 @@ def list_users(
|
||||
(口径见 [_last_active_expr])。**offset 分页**(cursor=offset):任意列排序下游标语义统一,
|
||||
代价是翻页期间数据变动可能错位一条——admin 低频场景可接受(同 [list_all_withdraw_orders])。
|
||||
日期入参统一转 tz-aware UTC 比较(列为 timestamptz,见 _as_utc)。"""
|
||||
# 最近活跃 = max(注册时间, 最近行为事件, 最近领券发起)。baseline 由 last_login_at 改为 created_at
|
||||
#(登录不代表在用 App;口径统一到 activity.py,含 home_view + 比价 + 领券,见 activity.ACTIVE_EVENTS)。
|
||||
# 未命中侧 coalesce 到 created_at(恒非空基线)。派生表 1:1,outerjoin 不放大行数。
|
||||
ev_agg, eng_agg = activity.last_active_subqueries(db)
|
||||
last_active = activity.last_active_expr(
|
||||
User.created_at, ev_agg, eng_agg, db.get_bind().dialect.name
|
||||
# 最近活跃 = max(最近登录, 最近行为事件, 最近领券发起)。PG 用 GREATEST;SQLite 标量 max()
|
||||
# 任一参数 NULL 即返回 NULL,故 LEFT JOIN 未命中侧 coalesce 到 last_login_at 兜底
|
||||
# (注册即登录,该列恒非空)。派生表 1:1(按 user_id 聚合),outerjoin 不会放大行数,
|
||||
# offset_paginate 的 count 不受影响。
|
||||
ev_agg, eng_agg = _last_active_parts()
|
||||
greatest = func.greatest if db.get_bind().dialect.name == "postgresql" else func.max
|
||||
last_active = greatest(
|
||||
User.last_login_at,
|
||||
func.coalesce(ev_agg.c.last_at, User.last_login_at),
|
||||
func.coalesce(eng_agg.c.last_at, User.last_login_at),
|
||||
)
|
||||
stmt = (
|
||||
select(User)
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.repositories import ad_watch as crud_watch
|
||||
from app.repositories import app_config
|
||||
from app.repositories import signin as crud_signin
|
||||
from app.schemas.ad import (
|
||||
AdRewardResultOut,
|
||||
AdRewardStatusOut,
|
||||
EcpmReportIn,
|
||||
EcpmReportOut,
|
||||
@@ -242,6 +243,24 @@ def reward_status(user: CurrentUser, db: DbSession) -> AdRewardStatusOut:
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/reward-result/{ad_session_id}",
|
||||
response_model=AdRewardResultOut,
|
||||
summary="按广告会话查本次服务端权威发奖结果(弹窗展示实发金币用)",
|
||||
)
|
||||
def reward_result(ad_session_id: str, user: CurrentUser, db: DbSession) -> AdRewardResultOut:
|
||||
"""激励视频关闭后,客户端按本次 `ad_session_id` 查服务端到底发了多少金币,弹窗只展示这个权威数字。
|
||||
|
||||
只读、只查本人本会话的 reward_video 记录:没有记录=pending(S2S 尚未到账,客户端继续有限重试,
|
||||
别把"未到账"当 0);granted 返回真实 coin;capped/closed_early/ecpm_missing 返回终态(coin=0,
|
||||
不伪装成 granted)。不返回 eCPM / 回调原文 / 他人信息。
|
||||
"""
|
||||
rec = crud_ad.find_reward_video_result(db, user.id, ad_session_id)
|
||||
if rec is None:
|
||||
return AdRewardResultOut(ad_session_id=ad_session_id, status="pending", coin=None)
|
||||
return AdRewardResultOut(ad_session_id=ad_session_id, status=rec.status, coin=rec.coin)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/watch-report",
|
||||
response_model=WatchReportOut,
|
||||
|
||||
+16
-299
@@ -12,36 +12,19 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from fastapi import APIRouter, HTTPException, Request, status
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.core import test_account
|
||||
from app.core.ratelimit import (
|
||||
RateLimitRule,
|
||||
check_rate_limits,
|
||||
enforce_rate_limit,
|
||||
record_rate_limits,
|
||||
)
|
||||
from app.core.security import (
|
||||
TokenError,
|
||||
create_bind_ticket,
|
||||
create_conflict_ticket,
|
||||
decode_bind_ticket,
|
||||
decode_conflict_ticket,
|
||||
decode_token,
|
||||
issue_token_pair,
|
||||
)
|
||||
from app.integrations import wxpay
|
||||
from app.core.ratelimit import enforce_rate_limit
|
||||
from app.core.security import TokenError, decode_token, issue_token_pair
|
||||
from app.integrations.jiguang import JiguangError, 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
|
||||
from app.repositories import user as user_repo
|
||||
from app.schemas.auth import (
|
||||
JverifyLoginRequest,
|
||||
LogoutResponse,
|
||||
OccupiedAccountInfo,
|
||||
RefreshRequest,
|
||||
SmsLoginRequest,
|
||||
SmsSendRequest,
|
||||
@@ -49,13 +32,6 @@ from app.schemas.auth import (
|
||||
TokenPair,
|
||||
TokenWithUser,
|
||||
UserOut,
|
||||
WechatBindPhoneJverifyRequest,
|
||||
WechatBindPhoneSmsRequest,
|
||||
WechatBindResultResponse,
|
||||
WechatConflictContinueRequest,
|
||||
WechatConflictRebindRequest,
|
||||
WechatLoginRequest,
|
||||
WechatLoginResponse,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("shagua.auth")
|
||||
@@ -64,10 +40,9 @@ router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
# 手机号登录防刷:同一设备(device_id) + 同一 IP 每小时最多的登录尝试次数(成功/失败都计)。
|
||||
SMS_LOGIN_MAX_PER_HOUR = 5
|
||||
# 发码防刷(同一设备 device_id + 同一 IP,**只按成功发码计数**;被单号 60s 冷却挡下的重发不占额度):
|
||||
# 发码防刷:同一设备(device_id) + 同一 IP 每小时最多的发码次数。
|
||||
# 堵「换手机号绕开单号 60s 冷却」的洞 —— 冷却是单号维度,一机换号能绕开。
|
||||
SMS_SEND_MAX_PER_HOUR_PER_DEVICE = 5 # 每小时上限
|
||||
SMS_SEND_MAX_PER_DAY_PER_DEVICE = 20 # 每天上限(再叠一层日封顶,挡低频长时间轰炸)
|
||||
SMS_SEND_MAX_PER_HOUR_PER_DEVICE = 5
|
||||
|
||||
|
||||
def _login_response(
|
||||
@@ -124,26 +99,23 @@ def sms_send(req: SmsSendRequest, request: Request) -> SmsSendResponse:
|
||||
logger.info("test_account sms_send short-circuit (不真发)")
|
||||
return SmsSendResponse(sent=True, mock=True, cooldown_sec=0)
|
||||
|
||||
# 发码防刷:同一设备(device_id) + 同一 IP,每小时 / 每天两道闸,**均只按成功发码计数**。
|
||||
# 补「换手机号绕开单号 60s 冷却」的洞(冷却是单号维度,一机换号能绕);设备维度按机器封顶,挡短信轰炸/烧钱。
|
||||
# 关键:被单号 60s 冷却挡下的重发是「没真发、没烧钱」→ 不该占额度。故 check(先判)放在真发之前
|
||||
# (超限直接 429、不真发),record(计数)只在 send_code 成功后调 —— 冷却/供应商失败抛 429 时直接返回、不计数。
|
||||
send_rules = [
|
||||
RateLimitRule("sms-send-device", SMS_SEND_MAX_PER_HOUR_PER_DEVICE, 3600,
|
||||
"操作过于频繁,请稍后再试"),
|
||||
RateLimitRule("sms-send-device-daily", SMS_SEND_MAX_PER_DAY_PER_DEVICE, 86400,
|
||||
"今日验证码发送次数过多,请明天再试"),
|
||||
]
|
||||
check_rate_limits(request, subject=req.device_id, rules=send_rules)
|
||||
# 防刷:同一设备(device_id) + 同一 IP 每小时最多 SMS_SEND_MAX_PER_HOUR_PER_DEVICE 次发码。
|
||||
# 补「换手机号绕开单号 60s 冷却」的洞(冷却是单号维度,一机换号能绕);设备维度按机器封顶,
|
||||
# 挡短信轰炸/烧钱。放在真发(send_code)之前 → 超限直接拦下、不真发短信。
|
||||
enforce_rate_limit(
|
||||
request,
|
||||
scope="sms-send-device",
|
||||
subject=req.device_id,
|
||||
limit=SMS_SEND_MAX_PER_HOUR_PER_DEVICE,
|
||||
window_sec=3600,
|
||||
detail="操作过于频繁,请稍后再试",
|
||||
)
|
||||
|
||||
try:
|
||||
cooldown = send_code(req.phone)
|
||||
except SmsError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e)) from e
|
||||
|
||||
# 发码成功 → 两道闸各 +1(被单号冷却挡下的重发走不到这里,故不占额度)
|
||||
record_rate_limits(request, subject=req.device_id, rules=send_rules)
|
||||
|
||||
from app.core.config import settings # 局部 import 避免循环
|
||||
|
||||
return SmsSendResponse(sent=True, mock=settings.SMS_MOCK, cooldown_sec=cooldown)
|
||||
@@ -194,261 +166,6 @@ def sms_login(req: SmsLoginRequest, request: Request, db: DbSession) -> TokenWit
|
||||
return _login_response(user, onboarding_completed=completed)
|
||||
|
||||
|
||||
# ===================== 微信登录 =====================
|
||||
|
||||
@router.post(
|
||||
"/wechat-login",
|
||||
response_model=WechatLoginResponse,
|
||||
summary="微信登录(openid 命中即登入,否则发绑号令牌)",
|
||||
)
|
||||
def wechat_login(req: WechatLoginRequest, db: DbSession) -> WechatLoginResponse:
|
||||
from app.core.config import settings # 局部 import,避免循环
|
||||
|
||||
# 微信登录只需 code→openid(sns/oauth2),不需要商户转账证书;故只校验 APP_ID/SECRET。
|
||||
if not (settings.WECHAT_APP_ID and settings.WECHAT_APP_SECRET):
|
||||
raise HTTPException(status_code=503, detail="wechat login not configured")
|
||||
|
||||
try:
|
||||
info = wxpay.code_to_userinfo(req.code) # {openid, nickname, avatar_url, raw};失败抛 ValueError
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
|
||||
openid = info["openid"]
|
||||
user = user_repo.get_user_by_wechat_openid(db, openid)
|
||||
if user is not None:
|
||||
# openid 命中 → 直接登入(绝不套用提现 bind-wechat 的"撞号即 409"逻辑)
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=403, detail="account disabled")
|
||||
user_repo.touch_last_login(db, user)
|
||||
completed = onboarding_repo.is_completed(db, user_id=user.id, device_id=req.device_id)
|
||||
logger.info("wechat_login hit user_id=%d openid=%s*** onboarded=%s", user.id, openid[:6], completed)
|
||||
return WechatLoginResponse(
|
||||
status="logged_in",
|
||||
token=_login_response(user, onboarding_completed=completed),
|
||||
)
|
||||
|
||||
# 未命中 → 签发短时 bind_ticket,进手机号绑定流程(账号此刻还不建)
|
||||
ticket = create_bind_ticket(
|
||||
openid=openid,
|
||||
wechat_nickname=info["nickname"],
|
||||
wechat_avatar_url=info["avatar_url"],
|
||||
)
|
||||
logger.info("wechat_login new openid=%s*** issue bind_ticket", openid[:6])
|
||||
return WechatLoginResponse(
|
||||
status="need_bind_phone",
|
||||
bind_ticket=ticket,
|
||||
wechat_nickname=info["nickname"],
|
||||
wechat_avatar_url=info["avatar_url"],
|
||||
)
|
||||
|
||||
|
||||
def _finish_wechat_bind(
|
||||
db,
|
||||
*,
|
||||
openid: str,
|
||||
wechat_nickname: str | None,
|
||||
wechat_avatar_url: str | None,
|
||||
phone: str,
|
||||
device_id: str,
|
||||
) -> WechatBindResultResponse:
|
||||
"""绑手机建号的公共尾段:手机号被占用 → 返回 phone_occupied(M2 处理 3 选 1);
|
||||
未占用 → 新建微信账号(channel=wechat,昵称头像取微信)→ 签 token 登入。"""
|
||||
existing = user_repo.get_user_by_phone(db, phone)
|
||||
if existing is not None:
|
||||
from app.core.config import settings # 局部 import,避免循环
|
||||
|
||||
ticket = create_conflict_ticket(
|
||||
openid=openid,
|
||||
wechat_nickname=wechat_nickname,
|
||||
wechat_avatar_url=wechat_avatar_url,
|
||||
phone=phone,
|
||||
)
|
||||
blocked = rebind_repo.rebound_within_days(db, phone, settings.PHONE_REBIND_LIMIT_DAYS)
|
||||
logger.info(
|
||||
"wechat bind phone occupied phone=%s by user_id=%d has_wechat=%s",
|
||||
mask_phone(phone), existing.id, bool(existing.wechat_openid),
|
||||
)
|
||||
return WechatBindResultResponse(
|
||||
status="phone_occupied",
|
||||
occupied_account=OccupiedAccountInfo(
|
||||
nickname=existing.nickname,
|
||||
avatar_url=existing.avatar_url,
|
||||
created_at=existing.created_at,
|
||||
has_wechat=bool(existing.wechat_openid),
|
||||
),
|
||||
conflict_ticket=ticket,
|
||||
rebind_available=not blocked,
|
||||
rebind_blocked_days=(
|
||||
rebind_repo.remaining_block_days(db, phone, settings.PHONE_REBIND_LIMIT_DAYS)
|
||||
if blocked else 0
|
||||
),
|
||||
)
|
||||
user = user_repo.create_wechat_user(
|
||||
db,
|
||||
phone=phone,
|
||||
openid=openid,
|
||||
wechat_nickname=wechat_nickname,
|
||||
wechat_avatar_url=wechat_avatar_url,
|
||||
)
|
||||
completed = onboarding_repo.is_completed(db, user_id=user.id, device_id=device_id)
|
||||
logger.info("wechat bind ok user_id=%d phone=%s openid=%s*** onboarded=%s",
|
||||
user.id, mask_phone(phone), openid[:6], completed)
|
||||
return WechatBindResultResponse(
|
||||
status="logged_in",
|
||||
token=_login_response(user, onboarding_completed=completed),
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/wechat/bind-phone/sms",
|
||||
response_model=WechatBindResultResponse,
|
||||
summary="微信登录·其他手机号(短信)绑定",
|
||||
)
|
||||
def wechat_bind_phone_sms(
|
||||
req: WechatBindPhoneSmsRequest, request: Request, db: DbSession
|
||||
) -> WechatBindResultResponse:
|
||||
try:
|
||||
claims = decode_bind_ticket(req.bind_ticket)
|
||||
except TokenError as e:
|
||||
raise HTTPException(status_code=401, detail="授权已过期,请重新用微信登录") from e
|
||||
|
||||
# 防刷:同 sms/login,按 设备+IP 每小时限流(放在验证码校验之前,失败也计数)
|
||||
enforce_rate_limit(
|
||||
request,
|
||||
scope="wechat-bind-sms-device",
|
||||
subject=req.device_id,
|
||||
limit=SMS_LOGIN_MAX_PER_HOUR,
|
||||
window_sec=3600,
|
||||
detail="登录尝试过于频繁,请稍后再试",
|
||||
)
|
||||
|
||||
if not verify_code(req.phone, req.code):
|
||||
raise HTTPException(status_code=400, detail="invalid sms code")
|
||||
|
||||
return _finish_wechat_bind(
|
||||
db,
|
||||
openid=claims["openid"],
|
||||
wechat_nickname=claims["wnk"],
|
||||
wechat_avatar_url=claims["wav"],
|
||||
phone=req.phone,
|
||||
device_id=req.device_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/wechat/bind-phone/jverify",
|
||||
response_model=WechatBindResultResponse,
|
||||
summary="微信登录·本机号(极光)绑定",
|
||||
)
|
||||
def wechat_bind_phone_jverify(
|
||||
req: WechatBindPhoneJverifyRequest, db: DbSession
|
||||
) -> WechatBindResultResponse:
|
||||
try:
|
||||
claims = decode_bind_ticket(req.bind_ticket)
|
||||
except TokenError as e:
|
||||
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
|
||||
|
||||
return _finish_wechat_bind(
|
||||
db,
|
||||
openid=claims["openid"],
|
||||
wechat_nickname=claims["wnk"],
|
||||
wechat_avatar_url=claims["wav"],
|
||||
phone=phone,
|
||||
device_id=req.device_id,
|
||||
)
|
||||
|
||||
|
||||
# ===================== 微信占用冲突(M2) =====================
|
||||
|
||||
@router.post(
|
||||
"/wechat/conflict/continue",
|
||||
response_model=WechatBindResultResponse,
|
||||
summary="微信占用冲突·继续绑定(登录老账号,能绑就绑)",
|
||||
)
|
||||
def wechat_conflict_continue(
|
||||
req: WechatConflictContinueRequest, request: Request, db: DbSession
|
||||
) -> WechatBindResultResponse:
|
||||
try:
|
||||
claims = decode_conflict_ticket(req.conflict_ticket)
|
||||
except TokenError as e:
|
||||
raise HTTPException(status_code=401, detail="操作超时,请重新用微信登录") from e
|
||||
|
||||
enforce_rate_limit(
|
||||
request, scope="wechat-conflict-device", subject=req.device_id,
|
||||
limit=SMS_LOGIN_MAX_PER_HOUR, window_sec=3600, detail="操作过于频繁,请稍后再试",
|
||||
)
|
||||
|
||||
user = user_repo.get_user_by_phone(db, claims["phone"])
|
||||
if user is None:
|
||||
# P 期间被腾空(老账号改号/注销)→ 前提已变,让前端重走
|
||||
raise HTTPException(status_code=409, detail="账号状态已变化,请重新登录")
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=403, detail="account disabled")
|
||||
|
||||
if user.wechat_openid is None:
|
||||
try:
|
||||
user_repo.attach_wechat_to_user(
|
||||
db, user, openid=claims["openid"],
|
||||
wechat_nickname=claims["wnk"], wechat_avatar_url=claims["wav"],
|
||||
)
|
||||
except IntegrityError:
|
||||
db.rollback() # openid 被别处绑走 → 只登入不绑
|
||||
user_repo.touch_last_login(db, user)
|
||||
else:
|
||||
user_repo.touch_last_login(db, user) # X 已绑别的微信 → 只登入,丢弃本次 openid
|
||||
|
||||
completed = onboarding_repo.is_completed(db, user_id=user.id, device_id=req.device_id)
|
||||
logger.info("wechat conflict continue user_id=%d openid=%s***", user.id, claims["openid"][:6])
|
||||
return WechatBindResultResponse(
|
||||
status="logged_in",
|
||||
token=_login_response(user, onboarding_completed=completed),
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/wechat/conflict/rebind",
|
||||
response_model=WechatBindResultResponse,
|
||||
summary="微信占用冲突·换绑(注销老账号+用该号重建全新账号)",
|
||||
)
|
||||
def wechat_conflict_rebind(
|
||||
req: WechatConflictRebindRequest, request: Request, db: DbSession
|
||||
) -> WechatBindResultResponse:
|
||||
from app.core.config import settings # 局部 import,避免循环
|
||||
|
||||
try:
|
||||
claims = decode_conflict_ticket(req.conflict_ticket)
|
||||
except TokenError as e:
|
||||
raise HTTPException(status_code=401, detail="操作超时,请重新用微信登录") from e
|
||||
|
||||
enforce_rate_limit(
|
||||
request, scope="wechat-conflict-device", subject=req.device_id,
|
||||
limit=SMS_LOGIN_MAX_PER_HOUR, window_sec=3600, detail="操作过于频繁,请稍后再试",
|
||||
)
|
||||
|
||||
phone = claims["phone"]
|
||||
if rebind_repo.rebound_within_days(db, phone, settings.PHONE_REBIND_LIMIT_DAYS):
|
||||
days = rebind_repo.remaining_block_days(db, phone, settings.PHONE_REBIND_LIMIT_DAYS)
|
||||
raise HTTPException(status_code=409, detail=f"该手机号 {days} 天内已换绑过,暂不能再次换绑")
|
||||
|
||||
user = user_repo.rebind_account(
|
||||
db, phone=phone, openid=claims["openid"],
|
||||
wechat_nickname=claims["wnk"], wechat_avatar_url=claims["wav"],
|
||||
)
|
||||
completed = onboarding_repo.is_completed(db, user_id=user.id, device_id=req.device_id)
|
||||
logger.info("wechat conflict rebind new_user_id=%d phone=%s openid=%s***",
|
||||
user.id, mask_phone(phone), claims["openid"][:6])
|
||||
return WechatBindResultResponse(
|
||||
status="logged_in",
|
||||
token=_login_response(user, onboarding_completed=completed),
|
||||
)
|
||||
|
||||
|
||||
# ===================== Refresh =====================
|
||||
|
||||
@router.post("/refresh", response_model=TokenPair, summary="用 refresh_token 换新 token 对")
|
||||
|
||||
@@ -44,11 +44,6 @@ class Settings(BaseSettings):
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 120
|
||||
JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 30
|
||||
# 微信登录未命中 openid 时签发的"待绑手机"令牌有效期(JWT_SECRET_KEY 签名,typ=wechat_bind;
|
||||
# 见 security.create_bind_ticket)。需覆盖"授权→输手机号→收短信→输验证码"整个绑定流程。
|
||||
WECHAT_BIND_TICKET_EXPIRE_MINUTES: int = 10
|
||||
# 一个手机号 30 天内最多换绑一次(微信占用冲突页的"换绑"动作)。见 phone_rebind_log。
|
||||
PHONE_REBIND_LIMIT_DAYS: int = 30
|
||||
|
||||
# ===== Admin 后台 =====
|
||||
# admin 用独立 JWT secret(≠ JWT_SECRET_KEY),App 用户 token 无法越权访问后台。
|
||||
@@ -86,7 +81,6 @@ class Settings(BaseSettings):
|
||||
SMS_SIGN_ID: int = 31729 # 极光短信签名 ID(非机密,可被 .env 覆盖)
|
||||
SMS_TEMPLATE_ID: int = 1 # 极光短信模板 ID(变量名 code,有效期 5 分钟)
|
||||
SMS_CODE_LENGTH: int = 6 # 验证码位数(本服务生成;前端 code 字段 4-8 位兼容)
|
||||
SMS_DAILY_LIMIT_PER_PHONE: int = 10 # 单手机号每日发送上限(防刷 + 控费)
|
||||
SMS_MAX_VERIFY_ATTEMPTS: int = 5 # 单个验证码最多校验失败次数,超过即作废(防爆破)
|
||||
|
||||
# ===== 测试账号(release 包全流程联调用)=====
|
||||
@@ -112,9 +106,6 @@ class Settings(BaseSettings):
|
||||
# 美团调用走的代理。本机开发直连美团会 SSL EOF,需填 http://127.0.0.1:7897;
|
||||
# 线上国内服务器留空(=直连)。见 .env.example 与 integrations/meituan.py。
|
||||
MT_CPS_PROXY: str = ""
|
||||
# 本地开发:开启后 /feed 接口直接返回 mock 数据,不调美团 API、不查离线库,
|
||||
# 方便前端联调 feed 卡片样式、分页、距离排序等 UI。生产必须 false。
|
||||
MT_CPS_MOCK_FEED: bool = True
|
||||
|
||||
@property
|
||||
def mt_cps_configured(self) -> bool:
|
||||
@@ -178,13 +169,6 @@ class Settings(BaseSettings):
|
||||
# 进程内自动兑换 worker 的检查间隔(秒):每隔这么久醒一次,跨过北京 0 点就跑一轮。
|
||||
# 默认 600s=10min,即 0 点后最多 10 分钟内兑完(客户端文案已注明「可能存在延迟」)。
|
||||
AUTO_EXCHANGE_CHECK_INTERVAL_SEC: int = 600
|
||||
# === 15 天不活跃清零(app.core.inactivity_reset_worker)===
|
||||
INACTIVITY_RESET_ENABLED: bool = False # 总闸,默认关;灰度验证后再开
|
||||
INACTIVITY_RESET_DAYS: int = 15 # 不活跃阈值(天),第 (N+1) 日 0 点清
|
||||
INACTIVITY_WARN_DAYS_BEFORE: str = "7,2" # 清零前几天各推一次;""=不推。逗号分隔
|
||||
INACTIVITY_RESET_RUN_HOUR: int = 3 # 北京时间每日执行点(0-23)
|
||||
INACTIVITY_NOTIFY_CHANNEL: str = "log" # log(占位) / jpush / sms
|
||||
INACTIVITY_RESET_CHECK_INTERVAL_SEC: int = 1800 # worker 唤醒间隔(秒)
|
||||
# 免确认收款授权(用户授权免确认模式)的授权结果回调地址,必须公网可访问 HTTPS、不带参数。
|
||||
# 发起授权 / 首单顺带授权时作为 authorization_notify_url 传给微信。一期不处理回调内容
|
||||
# (授权状态靠 query 查询兜底),但微信要求该字段非空,故启用免确认前必须配置;留空时免确认相关接口返回未配置。
|
||||
@@ -205,19 +189,6 @@ class Settings(BaseSettings):
|
||||
"""免确认收款授权可用 = 微信支付凭证齐全 + 授权回调地址已配。"""
|
||||
return bool(self.wxpay_configured and self.WXPAY_AUTH_NOTIFY_URL)
|
||||
|
||||
@property
|
||||
def inactivity_warn_stages(self) -> list[int]:
|
||||
"""解析 INACTIVITY_WARN_DAYS_BEFORE → 降序去重的提前天数列表。
|
||||
丢弃非数字 / <=0 / >=RESET_DAYS 的项(空串 → 空列表 = 不推)。"""
|
||||
out: list[int] = []
|
||||
for part in (self.INACTIVITY_WARN_DAYS_BEFORE or "").split(","):
|
||||
part = part.strip()
|
||||
if part.isdigit():
|
||||
v = int(part)
|
||||
if 0 < v < self.INACTIVITY_RESET_DAYS and v not in out:
|
||||
out.append(v)
|
||||
return sorted(out, reverse=True)
|
||||
|
||||
# ===== 穿山甲激励视频(服务端发奖回调)=====
|
||||
# 看完激励视频后穿山甲服务器回调本服务发金币(S2S,客户端被破解也刷不到)。
|
||||
# 穿山甲后台配置的"奖励校验密钥"(m-key),验签用。每个 GroMore 广告位 m-key 不同(后台各自
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
"""15 天不活跃清零的进程内每日任务。
|
||||
|
||||
仿 daily_exchange_worker:App 启动自带,每 `INACTIVITY_RESET_CHECK_INTERVAL_SEC` 醒一次,
|
||||
跨进北京新的一天且到达 `INACTIVITY_RESET_RUN_HOUR`(默认 3 点)后跑一轮 `run_once`(预警 + 清零)。
|
||||
|
||||
健壮性:
|
||||
- **逐用户幂等**:清完余额=0 次日不再匹配;预警按 streak 去重。启动补跑 / 多次唤醒 / 重启都安全。
|
||||
- **同机多进程互斥**:文件锁保证多 worker 只有一个实际跑。
|
||||
- **开关**:settings.INACTIVITY_RESET_ENABLED=false 时不启动(默认关,灰度验证后再开)。
|
||||
|
||||
⚠️ 这是不可逆批量资金操作(清空金币 + 折算现金,**邀请现金不清**)。口径见
|
||||
app.repositories.inactivity / app.repositories.activity。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.rewards import CN_TZ, cn_today
|
||||
from app.db.session import SessionLocal
|
||||
from app.integrations.notifier import get_notifier
|
||||
from app.repositories import inactivity as inactivity_repo
|
||||
|
||||
logger = logging.getLogger("shagua.inactivity")
|
||||
_LOCK_PATH = Path(__file__).resolve().parents[2] / "data" / "inactivity_reset.lock"
|
||||
|
||||
|
||||
def _cn_today() -> date:
|
||||
return cn_today()
|
||||
|
||||
|
||||
def _touch_lock() -> None:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.utime(_LOCK_PATH, None)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _single_instance_lock(stale_after_sec: int) -> Iterator[bool]:
|
||||
"""同机多进程保护:同一时间只允许一个清零 worker 运行。"""
|
||||
_LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd: int | None = None
|
||||
try:
|
||||
try:
|
||||
fd = os.open(str(_LOCK_PATH), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
except FileExistsError:
|
||||
try:
|
||||
age = time.time() - _LOCK_PATH.stat().st_mtime
|
||||
except FileNotFoundError:
|
||||
age = stale_after_sec + 1
|
||||
if age > stale_after_sec:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
_LOCK_PATH.unlink()
|
||||
try:
|
||||
fd = os.open(str(_LOCK_PATH), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
except FileExistsError:
|
||||
fd = None
|
||||
|
||||
if fd is None:
|
||||
yield False
|
||||
return
|
||||
|
||||
os.write(fd, f"pid={os.getpid()} started_at={int(time.time())}\n".encode("ascii"))
|
||||
yield True
|
||||
finally:
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
_LOCK_PATH.unlink()
|
||||
|
||||
|
||||
def _run_once_entry() -> dict:
|
||||
"""跑一轮(预警 + 清零)。独立开 Session。"""
|
||||
notifier = get_notifier(settings.INACTIVITY_NOTIFY_CHANNEL)
|
||||
with SessionLocal() as db:
|
||||
return inactivity_repo.run_once(
|
||||
db,
|
||||
notifier=notifier,
|
||||
reset_days=settings.INACTIVITY_RESET_DAYS,
|
||||
warn_stages=settings.inactivity_warn_stages,
|
||||
today=_cn_today(),
|
||||
)
|
||||
|
||||
|
||||
async def _run_loop() -> None:
|
||||
interval = max(60, int(settings.INACTIVITY_RESET_CHECK_INTERVAL_SEC))
|
||||
lock_stale_after = max(interval * 3, 1800)
|
||||
with _single_instance_lock(lock_stale_after) as lock_acquired:
|
||||
if not lock_acquired:
|
||||
logger.warning("inactivity reset skipped: another worker owns lock")
|
||||
return
|
||||
await _run_locked_loop(interval)
|
||||
|
||||
|
||||
async def _run_locked_loop(interval: int) -> None:
|
||||
logger.info(
|
||||
"inactivity reset worker started interval=%ss run_hour=%s",
|
||||
interval,
|
||||
settings.INACTIVITY_RESET_RUN_HOUR,
|
||||
)
|
||||
# 本进程上次跑过的北京日;None=尚未跑过本进程(当天到点即补)。
|
||||
last_run: date | None = None
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
_touch_lock()
|
||||
today = _cn_today()
|
||||
hour = datetime.now(CN_TZ).hour
|
||||
if last_run != today and hour >= int(settings.INACTIVITY_RESET_RUN_HOUR):
|
||||
result = await asyncio.to_thread(_run_once_entry)
|
||||
last_run = today
|
||||
logger.info("inactivity reset done date=%s result=%s", today, result)
|
||||
except SQLAlchemyError:
|
||||
logger.exception("inactivity reset db error")
|
||||
except Exception: # noqa: BLE001 - 后台任务不能因单次异常退出
|
||||
logger.exception("inactivity reset unexpected error")
|
||||
await asyncio.sleep(interval)
|
||||
except asyncio.CancelledError:
|
||||
logger.info("inactivity reset worker stopped")
|
||||
raise
|
||||
|
||||
|
||||
def start_inactivity_reset_worker() -> asyncio.Task | None:
|
||||
if not settings.INACTIVITY_RESET_ENABLED:
|
||||
logger.info("inactivity reset disabled (INACTIVITY_RESET_ENABLED=false)")
|
||||
return None
|
||||
return asyncio.create_task(_run_loop(), name="inactivity-reset")
|
||||
|
||||
|
||||
async def stop_inactivity_reset_worker(task: asyncio.Task | None) -> None:
|
||||
if task is None:
|
||||
return
|
||||
task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
+8
-93
@@ -9,41 +9,29 @@ from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import NamedTuple
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
# key -> (window_start_ts, count, window_sec)
|
||||
# 存每个 key 自己的 window_sec:_buckets 混着不同窗口(60s 广告 / 3600s 登录 / 86400s 日闸)的 key,
|
||||
# GC 必须按各 key 自己的窗口判过期(见 [_purge_expired]),否则短窗口调用触发的 GC 会误删长窗口 key。
|
||||
_buckets: dict[str, tuple[float, int, float]] = {}
|
||||
# key -> (window_start_ts, count)
|
||||
_buckets: dict[str, tuple[float, int]] = {}
|
||||
_lock = threading.Lock()
|
||||
_GC_THRESHOLD = 10000 # _buckets 超此阈值才顺手清过期 key(仿 sms.py;测试可 monkeypatch 调小强制每次扫)
|
||||
|
||||
|
||||
def _purge_expired(now: float) -> None:
|
||||
"""清过期 key(**仅在持有 _lock 时调用**)。按每个 key 自己存的 window_sec 判过期,而非调用方的窗口
|
||||
—— _buckets 是全局共享、混着 60s(广告)/3600s(登录)/86400s(日闸)不同窗口的 key;若用调用方窗口,
|
||||
高频的 60s 广告端点触发 GC 时会把本该活 3600s/86400s 的登录/日闸计数一并删掉,使其在规模上(超阈值才
|
||||
触发本清理)被反复清零而失效。仅在超阈值时扫,低频、开销可忽略。"""
|
||||
if len(_buckets) <= _GC_THRESHOLD:
|
||||
return
|
||||
for k in [k for k, (s, _, w) in _buckets.items() if now - s >= w]:
|
||||
_buckets.pop(k, None)
|
||||
|
||||
|
||||
def _hit(key: str, limit: int, window_sec: float) -> bool:
|
||||
"""记一次访问。返回 True=放行,False=超限。"""
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
start, count, _ = _buckets.get(key, (now, 0, window_sec))
|
||||
start, count = _buckets.get(key, (now, 0))
|
||||
if now - start >= window_sec: # 窗口过期,重置
|
||||
start, count = now, 0
|
||||
count += 1
|
||||
_buckets[key] = (start, count, window_sec)
|
||||
_purge_expired(now) # 顺手清过期 key(按各自窗口),防内存无限涨
|
||||
_buckets[key] = (start, count)
|
||||
# 顺手清理过期 key,防内存无限涨(低频访问足够)
|
||||
if len(_buckets) > 10000:
|
||||
for k in [k for k, (s, _) in _buckets.items() if now - s >= window_sec]:
|
||||
_buckets.pop(k, None)
|
||||
return count <= limit
|
||||
|
||||
|
||||
@@ -95,76 +83,3 @@ def enforce_rate_limit(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
)
|
||||
|
||||
|
||||
# ===================== 先判 / 后记(只按「成功」计数)=====================
|
||||
# _hit 是原子「判+记」:一调用就 +1,适合登录爆破(失败尝试也要计)。但对「短信发码」这类
|
||||
# **只想给成功动作计数**的场景不合适 —— 被单号冷却挡下的重发没真发、没烧钱,不该占额度。
|
||||
# 故拆成 _peek(只判不记)+ _commit(只记):check_rate_limits 先判 → 动作 → 成功后 record。
|
||||
|
||||
|
||||
class RateLimitRule(NamedTuple):
|
||||
"""一条限流规则。scope 区分不同闸(不同 key 前缀);同一 (subject, IP) 在 window_sec
|
||||
内最多 limit 次,超限抛 429 用 detail 文案。
|
||||
|
||||
(scope, window_sec) 成对绑在一条规则里 —— check(先判)与 record(计数)复用同一条,
|
||||
避免两处把窗口/scope 写歪导致 key 对不上。
|
||||
"""
|
||||
|
||||
scope: str
|
||||
limit: int
|
||||
window_sec: float
|
||||
detail: str = "操作过于频繁,请稍后再试"
|
||||
|
||||
|
||||
def _peek(key: str, limit: int, window_sec: float) -> bool:
|
||||
"""只读:当前窗口内是否还没到上限(count < limit)。**不改计数**。
|
||||
与 [_commit] 配对实现「先判后记」——只在动作成功后才 _commit。"""
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
start, count, _ = _buckets.get(key, (now, 0, window_sec))
|
||||
if now - start >= window_sec: # 窗口已过期 → 视作已重置(count 归零)
|
||||
count = 0
|
||||
return count < limit
|
||||
|
||||
|
||||
def _commit(key: str, window_sec: float) -> None:
|
||||
"""记一次访问(+1)。窗口过期则以本次为起点重置。仅在动作成功后调用。"""
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
start, count, _ = _buckets.get(key, (now, 0, window_sec))
|
||||
if now - start >= window_sec: # 窗口过期,重置
|
||||
start, count = now, 0
|
||||
_buckets[key] = (start, count + 1, window_sec)
|
||||
_purge_expired(now) # 顺手清过期 key(按各自窗口,同 [_hit])
|
||||
|
||||
|
||||
def check_rate_limits(request: Request, subject: str, rules: list[RateLimitRule]) -> None:
|
||||
"""【先判】一组限流:任一规则已达上限即抛 429,且**不改计数**。
|
||||
|
||||
配合 [record_rate_limits] 实现「只按成功计数」:先 check 所有闸(全未超才继续)→ 执行动作
|
||||
→ 动作**成功后**再 record。动作被下游挡下(如短信单号冷却)、没真正发生时不 record → 不占额度。
|
||||
key = `scope:subject:client_ip`(与 [enforce_rate_limit] 同款)。
|
||||
"""
|
||||
if not settings.RATE_LIMIT_ENABLED:
|
||||
return
|
||||
ip = _client_ip(request)
|
||||
for rule in rules:
|
||||
if not _peek(f"{rule.scope}:{subject}:{ip}", rule.limit, rule.window_sec):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=rule.detail,
|
||||
)
|
||||
|
||||
|
||||
def record_rate_limits(request: Request, subject: str, rules: list[RateLimitRule]) -> None:
|
||||
"""【记一次】一组限流(每条规则 +1)。仅在动作成功后调用,与 [check_rate_limits] 配对。
|
||||
|
||||
⚠️ check→动作→record 非原子:并发突发下计数可能略超 limit(每个在途请求各 +1)。对
|
||||
「防脚本/防轰炸」的安全网定位可接受;要精确配额需迁 Redis(见模块 docstring)。
|
||||
"""
|
||||
if not settings.RATE_LIMIT_ENABLED:
|
||||
return
|
||||
ip = _client_ip(request)
|
||||
for rule in rules:
|
||||
_commit(f"{rule.scope}:{subject}:{ip}", rule.window_sec)
|
||||
|
||||
@@ -87,91 +87,6 @@ def issue_token_pair(user_id: int) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def create_bind_ticket(
|
||||
*, openid: str, wechat_nickname: str | None, wechat_avatar_url: str | None
|
||||
) -> str:
|
||||
"""微信登录未命中 openid 时,签发短时"待绑手机"令牌,承载 openid + 微信昵称头像。
|
||||
|
||||
typ='wechat_bind'、sub=openid;有效期 settings.WECHAT_BIND_TICKET_EXPIRE_MINUTES 分钟。
|
||||
与 access/refresh 用同一 JWT_SECRET_KEY 签名,靠 typ 区分,decode_bind_ticket 校验 typ。
|
||||
"""
|
||||
now = _now()
|
||||
expire = now + timedelta(minutes=settings.WECHAT_BIND_TICKET_EXPIRE_MINUTES)
|
||||
payload: dict[str, Any] = {
|
||||
"sub": openid,
|
||||
"typ": "wechat_bind",
|
||||
"wnk": wechat_nickname,
|
||||
"wav": wechat_avatar_url,
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int(expire.timestamp()),
|
||||
}
|
||||
return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_bind_ticket(token: str) -> dict[str, Any]:
|
||||
"""解析"待绑手机"令牌,校验签名/过期/类型。失败抛 TokenError。
|
||||
|
||||
返回 {'openid': str, 'wnk': str|None, 'wav': str|None}。
|
||||
"""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
||||
except jwt.ExpiredSignatureError as e:
|
||||
raise TokenError("bind ticket expired") from e
|
||||
except jwt.InvalidTokenError as e:
|
||||
raise TokenError(f"invalid bind ticket: {e}") from e
|
||||
if payload.get("typ") != "wechat_bind":
|
||||
raise TokenError(f"wrong token type: want=wechat_bind got={payload.get('typ')}")
|
||||
if "sub" not in payload:
|
||||
raise TokenError("bind ticket missing sub")
|
||||
return {"openid": payload["sub"], "wnk": payload.get("wnk"), "wav": payload.get("wav")}
|
||||
|
||||
|
||||
def create_conflict_ticket(
|
||||
*, openid: str, wechat_nickname: str | None, wechat_avatar_url: str | None, phone: str
|
||||
) -> str:
|
||||
"""手机号占用时签发的短时"冲突处理"令牌。
|
||||
|
||||
比 bind_ticket 多编码 **已验证的手机号 phone** —— 换绑/继续绑定只认它,证明"这对
|
||||
openid/手机号刚在绑号时验证通过",免用户重输验证码,又堵住"拿自己 openid + 任意手机号
|
||||
去夺号"的接管漏洞。typ='wechat_conflict';有效期复用 WECHAT_BIND_TICKET_EXPIRE_MINUTES。
|
||||
"""
|
||||
now = _now()
|
||||
expire = now + timedelta(minutes=settings.WECHAT_BIND_TICKET_EXPIRE_MINUTES)
|
||||
payload: dict[str, Any] = {
|
||||
"sub": openid,
|
||||
"typ": "wechat_conflict",
|
||||
"wnk": wechat_nickname,
|
||||
"wav": wechat_avatar_url,
|
||||
"phn": phone,
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int(expire.timestamp()),
|
||||
}
|
||||
return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_conflict_ticket(token: str) -> dict[str, Any]:
|
||||
"""解析"冲突处理"令牌,校验签名/过期/类型。失败抛 TokenError。
|
||||
|
||||
返回 {'openid': str, 'wnk': str|None, 'wav': str|None, 'phone': str}。
|
||||
"""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
||||
except jwt.ExpiredSignatureError as e:
|
||||
raise TokenError("conflict ticket expired") from e
|
||||
except jwt.InvalidTokenError as e:
|
||||
raise TokenError(f"invalid conflict ticket: {e}") from e
|
||||
if payload.get("typ") != "wechat_conflict":
|
||||
raise TokenError(f"wrong token type: want=wechat_conflict got={payload.get('typ')}")
|
||||
if "sub" not in payload or "phn" not in payload:
|
||||
raise TokenError("conflict ticket missing sub/phn")
|
||||
return {
|
||||
"openid": payload["sub"],
|
||||
"wnk": payload.get("wnk"),
|
||||
"wav": payload.get("wav"),
|
||||
"phone": payload["phn"],
|
||||
}
|
||||
|
||||
|
||||
# ===================== 密码 hash(admin 后台账号用)=====================
|
||||
# 用户侧是手机号+验证码登录,不存密码;仅 admin 账号用 username+password 登录。
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
"""不活跃预警通知器(可插拔)。
|
||||
|
||||
v1 仅日志占位(LogNotifier):现状无真实推送能力(极光只用于一键登录解密 + 设备心跳告警,
|
||||
心跳 worker 也只打印),先把清零主流程 + 审计做扎实。后续实现同协议的 JPushNotifier /
|
||||
SmsNotifier 即可替换,worker/repo 不改。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Protocol
|
||||
|
||||
logger = logging.getLogger("shagua.inactivity")
|
||||
|
||||
|
||||
class InactivityNotifier(Protocol):
|
||||
channel: str
|
||||
|
||||
def warn(self, *, user_id: int, coin: int, cash_cents: int,
|
||||
stage: int, days_until_reset: int) -> str:
|
||||
"""发预警(只涉及会被清的金币 + 折算现金;邀请现金不清、不预警)。
|
||||
返回状态:'sent' / 'failed' / 'placeholder'。"""
|
||||
...
|
||||
|
||||
|
||||
class LogNotifier:
|
||||
"""占位实现:只打印,不真推。参照 heartbeat_monitor_worker「本期先不接推送」先例。"""
|
||||
|
||||
channel = "log"
|
||||
|
||||
def warn(self, *, user_id: int, coin: int, cash_cents: int,
|
||||
stage: int, days_until_reset: int) -> str:
|
||||
logger.warning(
|
||||
"[inactivity-warn] user=%s coin=%s cash_cents=%s stage=T-%s days_until_reset=%s",
|
||||
user_id, coin, cash_cents, stage, days_until_reset,
|
||||
)
|
||||
return "placeholder"
|
||||
|
||||
|
||||
def get_notifier(channel: str) -> InactivityNotifier:
|
||||
"""按配置返回通知器。未实现的通道(jpush/sms)暂回退 LogNotifier 占位。"""
|
||||
# 后续:if channel == "jpush": return JPushNotifier()
|
||||
# if channel == "sms": return SmsNotifier()
|
||||
return LogNotifier()
|
||||
@@ -13,8 +13,7 @@ worker / 多机时内存不共享 → 冷却、校验都会失效,届时迁移
|
||||
|
||||
防刷两层(短信花钱 + `/sms/send` 在登录前无法 JWT 鉴权):
|
||||
1. 单号 `SMS_SEND_INTERVAL_SEC` 冷却(本文件)
|
||||
2. 单设备(device_id)+ IP 每小时 / 每天频控(api 层 auth.sms_send 的 check/record_rate_limits,
|
||||
**只按成功发码计数** —— 被本文件单号冷却挡下的重发不占额度)+ 极光控制台 IP 白名单/防轰炸(运维侧)。
|
||||
2. 单设备(device_id)每小时频控(api 层 auth.sms_send 内 enforce_rate_limit)+ 极光控制台 IP 白名单/防轰炸(运维侧)。
|
||||
⚠️ 原「单 IP 频控(rate_limit 依赖)」2026-06-26 按产品要求删除、改设备维度;但 device_id 客户端可伪造/轮换,
|
||||
脚本轮换 id 能绕过本层 → 挡脚本狂发主要靠极光控制台侧(+ 可选 nginx 限流)。
|
||||
⚠️ 原「单号每日上限」2026-07-03 按精简要求删除(mentor 定:登录风控只留单号冷却 + 单设备频控);
|
||||
|
||||
@@ -49,10 +49,6 @@ from app.core.heartbeat_monitor_worker import (
|
||||
start_heartbeat_monitor,
|
||||
stop_heartbeat_monitor,
|
||||
)
|
||||
from app.core.inactivity_reset_worker import (
|
||||
start_inactivity_reset_worker,
|
||||
stop_inactivity_reset_worker,
|
||||
)
|
||||
from app.core.logging import setup_logging
|
||||
from app.core.pricebot_client import aclose_pricebot_client, get_pricebot_client
|
||||
from app.core.withdraw_reconcile_worker import (
|
||||
@@ -84,14 +80,12 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
reconcile_task = start_withdraw_reconcile_worker()
|
||||
heartbeat_task = start_heartbeat_monitor()
|
||||
daily_exchange_task = start_daily_exchange_worker()
|
||||
inactivity_task = start_inactivity_reset_worker()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await stop_heartbeat_monitor(heartbeat_task)
|
||||
await stop_withdraw_reconcile_worker(reconcile_task)
|
||||
await stop_daily_exchange_worker(daily_exchange_task)
|
||||
await stop_inactivity_reset_worker(inactivity_task)
|
||||
await aclose_pricebot_client()
|
||||
logger.info("shutting down")
|
||||
|
||||
|
||||
@@ -27,16 +27,11 @@ from app.models.coupon_state import ( # noqa: F401
|
||||
CouponSession,
|
||||
)
|
||||
from app.models.feedback import Feedback # noqa: F401
|
||||
from app.models.inactivity import ( # noqa: F401
|
||||
InactivityNotificationLog,
|
||||
InactivityResetLog,
|
||||
)
|
||||
from app.models.invite import InviteRelation # noqa: F401
|
||||
from app.models.invite_fingerprint import InviteFingerprint # noqa: F401
|
||||
from app.models.launch_confirm_sample import LaunchConfirmSample # noqa: F401
|
||||
from app.models.meituan_coupon import MeituanCoupon # noqa: F401
|
||||
from app.models.onboarding import OnboardingCompletion # noqa: F401
|
||||
from app.models.phone_rebind_log import PhoneRebindLog # noqa: F401
|
||||
from app.models.ops_marquee_seed import OpsMarqueeSeed # noqa: F401
|
||||
from app.models.ops_stat_config import OpsStatConfig # noqa: F401
|
||||
from app.models.price_observation import PriceObservation # noqa: F401
|
||||
|
||||
@@ -15,7 +15,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, DateTime, Index, Integer, String, func
|
||||
from sqlalchemy import JSON, BigInteger, DateTime, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.base import Base
|
||||
@@ -23,12 +23,6 @@ from app.db.base import Base
|
||||
|
||||
class AnalyticsEvent(Base):
|
||||
__tablename__ = "analytics_event"
|
||||
__table_args__ = (
|
||||
# 活跃口径聚合热点(activity.active_event_condition + last_active_subqueries):
|
||||
# 按 (event,page) 过滤 首页可见(show/home)∪比价∪领券,再 group by user_id 取
|
||||
# max(created_at)。覆盖索引 → 该聚合走 index-only,避免高频 show 事件全表扫。
|
||||
Index("ix_analytics_event_active", "event", "page", "user_id", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
"""15 天不活跃清零相关表。
|
||||
|
||||
- inactivity_reset_log:每次清零一行,记清零前三桶余额快照 + 原因 + 判定时活跃时间/不活跃天数,
|
||||
供纠纷排查(需求①)。清零同时另写 2 条钱包流水(金币 + 折算现金,biz_type=inactivity_reset),
|
||||
资金流可逐笔回溯。**邀请现金是产品红线、不清零**,invite_cash_balance_cents_before 仅为清零时
|
||||
仍保留的邀请现金快照(便于排查、非被清金额;见 wallet.CoinAccount 注释)。
|
||||
- inactivity_notification_log:每次预警一行,记推送时余额快照 + 档位 + 通道 + 状态,
|
||||
兼作"预警去重"依据(created_at > last_active)与"待推送"占位 outbox(v1 通道=log)。
|
||||
|
||||
append-only,不更新。user_id 只索引、不设外键(同 analytics_event,避免删用户级联/历史留痕)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class InactivityResetLog(Base):
|
||||
__tablename__ = "inactivity_reset_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
|
||||
coin_balance_before: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
cash_balance_cents_before: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
invite_cash_balance_cents_before: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
last_active_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
inactive_days: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
reason: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
reset_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), index=True, nullable=False
|
||||
)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<InactivityResetLog id={self.id} user_id={self.user_id} coin={self.coin_balance_before}>"
|
||||
|
||||
|
||||
class InactivityNotificationLog(Base):
|
||||
__tablename__ = "inactivity_notification_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
|
||||
stage: Mapped[int] = mapped_column(Integer, nullable=False) # 提前天数档(如 7 / 2)
|
||||
inactive_days: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
coin_balance: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
cash_balance_cents: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
invite_cash_balance_cents: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
channel: Mapped[str] = mapped_column(String(16), nullable=False) # log / jpush / sms
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False) # placeholder / sent / failed
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), index=True, nullable=False
|
||||
)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<InactivityNotificationLog id={self.id} user_id={self.user_id} stage={self.stage}>"
|
||||
@@ -1,31 +0,0 @@
|
||||
"""手机号换绑台账。
|
||||
|
||||
记录"手机号从老账号被夺走、重建为新账号(X 注销 → Y)"这一破坏性事件,支撑"一个手机号
|
||||
30 天内最多换绑一次"的限制。手机号级、渠道无关(source 标来源);普通微信绑定不写此表。
|
||||
见 M2 spec §4.1。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class PhoneRebindLog(Base):
|
||||
__tablename__ = "phone_rebind_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
# 被换绑的真实手机号(注意:存真实号,不是老账号被腾号后的 deleted_<id>)
|
||||
phone: Mapped[str] = mapped_column(String(20), index=True, nullable=False)
|
||||
# 被注销的老账号 X;P 换绑时已被腾空(极边界)则为空
|
||||
old_user_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
# 换绑后新建的账号 Y
|
||||
new_user_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
# 换绑来源。手机号级配额、渠道无关,留字段给未来其他换绑路径共用同一份 30 天限制。
|
||||
source: Mapped[str] = mapped_column(String(32), nullable=False, default="wechat_conflict")
|
||||
rebound_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), index=True, nullable=False
|
||||
)
|
||||
@@ -1,101 +0,0 @@
|
||||
"""活跃口径唯一真源:worker(不活跃清零)与 admin(最近活跃/DAU)共用,防两处漂移。
|
||||
|
||||
口径 = max(User.created_at, AnalyticsEvent[首页可见 show/home + 比价 + 领券], CouponPromptEngagement[claim_started])。
|
||||
**不含 last_login_at**(登录/re-login 不代表在用 App);created_at 为恒非空基线。
|
||||
清零/预警按北京自然日 0 点对齐(见 reset_cutoff)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import and_, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.rewards import CN_TZ, cn_today
|
||||
from app.models.analytics_event import AnalyticsEvent
|
||||
from app.models.coupon_state import CouponPromptEngagement
|
||||
|
||||
# —— 活跃口径事件(与"用户管理"口径一致)——
|
||||
# 首页可见:前端埋点 event=show + page=home(组合判定,单个 event 名不足以区分,见
|
||||
# active_event_condition);其余为纯 event 名。
|
||||
HOME_VIEW_EVENT = "show"
|
||||
HOME_VIEW_PAGE = "home"
|
||||
COMPARE_START_EVENT = "real_compare_start" # 发起比价(含浮窗触发)
|
||||
COUPON_START_EVENT = "real_coupon_start" # 发起领券
|
||||
# 纯 event 名即可判定的活跃事件(首页可见是 event+page 组合、不在此列)
|
||||
ACTIVE_EVENTS = (COMPARE_START_EVENT, COUPON_START_EVENT)
|
||||
ACTIVE_ENGAGE_TYPE = "claim_started" # coupon_prompt_engagement 一键领取
|
||||
|
||||
|
||||
def active_event_condition():
|
||||
"""analytics_event 中算"活跃"的行为过滤:首页可见(event=show & page=home)
|
||||
∪ 发起比价 ∪ 发起领券。worker 子查询与 admin 展示共用,单一真源。"""
|
||||
return or_(
|
||||
and_(AnalyticsEvent.event == HOME_VIEW_EVENT, AnalyticsEvent.page == HOME_VIEW_PAGE),
|
||||
AnalyticsEvent.event.in_(ACTIVE_EVENTS),
|
||||
)
|
||||
|
||||
|
||||
def as_utc(value: datetime) -> datetime:
|
||||
"""任意 datetime → tz-aware UTC(无时区按 UTC 解释)。用于与 DateTime(timezone=True) 列比较,
|
||||
比较绝对时刻、与会话时区无关(口径同 admin queries._as_utc)。"""
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def norm_utc(dt: datetime | None) -> datetime | None:
|
||||
"""naive 视为 UTC 补 tzinfo(SQLite 读回 naive、PG 读回 aware,混着 max() 会 TypeError)。"""
|
||||
if dt is None:
|
||||
return None
|
||||
return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def cn_midnight_utc(d: date) -> datetime:
|
||||
"""北京 d 日 00:00 → tz-aware UTC datetime。"""
|
||||
return as_utc(datetime(d.year, d.month, d.day, tzinfo=CN_TZ))
|
||||
|
||||
|
||||
def reset_cutoff(reset_days: int, today: date | None = None) -> datetime:
|
||||
"""应清零边界(tz-aware UTC):last_active < 此值 ⟺ 距末次活跃已满 reset_days 天(北京 0 点对齐)。
|
||||
= 北京 00:00 of (today − (reset_days − 1))。例:reset_days=15、today=1/20 → 北京 1/6 00:00。"""
|
||||
today = today or cn_today()
|
||||
return cn_midnight_utc(today - timedelta(days=reset_days - 1))
|
||||
|
||||
|
||||
def last_active_subqueries(db: Session):
|
||||
"""两个按 user_id 预聚合的派生表:最近活跃事件(见 active_event_condition)、
|
||||
最近领券发起(claim_started)。返回 (ev_sub, eng_sub)。口径同 admin,LEFT JOIN 用。"""
|
||||
ev_sub = (
|
||||
select(
|
||||
AnalyticsEvent.user_id.label("user_id"),
|
||||
func.max(AnalyticsEvent.created_at).label("last_at"),
|
||||
)
|
||||
.where(AnalyticsEvent.user_id.is_not(None), active_event_condition())
|
||||
.group_by(AnalyticsEvent.user_id)
|
||||
.subquery()
|
||||
)
|
||||
eng_sub = (
|
||||
select(
|
||||
CouponPromptEngagement.user_id.label("user_id"),
|
||||
func.max(CouponPromptEngagement.created_at).label("last_at"),
|
||||
)
|
||||
.where(
|
||||
CouponPromptEngagement.user_id.is_not(None),
|
||||
CouponPromptEngagement.engage_type == ACTIVE_ENGAGE_TYPE,
|
||||
)
|
||||
.group_by(CouponPromptEngagement.user_id)
|
||||
.subquery()
|
||||
)
|
||||
return ev_sub, eng_sub
|
||||
|
||||
|
||||
def last_active_expr(base_col, ev_sub, eng_sub, dialect: str):
|
||||
"""max(base_col, 最近活跃事件, 最近领券) 的 SQL 表达式。PG 用 greatest、SQLite 用 max。
|
||||
子聚合缺失(未命中)时 coalesce 到 base_col(= User.created_at,恒非空基线)。"""
|
||||
greatest = func.greatest if dialect == "postgresql" else func.max
|
||||
return greatest(
|
||||
base_col,
|
||||
func.coalesce(ev_sub.c.last_at, base_col),
|
||||
func.coalesce(eng_sub.c.last_at, base_col),
|
||||
)
|
||||
@@ -41,6 +41,27 @@ def find_by_trans(db: Session, trans_id: str) -> AdRewardRecord | None:
|
||||
return _find_by_trans(db, trans_id)
|
||||
|
||||
|
||||
def find_reward_video_result(
|
||||
db: Session, user_id: int, ad_session_id: str
|
||||
) -> AdRewardRecord | None:
|
||||
"""按 (user_id, ad_session_id, reward_scene='reward_video') 查**最新一条**发奖记录,
|
||||
供客户端弹窗查这次广告的权威发奖结果。
|
||||
|
||||
只读、按 user_id 隔离(他人查不到)。取最新:同一会话可能先有 closed_early 留痕、S2S 延迟
|
||||
到账后又写 granted,按 (created_at, id) 倒序让 granted 覆盖早先的 closed_early。查不到返回 None。
|
||||
"""
|
||||
return db.execute(
|
||||
select(AdRewardRecord)
|
||||
.where(
|
||||
AdRewardRecord.user_id == user_id,
|
||||
AdRewardRecord.ad_session_id == ad_session_id,
|
||||
AdRewardRecord.reward_scene == "reward_video",
|
||||
)
|
||||
.order_by(AdRewardRecord.created_at.desc(), AdRewardRecord.id.desc())
|
||||
.limit(1)
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
def _granted_today(db: Session, user_id: int, reward_date: str) -> int:
|
||||
return db.execute(
|
||||
select(func.count())
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
"""15 天不活跃清零业务逻辑(纯同步,可单测)。worker 只是它的 asyncio 外壳。
|
||||
|
||||
活跃口径复用 app.repositories.activity;清零走 wallet.grant_*(负数出账、写流水、不 commit)。
|
||||
逐用户独立事务,一个失败不影响其余。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.rewards import CN_TZ
|
||||
from app.integrations.notifier import InactivityNotifier
|
||||
from app.models.inactivity import InactivityNotificationLog, InactivityResetLog
|
||||
from app.models.user import User
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import activity
|
||||
from app.repositories import wallet as wallet_repo
|
||||
|
||||
logger = logging.getLogger("shagua.inactivity")
|
||||
|
||||
RESET_BIZ_TYPE = "inactivity_reset"
|
||||
RESET_REMARK = "15天不活跃清零"
|
||||
|
||||
# 清零候选口径:金币或折算现金有余额即入选。**邀请现金不算**——它是产品红线、不清零
|
||||
# (见 wallet.CoinAccount 注释),只有邀请现金余额的用户没有可清项,故不入选。
|
||||
_ANY_BALANCE = or_(
|
||||
CoinAccount.coin_balance > 0,
|
||||
CoinAccount.cash_balance_cents > 0,
|
||||
)
|
||||
|
||||
|
||||
def _base_query(db: Session):
|
||||
"""select(user_id, last_active, 三桶余额),join CoinAccount + 两活跃子查询。"""
|
||||
ev_sub, eng_sub = activity.last_active_subqueries(db)
|
||||
dialect = db.get_bind().dialect.name
|
||||
last_active = activity.last_active_expr(User.created_at, ev_sub, eng_sub, dialect)
|
||||
stmt = (
|
||||
select(
|
||||
User.id.label("user_id"),
|
||||
last_active.label("last_active"),
|
||||
CoinAccount.coin_balance,
|
||||
CoinAccount.cash_balance_cents,
|
||||
CoinAccount.invite_cash_balance_cents,
|
||||
)
|
||||
.join(CoinAccount, CoinAccount.user_id == User.id)
|
||||
.outerjoin(ev_sub, ev_sub.c.user_id == User.id)
|
||||
.outerjoin(eng_sub, eng_sub.c.user_id == User.id)
|
||||
)
|
||||
return stmt, last_active
|
||||
|
||||
|
||||
def _cn_date(dt: datetime) -> date:
|
||||
"""datetime → 北京自然日(naive 视为 UTC)。"""
|
||||
return activity.norm_utc(dt).astimezone(CN_TZ).date()
|
||||
|
||||
|
||||
def _inactive_days(last_active: datetime, today: date) -> int:
|
||||
return (today - _cn_date(last_active)).days
|
||||
|
||||
|
||||
def select_inactive_users(db: Session, *, cutoff: datetime):
|
||||
"""应清零用户:last_active < cutoff 且金币/折算现金有余额(邀请现金不清、不计)。
|
||||
返回 Row 列表(值已快照,可跨 commit)。"""
|
||||
stmt, last_active = _base_query(db)
|
||||
stmt = stmt.where(_ANY_BALANCE, last_active < activity.as_utc(cutoff))
|
||||
return db.execute(stmt).all()
|
||||
|
||||
|
||||
def clear_user(db: Session, *, user_id: int, last_active: datetime, inactive_days: int, reason: str) -> bool:
|
||||
"""单用户清零(独立事务、行锁)。金币 + 折算现金归零 + 写审计 + 2 条流水;**邀请现金不清**
|
||||
(产品红线,见 wallet.CoinAccount 注释),仅作快照记入审计。返回是否真清了(有可清余额)。"""
|
||||
acc = wallet_repo.get_or_create_account(db, user_id, commit=False, lock=True)
|
||||
coin, cash, invite = acc.coin_balance, acc.cash_balance_cents, acc.invite_cash_balance_cents
|
||||
if coin == 0 and cash == 0: # 邀请现金不清,故不算"有可清余额"
|
||||
return False
|
||||
log = InactivityResetLog(
|
||||
user_id=user_id, coin_balance_before=coin, cash_balance_cents_before=cash,
|
||||
invite_cash_balance_cents_before=invite, last_active_at=activity.norm_utc(last_active),
|
||||
inactive_days=inactive_days, reason=reason,
|
||||
)
|
||||
db.add(log)
|
||||
db.flush() # 拿 log.id 作 ref_id 交叉链接审计↔流水
|
||||
ref = str(log.id)
|
||||
if coin:
|
||||
wallet_repo.grant_coins(db, user_id, -coin, biz_type=RESET_BIZ_TYPE, ref_id=ref, remark=RESET_REMARK)
|
||||
if cash:
|
||||
wallet_repo.grant_cash(db, user_id, -cash, biz_type=RESET_BIZ_TYPE, ref_id=ref, remark=RESET_REMARK)
|
||||
# 邀请现金(invite_cash_balance_cents)刻意不动:两本账物理隔离、邀请金是产品红线。
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def run_reset_once(db: Session, *, reset_days: int, today: date) -> dict:
|
||||
"""扫一轮清零。逐用户独立 commit,失败隔离。"""
|
||||
stats = {"scanned": 0, "cleared": 0, "failed": 0}
|
||||
cutoff = activity.reset_cutoff(reset_days, today)
|
||||
reason = f"inactive_{reset_days}d"
|
||||
rows = select_inactive_users(db, cutoff=cutoff) # 先物化,避免边遍历边 commit
|
||||
for row in rows:
|
||||
stats["scanned"] += 1
|
||||
idays = _inactive_days(row.last_active, today)
|
||||
try:
|
||||
if clear_user(db, user_id=row.user_id, last_active=row.last_active,
|
||||
inactive_days=idays, reason=reason):
|
||||
stats["cleared"] += 1
|
||||
except SQLAlchemyError:
|
||||
db.rollback()
|
||||
stats["failed"] += 1
|
||||
return stats
|
||||
|
||||
|
||||
def select_warn_candidates(db: Session, *, clear_cutoff: datetime, warn_hi: datetime):
|
||||
"""预警候选:clear_cutoff <= last_active < warn_hi 且有可清余额(即已进预警窗、尚未到清零)。"""
|
||||
stmt, last_active = _base_query(db)
|
||||
stmt = stmt.where(
|
||||
_ANY_BALANCE,
|
||||
last_active >= activity.as_utc(clear_cutoff),
|
||||
last_active < activity.as_utc(warn_hi),
|
||||
)
|
||||
return db.execute(stmt).all()
|
||||
|
||||
|
||||
def run_warn_once(db: Session, notifier: InactivityNotifier, *,
|
||||
reset_days: int, warn_stages: list[int], today: date) -> dict:
|
||||
"""扫一轮预警。每人取"最紧急的已到达档",按 streak 去重(notification_log.created_at > last_active)。
|
||||
预警只涉及会被清的金币 + 折算现金;邀请现金不清、不预警(仅在 notification_log 记快照)。
|
||||
逐用户 try/except 隔离:单用户通知器抛错 / DB 错不阻断其余,也绝不能拖累后续清零。"""
|
||||
stats = {"warned": 0, "warn_skipped": 0, "warn_failed": 0}
|
||||
if not warn_stages:
|
||||
return stats
|
||||
clear_cutoff = activity.reset_cutoff(reset_days, today) # 到此即清零,不再预警
|
||||
warn_hi = activity.reset_cutoff(reset_days - max(warn_stages), today) # 最早预警档边界
|
||||
ascending = sorted(warn_stages) # 最紧急(最小 k)在前
|
||||
for row in select_warn_candidates(db, clear_cutoff=clear_cutoff, warn_hi=warn_hi):
|
||||
idays = _inactive_days(row.last_active, today)
|
||||
stage = next((k for k in ascending if idays >= reset_days - k), None)
|
||||
if stage is None: # 防御:候选已在预警窗内、stage 必命中,此分支实际不可达
|
||||
continue
|
||||
try:
|
||||
already = db.execute(
|
||||
select(InactivityNotificationLog.id).where(
|
||||
InactivityNotificationLog.user_id == row.user_id,
|
||||
InactivityNotificationLog.stage == stage,
|
||||
InactivityNotificationLog.created_at > activity.as_utc(row.last_active),
|
||||
).limit(1)
|
||||
).first()
|
||||
if already:
|
||||
stats["warn_skipped"] += 1
|
||||
continue
|
||||
status = notifier.warn(
|
||||
user_id=row.user_id, coin=row.coin_balance, cash_cents=row.cash_balance_cents,
|
||||
stage=stage, days_until_reset=reset_days - idays,
|
||||
)
|
||||
db.add(InactivityNotificationLog(
|
||||
user_id=row.user_id, stage=stage, inactive_days=idays,
|
||||
coin_balance=row.coin_balance, cash_balance_cents=row.cash_balance_cents,
|
||||
invite_cash_balance_cents=row.invite_cash_balance_cents, # 快照,不参与"将清"额度
|
||||
channel=notifier.channel, status=status,
|
||||
))
|
||||
db.commit()
|
||||
stats["warned"] += 1
|
||||
except Exception: # noqa: BLE001 - 单用户预警失败(通知器抛错/DB 错)隔离,不阻断其余、不拖累清零
|
||||
db.rollback()
|
||||
stats["warn_failed"] += 1
|
||||
return stats
|
||||
|
||||
|
||||
def run_once(db: Session, *, notifier: InactivityNotifier, reset_days: int,
|
||||
warn_stages: list[int], today: date) -> dict:
|
||||
"""一轮完整任务:先预警(阶段 A)再清零(阶段 B)。返回合并统计。
|
||||
预警整段异常也**绝不阻塞清零**——清零是核心、不可逆资金操作,不能被通知故障拖住。"""
|
||||
try:
|
||||
warn = run_warn_once(db, notifier, reset_days=reset_days, warn_stages=warn_stages, today=today)
|
||||
except Exception: # noqa: BLE001 - 预警阶段整体失败(如候选查询失败)也要继续清零
|
||||
logger.exception("inactivity warn phase failed; proceeding to reset")
|
||||
db.rollback()
|
||||
warn = {"warned": 0, "warn_skipped": 0, "warn_failed": 0, "warn_phase_error": 1}
|
||||
reset = run_reset_once(db, reset_days=reset_days, today=today)
|
||||
return {**warn, **reset}
|
||||
@@ -1,39 +0,0 @@
|
||||
"""手机号换绑台账(phone_rebind_log)的查询与写入。见 M2 spec §4.1。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.phone_rebind_log import PhoneRebindLog
|
||||
|
||||
|
||||
def rebound_within_days(db: Session, phone: str, days: int) -> bool:
|
||||
"""该手机号在最近 days 天内是否换绑过(命中 → 禁止再次换绑)。"""
|
||||
since = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
stmt = (
|
||||
select(PhoneRebindLog.id)
|
||||
.where(PhoneRebindLog.phone == phone, PhoneRebindLog.rebound_at >= since)
|
||||
.limit(1)
|
||||
)
|
||||
return db.execute(stmt).first() is not None
|
||||
|
||||
|
||||
def remaining_block_days(db: Session, phone: str, days: int) -> int:
|
||||
"""距离该手机号可再次换绑还剩几天(向上取整;无记录返回 0)。"""
|
||||
last = db.execute(
|
||||
select(func.max(PhoneRebindLog.rebound_at)).where(PhoneRebindLog.phone == phone)
|
||||
).scalar_one_or_none()
|
||||
if last is None:
|
||||
return 0
|
||||
if last.tzinfo is None: # SQLite 取回 naive datetime,按 UTC 归一
|
||||
last = last.replace(tzinfo=timezone.utc)
|
||||
remaining = (last + timedelta(days=days) - datetime.now(timezone.utc)).total_seconds()
|
||||
return max(0, math.ceil(remaining / 86400))
|
||||
|
||||
|
||||
def add_rebind_log(db: Session, *, phone: str, old_user_id: int | None, new_user_id: int, source: str) -> None:
|
||||
"""写一条换绑台账(**不 commit**,交给调用方 rebind_account 的单事务)。"""
|
||||
db.add(PhoneRebindLog(phone=phone, old_user_id=old_user_id, new_user_id=new_user_id, source=source))
|
||||
@@ -12,7 +12,6 @@ from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.user import User
|
||||
from app.repositories import phone_rebind
|
||||
|
||||
|
||||
# ===== 创建时分配的标识:用户名(对外展示账号 ID)+ 默认昵称 =====
|
||||
@@ -59,17 +58,6 @@ def is_default_nickname(nickname: str | None) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def apply_wechat_display_identity(
|
||||
user: User, *, wechat_nickname: str | None, wechat_avatar_url: str | None
|
||||
) -> None:
|
||||
"""§10:用已有账号绑微信时,仅当展示字段仍为默认才用微信昵称/头像替换(两规则独立);
|
||||
自定义(改过昵称/传过头像)则保留。只改内存对象,由调用方 commit。"""
|
||||
if is_default_nickname(user.nickname) and wechat_nickname:
|
||||
user.nickname = wechat_nickname
|
||||
if user.avatar_url is None and wechat_avatar_url:
|
||||
user.avatar_url = wechat_avatar_url
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str) -> User | None:
|
||||
return db.execute(
|
||||
select(User).where(User.username == username)
|
||||
@@ -98,85 +86,6 @@ def get_user_by_phone(db: Session, phone: str) -> User | None:
|
||||
return db.execute(stmt).scalar_one_or_none()
|
||||
|
||||
|
||||
def get_user_by_wechat_openid(db: Session, openid: str) -> User | None:
|
||||
stmt = select(User).where(User.wechat_openid == openid)
|
||||
return db.execute(stmt).scalar_one_or_none()
|
||||
|
||||
|
||||
def touch_last_login(db: Session, user: User) -> User:
|
||||
"""openid 命中登录时更新 last_login_at(手机号登录在 upsert_user_for_login 里已更新)。"""
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def attach_wechat_to_user(
|
||||
db: Session, user: User, *, openid: str, wechat_nickname: str | None, wechat_avatar_url: str | None
|
||||
) -> User:
|
||||
"""继续绑定:把微信 openid + 微信源字段并入已存在账号(调用方保证 user.wechat_openid 为空)。
|
||||
|
||||
写 wechat_openid / wechat_nickname / wechat_avatar_url,并按 §10 规则回填展示字段:
|
||||
仅当昵称仍为默认值(is_default_nickname)时用微信昵称替换,仅当头像为 null 时用微信头像替换;
|
||||
用户已自定义的展示昵称/头像始终保留,两规则相互独立。
|
||||
撞 openid 唯一约束(O 期间被别处绑走,极罕见)时由调用方捕获 IntegrityError 兜底降级为"只登入不绑"。
|
||||
"""
|
||||
user.wechat_openid = openid
|
||||
user.wechat_nickname = wechat_nickname
|
||||
user.wechat_avatar_url = wechat_avatar_url
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
apply_wechat_display_identity(user, wechat_nickname=wechat_nickname, wechat_avatar_url=wechat_avatar_url)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _build_wechat_user(
|
||||
db: Session,
|
||||
*,
|
||||
phone: str,
|
||||
openid: str,
|
||||
wechat_nickname: str | None,
|
||||
wechat_avatar_url: str | None,
|
||||
) -> User:
|
||||
"""构造并 db.add 一个微信账号行(register_channel='wechat',展示昵称头像取微信,缺则默认),
|
||||
**不 commit**。create_wechat_user 与 rebind_account 共用,保证建号逻辑单一来源。"""
|
||||
user = User(
|
||||
phone=phone,
|
||||
username=_gen_unique_username(db),
|
||||
nickname=wechat_nickname or _gen_nickname(),
|
||||
avatar_url=wechat_avatar_url,
|
||||
register_channel="wechat",
|
||||
wechat_openid=openid,
|
||||
wechat_nickname=wechat_nickname,
|
||||
wechat_avatar_url=wechat_avatar_url,
|
||||
last_login_at=datetime.now(timezone.utc),
|
||||
)
|
||||
db.add(user)
|
||||
return user
|
||||
|
||||
|
||||
def create_wechat_user(
|
||||
db: Session,
|
||||
*,
|
||||
phone: str,
|
||||
openid: str,
|
||||
wechat_nickname: str | None,
|
||||
wechat_avatar_url: str | None,
|
||||
) -> User:
|
||||
"""微信登录新建账号(未占用分支)。见 _build_wechat_user。
|
||||
|
||||
openid 唯一约束是并发/重复绑定的最终防线(极罕见,openid 在 wechat-login 刚查过为空)。
|
||||
"""
|
||||
user = _build_wechat_user(
|
||||
db, phone=phone, openid=openid,
|
||||
wechat_nickname=wechat_nickname, wechat_avatar_url=wechat_avatar_url,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def upsert_user_for_login(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -245,44 +154,3 @@ def soft_delete_account(db: Session, user: User) -> None:
|
||||
# 释放邀请码唯一槽
|
||||
user.invite_code = None
|
||||
db.commit()
|
||||
|
||||
|
||||
def rebind_account(
|
||||
db: Session,
|
||||
*,
|
||||
phone: str,
|
||||
openid: str,
|
||||
wechat_nickname: str | None,
|
||||
wechat_avatar_url: str | None,
|
||||
source: str = "wechat_conflict",
|
||||
) -> User:
|
||||
"""换绑:**单事务内**注销老账号 X(腾出手机号)+ 用该号建全新微信账号 Y + 写换绑台账。
|
||||
|
||||
- 老账号可能已不存在(P 被腾空)→ old_user_id=None,直接建 Y(幂等更稳)。
|
||||
- 手机号唯一约束靠时序:先把 X.phone 改名并 flush 腾号,再插 Y。
|
||||
- 全程不中途 commit,任一步失败整体回滚,绝不出现"X 删了 Y 没建"。
|
||||
X 的字段变更等价 soft_delete_account(软删 + 匿名化 + 释放 openid/邀请码唯一槽),但不在此 commit。
|
||||
"""
|
||||
old = get_user_by_phone(db, phone)
|
||||
old_id = old.id if old is not None else None
|
||||
if old is not None:
|
||||
old.status = "deleted"
|
||||
old.phone = f"deleted_{old.id}"
|
||||
old.nickname = None
|
||||
old.avatar_url = None
|
||||
old.wechat_openid = None
|
||||
old.wechat_nickname = None
|
||||
old.wechat_avatar_url = None
|
||||
old.invite_code = None
|
||||
db.flush() # 先落 phone 改名,腾出手机号唯一约束,才能给 Y 用
|
||||
new_user = _build_wechat_user(
|
||||
db, phone=phone, openid=openid,
|
||||
wechat_nickname=wechat_nickname, wechat_avatar_url=wechat_avatar_url,
|
||||
)
|
||||
db.flush() # 拿 new_user.id
|
||||
phone_rebind.add_rebind_log(
|
||||
db, phone=phone, old_user_id=old_id, new_user_id=new_user.id, source=source
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
return new_user
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.core.config import settings
|
||||
from app.core.rewards import COIN_PER_CENT, coins_to_cents
|
||||
from app.integrations import wxpay
|
||||
from app.models.user import User
|
||||
from app.repositories.user import apply_wechat_display_identity
|
||||
from app.models.wallet import (
|
||||
CashTransaction,
|
||||
CoinAccount,
|
||||
@@ -35,10 +34,6 @@ _WX_STATE_SUCCESS = "SUCCESS"
|
||||
_WX_STATE_FAILED = {"FAIL", "CANCELLED", "CLOSED"}
|
||||
_WX_STATE_WAIT_CONFIRM = "WAIT_USER_CONFIRM" # 用户还没在微信确认页确认
|
||||
_WITHDRAW_ACTIVE_STATUSES = {"reviewing", "pending"}
|
||||
# 占用新人档「一次性」资格的提现状态:进行中(reviewing/pending)或成功打款(success)。
|
||||
# 被拒/转账失败/解绑退回(rejected/failed,均已退款、钱没到手)不在此列 → 新人档恢复可提
|
||||
# (2026-07-16 修正:此前判定不看状态,解绑微信退回后 0.1 被误判已用、资格永久锁死)。
|
||||
_NEWBIE_TIER_HELD_STATUSES = {"reviewing", "pending", "success"}
|
||||
# 免确认收款授权状态
|
||||
_WX_AUTH_ACTIVE = "TAKING_EFFECT" # 已生效,可免确认转账
|
||||
_WX_AUTH_CLOSED = "CLOSED" # 已关闭(用户/商户/风控),需重新开启
|
||||
@@ -379,7 +374,6 @@ def bind_wechat_openid(db: Session, user_id: int, code: str) -> dict:
|
||||
user.wechat_openid = info["openid"]
|
||||
user.wechat_nickname = info["nickname"]
|
||||
user.wechat_avatar_url = info["avatar_url"]
|
||||
apply_wechat_display_identity(user, wechat_nickname=info["nickname"], wechat_avatar_url=info["avatar_url"])
|
||||
db.commit()
|
||||
return info
|
||||
|
||||
@@ -628,10 +622,9 @@ def _beijing_today_start_utc() -> datetime:
|
||||
def withdraw_tier_states(db: Session, user_id: int, source: str = "coin_cash") -> list[dict]:
|
||||
"""福利页(coin_cash)提现档位的可提现状态。withdraw-info 下发与 create_withdraw 校验共用此口径。
|
||||
|
||||
规则(2026-07-09 拍板,7-9提现ui对齐;新人档判定 2026-07-16 修正):
|
||||
- 新人档(0.1/0.3):账号历史一次性——进行中(reviewing/pending)或成功打款(success)即视为
|
||||
已用,直接**从返回列表消失**;被拒/转账失败/解绑退回(均已退款、钱没到手)则恢复可提,不永久
|
||||
占用资格。两档各自独立互不影响,不参与"每日选一个额度"互斥。
|
||||
规则(2026-07-09 拍板,7-9提现ui对齐):
|
||||
- 新人档(0.1/0.3):账号历史一次性——只要发起过(**任意状态**,含被拒/失败,"发起就算")
|
||||
即视为已用,直接**从返回列表消失**;两档各自独立互不影响,不参与"每日选一个额度"互斥。
|
||||
- 常规档(0.5×3 / 10×1 / 20×1):按北京日计次,"发起就算占用"(当天创建的单不论最终状态
|
||||
都计入,被拒/失败不退当天名额);三档每天只能选一个,选定后其余两档当天 other_tier_selected。
|
||||
- invite_cash 本轮无档位概念 → 返回空列表(邀请页客户端仍用本地写死档位,行为不变)。
|
||||
@@ -642,7 +635,7 @@ def withdraw_tier_states(db: Session, user_id: int, source: str = "coin_cash") -
|
||||
tiers = rewards.WITHDRAW_TIERS_COIN_CASH
|
||||
amounts = [t.amount_cents for t in tiers]
|
||||
newbie_amounts = [t.amount_cents for t in tiers if t.is_newbie]
|
||||
# 新人档历史是否用过:进行中或已成功打款的单占用资格;被拒/失败/解绑退回(已退款)不算(恢复可提)
|
||||
# 新人档历史是否用过:任意时间、任意状态("发起就算")
|
||||
used_newbie: set[int] = set(
|
||||
db.execute(
|
||||
select(WithdrawOrder.amount_cents)
|
||||
@@ -651,7 +644,6 @@ def withdraw_tier_states(db: Session, user_id: int, source: str = "coin_cash") -
|
||||
WithdrawOrder.user_id == user_id,
|
||||
WithdrawOrder.source == "coin_cash",
|
||||
WithdrawOrder.amount_cents.in_(newbie_amounts),
|
||||
WithdrawOrder.status.in_(_NEWBIE_TIER_HELD_STATUSES),
|
||||
)
|
||||
).scalars()
|
||||
) if newbie_amounts else set()
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -43,6 +44,23 @@ class AdRewardStatusOut(BaseModel):
|
||||
watch_seconds_remaining: int = Field(0, description="今日剩余可观看秒数;limit=0 时客户端不据此拦截")
|
||||
|
||||
|
||||
class AdRewardResultOut(BaseModel):
|
||||
"""客户端弹窗按 `ad_session_id` 查这次广告服务端**权威发奖结果**,只展示这个数字。
|
||||
|
||||
- `pending`:本人没有该会话的 reward_video 记录(S2S 尚未到账)——客户端继续有限重试,
|
||||
**别把"未到账"当成 0 金币**,`coin=null`。
|
||||
- `granted`:返回真实到账金币 `coin`(>0)。
|
||||
- `capped`:达每日上限,`coin=0`,客户端走上限提示而非"获得 0 金币"。
|
||||
- `closed_early` / `ecpm_missing`:终态,`coin=0`,**不能伪装成 granted**。
|
||||
|
||||
不返回 eCPM、回调原文或其他用户信息。
|
||||
"""
|
||||
|
||||
ad_session_id: str
|
||||
status: Literal["pending", "granted", "capped", "closed_early", "ecpm_missing"]
|
||||
coin: int | None = None
|
||||
|
||||
|
||||
class EcpmReportIn(BaseModel):
|
||||
"""客户端上报一次广告展示的 eCPM(内部收益统计/对账)。
|
||||
|
||||
|
||||
@@ -102,64 +102,3 @@ class RefreshRequest(BaseModel):
|
||||
|
||||
class LogoutResponse(BaseModel):
|
||||
ok: bool = True
|
||||
|
||||
|
||||
# ===== 微信登录 =====
|
||||
|
||||
class WechatLoginRequest(BaseModel):
|
||||
code: str = Field(..., min_length=1, description="微信 App 授权拿到的 code(单次有效)")
|
||||
device_id: str = Field(
|
||||
"", max_length=64,
|
||||
description="硬件级设备标识(Android ANDROID_ID),用于新手引导按 设备+账号 去重;空=按未完成处理",
|
||||
)
|
||||
|
||||
|
||||
class WechatLoginResponse(BaseModel):
|
||||
# status="logged_in" → openid 命中,token 有值;"need_bind_phone" → 未命中,bind_ticket 有值
|
||||
status: str
|
||||
token: TokenWithUser | None = None
|
||||
bind_ticket: str | None = None
|
||||
wechat_nickname: str | None = None
|
||||
wechat_avatar_url: str | None = None
|
||||
|
||||
|
||||
class OccupiedAccountInfo(BaseModel):
|
||||
"""手机号被占用时返回的原账号脱敏展示信息(供冲突页)。"""
|
||||
nickname: str | None = None
|
||||
avatar_url: str | None = None
|
||||
created_at: datetime
|
||||
has_wechat: bool = False
|
||||
|
||||
|
||||
class WechatBindResultResponse(BaseModel):
|
||||
# status="logged_in" → 未占用,已建号登入,token 有值;
|
||||
# "phone_occupied" → 手机号被占用,occupied_account + conflict_ticket 有值,token 为 None
|
||||
status: str
|
||||
token: TokenWithUser | None = None
|
||||
occupied_account: OccupiedAccountInfo | None = None
|
||||
conflict_ticket: str | None = None # 占用时签发,换绑/继续绑定只认它
|
||||
rebind_available: bool | None = None # 该手机号 30 天内是否还能换绑(给换绑按钮预置禁用态)
|
||||
rebind_blocked_days: int | None = None # 被限时剩余天数(rebind_available=False 时>0)
|
||||
|
||||
|
||||
class WechatBindPhoneSmsRequest(BaseModel):
|
||||
bind_ticket: str = Field(..., min_length=1)
|
||||
phone: str = Field(..., min_length=11, max_length=11, pattern=r"^1\d{10}$")
|
||||
code: str = Field(..., min_length=4, max_length=8)
|
||||
device_id: str = Field("", max_length=64)
|
||||
|
||||
|
||||
class WechatBindPhoneJverifyRequest(BaseModel):
|
||||
bind_ticket: str = Field(..., min_length=1)
|
||||
login_token: str = Field(..., min_length=1, description="客户端 loginAuth 拿到的 loginToken")
|
||||
device_id: str = Field("", max_length=64)
|
||||
|
||||
|
||||
class WechatConflictContinueRequest(BaseModel):
|
||||
conflict_ticket: str = Field(..., min_length=1)
|
||||
device_id: str = Field("", max_length=64)
|
||||
|
||||
|
||||
class WechatConflictRebindRequest(BaseModel):
|
||||
conflict_ticket: str = Field(..., min_length=1)
|
||||
device_id: str = Field("", max_length=64)
|
||||
|
||||
@@ -42,8 +42,6 @@
|
||||
| `ad_ecpm_record` | 广告展示 eCPM 上报(收益对账) | `models/ad_ecpm.py` | [详情](./ad_ecpm_record.md) |
|
||||
| `ad_feed_reward_record` | 信息流/Draw 广告结算记录(10 秒一份,client_event_id 幂等;`ad_type`+`feed_scene` 分形态/场景) | `models/ad_feed_reward.py` | [详情](./ad_feed_reward_record.md) |
|
||||
| `ad_pangle_daily_revenue` | 穿山甲 GroMore 后台收益日表(定时拉取,收益报表/大盘真实收益源,#92) | `models/ad_pangle_revenue.py` | [详情](./ad_pangle_daily_revenue.md) |
|
||||
| `inactivity_reset_log` | 15 天不活跃清零审计(每次清零一行;清零前三桶余额快照+原因+不活跃天数;只清金币+现金,邀请金仅快照) | `models/inactivity.py` | [详情](./inactivity_reset_log.md) |
|
||||
| `inactivity_notification_log` | 不活跃清零前预警记录(余额快照+档位+通道+状态;streak 去重依据 + 占位 outbox) | `models/inactivity.py` | [详情](./inactivity_notification_log.md) |
|
||||
|
||||
### 比价 / 省钱
|
||||
| 表 | 用途 | 模型 | 文档 |
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# inactivity_notification_log — 不活跃清零前预警记录
|
||||
|
||||
> 模型 `app/models/inactivity.py` · 仓库 `app/repositories/inactivity.py` · 通知器 `app/integrations/notifier.py` · [← 索引](./README.md) · [总览](./OVERVIEW.md)
|
||||
|
||||
清零前按可配置节奏(`INACTIVITY_WARN_DAYS_BEFORE`,默认清零前 7 天、2 天各一次)向用户预警"账户里的 xx 金币和 xx 现金将被清零"。每发一次预警写一行,记推送时的余额快照 + 提前天数档 + 通道 + 状态。兼作两用:**预警去重**依据(同 streak 内 `stage==k 且 created_at > last_active` 即已推过、不重推)与**占位 outbox**(v1 通道=`log`,只打日志不真推;后续接 JPush/短信同层扩展)。append-only,不更新。**预警只涉及会被清的金币 + 折算现金;邀请奖励金不清、不预警**(`invite_cash_balance_cents` 仅作账户状态快照)。
|
||||
|
||||
## 用在哪 / 增删改查
|
||||
- **C(插入)**:`inactivity.run_warn_once` 命中预警档、且本 streak 未推过时,调 `notifier.warn` 后写一行(`status` = 通知器返回,占位实现为 `placeholder`)。
|
||||
- **U / D**:无(append-only)。
|
||||
- **R**:预警去重查询(`user_id + stage + created_at > last_active`);未来接真实推送时作待推送 outbox。
|
||||
|
||||
## 字段
|
||||
| 列 | 类型 | 约束 / 默认 | 说明(取值 / join) |
|
||||
|---|---|---|---|
|
||||
| `id` | Integer | **PK**, autoincrement | 主键 |
|
||||
| `user_id` | Integer | NOT NULL, index | 预警对象;只索引不设外键(同 `analytics_event`) |
|
||||
| `stage` | Integer | NOT NULL | 提前天数档(如 `7` / `2`,即清零前第几天推) |
|
||||
| `inactive_days` | Integer | NOT NULL | 推送时的不活跃天数(北京自然日) |
|
||||
| `coin_balance` | Integer | NOT NULL | 推送时金币余额快照(将被清) |
|
||||
| `cash_balance_cents` | Integer | NOT NULL | 推送时折算现金余额快照(分,将被清) |
|
||||
| `invite_cash_balance_cents` | Integer | NOT NULL | 推送时**邀请奖励金**余额快照(分,**不清、不在预警额度内**) |
|
||||
| `channel` | String(16) | NOT NULL | 通道:`log`(占位) / `jpush` / `sms` |
|
||||
| `status` | String(16) | NOT NULL | 状态:`placeholder`(占位未真推) / `sent` / `failed` |
|
||||
| `created_at` | DateTime(tz) | server_default now(), index | 推送时刻;去重比 `created_at > last_active`(用户回归后 `last_active` 前移 → 旧行自然失效、开启新 streak) |
|
||||
|
||||
## 关系 / Join Key
|
||||
- `user_id` → `user.id`(无外键直连,靠 `user_id` 关联)。
|
||||
- 与 `inactivity_reset_log` 无直接外键;同一 streak 内先有若干预警行,到期后有一行清零。
|
||||
|
||||
## 索引与约束
|
||||
- PK `id`;`ix_inactivity_notification_log_user_id`、`ix_inactivity_notification_log_created_at`。
|
||||
|
||||
## 注意
|
||||
- **预警去重按 streak**:判据是 `created_at > last_active`;用户一有活跃(`home_view`/比价/领券),`last_active` 前移,旧预警行"失效",回归后可重新进入预警。
|
||||
- **占位实现**:v1 `LogNotifier` 只 `logger.warning("[inactivity-warn] ...")`、返回 `placeholder`,不真推(参照心跳告警"本期先不接推送"先例)。
|
||||
- **漏跑补发**:worker 漏跑数天后某用户可能同时满足多档,只补发**最紧急的未推档**(最小提前天数),避免刷屏。
|
||||
@@ -1,35 +0,0 @@
|
||||
# inactivity_reset_log — 15 天不活跃清零审计
|
||||
|
||||
> 模型 `app/models/inactivity.py` · 仓库 `app/repositories/inactivity.py` · worker `app/core/inactivity_reset_worker.py` · [← 索引](./README.md) · [总览](./OVERVIEW.md)
|
||||
|
||||
连续 15 天不活跃(北京自然日,活跃口径见 `app/repositories/activity.py`:`home_view` + 发起比价 + 发起领券,**不含登录**)的用户,worker 每日自动清零其**金币 + 折算现金**。每清一个用户写一行,记清零前三桶余额快照 + 原因 + 判定时的活跃时间/不活跃天数,供纠纷排查。清零同时另写 2 条钱包流水(`coin_transaction` / `cash_transaction`,`biz_type=inactivity_reset`,`ref_id=` 本表 `id`),资金流可逐笔回溯、人工恢复。**邀请奖励金(`invite_cash_balance_cents`)是产品红线、不清零**,本表 `invite_cash_balance_cents_before` 仅为清零时仍保留的邀请金快照(非被清金额)。append-only,不更新。
|
||||
|
||||
## 用在哪 / 增删改查
|
||||
- **C(插入)**:`inactivity.clear_user` 逐用户清零(独立事务、行锁)时写一行,`db.flush()` 拿 `id` 作流水 `ref_id` 交叉链接。
|
||||
- **U / D**:无(append-only 审计)。
|
||||
- **R**:纠纷排查 / 对账(与 `coin_transaction` / `cash_transaction` 的 `ref_id` 交叉核对)。
|
||||
|
||||
## 字段
|
||||
| 列 | 类型 | 约束 / 默认 | 说明(取值 / join) |
|
||||
|---|---|---|---|
|
||||
| `id` | Integer | **PK**, autoincrement | 主键;作 `ref_id` 写入两条清零流水 |
|
||||
| `user_id` | Integer | NOT NULL, index | 被清零用户;只索引不设外键(同 `analytics_event`,避免删用户级联 / 留历史) |
|
||||
| `coin_balance_before` | Integer | NOT NULL | 清零前金币余额(个数);= 对应 `coin_transaction.amount` 绝对值 |
|
||||
| `cash_balance_cents_before` | Integer | NOT NULL | 清零前折算现金余额(分);= 对应 `cash_transaction.amount_cents` 绝对值 |
|
||||
| `invite_cash_balance_cents_before` | Integer | NOT NULL | 清零时的**邀请奖励金**余额快照(分)——**不清、原封保留**,仅记录以证明"未动邀请金" |
|
||||
| `last_active_at` | DateTime(tz) | nullable | 判定时的最近活跃时刻(UTC);无任何活跃信号时兜底为 `user.created_at` |
|
||||
| `inactive_days` | Integer | NOT NULL | 判定时的不活跃天数(北京自然日) |
|
||||
| `reason` | String(32) | NOT NULL | 清零原因,如 `inactive_15d` |
|
||||
| `reset_at` | DateTime(tz) | server_default now(), index | 清零时刻 |
|
||||
|
||||
## 关系 / Join Key
|
||||
- `user_id` → `user.id`(无外键直连,靠 `user_id` 关联)。
|
||||
- `id` → `coin_transaction.ref_id` / `cash_transaction.ref_id`(`biz_type=inactivity_reset`):审计行 ↔ 资金流水交叉对账。
|
||||
|
||||
## 索引与约束
|
||||
- PK `id`;`ix_inactivity_reset_log_user_id`(按用户查)、`ix_inactivity_reset_log_reset_at`(按时间查)。
|
||||
|
||||
## 注意
|
||||
- **只清 2 桶**:金币 + 折算现金;**邀请现金不清**(两本账物理隔离,见 [`coin_account`](./coin_account.md) / `wallet.CoinAccount` 注释)。
|
||||
- **天然幂等**:清完余额=0,次日不再匹配;worker 重启 / 多次唤醒 / 补跑都不会重复清零或重复流水。
|
||||
- **总闸默认关**(`INACTIVITY_RESET_ENABLED=false`),灰度验证清零名单后再开。
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,296 +0,0 @@
|
||||
# 15 天不活跃自动清零(金币 + 现金)设计
|
||||
|
||||
- **日期**:2026-07-16
|
||||
- **状态**:Draft — 待评审
|
||||
- **所属**:app-server(`app/`),含一处 admin 侧重构 + 一项 Android 端埋点依赖
|
||||
- **一句话**:连续 15 天不活跃的用户,自动清零其金币与现金;清零前按可配置节奏预警;全过程留审计以备纠纷排查。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
运营需要对**长期不活跃**用户的钱包余额做清理。两条硬性要求:
|
||||
|
||||
1. **可审计**:记录清零原因与**清零前的三桶余额**,便于后续排查与处理客户纠纷。
|
||||
2. **临清预警**:在临近清零前推送信息告知用户"因账号不活跃,账户里的 xx 金币和 xx 现金将被清零"。
|
||||
|
||||
### 非目标(本期不做)
|
||||
|
||||
- 不做真实推送通道(极光 JPush / 短信)的对接 —— 仅做**可插拔通知器 + 日志占位**,接口预留、后续无缝替换。
|
||||
- 不改动提现(`WithdrawOrder`)流程。
|
||||
- 不新增 `User.last_active_at` 列、不改鉴权热路径。
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求
|
||||
|
||||
| # | 需求 | 落地 |
|
||||
|---|---|---|
|
||||
| R1 | 连续 15 天不活跃 → 清零金币 + 现金 | 每日 worker 扫描 + 逐用户事务清零(§6) |
|
||||
| R2 | 记录清零原因 + 清零前余额 | `inactivity_reset_log` 审计表 + 3 条钱包流水(§5、§7) |
|
||||
| R3 | 临清前预警"xx 金币 xx 现金将清零" | 阶段 A 预警 + `inactivity_notification_log`(§6、§7) |
|
||||
| R4 | 活跃口径与"用户管理"一致 | 抽共享模块 `activity.py`,admin 与 worker 共用(§4、§12) |
|
||||
| R5 | 预警时机完全可配置 | `INACTIVITY_*` 配置项(§8) |
|
||||
|
||||
---
|
||||
|
||||
## 3. 决策记录(来自评审问答)
|
||||
|
||||
| 决策点 | 结论 | 理由 |
|
||||
|---|---|---|
|
||||
| **活跃口径** | 与"用户管理"一致:`max(首页可见 show/home, 比价, 领券)`,**不含 last_login_at**;无任何信号时以 `created_at` 为非空基线 | 比价可从**浮窗**触发、不进首页;`last_login_at` 只在登录/换绑动作更新(re-login 也算),代表不了"在用 App",故彻底排除 |
|
||||
| **"进首页"信号落地** | **方案 A:前端上报 `home_view` 埋点**(复用 `/analytics/events`),非新接口 | 三个活跃信号统一为同类埋点事件;零新接口零新列;与 admin 口径天然一致。B(鉴权接口 + 列)"更权威"的优势是假的——比价/领券仍是端上报事件,最弱环决定整体可信度 |
|
||||
| **清零范围** | **金币 + 折算现金**(**邀请现金不清**——产品红线,仅快照入审计) | 对应"账户里的金币和现金";邀请奖励金与金币现金物理隔离、不可累加,见 `wallet.CoinAccount` 注释 |
|
||||
| **预警推送** | **可插拔通知器 + 日志占位**(v1),后续接 JPush/短信 | 现状无真实推送能力;先把清零主流程 + 审计做扎实,不阻塞 |
|
||||
| **预警时机** | **完全可配置**(提前天数列表 + 次数 + 执行点 + 通道) | R5 |
|
||||
| **触发方式** | **进程内每日 worker**,仿 `daily_exchange_worker` | 与项目最新模式一致,无需外部 cron |
|
||||
| **admin 共享口径** | 共享模块 + **重构 admin 改用它** | 单一真源,永不漂移(R4) |
|
||||
|
||||
### 已知取舍(可接受)
|
||||
|
||||
- analytics 的 `user_id` 是**端上报、未鉴权**(可伪造)。但伪造只能"保自己活跃、避免被清",无收益,且正是本功能要防的行为,风险良性。活跃时间的非空基线由服务端权威的 `User.created_at` 提供(见 §4),不再依赖 `last_login_at`。与"用户管理"口径一致。
|
||||
|
||||
---
|
||||
|
||||
## 4. 活跃口径与共享模块 `app/repositories/activity.py`(新建)
|
||||
|
||||
活跃口径的**唯一真源**。app 侧模块,admin 可 import(`app.main` 不 import `app.admin`,反向允许)。
|
||||
|
||||
### 口径
|
||||
|
||||
```
|
||||
last_active = max(
|
||||
User.created_at, # 注册基线(恒非空;re-login 不推进,只有真实使用才推进)
|
||||
max AnalyticsEvent.created_at WHERE event IN ACTIVE_EVENTS,
|
||||
max CouponPromptEngagement.created_at WHERE engage_type == "claim_started",
|
||||
)
|
||||
不活跃判定:按北京自然日、0 点对齐(非从末次活跃时刻滚动 15×24h)
|
||||
last_active_date = 北京(last_active).date() # 末次活跃的北京日,记为「第 1 日」
|
||||
清零边界 = 北京 00:00 of (last_active_date + RESET_DAYS 天) =「第 (RESET_DAYS+1) 日 0 点」 # 15 → 第16日0点
|
||||
应清零 ⟺ (cn_today() − last_active_date).days ≥ RESET_DAYS
|
||||
⟺ last_active < cutoff, cutoff = 北京 00:00 of (cn_today() − (RESET_DAYS−1)) # 供 SQL 比较
|
||||
inactive_days = (cn_today() − last_active_date).days # 清零当日恰 = RESET_DAYS
|
||||
例:末次活跃 1/1 → 1/16 00:00(第16日0点)清零,当日 inactive_days=15;1/15 及之前不清
|
||||
```
|
||||
|
||||
### 模块内容
|
||||
|
||||
- 常量:
|
||||
- **首页可见活跃信号已定名:`event=show` + `page=home`**(前端确认,原占位 `home_view`;下文出现的 `home_view` 均指此信号)。活跃行为过滤见 `activity.active_event_condition()`:首页可见 ∪ 比价 `real_compare_start` ∪ 领券 `real_coupon_start`;`ACTIVE_EVENTS` 仅含后两个纯 event 名(首页可见是 event+page 组合、单列)。
|
||||
- `ACTIVE_ENGAGE_TYPE = "claim_started"`
|
||||
- `last_active_subqueries(db)` —— 复刻现 admin `queries._last_active_parts()`:两个按 `user_id` 的 `GROUP BY max(created_at)` 聚合子查询。
|
||||
- `last_active_expr(base_col, ev_sub, eng_sub, dialect)` —— 生成 `greatest`/`max`(PG `func.greatest`/SQLite `func.max`);子聚合缺失时 `coalesce(子聚合, User.created_at)` 兜底(注册基线恒非空,**替代原 last_login_at**)。
|
||||
- `_norm_utc()` —— 沿用现 admin 的 naive→UTC 归一(SQLite naive / PG aware 混算保护)。
|
||||
- `reset_cutoff(reset_days)` / `warn_cutoff(reset_days, k)` —— 生成**北京 0 点对齐**的边界 datetime(见口径):`reset_cutoff = 北京 00:00 of (cn_today() − (reset_days−1))`,供下面查询按 `last_active < cutoff` 比较。
|
||||
- `select_inactive_users(db, *, cutoff, with_balance=True)` —— **worker 专用**:join `CoinAccount`,筛 `last_active < cutoff`(cutoff = 北京 0 点对齐边界,见口径)且(`coin_balance>0 OR cash_balance_cents>0`;**邀请现金不清、不计入候选**),返回 `(user, account, last_active, inactive_days)`。
|
||||
- `select_warn_targets(db, *, reset_days, warn_days_before)` —— **worker 专用**:返回 `(user, account, last_active, inactive_days, stage)` 元组——各"提前天数"窗口内、有余额、本 streak 未推过档 `stage` 的用户(去重结合 `notification_log`,逻辑见 §9)。
|
||||
|
||||
> **参考现状**:现口径散落在 `app/admin/repositories/queries.py:38,91-124,199-204`(`_ACTIVE_EVENTS`/`_last_active_parts`/`greatest`)与 `app/admin/repositories/stats.py:51-52,138-146`(`COMPARE_START_EVENT`/`COUPON_START_EVENT`/活跃用户集)。这些改为从 `activity.py` 导入(§12)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 数据模型(2 张新表,不动 `User`)
|
||||
|
||||
两表均登记进 `app/models/__init__.py`;一个 Alembic 迁移建两表(`render_as_batch`,SQLite 兼容)。
|
||||
|
||||
### ① `inactivity_reset_log` —— 清零审计(R2)
|
||||
|
||||
仿 `app/models/phone_rebind_log.py` 的简单审计表风格。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int PK autoincrement | |
|
||||
| `user_id` | int, index, not null | |
|
||||
| `coin_balance_before` | int, not null | 清零前金币 |
|
||||
| `cash_balance_cents_before` | int, not null | 清零前折算现金(分) |
|
||||
| `invite_cash_balance_cents_before` | int, not null | 清零前邀请现金(分) |
|
||||
| `last_active_at` | DateTime(tz), nullable | 判定时的最近活跃时间 |
|
||||
| `inactive_days` | int, not null | 判定时不活跃天数 |
|
||||
| `reason` | String(32), not null | 如 `"inactive_15d"` |
|
||||
| `reset_at` | DateTime(tz), server_default now(), index, not null | 清零时刻 |
|
||||
|
||||
### ② `inactivity_notification_log` —— 预警记录 + 去重 + 占位 outbox(R3)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int PK autoincrement | |
|
||||
| `user_id` | int, index, not null | |
|
||||
| `stage` | int, not null | 提前天数档(如 7 / 2) |
|
||||
| `inactive_days` | int, not null | 推送时不活跃天数 |
|
||||
| `coin_balance` | int, not null | 推送快照:告知用户的金币数 |
|
||||
| `cash_balance_cents` | int, not null | 推送快照:折算现金 |
|
||||
| `invite_cash_balance_cents` | int, not null | 推送快照:邀请现金 |
|
||||
| `channel` | String(16), not null | `"log"` / `"jpush"` / `"sms"` |
|
||||
| `status` | String(16), not null | `"placeholder"` / `"sent"` / `"failed"` |
|
||||
| `created_at` | DateTime(tz), server_default now(), index, not null | 去重锚点(见 §9) |
|
||||
|
||||
> 备注:不新增 `User.last_active_at` 列,不改 `get_current_user`。活跃时间由 §4 口径**实时计算**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 清零 worker `app/core/inactivity_reset_worker.py`(新建)
|
||||
|
||||
**完全仿 [`app/core/daily_exchange_worker.py`](../../../app/core/daily_exchange_worker.py)**:App 启动自带 asyncio 任务,文件锁(`data/inactivity_reset.lock`)防同机多进程并发,总闸 `INACTIVITY_RESET_ENABLED`(默认关)。
|
||||
|
||||
### 调度
|
||||
|
||||
- 每 `INACTIVITY_RESET_CHECK_INTERVAL_SEC` 秒醒一次;`last_run: date` 守卫**北京日**,保证每日只跑一轮。
|
||||
- 仅当 `cn_today() != last_run` 且当前北京小时 `>= INACTIVITY_RESET_RUN_HOUR` 时执行(启动补跑同 daily_exchange 语义)。
|
||||
- **清零资格边界 = 第 16 日 0 点(北京,见 §4),与 worker 执行点解耦**:worker 于当日 `RUN_HOUR`(默认 3 点)跑,把已过边界者一并清;若要严格 0 点触发可置 `RUN_HOUR=0`,但注意与 `daily_auto_exchange` 的 0 点任务错峰。
|
||||
- lifespan 里 `start_inactivity_reset_worker()` / `stop_...`(仿 `start_daily_exchange_worker` 在 `app/main.py` 的接线)。
|
||||
|
||||
### 一轮 `run_once(db)` 两阶段(同一次运行、各自逐用户独立 commit)
|
||||
|
||||
**阶段 A — 预警**
|
||||
```
|
||||
for user, acc, last_active, inactive_days, stage in activity.select_warn_targets(...):
|
||||
notifier.send_inactivity_warning(user, balances=snapshot(acc), stage=stage, days_until_reset=RESET_DAYS-inactive_days)
|
||||
db.add(InactivityNotificationLog(..., channel=notifier.channel, status=notifier.last_status))
|
||||
db.commit() # 逐条独立
|
||||
```
|
||||
|
||||
**阶段 B — 清零**(`biz_type="inactivity_reset"`)
|
||||
```
|
||||
for user, acc, last_active, inactive_days in activity.select_inactive_users(db, cutoff=activity.reset_cutoff(RESET_DAYS)): # 北京 00:00 of (今天−(RESET_DAYS−1))
|
||||
try:
|
||||
acc = wallet.get_or_create_account(db, user.id, commit=False, lock=True) # 行锁
|
||||
before = (acc.coin_balance, acc.cash_balance_cents, acc.invite_cash_balance_cents)
|
||||
if acc.coin_balance == 0 and acc.cash_balance_cents == 0: continue # 邀请现金不清,不算可清余额
|
||||
log = InactivityResetLog(user_id=user.id, coin_balance_before=before[0],
|
||||
cash_balance_cents_before=before[1], invite_cash_balance_cents_before=before[2], # 邀请现金仅快照
|
||||
last_active_at=last_active, inactive_days=inactive_days, reason=f"inactive_{RESET_DAYS}d")
|
||||
db.add(log); db.flush() # 拿 log.id 作 ref_id 交叉链接
|
||||
if acc.coin_balance: wallet.grant_coins(db, user.id, -acc.coin_balance, biz_type="inactivity_reset", ref_id=str(log.id), remark="15天不活跃清零")
|
||||
if acc.cash_balance_cents: wallet.grant_cash(db, user.id, -acc.cash_balance_cents, biz_type="inactivity_reset", ref_id=str(log.id), remark="15天不活跃清零")
|
||||
# 邀请现金(invite_cash_balance_cents)不清:产品红线、两本账物理隔离,仅快照记入审计。
|
||||
db.commit()
|
||||
except SQLAlchemyError:
|
||||
db.rollback(); stats["failed"] += 1
|
||||
```
|
||||
|
||||
- `grant_*` 负数出账、`balance_after=0`、写**两条**流水(金币 + 折算现金;**邀请现金不清**);`grant_coins` 负数**不**动 `total_coin_earned`(历史累计保留)。
|
||||
- 逐用户独立 commit:一个失败不影响其余。返回 `stats = {warned, warn_skipped, warn_failed, scanned, cleared, failed}` 并 `logger.info`。**预警逐用户 try/except 隔离、且预警整段异常也绝不阻塞清零**(清零是不可逆资金操作,不能被通知故障拖住)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 预警与可插拔通知器
|
||||
|
||||
`app/integrations/notifier.py` 定义协议(外部投递属 integrations 层):
|
||||
|
||||
```python
|
||||
class InactivityNotifier(Protocol):
|
||||
channel: str # "log" / "jpush" / "sms"
|
||||
last_status: str # "placeholder" / "sent" / "failed"
|
||||
def send_inactivity_warning(self, user, *, balances, stage, days_until_reset) -> None: ...
|
||||
```
|
||||
|
||||
- **v1 `LogNotifier`**(`channel="log"`):`logger.warning("[inactivity-warn] user=%s coin=%s cash=%s invite=%s T-%s", ...)`,`last_status="placeholder"`。参照 `heartbeat_monitor_worker` 先例("本期先不接推送,用终端打印代替")。
|
||||
- 未来 `JPushNotifier` / `SmsNotifier`:实现同协议即可替换,worker 不改。
|
||||
- 选择:`INACTIVITY_NOTIFY_CHANNEL` → 工厂返回对应实现(未配到真实实现时回退 `LogNotifier`)。
|
||||
- 预警文案数据来自快照 `balances`,满足 R3"告知 xx 金币 xx 现金"。
|
||||
|
||||
---
|
||||
|
||||
## 8. 配置项(`app/core/config.py`)
|
||||
|
||||
```
|
||||
INACTIVITY_RESET_ENABLED = False # 总闸,默认关;灰度验证后再开
|
||||
INACTIVITY_RESET_DAYS = 15 # 不活跃阈值(天)
|
||||
INACTIVITY_WARN_DAYS_BEFORE = "7,2" # 清零前几天各推一次;空串=不推。逗号分隔,降序解析
|
||||
INACTIVITY_RESET_RUN_HOUR = 3 # 北京时间每日执行点(0-23)
|
||||
INACTIVITY_NOTIFY_CHANNEL = "log" # log(占位) / jpush / sms
|
||||
INACTIVITY_RESET_CHECK_INTERVAL_SEC = 1800 # worker 唤醒间隔(可复用现有间隔常量)
|
||||
```
|
||||
|
||||
- 清零范围(三桶)固定为常量,不做配置。
|
||||
- `INACTIVITY_WARN_DAYS_BEFORE` 语义(`inactive_days` 为北京自然日,见 §4):档位 `k` ⟹ 当 `inactive_days >= RESET_DAYS-k` 且 `< RESET_DAYS` 且本 streak 未推过档 `k` 时预警,即在北京日 `last_active_date + (RESET_DAYS−k)` 触发(漏跑某天时补发最紧急未推档,§9)。
|
||||
- `INACTIVITY_RESET_RUN_HOUR` 只决定 worker 每日执行点,**不改变**"第 16 日 0 点"这一资格边界(§4/§6)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 幂等与重新活跃
|
||||
|
||||
- **重新活跃自动退出**:`inactive_days` 由 §4 口径**实时算**。用户一有 `home_view`/比价/领券(**登录本身不算**),`last_active` 前移,自动移出预警与清零队列。**无需**显式"重置标记"。
|
||||
- **预警去重**:`inactivity_notification_log` 中存在 `stage==k 且 created_at > last_active` 的行 ⟹ 本 streak 已推过档 `k`,不重推。用户回归后 `last_active` 前移,旧预警行自然"失效",开启新 streak。
|
||||
- **清零幂等**:阶段 B 只处理三桶非全 0 者;清完 = 0,次日不再匹配。worker 重启 / 多次唤醒 / 补跑均安全,不产生重复清零或重复流水。
|
||||
- **稳健补发**:worker 漏跑数天后,某用户可能同时满足多档;只补发**最紧急的未推档**(最小 `k`),避免一次刷屏。
|
||||
|
||||
---
|
||||
|
||||
## 10. 边界与安全
|
||||
|
||||
| 场景 | 处理 |
|
||||
|---|---|
|
||||
| 新用户 | `created_at` 作活跃基线(恒非空)→ 注册即"第 1 日活跃";注册后连续 15 天无 home_view/比价/领券 才清 |
|
||||
| 在途提现 | 提现申请时现金已扣入 `WithdrawOrder`,当前余额已不含在途;只清当前余额、不动提现单。提现失败退款到已清账户 = 用户的钱,正常 |
|
||||
| 与 `daily_auto_exchange` 并存 | 各自逐用户幂等;金币多已日结折现金,三桶全清正好覆盖 |
|
||||
| 时区/日界 | 统一北京(`rewards.cn_today()`/`CN_TZ`);**清零/预警按北京自然日 0 点对齐**(末次活跃记为第 1 日 → 第 16 日 0 点清零,见 §4),非滚动 24h;流水 `created_at` 沿用北京 wall-clock naive |
|
||||
| 误清防护 | 总闸默认关;先灰度只看预警/清零**名单**对不对,再开清零(§13) |
|
||||
|
||||
---
|
||||
|
||||
## 11. 前端依赖:`home_view` 埋点(跨仓 — Android)
|
||||
|
||||
- **Android 端**(`shaguabijia-app-android`)需在**首页可见**(`onResume`/Tab 切入)时,向现有 `POST /api/v1/analytics/events` 批量上报里加一条 `event=<首页可见事件名>`(名称明天加埋点时定,暂记 `"home_view"`) 的事件,**携带登录后的 `user_id`**。
|
||||
- 客户端按会话/前台去重即可(服务端只取 `max(created_at)`,多报无害)。
|
||||
- **上线顺序依赖**:`home_view` 全量覆盖前,"进首页"信号缺失,只有比价/领券能推进活跃、其余落到 `created_at` 基线("只开首页不操作"且注册满 15 天的用户会被误清)—— 故清零总闸必须待 `home_view` 铺满后再开(§13)。
|
||||
|
||||
---
|
||||
|
||||
## 12. admin 重构范围与影响(R4)
|
||||
|
||||
- `app/admin/repositories/queries.py`:删本地 `_ACTIVE_EVENTS`/`_last_active_parts()`,改用 `activity.py` 的常量与子查询构造;`list_users` 的 `greatest(...)` 排序/筛选、`_attach_last_active` 均改走共享构造器。
|
||||
- `app/admin/repositories/stats.py`:`COMPARE_START_EVENT`/`COUPON_START_EVENT`/活跃用户集(`:138-146`)改用共享常量与口径。
|
||||
- **行为变化(预期内、需产品知会)**:admin 的"最近活跃 / DAU"口径变化——**移除 `last_login_at`(登录不再计为活跃)、以 `created_at` 为基线、纳入 `home_view`**。net:`home_view` 铺满后更准(真正把"开首页"算进活跃);铺满前"只登录不操作"的用户活跃度会下降。
|
||||
- **回归底线**:现有 admin 用户列表 / stats 测试按新口径**更新预期**(last_login_at 移除 + created_at 基线 + home_view 纳入);非活跃口径部分行为不变。
|
||||
|
||||
---
|
||||
|
||||
## 13. 灰度与上线顺序(安全优先)
|
||||
|
||||
1. **后端先行**:合入共享模块 + 两表 + worker + 通知器,`INACTIVITY_RESET_ENABLED=False`;活跃口径以 `created_at` 为非空基线、**不含 last_login_at**。
|
||||
2. **Android 发版**:上报 `home_view`;观察 analytics 覆盖率。
|
||||
3. **只读灰度**:临时开一个"dry-run/只出名单不清零"路径或看阶段 A 预警日志,核对预警/清零**名单**准确。
|
||||
4. **开清零**:确认无误后置 `INACTIVITY_RESET_ENABLED=True`。
|
||||
5. **收尾/监控**:持续观察 `home_view` 覆盖率与预警/清零名单;发现"活跃却被判不活跃"的漏报即回查埋点覆盖(口径已不含 last_login_at,登录不再兜底)。
|
||||
|
||||
---
|
||||
|
||||
## 14. 测试计划
|
||||
|
||||
- **活跃口径(共享模块)**:`home_view`/比价/领券 各单独命中都算活跃;**纯登录不算**;无信号用户以 `created_at` 计;`max` 取最新;naive/aware 混算不崩。
|
||||
- **admin 回归**:用户列表 / stats 按新口径更新预期(移除 last_login_at + created_at 基线 + home_view)。
|
||||
- **不活跃判定**:`last_active` 分别 `<15d / =15d / >15d` × 有/无余额 的命中矩阵。
|
||||
- **清零**:三桶归零;`inactivity_reset_log` 清前值正确;三条流水 `biz_type=inactivity_reset`、`balance_after=0`、`ref_id=log.id`;`total_coin_earned` 不变。
|
||||
- **预警**:命中窗口调 notifier + 写 `notification_log`;同 streak 不重推;回归后 `last_active` 前移可再次预警;漏跑补发最紧急档。
|
||||
- **worker**:总闸关不启动;文件锁互斥;逐用户失败隔离(一个抛错不影响其余,`failed` 计数);重复跑幂等。
|
||||
- **配置**:`INACTIVITY_WARN_DAYS_BEFORE` 解析(含空串=不推);`RESET_DAYS`/`RUN_HOUR` 生效。
|
||||
- 沿用 `tests/conftest.py`(临时 SQLite、`RATE_LIMIT_ENABLED=false`);外部通知 monkeypatch。
|
||||
|
||||
---
|
||||
|
||||
## 15. 未来工作
|
||||
|
||||
- 接真实 `JPushNotifier`(需用户级 `registration_id` 覆盖 + JPush push API)/ `SmsNotifier`。
|
||||
- 如需 admin 后台可视化:不活跃/预警/清零名单与历史查询接口。
|
||||
- 如量级增长导致每日 join 扫描变慢:再考虑物化 `last_active_at`(当前每日一次可接受)。
|
||||
|
||||
---
|
||||
|
||||
## 附:涉及文件清单
|
||||
|
||||
**新增**
|
||||
- `app/repositories/activity.py` — 活跃口径唯一真源
|
||||
- `app/models/inactivity_reset_log.py` — 审计表
|
||||
- `app/models/inactivity_notification_log.py` — 预警/占位表
|
||||
- `app/core/inactivity_reset_worker.py` — 每日 worker(仿 daily_exchange_worker)
|
||||
- `app/integrations/notifier.py` — 通知器协议 + `LogNotifier`(真实 JPush/短信后续同层扩展)
|
||||
- `alembic/versions/<...>_add_inactivity_tables.py` — 建两表迁移
|
||||
- `docs/database/inactivity_reset_log.md` / `inactivity_notification_log.md` — 表字典(随实现补)
|
||||
- 对应 `tests/test_inactivity_reset.py`
|
||||
|
||||
**改动**
|
||||
- `app/models/__init__.py` — 注册两模型
|
||||
- `app/core/config.py` — `INACTIVITY_*` 配置
|
||||
- `app/main.py` — lifespan 接线 start/stop worker
|
||||
- `app/admin/repositories/queries.py`、`stats.py` — 改用 `activity.py`(§12)
|
||||
@@ -1,139 +0,0 @@
|
||||
"""人工验证用:按「金币/现金/邀请」排列组合 + 活跃/新用户对照,造一批账号。
|
||||
|
||||
用法(仓库根目录,venv 解释器):
|
||||
.venv/Scripts/python.exe scripts/seed_inactivity_cases.py # 造号(会先清掉上次 vcase*)
|
||||
.venv/Scripts/python.exe scripts/seed_inactivity_cases.py --clean # 只清理,不造
|
||||
|
||||
配合默认配置 INACTIVITY_RESET_DAYS=15 / INACTIVITY_WARN_DAYS_BEFORE=7,2 验证。
|
||||
造完把 worker 打开(见 README/对话里的 .env),启动服务即会在 RUN_HOUR 后跑一轮。
|
||||
|
||||
⚠️ worker 清零针对**库里所有**符合条件的用户,不止 vcase*——dev 库里若有其它"老且有余额、
|
||||
无近期活跃事件"的用户,也会被一起清。要干净验证建议用一个空/副本 dev 库。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sqlalchemy import delete, select # noqa: E402
|
||||
|
||||
from app.db.session import SessionLocal # noqa: E402
|
||||
from app.models.analytics_event import AnalyticsEvent # noqa: E402
|
||||
from app.models.inactivity import ( # noqa: E402
|
||||
InactivityNotificationLog,
|
||||
InactivityResetLog,
|
||||
)
|
||||
from app.models.user import User # noqa: E402
|
||||
from app.models.wallet import ( # noqa: E402
|
||||
CashTransaction,
|
||||
CoinAccount,
|
||||
CoinTransaction,
|
||||
InviteCashTransaction,
|
||||
)
|
||||
from app.repositories import wallet as wallet_repo # noqa: E402
|
||||
|
||||
MARK = "vcase" # username 前缀,用于清理
|
||||
|
||||
# label, 创建于N天前, coin, cash, invite, 近期事件(N天前)or None, 预期
|
||||
CASES = [
|
||||
("1 三桶全有", 30, 100, 200, 300, None, "清 coin+cash;invite=300 保留;审计1行+2流水"),
|
||||
("2 金币+现金", 30, 100, 200, 0, None, "清 coin+cash;审计1行+2流水"),
|
||||
("3 金币+邀请", 30, 100, 0, 300, None, "清 coin;invite=300 保留;审计1行+1流水"),
|
||||
("4 现金+邀请", 30, 0, 200, 300, None, "清 cash;invite=300 保留;审计1行+1流水"),
|
||||
("5 只有金币", 30, 100, 0, 0, None, "清 coin;审计1行+1流水"),
|
||||
("6 只有现金", 30, 0, 200, 0, None, "清 cash;审计1行+1流水"),
|
||||
("7 只有邀请(红线)", 30, 0, 0, 300, None, "不选中/不清/无审计/无流水;invite=300 原封"),
|
||||
("8 预警窗(10天)", 10, 50, 60, 70, None, "不清;发 T-7 预警;notification_log 1行;余额不动"),
|
||||
("9 活跃兜底", 30, 100, 200, 300, 1, "昨日 home_view→last_active 近→不清不警"),
|
||||
("10 新用户(3天)", 3, 100, 200, 0, None, "created_at 近→不清不警"),
|
||||
]
|
||||
|
||||
|
||||
def _mark_uids(db) -> list[int]:
|
||||
return list(db.execute(select(User.id).where(User.username.like(f"{MARK}%"))).scalars())
|
||||
|
||||
|
||||
def clean(db) -> int:
|
||||
uids = _mark_uids(db)
|
||||
if uids:
|
||||
for model in (
|
||||
InactivityResetLog, InactivityNotificationLog,
|
||||
CoinTransaction, CashTransaction, InviteCashTransaction,
|
||||
AnalyticsEvent, CoinAccount,
|
||||
):
|
||||
db.execute(delete(model).where(model.user_id.in_(uids)))
|
||||
db.execute(delete(User).where(User.id.in_(uids)))
|
||||
db.commit()
|
||||
return len(uids)
|
||||
|
||||
|
||||
def seed(db) -> None:
|
||||
now = datetime.now(UTC)
|
||||
print(f"{'#':>3} {'uid':>5} {'案例':<16} {'coin/cash/invite':<18} {'创建':<7} 预期")
|
||||
for i, (label, days_ago, coin, cash, invite, ev_days, expected) in enumerate(CASES, 1):
|
||||
u = User(
|
||||
phone=f"seed_tmp_{i}", username=f"{MARK}{i}", status="active",
|
||||
created_at=now - timedelta(days=days_ago),
|
||||
last_login_at=now, # 登录很新——但登录不算活跃,清零该发生照发生
|
||||
)
|
||||
db.add(u)
|
||||
db.flush() # 拿自增 id
|
||||
u.phone = f"1{u.id:010d}" # 用全局唯一 id 拼 "100…" 段手机号,dev 库里绝不撞
|
||||
acc = wallet_repo.get_or_create_account(db, u.id, commit=False)
|
||||
acc.coin_balance, acc.cash_balance_cents, acc.invite_cash_balance_cents = coin, cash, invite
|
||||
acc.total_coin_earned = coin
|
||||
if ev_days is not None:
|
||||
db.add(AnalyticsEvent( # 首页可见 = event=show + page=home
|
||||
event="show", page="home", device_id=MARK, user_id=u.id,
|
||||
client_ts=0, created_at=now - timedelta(days=ev_days),
|
||||
))
|
||||
db.flush()
|
||||
print(f"{i:>3} {u.id:>5} {label:<16} {f'{coin}/{cash}/{invite}':<18} {f'{days_ago}天前':<7} {expected}")
|
||||
db.commit()
|
||||
|
||||
|
||||
def check(db) -> None:
|
||||
"""worker 跑完后:打印每个 vcase 账号的当前三桶余额 + 是否有审计/预警行。"""
|
||||
rows = db.execute(
|
||||
select(User.id, User.username).where(User.username.like(f"{MARK}%")).order_by(User.id)
|
||||
).all()
|
||||
if not rows:
|
||||
print("没有 vcase* 账号(先跑一次不带参数造号)")
|
||||
return
|
||||
print(f"{'uid':>5} {'账号':<8} {'coin/cash/invite(现在)':<24} {'审计':<5} 预警")
|
||||
for uid, uname in rows:
|
||||
acc = db.get(CoinAccount, uid)
|
||||
bal = f"{acc.coin_balance}/{acc.cash_balance_cents}/{acc.invite_cash_balance_cents}" if acc else "—"
|
||||
has_reset = db.execute(
|
||||
select(InactivityResetLog.id).where(InactivityResetLog.user_id == uid).limit(1)
|
||||
).first()
|
||||
stages = db.execute(
|
||||
select(InactivityNotificationLog.stage).where(InactivityNotificationLog.user_id == uid)
|
||||
).scalars().all()
|
||||
warn = ",".join(f"T-{s}" for s in stages) if stages else "—"
|
||||
print(f"{uid:>5} {uname:<8} {bal:<24} {'有' if has_reset else '—':<5} {warn}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if "--check" in sys.argv:
|
||||
check(db)
|
||||
return
|
||||
removed = clean(db)
|
||||
if removed:
|
||||
print(f"已清理上次 {removed} 个 {MARK}* 账号")
|
||||
if "--clean" in sys.argv:
|
||||
return
|
||||
seed(db)
|
||||
print("\n造号完成。打开 worker(INACTIVITY_RESET_ENABLED=true, RUN_HOUR=17)后启动服务,"
|
||||
"≥17:00 首个 tick 即跑一轮。验完 `--clean` 清理。")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -356,3 +356,117 @@ def test_callback_disabled_returns_503(client, monkeypatch) -> None:
|
||||
# 503 发生在验签/发奖之前,不需要真实用户
|
||||
r = _callback(client, _signed(1, "trans_disabled"))
|
||||
assert r.status_code == 503, r.text
|
||||
|
||||
|
||||
# ===== 按广告会话查权威发奖结果(弹窗展示实发金币用)=====
|
||||
|
||||
|
||||
def _reward_result(client, token: str, ad_session_id: str):
|
||||
return client.get(f"/api/v1/ad/reward-result/{ad_session_id}", headers=_auth(token))
|
||||
|
||||
|
||||
def test_reward_result_requires_auth(client) -> None:
|
||||
"""按会话查发奖结果需登录。"""
|
||||
assert client.get("/api/v1/ad/reward-result/sess_noauth_001").status_code == 401
|
||||
|
||||
|
||||
def test_reward_result_pending_when_no_record(client) -> None:
|
||||
"""本人没有这次会话的发奖记录 → pending、coin=null(不能把"尚未到账"当成 0 金币)。"""
|
||||
phone = "13800003601"
|
||||
token = _login(client, phone)
|
||||
r = _reward_result(client, token, "sess_pending_never")
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["ad_session_id"] == "sess_pending_never"
|
||||
assert body["status"] == "pending"
|
||||
assert body["coin"] is None
|
||||
|
||||
|
||||
def test_reward_result_granted_returns_real_coin(client) -> None:
|
||||
"""本人存在 granted 记录 → 返回真实到账金币(与发奖公式一致),status=granted。"""
|
||||
phone = "13800003602"
|
||||
token = _login(client, phone)
|
||||
uid = _user_id(phone)
|
||||
session = "sess_granted_0001"
|
||||
r = _callback(client, _signed(uid, "trans_rr_grant", ecpm="200",
|
||||
extra=json.dumps({"ad_session_id": session})))
|
||||
assert r.status_code == 200, r.text
|
||||
expected = calculate_ad_reward_coin("200", 1)
|
||||
assert expected > 0
|
||||
assert _coin_balance(client, token) == expected
|
||||
|
||||
body = _reward_result(client, token, session).json()
|
||||
assert body["status"] == "granted"
|
||||
assert body["coin"] == expected
|
||||
|
||||
|
||||
def test_reward_result_capped_returns_zero(client, monkeypatch) -> None:
|
||||
"""达每日上限记 capped → status=capped、coin=0(客户端走上限提示,不显示"获得 0 金币")。"""
|
||||
monkeypatch.setattr("app.core.rewards.get_ad_daily_limit", lambda db: 0)
|
||||
phone = "13800003603"
|
||||
token = _login(client, phone)
|
||||
uid = _user_id(phone)
|
||||
session = "sess_capped_0001"
|
||||
before = _coin_balance(client, token)
|
||||
r = _callback(client, _signed(uid, "trans_rr_capped", ecpm="200",
|
||||
extra=json.dumps({"ad_session_id": session})))
|
||||
assert r.status_code == 200, r.text
|
||||
assert _coin_balance(client, token) == before # capped 未加币
|
||||
|
||||
body = _reward_result(client, token, session).json()
|
||||
assert body["status"] == "capped"
|
||||
assert body["coin"] == 0
|
||||
|
||||
|
||||
def test_reward_result_closed_early_not_granted(client) -> None:
|
||||
"""提前关闭留痕(closed_early)不是成功奖励 → 返回终态、coin=0,不能伪装成 granted。"""
|
||||
phone = "13800003604"
|
||||
token = _login(client, phone)
|
||||
session = "sess_closed_early_0001"
|
||||
r = client.post("/api/v1/ad/reward-noshow",
|
||||
json={"ad_session_id": session, "watched_seconds": 2},
|
||||
headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "closed_early"
|
||||
|
||||
body = _reward_result(client, token, session).json()
|
||||
assert body["status"] == "closed_early"
|
||||
assert body["status"] != "granted"
|
||||
assert body["coin"] == 0
|
||||
|
||||
|
||||
def test_reward_result_isolated_per_user(client) -> None:
|
||||
"""他人用同一会话 id 查 → 读不到,仍 pending(会话结果按 user_id 隔离)。"""
|
||||
owner_phone = "13800003605"
|
||||
owner_token = _login(client, owner_phone)
|
||||
owner_uid = _user_id(owner_phone)
|
||||
session = "sess_shared_0001"
|
||||
_callback(client, _signed(owner_uid, "trans_rr_shared", ecpm="200",
|
||||
extra=json.dumps({"ad_session_id": session})))
|
||||
assert _reward_result(client, owner_token, session).json()["status"] == "granted"
|
||||
|
||||
other_token = _login(client, "13800003606")
|
||||
body = _reward_result(client, other_token, session).json()
|
||||
assert body["status"] == "pending"
|
||||
assert body["coin"] is None
|
||||
|
||||
|
||||
def test_reward_result_granted_supersedes_earlier_closed_early(client) -> None:
|
||||
"""同一会话先留痕 closed_early、S2S 延迟到账后又 granted → 查最新返回 granted 与真实金币
|
||||
(弹窗最终展示真实到账,不被早先的 closed_early 顶掉;这正是 S2S 延迟场景)。"""
|
||||
phone = "13800003607"
|
||||
token = _login(client, phone)
|
||||
uid = _user_id(phone)
|
||||
session = "sess_late_grant_0001"
|
||||
# 1) 客户端以为提前关闭,先留痕 closed_early
|
||||
assert client.post("/api/v1/ad/reward-noshow",
|
||||
json={"ad_session_id": session},
|
||||
headers=_auth(token)).json()["status"] == "closed_early"
|
||||
# 2) S2S 延迟到账,写入 granted(不同 trans_id)
|
||||
r = _callback(client, _signed(uid, "trans_late_grant", ecpm="200",
|
||||
extra=json.dumps({"ad_session_id": session})))
|
||||
assert r.status_code == 200, r.text
|
||||
expected = calculate_ad_reward_coin("200", 1)
|
||||
body = _reward_result(client, token, session).json()
|
||||
assert body["status"] == "granted"
|
||||
assert body["coin"] == expected
|
||||
|
||||
@@ -107,67 +107,6 @@ def test_sms_send_device_ip_rate_limit(client, monkeypatch) -> None:
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def test_sms_send_cooldown_reject_not_counted(client, monkeypatch) -> None:
|
||||
"""发码额度只算「成功发码」:被单号 60s 冷却挡下的重发(429)不占设备额度。
|
||||
做法:同号狂发只成功 1 次、其余被冷却挡下;把小时额度设 2,证明换号后仍能再成功发 1 次
|
||||
—— 若冷却重发也计数,额度早被那几次耗尽。"""
|
||||
from app.api.v1 import auth
|
||||
from app.core import ratelimit
|
||||
|
||||
monkeypatch.setattr(ratelimit.settings, "RATE_LIMIT_ENABLED", True)
|
||||
monkeypatch.setattr(auth, "SMS_SEND_MAX_PER_HOUR_PER_DEVICE", 2)
|
||||
ratelimit._buckets.clear()
|
||||
|
||||
device = "dev-cooldown"
|
||||
phone_a = "13710137000"
|
||||
# 首发成功(小时闸计 1/2)
|
||||
assert client.post(
|
||||
"/api/v1/auth/sms/send", json={"phone": phone_a, "device_id": device}
|
||||
).status_code == 200
|
||||
# 同号连发 3 次:都被单号 60s 冷却挡下 → 429,且**不占**设备额度
|
||||
for _ in range(3):
|
||||
r = client.post(
|
||||
"/api/v1/auth/sms/send", json={"phone": phone_a, "device_id": device}
|
||||
)
|
||||
assert r.status_code == 429, r.text
|
||||
# 换号再发:设备额度只用了 1/2(冷却那几次没算)→ 仍放行(计到 2/2)
|
||||
assert client.post(
|
||||
"/api/v1/auth/sms/send", json={"phone": "13710137001", "device_id": device}
|
||||
).status_code == 200
|
||||
# 又换号:此时小时闸已 2/2 → 429(反证成功发码确实各计了 1)
|
||||
r = client.post(
|
||||
"/api/v1/auth/sms/send", json={"phone": "13710137002", "device_id": device}
|
||||
)
|
||||
assert r.status_code == 429, r.text
|
||||
|
||||
|
||||
def test_sms_send_daily_cap(client, monkeypatch) -> None:
|
||||
"""每天发码上限(设备 + IP):成功发码累计到日上限即 429(用不同手机号绕开单号冷却)。
|
||||
抬高小时闸单独测日闸;超限文案含「今日」以便前端提示明天再来。"""
|
||||
from app.api.v1 import auth
|
||||
from app.core import ratelimit
|
||||
|
||||
monkeypatch.setattr(ratelimit.settings, "RATE_LIMIT_ENABLED", True)
|
||||
monkeypatch.setattr(auth, "SMS_SEND_MAX_PER_HOUR_PER_DEVICE", 100) # 抬高小时闸,不干扰
|
||||
monkeypatch.setattr(auth, "SMS_SEND_MAX_PER_DAY_PER_DEVICE", 3)
|
||||
ratelimit._buckets.clear()
|
||||
|
||||
device = "dev-daily"
|
||||
for i in range(3):
|
||||
r = client.post(
|
||||
"/api/v1/auth/sms/send",
|
||||
json={"phone": f"13720137{i:03d}", "device_id": device},
|
||||
)
|
||||
assert r.status_code == 200, f"第 {i + 1} 次应放行: {r.text}"
|
||||
# 第 4 次:同设备同 IP 当日超限 → 429
|
||||
r = client.post(
|
||||
"/api/v1/auth/sms/send",
|
||||
json={"phone": "13720137999", "device_id": device},
|
||||
)
|
||||
assert r.status_code == 429, r.text
|
||||
assert "今日" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_sms_login_device_ip_rate_limit(client, monkeypatch) -> None:
|
||||
"""防刷:同一设备(device_id) + 同一 IP 每小时最多 SMS_LOGIN_MAX_PER_HOUR 次登录尝试,超出 429。
|
||||
conftest 默认 RATE_LIMIT_ENABLED=false(内存计数跨用例累加),本用例临时打开并清空计数隔离。"""
|
||||
|
||||
@@ -1,416 +0,0 @@
|
||||
"""15 天不活跃清零:模型 / 活跃口径 / 清零 / 预警 / 配置 / worker。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import delete, select, update
|
||||
|
||||
from app.db.session import SessionLocal
|
||||
from app.models.inactivity import InactivityNotificationLog, InactivityResetLog
|
||||
from app.repositories import activity
|
||||
|
||||
|
||||
def test_reset_and_notification_models_persist() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db.add(InactivityResetLog(
|
||||
user_id=1, coin_balance_before=10, cash_balance_cents_before=20,
|
||||
invite_cash_balance_cents_before=30,
|
||||
last_active_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
|
||||
inactive_days=15, reason="inactive_15d",
|
||||
))
|
||||
db.add(InactivityNotificationLog(
|
||||
user_id=1, stage=7, inactive_days=8, coin_balance=10,
|
||||
cash_balance_cents=20, invite_cash_balance_cents=30,
|
||||
channel="log", status="placeholder",
|
||||
))
|
||||
db.commit()
|
||||
r = db.execute(select(InactivityResetLog).where(InactivityResetLog.user_id == 1)).scalar_one()
|
||||
assert r.reason == "inactive_15d" and r.reset_at is not None
|
||||
n = db.execute(select(InactivityNotificationLog).where(InactivityNotificationLog.user_id == 1)).scalar_one()
|
||||
assert n.stage == 7 and n.created_at is not None
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_reset_cutoff_is_cn_midnight_of_today_minus_days_minus_1() -> None:
|
||||
# RESET_DAYS=15, today=1/20 → cutoff = 北京 00:00 of 1/6 = 1/5 16:00 UTC
|
||||
cutoff = activity.reset_cutoff(15, today=date(2026, 1, 20))
|
||||
assert cutoff == datetime(2026, 1, 5, 16, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def test_active_event_constants() -> None:
|
||||
# 首页可见 = event=show + page=home 组合,不在纯 event 名集合里
|
||||
assert activity.HOME_VIEW_EVENT == "show" and activity.HOME_VIEW_PAGE == "home"
|
||||
assert activity.HOME_VIEW_EVENT not in activity.ACTIVE_EVENTS
|
||||
assert "real_compare_start" in activity.ACTIVE_EVENTS
|
||||
assert "real_coupon_start" in activity.ACTIVE_EVENTS
|
||||
assert activity.ACTIVE_ENGAGE_TYPE == "claim_started"
|
||||
|
||||
|
||||
def test_as_utc_normalizes() -> None:
|
||||
assert activity.as_utc(datetime(2026, 1, 1)) == datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
cn = datetime(2026, 1, 1, tzinfo=activity.CN_TZ) # 北京 0 点 = 前一天 16:00 UTC
|
||||
assert activity.as_utc(cn) == datetime(2025, 12, 31, 16, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
from app.core.rewards import CN_TZ
|
||||
from app.models.analytics_event import AnalyticsEvent
|
||||
from app.models.coupon_state import CouponPromptEngagement
|
||||
from app.models.user import User
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import wallet as wallet_repo
|
||||
|
||||
_PHONE_SEQ = [0]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_inactivity_state():
|
||||
"""本文件的测试都做全表扫描 + 全局计数,而 SQLite 测试库 session 级共享、无逐用例回滚
|
||||
(commit 后的 rollback 是 no-op),故先把可能泄漏的余额清零 + 清掉活跃事件/审计行,
|
||||
保证每个用例干净起步。不删 User(零余额用户不会被扫描选中,避免跨文件/外键影响)。"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db.execute(update(CoinAccount).values(
|
||||
coin_balance=0, cash_balance_cents=0, invite_cash_balance_cents=0))
|
||||
for model in (AnalyticsEvent, CouponPromptEngagement,
|
||||
InactivityResetLog, InactivityNotificationLog):
|
||||
db.execute(delete(model))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
yield
|
||||
|
||||
|
||||
def _new_user(db, *, created_at, coin=0, cash=0, invite=0) -> int:
|
||||
"""直接建一个 User + CoinAccount,created_at 可控。返回 user_id。"""
|
||||
_PHONE_SEQ[0] += 1
|
||||
# 199 前缀 + 递增序号:共享测试库跨文件累积用户,别的文件用固定手机号(如 test_admin_write
|
||||
# 的 13900000001..),这里用没人用的 199 段避免撞 user.phone / username 的 UNIQUE。
|
||||
u = User(phone=f"199{_PHONE_SEQ[0]:08d}", created_at=created_at,
|
||||
last_login_at=created_at, status="active",
|
||||
username=f"inact{_PHONE_SEQ[0]}")
|
||||
db.add(u)
|
||||
db.flush()
|
||||
acc = wallet_repo.get_or_create_account(db, u.id, commit=False)
|
||||
acc.coin_balance, acc.cash_balance_cents, acc.invite_cash_balance_cents = coin, cash, invite
|
||||
acc.total_coin_earned = coin
|
||||
db.flush()
|
||||
return u.id
|
||||
|
||||
|
||||
def _add_event(db, user_id, event, when: datetime, page=None) -> None:
|
||||
db.add(AnalyticsEvent(event=event, device_id="d", user_id=user_id, client_ts=0,
|
||||
created_at=when, page=page))
|
||||
|
||||
|
||||
def _add_engage(db, user_id, when: datetime, engage_type="claim_started") -> None:
|
||||
db.add(CouponPromptEngagement(device_id=f"dev{user_id}", package="p", user_id=user_id,
|
||||
engage_date=when.date(), engage_type=engage_type, created_at=when))
|
||||
|
||||
|
||||
def test_last_active_expr_takes_max_of_baseline_and_events() -> None:
|
||||
from sqlalchemy import select
|
||||
db = SessionLocal()
|
||||
try:
|
||||
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
uid = _new_user(db, created_at=base, coin=5)
|
||||
_add_event(db, uid, "real_compare_start", datetime(2026, 1, 10, tzinfo=timezone.utc))
|
||||
db.commit()
|
||||
ev_sub, eng_sub = activity.last_active_subqueries(db)
|
||||
dialect = db.get_bind().dialect.name
|
||||
expr = activity.last_active_expr(User.created_at, ev_sub, eng_sub, dialect)
|
||||
stmt = (select(expr).select_from(User)
|
||||
.outerjoin(ev_sub, ev_sub.c.user_id == User.id)
|
||||
.outerjoin(eng_sub, eng_sub.c.user_id == User.id)
|
||||
.where(User.id == uid))
|
||||
got = activity.norm_utc(db.execute(stmt).scalar_one())
|
||||
assert got == datetime(2026, 1, 10, tzinfo=timezone.utc) # 事件 > 基线
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_home_signal_uses_show_event_on_home_page() -> None:
|
||||
"""首页可见活跃口径 = event=show + page=home 组合;show 但非 home 页不算活跃。"""
|
||||
from sqlalchemy import select
|
||||
db = SessionLocal()
|
||||
try:
|
||||
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
seen = _new_user(db, created_at=base) # show/home → 活跃
|
||||
_add_event(db, seen, "show", datetime(2026, 1, 10, tzinfo=timezone.utc), page="home")
|
||||
other = _new_user(db, created_at=base) # show/其他页 → 不算活跃
|
||||
_add_event(db, other, "show", datetime(2026, 1, 10, tzinfo=timezone.utc), page="coupon")
|
||||
db.commit()
|
||||
|
||||
ev_sub, eng_sub = activity.last_active_subqueries(db)
|
||||
dialect = db.get_bind().dialect.name
|
||||
expr = activity.last_active_expr(User.created_at, ev_sub, eng_sub, dialect)
|
||||
|
||||
def last_active(uid):
|
||||
stmt = (select(expr).select_from(User)
|
||||
.outerjoin(ev_sub, ev_sub.c.user_id == User.id)
|
||||
.outerjoin(eng_sub, eng_sub.c.user_id == User.id)
|
||||
.where(User.id == uid))
|
||||
return activity.norm_utc(db.execute(stmt).scalar_one())
|
||||
|
||||
assert last_active(seen) == datetime(2026, 1, 10, tzinfo=timezone.utc) # show/home 算
|
||||
assert last_active(other) == base # show/其他页 不算
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_inactivity_warn_stages_parsing() -> None:
|
||||
from app.core.config import Settings
|
||||
s = Settings(INACTIVITY_WARN_DAYS_BEFORE="7,2", INACTIVITY_RESET_DAYS=15)
|
||||
assert s.inactivity_warn_stages == [7, 2] # 降序去重
|
||||
s2 = Settings(INACTIVITY_WARN_DAYS_BEFORE="", INACTIVITY_RESET_DAYS=15)
|
||||
assert s2.inactivity_warn_stages == [] # 空=不推
|
||||
s3 = Settings(INACTIVITY_WARN_DAYS_BEFORE="2,20,7,2", INACTIVITY_RESET_DAYS=15)
|
||||
assert s3.inactivity_warn_stages == [7, 2] # 去重 + 丢弃 >=RESET_DAYS(20)
|
||||
|
||||
|
||||
def test_log_notifier_returns_placeholder(caplog) -> None:
|
||||
from app.integrations.notifier import LogNotifier, get_notifier
|
||||
n = get_notifier("log")
|
||||
assert isinstance(n, LogNotifier) and n.channel == "log"
|
||||
status = n.warn(user_id=1, coin=10, cash_cents=20, stage=7, days_until_reset=8)
|
||||
assert status == "placeholder"
|
||||
# 未实现通道回退 LogNotifier(占位)
|
||||
assert get_notifier("jpush").channel == "log"
|
||||
|
||||
|
||||
def test_run_reset_clears_coin_and_cash_but_preserves_invite_cash() -> None:
|
||||
from sqlalchemy import select
|
||||
from app.models.wallet import CoinAccount, CoinTransaction, CashTransaction, InviteCashTransaction
|
||||
from app.repositories import inactivity
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
# 末次活跃 = created_at 基线 = 1/10(距 today 22 天 → 应清)
|
||||
old = _new_user(db, created_at=datetime(2026, 1, 10, tzinfo=timezone.utc),
|
||||
coin=100, cash=200, invite=300)
|
||||
# 活跃用户:昨天有 home_view → 不清
|
||||
fresh = _new_user(db, created_at=datetime(2026, 1, 1, tzinfo=timezone.utc), coin=50)
|
||||
_add_event(db, fresh, "show", datetime(2026, 1, 31, tzinfo=timezone.utc), page="home")
|
||||
db.commit()
|
||||
|
||||
stats = inactivity.run_reset_once(db, reset_days=15, today=today)
|
||||
assert stats["cleared"] == 1 and stats["failed"] == 0
|
||||
|
||||
acc = db.get(CoinAccount, old)
|
||||
# 金币 + 折算现金清零;邀请现金是产品红线,原封不动(见 wallet.CoinAccount 注释)
|
||||
assert (acc.coin_balance, acc.cash_balance_cents) == (0, 0)
|
||||
assert acc.invite_cash_balance_cents == 300
|
||||
assert acc.total_coin_earned == 100 # 历史累计不动
|
||||
|
||||
log = db.execute(select(InactivityResetLog).where(InactivityResetLog.user_id == old)).scalar_one()
|
||||
# 审计仍快照三桶余额(邀请现金记为"清零时仍保留"的余额,便于纠纷排查)
|
||||
assert (log.coin_balance_before, log.cash_balance_cents_before,
|
||||
log.invite_cash_balance_cents_before) == (100, 200, 300)
|
||||
assert log.inactive_days == 22 and log.reason == "inactive_15d"
|
||||
|
||||
ct = db.execute(select(CoinTransaction).where(
|
||||
CoinTransaction.user_id == old, CoinTransaction.biz_type == "inactivity_reset")).scalar_one()
|
||||
assert ct.amount == -100 and ct.balance_after == 0 and ct.ref_id == str(log.id)
|
||||
assert db.execute(select(CashTransaction).where(
|
||||
CashTransaction.user_id == old, CashTransaction.biz_type == "inactivity_reset")).scalar_one().amount_cents == -200
|
||||
# 关键:不写邀请现金流水(邀请现金不清)
|
||||
assert db.execute(select(InviteCashTransaction).where(
|
||||
InviteCashTransaction.user_id == old,
|
||||
InviteCashTransaction.biz_type == "inactivity_reset")).first() is None
|
||||
|
||||
# 活跃用户不动;再跑一次幂等(coin+cash 已 0、邀请现金不算候选 → 不再匹配)
|
||||
assert db.get(CoinAccount, fresh).coin_balance == 50
|
||||
assert inactivity.run_reset_once(db, reset_days=15, today=today)["cleared"] == 0
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_user_with_only_invite_cash_is_not_cleared() -> None:
|
||||
"""只有邀请现金余额的久不活跃用户:邀请现金是产品红线,不清 → 根本不该被选中。"""
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import inactivity
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
uid = _new_user(db, created_at=datetime(2026, 1, 10, tzinfo=timezone.utc),
|
||||
coin=0, cash=0, invite=500)
|
||||
db.commit()
|
||||
stats = inactivity.run_reset_once(db, reset_days=15, today=today)
|
||||
assert stats["cleared"] == 0
|
||||
assert db.get(CoinAccount, uid).invite_cash_balance_cents == 500 # 原封不动
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_run_warn_picks_stage_and_dedups_within_streak() -> None:
|
||||
from app.integrations.notifier import LogNotifier
|
||||
from app.repositories import inactivity
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
# 末次活跃 1/22(距 today 10 天)→ 档 7 命中(idays>=8),档 2 未到(需>=13)
|
||||
uid = _new_user(db, created_at=datetime(2026, 1, 22, tzinfo=timezone.utc), coin=100)
|
||||
db.commit()
|
||||
|
||||
stats = inactivity.run_warn_once(db, LogNotifier(), reset_days=15, warn_stages=[7, 2], today=today)
|
||||
assert stats["warned"] == 1
|
||||
from sqlalchemy import select
|
||||
rows = db.execute(select(InactivityNotificationLog).where(
|
||||
InactivityNotificationLog.user_id == uid)).scalars().all()
|
||||
assert len(rows) == 1 and rows[0].stage == 7 and rows[0].status == "placeholder"
|
||||
assert rows[0].inactive_days == 10 and rows[0].coin_balance == 100
|
||||
|
||||
# 同一 streak 再跑 → 不重推
|
||||
assert inactivity.run_warn_once(db, LogNotifier(), reset_days=15, warn_stages=[7, 2], today=today)["warned"] == 0
|
||||
|
||||
# 无余额用户不预警
|
||||
_new_user(db, created_at=datetime(2026, 1, 22, tzinfo=timezone.utc), coin=0)
|
||||
db.commit()
|
||||
assert inactivity.run_warn_once(db, LogNotifier(), reset_days=15, warn_stages=[7, 2], today=today)["warned"] == 0
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_run_once_warns_then_resets() -> None:
|
||||
from app.integrations.notifier import LogNotifier
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import inactivity
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
warn_uid = _new_user(db, created_at=datetime(2026, 1, 22, tzinfo=timezone.utc), coin=10) # 10天→预警
|
||||
clear_uid = _new_user(db, created_at=datetime(2026, 1, 5, tzinfo=timezone.utc), coin=10) # 27天→清零
|
||||
db.commit()
|
||||
stats = inactivity.run_once(db, notifier=LogNotifier(), reset_days=15, warn_stages=[7, 2], today=today)
|
||||
assert stats["warned"] == 1 and stats["cleared"] == 1
|
||||
assert db.get(CoinAccount, clear_uid).coin_balance == 0
|
||||
assert db.get(CoinAccount, warn_uid).coin_balance == 10 # 预警不动钱
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_worker_disabled_returns_none(monkeypatch) -> None:
|
||||
from app.core import inactivity_reset_worker as w
|
||||
from app.core.config import settings
|
||||
monkeypatch.setattr(settings, "INACTIVITY_RESET_ENABLED", False)
|
||||
assert w.start_inactivity_reset_worker() is None
|
||||
|
||||
|
||||
def test_worker_run_once_entry_executes(monkeypatch) -> None:
|
||||
"""_run_once_entry 用真实 SessionLocal 跑一轮,总闸开时能清掉一个不活跃用户。"""
|
||||
from app.core import inactivity_reset_worker as w
|
||||
from app.core.config import settings
|
||||
from app.models.wallet import CoinAccount
|
||||
|
||||
monkeypatch.setattr(settings, "INACTIVITY_RESET_ENABLED", True)
|
||||
monkeypatch.setattr(settings, "INACTIVITY_RESET_DAYS", 15)
|
||||
monkeypatch.setattr(settings, "INACTIVITY_WARN_DAYS_BEFORE", "") # 只测清零
|
||||
# 固定"今天"避免依赖真实时钟
|
||||
monkeypatch.setattr(w, "_cn_today", lambda: date(2026, 2, 1))
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
uid = _new_user(db, created_at=datetime(2026, 1, 1, tzinfo=timezone.utc), coin=100)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
stats = w._run_once_entry()
|
||||
assert stats["cleared"] >= 1
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
assert db.get(CoinAccount, uid).coin_balance == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_admin_list_users_last_active_ignores_login() -> None:
|
||||
"""admin 用户列表 last_active_at 改用共享口径:登录不算活跃(baseline=created_at)、只认活跃事件。"""
|
||||
from app.admin.repositories import queries
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
created = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
uid = _new_user(db, created_at=created)
|
||||
u = db.get(User, uid)
|
||||
u.last_login_at = datetime(2026, 6, 1, tzinfo=timezone.utc) # 登录很新、但无任何活跃事件
|
||||
db.commit()
|
||||
phone = db.get(User, uid).phone
|
||||
users, _cursor, _total = queries.list_users(db, phone=phone)
|
||||
item = next(x for x in users if x.id == uid)
|
||||
assert activity.norm_utc(item.last_active_at) == created # 登录不算 → last_active=created_at
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_run_warn_isolates_notifier_failure_and_does_not_block_reset() -> None:
|
||||
"""单用户通知器抛错:预警计 warn_failed、不外抛,且清零(reset)照常执行。"""
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import inactivity
|
||||
|
||||
class BoomNotifier:
|
||||
channel = "log"
|
||||
|
||||
def warn(self, *, user_id, coin, cash_cents, stage, days_until_reset) -> str:
|
||||
raise RuntimeError("push service down")
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
warn_uid = _new_user(db, created_at=datetime(2026, 1, 22, tzinfo=timezone.utc), coin=10) # 10天→预警
|
||||
clear_uid = _new_user(db, created_at=datetime(2026, 1, 5, tzinfo=timezone.utc), coin=10) # 27天→清零
|
||||
db.commit()
|
||||
|
||||
stats = inactivity.run_once(db, notifier=BoomNotifier(), reset_days=15,
|
||||
warn_stages=[7, 2], today=today)
|
||||
assert stats["warned"] == 0 and stats["warn_failed"] >= 1 # 预警失败被隔离
|
||||
assert stats["cleared"] == 1 # 关键:清零没被阻塞
|
||||
assert db.get(CoinAccount, clear_uid).coin_balance == 0
|
||||
assert db.get(CoinAccount, warn_uid).coin_balance == 10 # 预警用户不动钱
|
||||
# 预警失败已回滚,不留半条 notification_log
|
||||
from sqlalchemy import select
|
||||
assert db.execute(select(InactivityNotificationLog).where(
|
||||
InactivityNotificationLog.user_id == warn_uid)).first() is None
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
def test_run_once_reset_runs_even_if_warn_phase_throws(monkeypatch) -> None:
|
||||
"""预警整段异常(如候选查询失败)也绝不阻塞清零。"""
|
||||
from app.integrations.notifier import LogNotifier
|
||||
from app.models.wallet import CoinAccount
|
||||
from app.repositories import inactivity
|
||||
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("warn phase blew up")
|
||||
|
||||
monkeypatch.setattr(inactivity, "run_warn_once", boom)
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date(2026, 2, 1)
|
||||
clear_uid = _new_user(db, created_at=datetime(2026, 1, 5, tzinfo=timezone.utc), coin=10)
|
||||
db.commit()
|
||||
stats = inactivity.run_once(db, notifier=LogNotifier(), reset_days=15,
|
||||
warn_stages=[7, 2], today=today)
|
||||
assert stats["cleared"] == 1
|
||||
assert db.get(CoinAccount, clear_uid).coin_balance == 0
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
@@ -1,57 +0,0 @@
|
||||
"""ratelimit 内存桶过期清理(GC)测试。
|
||||
|
||||
回归重点:_buckets 是**全局共享**、混着不同窗口(60s 广告 / 3600s 登录 / 86400s 日闸)的 key。
|
||||
GC 必须按【每个 key 自己存的 window_sec】判过期,而不是当前调用方的窗口 —— 否则高频的 60s 端点
|
||||
触发 GC 时会把本该存活更久的 3600s/86400s 计数(如短信日闸)一并删掉,使其被反复清零、限流失效。
|
||||
用 monkeypatch 把 _GC_THRESHOLD 调 0 强制每次都扫,免造上万条(仿 test_auth 里对 sms._GC_THRESHOLD 的做法)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core import ratelimit
|
||||
|
||||
|
||||
def test_purge_expired_respects_each_key_own_window(monkeypatch) -> None:
|
||||
"""短窗口(60s)触发的 GC 只删真正过期的 key,不得删掉仍在自身窗口内的长窗口 key。"""
|
||||
monkeypatch.setattr(ratelimit, "_GC_THRESHOLD", 0) # 强制每次都扫
|
||||
ratelimit._buckets.clear()
|
||||
|
||||
now = 1_000_000.0
|
||||
# 日闸:100s 前开窗、window=86400 → 远未过期,必须保留
|
||||
ratelimit._buckets["sms-send-device-daily:D:IP"] = (now - 100, 7, 86400.0)
|
||||
# 登录:1800s、window=3600 → 未过期,保留
|
||||
ratelimit._buckets["sms-login-device:D:IP"] = (now - 1800, 2, 3600.0)
|
||||
# 广告:120s、window=60 → 已过期,应删
|
||||
ratelimit._buckets["ad-watch-report:IP2"] = (now - 120, 3, 60.0)
|
||||
|
||||
ratelimit._purge_expired(now)
|
||||
|
||||
assert "sms-send-device-daily:D:IP" in ratelimit._buckets
|
||||
assert "sms-login-device:D:IP" in ratelimit._buckets
|
||||
assert "ad-watch-report:IP2" not in ratelimit._buckets
|
||||
|
||||
|
||||
def test_purge_expired_keeps_long_window_key_older_than_short_window(monkeypatch) -> None:
|
||||
"""反证旧 bug:日闸 key 已老于 3600s,旧代码在 60s/3600s 端点触发 GC 时会误删它;
|
||||
现在按自身 86400s 窗口判 → 未过期 → 必须保留。"""
|
||||
monkeypatch.setattr(ratelimit, "_GC_THRESHOLD", 0)
|
||||
ratelimit._buckets.clear()
|
||||
|
||||
now = 2_000_000.0
|
||||
# 3700s 前开窗(> 1 小时),但 window=86400 → 未过期
|
||||
ratelimit._buckets["sms-send-device-daily:D:IP"] = (now - 3700, 20, 86400.0)
|
||||
|
||||
ratelimit._purge_expired(now)
|
||||
|
||||
assert "sms-send-device-daily:D:IP" in ratelimit._buckets
|
||||
|
||||
|
||||
def test_purge_expired_noop_below_threshold(monkeypatch) -> None:
|
||||
"""未超阈值时不扫(即便有过期 key 也不动),避免每次请求都 O(n) 扫全表。"""
|
||||
monkeypatch.setattr(ratelimit, "_GC_THRESHOLD", 10)
|
||||
ratelimit._buckets.clear()
|
||||
|
||||
now = 3_000_000.0
|
||||
ratelimit._buckets["stale:IP"] = (now - 999, 1, 60.0) # 早过期,但没超阈值
|
||||
ratelimit._purge_expired(now)
|
||||
|
||||
assert "stale:IP" in ratelimit._buckets # 桶数没超阈值 → 不清理
|
||||
@@ -1,232 +0,0 @@
|
||||
"""微信登录 M2 测试:conflict_ticket 令牌、继续绑定(attach/只登入)、换绑(建号+软删+30天限)。
|
||||
|
||||
沿用 tests/test_wechat_login.py 风格:HTTP 走 client;微信 code→openid 用 monkeypatch;
|
||||
短信走 SMS_MOCK(任意 6 位过)。数据变更用"再走一遍 wechat-login 看 openid 落在哪个账号"做行为断言。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.v1 import auth # noqa: F401 (后续测试打桩 verify_and_get_phone 用)
|
||||
from app.core import security
|
||||
from app.integrations import wxpay
|
||||
from app.models.phone_rebind_log import PhoneRebindLog
|
||||
|
||||
|
||||
def _fake_userinfo(openid: str, nickname: str | None = "微信昵称", avatar: str | None = "http://x/a.png"):
|
||||
def _f(code: str) -> dict:
|
||||
return {"openid": openid, "nickname": nickname, "avatar_url": avatar, "raw": {}}
|
||||
return _f
|
||||
|
||||
|
||||
def _sms_occupy(client, phone: str) -> int:
|
||||
"""用普通短信登录占用一个手机号(register_channel=sms),返回该账号 id。"""
|
||||
assert client.post("/api/v1/auth/sms/send", json={"phone": phone}).status_code == 200
|
||||
r = client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()["user"]["id"]
|
||||
|
||||
|
||||
def _occupy_via_conflict(client, monkeypatch, openid: str, phone: str, device_id: str) -> dict:
|
||||
"""微信登录(新 openid)→ 绑同一手机号 → 返回 phone_occupied 的响应体(含 conflict_ticket)。"""
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo(openid))
|
||||
ticket = client.post(
|
||||
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": device_id}
|
||||
).json()["bind_ticket"]
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/sms",
|
||||
json={"bind_ticket": ticket, "phone": phone, "code": "123456", "device_id": device_id},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "phone_occupied"
|
||||
return body
|
||||
|
||||
|
||||
# ===== Task 1: 模型可导入(建表由 conftest 的 create_all 完成) =====
|
||||
|
||||
def test_phone_rebind_log_model_importable() -> None:
|
||||
assert PhoneRebindLog.__tablename__ == "phone_rebind_log"
|
||||
|
||||
|
||||
# ===== Task 2: conflict_ticket 令牌 =====
|
||||
|
||||
def test_conflict_ticket_roundtrip() -> None:
|
||||
token = security.create_conflict_ticket(
|
||||
openid="oid1", wechat_nickname="昵", wechat_avatar_url="http://a", phone="13900139000"
|
||||
)
|
||||
claims = security.decode_conflict_ticket(token)
|
||||
assert claims["openid"] == "oid1"
|
||||
assert claims["wnk"] == "昵"
|
||||
assert claims["wav"] == "http://a"
|
||||
assert claims["phone"] == "13900139000"
|
||||
|
||||
|
||||
def test_conflict_ticket_wrong_type_rejected() -> None:
|
||||
# bind_ticket 冒充 conflict_ticket → TokenError(typ 不匹配)
|
||||
bind = security.create_bind_ticket(openid="oid", wechat_nickname=None, wechat_avatar_url=None)
|
||||
with pytest.raises(security.TokenError):
|
||||
security.decode_conflict_ticket(bind)
|
||||
|
||||
|
||||
def test_conflict_ticket_expired_rejected(monkeypatch) -> None:
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
token = security.create_conflict_ticket(
|
||||
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139000"
|
||||
)
|
||||
with pytest.raises(security.TokenError):
|
||||
security.decode_conflict_ticket(token)
|
||||
|
||||
|
||||
# ===== Task 3: 占用响应扩展 =====
|
||||
|
||||
def test_phone_occupied_returns_conflict_ticket_and_flags(client, monkeypatch) -> None:
|
||||
phone = "13900139101"
|
||||
_sms_occupy(client, phone) # 老账号 X(sms,无微信)
|
||||
body = _occupy_via_conflict(client, monkeypatch, "openid_occ_101", phone, "devO1")
|
||||
assert body["conflict_ticket"]
|
||||
assert body["rebind_available"] is True # 首次,未换绑过
|
||||
assert body["rebind_blocked_days"] == 0
|
||||
assert body["occupied_account"]["has_wechat"] is False # X 是 sms 账号
|
||||
|
||||
|
||||
# ===== Task 4: 继续绑定 =====
|
||||
|
||||
def test_continue_attaches_wechat_and_logs_into_existing(client, monkeypatch) -> None:
|
||||
"""X 无微信 → 继续绑定并入 openid + 登入 X;之后同 openid 登录直接命中 X。"""
|
||||
phone = "13900139201"
|
||||
x_id = _sms_occupy(client, phone) # X:sms 账号,无微信
|
||||
body = _occupy_via_conflict(client, monkeypatch, "openid_cont_201", phone, "devC1")
|
||||
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/continue",
|
||||
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC1"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "logged_in"
|
||||
assert r.json()["token"]["user"]["id"] == x_id # 登入的是老账号 X
|
||||
|
||||
# openid 现已并入 X:再走 wechat-login 直接命中 X
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC1"})
|
||||
assert r.json()["status"] == "logged_in"
|
||||
assert r.json()["token"]["user"]["id"] == x_id
|
||||
|
||||
|
||||
def test_continue_when_existing_has_wechat_logs_in_and_discards_openid(client, monkeypatch) -> None:
|
||||
"""X 已绑别的微信 → 继续绑定只登入 X、丢弃本次 openid(不覆盖)。"""
|
||||
phone = "13900139202"
|
||||
# 先建一个已绑微信 O1 的账号 X(微信登录 O1 + 短信绑号)
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o1_202"))
|
||||
t = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2"}).json()["bind_ticket"]
|
||||
x = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/sms",
|
||||
json={"bind_ticket": t, "phone": phone, "code": "123456", "device_id": "devC2"},
|
||||
).json()
|
||||
x_id = x["token"]["user"]["id"]
|
||||
|
||||
# 新 openid O2 撞同号 → 占用(has_wechat=True)→ 继续绑定
|
||||
body = _occupy_via_conflict(client, monkeypatch, "openid_o2_202", phone, "devC2b")
|
||||
assert body["occupied_account"]["has_wechat"] is True
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/continue",
|
||||
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC2b"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["token"]["user"]["id"] == x_id # 登入 X
|
||||
|
||||
# O2 被丢弃:再走 wechat-login(O2)→ 仍未命中(need_bind_phone)
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o2_202"))
|
||||
assert client.post(
|
||||
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2b"}
|
||||
).json()["status"] == "need_bind_phone"
|
||||
|
||||
|
||||
def test_continue_expired_ticket_returns_401(client, monkeypatch) -> None:
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
expired = security.create_conflict_ticket(
|
||||
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139209"
|
||||
)
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/continue",
|
||||
json={"conflict_ticket": expired, "device_id": "devC3"},
|
||||
)
|
||||
assert r.status_code == 401, r.text
|
||||
|
||||
|
||||
# ===== Task 5: 换绑 =====
|
||||
|
||||
def test_rebind_creates_new_account_and_binds_openid(client, monkeypatch) -> None:
|
||||
"""换绑 → 建全新微信账号 Y(≠X)+ openid 落到 Y;老账号 X 被注销(手机号归 Y)。"""
|
||||
phone = "13900139301"
|
||||
x_id = _sms_occupy(client, phone)
|
||||
body = _occupy_via_conflict(client, monkeypatch, "openid_rb_301", phone, "devR1")
|
||||
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/rebind",
|
||||
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR1"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
y = r.json()["token"]["user"]
|
||||
assert r.json()["status"] == "logged_in"
|
||||
assert y["phone"] == phone
|
||||
assert y["register_channel"] == "wechat"
|
||||
assert y["id"] != x_id # 是全新账号,不是老账号
|
||||
|
||||
# openid 落到 Y:再走 wechat-login 命中 Y
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devR1"})
|
||||
assert r.json()["status"] == "logged_in"
|
||||
assert r.json()["token"]["user"]["id"] == y["id"]
|
||||
|
||||
|
||||
# ===== §10: continue 路径也应用展示身份回填规则 =====
|
||||
|
||||
def test_continue_applies_section10(client, monkeypatch) -> None:
|
||||
"""§10 via M2 attach 路径: X 是默认昵称+null头像的 sms 账号;
|
||||
continue 绑定微信后,展示昵称/头像应被微信值替换,并体现在响应的 token.user 中。"""
|
||||
phone = "13900139211"
|
||||
_sms_occupy(client, phone) # 建 X:默认昵称, null avatar
|
||||
body = _occupy_via_conflict(
|
||||
client, monkeypatch, "openid_s10", phone, "devS10"
|
||||
) # fake_userinfo 默认 nickname="微信昵称", avatar="http://x/a.png"
|
||||
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/continue",
|
||||
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devS10"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
user_out = r.json()["token"]["user"]
|
||||
assert user_out["nickname"] == "微信昵称"
|
||||
assert user_out["avatar_url"] == "http://x/a.png"
|
||||
|
||||
|
||||
def test_rebind_blocked_within_30_days(client, monkeypatch) -> None:
|
||||
"""同一手机号 30 天内二次换绑 → 409;占用响应 rebind_available=False。"""
|
||||
phone = "13900139302"
|
||||
_sms_occupy(client, phone)
|
||||
body = _occupy_via_conflict(client, monkeypatch, "openid_rb_302a", phone, "devR2")
|
||||
assert client.post(
|
||||
"/api/v1/auth/wechat/conflict/rebind",
|
||||
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR2"},
|
||||
).status_code == 200
|
||||
|
||||
# 第二次:新 openid 撞同号 → 占用响应此时 rebind_available=False
|
||||
body2 = _occupy_via_conflict(client, monkeypatch, "openid_rb_302b", phone, "devR2b")
|
||||
assert body2["rebind_available"] is False
|
||||
assert body2["rebind_blocked_days"] >= 1
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/rebind",
|
||||
json={"conflict_ticket": body2["conflict_ticket"], "device_id": "devR2b"},
|
||||
)
|
||||
assert r.status_code == 409, r.text
|
||||
|
||||
|
||||
def test_rebind_expired_ticket_returns_401(client, monkeypatch) -> None:
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
expired = security.create_conflict_ticket(
|
||||
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139309"
|
||||
)
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/conflict/rebind",
|
||||
json={"conflict_ticket": expired, "device_id": "devR3"},
|
||||
)
|
||||
assert r.status_code == 401, r.text
|
||||
@@ -1,198 +0,0 @@
|
||||
"""微信登录 M1 测试:bind_ticket 令牌、wechat-login(openid 命中/未命中)、
|
||||
bind-phone(建号/占用/令牌过期)。
|
||||
|
||||
沿用 tests/test_auth.py 风格:HTTP 走 client fixture;微信 code→openid 用 monkeypatch
|
||||
拦掉(conftest 里 WECHAT_APP_ID/SECRET 是 dummy,不真连微信);短信走 SMS_MOCK(任意 6 位通过)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.v1 import auth
|
||||
from app.core import security
|
||||
from app.integrations import wxpay
|
||||
|
||||
|
||||
def _fake_userinfo(openid: str, nickname: str | None = "微信昵称", avatar: str | None = "http://x/a.png"):
|
||||
"""返回一个可传给 monkeypatch 的假 code_to_userinfo(忽略 code,固定返回给定 openid)。"""
|
||||
def _f(code: str) -> dict:
|
||||
return {"openid": openid, "nickname": nickname, "avatar_url": avatar, "raw": {}}
|
||||
return _f
|
||||
|
||||
|
||||
# ===== Task 1: bind_ticket 令牌 =====
|
||||
|
||||
def test_bind_ticket_roundtrip() -> None:
|
||||
token = security.create_bind_ticket(openid="oid1", wechat_nickname="昵", wechat_avatar_url="http://a")
|
||||
claims = security.decode_bind_ticket(token)
|
||||
assert claims["openid"] == "oid1"
|
||||
assert claims["wnk"] == "昵"
|
||||
assert claims["wav"] == "http://a"
|
||||
|
||||
|
||||
def test_bind_ticket_wrong_type_rejected() -> None:
|
||||
# 用 access token 冒充 bind_ticket → TokenError(typ 不匹配)
|
||||
access, _ = security.create_token(user_id=1, token_type="access")
|
||||
with pytest.raises(security.TokenError):
|
||||
security.decode_bind_ticket(access)
|
||||
|
||||
|
||||
def test_bind_ticket_expired_rejected(monkeypatch) -> None:
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
token = security.create_bind_ticket(openid="oid", wechat_nickname=None, wechat_avatar_url=None)
|
||||
with pytest.raises(security.TokenError):
|
||||
security.decode_bind_ticket(token)
|
||||
|
||||
|
||||
# ===== Task 2: wechat-login =====
|
||||
|
||||
def test_wechat_login_new_openid_returns_bind_ticket(client, monkeypatch) -> None:
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_new_1", "小明", "http://x/m.png"))
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "wxcode1", "device_id": "devA"})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "need_bind_phone"
|
||||
assert body["bind_ticket"]
|
||||
assert body["wechat_nickname"] == "小明"
|
||||
assert body["wechat_avatar_url"] == "http://x/m.png"
|
||||
assert body["token"] is None
|
||||
|
||||
|
||||
def test_wechat_login_invalid_code_returns_400(client, monkeypatch) -> None:
|
||||
def _raise(code: str) -> dict:
|
||||
raise ValueError("微信授权失败: invalid code")
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _raise)
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "bad", "device_id": "devA"})
|
||||
assert r.status_code == 400, r.text
|
||||
|
||||
|
||||
# ===== Task 3: bind-phone/sms =====
|
||||
|
||||
def test_wechat_bind_sms_creates_account_then_openid_logs_in(client, monkeypatch) -> None:
|
||||
"""未占用 → 建微信账号(channel=wechat,昵称头像取微信);再次同 openid 登录 → 直接登入同一账号。"""
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_flow_2", "阿花", "http://x/h.png"))
|
||||
phone = "13900139002"
|
||||
|
||||
# 1) 微信登录 → 未命中 → 拿 ticket
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "c1", "device_id": "devB"})
|
||||
ticket = r.json()["bind_ticket"]
|
||||
assert ticket
|
||||
|
||||
# 2) 短信绑号(SMS_MOCK:任意 6 位通过)→ 建号 + 登入
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/sms",
|
||||
json={"bind_ticket": ticket, "phone": phone, "code": "123456", "device_id": "devB"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "logged_in"
|
||||
user = body["token"]["user"]
|
||||
assert user["phone"] == phone
|
||||
assert user["register_channel"] == "wechat"
|
||||
assert user["nickname"] == "阿花"
|
||||
assert user["avatar_url"] == "http://x/h.png"
|
||||
uid = user["id"]
|
||||
|
||||
# 3) 再次微信登录(同 openid)→ 命中 → 直接登入同一账号
|
||||
r = client.post("/api/v1/auth/wechat-login", json={"code": "c2", "device_id": "devB"})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "logged_in"
|
||||
assert body["token"]["user"]["id"] == uid
|
||||
|
||||
|
||||
def test_wechat_bind_sms_phone_occupied(client, monkeypatch) -> None:
|
||||
"""手机号已被其他账号占用 → 返回 phone_occupied + 原账号信息(不建号)。"""
|
||||
phone = "13900139003"
|
||||
# 先用普通短信登录占用该手机号(register_channel=sms)
|
||||
assert client.post("/api/v1/auth/sms/send", json={"phone": phone}).status_code == 200
|
||||
r = client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"})
|
||||
assert r.status_code == 200, r.text
|
||||
occupied_nickname = r.json()["user"]["nickname"]
|
||||
|
||||
# 微信登录(新 openid)→ 未命中 → ticket
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_occ_3"))
|
||||
ticket = client.post(
|
||||
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC"}
|
||||
).json()["bind_ticket"]
|
||||
|
||||
# 绑同一手机号 → 占用
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/sms",
|
||||
json={"bind_ticket": ticket, "phone": phone, "code": "123456", "device_id": "devC"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "phone_occupied"
|
||||
assert body["token"] is None
|
||||
assert body["occupied_account"]["nickname"] == occupied_nickname
|
||||
assert body["occupied_account"]["avatar_url"] is None # 短信注册账号无头像 → 序列化为 null
|
||||
assert body["occupied_account"]["created_at"]
|
||||
|
||||
|
||||
def test_wechat_bind_sms_expired_ticket_returns_401(client, monkeypatch) -> None:
|
||||
"""过期 bind_ticket → 401。"""
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
expired = security.create_bind_ticket(openid="openid_exp", wechat_nickname="x", wechat_avatar_url=None)
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/sms",
|
||||
json={"bind_ticket": expired, "phone": "13900139009", "code": "123456", "device_id": "devD"},
|
||||
)
|
||||
assert r.status_code == 401, r.text
|
||||
|
||||
|
||||
# ===== Task 4: bind-phone/jverify =====
|
||||
|
||||
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)
|
||||
|
||||
ticket = client.post(
|
||||
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devE"}
|
||||
).json()["bind_ticket"]
|
||||
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/jverify",
|
||||
json={"bind_ticket": ticket, "login_token": "jgtoken", "device_id": "devE"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "logged_in"
|
||||
user = body["token"]["user"]
|
||||
assert user["phone"] == phone
|
||||
assert user["register_channel"] == "wechat"
|
||||
assert user["nickname"] == "极光用户"
|
||||
# 微信 userinfo 隐私脱敏 avatar=None → 头像为空(客户端兜底默认头像)
|
||||
assert user["avatar_url"] is None
|
||||
|
||||
|
||||
def test_wechat_bind_jverify_expired_ticket_returns_401(client, monkeypatch) -> None:
|
||||
"""过期 bind_ticket → 401(极光绑号路径,decode 先于极光核验)。"""
|
||||
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
||||
expired = security.create_bind_ticket(openid="openid_jv_exp", wechat_nickname="x", wechat_avatar_url=None)
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/jverify",
|
||||
json={"bind_ticket": expired, "login_token": "jgtoken", "device_id": "devE"},
|
||||
)
|
||||
assert r.status_code == 401, r.text
|
||||
|
||||
|
||||
def test_wechat_bind_jverify_jiguang_error_returns_502(client, monkeypatch) -> None:
|
||||
"""极光核验失败(JiguangError)→ 502。"""
|
||||
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_jv_err"))
|
||||
|
||||
def _raise(token: str) -> str:
|
||||
raise auth.JiguangError("mock jg failure")
|
||||
|
||||
monkeypatch.setattr(auth, "verify_and_get_phone", _raise)
|
||||
ticket = client.post(
|
||||
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devE"}
|
||||
).json()["bind_ticket"]
|
||||
r = client.post(
|
||||
"/api/v1/auth/wechat/bind-phone/jverify",
|
||||
json={"bind_ticket": ticket, "login_token": "badtoken", "device_id": "devE"},
|
||||
)
|
||||
assert r.status_code == 502, r.text
|
||||
@@ -312,94 +312,6 @@ def test_bind_rejects_openid_already_bound(client, monkeypatch) -> None:
|
||||
assert r.status_code == 409, r.text
|
||||
|
||||
|
||||
# ===== §10 绑微信时展示身份回填规则 =====
|
||||
|
||||
def test_bind_replaces_default_nickname_and_null_avatar(client, monkeypatch) -> None:
|
||||
"""§10-A: 全默认(昵称=系统默认,头像=null) → 绑微信后两个展示字段都替换为微信值。"""
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.code_to_userinfo",
|
||||
lambda code: {"openid": "openid_s10_a", "nickname": "微信昵称A", "avatar_url": "https://x/a.png", "raw": {}},
|
||||
)
|
||||
token = _login(client, "13800003001")
|
||||
r = client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
r = client.get("/api/v1/auth/me", headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["nickname"] == "微信昵称A"
|
||||
assert body["avatar_url"] == "https://x/a.png"
|
||||
|
||||
|
||||
def test_bind_keeps_customized_nickname(client, monkeypatch) -> None:
|
||||
"""§10-B: 用户已改过昵称 → 绑微信后昵称保留,但 null 头像仍替换为微信头像。"""
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.code_to_userinfo",
|
||||
lambda code: {"openid": "openid_s10_b", "nickname": "微信昵称B", "avatar_url": "https://x/b.png", "raw": {}},
|
||||
)
|
||||
token = _login(client, "13800003002")
|
||||
# 先把昵称改成非默认值
|
||||
r = client.patch(
|
||||
"/api/v1/user/profile", json={"nickname": "我的名字"}, headers=_auth(token)
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
r = client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
r = client.get("/api/v1/auth/me", headers=_auth(token))
|
||||
body = r.json()
|
||||
assert body["nickname"] == "我的名字" # 保留自定义昵称
|
||||
assert body["avatar_url"] == "https://x/b.png" # null 头像被微信头像替换
|
||||
|
||||
|
||||
def test_bind_keeps_customized_avatar(client, monkeypatch) -> None:
|
||||
"""§10-C: 已有自定义头像 → 绑微信后头像保留,但默认昵称替换为微信昵称。"""
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.code_to_userinfo",
|
||||
lambda code: {"openid": "openid_s10_c", "nickname": "微信昵称C", "avatar_url": "https://x/c.png", "raw": {}},
|
||||
)
|
||||
token = _login(client, "13800003003")
|
||||
phone = "13800003003"
|
||||
# 直接用 DB 给用户写入自定义头像(保持默认昵称)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = db.execute(select(User).where(User.phone == phone)).scalar_one()
|
||||
user.avatar_url = "https://custom/av.png"
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
r = client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
r = client.get("/api/v1/auth/me", headers=_auth(token))
|
||||
body = r.json()
|
||||
assert body["nickname"] == "微信昵称C" # 默认昵称被替换
|
||||
assert body["avatar_url"] == "https://custom/av.png" # 自定义头像保留
|
||||
|
||||
|
||||
def test_bind_wechat_empty_keeps_default(client, monkeypatch) -> None:
|
||||
"""§10-D: 微信侧 nickname/avatar 均为 None → 不覆盖,展示字段维持原默认值。"""
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.code_to_userinfo",
|
||||
lambda code: {"openid": "openid_s10_d", "nickname": None, "avatar_url": None, "raw": {}},
|
||||
)
|
||||
token = _login(client, "13800003004")
|
||||
|
||||
r = client.get("/api/v1/auth/me", headers=_auth(token))
|
||||
original_nickname = r.json()["nickname"] # 系统分配的默认昵称
|
||||
assert original_nickname.startswith("用户")
|
||||
|
||||
r = client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
r = client.get("/api/v1/auth/me", headers=_auth(token))
|
||||
body = r.json()
|
||||
assert body["nickname"] == original_nickname # 默认昵称不变
|
||||
assert body["avatar_url"] is None # 头像仍为 null
|
||||
|
||||
|
||||
def test_withdraw_reject_refunds(client, monkeypatch) -> None:
|
||||
"""管理员审核拒绝 → 退回现金 + 单 rejected + 理由写入 fail_reason(用户可见)。"""
|
||||
monkeypatch.setattr("app.integrations.wxpay.code_to_userinfo", lambda code: {"openid": "openid_reject", "nickname": None, "avatar_url": None, "raw": {}})
|
||||
|
||||
Reference in New Issue
Block a user