From e11f506e1e485fb77b6dcc4f6f81d39fee645455 Mon Sep 17 00:00:00 2001 From: guke Date: Fri, 24 Jul 2026 16:40:57 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E6=8F=90=E7=8E=B0=E5=85=81=E8=AE=B8?= =?UTF-8?q?=E5=9C=A8=E9=80=94=E6=97=B6=E7=BB=A7=E7=BB=AD=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=E7=94=B3=E8=AF=B7=20=E8=AE=BE=E8=AE=A1spec=20(#173)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 摘要 取消「同一用户同时仅一笔在途提现」限制:已有 reviewing/pending 提现单时可继续发起新申请。 - 删应用层在途单检查(WithdrawTooFrequentError)+ 删 DB 分区唯一索引 ux_withdraw_order_user_active(含迁移) - 清理失效死代码;IntegrityError 兜底瘦身为仅处理 out_bill_no 幂等 - 既有约束不变:建单先扣款(防超提)、coin_cash 每日档位次数、out_bill_no 幂等、解绑退款、admin 审核/对账均按单号维度 ## 测试 - 新增:多笔在途并存放行(coin_cash & invite_cash)、第二笔仅受余额约束(409 现金余额不足) - 迁移 upgrade→downgrade→upgrade 回环验证 - 提现域全绿(test_withdraw / test_invite_cash_withdraw / test_withdraw_ledger_check) ## 注意 - 客户端:每次提交需生成新的 out_bill_no;未开免确认时多笔 pending 各返回一个微信确认页,App 需能处理多笔待确认 - 无并发硬上限(产品拍板):coin_cash 由每日档位次数天然封顶,invite_cash 仅受余额约束 --------- Co-authored-by: guke Reviewed-on: https://gitea.shaguabijia.com/WonderableAI/shaguabijia-app-server/pulls/173 --- .../drop_withdraw_active_unique_index.py | 37 ++ app/api/v1/wallet.py | 5 - app/models/wallet.py | 9 - app/repositories/wallet.py | 25 +- .../2026-07-24-withdraw-allow-concurrent.md | 323 ++++++++++++++++++ ...-07-24-withdraw-allow-concurrent-design.md | 119 +++++++ tests/test_invite_cash_withdraw.py | 41 ++- tests/test_withdraw.py | 55 +++ 8 files changed, 572 insertions(+), 42 deletions(-) create mode 100644 alembic/versions/drop_withdraw_active_unique_index.py create mode 100644 docs/superpowers/plans/2026-07-24-withdraw-allow-concurrent.md create mode 100644 docs/superpowers/specs/2026-07-24-withdraw-allow-concurrent-design.md diff --git a/alembic/versions/drop_withdraw_active_unique_index.py b/alembic/versions/drop_withdraw_active_unique_index.py new file mode 100644 index 0000000..97ac454 --- /dev/null +++ b/alembic/versions/drop_withdraw_active_unique_index.py @@ -0,0 +1,37 @@ +"""drop withdraw active-order partial unique index (allow multiple in-flight withdrawals) + +Revision ID: drop_withdraw_active_unique_index +Revises: d8dd2106e438 +Create Date: 2026-07-24 00:00:00.000000 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = "drop_withdraw_active_unique_index" +down_revision: Union[str, Sequence[str], None] = "d8dd2106e438" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # 取消「同一用户同一时刻仅一笔在途提现」:允许 reviewing/pending 并存。 + # 仅删本索引;姊妹索引 ux_cash_transaction_withdraw_refund_ref(退款幂等)保持不动。 + op.drop_index("ux_withdraw_order_user_active", table_name="withdraw_order") + + +def downgrade() -> None: + # 回滚重建分区唯一索引。注意:若届时某用户已有 ≥2 张在途单,重建会因唯一冲突失败—— + # 属预期的回滚代价(取消限制后本就允许多单),需先人工收敛在途单再回滚。 + op.create_index( + "ux_withdraw_order_user_active", + "withdraw_order", + ["user_id"], + unique=True, + sqlite_where=sa.text("status IN ('reviewing', 'pending')"), + postgresql_where=sa.text("status IN ('reviewing', 'pending')"), + ) diff --git a/app/api/v1/wallet.py b/app/api/v1/wallet.py index 7b0dac0..6441f47 100644 --- a/app/api/v1/wallet.py +++ b/app/api/v1/wallet.py @@ -222,11 +222,6 @@ def withdraw(req: WithdrawRequest, user: CurrentUser, db: DbSession) -> Withdraw ) from e except crud_wallet.WechatNotBoundError as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请先绑定微信") from e - except crud_wallet.WithdrawTooFrequentError as e: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="已有提现申请正在审核或打款中,请处理完成后再申请", - ) from e except crud_wallet.WithdrawTierUnavailableError as e: # 福利页档位闸(7-9):次数满/已选其他额度。正常客户端已按 tiers 预拦,此处兜底防绕过。 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="今日额度已达上限") from e diff --git a/app/models/wallet.py b/app/models/wallet.py index cb815d8..47c9764 100644 --- a/app/models/wallet.py +++ b/app/models/wallet.py @@ -96,15 +96,6 @@ class WithdrawOrder(Base): """ __tablename__ = "withdraw_order" - __table_args__ = ( - Index( - "ux_withdraw_order_user_active", - "user_id", - unique=True, - sqlite_where=text("status IN ('reviewing', 'pending')"), - postgresql_where=text("status IN ('reviewing', 'pending')"), - ), - ) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) user_id: Mapped[int] = mapped_column( diff --git a/app/repositories/wallet.py b/app/repositories/wallet.py index 5484337..4337752 100644 --- a/app/repositories/wallet.py +++ b/app/repositories/wallet.py @@ -35,7 +35,6 @@ from app.services import notification_events _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 被误判已用、资格永久锁死)。 @@ -69,10 +68,6 @@ class InsufficientCashError(Exception): """现金余额不足。""" -class WithdrawTooFrequentError(Exception): - """提现申请过于频繁,或已有未完成提现单。""" - - class WithdrawTierUnavailableError(Exception): """该档位今日不可提:次数已满,或今天已选了其他额度(7-9 福利页档位规则)。""" @@ -755,17 +750,8 @@ def create_withdraw( else: out_bill_no = uuid.uuid4().hex - active_order_id = db.execute( - select(WithdrawOrder.id).where( - WithdrawOrder.user_id == user_id, - WithdrawOrder.status.in_(_WITHDRAW_ACTIVE_STATUSES), - ).limit(1) - ).scalar_one_or_none() - if active_order_id is not None: - raise WithdrawTooFrequentError - # 福利页档位闸(7-9):coin_cash 只能提预设档位,且该档今日可提(服务端权威口径,防绕过 - # 客户端刷)。放在幂等返回/在途互斥之后:同号重试仍原样返回旧单,不被档位闸误杀。 + # 客户端刷)。放在幂等返回之后:同号重试仍原样返回旧单,不被档位闸误杀。 # allow_sub_min(0.01 调试直发)保持原样放行,不受档位约束;invite_cash 本轮无档位概念不校验。 if source == "coin_cash" and not allow_sub_min: tier_state = next( @@ -815,6 +801,7 @@ def create_withdraw( db.commit() except IntegrityError: db.rollback() + # 唯一冲突只可能来自 out_bill_no 幂等键并发重试:原样返回既有单;否则未知冲突,上抛。 existing = db.execute( select(WithdrawOrder).where( WithdrawOrder.out_bill_no == out_bill_no, WithdrawOrder.user_id == user_id @@ -822,14 +809,6 @@ def create_withdraw( ).scalar_one_or_none() if existing is not None: return existing - active_order_id = db.execute( - select(WithdrawOrder.id).where( - WithdrawOrder.user_id == user_id, - WithdrawOrder.status.in_(_WITHDRAW_ACTIVE_STATUSES), - ).limit(1) - ).scalar_one_or_none() - if active_order_id is not None: - raise WithdrawTooFrequentError from None raise db.refresh(order) return order # 待管理员审核;**不在此处打款** diff --git a/docs/superpowers/plans/2026-07-24-withdraw-allow-concurrent.md b/docs/superpowers/plans/2026-07-24-withdraw-allow-concurrent.md new file mode 100644 index 0000000..6b1498c --- /dev/null +++ b/docs/superpowers/plans/2026-07-24-withdraw-allow-concurrent.md @@ -0,0 +1,323 @@ +# 允许在途提现时继续提交新申请 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 取消「同一用户同一时刻仅一笔在途提现」限制,已有 `reviewing`/`pending` 单时允许继续提交新的提现申请。 + +**Architecture:** 该限制由两道闸共同强制——应用层 `create_withdraw` 的在途单检查(`WithdrawTooFrequentError`)与数据库分区唯一索引 `ux_withdraw_order_user_active`。彻底移除两者 + 清理随之失效的死代码;既有约束(建单先扣款、`coin_cash` 每日档位次数、`out_bill_no` 幂等)天然保留,无需改动。测试库由 `Base.metadata.create_all()` 依模型建表,故删模型内索引定义即让测试反映新 schema;另配一条 Alembic 迁移让真实库(dev/prod)落地同一变更。 + +**Tech Stack:** FastAPI · SQLAlchemy 2.0 · Alembic · pytest · ruff + +规格来源:[docs/superpowers/specs/2026-07-24-withdraw-allow-concurrent-design.md](../specs/2026-07-24-withdraw-allow-concurrent-design.md) + +--- + +## 关键事实(实现依据) + +- 当前 Alembic head:`d8dd2106e438`(新迁移的 `down_revision`)。 +- 索引出处:[`alembic/versions/withdraw_safety_indexes.py`](../../../alembic/versions/withdraw_safety_indexes.py) 同时建了两个索引——本次**只删** `ux_withdraw_order_user_active`,**保留**姊妹索引 `ux_cash_transaction_withdraw_refund_ref`(退款幂等)。 +- 档位:`WithdrawTier(50, "0.5", None, 3, False)`——50 分(0.5 元)是**常规档**,每日 3 次,非新人档;测试用它来造多笔在途。 +- 测试库走 `create_all`(见 `tests/conftest.py`),**不跑 Alembic**;故迁移的正确性由本计划单独的 upgrade/downgrade 回环验证,不由 pytest 覆盖。 +- `app/models/wallet.py` 的 `Index`/`text` 仍被其它表(行 54/186/224)使用,删本表 `__table_args__` 后**无需**清理 import。 + +--- + +## Task 1: 允许多笔在途提现并存(TDD:模型 + 应用层 + 端点 + 迁移,单次提交) + +本变更是一次原子的 schema+行为改动:模型内索引、应用层检查、Alembic 迁移相互依赖,任一缺失都会让"多笔在途"在测试库或真实库其一不成立。故作为**一个任务、一次提交**完成,内部按 TDD 分步。 + +**Files:** +- Test: `tests/test_withdraw.py`(新增 2 个用例) +- Modify: `app/repositories/wallet.py`(删在途单检查 + IntegrityError 兜底瘦身 + 删死常量/异常) +- Modify: `app/api/v1/wallet.py:225-229`(删失效的 409 处理) +- Modify: `app/models/wallet.py:99-107`(删分区唯一索引) +- Create: `alembic/versions/drop_withdraw_active_unique_index.py`(真实库删索引) + +--- + +- [ ] **Step 1: 写两个失败测试** + +在 `tests/test_withdraw.py` 末尾追加(复用文件内既有 helper `_login`/`_auth`/`_seed_cash`/`_patch_userinfo`): + +```python +def test_withdraw_multiple_in_flight_allowed(client, monkeypatch) -> None: + """取消「同时仅一单」:已有在途(reviewing)时,不同 out_bill_no 可继续提交,两单并存。""" + _patch_userinfo(monkeypatch, "openid_multi_inflight") + token = _login(client, "13800002020") + _seed_cash(client, token, "13800002020", 100) # 够两笔 0.5 + client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) + + r1 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billmulti00000001"}, + headers=_auth(token), + ) + assert r1.status_code == 200, r1.text + assert r1.json()["status"] == "reviewing" + + r2 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billmulti00000002"}, + headers=_auth(token), + ) + assert r2.status_code == 200, r2.text + assert r2.json()["status"] == "reviewing" + + # 两张在途单并存 + r = client.get("/api/v1/wallet/withdraw-orders", headers=_auth(token)) + reviewing = [o for o in r.json()["items"] if o["status"] == "reviewing"] + assert len(reviewing) == 2, r.text + # 余额扣两次:100-50-50=0 + r = client.get("/api/v1/wallet/account", headers=_auth(token)) + assert r.json()["cash_balance_cents"] == 0 + + +def test_withdraw_second_blocked_only_by_insufficient_cash(client, monkeypatch) -> None: + """并行放开后第二笔仅受余额约束:余额不足返 409「现金余额不足」,而非旧的「已有提现」拦截。""" + _patch_userinfo(monkeypatch, "openid_multi_insuff") + token = _login(client, "13800002021") + _seed_cash(client, token, "13800002021", 50) # 仅够一笔 0.5 + client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) + + r1 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billinsuff0000001"}, + headers=_auth(token), + ) + assert r1.status_code == 200, r1.text + + r2 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billinsuff0000002"}, + headers=_auth(token), + ) + assert r2.status_code == 409, r2.text + assert "现金余额不足" in r2.json()["detail"] +``` + +- [ ] **Step 2: 运行新测试,确认失败** + +Run: `pytest tests/test_withdraw.py::test_withdraw_multiple_in_flight_allowed tests/test_withdraw.py::test_withdraw_second_blocked_only_by_insufficient_cash -q` +Expected: 两条 FAIL —— `multiple_in_flight` 因第二笔被拦返回 409(期望 200);`second_blocked` 因返回的 409 detail 是「已有提现申请正在审核或打款中」而非「现金余额不足」。 + +- [ ] **Step 3: 应用层删在途单互斥检查**(`app/repositories/wallet.py` · `create_withdraw`) + +删掉在途单预检查(它紧邻档位闸注释之前): + +old: +```python + active_order_id = db.execute( + select(WithdrawOrder.id).where( + WithdrawOrder.user_id == user_id, + WithdrawOrder.status.in_(_WITHDRAW_ACTIVE_STATUSES), + ).limit(1) + ).scalar_one_or_none() + if active_order_id is not None: + raise WithdrawTooFrequentError + + # 福利页档位闸(7-9):coin_cash 只能提预设档位,且该档今日可提(服务端权威口径,防绕过 +``` +new: +```python + # 福利页档位闸(7-9):coin_cash 只能提预设档位,且该档今日可提(服务端权威口径,防绕过 +``` + +- [ ] **Step 4: 应用层给 IntegrityError 兜底瘦身**(同函数末尾 commit 处) + +索引移除后不会再因在途单触发唯一冲突,只保留 `out_bill_no` 幂等重试分支: + +old: +```python + except IntegrityError: + db.rollback() + existing = db.execute( + select(WithdrawOrder).where( + WithdrawOrder.out_bill_no == out_bill_no, WithdrawOrder.user_id == user_id + ) + ).scalar_one_or_none() + if existing is not None: + return existing + active_order_id = db.execute( + select(WithdrawOrder.id).where( + WithdrawOrder.user_id == user_id, + WithdrawOrder.status.in_(_WITHDRAW_ACTIVE_STATUSES), + ).limit(1) + ).scalar_one_or_none() + if active_order_id is not None: + raise WithdrawTooFrequentError from None + raise +``` +new: +```python + except IntegrityError: + db.rollback() + # 唯一冲突只可能来自 out_bill_no 幂等键并发重试:原样返回既有单;否则未知冲突,上抛。 + existing = db.execute( + select(WithdrawOrder).where( + WithdrawOrder.out_bill_no == out_bill_no, WithdrawOrder.user_id == user_id + ) + ).scalar_one_or_none() + if existing is not None: + return existing + raise +``` + +- [ ] **Step 5: 删死常量 `_WITHDRAW_ACTIVE_STATUSES`**(`app/repositories/wallet.py` 模块顶部) + +只删常量行,保留其后属于 `_NEWBIE_TIER_HELD_STATUSES` 的注释: + +old: +```python +_WITHDRAW_ACTIVE_STATUSES = {"reviewing", "pending"} +# 占用新人档「一次性」资格的提现状态:进行中(reviewing/pending)或成功打款(success)。 +``` +new: +```python +# 占用新人档「一次性」资格的提现状态:进行中(reviewing/pending)或成功打款(success)。 +``` + +- [ ] **Step 6: 删死异常类 `WithdrawTooFrequentError`**(`app/repositories/wallet.py`) + +old: +```python +class WithdrawTooFrequentError(Exception): + """提现申请过于频繁,或已有未完成提现单。""" + + +class WithdrawTierUnavailableError(Exception): +``` +new: +```python +class WithdrawTierUnavailableError(Exception): +``` + +- [ ] **Step 7: 删端点内失效的 409 处理**(`app/api/v1/wallet.py` · `withdraw`) + +old: +```python + except crud_wallet.WechatNotBoundError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请先绑定微信") from e + except crud_wallet.WithdrawTooFrequentError as e: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="已有提现申请正在审核或打款中,请处理完成后再申请", + ) from e + except crud_wallet.WithdrawTierUnavailableError as e: +``` +new: +```python + except crud_wallet.WechatNotBoundError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请先绑定微信") from e + except crud_wallet.WithdrawTierUnavailableError as e: +``` + +- [ ] **Step 8: 删模型内分区唯一索引**(`app/models/wallet.py` · `WithdrawOrder`) + +old: +```python + __tablename__ = "withdraw_order" + __table_args__ = ( + Index( + "ux_withdraw_order_user_active", + "user_id", + unique=True, + sqlite_where=text("status IN ('reviewing', 'pending')"), + postgresql_where=text("status IN ('reviewing', 'pending')"), + ), + ) +``` +new: +```python + __tablename__ = "withdraw_order" +``` + +- [ ] **Step 9: 运行新测试,确认通过** + +Run: `pytest tests/test_withdraw.py::test_withdraw_multiple_in_flight_allowed tests/test_withdraw.py::test_withdraw_second_blocked_only_by_insufficient_cash -q` +Expected: 2 passed。 + +- [ ] **Step 10: 建 Alembic 迁移(真实库删索引)** + +创建 `alembic/versions/drop_withdraw_active_unique_index.py`: + +```python +"""drop withdraw active-order partial unique index (allow multiple in-flight withdrawals) + +Revision ID: drop_withdraw_active_unique_index +Revises: d8dd2106e438 +Create Date: 2026-07-24 00:00:00.000000 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = "drop_withdraw_active_unique_index" +down_revision: Union[str, Sequence[str], None] = "d8dd2106e438" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # 取消「同一用户同一时刻仅一笔在途提现」:允许 reviewing/pending 并存。 + # 仅删本索引;姊妹索引 ux_cash_transaction_withdraw_refund_ref(退款幂等)保持不动。 + op.drop_index("ux_withdraw_order_user_active", table_name="withdraw_order") + + +def downgrade() -> None: + # 回滚重建分区唯一索引。注意:若届时某用户已有 ≥2 张在途单,重建会因唯一冲突失败—— + # 属预期的回滚代价(取消限制后本就允许多单),需先人工收敛在途单再回滚。 + op.create_index( + "ux_withdraw_order_user_active", + "withdraw_order", + ["user_id"], + unique=True, + sqlite_where=sa.text("status IN ('reviewing', 'pending')"), + postgresql_where=sa.text("status IN ('reviewing', 'pending')"), + ) +``` + +- [ ] **Step 11: 验证迁移 upgrade + 回环 downgrade/upgrade** + +Run: `alembic upgrade head` +Expected: 输出应用 `drop_withdraw_active_unique_index`,无报错。 + +Run: `alembic downgrade -1 && alembic upgrade head` +Expected: downgrade 重建索引、upgrade 再次删除,均成功(dev 库每用户在途单 ≤1,不会触发唯一冲突)。 + +- [ ] **Step 12: 全量测试 + Lint** + +Run: `pytest -q` +Expected: 全绿(既有 `test_withdraw_idempotent_same_bill_no`、`tests/test_withdraw_tiers.py`、`tests/test_invite_cash_withdraw.py` 均不受影响)。 + +Run: `ruff check .` +Expected: 无新增告警(死常量/异常已连同引用一并删除)。 + +- [ ] **Step 13: 提交** + +```bash +git add tests/test_withdraw.py app/repositories/wallet.py app/api/v1/wallet.py app/models/wallet.py alembic/versions/drop_withdraw_active_unique_index.py +git commit -m "feat(withdraw): 允许在途提现时继续提交新申请 + +取消「同一用户同时仅一笔在途提现」限制:删应用层在途单检查 + +删 DB 分区唯一索引 ux_withdraw_order_user_active + 清理死代码 +(_WITHDRAW_ACTIVE_STATUSES / WithdrawTooFrequentError)。 +先扣款、coin_cash 每日档位次数、out_bill_no 幂等等既有约束不变。 + +Co-Authored-By: Claude Opus 4.8 " +``` + +--- + +## 自审(spec 覆盖核对) + +- **R1 已有 reviewing/pending 可再提** → Step 3/4(应用层)+ Step 8/10(模型 + 迁移);`test_withdraw_multiple_in_flight_allowed` 证明。✓ +- **R2 不加硬上限** → 无新增限制;`coin_cash` 天然封顶由既有档位次数(`tests/test_withdraw_tiers.py`)保障,不改。✓ +- **R3 幂等/限额/退款/对账不回退** → `test_withdraw_idempotent_same_bill_no` 与档位/邀请现金测试留绿(Step 12);解绑退款、对账按单号维度,未触碰。✓ +- **spec §4 四处改动** → Step 3/4/5/6(repo)、Step 7(api)、Step 8(model)、Step 10(迁移)一一对应。✓ +- **spec §6 客户端注意点** → 属跨仓 App 事项,文档已记,本计划无对应代码任务(有意为之)。✓ +- **占位符扫描**:迁移 `revision` / `down_revision`(`d8dd2106e438`)均为具体值,无 TBD。✓ +- **命名一致性**:`WithdrawTooFrequentError`/`_WITHDRAW_ACTIVE_STATUSES` 的删除点与引用点全覆盖(全仓仅这 4 处);`ux_withdraw_order_user_active` 在模型/迁移中拼写一致。✓ diff --git a/docs/superpowers/specs/2026-07-24-withdraw-allow-concurrent-design.md b/docs/superpowers/specs/2026-07-24-withdraw-allow-concurrent-design.md new file mode 100644 index 0000000..737bd3e --- /dev/null +++ b/docs/superpowers/specs/2026-07-24-withdraw-allow-concurrent-design.md @@ -0,0 +1,119 @@ +# 允许在途提现时继续提交新的提现申请 设计 + +- **日期**:2026-07-24 +- **状态**:Draft — 待评审 +- **所属**:app-server(`app/`),含一处 Alembic 迁移;另有一条 Android/客户端注意点(非本次后端工作) +- **一句话**:取消「同一用户同一时刻只能有一笔在途提现」的限制 —— 已有 `reviewing`(待审核)或 `pending`(打款在途)提现单时,允许再次发起新的提现申请。 + +--- + +## 1. 背景与目标 + +现状:用户发起提现后,在管理员审核通过并打款完成之前(`reviewing` / `pending`),**无法再发起第二笔提现**,会收到 409「已有提现申请正在审核或打款中,请处理完成后再申请」。人工审核有延迟时,用户被卡住、体验差。 + +**目标**:放开该限制,已有在途提现单时仍可继续提交新的提现申请。 + +### 非目标(本期不做) + +- 不改「先扣款」模型(提现建单即原子扣现金,天然防超提)。 +- 不改 `coin_cash` 的每日档位次数限制(仍是独立的限额闸)。 +- 不加任何新的并发/次数硬上限(见 §3 决策)。 +- 不改 admin 审核/打款/对账逻辑(其全部按单号维度操作,天然支持一人多单)。 + +--- + +## 2. 需求 + +| # | 需求 | 落地 | +|---|---|---| +| R1 | 已有 `reviewing` 或 `pending` 单时可再次发起提现 | 删除应用层在途单互斥检查 + 删除 DB 分区唯一索引(§4) | +| R2 | 不引入新的并发上限 | 仅靠既有约束:先扣款余额 + `coin_cash` 每日档位次数(§5) | +| R3 | 既有幂等/限额/退款/对账行为不回退 | 保留 `out_bill_no` 幂等、档位闸、解绑退款、对账(§5) | + +--- + +## 3. 决策记录(来自评审问答) + +| 决策点 | 结论 | 理由 | +|---|---|---| +| **放行范围** | `reviewing` 与 `pending` **两种在途状态都放行**,彻底取消「同时仅一单」 | 需求即"存在在途提现时可继续提交";人工审核延迟不应卡住用户 | +| **并发上限** | **不加硬上限** | 现金**先扣款**→每笔各需自己的余额,不会超提;`coin_cash` 每日档位次数已是天然上限;`invite_cash` 仅受余额约束,可接受 | +| **实现方式** | **彻底移除**(删检查 + 删索引 + 清理死代码),非配置开关 | 决策明确且无回滚诉求,YAGNI;避免留半死代码与多余配置项 | +| **已失效异常/文案** | 删除 `WithdrawTooFrequentError` 及端点的 409 处理 | 全仓仅这 4 处引用(§4),移除后无残留 | + +### 已知取舍(可接受) + +- **多笔 `pending` × 未开免确认**:每笔 `pending` 会各自返回一个微信确认页 `package_info`。用户若**未开启免确认**,可能同时存在多笔待确认。属客户端交互问题(§6),后端行为正确;开启免确认后直接到账、无此问题。 +- **回滚风险**:迁移 `downgrade` 会重建分区唯一索引;若届时某用户已有 ≥2 张在途单,重建会失败 —— 属预期的回滚代价,在迁移里注释说明。 + +--- + +## 4. 现状机制与改动点 + +「同一时刻仅一笔在途提现」由**两道闸**共同强制,均以 `status IN ('reviewing','pending')` 为口径: + +1. **应用层** — [`app/repositories/wallet.py:758-765`](../../../app/repositories/wallet.py) `create_withdraw` 内:查在途单 → `raise WithdrawTooFrequentError` → 端点转 409。 +2. **数据库层** — [`app/models/wallet.py:99-107`](../../../app/models/wallet.py) 的**分区唯一索引** `ux_withdraw_order_user_active`(`user_id WHERE status IN ('reviewing','pending')`)。这是硬约束,`create_withdraw` 的 `IntegrityError` 兜底([`:814-833`](../../../app/repositories/wallet.py))即捕获它。 + +> 提现单状态机:`reviewing`(待审核,建单即扣现金)→`pending`(审核通过、打款在途)→`success`/`failed`;或 `reviewing`→`rejected`(已退款)。 + +### 改动清单(4 处代码 + 1 个迁移) + +**① `app/repositories/wallet.py` · `create_withdraw`** +- 删除在途单互斥检查([`:758-765`](../../../app/repositories/wallet.py)):`select WithdrawOrder.id WHERE status IN (_WITHDRAW_ACTIVE_STATUSES)` → `raise WithdrawTooFrequentError`。 +- `IntegrityError` 兜底([`:814-833`](../../../app/repositories/wallet.py)):**保留** `out_bill_no` 幂等重试分支([`:816-824`](../../../app/repositories/wallet.py));**删除**其中的在途单二次检查分支([`:825-832`](../../../app/repositories/wallet.py))(索引移除后不会再因在途单触发 `IntegrityError`);末尾其余情况原样 `raise`(仅剩 `out_bill_no` 唯一冲突等,正常不该出现)。 +- 删除模块常量 `_WITHDRAW_ACTIVE_STATUSES`([`:38`](../../../app/repositories/wallet.py))与异常类 `WithdrawTooFrequentError`([`:72-73`](../../../app/repositories/wallet.py))。`_NEWBIE_TIER_HELD_STATUSES`(档位资格判定,含 `success`)与本改动无关,**保留**。 + +**② `app/models/wallet.py` · `WithdrawOrder`** +- 删除 `__table_args__` 中的分区唯一索引 `ux_withdraw_order_user_active`([`:99-107`](../../../app/models/wallet.py))。该表 `__table_args__` 仅此一项,整块移除。 + +**③ `app/api/v1/wallet.py` · `withdraw` 端点** +- 删除 `except crud_wallet.WithdrawTooFrequentError`([`:225-229`](../../../app/api/v1/wallet.py))这段已失效的 409 处理。 + +**④ 新增 Alembic 迁移** `alembic/versions/<...>_drop_withdraw_active_unique_index.py` +- `down_revision` = 当前 head(实现时确定)。 +- `upgrade`:`op.drop_index("ux_withdraw_order_user_active", table_name="withdraw_order")`。 +- `downgrade`:`op.create_index("ux_withdraw_order_user_active", "withdraw_order", ["user_id"], unique=True, sqlite_where=text("status IN ('reviewing','pending')"), postgresql_where=text("status IN ('reviewing','pending')"))`,并注释"若已有用户存在多张在途单则重建失败,属预期回滚代价"。 +- 索引的 drop/create 为具名操作,SQLite/PG 均无需 `render_as_batch` 重建表。 + +--- + +## 5. 天然保持不变(无需改动)的约束 + +| 约束 | 为何仍成立 | +|---|---| +| **不会超提** | 建单即原子扣现金(`_try_deduct_cash`,余额不足影响 0 行 → `InsufficientCashError`);每笔并行单各需自己的余额 | +| **`coin_cash` 每日档位次数** | `withdraw_tier_states` 的档位闸独立于在途单检查:常规档按**当天发起即计入(任意状态,含被拒/失败,按 `created_at` 北京日)**、每档每日限次(0.5×3 / 10×1 / 20×1)且当天只选一档;新人档(0.1/0.3)按 `reviewing/pending/success` 一次性占用。故即便并行,`coin_cash` 单日在途仍被档位天然封顶(至多 3 笔 0.5) | +| **`out_bill_no` 幂等** | 幂等分支在被删检查之前,同号重试仍原样返回旧单、不重复扣款 | +| **解绑退款** | `refund_reviewing_withdraws_on_unbind` 已 `for` 遍历该用户**所有** `reviewing` 单,天然支持多单 | +| **admin 审核 / 打款 / 对账** | `approve_withdraw`/`reject_withdraw`/`refresh_withdraw_status`/对账全按 `out_bill_no` 单号维度,不假设一人一单 | + +--- + +## 6. 客户端/App 团队注意点(跨仓,非本次后端工作) + +> - 允许多笔并行后,每次提交都要生成**新的 `out_bill_no`**(复用旧号会命中幂等、返回旧单)。 +> - 用户**未开启免确认**时,多笔 `pending` 会各自返回一个微信确认页 `package_info`,App 需能处理/串行多笔待确认。开启免确认后直接到账、无此问题。 + +--- + +## 7. 测试计划(`tests/test_withdraw.py`,沿用现有 helper) + +- **新增 · 多笔在途放行**:同一用户 seed ≥1 元现金,用**两个不同 `out_bill_no`** 各提 0.5 元(在 0.5 元档 3 次/天限额内)→ 两次均 200 且 `status=reviewing`;`/withdraw-orders` 返回 2 条;余额正确扣两次(1 元 → 0)。 +- **新增 · 第二笔余额不足**:seed 0.5 元,连提两笔 0.5 元 → 第一笔 200、第二笔 409(`InsufficientCashError`),验证每笔各需自己的余额。 +- **回归 · 幂等**:`test_withdraw_idempotent_same_bill_no`(同 `out_bill_no` → 同一单、只扣一次)仍绿。 +- **回归 · 档位限额**:`tests/test_withdraw_tiers.py`(0.5 元日 3 次、第 4 次 409;跨档互斥)不受影响仍绿。 +- 沿用 `tests/conftest.py`(临时 SQLite、`RATE_LIMIT_ENABLED=false`);wxpay 网络调用全部 monkeypatch。 + +--- + +## 附:涉及文件清单 + +**改动** +- `app/repositories/wallet.py` — 删在途单检查 + `IntegrityError` 兜底瘦身 + 删 `_WITHDRAW_ACTIVE_STATUSES` / `WithdrawTooFrequentError` +- `app/models/wallet.py` — 删分区唯一索引 `ux_withdraw_order_user_active` +- `app/api/v1/wallet.py` — 删 `WithdrawTooFrequentError` 的 409 处理 +- `tests/test_withdraw.py` — 新增多笔在途放行 / 第二笔余额不足用例 + +**新增** +- `alembic/versions/<...>_drop_withdraw_active_unique_index.py` — drop 分区唯一索引(downgrade 重建) diff --git a/tests/test_invite_cash_withdraw.py b/tests/test_invite_cash_withdraw.py index 5b83110..bfa5096 100644 --- a/tests/test_invite_cash_withdraw.py +++ b/tests/test_invite_cash_withdraw.py @@ -128,8 +128,7 @@ def test_invite_cash_reject_refunds_invite_account(client, monkeypatch) -> None: def test_two_accounts_withdraw_independent(client, monkeypatch) -> None: - """两账户各提各的不串:先提 invite_cash(拒绝结清),再提 cash,各扣各账户。 - 注:一个用户同一时间只能一个活跃提现单(跨账户),故第二笔需先结清第一笔。""" + """两账户各提各的不串:提 invite_cash(拒绝→验证退款回原账户),再提 cash,各扣各账户互不串。""" _patch_userinfo(monkeypatch, "openid_ic_3") token = _login(client, "13800004003") _seed_balances(client, token, "13800004003", cash=400, invite_cash=500) @@ -140,7 +139,7 @@ def test_two_accounts_withdraw_independent(client, monkeypatch) -> None: json={"amount_cents": 200, "source": "invite_cash"}, headers=_auth(token), ) - _reject(r1.json()["out_bill_no"]) # 退回 invite_cash + 结清活跃单 + _reject(r1.json()["out_bill_no"]) # 拒绝退回 invite_cash(验证退款回原账户) r2 = client.post( "/api/v1/wallet/withdraw", # 50 分 = 0.5 元档(7-9 起 coin_cash 只能提预设档位) @@ -154,6 +153,39 @@ def test_two_accounts_withdraw_independent(client, monkeypatch) -> None: assert cash == 350 # 扣了 cash 50 +def test_invite_cash_multiple_in_flight_allowed(client, monkeypatch) -> None: + """取消「同时仅一单」:invite_cash 无档位上限,已有在途时仍可继续提交,多笔并存各扣 invite_cash。""" + _patch_userinfo(monkeypatch, "openid_ic_multi") + token = _login(client, "13800004006") + _seed_balances(client, token, "13800004006", cash=0, invite_cash=500) + client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) + + r1 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 200, "source": "invite_cash", "out_bill_no": "billicflight0001"}, + headers=_auth(token), + ) + assert r1.status_code == 200, r1.text + assert r1.json()["status"] == "reviewing" + + r2 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 200, "source": "invite_cash", "out_bill_no": "billicflight0002"}, + headers=_auth(token), + ) + assert r2.status_code == 200, r2.text + assert r2.json()["status"] == "reviewing" + + # 两笔 invite_cash 在途并存,共扣 400(500→100),金币现金不动 + cash, invite_cash = _balances(client, token) + assert invite_cash == 100 and cash == 0 + orders = client.get( + "/api/v1/wallet/withdraw-orders", params={"source": "invite_cash"}, headers=_auth(token) + ).json()["items"] + reviewing = [o for o in orders if o["status"] == "reviewing"] + assert len(reviewing) == 2 + + def test_invite_me_returns_reward_stats(client) -> None: """/invite/me 返回 reward_balance_cents(可提现奖励金)。""" token = _login(client, "13800004004") @@ -170,12 +202,11 @@ def test_withdraw_orders_source_filter(client, monkeypatch) -> None: _seed_balances(client, token, "13800004005", cash=400, invite_cash=500) client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) - r1 = client.post( + client.post( "/api/v1/wallet/withdraw", json={"amount_cents": 200, "source": "invite_cash"}, headers=_auth(token), ) - _reject(r1.json()["out_bill_no"]) # 结清,才能提第二笔 client.post( "/api/v1/wallet/withdraw", # 50 分 = 0.5 元档(7-9 起 coin_cash 只能提预设档位) diff --git a/tests/test_withdraw.py b/tests/test_withdraw.py index ac395a4..88a0eb9 100644 --- a/tests/test_withdraw.py +++ b/tests/test_withdraw.py @@ -268,6 +268,61 @@ def test_withdraw_idempotent_same_bill_no(client, monkeypatch) -> None: assert sum(1 for t in r.json()["items"] if t["biz_type"] == "withdraw") == 1 +def test_withdraw_multiple_in_flight_allowed(client, monkeypatch) -> None: + """取消「同时仅一单」:已有在途(reviewing)时,不同 out_bill_no 可继续提交,两单并存。""" + _patch_userinfo(monkeypatch, "openid_multi_inflight") + token = _login(client, "13800002020") + _seed_cash(client, token, "13800002020", 100) # 够两笔 0.5 + client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) + + r1 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billmulti00000001"}, + headers=_auth(token), + ) + assert r1.status_code == 200, r1.text + assert r1.json()["status"] == "reviewing" + + r2 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billmulti00000002"}, + headers=_auth(token), + ) + assert r2.status_code == 200, r2.text + assert r2.json()["status"] == "reviewing" + + # 两张在途单并存 + r = client.get("/api/v1/wallet/withdraw-orders", headers=_auth(token)) + reviewing = [o for o in r.json()["items"] if o["status"] == "reviewing"] + assert len(reviewing) == 2, r.text + # 余额扣两次:100-50-50=0 + r = client.get("/api/v1/wallet/account", headers=_auth(token)) + assert r.json()["cash_balance_cents"] == 0 + + +def test_withdraw_second_blocked_only_by_insufficient_cash(client, monkeypatch) -> None: + """并行放开后第二笔仅受余额约束:余额不足返 409「现金余额不足」,而非旧的「已有提现」拦截。""" + _patch_userinfo(monkeypatch, "openid_multi_insuff") + token = _login(client, "13800002021") + _seed_cash(client, token, "13800002021", 50) # 仅够一笔 0.5 + client.post("/api/v1/wallet/bind-wechat", json={"code": "c"}, headers=_auth(token)) + + r1 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billinsuff0000001"}, + headers=_auth(token), + ) + assert r1.status_code == 200, r1.text + + r2 = client.post( + "/api/v1/wallet/withdraw", + json={"amount_cents": 50, "out_bill_no": "billinsuff0000002"}, + headers=_auth(token), + ) + assert r2.status_code == 409, r2.text + assert "现金余额不足" in r2.json()["detail"] + + def test_withdraw_ambiguous_timeout_then_success_no_refund(client, monkeypatch) -> None: """#3 转账调用超时(异常),但查单确认已 SUCCESS → 不退款,单置 success。""" monkeypatch.setattr("app.integrations.wxpay.code_to_userinfo", lambda code: {"openid": "openid_amb", "nickname": None, "avatar_url": None, "raw": {}})