Skip to content

优化 Turnstile 位置到 继续 按钮上方,修复当 AFF 奖励为 0 时钱包界面不显示已邀请用户的问题 - #4197

Closed
Hoshino-Yumetsuki wants to merge 36 commits into
QuantumNous:mainfrom
Hoshino-Yumetsuki:main
Closed

Hoshino-Yumetsuki wants to merge 36 commits into
QuantumNous:mainfrom
Hoshino-Yumetsuki:main

Conversation

@Hoshino-Yumetsuki

@Hoshino-Yumetsuki Hoshino-Yumetsuki commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

Important

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

📝 变更描述 / Description

优化 Turnstile 位置到 继续 按钮上方,修复当 AFF 奖励为 0 时钱包界面不显示已邀请用户的问题

🚀 变更类型 / Type of change

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

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

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

📸 运行证明 / Proof of Work

image image

Summary by CodeRabbit

  • Bug Fixes

    • Invite/referral counts are reconciled against actual invite records and persisted; if persistence fails the displayed count still shows the reconciled value for the session.
  • Improvements

    • Inviter reward and referral stats updates are now applied more reliably when an inviter is present.
  • User Experience

    • CAPTCHA (Turnstile) is shown only for email-based sign-in/registration and inside the WeChat login modal.
  • Tests

    • Added automated tests for invite-count reconciliation, persistence, and fallback.

@coderabbitai

coderabbitai Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

GetSelf now reconciles aff_count via a count of invitees and attempts to persist differences; inviter reward logic was centralized and inviter stat updates made atomic; Turnstile CAPTCHA rendering moved into email-specific login/register and WeChat modal paths; tests added for aff_count reconciliation and persistence failure.

Changes

Cohort / File(s) Summary
User controller
controller/user.go
GetSelf fetches invitee count via GetInviteeCountByInviterId, returns the reconciled aff_count, and attempts to persist it with UpdateUserAffCount; logs on lookup/update errors.
User model & inviter flow
model/user.go
Added GetInviteeCountByInviterId, UpdateUserAffCount, and applyInviterRewards; replaced inline inviter logic in (*User).Insert and FinalizeOAuthUserCreation with applyInviterRewards; inviteUser now performs atomic DB increments and errors on inviterId==0.
Tests
controller/token_test.go
Added tests TestGetSelfReconcilesAndPersistsAffCount and TestGetSelfReturnsReconciledAffCountWhenPersistenceFails; test DB now AutoMigrates model.User and model.Token.
Auth UI (Turnstile placement)
web/src/components/auth/LoginForm.jsx, web/src/components/auth/RegisterForm.jsx
Moved Turnstile CAPTCHA into renderEmailLoginForm() / renderEmailRegisterForm() and into the WeChat modal render path; removed global/top-level CAPTCHA so it only appears for email flows or WeChat modal.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant Controller as UserController
  participant Model as UserModel
  participant DB as Database

  Client->>Controller: GET /api/user/self
  Controller->>Model: GetInviteeCountByInviterId(user.Id)
  Model->>DB: SELECT COUNT(*) FROM users WHERE inviter_id = ?
  DB-->>Model: invitee_count
  Model-->>Controller: invitee_count
  alt invitee_count != user.AffCount
    Controller->>Model: UpdateUserAffCount(user.Id, invitee_count)
    Model->>DB: UPDATE users SET aff_count = ? WHERE id = ?
    DB-->>Model: update result
  end
  Controller-->>Client: 200 { id, aff_count: invitee_count_or_stored }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I tallied friends beneath a lantern's light,

