Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f37eef75f2 | |||
| 07c0b7502c | |||
| 67a9a15775 | |||
| 8fea6d2b5d | |||
| 1893c01f54 | |||
| 0b8037c725 | |||
| 1a893d8d96 |
@@ -0,0 +1,62 @@
|
||||
"""withdraw_order.user_name 列 + ad_watch_log 表
|
||||
|
||||
提现审核功能:WithdrawOrder 加 user_name(审核异步打款时传给微信的实名,达额转账要求)。
|
||||
看广告时长防刷:新增 ad_watch_log 表(前端 onAdClose 上报观看秒数,按 (user_id, watch_date)
|
||||
聚合做"每天 50 分钟"硬上限)。
|
||||
|
||||
Revision ID: withdraw_review_ad_watch
|
||||
Revises: ebb6af5c0b56
|
||||
Create Date: 2026-06-05 12:00:00.000000
|
||||
|
||||
注:本迁移原 down_revision=ad60a1b2c3d4(分支创建时的 head);rebase 合 main 后 main 侧已新增
|
||||
app_config / price_report 等迁移并 merge 出 head=ebb6af5c0b56,故改挂到其上,保持单 head(本迁移
|
||||
与那些表互不相干,叠加顺序无影响)。
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'withdraw_review_ad_watch'
|
||||
down_revision: Union[str, Sequence[str], None] = 'ebb6af5c0b56'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ① 提现单加实名列:审核通过后异步打款时传给微信(达额转账要求),发起提现时存下
|
||||
with op.batch_alter_table('withdraw_order', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('user_name', sa.String(length=64), nullable=True))
|
||||
|
||||
# ② 看广告观看时长表:前端上报观看秒数,(user_id, watch_date) 聚合做每日 50 分钟防刷主闸
|
||||
op.create_table(
|
||||
'ad_watch_log',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('watch_seconds', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('watch_date', sa.String(length=10), nullable=False),
|
||||
sa.Column(
|
||||
'created_at', sa.DateTime(timezone=True),
|
||||
server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
with op.batch_alter_table('ad_watch_log', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_ad_watch_log_user_id'), ['user_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_ad_watch_log_watch_date'), ['watch_date'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_ad_watch_log_created_at'), ['created_at'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('ad_watch_log', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_ad_watch_log_created_at'))
|
||||
batch_op.drop_index(batch_op.f('ix_ad_watch_log_watch_date'))
|
||||
batch_op.drop_index(batch_op.f('ix_ad_watch_log_user_id'))
|
||||
op.drop_table('ad_watch_log')
|
||||
|
||||
with op.batch_alter_table('withdraw_order', schema=None) as batch_op:
|
||||
batch_op.drop_column('user_name')
|
||||
@@ -14,7 +14,7 @@ from app.admin.audit import write_audit
|
||||
from app.admin.deps import AdminDb, get_client_ip, get_current_admin, require_role
|
||||
from app.admin.repositories import queries
|
||||
from app.admin.schemas.common import CursorPage
|
||||
from app.admin.schemas.wallet import ReconcileResult, WithdrawOrderOut
|
||||
from app.admin.schemas.wallet import ReconcileResult, WithdrawOrderOut, WithdrawRejectRequest
|
||||
from app.integrations import wxpay
|
||||
from app.models.admin import AdminUser
|
||||
from app.repositories import wallet as wallet_repo
|
||||
@@ -83,3 +83,58 @@ def refresh_withdraw(
|
||||
ip=get_client_ip(request), commit=True,
|
||||
)
|
||||
return WithdrawOrderOut.model_validate(refreshed)
|
||||
|
||||
|
||||
@router.post("/{out_bill_no}/approve", response_model=WithdrawOrderOut, summary="审核通过(发起微信打款)")
|
||||
def approve_withdraw_order(
|
||||
out_bill_no: str,
|
||||
request: Request,
|
||||
admin: Annotated[AdminUser, Depends(require_role("finance"))],
|
||||
db: AdminDb,
|
||||
) -> WithdrawOrderOut:
|
||||
"""审核通过 → 调微信转账。仅 reviewing 单可通过(非 reviewing 返 409,防重复打款)。
|
||||
|
||||
打款的钱逻辑(转账/查单/退款/幂等)复用 wallet_repo.approve_withdraw → execute_withdraw_transfer;
|
||||
返回的 order 可能是 pending(在途/待用户确认)/success/failed(打款失败已退),admin 前端按 status 展示。
|
||||
"""
|
||||
try:
|
||||
order = wallet_repo.approve_withdraw(db, out_bill_no)
|
||||
except wallet_repo.WithdrawOrderNotFound as e:
|
||||
raise HTTPException(status_code=404, detail="提现单不存在") from e
|
||||
except wallet_repo.WithdrawNotReviewable as e:
|
||||
raise HTTPException(status_code=409, detail=str(e)) from e
|
||||
except wxpay.WxPayNotConfiguredError as e:
|
||||
raise HTTPException(status_code=503, detail="微信支付未配置") from e
|
||||
write_audit(
|
||||
db, admin, action="withdraw.approve", target_type="withdraw", target_id=out_bill_no,
|
||||
detail={
|
||||
"status": order.status,
|
||||
"wechat_state": order.wechat_state,
|
||||
"amount_cents": order.amount_cents,
|
||||
},
|
||||
ip=get_client_ip(request), commit=True,
|
||||
)
|
||||
return WithdrawOrderOut.model_validate(order)
|
||||
|
||||
|
||||
@router.post("/{out_bill_no}/reject", response_model=WithdrawOrderOut, summary="审核拒绝(退回现金)")
|
||||
def reject_withdraw_order(
|
||||
out_bill_no: str,
|
||||
body: WithdrawRejectRequest,
|
||||
request: Request,
|
||||
admin: Annotated[AdminUser, Depends(require_role("finance"))],
|
||||
db: AdminDb,
|
||||
) -> WithdrawOrderOut:
|
||||
"""审核拒绝 → 退回用户现金 + 置 rejected,理由写入 fail_reason(用户可见)。仅 reviewing 单可拒。"""
|
||||
try:
|
||||
order = wallet_repo.reject_withdraw(db, out_bill_no, body.reason)
|
||||
except wallet_repo.WithdrawOrderNotFound as e:
|
||||
raise HTTPException(status_code=404, detail="提现单不存在") from e
|
||||
except wallet_repo.WithdrawNotReviewable as e:
|
||||
raise HTTPException(status_code=409, detail=str(e)) from e
|
||||
write_audit(
|
||||
db, admin, action="withdraw.reject", target_type="withdraw", target_id=out_bill_no,
|
||||
detail={"reason": body.reason, "amount_cents": order.amount_cents},
|
||||
ip=get_client_ip(request), commit=True,
|
||||
)
|
||||
return WithdrawOrderOut.model_validate(order)
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class CoinTxnOut(BaseModel):
|
||||
@@ -39,6 +39,7 @@ class WithdrawOrderOut(BaseModel):
|
||||
user_id: int
|
||||
out_bill_no: str
|
||||
amount_cents: int
|
||||
user_name: str | None = None # 提现实名(审核核对 + 打款用)
|
||||
status: str
|
||||
wechat_state: str | None = None
|
||||
transfer_bill_no: str | None = None
|
||||
@@ -50,3 +51,9 @@ class WithdrawOrderOut(BaseModel):
|
||||
class ReconcileResult(BaseModel):
|
||||
checked: int
|
||||
resolved: int
|
||||
|
||||
|
||||
class WithdrawRejectRequest(BaseModel):
|
||||
reason: str = Field(
|
||||
..., min_length=1, max_length=200, description="拒绝理由(写入 fail_reason,用户可见)"
|
||||
)
|
||||
|
||||
+36
-2
@@ -21,12 +21,15 @@ from app.integrations import pangle
|
||||
from app.core.ratelimit import rate_limit
|
||||
from app.repositories import ad_ecpm as crud_ecpm
|
||||
from app.repositories import ad_reward as crud_ad
|
||||
from app.repositories import ad_watch as crud_watch
|
||||
from app.schemas.ad import (
|
||||
AdRewardStatusOut,
|
||||
EcpmReportIn,
|
||||
EcpmReportOut,
|
||||
PangleCallbackOut,
|
||||
TestGrantOut,
|
||||
WatchReportIn,
|
||||
WatchReportOut,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("shagua.ad")
|
||||
@@ -91,7 +94,8 @@ def pangle_callback(request: Request, db: DbSession) -> PangleCallbackOut:
|
||||
|
||||
@router.get("/reward-status", response_model=AdRewardStatusOut, summary="今日看广告发奖进度")
|
||||
def reward_status(user: CurrentUser, db: DbSession) -> AdRewardStatusOut:
|
||||
used, limit, coin_per, round_count, cooldown_until = crud_ad.today_status(db, user.id)
|
||||
(used, limit, coin_per, round_count, cooldown_until,
|
||||
watched_sec, watch_limit) = crud_ad.today_status(db, user.id)
|
||||
return AdRewardStatusOut(
|
||||
used_today=used,
|
||||
daily_limit=limit,
|
||||
@@ -99,6 +103,35 @@ def reward_status(user: CurrentUser, db: DbSession) -> AdRewardStatusOut:
|
||||
coin_per_ad=coin_per,
|
||||
round_count=round_count,
|
||||
cooldown_until=cooldown_until,
|
||||
watched_seconds_today=watched_sec,
|
||||
watch_seconds_limit=watch_limit,
|
||||
watch_seconds_remaining=max(0, watch_limit - watched_sec),
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/watch-report",
|
||||
response_model=WatchReportOut,
|
||||
summary="上报激励视频观看时长(每日 50 分钟防刷计时)",
|
||||
dependencies=[Depends(rate_limit(120, 60, "ad-watch-report"))],
|
||||
)
|
||||
def watch_report(payload: WatchReportIn, user: CurrentUser, db: DbSession) -> WatchReportOut:
|
||||
"""客户端在激励视频关闭(onAdClose)后上报本次实际观看秒数,服务端累计到当日总时长。
|
||||
|
||||
Bearer 鉴权,user_id 取自 JWT(不信 body)。seconds 服务端夹 [0, MAX_SINGLE_WATCH_SECONDS]。
|
||||
当日累计达 DAILY_AD_WATCH_SECONDS_LIMIT(50 分钟)后:① 本接口 / reward-status 返回 remaining=0,
|
||||
客户端不再展示广告;② 后端发奖(S2S 回调)也会因时长闸记 capped 不发金币(双闸,前端绕不过)。
|
||||
"""
|
||||
total = crud_watch.add_watch_seconds(db, user.id, payload.seconds)
|
||||
limit = rewards.DAILY_AD_WATCH_SECONDS_LIMIT
|
||||
logger.info(
|
||||
"ad watch report user_id=%d +%ds total=%d/%d",
|
||||
user.id, payload.seconds, total, limit,
|
||||
)
|
||||
return WatchReportOut(
|
||||
watched_seconds_today=total,
|
||||
watch_seconds_limit=limit,
|
||||
watch_seconds_remaining=max(0, limit - total),
|
||||
)
|
||||
|
||||
|
||||
@@ -151,7 +184,8 @@ def test_grant(user: CurrentUser, db: DbSession) -> TestGrantOut:
|
||||
except crud_ad.UnknownUserError as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user not found") from e
|
||||
|
||||
used, limit, coin_per, round_count, cooldown_until = crud_ad.today_status(db, user.id)
|
||||
(used, limit, coin_per, round_count, cooldown_until,
|
||||
_watched, _watch_limit) = crud_ad.today_status(db, user.id)
|
||||
logger.info("ad TEST grant user_id=%d status=%s coin=%d", user.id, rec.status, rec.coin)
|
||||
return TestGrantOut(
|
||||
granted=(rec.status == "granted"),
|
||||
|
||||
@@ -42,6 +42,7 @@ def battle(user: CurrentUser, db: DbSession) -> SavingsBattleOut:
|
||||
week_saved_cents=b.week_saved_cents,
|
||||
beat_percent=b.beat_percent,
|
||||
streak_days=b.streak_days,
|
||||
compare_count=b.compare_count,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+13
-5
@@ -170,10 +170,11 @@ def withdraw_info(user: CurrentUser, db: DbSession) -> WithdrawInfoOut:
|
||||
@router.post(
|
||||
"/withdraw",
|
||||
response_model=WithdrawResultOut,
|
||||
summary="发起提现到微信零钱",
|
||||
summary="发起提现(扣款建单,待人工审核;审核通过后才打款)",
|
||||
dependencies=[Depends(rate_limit(20, 60, "withdraw"))], # #6 同 IP 每分钟≤20 次
|
||||
)
|
||||
def withdraw(req: WithdrawRequest, user: CurrentUser, db: DbSession) -> WithdrawResultOut:
|
||||
# 提现发起本身不调微信(打款在审核通过后),但仍要求微信支付已配置——否则审核通过也打不了款,提前拦
|
||||
if not settings.wxpay_configured:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="wechat pay not configured")
|
||||
try:
|
||||
@@ -189,12 +190,14 @@ def withdraw(req: WithdrawRequest, user: CurrentUser, db: DbSession) -> Withdraw
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="wechat not bound") from e
|
||||
except crud_wallet.InsufficientCashError as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="insufficient cash balance") from e
|
||||
except crud_wallet.WithdrawTransferError as e:
|
||||
# 转账调用失败,余额已退回
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"wechat transfer failed: {e}") from e
|
||||
|
||||
acc = crud_wallet.get_or_create_account(db, user.id)
|
||||
logger.info("withdraw user_id=%d cents=%d bill=%s state=%s", user.id, req.amount_cents, order.out_bill_no, order.wechat_state)
|
||||
logger.info(
|
||||
"withdraw submitted user_id=%d cents=%d bill=%s status=%s(待审核)",
|
||||
user.id, req.amount_cents, order.out_bill_no, order.status,
|
||||
)
|
||||
# 此刻 status=reviewing,尚未打款 → 无 package_info;App 据 status 提示"已提交,等待审核"。
|
||||
# 审核通过后客户端轮询 /withdraw/status 拿到 package_info(若需确认)再拉起微信确认页。
|
||||
return WithdrawResultOut(
|
||||
out_bill_no=order.out_bill_no,
|
||||
status=order.status,
|
||||
@@ -223,6 +226,11 @@ def withdraw_status(
|
||||
status=order.status,
|
||||
wechat_state=order.wechat_state,
|
||||
amount_cents=order.amount_cents,
|
||||
fail_reason=order.fail_reason,
|
||||
# 审核通过后 status=pending 且可能带 package_info(WAIT_USER_CONFIRM):供 App 拉起微信确认页
|
||||
package_info=order.package_info,
|
||||
mch_id=settings.WXPAY_MCH_ID if order.package_info else None,
|
||||
app_id=settings.WECHAT_APP_ID if order.package_info else None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+18
-6
@@ -34,8 +34,9 @@ COIN_PER_YUAN: int = 10000
|
||||
CENTS_PER_YUAN: int = 100
|
||||
# 1 分对应多少金币 = 100。兑换金币数必须是它的整数倍,否则会出现不足 1 分的零头。
|
||||
COIN_PER_CENT: int = COIN_PER_YUAN // CENTS_PER_YUAN
|
||||
# 单次兑换最少 1 元(避免大量 1 分级碎兑)
|
||||
MIN_EXCHANGE_COIN: int = COIN_PER_YUAN
|
||||
# 单次兑换最少 1 分(=COIN_PER_CENT;产品定:可兑 1 分起,与 step 同粒度)。早先为 1 元(=COIN_PER_YUAN),
|
||||
# 用户 2026-06 改为 1 分:让"换现金"小额即可用(也方便联调验证资产卡飞金币动画)。
|
||||
MIN_EXCHANGE_COIN: int = COIN_PER_CENT
|
||||
|
||||
|
||||
def coins_to_cents(coin_amount: int) -> int:
|
||||
@@ -54,7 +55,7 @@ TASK_ENABLE_NOTIFICATION = "enable_notification"
|
||||
|
||||
# task_key -> 奖励金币
|
||||
# 打开消息提醒: 1000 金币(=¥0.1, 客户端原型展示口径; 量级与签到/里程碑相称)。
|
||||
# 注意: 已不再 = 兑换下限(MIN_EXCHANGE_COIN=10000), test_exchange_flow 改走 grant_coins 直接供款。
|
||||
# 注意: 不再 = 兑换下限(下限已降到 MIN_EXCHANGE_COIN=COIN_PER_CENT=100), test_exchange_flow 改走 grant_coins 直接供款。
|
||||
TASK_REWARDS: dict[str, int] = {
|
||||
TASK_ENABLE_NOTIFICATION: 1000,
|
||||
}
|
||||
@@ -82,9 +83,20 @@ def record_milestone_reward(milestone: int) -> int:
|
||||
AD_REWARD_COIN: int = 666
|
||||
# 单次发奖金币上限:夹紧穿山甲回调里异常的 reward_amount(如后台多打一个 0),防刷爆余额。
|
||||
MAX_AD_REWARD_COIN: int = 1000
|
||||
# 每用户每日发奖次数上限,防刷 + 控成本。
|
||||
# ⚠️ 测试阶段值=20:正式上线前按产品策略 + 广告 eCPM 实测收益重新核定,改这里即可。
|
||||
DAILY_AD_REWARD_LIMIT: int = 20
|
||||
# 每用户每日发奖次数上限——现作为"看广告时长上限"的**次数兜底**(防前端少报观看时长绕过时长闸)。
|
||||
# 主闸是 DAILY_AD_WATCH_SECONDS_LIMIT(50 分钟);次数兜底要 ≥ 时长闸内的"合理最大次数",
|
||||
# 否则会比主闸先掐、误伤看大量短广告的正常用户:50 分钟里若广告各 ~15s,理论可看 ~200 次,
|
||||
# 故取 200(≈时长闸的次数等价),正常用户先撞 50 分钟时长闸,仅前端时长全报 0 等异常时本闸才兜住。
|
||||
# 不要为"更严"而下调到 120 之类(会在 ~30 分钟就掐短广告用户);要更严应在客户端如实上报时长。
|
||||
DAILY_AD_REWARD_LIMIT: int = 200
|
||||
|
||||
# ===== 看激励视频每日总时长上限(防刷主闸)=====
|
||||
# 用户每天最多看 50 分钟激励视频,超了不发奖 / 不给看。时长由前端 onAdClose 上报真实观看
|
||||
# 秒数累计(POST /api/v1/ad/watch-report → ad_watch_log 表 SUM)。前端不可信,故配合上面
|
||||
# DAILY_AD_REWARD_LIMIT 次数兜底一起防刷。要调上限直接改这里。
|
||||
DAILY_AD_WATCH_SECONDS_LIMIT: int = 50 * 60 # 3000 秒 = 50 分钟
|
||||
# 单次上报观看时长的合理上限(夹紧异常值):激励视频一般 15~60 秒,超 120 秒按 120 记,防刷大值。
|
||||
MAX_SINGLE_WATCH_SECONDS: int = 120
|
||||
# 一轮看 N 次激励视频,看完一轮强制 10 分钟冷却(reward-status 派生 cooldown_until 给客户端,
|
||||
# 客户端任务行 CTA 在冷却期间显示"MM:SS"且不可点)。冷却是 UX 约束,后端发奖只看 daily_limit,
|
||||
# 冷却期间穿山甲回调仍照常发奖,不另设拒发分支。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""所有 ORM model 必须在这里 import 一次,Alembic / metadata 才能扫到。"""
|
||||
from app.models.ad_ecpm import AdEcpmRecord # noqa: F401
|
||||
from app.models.ad_reward import AdRewardRecord # noqa: F401
|
||||
from app.models.ad_watch_log import AdWatchLog # noqa: F401
|
||||
from app.models.admin import AdminAuditLog, AdminUser # noqa: F401
|
||||
from app.models.app_config import AppConfig # noqa: F401
|
||||
from app.models.comparison import ComparisonRecord # noqa: F401
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""看激励视频观看时长记录(每日总时长防刷)。
|
||||
|
||||
每条 = 客户端 onAdClose 上报的一次激励视频实际观看秒数。按 (user_id, watch_date) 聚合
|
||||
SUM(watch_seconds) 得当日总观看时长,用于"每天最多看 50 分钟激励视频"硬上限(超了不再发奖 /
|
||||
不给看,见 core.rewards.DAILY_AD_WATCH_SECONDS_LIMIT)。
|
||||
|
||||
这是看广告的第三条数据流,与另两条并列、互不关联:
|
||||
- ad_reward(AdRewardRecord):穿山甲 S2S 回调发金币(后端,有 trans_id);
|
||||
- ad_ecpm(AdEcpmRecord):客户端上报展示收益(前端,有 ecpm);
|
||||
- ad_watch_log(本表):客户端上报观看时长(前端,有 watch_seconds)。
|
||||
前端上报的时长不可信 → 时长是防刷"主闸",配合 ad_reward 的每日次数上限(DAILY_AD_REWARD_LIMIT)
|
||||
做"次数兜底",前端少报时长也刷不过次数闸。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class AdWatchLog(Base):
|
||||
__tablename__ = "ad_watch_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("user.id"), index=True, nullable=False
|
||||
)
|
||||
# 本次激励视频实际观看秒数(前端 onAdShow→onAdClose);服务端已夹 [0, MAX_SINGLE_WATCH_SECONDS]
|
||||
watch_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# 北京时间日期串 'YYYY-MM-DD',按它等值做"当日总时长"聚合(不在 SQL 里跨时区比较)
|
||||
watch_date: Mapped[str] = mapped_column(String(10), index=True, nullable=False)
|
||||
|
||||
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"<AdWatchLog user_id={self.user_id} sec={self.watch_seconds} {self.watch_date}>"
|
||||
@@ -86,7 +86,7 @@ class ComparisonRecord(Base):
|
||||
# ===== 明细(JSON,越详细越好)=====
|
||||
# 下单菜品 [{name, qty, specs?}]
|
||||
items: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 逐平台对比 [{platform_id, platform_name, package, price, is_source, rank, coupon_saved}](price/coupon_saved 单位:元,原样存)
|
||||
# 逐平台对比 [{platform_id, platform_name, package, price, is_source, rank, coupon_saved, coupon_name}](price/coupon_saved 单位:元,原样存;coupon_name=优惠来源名)
|
||||
comparison_results: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
# 目标平台未找到、跳过的菜名
|
||||
skipped_dish_names: Mapped[list] = mapped_column(_JSON, nullable=False, default=list)
|
||||
|
||||
+11
-6
@@ -65,11 +65,14 @@ class CoinTransaction(Base):
|
||||
|
||||
|
||||
class WithdrawOrder(Base):
|
||||
"""提现单(现金 → 微信零钱)。状态机:pending → success / failed。
|
||||
"""提现单(现金 → 微信零钱)。状态机:
|
||||
reviewing →(管理员通过)→ pending → success / failed
|
||||
reviewing →(管理员拒绝)→ rejected(已退款)
|
||||
|
||||
扣现金 + 写 cash_transaction(withdraw) 与建本单在同一事务;失败/取消时退回现金
|
||||
并写 cash_transaction(withdraw_refund)。wechat_state 存微信侧原始状态(WAIT_USER_CONFIRM /
|
||||
SUCCESS / FAIL / CANCELLED ...),status 是我们归一化后的三态。
|
||||
扣现金 + 写 cash_transaction(withdraw) 与建本单在同一事务,初始 reviewing(待人工审核,
|
||||
**不打款**);管理员审核通过才调微信转账(execute_withdraw_transfer)→ pending,拒绝则退回
|
||||
现金 + 置 rejected。微信侧失败/取消时退回现金并写 cash_transaction(withdraw_refund) → failed。
|
||||
wechat_state 存微信侧原始状态(WAIT_USER_CONFIRM / SUCCESS / FAIL / CANCELLED ...)。
|
||||
"""
|
||||
|
||||
__tablename__ = "withdraw_order"
|
||||
@@ -81,8 +84,10 @@ class WithdrawOrder(Base):
|
||||
# 商户单号(我们生成,微信查单的 out_bill_no),唯一
|
||||
out_bill_no: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
|
||||
amount_cents: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
# 归一化状态:pending / success / failed
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending")
|
||||
# 提现实名(微信达额转账要求):审核后异步打款时要用,发起提现时存下,可空
|
||||
user_name: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 归一化状态:reviewing(待审核) / pending(打款在途) / success / failed(打款失败已退) / rejected(审核拒绝已退)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="reviewing")
|
||||
# 微信侧原始状态
|
||||
wechat_state: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
# 微信转账单号
|
||||
|
||||
@@ -18,10 +18,11 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.core import rewards
|
||||
from app.core.ad_cooldown import compute_cooldown
|
||||
from app.core.rewards import cn_today
|
||||
from app.core.rewards import DAILY_AD_WATCH_SECONDS_LIMIT, cn_today
|
||||
from app.models.ad_reward import AdRewardRecord
|
||||
from app.models.user import User
|
||||
from app.repositories import wallet as crud_wallet
|
||||
from app.repositories.ad_watch import watched_seconds_today
|
||||
|
||||
|
||||
class UnknownUserError(Exception):
|
||||
@@ -71,8 +72,12 @@ def grant_ad_reward(
|
||||
|
||||
today = cn_today().isoformat()
|
||||
|
||||
# #3 每日上限:超了记一条 capped(不发金币),让审计能看到"今天到顶了"
|
||||
if _granted_today(db, user_id, today) >= rewards.get_ad_daily_limit(db):
|
||||
# #3 每日上限:观看时长(主闸,50 分钟) 或 发奖次数(兜底) 任一到顶 → 记 capped 不发金币,
|
||||
# 让审计能看到"今天到顶了"。时长由前端 watch-report 累计(防刷主闸),次数防前端少报时长
|
||||
# 绕过;次数上限走 app_config(运营后台可改,默认 rewards.DAILY_AD_REWARD_LIMIT)。
|
||||
over_time = watched_seconds_today(db, user_id, today=today) >= DAILY_AD_WATCH_SECONDS_LIMIT
|
||||
over_count = _granted_today(db, user_id, today) >= rewards.get_ad_daily_limit(db)
|
||||
if over_time or over_count:
|
||||
rec = AdRewardRecord(
|
||||
trans_id=trans_id, user_id=user_id, coin=0, status="capped",
|
||||
reward_date=today, reward_name=reward_name, raw=raw,
|
||||
@@ -126,12 +131,14 @@ def _granted_times_today_desc(db: Session, user_id: int, reward_date: str) -> li
|
||||
|
||||
def today_status(
|
||||
db: Session, user_id: int
|
||||
) -> tuple[int, int, int, int, datetime | None]:
|
||||
) -> tuple[int, int, int, int, datetime | None, int, int]:
|
||||
"""客户端查"今日看广告发奖"进度。
|
||||
|
||||
返回 (今日已发次数, 每日上限, 单次金币, 本轮已看次数, 本轮冷却结束时间(UTC))。
|
||||
上限/单次金币/每轮次数/冷却秒 均从 app_config 读(运营后台可改);冷却策略判断委托
|
||||
[app.core.ad_cooldown.compute_cooldown](纯函数)。
|
||||
返回 (今日已发次数, 每日次数上限, 单次金币, 本轮已看次数, 本轮冷却结束时间(UTC),
|
||||
今日已观看总秒数, 每日观看总时长上限(秒))。
|
||||
次数上限/单次金币/每轮次数/冷却秒 均从 app_config 读(运营后台可改);次数维度的"本轮已看
|
||||
几次 + 冷却到几点"委托 [app.core.ad_cooldown.compute_cooldown](纯函数);时长维度(50 分钟
|
||||
主闸)查 ad_watch_log 当日累计——前端据此展示"今日已看 X/50 分钟"+ 满则不给看。
|
||||
"""
|
||||
today = cn_today().isoformat()
|
||||
granted_desc = _granted_times_today_desc(db, user_id, today)
|
||||
@@ -147,4 +154,6 @@ def today_status(
|
||||
rewards.get_ad_reward_coin(db),
|
||||
state.round_count,
|
||||
state.cooldown_until,
|
||||
watched_seconds_today(db, user_id, today=today),
|
||||
DAILY_AD_WATCH_SECONDS_LIMIT,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""看激励视频观看时长 CRUD(每日总时长防刷)。
|
||||
|
||||
前端 onAdClose 上报本次观看秒数 → add_watch_seconds 落库 + 返回当日累计;
|
||||
watched_seconds_today 给"时长闸"(发奖 / 展示前)判断当天是否已达 50 分钟上限。
|
||||
鉴权接口已确保 user 存在(JWT),故不做 UnknownUser 校验。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.rewards import MAX_SINGLE_WATCH_SECONDS, cn_today
|
||||
from app.models.ad_watch_log import AdWatchLog
|
||||
|
||||
|
||||
def watched_seconds_today(db: Session, user_id: int, *, today: str | None = None) -> int:
|
||||
"""该用户今日(北京时间)累计观看秒数。coalesce 防无记录时 SUM 返 None。"""
|
||||
d = today or cn_today().isoformat()
|
||||
return db.execute(
|
||||
select(func.coalesce(func.sum(AdWatchLog.watch_seconds), 0)).where(
|
||||
AdWatchLog.user_id == user_id,
|
||||
AdWatchLog.watch_date == d,
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
|
||||
def add_watch_seconds(db: Session, user_id: int, seconds: int) -> int:
|
||||
"""记一次观看时长,返回当日累计秒数。
|
||||
|
||||
seconds 夹 [0, MAX_SINGLE_WATCH_SECONDS] 防前端报异常大值(刷时长无意义,但夹紧更稳)。
|
||||
"""
|
||||
clamped = max(0, min(int(seconds), MAX_SINGLE_WATCH_SECONDS))
|
||||
today = cn_today().isoformat()
|
||||
db.add(AdWatchLog(user_id=user_id, watch_seconds=clamped, watch_date=today))
|
||||
db.commit()
|
||||
return watched_seconds_today(db, user_id, today=today)
|
||||
@@ -52,6 +52,7 @@ class SavingsBattle:
|
||||
week_saved_cents: int # 本周(周一起)已省
|
||||
beat_percent: int # 超过百分之多少用户
|
||||
streak_days: int # 连续省钱天数
|
||||
compare_count: int # 累计完成比价次数(= 有效记录数:真实用 compare 记录、否则 demo 兜底)
|
||||
|
||||
|
||||
def _local_date(dt: datetime):
|
||||
@@ -163,7 +164,10 @@ def get_battle(db: Session, user_id: int) -> SavingsBattle:
|
||||
beat_percent = _compute_beat_percent(db, user_id)
|
||||
|
||||
return SavingsBattle(
|
||||
week_saved_cents=week_saved, beat_percent=beat_percent, streak_days=streak
|
||||
week_saved_cents=week_saved,
|
||||
beat_percent=beat_percent,
|
||||
streak_days=streak,
|
||||
compare_count=len(records),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+92
-22
@@ -57,6 +57,10 @@ class WithdrawOrderNotFound(Exception):
|
||||
"""提现单不存在。"""
|
||||
|
||||
|
||||
class WithdrawNotReviewable(Exception):
|
||||
"""提现单当前状态不可审核(非 reviewing,可能已被处理过)。"""
|
||||
|
||||
|
||||
def get_or_create_account(db: Session, user_id: int, *, commit: bool = True) -> CoinAccount:
|
||||
"""取用户金币账户,不存在则建一个空账户。"""
|
||||
acc = db.get(CoinAccount, user_id)
|
||||
@@ -254,10 +258,18 @@ def _add_cash(db: Session, user_id: int, amount_cents: int) -> int:
|
||||
return bal
|
||||
|
||||
|
||||
def _refund_withdraw(db: Session, order: WithdrawOrder, reason: str) -> None:
|
||||
"""转账失败/取消:退回现金 + 写 withdraw_refund 流水 + 单子置 failed。幂等:已 failed 不重复退。"""
|
||||
if order.status == "failed":
|
||||
return # 防重复退款(并发/对账与查单同时触发)
|
||||
def _refund_withdraw(
|
||||
db: Session, order: WithdrawOrder, reason: str, *, final_status: str = "failed"
|
||||
) -> None:
|
||||
"""退回现金 + 写 withdraw_refund 流水 + 单子置终态。幂等:已是退款终态不重复退。
|
||||
|
||||
final_status:
|
||||
- "failed" (默认):微信转账失败/取消 → 自动退款
|
||||
- "rejected":管理员审核拒绝 → 退款(走 reject_withdraw)
|
||||
两种都已退款,用 in 判定防重复退(并发/对账/拒绝重复点)。
|
||||
"""
|
||||
if order.status in ("failed", "rejected"):
|
||||
return # 防重复退款(并发/对账与查单/重复拒绝同时触发)
|
||||
bal = _add_cash(db, order.user_id, order.amount_cents)
|
||||
db.add(
|
||||
CashTransaction(
|
||||
@@ -266,10 +278,11 @@ def _refund_withdraw(db: Session, order: WithdrawOrder, reason: str) -> None:
|
||||
balance_after_cents=bal,
|
||||
biz_type="withdraw_refund",
|
||||
ref_id=order.out_bill_no,
|
||||
remark="提现未成功,金额已退回", # 用户可见;技术原因记在 order.fail_reason
|
||||
# 用户可见文案区分"未成功(自动退)"vs"审核未通过";技术原因记在 order.fail_reason
|
||||
remark="提现审核未通过,金额已退回" if final_status == "rejected" else "提现未成功,金额已退回",
|
||||
)
|
||||
)
|
||||
order.status = "failed"
|
||||
order.status = final_status
|
||||
order.fail_reason = reason[:256]
|
||||
db.commit()
|
||||
|
||||
@@ -327,22 +340,26 @@ def create_withdraw(
|
||||
user_name: str | None = None,
|
||||
out_bill_no: str | None = None,
|
||||
) -> WithdrawOrder:
|
||||
"""发起提现(原子扣款 + 幂等 + 模糊失败查单)。
|
||||
"""发起提现:原子扣款 + 建单 reviewing(待人工审核),**不打款**。
|
||||
|
||||
#1 用原子条件 UPDATE 扣款,杜绝并发超额。
|
||||
#2 out_bill_no 由客户端提供作幂等键:同号重试不会重复转账,直接返回该单当前状态。
|
||||
#3 微信调用结果不明时先查单再决定,绝不盲目退款。
|
||||
返回提现单(可能含 package_info 供 App 拉起确认页)。
|
||||
打款推迟到管理员在 admin 后台审核通过(approve_withdraw → execute_withdraw_transfer)才发起;
|
||||
拒绝则退回现金(reject_withdraw)。
|
||||
#1 用原子条件 UPDATE 扣款,杜绝并发超额——且"待审核期间钱已扣减",防止用户拿同一笔余额
|
||||
重复发起多笔提现(审核拒绝再退回)。
|
||||
#2 out_bill_no 客户端幂等键:同号重试返回该单现状(reviewing 等审核),不重复扣款建单。
|
||||
实名 user_name 在此存下(WithdrawOrder.user_name),供异步审核打款时传给微信(达额需实名)。
|
||||
"""
|
||||
if amount_cents < rewards.get_withdraw_min_cents(db) or amount_cents > rewards.get_withdraw_max_cents(db):
|
||||
raise InvalidWithdrawAmountError
|
||||
|
||||
# 提现即要求已绑微信:否则审核通过也打不了款,提前拦更友好
|
||||
user = db.get(User, user_id)
|
||||
openid = user.wechat_openid if user else None
|
||||
if not openid:
|
||||
raise WechatNotBoundError
|
||||
|
||||
# #2 幂等:客户端传了合法 out_bill_no 且该单已存在 → 返回现状(pending 的顺手查一下),不重复发起
|
||||
# #2 幂等:该单已存在 → 直接返回现状(reviewing 等审核 / 已处理态原样返回),不重复扣款。
|
||||
# 不再像旧版对 pending 查微信:本函数不再涉及微信,查单交给 /withdraw/status 与对账任务。
|
||||
if out_bill_no and _OUT_BILL_NO_RE.match(out_bill_no):
|
||||
existing = db.execute(
|
||||
select(WithdrawOrder).where(
|
||||
@@ -350,8 +367,6 @@ def create_withdraw(
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if existing is not None:
|
||||
if existing.status == "pending":
|
||||
return refresh_withdraw_status(db, user_id, out_bill_no)
|
||||
return existing
|
||||
else:
|
||||
out_bill_no = uuid.uuid4().hex
|
||||
@@ -374,32 +389,53 @@ def create_withdraw(
|
||||
balance_after_cents=bal,
|
||||
biz_type="withdraw",
|
||||
ref_id=out_bill_no,
|
||||
remark="提现到微信零钱",
|
||||
remark="提现到微信零钱(待审核)",
|
||||
)
|
||||
)
|
||||
order = WithdrawOrder(
|
||||
user_id=user_id, out_bill_no=out_bill_no, amount_cents=amount_cents, status="pending"
|
||||
user_id=user_id,
|
||||
out_bill_no=out_bill_no,
|
||||
amount_cents=amount_cents,
|
||||
user_name=user_name,
|
||||
status="reviewing",
|
||||
)
|
||||
db.add(order)
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
return order # 待管理员审核;**不在此处打款**
|
||||
|
||||
|
||||
def execute_withdraw_transfer(db: Session, order: WithdrawOrder) -> WithdrawOrder:
|
||||
"""审核通过后真正发起微信转账(复用原"转账 + 模糊失败查单"逻辑,绝不盲目退款)。
|
||||
|
||||
流程:reviewing → 置 pending → 调微信转账 → SUCCESS=success / 失败/取消=退款 failed /
|
||||
结果不明=先查单再决定。**不抛异常**(admin 调用方按 order.status 判断结果)。
|
||||
用户在审核期间解绑微信 → 退款 failed(打不了款)。
|
||||
可能返回 package_info(WAIT_USER_CONFIRM 场景:需用户在 App 端确认页确认后才真正到账)。
|
||||
"""
|
||||
user = db.get(User, order.user_id)
|
||||
openid = user.wechat_openid if user else None
|
||||
if not openid:
|
||||
_refund_withdraw(db, order, reason="用户已解绑微信,无法打款")
|
||||
db.refresh(order)
|
||||
return order
|
||||
|
||||
order.status = "pending" # 进入打款在途(转账调用前崩溃留 pending,交对账兜底)
|
||||
db.commit()
|
||||
|
||||
# 2) 调微信转账;结果不明先查单再决定(#3)
|
||||
try:
|
||||
result = wxpay.create_transfer(openid, amount_cents, out_bill_no, user_name=user_name)
|
||||
result = wxpay.create_transfer(
|
||||
openid, order.amount_cents, order.out_bill_no, user_name=order.user_name
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 — 超时/网络异常≠失败,查单确认
|
||||
_settle_after_ambiguous(db, order, reason=f"转账调用异常: {e}")
|
||||
db.refresh(order)
|
||||
if order.status == "failed":
|
||||
raise WithdrawTransferError(str(e)) from e
|
||||
return order
|
||||
|
||||
if result["status_code"] != 200:
|
||||
msg = str(result["data"].get("message") or result["data"])
|
||||
_settle_after_ambiguous(db, order, reason=msg)
|
||||
db.refresh(order)
|
||||
if order.status == "failed":
|
||||
raise WithdrawTransferError(msg)
|
||||
return order
|
||||
|
||||
data = result["data"]
|
||||
@@ -413,6 +449,40 @@ def create_withdraw(
|
||||
return order
|
||||
|
||||
|
||||
def _get_withdraw_or_raise(db: Session, out_bill_no: str) -> WithdrawOrder:
|
||||
"""按 out_bill_no 取提现单(admin 跨用户,不限 user_id)。不存在抛 WithdrawOrderNotFound。"""
|
||||
order = db.execute(
|
||||
select(WithdrawOrder).where(WithdrawOrder.out_bill_no == out_bill_no)
|
||||
).scalar_one_or_none()
|
||||
if order is None:
|
||||
raise WithdrawOrderNotFound
|
||||
return order
|
||||
|
||||
|
||||
def approve_withdraw(db: Session, out_bill_no: str) -> WithdrawOrder:
|
||||
"""管理员审核通过:校验 reviewing → 发起微信转账。返回最终 order(pending/success/failed)。
|
||||
|
||||
幂等防误操作:非 reviewing(已通过/已拒绝/已打款)抛 WithdrawNotReviewable,不会重复打款。
|
||||
"""
|
||||
order = _get_withdraw_or_raise(db, out_bill_no)
|
||||
if order.status != "reviewing":
|
||||
raise WithdrawNotReviewable(f"提现单状态为 {order.status},非待审核,不能通过")
|
||||
return execute_withdraw_transfer(db, order)
|
||||
|
||||
|
||||
def reject_withdraw(db: Session, out_bill_no: str, reason: str) -> WithdrawOrder:
|
||||
"""管理员审核拒绝:校验 reviewing → 退回现金 + 置 rejected。
|
||||
|
||||
非 reviewing 抛 WithdrawNotReviewable(防对已打款单误退导致重复退款)。
|
||||
"""
|
||||
order = _get_withdraw_or_raise(db, out_bill_no)
|
||||
if order.status != "reviewing":
|
||||
raise WithdrawNotReviewable(f"提现单状态为 {order.status},非待审核,不能拒绝")
|
||||
_refund_withdraw(db, order, reason=reason or "审核未通过", final_status="rejected")
|
||||
db.refresh(order)
|
||||
return order
|
||||
|
||||
|
||||
def refresh_withdraw_status(
|
||||
db: Session, user_id: int, out_bill_no: str, *, cancel_if_unconfirmed: bool = False
|
||||
) -> WithdrawOrder:
|
||||
|
||||
@@ -37,6 +37,10 @@ class AdRewardStatusOut(BaseModel):
|
||||
description="本轮看完后 10 分钟冷却结束时间(UTC ISO),null 表示不在冷却。"
|
||||
"冷却是 UX 约束,后端发奖不受影响,客户端 CTA 据此显示 MM:SS 倒计时且不可点",
|
||||
)
|
||||
# ===== 看广告每日总时长(50 分钟防刷主闸):客户端据此展示"今日已看 X/50 分钟"、满则不给看 =====
|
||||
watched_seconds_today: int = Field(0, description="今日已观看激励视频总秒数(前端累计上报)")
|
||||
watch_seconds_limit: int = Field(0, description="每日观看总时长上限(秒,默认 3000=50 分钟)")
|
||||
watch_seconds_remaining: int = Field(0, description="今日剩余可观看秒数(<=0 时客户端不应再展示广告)")
|
||||
|
||||
|
||||
class EcpmReportIn(BaseModel):
|
||||
@@ -57,6 +61,23 @@ class EcpmReportOut(BaseModel):
|
||||
ok: bool = True
|
||||
|
||||
|
||||
class WatchReportIn(BaseModel):
|
||||
"""客户端上报一次激励视频的实际观看时长(onAdClose 时,onAdShow→onAdClose 墙钟秒数)。
|
||||
|
||||
user_id 由 JWT 取(Bearer),不在 body。seconds 服务端会夹 [0, MAX_SINGLE_WATCH_SECONDS]。
|
||||
"""
|
||||
|
||||
seconds: int = Field(..., ge=0, description="本次观看秒数")
|
||||
|
||||
|
||||
class WatchReportOut(BaseModel):
|
||||
"""上报后返回当日累计 + 剩余,客户端即时更新"今日还能看多久"。"""
|
||||
|
||||
watched_seconds_today: int = Field(..., description="今日累计观看秒数")
|
||||
watch_seconds_limit: int = Field(..., description="每日上限(秒)")
|
||||
watch_seconds_remaining: int = Field(..., description="今日剩余可观看秒数")
|
||||
|
||||
|
||||
class TestGrantOut(BaseModel):
|
||||
"""[仅本地联调]模拟发奖结果。带上今日进度,客户端可直接据此刷新展示。"""
|
||||
|
||||
|
||||
@@ -37,6 +37,9 @@ class ComparisonResultIn(BaseModel):
|
||||
# 必须显式声明: 落库走 model_dump(), pydantic 默认丢未知字段, 不声明这行会被悄悄吞掉。
|
||||
# 各平台抠到红包即带值(2026-06 起源平台 Phase1 意图识别也抠, 当前仅淘宝源)。见 pricebot 侧 比价红包额留痕-实现方案.md。
|
||||
coupon_saved: float | None = None
|
||||
# 优惠**来源名**(展示用, best-effort): 美团"外卖大额神券"/京东"百亿补贴"/淘宝"平台红包"。
|
||||
# None=没抠到 → 前端走通用"红包"。同样必须显式声明否则上报边界被 pydantic 静默丢弃(pricebot#38 引入)。
|
||||
coupon_name: str | None = None
|
||||
|
||||
|
||||
class ComparisonRecordIn(BaseModel):
|
||||
|
||||
@@ -106,7 +106,7 @@ class WithdrawRequest(BaseModel):
|
||||
|
||||
class WithdrawResultOut(BaseModel):
|
||||
out_bill_no: str = Field(..., description="商户提现单号(查单用)")
|
||||
status: str = Field(..., description="pending / success / failed")
|
||||
status: str = Field(..., description="reviewing(待审核) / pending / success / failed / rejected")
|
||||
wechat_state: str | None = Field(None, description="微信侧原始状态")
|
||||
amount_cents: int
|
||||
cash_balance_cents: int = Field(..., description="提现后现金余额(分)")
|
||||
@@ -118,9 +118,14 @@ class WithdrawResultOut(BaseModel):
|
||||
|
||||
class WithdrawStatusOut(BaseModel):
|
||||
out_bill_no: str
|
||||
status: str = Field(..., description="pending / success / failed")
|
||||
status: str = Field(..., description="reviewing(待审核) / pending / success / failed / rejected")
|
||||
wechat_state: str | None = None
|
||||
amount_cents: int
|
||||
fail_reason: str | None = Field(None, description="failed/rejected 时的原因(用户可读)")
|
||||
# 审核通过进入打款、且微信要求用户确认(WAIT_USER_CONFIRM)时,带回这三项供 App 拉起微信确认页
|
||||
package_info: str | None = None
|
||||
mch_id: str | None = None
|
||||
app_id: str | None = None
|
||||
|
||||
|
||||
class WithdrawOrderOut(BaseModel):
|
||||
@@ -129,7 +134,7 @@ class WithdrawOrderOut(BaseModel):
|
||||
id: int
|
||||
out_bill_no: str
|
||||
amount_cents: int
|
||||
status: str
|
||||
status: str = Field(..., description="reviewing(待审核) / pending / success / failed / rejected")
|
||||
wechat_state: str | None = None
|
||||
fail_reason: str | None = None
|
||||
created_at: datetime
|
||||
@@ -194,6 +199,7 @@ class SavingsBattleOut(BaseModel):
|
||||
week_saved_cents: int = Field(..., description="本周已省(分)")
|
||||
beat_percent: int = Field(..., description="超过百分之多少用户")
|
||||
streak_days: int = Field(..., description="连续省钱天数")
|
||||
compare_count: int = Field(..., description="累计完成比价次数(= 比价上报记录数)")
|
||||
|
||||
|
||||
class SavingsRecordOut(BaseModel):
|
||||
|
||||
+21
-1
@@ -3,7 +3,7 @@
|
||||
> Base URL:生产 `https://app-api.shaguabijia.com`;本地联调 `http://<开发机>:8770`
|
||||
> 协议:HTTP / JSON,请求与响应体均 `application/json`,字段统一 **snake_case**
|
||||
> 鉴权:需鉴权的接口在请求头带 `Authorization: Bearer <access_token>`
|
||||
> 最后更新:2026-05-31(+ 比价战绩里程碑 12d/12e)
|
||||
> 最后更新:2026-06-04(+ 运营后台 Admin 子应用 A1–A18,见下方「运营后台 Admin」组)
|
||||
> 架构:`app/api/v1/` 只放很轻的接口层;穿山甲/微信支付/极光/短信/美团等 SDK 集成的重逻辑在 `app/integrations/`,实现细节见 [docs/integrations/](../integrations/README.md)。
|
||||
|
||||
---
|
||||
@@ -69,6 +69,26 @@
|
||||
| **静态资源**(StaticFiles 挂载,见下方 `/media` 静态服务) |||
|
||||
| - | `GET /media/avatars/<file>` | 无 | 用户头像;返回二进制图片 |
|
||||
| - | `GET /media/feedback/<file>` | 无 | 反馈截图;返回二进制图片 |
|
||||
| **运营后台 Admin**(独立子应用 `app/admin/`,前缀 `/admin/api`,独立进程 + 独立 admin JWT。鉴权列:`admin`=任意已登录管理员,`operator`/`finance`/`super_admin`=需对应角色(`super_admin` 恒通过)) |||
|
||||
| A1 | `POST /admin/api/auth/login` | 无 | [详情](./admin-auth-login.md) |
|
||||
| A2 | `GET /admin/api/auth/me` | admin | [详情](./admin-auth-me.md) |
|
||||
| A3 | `GET /admin/api/stats/overview` | admin | [详情](./admin-stats-overview.md) |
|
||||
| A4 | `GET /admin/api/users` | admin | [详情](./admin-users-list.md) |
|
||||
| A5 | `GET /admin/api/users/{user_id}` | admin | [详情](./admin-user-detail.md) |
|
||||
| A6 | `POST /admin/api/users/{user_id}/status` | operator | [详情](./admin-user-status.md) |
|
||||
| A7 | `POST /admin/api/users/{user_id}/coins` | finance | [详情](./admin-user-coins.md) |
|
||||
| A8 | `GET /admin/api/wallet/coin-transactions` | admin | [详情](./admin-wallet-coin-transactions.md) |
|
||||
| A9 | `GET /admin/api/wallet/cash-transactions` | admin | [详情](./admin-wallet-cash-transactions.md) |
|
||||
| A10 | `GET /admin/api/withdraws` | admin | [详情](./admin-withdraws-list.md) |
|
||||
| A11 | `POST /admin/api/withdraws/reconcile` | finance | [详情](./admin-withdraw-reconcile.md) |
|
||||
| A12 | `POST /admin/api/withdraws/{out_bill_no}/refresh` | finance | [详情](./admin-withdraw-refresh.md) |
|
||||
| A13 | `GET /admin/api/feedbacks` | admin | [详情](./admin-feedbacks-list.md) |
|
||||
| A14 | `POST /admin/api/feedbacks/{feedback_id}/handle` | operator | [详情](./admin-feedback-handle.md) |
|
||||
| A15 | `GET /admin/api/admins` | super_admin | [详情](./admin-admins-list.md) |
|
||||
| A16 | `POST /admin/api/admins` | super_admin | [详情](./admin-admin-create.md) |
|
||||
| A17 | `PATCH /admin/api/admins/{admin_id}` | super_admin | [详情](./admin-admin-update.md) |
|
||||
| A18 | `GET /admin/api/audit-logs` | admin | [详情](./admin-audit-logs.md) |
|
||||
| - | `GET /admin/api/health` | 无 | admin 健康检查(无单独文档) |
|
||||
|
||||
> ⚠️ 美团三个接口当前**无鉴权**,且 `referral-link` 的 `sid` 允许客户端传值覆盖默认渠道——见各接口"备注"。
|
||||
> `coupon/step` 及外卖比价的 `intent/recognize` / `price/step` 都透传到 pricebot-backend,**MVP 阶段均不鉴权**(device_id 透传,待补 JWT——见各接口详情)。
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# POST /admin/api/admins — 创建管理员
|
||||
|
||||
> 所属:Admin·Accounts 组(前缀 `/admin/api/admins`) | 鉴权:Bearer admin_token(角色:super_admin) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
**application/json**:
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `username` | string | ✓ | — | 账号,3–64 字 |
|
||||
| `password` | string | ✓ | — | 初始密码,8–72 字(bcrypt ≤72 字节) |
|
||||
| `role` | string | ✗ | `operator` | 角色,枚举:`super_admin` / `finance` / `operator` |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminOut`(新建的管理员)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 管理员 id |
|
||||
| `username` | string | 账号 |
|
||||
| `role` | string | 角色 |
|
||||
| `status` | string | 状态(新建默认 `active`) |
|
||||
| `created_at` | datetime | 创建时间(UTC) |
|
||||
| `last_login_at` | datetime \| null | 上次登录时间(新建为 null) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带 admin token / token 无效或过期 / 管理员被禁用
|
||||
- `403` 角色不足(仅 super_admin)
|
||||
- `409` 用户名已存在
|
||||
- `422` 缺字段 / `username` 长度不在 3–64 / `password` 长度不在 8–72 / `role` 非法枚举
|
||||
|
||||
## 说明
|
||||
- 创建成功后写一条审计:`action=admin.create`、`target_type=admin`、`target_id=新管理员 id`、`detail={username, role}`。见 [admin_audit_log](../database/admin_audit_log.md)。
|
||||
- 数据表见 [admin_user](../database/admin_user.md)。
|
||||
@@ -0,0 +1,39 @@
|
||||
# PATCH /admin/api/admins/{admin_id} — 改角色/启停/重置密码
|
||||
|
||||
> 所属:Admin·Accounts 组(前缀 `/admin/api/admins`) | 鉴权:Bearer admin_token(角色:super_admin) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
**路径参数**:
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `admin_id` | int | ✓ | 目标管理员 id |
|
||||
|
||||
**application/json**(三字段都可选,只改传了的;至少传一个):
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `role` | string | ✗ | 改角色,枚举:`super_admin` / `finance` / `operator` |
|
||||
| `status` | string | ✗ | 启停,枚举:`active`(启用)/ `disabled`(禁用) |
|
||||
| `password` | string | ✗ | 重置密码,8–72 字(传则覆盖原密码) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminOut`(更新后的管理员)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 管理员 id |
|
||||
| `username` | string | 账号 |
|
||||
| `role` | string | 角色 |
|
||||
| `status` | string | 状态 |
|
||||
| `created_at` | datetime | 创建时间(UTC) |
|
||||
| `last_login_at` | datetime \| null | 上次登录时间 |
|
||||
|
||||
## 错误码
|
||||
- `400` 不能禁用自己(`admin_id == 当前 admin.id` 且 `status=disabled`) / 无任何变更字段(三字段全空)
|
||||
- `401` 未带 admin token / token 无效或过期 / 管理员被禁用
|
||||
- `403` 角色不足(仅 super_admin)
|
||||
- `404` 管理员不存在
|
||||
- `422` `role`/`status` 非法枚举 / `password` 长度不在 8–72
|
||||
|
||||
## 说明
|
||||
- 更新成功后写一条审计:`action=admin.update`、`target_type=admin`、`target_id=admin_id`、`detail` 为本次实际变更字段(如 `{"role": "...", "status": "...", "password": "reset"}`,密码只记 `reset` 不记明文)。见 [admin_audit_log](../database/admin_audit_log.md)。
|
||||
- 数据表见 [admin_user](../database/admin_user.md)。
|
||||
@@ -0,0 +1,26 @@
|
||||
# GET /admin/api/admins — 管理员列表
|
||||
|
||||
> 所属:Admin·Accounts 组(前缀 `/admin/api/admins`) | 鉴权:Bearer admin_token(角色:super_admin) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
无(按 `id` 升序返回全部,无分页)
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminOut[]`
|
||||
|
||||
**AdminOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 管理员 id |
|
||||
| `username` | string | 账号 |
|
||||
| `role` | string | 角色:`super_admin` / `finance` / `operator` |
|
||||
| `status` | string | 状态:`active` / `disabled` |
|
||||
| `created_at` | datetime | 创建时间(UTC) |
|
||||
| `last_login_at` | datetime \| null | 上次登录时间,从未登录为 null |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带 admin token / token 无效或过期 / 管理员被禁用
|
||||
- `403` 角色不足(仅 super_admin 可访问,detail 形如 `role 'operator' not allowed (need one of [...])`)
|
||||
|
||||
## 说明
|
||||
账号管理整组(`/admin/api/admins`)的角色守卫为 `require_role()` 无参,即仅 `super_admin` 通过。数据表见 [admin_user](../database/admin_user.md)。
|
||||
@@ -0,0 +1,35 @@
|
||||
# GET /admin/api/audit-logs — 审计日志(谁改了什么,游标分页)
|
||||
|
||||
> 所属:Admin·Audit 组(前缀 `/admin/api/audit-logs`) | 鉴权:Bearer admin_token(角色:任意已登录 admin) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `action` | string | ❌ | null | 按操作类型过滤,如 `admin.create` / `admin.update` |
|
||||
| `target_type` | string | ❌ | null | 按目标对象类型过滤,如 `admin` |
|
||||
| `admin_id` | int | ❌ | null | 按操作人(管理员 id)过滤 |
|
||||
| `limit` | int | ❌ | 50 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页末条 `id`,首页不传 |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: AdminAuditLogOut[], next_cursor: int|null }`(按 `id` 倒序;分页见 [索引#游标分页约定](./README.md#游标分页约定))
|
||||
|
||||
**AdminAuditLogOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 审计 id(也是游标) |
|
||||
| `admin_id` | int | 操作人管理员 id |
|
||||
| `admin_username` | string | 操作人账号(写入时快照) |
|
||||
| `action` | string | 操作类型,如 `admin.create` / `admin.update` |
|
||||
| `target_type` | string | 目标对象类型,如 `admin` |
|
||||
| `target_id` | string \| null | 目标对象 id(字符串) |
|
||||
| `detail` | object \| null | 操作详情(JSON,如变更字段) |
|
||||
| `ip` | string \| null | 操作来源 IP(取 XFF 首段或直连 IP,仅记录不鉴权) |
|
||||
| `created_at` | datetime | 操作时间(UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带 admin token / token 无效或过期 / 管理员被禁用
|
||||
|
||||
## 说明
|
||||
- 整组(`/admin/api/audit-logs`)守卫为 `get_current_admin`,任意已登录 admin 均可查看,无角色限制。
|
||||
- 审计日志只增不改不删,任何写操作经 `write_audit` 落一条。数据表见 [admin_audit_log](../database/admin_audit_log.md)。
|
||||
@@ -0,0 +1,40 @@
|
||||
# POST /admin/api/auth/login — 管理员登录
|
||||
|
||||
> 所属:Admin·Auth 组(前缀 `/admin/api/auth`) | 鉴权:无 | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
**application/json**:
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `username` | string | ✓ | 管理员账号,1–64 字 |
|
||||
| `password` | string | ✓ | 密码,1–128 字 |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminLoginResponse`
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `access_token` | string | admin JWT(独立 `ADMIN_JWT_SECRET`、payload `typ=admin`、默认 12h、无 refresh) |
|
||||
| `token_type` | string | 固定 `Bearer` |
|
||||
| `expires_in` | int | access_token 剩余秒数(过期需重新登录) |
|
||||
| `admin` | AdminOut | 当前管理员信息,字段见下 |
|
||||
|
||||
**AdminOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 管理员 id |
|
||||
| `username` | string | 账号 |
|
||||
| `role` | string | 角色:`super_admin` / `finance` / `operator` |
|
||||
| `status` | string | 状态:`active` / `disabled` |
|
||||
| `created_at` | datetime | 创建时间(UTC) |
|
||||
| `last_login_at` | datetime \| null | 上次登录时间,从未登录为 null |
|
||||
|
||||
## 错误码
|
||||
- `401` 用户名或密码错误(用户名不存在与密码错误统一同文案,防账号枚举)
|
||||
- `403` 账号已禁用(`status != active`)
|
||||
- `422` 缺 `username` 或 `password` / 长度超限
|
||||
- `429` 同 IP 每分钟登录超过 10 次(限流防爆破)
|
||||
|
||||
## 说明
|
||||
- 登录成功后回写 `last_login_at` 为当前时间。
|
||||
- 后续所有 admin 接口须带 `Authorization: Bearer <access_token>`;admin token 与 App 用户 token 完全隔离。
|
||||
@@ -0,0 +1,24 @@
|
||||
# GET /admin/api/auth/me — 当前管理员
|
||||
|
||||
> 所属:Admin·Auth 组(前缀 `/admin/api/auth`) | 鉴权:Bearer admin_token(角色:任意已登录 admin) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
无(身份取自 Header token)
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminOut`
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 管理员 id |
|
||||
| `username` | string | 账号 |
|
||||
| `role` | string | 角色:`super_admin` / `finance` / `operator` |
|
||||
| `status` | string | 状态:`active` / `disabled` |
|
||||
| `created_at` | datetime | 创建时间(UTC) |
|
||||
| `last_login_at` | datetime \| null | 上次登录时间,从未登录为 null |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带 admin token / token 无效或过期 / `typ` 非 admin / 管理员不存在或被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
|
||||
## 说明
|
||||
无
|
||||
@@ -0,0 +1,23 @@
|
||||
# POST /admin/api/feedbacks/{feedback_id}/handle — 标记反馈已处理
|
||||
|
||||
> 所属:Admin·反馈 组(前缀 `/admin/api/feedbacks`) | 鉴权:Bearer admin_token(角色:`operator`,`super_admin` 恒通过,`require_role("operator")`) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
- 路径:`feedback_id`(int)
|
||||
- body:无
|
||||
|
||||
## 出参
|
||||
响应 `200`:`OkResponse` = `{ "ok": true }`
|
||||
|
||||
幂等说明:将该反馈 `status` 置为 `handled`(不校验原状态,重复调用结果一致)。
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 角色不足(需 `operator` 或 `super_admin`)
|
||||
- `404` 反馈不存在(`detail: "反馈不存在"`)
|
||||
- `422` `feedback_id` 非合法 int
|
||||
|
||||
## 说明
|
||||
- 写操作记审计 [admin_audit_log](../database/admin_audit_log.md):`action="feedback.handle"`、`target_type="feedback"`、`target_id=<feedback_id>`、`detail={"before": <原 status>, "after": "handled"}`、`ip=<客户端 IP>`。
|
||||
- 状态变更与审计写入在同一事务(`commit=False` 后统一 `db.commit()`)。
|
||||
- 关联表 [feedback](../database/feedback.md)。
|
||||
@@ -0,0 +1,34 @@
|
||||
# GET /admin/api/feedbacks — 反馈工单列表(游标分页)
|
||||
|
||||
> 所属:Admin·反馈 组(前缀 `/admin/api/feedbacks`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,无 `require_role`,仅 `get_current_admin`) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `status` | string | ❌ | null | 反馈状态,精确匹配:`new`(待处理) / `handled`(已处理);传空/不传则不筛 |
|
||||
| `user_id` | int | ❌ | null | 按提交用户 id 精确筛 |
|
||||
| `limit` | int | ❌ | 20 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页 next_cursor(按 feedback id 倒序,查 `id < cursor`) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: FeedbackOut[], next_cursor: int|null }`(`next_cursor=null` 表示末页)
|
||||
|
||||
**FeedbackOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 反馈 id |
|
||||
| `user_id` | int | 提交用户 id |
|
||||
| `content` | string | 反馈内容 |
|
||||
| `contact` | string | 联系方式(微信/QQ/手机,便于回访) |
|
||||
| `images` | string[] \| null | 截图相对路径列表(如 `["/media/feedback/u1_ab12.jpg"]`),无图为 null |
|
||||
| `status` | string | 反馈状态:`new`(待处理) / `handled`(已处理) |
|
||||
| `created_at` | datetime | 提交时间(UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `422` `limit` 超出 1–100 范围 / 字段类型不合法
|
||||
|
||||
## 说明
|
||||
- 游标分页约定:结果按 feedback `id` 倒序;`cursor` 传上一页返回的 `next_cursor`;`next_cursor=null` 即末页。
|
||||
- `status` / `user_id` 均为精确匹配,可叠加。
|
||||
- 关联表 [feedback](../database/feedback.md);截图为相对路径,经 `GET /media/feedback/<file>` 静态读。
|
||||
@@ -0,0 +1,69 @@
|
||||
# GET /admin/api/stats/overview — 大盘核心指标
|
||||
|
||||
> 所属:Admin·数据大盘 组(前缀 `/admin/api/stats`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,无 require_role) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
无
|
||||
|
||||
## 出参
|
||||
响应 `200`:`DashboardOverview`(全局只读聚合,六大块嵌套)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `users` | DashboardUsers | 用户指标 |
|
||||
| `coins` | DashboardCoins | 金币指标 |
|
||||
| `cash` | DashboardCash | 现金/提现指标 |
|
||||
| `comparison` | DashboardComparison | 比价指标 |
|
||||
| `feedback` | DashboardFeedback | 反馈指标 |
|
||||
| `cps` | DashboardCps | CPS 收入(P2 未接入) |
|
||||
|
||||
**DashboardUsers**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `total` | int | 用户总数 |
|
||||
| `active` | int | 状态 `active` 数 |
|
||||
| `disabled` | int | 状态 `disabled` 数 |
|
||||
| `deleted` | int | 状态 `deleted` 数 |
|
||||
| `new_today` | int | 今日新增(按北京时区切天的 `created_at`) |
|
||||
| `dau` | int | 日活(今日有 `last_login_at`,北京时区切天) |
|
||||
|
||||
**DashboardCoins**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `granted_total` | int | 累计发放金币(coin_transaction 中所有 `amount > 0` 之和;负数兑换/扣减不计) |
|
||||
|
||||
**DashboardCash**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `withdraw_success_cents` | int | 提现成功累计金额(分,`status=success` 之和) |
|
||||
| `withdraw_pending_count` | int | 提现 `pending` 单数 |
|
||||
| `withdraw_success_count` | int | 提现 `success` 单数 |
|
||||
| `withdraw_failed_count` | int | 提现 `failed` 单数 |
|
||||
|
||||
**DashboardComparison**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `total` | int | 比价记录总数 |
|
||||
| `success` | int | 比价成功数(`status=success`) |
|
||||
| `success_rate` | float | 成功率 = success/total,保留 4 位小数;total 为 0 时返回 `0.0` |
|
||||
|
||||
**DashboardFeedback**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `new` | int | 待处理反馈数(`status=new`) |
|
||||
|
||||
**DashboardCps**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `available` | bool | CPS 数据是否可用(当前固定 `false`) |
|
||||
| `note` | string | 说明文案(当前固定 `"CPS 转化数据未接入(P2)"`) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
|
||||
## 说明
|
||||
- 全部为全局只读聚合(count / sum / DAU / 成功率),不改任何数据。
|
||||
- `new_today` / `dau` 按**北京时区**(UTC+8)切天,其余金额/计数无时区概念。
|
||||
- 金额单位:`*_cents` 为分;金币(`granted_total`)为个数。
|
||||
- CPS 收入数据源未接入(referral-link 只换链接,转化/佣金未回收),`cps` 恒为 `{available:false, note:...}`,前端显示"待接入"。
|
||||
- 关联表:[user](../database/user.md) / [coin_transaction](../database/coin_transaction.md) / [withdraw_order](../database/withdraw_order.md) / [comparison_record](../database/comparison_record.md) / [feedback](../database/feedback.md)。
|
||||
@@ -0,0 +1,29 @@
|
||||
# POST /admin/api/users/{user_id}/coins — 手动增减金币(带审计)
|
||||
|
||||
> 所属:Admin·用户 组(前缀 `/admin/api/users`) | 鉴权:Bearer admin_token(角色:`finance`,`super_admin` 恒通过) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
- 路径:`user_id`(int)
|
||||
- **application/json**:
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `amount` | int | ✓ | 金币变动(个数):正=增加,负=扣减;不可为 0 |
|
||||
| `reason` | string | ✓ | 操作原因,1–128 字(必填,入审计与流水备注) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`OkResponse` = `{ "ok": true }`
|
||||
|
||||
## 错误码
|
||||
- `400` `amount == 0`(`detail: "amount 不能为 0"`);或负数扣减后余额会变负(`detail: "扣减后金币为负(当前余额 N)"`)
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 角色不足(需 `finance` 或 `super_admin`)
|
||||
- `404` 用户不存在(`detail: "用户不存在"`)
|
||||
- `422` 缺 `amount`/`reason`、`reason` 长度不在 1–128、字段类型不合法 / `user_id` 非整数
|
||||
|
||||
## 说明
|
||||
- 金币 = 个数(非现金);本接口只动金币余额,不涉及现金(`*_cents`)。
|
||||
- 扣减保护:`amount < 0` 时若扣减后金币余额 < 0 直接拒绝(运营误操作保护)。
|
||||
- 金币变动写流水 [coin_transaction](../database/coin_transaction.md):`biz_type` 增加为 `admin_grant`、扣减为 `admin_deduct`,`remark = admin:<reason>`(截断至 128 字)。
|
||||
- 写操作记审计 [admin_audit_log](../database/admin_audit_log.md):`action = user.coins.grant`,`target_type = user`,`target_id = user_id`,`detail = {amount, balance_after, reason}`,并记录操作 IP。
|
||||
- 金币变动 + 审计在同一事务原子提交(改钱必留痕)。
|
||||
- 关联用户表 [user](../database/user.md);金币账户 [coin_account](../database/coin_account.md);金币流水 [coin_transaction](../database/coin_transaction.md)。
|
||||
@@ -0,0 +1,43 @@
|
||||
# GET /admin/api/users/{user_id} — 用户 360 详情
|
||||
|
||||
> 所属:Admin·用户 组(前缀 `/admin/api/users`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,无 require_role) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
- 路径:`user_id`(int)
|
||||
|
||||
## 出参
|
||||
响应 `200`:`AdminUserOverview`(基础资料 + 钱包余额 + 各项 count;历史明细走各自分页接口)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `user` | AdminUserListItem | 用户基础资料,字段见下 |
|
||||
| `coin_balance` | int | 当前金币余额(个数);无金币账户时为 0 |
|
||||
| `cash_balance_cents` | int | 当前现金余额(分);无账户时为 0 |
|
||||
| `total_coin_earned` | int | 累计获得金币(个数);无账户时为 0 |
|
||||
| `comparison_total` | int | 比价记录总数 |
|
||||
| `comparison_success` | int | 比价成功数(`status=success`) |
|
||||
| `withdraw_total` | int | 提现单总数 |
|
||||
| `withdraw_success_cents` | int | 提现成功累计金额(分,`status=success` 之和) |
|
||||
| `feedback_total` | int | 反馈总数 |
|
||||
|
||||
**AdminUserListItem**(`user` 字段)
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 用户 id |
|
||||
| `phone` | string | 手机号 |
|
||||
| `nickname` | string \| null | 昵称,可空 |
|
||||
| `register_channel` | string | 注册渠道 |
|
||||
| `status` | string | 用户状态:`active` / `disabled` / `deleted` |
|
||||
| `wechat_openid` | string \| null | 微信 openid,可空 |
|
||||
| `created_at` | datetime | 注册时间(UTC) |
|
||||
| `last_login_at` | datetime | 上次登录时间(UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `404` 用户不存在(`detail: "用户不存在"`)
|
||||
- `422` `user_id` 非整数
|
||||
|
||||
## 说明
|
||||
- 金币三项(`coin_balance` / `cash_balance_cents` / `total_coin_earned`)读 [coin_account](../database/coin_account.md);从未发生金币动作(账户不存在)时统一返回 0。
|
||||
- 各 count 为聚合数,明细历史走带 `user_id` 过滤的分页接口(金币流水 / 现金流水 / 提现 / 比价 / 反馈)。
|
||||
- 关联用户表 [user](../database/user.md);金币账户 [coin_account](../database/coin_account.md);提现单 [withdraw_order](../database/withdraw_order.md);比价记录 [comparison_record](../database/comparison_record.md);反馈 [feedback](../database/feedback.md)。
|
||||
@@ -0,0 +1,25 @@
|
||||
# POST /admin/api/users/{user_id}/status — 封禁/解封用户
|
||||
|
||||
> 所属:Admin·用户 组(前缀 `/admin/api/users`) | 鉴权:Bearer admin_token(角色:`operator`,`super_admin` 恒通过) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参
|
||||
- 路径:`user_id`(int)
|
||||
- **application/json**:
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `status` | string | ✓ | 目标状态,枚举 `active`(解封)/ `disabled`(封禁);注销 `deleted` 不走此接口 |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`OkResponse` = `{ "ok": true }`
|
||||
|
||||
## 错误码
|
||||
- `400` 已注销账号不可改状态(目标用户当前 `status == deleted`,`detail: "已注销账号不可改状态"`)
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 角色不足(需 `operator` 或 `super_admin`)
|
||||
- `404` 用户不存在(`detail: "用户不存在"`)
|
||||
- `422` `status` 非 `active`/`disabled` 枚举 / 缺字段 / `user_id` 非整数
|
||||
|
||||
## 说明
|
||||
- 业务写(改用户状态)与审计写在同一事务原子提交:改了就有痕、有痕就真改了。
|
||||
- 写操作记审计 [admin_audit_log](../database/admin_audit_log.md):`action = user.status.set`,`target_type = user`,`target_id = user_id`,`detail = {before, after}`,并记录操作 IP。
|
||||
- 关联用户表 [user](../database/user.md)。
|
||||
@@ -0,0 +1,37 @@
|
||||
# GET /admin/api/users — 用户列表(筛选+分页)
|
||||
|
||||
> 所属:Admin·用户 组(前缀 `/admin/api/users`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,无 require_role) | [← 返回 API 索引](./README.md)
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `phone` | string | ❌ | null | 手机号**前缀**匹配(`phone LIKE '<值>%'`) |
|
||||
| `register_channel` | string | ❌ | null | 注册渠道,精确匹配 |
|
||||
| `status` | string | ❌ | null | 用户状态,精确匹配:`active` / `disabled` / `deleted` |
|
||||
| `limit` | int | ❌ | 20 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页 next_cursor(按 user id 倒序,查 `id < cursor`) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: AdminUserListItem[], next_cursor: int|null }`(`next_cursor=null` 表示末页)
|
||||
|
||||
**AdminUserListItem**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 用户 id |
|
||||
| `phone` | string | 手机号 |
|
||||
| `nickname` | string \| null | 昵称,可空 |
|
||||
| `register_channel` | string | 注册渠道 |
|
||||
| `status` | string | 用户状态:`active` / `disabled` / `deleted` |
|
||||
| `wechat_openid` | string \| null | 微信 openid,可空 |
|
||||
| `created_at` | datetime | 注册时间(UTC) |
|
||||
| `last_login_at` | datetime | 上次登录时间(UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(头带 `WWW-Authenticate: Bearer`)
|
||||
- `422` `limit` 超出 1–100 范围 / 字段类型不合法
|
||||
|
||||
## 说明
|
||||
- 游标分页约定:结果按 user `id` 倒序;`cursor` 传上一页返回的 `next_cursor`;`next_cursor=null` 即末页。
|
||||
- `phone` 为前缀匹配(`LIKE '<值>%'`),`register_channel` / `status` 为精确匹配;三者可叠加。
|
||||
- 关联用户表 [user](../database/user.md)。
|
||||
- 历史明细(金币流水、提现、比价、反馈等)不在本列表,走各自带 `user_id` 过滤的分页接口。
|
||||
@@ -0,0 +1,35 @@
|
||||
# GET /admin/api/wallet/cash-transactions — 现金流水(游标分页)
|
||||
|
||||
> 所属:Admin·钱包 组(前缀 `/admin/api/wallet`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,仅需 `get_current_admin`,无 `require_role`) | [← 返回 API 索引](./README.md)
|
||||
|
||||
跨用户查询全量现金流水,可按 `user_id` / `biz_type` 过滤。游标分页(`id` 倒序)。金额单位一律为**分**。
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `user_id` | int | ❌ | null | 按用户过滤;不传则查全量 |
|
||||
| `biz_type` | string | ❌ | null | 按业务类型过滤 |
|
||||
| `limit` | int | ❌ | 20 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页 next_cursor(查 `id < cursor`) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: CashTxnOut[], next_cursor: int|null }`(`next_cursor=null` 表示末页)
|
||||
|
||||
**CashTxnOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 流水主键 |
|
||||
| `user_id` | int | 所属用户 |
|
||||
| `amount_cents` | int | 现金变动量,单位:**分**(正/负) |
|
||||
| `balance_after_cents` | int | 本次变动后现金余额,单位:**分** |
|
||||
| `biz_type` | string | 业务类型 |
|
||||
| `ref_id` | string \| null | 关联业务 ID |
|
||||
| `remark` | string \| null | 备注 |
|
||||
| `created_at` | datetime | 创建时间(ISO 8601 UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `422` query 参数校验失败(如 `limit` 越界、类型错误)
|
||||
|
||||
## 说明
|
||||
关联 [cash_transaction](../database/cash_transaction.md)。所有金额字段单位为分。
|
||||
@@ -0,0 +1,35 @@
|
||||
# GET /admin/api/wallet/coin-transactions — 金币流水(游标分页)
|
||||
|
||||
> 所属:Admin·钱包 组(前缀 `/admin/api/wallet`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,仅需 `get_current_admin`,无 `require_role`) | [← 返回 API 索引](./README.md)
|
||||
|
||||
跨用户查询全量金币流水,可按 `user_id` / `biz_type` 过滤。游标分页(`id` 倒序)。
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `user_id` | int | ❌ | null | 按用户过滤;不传则查全量 |
|
||||
| `biz_type` | string | ❌ | null | 按业务类型过滤 |
|
||||
| `limit` | int | ❌ | 20 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页 next_cursor(查 `id < cursor`) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: CoinTxnOut[], next_cursor: int|null }`(`next_cursor=null` 表示末页)
|
||||
|
||||
**CoinTxnOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 流水主键 |
|
||||
| `user_id` | int | 所属用户 |
|
||||
| `amount` | int | 金币变动量(正/负,单位:金币个数,非分) |
|
||||
| `balance_after` | int | 本次变动后金币余额 |
|
||||
| `biz_type` | string | 业务类型 |
|
||||
| `ref_id` | string \| null | 关联业务 ID |
|
||||
| `remark` | string \| null | 备注 |
|
||||
| `created_at` | datetime | 创建时间(ISO 8601 UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `422` query 参数校验失败(如 `limit` 越界、类型错误)
|
||||
|
||||
## 说明
|
||||
关联 [coin_transaction](../database/coin_transaction.md)。金币为个数计量,非分。
|
||||
@@ -0,0 +1,37 @@
|
||||
# POST /admin/api/withdraws/reconcile — 批量对账(扫超时 pending 单)
|
||||
|
||||
> 所属:Admin·提现 组(前缀 `/admin/api/withdraws`) | 鉴权:Bearer admin_token(角色:`finance`,`super_admin` 恒通过) | [← 返回 API 索引](./README.md)
|
||||
|
||||
扫描创建时间超过 `older_than_minutes` 分钟、仍为 `pending` 的提现单,逐单调微信查单并归一化(成功落 `success`;失败/已撤销则退款落 `failed`;查到 `WAIT_USER_CONFIRM` 视为用户放弃,撤单+退款)。用于解开"扣了款但转账没发起/没确认"的孤儿单。单笔失败不影响其余(内部 rollback 后继续,下轮再试)。
|
||||
|
||||
> 路由注册顺序上,静态路径 `/reconcile` 必须在路径参数 `/{out_bill_no}/refresh` 之前声明。
|
||||
|
||||
## 入参
|
||||
- 路径:无
|
||||
- query:
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `older_than_minutes` | int | ❌ | 15 | 只扫创建时间早于「现在 − N 分钟」的 pending 单;`ge=0` |
|
||||
|
||||
- body:无
|
||||
|
||||
## 出参
|
||||
响应 `200`:`ReconcileResult`
|
||||
|
||||
**ReconcileResult**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `checked` | int | 本次扫到的超时 pending 单数量 |
|
||||
| `resolved` | int | 其中被归一化为终态(success/failed)的数量 |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 角色不足(需 `finance` 或 `super_admin`)
|
||||
- `422` query 参数校验失败(如 `older_than_minutes < 0`)
|
||||
- `503` 微信支付未配置(捕获 `WxPayNotConfiguredError`,`detail="微信支付未配置"`)
|
||||
|
||||
## 说明
|
||||
- 调用底层 `app.repositories.wallet.reconcile_pending_withdraws`(内部逐单调微信查单/撤单/退款,各自 commit)。
|
||||
- 写操作记审计 [admin_audit_log](../database/admin_audit_log.md)(`action="withdraw.reconcile"`,`detail` 为 `{checked, resolved}`,含触发管理员与客户端 IP)。
|
||||
- 关联 [withdraw_order](../database/withdraw_order.md)。
|
||||
@@ -0,0 +1,39 @@
|
||||
# POST /admin/api/withdraws/{out_bill_no}/refresh — 单笔提现重试查单
|
||||
|
||||
> 所属:Admin·提现 组(前缀 `/admin/api/withdraws`) | 鉴权:Bearer admin_token(角色:`finance`,`super_admin` 恒通过) | [← 返回 API 索引](./README.md)
|
||||
|
||||
对单笔提现单调微信查单并归一化:`SUCCESS`→`success`;`FAIL`/`CANCELLED`/`CLOSED`→退款+`failed`;查到 `WAIT_USER_CONFIRM` 视为用户放弃(`cancel_if_unconfirmed=True`),撤单+退款;`ACCEPTED`/`PROCESSING` 等仍在途则保持 `pending`。已是终态的单直接返回、不再查。
|
||||
|
||||
## 入参
|
||||
- 路径:`out_bill_no`(string) — 商户提现单号
|
||||
- body:无
|
||||
|
||||
## 出参
|
||||
响应 `200`:`WithdrawOrderOut`(归一化后的最新提现单)
|
||||
|
||||
**WithdrawOrderOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 提现单主键 |
|
||||
| `user_id` | int | 所属用户 |
|
||||
| `out_bill_no` | string | 商户提现单号 |
|
||||
| `amount_cents` | int | 提现金额,单位:**分** |
|
||||
| `status` | string | 单状态(`pending` / `success` / `failed`) |
|
||||
| `wechat_state` | string \| null | 微信侧转账状态 |
|
||||
| `transfer_bill_no` | string \| null | 微信转账单号 |
|
||||
| `fail_reason` | string \| null | 失败/退款原因 |
|
||||
| `created_at` | datetime | 创建时间(ISO 8601 UTC) |
|
||||
| `updated_at` | datetime | 更新时间(ISO 8601 UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `403` 角色不足(需 `finance` 或 `super_admin`)
|
||||
- `404` 提现单不存在(`detail="提现单不存在"`)
|
||||
- `503` 微信支付未配置(捕获 `WxPayNotConfiguredError`,`detail="微信支付未配置"`)
|
||||
|
||||
> 注:微信查单本身失败(非未配置)时不抛错、不改状态,单保持 `pending` 等下次重试,故无 `502`。
|
||||
|
||||
## 说明
|
||||
- 调用底层 `app.repositories.wallet.refresh_withdraw_status(..., cancel_if_unconfirmed=True)`(内部调微信查单/撤单/退款并 commit)。
|
||||
- 写操作记审计 [admin_audit_log](../database/admin_audit_log.md)(`action="withdraw.refresh"`,`target_id=out_bill_no`,`detail` 为 `{status, wechat_state}`,含触发管理员与客户端 IP)。
|
||||
- 关联 [withdraw_order](../database/withdraw_order.md)。金额单位为分。
|
||||
@@ -0,0 +1,37 @@
|
||||
# GET /admin/api/withdraws — 提现单列表(游标分页)
|
||||
|
||||
> 所属:Admin·提现 组(前缀 `/admin/api/withdraws`) | 鉴权:Bearer admin_token(角色:任意已登录管理员,列表为只读,仅需 `get_current_admin`,无 `require_role`) | [← 返回 API 索引](./README.md)
|
||||
|
||||
跨用户查询全量提现单,可按 `user_id` / `status` 过滤。游标分页(`id` 倒序)。
|
||||
|
||||
## 入参(query)
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `user_id` | int | ❌ | null | 按用户过滤;不传则查全量 |
|
||||
| `status` | string | ❌ | null | 按状态过滤(如 `pending` / `success` / `failed`) |
|
||||
| `limit` | int | ❌ | 20 | 1–100 |
|
||||
| `cursor` | int | ❌ | null | 上一页 next_cursor(查 `id < cursor`) |
|
||||
|
||||
## 出参
|
||||
响应 `200`:`{ items: WithdrawOrderOut[], next_cursor: int|null }`(`next_cursor=null` 表示末页)
|
||||
|
||||
**WithdrawOrderOut**
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int | 提现单主键 |
|
||||
| `user_id` | int | 所属用户 |
|
||||
| `out_bill_no` | string | 商户提现单号(业务主键,重试/对账以此为准) |
|
||||
| `amount_cents` | int | 提现金额,单位:**分** |
|
||||
| `status` | string | 单状态(`pending` / `success` / `failed`) |
|
||||
| `wechat_state` | string \| null | 微信侧转账状态(如 `ACCEPTED` / `PROCESSING` / `WAIT_USER_CONFIRM` / `SUCCESS`) |
|
||||
| `transfer_bill_no` | string \| null | 微信转账单号 |
|
||||
| `fail_reason` | string \| null | 失败/退款原因 |
|
||||
| `created_at` | datetime | 创建时间(ISO 8601 UTC) |
|
||||
| `updated_at` | datetime | 更新时间(ISO 8601 UTC) |
|
||||
|
||||
## 错误码
|
||||
- `401` 未带/无效/过期 admin token、管理员被禁用(响应头带 `WWW-Authenticate: Bearer`)
|
||||
- `422` query 参数校验失败(如 `limit` 越界、类型错误)
|
||||
|
||||
## 说明
|
||||
关联 [withdraw_order](../database/withdraw_order.md)。金额单位为分。
|
||||
@@ -31,9 +31,10 @@
|
||||
|
||||
**Item**:`{ name: string, qty: int=1, specs: string[]\|null }`
|
||||
|
||||
**Result(comparison_results 元素)**:`{ platform_id, platform_name, package, price(元,float\|null), is_source(bool), rank(int\|null), coupon_saved(元,float\|null) }`
|
||||
**Result(comparison_results 元素)**:`{ platform_id, platform_name, package, price(元,float\|null), is_source(bool), rank(int\|null), coupon_saved(元,float\|null), coupon_name(string\|null) }`
|
||||
|
||||
- `coupon_saved`:该平台本单**平台主优惠额**(元)——美团红包 / 淘宝平台红包 / 京东优惠券·百亿补贴,**只取那一笔**,不含配送费减免/共减总额。仅外卖目标平台带值,源平台/没用为 `null`,前端记录页据此展示**「已优惠 ¥X」**(null 不展示)。
|
||||
- `coupon_name`:优惠**来源名**(展示用,best-effort)——美团「外卖大额神券」/ 京东「百亿补贴」/ 淘宝「平台红包」。仅在该行有 `coupon_saved` 时带;`null` 时前端走通用「红包」。非用户选中的具体券名(选中态不可读)。
|
||||
|
||||
## 服务端派生(客户端不用算)
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
| `week_saved_cents` | int | 本周已省(分) |
|
||||
| `beat_percent` | int | 超过百分之多少用户 |
|
||||
| `streak_days` | int | 连续省钱天数 |
|
||||
| `compare_count` | int | 累计完成比价次数(= 比价上报记录数;有真实 `compare` 记录用真实数,否则 demo 兜底) |
|
||||
|
||||
## 说明
|
||||
「我的」页「省钱战绩」卡数据源。接口已通但无真实业务写入,实际多为 0。
|
||||
「我的」页「省钱战绩」卡数据源(三列:本周已省 / 完成比价 / 连续比价)。`compare_count` 与 `/summary` 的 `order_count` 同源(均 = 有效记录数),对应原型「完成比价(次)」列。接口已通但无真实业务写入时走 demo 兜底(seed 约 23 条)。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
> 数据库:SQLite 起步(`data/app.db`),生产可切 PostgreSQL(改 `DATABASE_URL`)。
|
||||
> ORM:SQLAlchemy 2.0(`app/models/`),迁移:Alembic(`alembic/versions/`,`render_as_batch` 兼容 SQLite)。
|
||||
> 金额字段一律存**整数**:金币=个数,现金=**分**(`*_cents`)。时间列 `DateTime(timezone=True)`。
|
||||
> 最后更新:2026-05-31
|
||||
> 最后更新:2026-06-04(+ admin_user / admin_audit_log)
|
||||
|
||||
---
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
| `feedback` | 用户帮助与反馈 | `models/feedback.py` | 反馈 | [详情](./feedback.md) |
|
||||
| `comparison_record` | 比价记录(每次比价完整明细) | `models/comparison.py` | 比价记录 | [详情](./comparison_record.md) |
|
||||
| `comparison_milestone_claim` | 比价战绩里程碑领取记录 | `models/comparison_milestone.py` | 比价记录/福利 | [详情](./comparison_milestone_claim.md) |
|
||||
| `admin_user` | 运营后台管理员账号(独立鉴权) | `models/admin.py` | Admin 后台 | [详情](./admin_user.md) |
|
||||
| `admin_audit_log` | 运营后台操作审计日志(只追加) | `models/admin.py` | Admin 后台 | [详情](./admin_audit_log.md) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# admin_audit_log — 运营后台操作审计日志
|
||||
|
||||
> 模型 `app/models/admin.py` | 关联接口 [admin-audit-logs](../api/admin-audit-logs.md) | [← 表索引](./README.md)
|
||||
|
||||
每个**写操作**(改钱/改状态/处理反馈等)落一条,记录"谁在何时、对谁、做了什么、前后值"。仅追加、不可删,用于追溯。`admin_username` / `target_id` 冗余存字符串,即使关联对象被删/改名也能追溯。
|
||||
|
||||
## 字段
|
||||
| 列 | 类型 | 约束 / 默认 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `id` | Integer | PK, autoincrement | |
|
||||
| `admin_id` | Integer | FK→admin_user.id, index, NOT NULL | 操作者 |
|
||||
| `admin_username` | String(64) | NOT NULL | 冗余操作者用户名(改名/禁用后仍可追溯) |
|
||||
| `action` | String(64) | index, NOT NULL | 操作类型,如 `user.coins.grant` / `user.status.set` / `withdraw.refresh` / `feedback.handle` |
|
||||
| `target_type` | String(32) | NOT NULL | 被操作对象类型,如 `user` / `withdraw` / `feedback` |
|
||||
| `target_id` | String(64) | nullable | 被操作对象 id(用字符串以兼容 `out_bill_no` 等非整型主键) |
|
||||
| `detail` | JSON | nullable | 上下文 + 前后值,如 `{"amount":1000,"reason":"...","before":{...},"after":{...}}` |
|
||||
| `ip` | String(64) | nullable | 操作者客户端 IP(取自 `X-Forwarded-For` 首段,仅记录不鉴权) |
|
||||
| `created_at` | DateTime(tz) | server_default now(), index, NOT NULL | 操作时间 |
|
||||
|
||||
## 索引与约束
|
||||
- PK: `id`
|
||||
- index: `ix_admin_audit_log_admin_id`(`admin_id`)、`ix_admin_audit_log_action`(`action`)、`ix_admin_audit_log_created_at`(`created_at`)
|
||||
|
||||
## 关系
|
||||
- `admin_id` → [`admin_user`](./admin_user.md).`id`(多对一)
|
||||
|
||||
## 说明
|
||||
- **JSON 列**:`detail` 用 `JSON().with_variant(JSONB(), "postgresql")` —— PG 上 JSONB,SQLite 退化为通用 JSON(同 `comparison_record.raw_payload`)。
|
||||
- **只追加**:无更新/删除接口,审计不可篡改。
|
||||
- **IP 可伪造**:`X-Forwarded-For` 可被客户端伪造,nginx 必须用 `proxy_set_header X-Forwarded-For $remote_addr` 覆盖;审计 IP 仅作记录、不参与鉴权。
|
||||
@@ -0,0 +1,28 @@
|
||||
# admin_user — 运营后台管理员账号
|
||||
|
||||
> 模型 `app/models/admin.py` | 关联接口 [admin-auth-login](../api/admin-auth-login.md) / [admin-admins-list](../api/admin-admins-list.md) | [← 表索引](./README.md)
|
||||
|
||||
运营后台的管理员账号,与 App 用户(`user` 表)**完全隔离**:走独立 JWT secret、独立鉴权链(见 `app/admin/`)。密码 bcrypt 存哈希,带角色做权限分级。
|
||||
|
||||
## 字段
|
||||
| 列 | 类型 | 约束 / 默认 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `id` | Integer | PK, autoincrement | |
|
||||
| `username` | String(64) | unique, index, NOT NULL | 登录名 |
|
||||
| `password_hash` | String(255) | NOT NULL | bcrypt 哈希(明文不落库) |
|
||||
| `role` | String(20) | NOT NULL, default `operator` | `super_admin`(全权+管账号)/ `finance`(钱:提现+金币)/ `operator`(用户+反馈+大盘) |
|
||||
| `status` | String(20) | NOT NULL, default `active` | `active` / `disabled`(禁用后 token 立即失效) |
|
||||
| `created_at` | DateTime(tz) | server_default now(), NOT NULL | 创建时间 |
|
||||
| `last_login_at` | DateTime(tz) | nullable | 最近登录时间(登录成功时更新) |
|
||||
|
||||
## 索引与约束
|
||||
- PK: `id`
|
||||
- unique index: `ix_admin_user_username`(`username` 唯一)
|
||||
|
||||
## 关系
|
||||
- 被 [`admin_audit_log`](./admin_audit_log.md).`admin_id` 引用(一管理员多条审计)。
|
||||
|
||||
## 说明
|
||||
- **角色权限**:`super_admin` 恒通过所有角色守卫(`require_role`);`finance` 管钱(提现/金币),`operator` 管用户/反馈/大盘。具体守卫见各接口文档。
|
||||
- **鉴权隔离**:admin token `typ=admin` + 独立 `ADMIN_JWT_SECRET`(≠ App 的 `JWT_SECRET_KEY`),App 用户 token 无法当 admin 用。admin 无 refresh,过期(默认 12h)重新登录。
|
||||
- **初始化**:首个管理员用 `scripts/create_admin.py` 命令行创建(无自助注册接口)。
|
||||
@@ -29,7 +29,7 @@
|
||||
| `status` | String(16) | NOT NULL, default `success` | `success`(拿到有效对比)/ `failed`(出错/没采到目标价) |
|
||||
| `information` | String(256) | nullable | done 帧文案;成功=摘要,失败=具体原因(前端失败时当原因展示) |
|
||||
| `items` | JSON(PG: JSONB) | NOT NULL, default [] | 下单菜品 `[{name, qty, specs?}]` |
|
||||
| `comparison_results` | JSON(PG: JSONB) | NOT NULL, default [] | 逐平台对比 `[{platform_id,platform_name,package,price(元),is_source,rank,coupon_saved}]`;`coupon_saved`=该平台主优惠额(元,美团红包/淘宝平台红包/京东优惠券·百亿补贴,只取那一笔,不含配送费/共减总额),各平台抠到红包即带值(2026-06 起源平台 Phase1 意图识别也抠,当前仅淘宝源),没用/没抠到为 null,前端展示「已优惠 ¥X」 |
|
||||
| `comparison_results` | JSON(PG: JSONB) | NOT NULL, default [] | 逐平台对比 `[{platform_id,platform_name,package,price(元),is_source,rank,coupon_saved,coupon_name}]`;`coupon_saved`=该平台主优惠额(元,美团红包/淘宝平台红包/京东优惠券·百亿补贴,只取那一笔,不含配送费/共减总额),各平台抠到红包即带值(2026-06 起源平台 Phase1 意图识别也抠,当前仅淘宝源),没用/没抠到为 null,前端展示「已优惠 ¥X」;`coupon_name`=优惠来源名(展示用 best-effort,美团"外卖大额神券"/京东"百亿补贴"/淘宝"平台红包"),null 走前端通用"红包" |
|
||||
| `skipped_dish_names` | JSON(PG: JSONB) | NOT NULL, default [] | 被跳过的菜名 |
|
||||
| `raw_payload` | JSON(PG: JSONB) | nullable | 客户端原始上报(calibration + done.params 全量) |
|
||||
| `created_at` | DateTime(tz) | server_default now(), index | 时间 |
|
||||
|
||||
+44
-6
@@ -120,27 +120,65 @@ def test_callback_bad_sign(client) -> None:
|
||||
assert _coin_balance(client, token) == 0
|
||||
|
||||
|
||||
def test_daily_cap(client) -> None:
|
||||
"""达到每日上限后继续回调 → 受理但不发(capped),余额封顶。"""
|
||||
def test_daily_count_cap(client, monkeypatch) -> None:
|
||||
"""达到每日发奖**次数兜底上限**后继续回调 → 受理但不发(capped),余额封顶。
|
||||
|
||||
次数上限现为时长闸的兜底(默认 200),这里 monkeypatch 调小到 3 加速(不真跑 200 次);
|
||||
本用例不上报观看时长 → 时长主闸不触发,纯验次数兜底。
|
||||
"""
|
||||
# 次数兜底现走 app_config getter(rebase 合 main 的运营可配后);patch getter 调小到 3
|
||||
monkeypatch.setattr("app.core.rewards.get_ad_daily_limit", lambda db: 3)
|
||||
phone = "13800003004"
|
||||
token = _login(client, phone)
|
||||
uid = _user_id(phone)
|
||||
|
||||
for i in range(DAILY_AD_REWARD_LIMIT):
|
||||
for i in range(3):
|
||||
r = _callback(client, _signed(uid, f"trans_cap_{i}"))
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
# 第 limit+1 次:capped,仍 is_valid(不让穿山甲重试),但不加币
|
||||
# 第 4 次:capped,仍 is_verify(不让穿山甲重试),但不加币
|
||||
r = _callback(client, _signed(uid, "trans_cap_over"))
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"is_verify": True, "reason": 0}
|
||||
|
||||
assert _coin_balance(client, token) == DAILY_AD_REWARD_LIMIT * AD_REWARD_COIN
|
||||
assert _coin_balance(client, token) == 3 * AD_REWARD_COIN
|
||||
st = client.get("/api/v1/ad/reward-status", headers=_auth(token)).json()
|
||||
assert st["used_today"] == DAILY_AD_REWARD_LIMIT
|
||||
assert st["used_today"] == 3
|
||||
assert st["remaining"] == 0
|
||||
|
||||
|
||||
def test_daily_watch_time_cap(client, monkeypatch) -> None:
|
||||
"""看广告累计观看时长达每日上限(主闸,这里调小到 100s)后,再回调发奖 → capped 不发金币。
|
||||
|
||||
时长由前端 watch-report 上报累计;到顶后 ① watch-report/reward-status remaining=0(客户端不再展示),
|
||||
② 后端发奖也因时长闸记 capped(双闸,前端绕不过)。次数兜底不动它(此时只看了 1 次,远没到次数上限)。
|
||||
"""
|
||||
# 时长上限两处引用都要 patch:api 用 rewards.X、grant 闸/today_status 用 ad_reward 内绑定的 X
|
||||
monkeypatch.setattr("app.core.rewards.DAILY_AD_WATCH_SECONDS_LIMIT", 100)
|
||||
monkeypatch.setattr("app.repositories.ad_reward.DAILY_AD_WATCH_SECONDS_LIMIT", 100)
|
||||
phone = "13800003201"
|
||||
token = _login(client, phone)
|
||||
uid = _user_id(phone)
|
||||
|
||||
# 上报一次 100s 观看 → 当日累计达上限,remaining=0
|
||||
r = client.post("/api/v1/ad/watch-report", json={"seconds": 100}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["watched_seconds_today"] == 100
|
||||
assert r.json()["watch_seconds_remaining"] == 0
|
||||
|
||||
# 此时回调发奖 → 时长闸命中 → capped(is_verify 仍 true,不让重试),不加金币
|
||||
before = _coin_balance(client, token)
|
||||
r = _callback(client, _signed(uid, "trans_time_cap"))
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"is_verify": True, "reason": 0}
|
||||
assert _coin_balance(client, token) == before # 未加币
|
||||
|
||||
st = client.get("/api/v1/ad/reward-status", headers=_auth(token)).json()
|
||||
assert st["watched_seconds_today"] == 100
|
||||
assert st["watch_seconds_limit"] == 100
|
||||
assert st["watch_seconds_remaining"] == 0
|
||||
|
||||
|
||||
def test_callback_unknown_user(client) -> None:
|
||||
"""验签过但 user_id 不存在 → 不发奖(is_verify false + reason),不崩。"""
|
||||
params = _signed(999999, "trans_ghost")
|
||||
|
||||
@@ -108,7 +108,8 @@ def test_update_ad_limit_takes_effect(admin_client: TestClient, token: str) -> N
|
||||
uid = _seed_user("13912340002")
|
||||
db = SessionLocal()
|
||||
try:
|
||||
_used, limit, _coin, _rc, _cd = ad_reward.today_status(db, uid)
|
||||
# today_status 现返 7 元组(末两位为观看时长闸:已看秒数 / 上限),取次数上限位
|
||||
_used, limit, _coin, _rc, _cd, _ws, _wl = ad_reward.today_status(db, uid)
|
||||
assert limit == 5 # 新配置生效
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -33,7 +33,8 @@ def _food_payload(trace_id: str) -> dict:
|
||||
],
|
||||
"comparison_results": [
|
||||
{"platform_id": "meituan", "platform_name": "美团", "package": "com.sankuai.meituan",
|
||||
"price": 123.50, "is_source": False, "rank": 1, "coupon_saved": 7.0},
|
||||
"price": 123.50, "is_source": False, "rank": 1,
|
||||
"coupon_saved": 7.0, "coupon_name": "外卖大额神券"},
|
||||
{"platform_id": "taobao_flash", "platform_name": "淘宝闪购", "package": "com.taobao.taobao",
|
||||
"price": 128.50, "is_source": True, "rank": 2},
|
||||
{"platform_id": "jd_waimai", "platform_name": "京东外卖", "package": "com.jingdong.app.mall",
|
||||
@@ -79,7 +80,7 @@ def test_report_and_derive(client) -> None:
|
||||
|
||||
|
||||
def test_coupon_saved_passthrough(client) -> None:
|
||||
"""红包优惠额 coupon_saved 上报→落库→读出;仅目标平台带值,源平台不带(null)。"""
|
||||
"""红包优惠额 coupon_saved + 来源名 coupon_name 上报→落库→读出;仅目标平台带值,源平台不带(null)。"""
|
||||
token = _login(client, "13800002010")
|
||||
rid = client.post(
|
||||
"/api/v1/compare/record", json=_food_payload("trace-coupon"), headers=_auth(token)
|
||||
@@ -87,7 +88,9 @@ def test_coupon_saved_passthrough(client) -> None:
|
||||
d = client.get(f"/api/v1/compare/records/{rid}", headers=_auth(token)).json()
|
||||
by_pid = {x["platform_id"]: x for x in d["comparison_results"]}
|
||||
assert by_pid["meituan"]["coupon_saved"] == 7.0 # 目标平台带值
|
||||
assert by_pid["meituan"]["coupon_name"] == "外卖大额神券" # 来源名透传(pricebot#38)
|
||||
assert by_pid["taobao_flash"].get("coupon_saved") is None # 源平台不带/为 null
|
||||
assert by_pid["taobao_flash"].get("coupon_name") is None # 源平台无来源名
|
||||
|
||||
|
||||
def test_source_is_cheapest_no_saving(client) -> None:
|
||||
|
||||
+53
-6
@@ -133,10 +133,10 @@ def test_exchange_info(client) -> None:
|
||||
|
||||
|
||||
def test_exchange_flow(client) -> None:
|
||||
"""先供款够兑换下限的金币 → 兑换 1 元 → 金币扣、现金加 → 现金流水有记录。
|
||||
"""先供款够兑 1 元的金币 → 兑换 1 元 → 金币扣、现金加 → 现金流水有记录。
|
||||
|
||||
打开消息提醒任务已降到 1000 金币(不再 = 兑换下限), 不能再靠领任务供款;
|
||||
直接 grant_coins 注入 MIN_EXCHANGE_COIN(= COIN_PER_YUAN = 10000)当种子。
|
||||
兑换下限已降到 1 分(MIN_EXCHANGE_COIN = COIN_PER_CENT = 100), 但本用例验证兑换 1 元,
|
||||
直接 grant_coins 注入 COIN_PER_YUAN(= 10000)当种子(够兑 1 元)。
|
||||
"""
|
||||
phone = "13800001005"
|
||||
token = _login(client, phone)
|
||||
@@ -144,7 +144,7 @@ def test_exchange_flow(client) -> None:
|
||||
with SessionLocal() as db:
|
||||
user = get_user_by_phone(db, phone)
|
||||
assert user is not None
|
||||
crud_wallet.grant_coins(db, user.id, MIN_EXCHANGE_COIN, biz_type="test_seed", remark="测试供款")
|
||||
crud_wallet.grant_coins(db, user.id, COIN_PER_YUAN, biz_type="test_seed", remark="测试供款")
|
||||
db.commit()
|
||||
|
||||
# 兑换 10000 金币 → 100 分
|
||||
@@ -180,6 +180,51 @@ def test_exchange_flow(client) -> None:
|
||||
assert page["items"][0]["biz_type"] == "exchange_in"
|
||||
|
||||
|
||||
def test_exchange_min_floor_one_cent(client) -> None:
|
||||
"""锁定本次下调的兑换下限:正好兑下限额(MIN_EXCHANGE_COIN=100 金币=1 分)应成功。
|
||||
|
||||
这是本 PR 的核心新能力(下限 10000→100,可兑 1 分起)。test_exchange_flow 兑的是
|
||||
1 元(10000),在旧下限下也通过,证明不了新下限;本用例供款并兑换正好等于下限的
|
||||
100 金币,断言到账 1 分。若有人把 MIN_EXCHANGE_COIN 改回 10000,100 会因低于下限被
|
||||
判 400,本用例随之失败,从而把新下限值钉死。
|
||||
"""
|
||||
phone = "13800001010"
|
||||
token = _login(client, phone)
|
||||
# 供款: 正好注入一个下限额度的金币(=COIN_PER_CENT=100)
|
||||
with SessionLocal() as db:
|
||||
user = get_user_by_phone(db, phone)
|
||||
assert user is not None
|
||||
crud_wallet.grant_coins(
|
||||
db, user.id, MIN_EXCHANGE_COIN, biz_type="test_seed", remark="测试供款"
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# 兑换下限额 100 金币 → 1 分
|
||||
r = client.post(
|
||||
"/api/v1/wallet/exchange",
|
||||
json={"coin_amount": MIN_EXCHANGE_COIN},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
res = r.json()
|
||||
assert res["coin_amount"] == MIN_EXCHANGE_COIN
|
||||
assert res["cash_added_cents"] == 1 # coins_to_cents(100) == 1
|
||||
assert res["coin_balance"] == 0
|
||||
assert res["cash_balance_cents"] == 1
|
||||
|
||||
# 金币流水有一笔 exchange_out(=-100)
|
||||
r = client.get("/api/v1/wallet/coin-transactions", headers=_auth(token))
|
||||
out_txn = next(t for t in r.json()["items"] if t["biz_type"] == "exchange_out")
|
||||
assert out_txn["amount"] == -MIN_EXCHANGE_COIN
|
||||
|
||||
# 现金流水有且仅有一笔 exchange_in(=+1 分)
|
||||
r = client.get("/api/v1/wallet/cash-transactions", headers=_auth(token))
|
||||
cash = r.json()["items"]
|
||||
assert len(cash) == 1
|
||||
assert cash[0]["amount_cents"] == 1
|
||||
assert cash[0]["biz_type"] == "exchange_in"
|
||||
|
||||
|
||||
def test_exchange_insufficient_and_invalid(client) -> None:
|
||||
token = _login(client, "13800001006")
|
||||
|
||||
@@ -191,10 +236,10 @@ def test_exchange_insufficient_and_invalid(client) -> None:
|
||||
)
|
||||
assert r.status_code == 409
|
||||
|
||||
# 低于最小额 → 400
|
||||
# 低于最小额(下限现为 1 分=100;取 MIN_EXCHANGE_COIN-1=99,既低于下限又非整分)→ 400
|
||||
r = client.post(
|
||||
"/api/v1/wallet/exchange",
|
||||
json={"coin_amount": MIN_EXCHANGE_COIN - COIN_PER_CENT},
|
||||
json={"coin_amount": MIN_EXCHANGE_COIN - 1},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert r.status_code == 400
|
||||
@@ -226,6 +271,8 @@ def test_savings_summary_and_battle(client) -> None:
|
||||
assert b["streak_days"] >= 1
|
||||
assert b["week_saved_cents"] >= 0
|
||||
assert 0 <= b["beat_percent"] <= 100
|
||||
# 完成比价次数与 summary 的 order_count 同源(均 = 有效记录数)
|
||||
assert b["compare_count"] == s["order_count"]
|
||||
|
||||
|
||||
def test_savings_seeder_idempotent(client) -> None:
|
||||
|
||||
+79
-10
@@ -10,6 +10,7 @@ from sqlalchemy import select
|
||||
from app.db.session import SessionLocal
|
||||
from app.models.user import User
|
||||
from app.models.wallet import CoinAccount, WithdrawOrder
|
||||
from app.repositories import wallet as crud_wallet
|
||||
|
||||
|
||||
def _login(client, phone: str) -> str:
|
||||
@@ -43,6 +44,24 @@ def _patch_userinfo(monkeypatch, openid="openid_test_abc", nickname="测试昵
|
||||
)
|
||||
|
||||
|
||||
def _approve(bill: str) -> None:
|
||||
"""模拟管理员审核通过(走 repo,等价 admin 端点 approve → execute_withdraw_transfer 发起转账)。"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
crud_wallet.approve_withdraw(db, bill)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _reject(bill: str, reason: str = "不符合提现规则") -> None:
|
||||
"""模拟管理员审核拒绝(走 repo,等价 admin 端点 reject → 退款 + rejected)。"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
crud_wallet.reject_withdraw(db, bill, reason)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_bind_wechat(client, monkeypatch) -> None:
|
||||
_patch_userinfo(monkeypatch)
|
||||
token = _login(client, "13800002001")
|
||||
@@ -64,7 +83,8 @@ def test_bind_wechat(client, monkeypatch) -> None:
|
||||
assert j["wechat_nickname"] == "测试昵称"
|
||||
|
||||
|
||||
def test_withdraw_success_flow(client, monkeypatch) -> None:
|
||||
def test_withdraw_submit_then_approve_success_flow(client, monkeypatch) -> None:
|
||||
"""提现先进 reviewing(扣款不打款) → 管理员审核通过才发起转账 → 查单 SUCCESS → success。"""
|
||||
monkeypatch.setattr("app.integrations.wxpay.code_to_userinfo", lambda code: {"openid": "openid_ok", "nickname": None, "avatar_url": None, "raw": {}})
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.create_transfer",
|
||||
@@ -77,13 +97,12 @@ def test_withdraw_success_flow(client, monkeypatch) -> None:
|
||||
_seed_cash(client, token, "13800002002", 100)
|
||||
client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
|
||||
# 发起提现 50 分
|
||||
# 发起提现 50 分 → 进入待审核(reviewing),已扣款但未打款,无 package_info
|
||||
r = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["status"] == "pending"
|
||||
assert body["package_info"] == "pkg123"
|
||||
assert body["mch_id"] and body["app_id"]
|
||||
assert body["status"] == "reviewing"
|
||||
assert body["package_info"] is None
|
||||
assert body["cash_balance_cents"] == 50 # 已扣
|
||||
bill = body["out_bill_no"]
|
||||
|
||||
@@ -92,7 +111,10 @@ def test_withdraw_success_flow(client, monkeypatch) -> None:
|
||||
txns = r.json()["items"]
|
||||
assert any(t["biz_type"] == "withdraw" and t["amount_cents"] == -50 for t in txns)
|
||||
|
||||
# 查单 → 微信返回 SUCCESS → 归一化 success
|
||||
# 管理员审核通过 → 发起微信转账(mock WAIT_USER_CONFIRM,单进 pending)
|
||||
_approve(bill)
|
||||
|
||||
# 用户确认到账后查单 → SUCCESS → 归一化 success
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.query_transfer",
|
||||
lambda out_bill_no: {"status_code": 200, "data": {"state": "SUCCESS"}},
|
||||
@@ -123,8 +145,12 @@ def test_withdraw_abandoned_confirm_cancels_and_refunds(client, monkeypatch) ->
|
||||
|
||||
r = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50}, headers=_auth(token))
|
||||
bill = r.json()["out_bill_no"]
|
||||
assert r.json()["status"] == "reviewing"
|
||||
assert r.json()["cash_balance_cents"] == 50 # 已扣
|
||||
|
||||
# 管理员审核通过 → 发起转账(mock WAIT_USER_CONFIRM,单进 pending)
|
||||
_approve(bill)
|
||||
|
||||
# 回到 app 查单:微信仍是 WAIT_USER_CONFIRM(没确认) + 撤单成功
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.query_transfer",
|
||||
@@ -166,7 +192,8 @@ def test_withdraw_not_bound(client) -> None:
|
||||
assert r.status_code == 400, r.text
|
||||
|
||||
|
||||
def test_withdraw_transfer_fail_refunds(client, monkeypatch) -> None:
|
||||
def test_withdraw_approve_transfer_fail_refunds(client, monkeypatch) -> None:
|
||||
"""审核通过发起转账失败(非200) + 查单 NOT_FOUND(未创建) → 自动退款 + 单 failed。"""
|
||||
monkeypatch.setattr("app.integrations.wxpay.code_to_userinfo", lambda code: {"openid": "openid_fail", "nickname": None, "avatar_url": None, "raw": {}})
|
||||
monkeypatch.setattr(
|
||||
"app.integrations.wxpay.create_transfer",
|
||||
@@ -184,8 +211,14 @@ def test_withdraw_transfer_fail_refunds(client, monkeypatch) -> None:
|
||||
_seed_cash(client, token, "13800002005", 100)
|
||||
client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
|
||||
# 发起提现 → reviewing(已扣款),此刻不打款不会失败
|
||||
r = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50}, headers=_auth(token))
|
||||
assert r.status_code == 502, r.text
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "reviewing"
|
||||
bill = r.json()["out_bill_no"]
|
||||
|
||||
# 管理员审核通过 → 转账失败 → 自动退款 + 单 failed
|
||||
_approve(bill)
|
||||
|
||||
# 余额已退回
|
||||
r = client.get("/api/v1/wallet/account", headers=_auth(token))
|
||||
@@ -222,7 +255,9 @@ def test_withdraw_idempotent_same_bill_no(client, monkeypatch) -> None:
|
||||
r2 = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50, "out_bill_no": bill}, headers=_auth(token))
|
||||
assert r2.status_code == 200, r2.text
|
||||
|
||||
assert calls["n"] == 1 # 只真发起一次转账
|
||||
# 提现阶段不打款 → create_transfer 一次都不会被调;两次都返回同一张待审核单
|
||||
assert calls["n"] == 0
|
||||
assert r1.json()["status"] == "reviewing" and r2.json()["status"] == "reviewing"
|
||||
assert r1.json()["out_bill_no"] == bill
|
||||
assert r2.json()["out_bill_no"] == bill
|
||||
# 余额只扣一次(100-50=50)
|
||||
@@ -249,7 +284,13 @@ def test_withdraw_ambiguous_timeout_then_success_no_refund(client, monkeypatch)
|
||||
|
||||
r = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50}, headers=_auth(token))
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "success"
|
||||
assert r.json()["status"] == "reviewing"
|
||||
bill = r.json()["out_bill_no"]
|
||||
|
||||
# 审核通过 → 转账调用超时(异常) → 查单确认 SUCCESS → 不退款,单 success
|
||||
_approve(bill)
|
||||
r = client.get("/api/v1/wallet/withdraw-orders", headers=_auth(token))
|
||||
assert r.json()["items"][0]["status"] == "success"
|
||||
# 没退款:余额仍是扣后的 50,且无 withdraw_refund
|
||||
r = client.get("/api/v1/wallet/account", headers=_auth(token))
|
||||
assert r.json()["cash_balance_cents"] == 50
|
||||
@@ -269,3 +310,31 @@ def test_bind_rejects_openid_already_bound(client, monkeypatch) -> None:
|
||||
token_b = _login(client, "13800002010")
|
||||
r = client.post("/api/v1/wallet/bind-wechat", json={"code": "cb"}, headers=_auth(token_b))
|
||||
assert r.status_code == 409, r.text
|
||||
|
||||
|
||||
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": {}})
|
||||
token = _login(client, "13800002011")
|
||||
_seed_cash(client, token, "13800002011", 100)
|
||||
client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token))
|
||||
|
||||
# 发起提现 → reviewing(已扣款,余额 50)
|
||||
r = client.post("/api/v1/wallet/withdraw", json={"amount_cents": 50}, headers=_auth(token))
|
||||
assert r.json()["status"] == "reviewing"
|
||||
assert r.json()["cash_balance_cents"] == 50
|
||||
bill = r.json()["out_bill_no"]
|
||||
|
||||
# 管理员拒绝 → 退款 + rejected(不调微信,无需 mock 转账)
|
||||
_reject(bill, "测试拒绝")
|
||||
|
||||
# 余额退回 100
|
||||
r = client.get("/api/v1/wallet/account", headers=_auth(token))
|
||||
assert r.json()["cash_balance_cents"] == 100
|
||||
# 有退款流水
|
||||
r = client.get("/api/v1/wallet/cash-transactions", headers=_auth(token))
|
||||
assert any(t["biz_type"] == "withdraw_refund" and t["amount_cents"] == 50 for t in r.json()["items"])
|
||||
# 单 rejected + 理由透出
|
||||
r = client.get("/api/v1/wallet/withdraw/status", params={"out_bill_no": bill}, headers=_auth(token))
|
||||
assert r.json()["status"] == "rejected"
|
||||
assert r.json()["fail_reason"] == "测试拒绝"
|
||||
|
||||
Reference in New Issue
Block a user