Skip to content

fix(topup): unify credited quota calculation and stop scaling Creem amount - #8513

Open
seefs001 wants to merge 1 commit into
mainfrom
fix/creem-manual-topup-quota
Open

seefs001 wants to merge 1 commit into
mainfrom
fix/creem-manual-topup-quota

Conversation

@seefs001

@seefs001 seefs001 commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 关联任务 / Related Issue

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

📝 变更描述 / Description

修复管理员补单 ManualCompleteTopUp 对 Creem 订单重复乘以 common.QuotaPerUnit 导致入账额度放大 500,000 倍的问题:

  • model/topup.go:将所有充值渠道的应入账额度换算收敛到 (*TopUp).creditedQuota() (int, error),由 ManualCompleteTopUp 与 5 个 Recharge* 回调共用,统一经 common.WalletQuotaFromDecimalStrict 转换并校验 > 0。
    • creem 直接使用 Amount(下单时已存最终额度);stripe 使用 Money * quotaPerUnit;epay / waffo / waffo_pancake 使用 Amount * quotaPerUnit。
    • 历史 PaymentProvider == "" 订单仅在 TradeNo 以 ref_ 开头时按 PaymentMethod 区分 Creem/Stripe;ref_ 且 PaymentMethod 也为空的歧义旧单拒绝自动换算(返回 ErrInvalidTopUpQuota 并保持 pending);非 ref_ 的历史 Epay(USR...)即便带有自定义 stripe/creem method 仍保持 Amount * quotaPerUnit。
    • 在调用 decimal.NewFromFloat 前校验局部变量 quotaPerUnit 与 Money 为有限正数,避免 NaN/Inf panic 或负负得正。

📸 运行证明 / Proof of Work

在 model/payment_method_guard_test.go 新增 TestManualCompleteTopUpCreditsProviderQuota(16 组用例)、TestTopUpCreditedQuotaRejectsNonFiniteStripeMoney 与 TestRechargeCreemAndManualCompletionCreditSameQuota,覆盖 Creem 补单与回调一致(500000 仅入账 500000)、Stripe/Epay/Waffo 正常换算、历史 ref_ 歧义单拒绝、USR... Epay 冲突兼容、超上限与非有限/负数拦截。

gofmt -l model/topup.go model/payment_method_guard_test.go
# 无输出,exit 0

go vet ./model
# 无输出,exit 0

go test -count=1 ./model -run 'TopUp|Payment|Creem'
# ok github.com/QuantumNous/new-api/model 0.557s

go test -count=1 ./controller -run 'TopUp|Topup|Creem'
# ok github.com/QuantumNous/new-api/controller 1.128s

注:本次未修改表结构、SQL 或行锁,仅在默认 SQLite 测试库运行单测,未在 MySQL/PostgreSQL 实例上重跑。