I nudged the counts to make the ledger right,
Captcha hops where emails take the stage,
Invites get counted, stored upon the page,
A happy rabbit hops — small fixes, bright ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title describes multiple unrelated changes: Turnstile CAPTCHA repositioning and aff_count display fix. While both are present in the changeset, the title conflates two distinct features without clear prioritization, making it difficult to understand the primary focus. Consider splitting into separate PRs for each feature, or revise the title to highlight the most critical change (e.g., focus on the aff_count reconciliation logic which has higher code review complexity).
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@controller/user.go`:
- Around line 384-388: The GetSelf handler should not abort when
model.GetInviteeCountByInviterId fails: instead of calling common.ApiError and
returning, catch the error, log it (so failure is visible), set
reconciledAffCount = user.AffCount as a fallback, and proceed to build the
response; update the block around GetInviteeCountByInviterId/reconciledAffCount
in the GetSelf flow to remove the return on error and replace it with logging
plus the fallback to user.AffCount.

In `@model/user.go`:
- Around line 435-439: The inviteUser call is ignoring errors so inviter
side-effects (aff_count/quota) can be silently lost; change the call sites that
call inviteUser (and the similar block that deals with
IncreaseUserQuota/RecordLog) to capture the returned error, handle it (either
return it up the call stack or at minimum log it for visibility) and only
proceed with RecordLog/IncreaseUserQuota when there is no error; specifically
update the inviteUser(...) invocation to check `err := inviteUser(inviterId)`
and on err call a logging helper (or RecordLog with an error log type and the
error message) or propagate the error, and likewise un-comment and call
IncreaseUserQuota(inviterId, common.QuotaForInviter) capturing its error and
handling/logging it before recording the success RecordLog.

In `@web/src/components/auth/LoginForm.jsx`:
- Around line 805-814: The Turnstile widget was only rendered in the email login
UI so the WeChat/OAuth flow never presents a token, causing the turnstile_check
to block WeChat login; add the same conditional Turnstile block (guarded by
turnstileEnabled) into the WeChat modal component/UI and wire it to the same
setTurnstileToken/turnstileToken state used by the submit routine (and ensure
the WeChat submit handler uses the same token validation logic as the email
path), so users in the WeChat modal can complete the Turnstile challenge and
submit successfully.

In `@web/src/components/auth/RegisterForm.jsx`:
- Around line 678-687: The WeChat flow is being blocked because
onSubmitWeChatVerificationCode unconditionally requires turnstileToken even when
the Turnstile component isn't rendered for OAuth-first users; update
onSubmitWeChatVerificationCode so it only validates turnstileToken when
turnstileEnabled && turnstile_check are true AND the Turnstile is actually
rendered for the current flow (e.g. !isOAuthFirst or modal showing);
alternatively, render the Turnstile inside the WeChat modal above the “继续”
button and wire its setTurnstileToken into that modal so the token is set before
calling onSubmitWeChatVerificationCode. Ensure you reference and adjust the
Turnstile usage, setTurnstileToken, turnstileEnabled, turnstile_check, and
onSubmitWeChatVerificationCode so the check is conditional on the component
being present.
🪄 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: dc09afc4-0ba1-486f-bc07-f3c8386a3417

📥 Commits

Reviewing files that changed from the base of the PR and between ed7f839 and 971de5a.

📒 Files selected for processing (4)
  • controller/user.go
  • model/user.go
  • web/src/components/auth/LoginForm.jsx
  • web/src/components/auth/RegisterForm.jsx

Comment thread controller/user.go Resolved
Comment thread model/user.go Resolved
Comment thread web/src/components/auth/LoginForm.jsx Resolved

@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)
controller/token_test.go (1)

282-354: Add a regression test for the zero-reward signup path.

This test proves GetSelf can repair a stale aff_count, but it bypasses the creation flow that broke when common.QuotaForInviter == 0. A focused test around User.Insert/FinalizeOAuthUserCreation with inviter rewards disabled would catch the original regression instead of only the read-time fallback.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/token_test.go` around lines 282 - 354, The PR adds a test that
exercises GetSelf's reconciling of aff_count but misses the zero-reward signup
regression; add a focused test that simulates user creation/insert and
finalization when common.QuotaForInviter == 0 to ensure inviter rewards codepath
doesn't fail — specifically, write a test that calls User.Insert (or the
higher-level FinalizeOAuthUserCreation) with common.QuotaForInviter set to 0,
creating an inviter and a new invitee, then assert that the invitee creation
completes without error and inviter.AffCount remains stable (or is handled
correctly) and no panic/DB error occurs; use the same DB test harness as the
existing tests and reference the User.Insert and FinalizeOAuthUserCreation
functions and the common.QuotaForInviter constant to locate the relevant code to
exercise.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@model/user.go`:
- Around line 445-446: Two duplicate calls to inviteUser(inviterId) are causing
AffCount, AffQuota and AffHistoryQuota to be incremented twice; remove the
redundant inviteUser(inviterId) so each registration path calls inviteUser
exactly once. Locate the duplicated invocations of inviteUser (the two
consecutive _ = inviteUser(inviterId) occurrences) and delete the extra call in
both places where they appear, leaving a single call per registration flow;
after the change, run or add a quick test to confirm
AffCount/AffQuota/AffHistoryQuota are only incremented once per invite.

---

Nitpick comments:
In `@controller/token_test.go`:
- Around line 282-354: The PR adds a test that exercises GetSelf's reconciling
of aff_count but misses the zero-reward signup regression; add a focused test
that simulates user creation/insert and finalization when common.QuotaForInviter
== 0 to ensure inviter rewards codepath doesn't fail — specifically, write a
test that calls User.Insert (or the higher-level FinalizeOAuthUserCreation) with
common.QuotaForInviter set to 0, creating an inviter and a new invitee, then
assert that the invitee creation completes without error and inviter.AffCount
remains stable (or is handled correctly) and no panic/DB error occurs; use the
same DB test harness as the existing tests and reference the User.Insert and
FinalizeOAuthUserCreation functions and the common.QuotaForInviter constant to
locate the relevant code to exercise.
🪄 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: b67362ec-34af-4345-80cb-388891bc04a2

📥 Commits

Reviewing files that changed from the base of the PR and between 971de5a and 5f3e3c2.

📒 Files selected for processing (5)
  • controller/token_test.go
  • controller/user.go
  • model/user.go
  • web/src/components/auth/LoginForm.jsx
  • web/src/components/auth/RegisterForm.jsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • web/src/components/auth/LoginForm.jsx
  • web/src/components/auth/RegisterForm.jsx
  • controller/user.go

Comment thread model/user.go Resolved
@Hoshino-Yumetsuki
Hoshino-Yumetsuki marked this pull request as ready for review April 11, 2026 19:22

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@controller/user.go`:
- Around line 390-393: The code resets affCount to user.AffCount when
model.UpdateUserAffCount fails, causing the response to expose stale DB data;
instead preserve the freshly computed reconciledAffCount in the response. In the
error branch after model.UpdateUserAffCount(user.Id, reconciledAffCount) fails
(referencing reconciledAffCount, user.AffCount, affCount, and
model.UpdateUserAffCount), remove the assignment that sets affCount =
user.AffCount and ensure affCount remains reconciledAffCount (or explicitly set
affCount = reconciledAffCount) while still logging the error with
common.SysError.

