Repository navigation
feat: 自定义充值方式 - #1257
feat: 自定义充值方式#1257
Conversation
WalkthroughThis change introduces a configurable payment methods system across backend and frontend. The backend adds a global Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant SystemSettingUI
participant BackendAPI
participant OptionMap
participant PaymentSetting
User->>SystemSettingUI: Edits PayMethods JSON
SystemSettingUI->>BackendAPI: Submits updated PayMethods
BackendAPI->>OptionMap: updateOptionMap("PayMethods", value)
OptionMap->>PaymentSetting: UpdatePayMethodsByJsonString(value)
PaymentSetting-->>OptionMap: PayMethods updated
BackendAPI-->>SystemSettingUI: Responds with status including pay_methods
SystemSettingUI-->>User: Shows updated payment methods
sequenceDiagram
participant User
participant TopUpUI
participant LocalStorage
TopUpUI->>LocalStorage: Reads 'pay_methods' JSON
LocalStorage-->>TopUpUI: Returns payment methods array
TopUpUI-->>User: Displays dynamic payment buttons
User->>TopUpUI: Selects payment method
TopUpUI-->>User: Shows confirmation modal with selected method
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
model/option.go (1)
82-82: Initial option value will desync once struct refactor landsStoring the raw JSON string is fine, but when
PayMethodbecomes a struct (see earlier comment), remember to call the newPayMethods2JsonString()here to avoid stale format assumptions.
🧹 Nitpick comments (10)
web/src/helpers/data.js (1)
12-12: Guard against absent value to avoid"undefined"pollutionIf the backend ever omits
pay_methods,JSON.stringify(undefined)yieldsundefined(string), notnull, which laterJSON.parsewill choke on.- localStorage.setItem('pay_methods', JSON.stringify(data.pay_methods)); + if (data.pay_methods !== undefined) { + localStorage.setItem('pay_methods', JSON.stringify(data.pay_methods)); + } else { + localStorage.removeItem('pay_methods'); + }model/option.go (1)
392-394: Bubble up JSON parse errors for admin feedback
UpdatePayMethodsByJsonStringnow (after fix) returns an error when JSON is invalid, but the UI currently only logs a generic “更新失败”. Consider surfacing the specific parse error so the admin instantly knows the JSON is malformed.web/src/components/settings/SystemSetting.js (4)
20-21:verifyJSONmight not be tree-shake-safeImporting the helper solely for two verifications can increase bundle size if
verifyJSONsits in a large utilities file. Consider a lean sub-module export (e.g.helpers/json) to keep chunks small.
234-239: Duplicate JSON validation logic – abstract to reduce driftBoth
TopupGroupRatioandPayMethodsshare the"changed && verifyJSON"pattern. Extract a small helper:const needValidJson = (key) => originInputs[key] !== inputs[key] && !verifyJSON(inputs[key]);This keeps the form logic concise and avoids future copy-paste mistakes.
266-268: Push prettified JSON for better readability in DB and logsBefore
options.push({ key: 'PayMethods', value: inputs.PayMethods });
consider:options.push({ key: 'PayMethods', value: JSON.stringify(JSON.parse(inputs.PayMethods), null, 2), });This keeps the stored string human readable.
671-676: UI placeholder could link to schema for easier editingAdmins may not know the expected keys (
name,color,type). Add a short hint or example JSON in the placeholder/description to prevent invalid submissions.web/src/pages/TopUp/index.js (4)
52-60: Avoid duplicatingmin_topupin state initialisation.
minTopUpis already initialised just above. Instead of copying the literal again (which can drift), derive the initialtopUpCountfrom that state so there is a single source of truth:-const [topUpCount, setTopUpCount] = useState( - statusState?.status?.min_topup || 1, -); +const [topUpCount, setTopUpCount] = useState(() => statusState?.status?.min_topup || 1);This keeps the default in sync even if the backend changes its minimum.
70-70: Variable-name shadowing can confuse future readers.
payMethodsis used both as a local variable later and as a React state setter (setPayMethods). Consider renaming the local variable tostoredPayMethods(or similar) to avoid shadowing.
688-711: Duplicate payment-button markup – extract a component.
The desktop and mobile sections render the same “pay method” button grid. Extract a small<PayMethodButtons payMethods … />component to DRY this up and keep behaviour consistent.Also applies to: 963-985
618-662:InputNumberparser can returnNaN.
If the user erases the field completely the parser returns0, butonChangetreats falsy as invalid which leaves0in state. Consider guarding withNumber.isFinite(value)or coercing toundefinedto avoidtopUpCount = 0.Also applies to: 913-941
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
controller/misc.go(1 hunks)model/option.go(2 hunks)setting/payment.go(1 hunks)web/src/components/settings/SystemSetting.js(5 hunks)web/src/helpers/data.js(1 hunks)web/src/pages/TopUp/index.js(17 hunks)
🔇 Additional comments (5)
controller/misc.go (1)
79-80: Confirm frontend/key naming consistencyA new response field
"pay_methods"is added. Ensure:
- Frontend always lower-cases when reading (looks OK in
helpers/data.js).- No existing clients relied on camelCase (
payMethods) – breaking change risk.If any public API consumers exist, consider versioning or aliasing for backward compatibility.
web/src/pages/TopUp/index.js (4)
10-11: Imports look good.
The new helpers (getQuotaPerUnit) and theCoinsicon are correctly pulled in and alphabetically consistent with the surrounding imports.Also applies to: 37-38
86-87: 👍 Extra preset is harmless.
Adding the 1000-quota preset is straightforward and doesn’t touch validation logic.
136-137: Potential stale state when updating user quota.
userState.user.quotais read synchronously insidesetUserQuota, butuserState.usermay already be stale at this point. Prefer reading the fresh value fromupdatedUseror using a functional update onuserDispatch.
385-404: UI tweaks only.
Nothing functionally risky in these cosmetic changes.Also applies to: 431-441
| var PayMethods = []map[string]string{ | ||
| { | ||
| "name": "支付宝", | ||
| "color": "rgba(var(--semi-blue-5), 1)", | ||
| "type": "zfb", | ||
| }, | ||
| { | ||
| "name": "微信", | ||
| "color": "rgba(var(--semi-green-5), 1)", | ||
| "type": "wx", | ||
| }, | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider replacing map[string]string with a dedicated struct for type-safety
The slice is currently defined as []map[string]string.
Pros of introducing a type PayMethod struct { Name string; Color string; Type string }:
- Compile-time guarantees that every entry contains the three expected keys.
- No magic strings when accessing fields elsewhere (
pm.Typevs.m["type"]). - Easier JSON (un)marshalling and future refactors.
Refactoring now will avoid scattered map look-ups in the future.
🤖 Prompt for AI Agents
In setting/payment.go around lines 12 to 23, replace the slice of
map[string]string with a slice of a dedicated struct named PayMethod that has
fields Name, Color, and Type all of type string. Define the PayMethod struct
above the slice declaration, then update the slice to use PayMethod instances
instead of maps. This change will enforce type safety, eliminate string key
lookups, and simplify future maintenance and JSON handling.
| func UpdatePayMethodsByJsonString(jsonString string) error { | ||
| PayMethods = make([]map[string]string, 0) | ||
| return json.Unmarshal([]byte(jsonString), &PayMethods) | ||
| } | ||
|
|
||
| func PayMethods2JsonString() string { | ||
| jsonBytes, err := json.Marshal(PayMethods) | ||
| if err != nil { | ||
| return "[]" | ||
| } | ||
| return string(jsonBytes) | ||
| } | ||
|
|
||
| func ContainsPayMethod(method string) bool { | ||
| for _, payMethod := range PayMethods { | ||
| if payMethod["type"] == method { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } |
There was a problem hiding this comment.
Unprotected global mutation & potential data-loss in UpdatePayMethodsByJsonString
- A failed
json.UnmarshalleavesPayMethodsreset to an empty slice, silently wiping existing config. - Concurrent reads (e.g. from HTTP handlers) and this write introduce a clear data race.
Proposed fix (simplified):
+var payMethodsMu sync.RWMutex
+
func UpdatePayMethodsByJsonString(jsonString string) error {
- PayMethods = make([]map[string]string, 0)
- return json.Unmarshal([]byte(jsonString), &PayMethods)
+ var methods []map[string]string
+ if err := json.Unmarshal([]byte(jsonString), &methods); err != nil {
+ return err
+ }
+ payMethodsMu.Lock()
+ PayMethods = methods
+ payMethodsMu.Unlock()
+ return nil
}
func PayMethods2JsonString() string {
- jsonBytes, err := json.Marshal(PayMethods)
+ payMethodsMu.RLock()
+ jsonBytes, err := json.Marshal(PayMethods)
+ payMethodsMu.RUnlock()
@@
}
func ContainsPayMethod(method string) bool {
- for _, payMethod := range PayMethods {
+ payMethodsMu.RLock()
+ defer payMethodsMu.RUnlock()
+ for _, payMethod := range PayMethods {
if payMethod["type"] == method {
return true
}
}
return false
}This preserves the old value on parse failure and removes the race condition.
🤖 Prompt for AI Agents
In setting/payment.go around lines 25 to 45, the UpdatePayMethodsByJsonString
function resets the global PayMethods slice before unmarshaling, which causes
data loss if unmarshaling fails, and also introduces a data race with concurrent
reads. To fix this, first unmarshal the JSON into a local variable, check for
errors, and only update the global PayMethods if unmarshaling succeeds.
Additionally, protect access to PayMethods with appropriate synchronization
(e.g., a mutex) to prevent data races during concurrent reads and writes.
| let payMethods = localStorage.getItem('pay_methods'); | ||
| try { | ||
| payMethods = JSON.parse(payMethods); | ||
| if (payMethods && payMethods.length > 0) { | ||
| // 检查name和type是否为空 | ||
| payMethods = payMethods.filter((method) => { | ||
| return method.name && method.type; | ||
| }); | ||
| // 如果没有color,则设置默认颜色 | ||
| payMethods = payMethods.map((method) => { | ||
| if (!method.color) { | ||
| if (method.type === 'zfb') { | ||
| method.color = 'rgba(var(--semi-blue-5), 1)'; | ||
| } else if (method.type === 'wx') { | ||
| method.color = 'rgba(var(--semi-green-5), 1)'; | ||
| } else { | ||
| method.color = 'rgba(var(--semi-primary-5), 1)'; | ||
| } | ||
| } | ||
| return method; | ||
| }); | ||
| setPayMethods(payMethods); | ||
| } | ||
| } catch (e) { | ||
| console.log(e); | ||
| showError(t('支付方式配置错误, 请联系管理员')); | ||
| } | ||
| }, []); |
There was a problem hiding this comment.
Sanitise & de-duplicate pay_methods parsing.
- Shadowing (
payMethodsvs. state) and in-place mutation make this block hard to reason about. method.coloris injected directly into an inline style; a crafted colour such asurl(javascript:alert(1))would be executed by some browsers. Validate that the value matches a safe CSS colour format.
- let payMethods = localStorage.getItem('pay_methods');
- try {
- payMethods = JSON.parse(payMethods);
- if (payMethods && payMethods.length > 0) {
+ const raw = localStorage.getItem('pay_methods');
+ try {
+ const storedPayMethods = JSON.parse(raw);
+ if (Array.isArray(storedPayMethods) && storedPayMethods.length) {
// …
- setPayMethods(payMethods);
+ setPayMethods(sanitisedPayMethods);
}Add a simple colour whitelist, e.g. regex /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i or limit to known CSS variables.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In web/src/pages/TopUp/index.js around lines 294 to 321, the code mutates the
payMethods array directly and shadows the variable name, making it confusing.
Also, the method.color value is assigned without validation, which can lead to
security risks if malicious values are injected. To fix this, avoid mutating the
original array by creating a new sanitized array for state update, rename
variables to prevent shadowing, and implement a whitelist check for method.color
values using a regex that only allows safe CSS color formats or restrict to
known CSS variables before assigning them.
feat: 自定义充值方式
feat: 自定义充值方式
feat: 自定义充值方式
Summary by CodeRabbit