✅ 提交前检查项 / Checklist

  • 人工确认: 无论描述是否由 AI 生成,我已审阅并精炼全文,仅保留可复核的要点,并声明对其准确性与完整性负责。PR 正文及后续评论均未直接粘贴未经人工过滤的大段 AI 文本。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交(旧 PR fix(creem): fix manual refill and billing log for Creem orders(#4179) #4708 严重冲突且不符合当前计费转换规范)。
  • 新功能关联 Issue: 本 PR 为 Bug 修复。
  • 事前沟通: 本 PR 为聚焦的高危计费 Bug 修复。
  • 功能范围: 本 PR 不是 Coding Plan、逆向渠道、第三方封装接口,也不是对 Codex 渠道类型的改动。
  • 非透传: 本 PR 不是针对开启透传后的转发行为;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 范围聚焦: 本 PR 为一项聚焦改动,未包含无关代码。
  • 本地验证: 已按变更路径实际验证,并写明命令与观察结果。仅声明 go build 通过或测试通过,不视为有效证明。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

Summary by CodeRabbit

  • Bug Fixes
    • Improved top-up quota calculations across supported payment methods, including older payment records.
    • Invalid or ambiguous payment details, including non-finite Stripe amounts, are now rejected without changing the credited quota or order status.
    • Creem callback and manual top-up completion now credit consistent quota amounts.

…mount

Consolidate top-up quota calculation into (*TopUp).creditedQuota() shared by ManualCompleteTopUp and provider callbacks so Creem orders credit raw Amount without multiplying by QuotaPerUnit again, fail closed on ambiguous legacy ref_ orders, preserve legacy USR epay semantics, and reject non-finite or non-positive inputs before decimal conversion.

Closes #8489
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Top-up quota conversion now uses a shared helper across provider settlement paths and manual completion. The helper validates provider-specific inputs and converted quota values. Tests cover legacy provider inference, invalid inputs, unchanged state on failures, and matching Creem callback and manual credits.

Changes

Top-up quota handling

Layer / File(s) Summary
Shared quota calculation and validation
model/topup.go, model/payment_method_guard_test.go
TopUp.creditedQuota applies provider-specific conversion rules, infers Stripe or Creem only for eligible legacy references, and rejects invalid values. Tests cover non-finite Stripe money.
Settlement integration and coverage
model/topup.go, model/payment_method_guard_test.go
Epay, Stripe, manual completion, Creem, Waffo, and Waffo Pancake use the shared helper. Tests cover legacy records, invalid inputs, unchanged quota and order status on failures, and Creem callback and manual credit parity.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: High

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 026e5

This change stops admin manual completion from multiplying Creem top-up amounts by the quota-per-unit a second time. It also applies one validated conversion across all provider settlement paths. No concrete merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the two main changes: unifying the credited quota calculation across top-up settlement paths, and stopping the extra QuotaPerUnit scaling of Creem amounts. The raw summary and objectiv…
Linked Issues check Passed [#8489] The issue reports that admin manual completion (ManualCompleteTopUp) credits Creem orders at Amount * QuotaPerUnit, although Creem Amount is already quota. The diff to model/topup.go r…
Out of Scope Changes check Passed The diff stays within the Creem manual-completion defect. The shared creditedQuota() helper replaces the inline conversion blocks in ManualCompleteTopUp, RechargeEpay, Recharge, `RechargeCreem…
Full details: Title check

Explanation

The title names the two main changes: unifying the credited quota calculation across top-up settlement paths, and stopping the extra QuotaPerUnit scaling of Creem amounts. The raw summary and objectives both describe this centralized creditedQuota helper and the Creem fix (issue #8489), so the title matches the changeset.

Full details: Linked Issues check

Explanation

[#8489] The issue reports that admin manual completion (ManualCompleteTopUp) credits Creem orders at Amount * QuotaPerUnit, although Creem Amount is already quota. The diff to model/topup.go replaces the manual-completion conversion with (*TopUp).creditedQuota(). For PaymentProviderCreem, that helper uses decimal.NewFromInt(topUp.Amount) with no QuotaPerUnit multiplication, so a 500000-quota Creem order is credited 500000. The same helper is used by RechargeCreem, so manual completion and the Creem callback now use one conversion. Stripe, Epay, Waffo, and Waffo Pancake keep their previous multiplication formulas. Legacy ref_ handling and non-finite or non-positive input checks are additional hardening tied to the shared conversion path. The test file adds coverage for Creem manual completion and callback parity. Test results were reported by the author on the default SQLite database only. I did not rerun them, and MySQL and PostgreSQL were not tested.

Full details: Out of Scope Changes check

Explanation

The diff stays within the Creem manual-completion defect. The shared creditedQuota() helper replaces the inline conversion blocks in ManualCompleteTopUp, RechargeEpay, Recharge, RechargeCreem, RechargeWaffo, and RechargeWaffoPancake. This consolidation is the mechanism the PR uses to align manual completion with callbacks. The conversion formulas for non-Creem providers match the previous code, apart from the added positive and finite checks. The new legacy ref_ rule and the PaymentMethod gate affect only orders whose PaymentProvider is empty. The test file supports the changed behavior. No schema, SQL, or unrelated module changes appear in the reviewed diff.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the quota right,
Each provider’s sum comes out just right.
No NaN can pass the gate,
Failed orders keep their state.
Creem’s credit lands in measured light.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 36293133-7adf-4df0-9bf2-3dfed817da32
Commits

Reviewing files that changed from the base of the PR and between 04dfcbb and 026e508.

Files selected for processing: 2

  • model/payment_method_guard_test.go
  • model/topup.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

管理员补单 Creem 订单,额度被多乘 QuotaPerUnit

1 participant