In `@model/user.go`:
- Around line 361-366: The applyInviterRewards flow currently calls inviteUser
which reads a full User row, mutates AffCount/AffQuota/AffHistoryQuota in memory
and saves it back, causing lost increments and potential overwrites; change
inviteUser (or replace its call site in applyInviterRewards) to perform atomic
column increments via GORM column expressions (e.g., DB.Model(&User{}).Where("id
= ?", inviterId).UpdateColumn/Updates with gorm.Expr to increment AffCount,
AffQuota, AffHistoryQuota) so updates are done with SQL increments and do not
overwrite other concurrent field changes.
🪄 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: 120c6802-57a5-4291-9bed-8dccd9c373e3

📥 Commits

Reviewing files that changed from the base of the PR and between 0e67290 and 623161f.

📒 Files selected for processing (5)
  • controller/token_test.go
  • controller/user.go
  • model/user.go
  • web/src/components/auth/LoginForm.jsx
  • web/src/components/auth/RegisterForm.jsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/components/auth/RegisterForm.jsx
  • web/src/components/auth/LoginForm.jsx

Comment thread controller/user.go Resolved
Comment thread model/user.go Resolved

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@model/user.go`:
- Around line 338-341: The Updates call incorrectly updates "aff_history_quota"
instead of the actual DB column "aff_history", causing failures; in the
Updates(map[string]interface{}{ ... }) where aff_count, aff_quota and
aff_history_quota are set (using gorm.Expr and common.QuotaForInviter), change
the key/value for aff_history to use the real column name and expression: use
"aff_history": gorm.Expr("aff_history + ?", common.QuotaForInviter) (ensuring
this matches the struct tag for User.AffHistoryQuota) so inviter stats increment
correctly.
🪄 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: 761eb724-b017-4a10-9495-54b34cf4403a

📥 Commits

Reviewing files that changed from the base of the PR and between 623161f and b106137.

📒 Files selected for processing (3)
  • controller/token_test.go
  • controller/user.go
  • model/user.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • controller/token_test.go

Comment thread model/user.go Resolved

@6639835 6639835 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Great! Should add some comments in code sniffs.

@Hoshino-Yumetsuki

Copy link
Copy Markdown
Contributor Author

Great! Should add some comments in code sniffs.

thanks for the approval. just to clearify, what the 'code sniffs' do you mean?

Hoshino-Yumetsuki and others added 7 commits May 25, 2026 05:27
…ta cache

- Add payment commission system: inviters earn a percentage or fixed quota
  amount when their invitees make a payment (all providers supported)
- Add admin UI (both default and classic themes) to configure commission:
  enable/disable toggle, percentage or fixed type, rate/amount inputs
- Fix aff_count not incrementing when compliance is not confirmed: split
  count tracking from quota reward; count is now always recorded on
  registration regardless of compliance status
- Fix TransferAffQuotaToQuota not updating Redis quota cache after commit;
  now calls cacheIncrUserQuota in a goroutine post-commit
shirosoralumie648 added a commit to shirosoralumie648/newapi-rev that referenced this pull request Oct 18, 2026
…tistics

Complete the RF-07 invitation statistics panel so the administrator
summary, list filters and CSV export cover every recorded commission
state. The inviter view keeps exposing only the payable pipeline.

- model: the per-invitation aggregates and the filter-aware summary
  bucket the refused events (review, blocked, rejected) alongside
  pending/locked/settled, so the buckets add up to the recorded total;
  the commission-status validation accepts all six recorded states.
- controller: the administrator item embeds the admin-only refused
  fields while the self item stays payable-only and masked; the CSV
  export gains review_quota, blocked_quota and rejected_quota (17
  columns); the endpoints stay read-only and never move a balance.
- web: label and filter the refused states, show all six buckets in the
  admin dialog summary, keep the commission total across all six states,
  register the dynamic label keys, and cover the admin dialog with
  regression tests (summary, refused row, keyword filter, CSV export,
  disabled export on the empty state).
- i18n: 28 new keys in all seven locales. `node
  scripts/add-missing-keys.mjs` could not be executed in this sandbox,
  so the keys were inserted at their ICU-sorted anchors and normalized
  with `node scripts/sync-i18n.mjs`, which reports missingCount=0 and
  extrasCount=0.

Tests: TestReferralInvitationStats seeds refused events and asserts the
six buckets, their sum against the recorded total and the blocked
filter; TestReferralInvitationQueryValidation accepts all six states;
TestReferralInvitationStatisticsEndpoints covers masking, cross-inviter
isolation, the admin-only refused fields, filter errors, the 17-column
CSV and an unchanged balance.

Inspired-by: QuantumNous#6364
Inspired-by: QuantumNous#4197
Local tests not run (CI-only session).
shirosoralumie648 added a commit to shirosoralumie648/newapi-rev that referenced this pull request Oct 18, 2026
Add the RF-07 progress paragraph after RF-03 in section 12.4 and the
matching section 8 change-log row: the read-only user-side invitee
details (masked identifier, bound time, paid amount, commission states
and validity window), the administrator summary with keyword, source and
status filters plus the 17-column CSV export, the admin-only refused
commission states (review/blocked/rejected), the aff=0 invitee-access
fix (QuantumNous#4197), the 28 new keys across seven locales, and the tests covered
by the CI jobs.

Local tests not run (CI-only session).
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.

2 participants