Skip to content

fix: count invites when inviter reward is zero - #6363

Open
Sunshine-JamesHu wants to merge 1 commit into
QuantumNous:mainfrom
Sunshine-JamesHu:codex/fix-zero-rebate-invite-count
Open

Sunshine-JamesHu wants to merge 1 commit into
QuantumNous:mainfrom
Sunshine-JamesHu:codex/fix-zero-rebate-invite-count

Conversation

@Sunshine-JamesHu

@Sunshine-JamesHu Sunshine-JamesHu commented Jul 21, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

将邀请关系计数与邀请奖励发放解耦。有效邀请现在始终原子增加邀请人的 aff_count;只有奖励额度大于 0 时才增加 aff_quota 和 aff_history。密码注册与 OAuth 注册共用同一收尾逻辑,避免两个入口再次出现行为差异。

新增表驱动回归测试,覆盖邀请人奖励为 0、未确认支付合规时不发奖励,以及奖励正常发放三种场景。

AI-assisted disclosure: 本 PR 由 AI 辅助从本地开发分支提取、验证并整理提交;原始修复由 JamesHu 编写。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

go test ./model -run TestRegistrationTracksInvitesIndependentlyFromRewards -count=1
ok   github.com/QuantumNous/new-api/model

go test ./model -count=1
ok   github.com/QuantumNous/new-api/model

Summary by CodeRabbit

  • Bug Fixes
    • Invitation tracking now records successful invitations independently of reward configuration.
    • Reward quotas and invitation history are applied only when payment compliance requirements are met.
    • Password and OAuth registrations now follow consistent invitation and reward behavior.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Invitation finalization now records inviter counts independently of reward quota. Reward counters, invitee quota, and related logs remain conditional on payment compliance. New table-driven coverage validates password and OAuth registration paths.

Changes

Invitation tracking and rewards

Layer / File(s) Summary
Atomic invitation counter updates
model/user.go
recordUserInvite atomically increments invitation counts and conditionally updates reward quota and history counters, reporting missing inviters.
Registration invitation finalization
model/user.go, model/user_invite_test.go
finishInsert delegates invitation handling to finalizeInvitation, which separates counting from compliant rewards; tests cover password and OAuth registration scenarios.

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

Suggested reviewers: calcium-ion

Poem

I’m a rabbit with counters to tally,
Each invite now joins the rally.
Rewards may rest at zero,
But counts still grow—
While compliant quotas hop gladly!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the core fix: invite counts now increase when inviter reward is zero.
Linked Issues check ✅ Passed The changes match #6362 by decoupling invite counting from rewards and covering password and OAuth registration paths.
Out of Scope Changes check ✅ Passed The code changes and regression test stay within the invite-tracking bug fix scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
model/user_invite_test.go (1)

25-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add an OAuth case for compliance-confirmed + zero reward.

Case 1 covers password registration with complianceConfirmed: true and zero reward (the exact issue #6362 scenario). Case 2 covers OAuth but with complianceConfirmed left false, which exercises a different branch (early return before the reward block) than case 1. Since the PR objective states the bug affects both password and OAuth flows, consider adding a table entry with oauth: true, complianceConfirmed: true and zero inviterReward/inviteeReward to directly mirror the reported OAuth scenario.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/user_invite_test.go` around lines 25 - 52, Add a table entry in the
user invite tests covering OAuth registration with complianceConfirmed set to
true and both rewards left at zero. Keep the case distinct from the existing
OAuth non-compliance scenario so it exercises the same reward-processing branch
as the password compliance-confirmed case.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@model/user.go`:
- Around line 693-717: Update User.finalizeInvitation to stop the reward flow
immediately when recordUserInvite fails, rather than continuing to credit or log
rewards. Check and propagate the error from IncreaseUserQuota for the invitee,
and emit the “使用邀请码赠送” log only after that credit succeeds; retain the inviter
reward log only when recordUserInvite succeeded and the compliance conditions
apply.

---

Nitpick comments:
In `@model/user_invite_test.go`:
- Around line 25-52: Add a table entry in the user invite tests covering OAuth
registration with complianceConfirmed set to true and both rewards left at zero.
Keep the case distinct from the existing OAuth non-compliance scenario so it
exercises the same reward-processing branch as the password compliance-confirmed
case.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f4f724b4-a9ed-468a-9810-10dcc51e5507

📥 Commits

Reviewing files that changed from the base of the PR and between e0d5156 and e368aa0.

📒 Files selected for processing (2)
  • model/user.go
  • model/user_invite_test.go

Comment thread model/user.go
Comment on lines +693 to 717
func (user *User) finalizeInvitation(inviterId int) {
if inviterId == 0 {
return
}

rewardQuota := 0
complianceConfirmed := operation_setting.IsPaymentComplianceConfirmed()
if complianceConfirmed {
rewardQuota = common.QuotaForInviter
}
if err := recordUserInvite(inviterId, rewardQuota); err != nil {
common.SysError(fmt.Sprintf("failed to record invite for inviter %d: %v", inviterId, err))
}

if !complianceConfirmed {
return
}
if common.QuotaForInvitee > 0 {
_ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
}
if common.QuotaForInviter > 0 {
RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reward logs and invitee credit fire even when the inviter update fails.

If recordUserInvite fails (e.g. inviter not found), the error is only logged via SysError — execution continues to credit the invitee's quota and unconditionally records "邀请用户赠送" / "使用邀请码赠送" logs as if the reward transaction succeeded. Similarly, IncreaseUserQuota's error is discarded (_ =) and the "credited" log still fires regardless. This can leave an audit trail claiming a reward was granted when it wasn't, and the invitee could receive quota funded by a reward that never landed on the inviter's side.

🐛 Proposed fix to align logs with actual outcomes
 	if err := recordUserInvite(inviterId, rewardQuota); err != nil {
 		common.SysError(fmt.Sprintf("failed to record invite for inviter %d: %v", inviterId, err))
 	}
 
 	if !complianceConfirmed {
 		return
 	}
 	if common.QuotaForInvitee > 0 {
-		_ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
-		RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
+		if err := IncreaseUserQuota(user.Id, common.QuotaForInvitee, true); err != nil {
+			common.SysError(fmt.Sprintf("failed to increase invitee %d quota: %v", user.Id, err))
+		} else {
+			RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/user.go` around lines 693 - 717, Update User.finalizeInvitation to stop
the reward flow immediately when recordUserInvite fails, rather than continuing
to credit or log rewards. Check and propagate the error from IncreaseUserQuota
for the invitee, and emit the “使用邀请码赠送” log only after that credit succeeds;
retain the inviter reward log only when recordUserInvite succeeded and the
compliance conditions apply.

@Calcium-Ion
Calcium-Ion force-pushed the main branch 2 times, most recently from 51fdfc5 to 2b6f1df Compare August 30, 2026 15:03
shirosoralumie648 added a commit to shirosoralumie648/newapi-rev that referenced this pull request Oct 18, 2026
The one-time affiliate import backfills old relations with the legacy
source. Treat it as a recorded binding channel so the administrator
statistics accept it as a filter and the imported relations are counted,
and offer the matching filter option in the wallet frontend.

The transfer attempt test covers the per-attempt idempotency key and the
refused-transfer path of the affiliate hook.

Inspired-by: QuantumNous#6362
Inspired-by: QuantumNous#6363
Local tests not run (CI-only session).

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.

[Bug] 邀请人奖励为 0 时邀请人数未增加

1 participant