Commit Graph
699 Commits
Author SHA1 Message Date
erio b3a2611d67 chore: bump version to 0.1.110.52 2026-04-13 23:36:27 +08:00
erio c664e67018 refactor: M5 useQuotaNotifyState composable + H14 Vue file splits
M5: New composable frontend/src/composables/useQuotaNotifyState.ts
  - Replaces 9 individual refs in both Create/Edit modals with reactive state
  - Provides loadFromExtra/writeToExtra/reset helpers
  - Eliminates ~120 lines of duplicated code across the two modals

H14: Vue file length violations fixed
  - AdminPaymentPlansView.vue: 325 → 183 lines (extracted PlanEditDialog.vue)
  - QuotaLimitCard.vue: 327 → 268 lines (extracted QuotaDimensionRow.vue)
  - PlanEditDialog.vue: 181 lines (new, plan create/edit form)
  - QuotaDimensionRow.vue: 108 lines (new, single quota dimension row)
2026-04-13 22:35:24 +08:00
erio 7a5ec1a17a refactor: M6 extract applyAccountStatsCost helper, M11 fix postUsageBilling double-queue
M6: New applyAccountStatsCost() helper in account_stats_pricing.go replaces
    identical upstream-model-fallback + resolveAccountStatsCost() call sites
    in both gateway_service.go and openai_gateway_service.go

M11: postUsageBilling legacy path no longer calls finalizePostUsageBilling,
    fixing the double-queue bug (QueueDeductBalance was called twice if the
    fallback path was ever reached). Added NOTE comment documenting the split.
2026-04-13 22:22:05 +08:00
erio 4213688485 refactor: batch 3 — decompose CheckBalanceAfterDeduction, merge crossing checks, add QuotaNotifyConfig
M1: CheckBalanceAfterDeduction (63→18 lines) decomposed into:
    canNotifyBalance, resolveUserEffectiveThreshold, crossedDownward, dispatchBalanceLowEmail
M3: New Account.QuotaNotifyConfig(dim) method replaces 9 hardcoded getters
    (getters kept as thin wrappers for backward compatibility)
M4: checkQuotaDimCrossings + checkQuotaDimCrossingsFromState merged into one
    function taking pre-built []quotaDim; caller builds dims conditionally
2026-04-13 22:02:18 +08:00
erio 939902f998 fix: batch 2 audit fixes — diffSettings notify fields, slog migration, frontend constants
H5: diffSettings now tracks 5 balance/quota notify fields in audit log
M15: log.Printf audit log migrated to slog.Info, removed "log" import
M14: New frontend/src/constants/account.ts with shared constants
     QuotaNotifyToggle.vue uses QUOTA_THRESHOLD_TYPE_FIXED/PERCENTAGE
L2: UsageTable.vue uses BILLING_MODE_TOKEN/IMAGE from billingMode.ts
2026-04-13 21:54:01 +08:00
erio 563339dedb fix: batch 1 audit fixes — quota SQL fixed mode, public recharge URL, WebSearch bool fallback, UpdatePlan validation
H1: incrementUsageBillingAccountQuota now uses shared dailyExpiredExpr/weeklyExpiredExpr
    constants (supporting fixed reset mode) instead of hardcoded '24 hours'/'168 hours'
H4: public settings endpoint now maps balance_low_notify_recharge_url
H6: GetWebSearchEmulationMode tolerates legacy bool values (true→enabled)
H7: UpdatePlan validates non-nil patch fields (rejects negative price, empty name, etc.)
H8: UsageTable accountBilled() helper with total_cost ?? 0 null guard
H9: AdminUsageLog TS type adds channel_id + billing_tier
M2: account.go "fixed" literals replaced with thresholdTypeFixed constant
M13: SystemSettings TS type adds web_search_emulation_enabled
UI: QuotaLimitCard title labels now use flex-1 to align with flex-1 input boxes
2026-04-13 21:41:02 +08:00
erio 66ccd17492 fix(quota-card): balance input widths, inline reset hint, timezone GMT offset
- Limit input and notify threshold now share flex-1 equally (was w-28 fixed)
- Reset schedule hint text moved inline after the selectors (same row)
- Timezone dropdown shows GMT offset, e.g. "Asia/Shanghai (GMT+8)"
2026-04-13 20:45:12 +08:00
erio 69971098af fix(channels): apply platform color to rule group/account chips
In "custom account stats pricing rule" section, group checkbox labels and
selected account chips now use the platform text color (matching the top
"associated groups" header), making it visually consistent across the modal.
2026-04-13 20:39:06 +08:00
erio fea35fbfb2 fix(accounts): unify modal width, add notify props to create, fix quota layout
- EditAccountModal width changed from "normal" to "wide" (match CreateAccountModal)
- CreateAccountModal now passes all quota notify props to QuotaLimitCard
- QuotaLimitCard: when global notify disabled, hide title row, input takes full width
- Quota alert email: show remaining quota + threshold (fixed/$, percentage/%) instead of usage trigger point
2026-04-13 20:01:25 +08:00
erio b0305fef11 fix: audit findings - PUT response rechargeURL, NaN guard, debug logs
- Add BalanceLowNotifyRechargeURL to admin PUT response (fixes save-then-stale)
- Add ?? 1 guard for account_rate_multiplier in UsageTable else branch
- Downgrade high-frequency notify logs from Info to Debug
- Extract "Sub2API" magic string to defaultSiteName constant
2026-04-13 19:45:45 +08:00
erio 6307aff1d3 fix(notify): add recharge URL to admin settings GET response 2026-04-13 19:02:40 +08:00
erio 1621f8ae9e fix(notify): write back auto-filled recharge URL to form on save 2026-04-13 18:52:02 +08:00
erio 1d13c2d2ba fix(notify): auto-fill recharge URL with current origin when empty 2026-04-13 18:46:56 +08:00
erio 6c2c17d17e feat(notify): add platform/ID to quota alert email, add recharge URL to balance alert
- Quota alert email now shows account ID and platform
- Balance low email includes a "Top Up Now" button when recharge URL is configured
- New setting: balance_low_notify_recharge_url in admin settings
2026-04-13 18:39:45 +08:00
erio 78df126437 fix(ui): widen notify type dropdown to show % fully, align quota input widths 2026-04-13 18:23:20 +08:00
erio d6fe6da831 fix(plans): frontend validation for price > 0 and validity_days >= 1 2026-04-13 18:18:29 +08:00
erio f5e386e330 fix(plans): require price > 0 for subscription plans 2026-04-13 18:12:57 +08:00
erio 5277f33155 fix(plans): subscription plan page validation, sorting, and toFixed error
- Fix toFixed crash when price is undefined
- Remove sort_order field, order by created_at instead
- Fix group selector showing blank when nothing selected
- Add required field markers (*) and backend validation
- Add i18n groupRequired key for both zh/en
2026-04-13 18:08:06 +08:00
erio a03ffc8c99 fix: change quota notify threshold semantics to "remaining quota"
Threshold now represents remaining quota instead of usage amount:
- Fixed ($): threshold=400, limit=1000 → alert when remaining drops to $400
  (i.e., usage reaches $600)
- Percentage (%): threshold=30%, limit=1000 → alert when remaining drops
  to 30% (i.e., usage reaches $700)

Also:
- Rename 告警阈值 → 提醒阈值 in i18n
- Widen type dropdown to w-16 for proper $ / % display
2026-04-13 17:38:33 +08:00
erio 4a2ef0b538 fix(frontend): quota card layout - title row + input row, fix $ dropdown
- Separate title row (日限额 + 告警阈值) from input row
- Widen limit input to w-32 for better alignment with title
- Remove duplicate label from QuotaNotifyToggle (now in title row)
- Fix dropdown to always show $ or % as selected value
2026-04-13 17:27:57 +08:00
erio 879f88afe5 fix(frontend): compact quota card - inline labels, dropdown type selector
- Move dimension labels (日限额/周限额/总限额) inline with input row
- Replace $ / % toggle buttons with a compact dropdown select
- Reduce limit input width (w-28) to give more space for notify toggle
- Overall card height significantly reduced
2026-04-13 17:20:25 +08:00
erio 3ef3d6f34e fix(frontend): place quota notify toggle inline with limit input
Move QuotaNotifyToggle to the same row as the limit $ input for all
three dimensions (daily/weekly/total), significantly reducing card height.
2026-04-13 17:12:20 +08:00
erio 65ef8aceaf fix(frontend): collapsible quota card and compact notify layout
- QuotaLimitCard: add collapse/expand toggle (chevron icon + click header)
- QuotaNotifyToggle: show $ or % suffix in threshold input
- Reduce vertical spacing between reset mode hint and notify toggle
2026-04-13 17:04:23 +08:00
erio 20da7a8d07 perf: run balance/quota notification checks async
Move notifyBalanceLow and notifyAccountQuota to goroutines so the
threshold checking logic (DB settings reads, threshold calculation,
crossing detection) no longer blocks the request thread. Both are
fire-and-forget with panic recovery and log-only error handling.
2026-04-13 16:57:53 +08:00
erio 8183ce79a3 fix(frontend): quota notify UI improvements
- QuotaNotifyToggle: add $ or % suffix to threshold input based on type
- QuotaLimitCard: combine reset mode and notify toggle on same row
  to reduce vertical height for daily/weekly sections
- Remove redundant ml-4 indentation from QuotaNotifyToggle
2026-04-13 16:52:02 +08:00
erio 261ea08892 fix: correct account stats pricing priority order
Priority was wrong:
- Before: custom rules → LiteLLM (when ApplyPricingToAccountStats) → nil
- After:  custom rules → totalCost (when ApplyPricingToAccountStats) → LiteLLM → nil

When ApplyPricingToAccountStats is enabled, use the request's actual
client billing cost (before multiplier) as account_stats_cost, instead
of recalculating from LiteLLM per-token prices which produced incorrect
values for per-request billing mode.

LiteLLM model pricing is now the final fallback (priority 3), used only
when neither custom rules nor ApplyPricingToAccountStats apply.
2026-04-13 16:45:10 +08:00
erio c6a9da4ea9 debug: add notification path logging for beta investigation
Add slog.Info/Debug logs to notifyBalanceLow, notifyAccountQuota,
CheckBalanceAfterDeduction, and sendEmails to diagnose why balance
and quota notifications are not being sent in beta environment.
2026-04-13 16:20:07 +08:00
erio 9c9945071f fix: expose account_stats_cost in usage log API and fix frontend display
Backend:
- Add AccountStatsCost field to AdminUsageLog DTO
- Map AccountStatsCost in UsageLogFromServiceAdmin mapper
- Replace println with slog.Warn in api_key_auth_cache_impl.go

Frontend:
- Add account_stats_cost to AdminUsageLog TypeScript interface
- Usage tooltip and table: prefer account_stats_cost when available,
  fallback to total_cost * multiplier (mirrors SQL COALESCE logic)
- Excel export: same COALESCE fallback
2026-04-13 16:00:52 +08:00
erio 068407d884 fix: add missing AccountQuotaNotifyEnabled to admin settings API
The field was present in SystemSettings response DTO and service layer
but missing from:
- UpdateSettingsRequest (admin handler) - saves were silently ignored
- GET/PUT response mapping in admin handler
- UpdateSettingsRequest (non-admin dto)

This caused the toggle to always revert to off after saving.
2026-04-13 15:30:06 +08:00
erio c85272606d fix(frontend): hide quota notify toggle when global setting is disabled
QuotaLimitCard now requires quotaNotifyGlobalEnabled prop to control
visibility of QuotaNotifyToggle components. When the global account
quota notification is disabled in admin settings, per-account threshold
toggles are hidden in both Edit and Create account modals.
2026-04-13 15:13:56 +08:00
erio f7f2c82981 fix: use DB transaction return values for balance/quota notification crossing detection
Replace the stale Redis cache read + invalidation hack with direct DB
transaction RETURNING values:

- deductUsageBillingBalance: add RETURNING balance to get post-deduction balance
- incrementUsageBillingAccountQuota: extend RETURNING to include all 6 quota
  dimensions (daily/weekly/total used+limit)
- Expand UsageBillingApplyResult with NewBalance and QuotaState fields
- finalizePostUsageBilling uses result directly, no Redis read needed
- CheckAccountQuotaAfterIncrement accepts optional QuotaState to skip
  fetchFreshAccount when DB values are available

This eliminates the race condition where QueueDeductBalance async update
hadn't propagated to Redis before GetUserBalance read, causing oldBalance
to be inflated and threshold crossing detection to always fail.
2026-04-13 15:03:49 +08:00
erio c37cff6a86 fix: round 3 audit fixes - SMTP header sanitization and goroutine safety
- Move sanitizeEmailHeader to SendEmailWithConfig entry point, covering all
  email senders (verify code, password reset, ops alerts, notifications)
- Add panic recovery to UpdateBalance goroutine
- Fix stale comment in getAccountQuotaNotifyEmails (email="" no longer used)
- Log error instead of silently discarding verifyNotifyCode cache update failure
2026-04-13 14:21:37 +08:00
erio ad351d4252 fix: audit fixes for websearch, notifications, and channel pricing
P0: fix wildcard matching test assertion (config order, not longest prefix)
P0: add TotalRecharged to auth cache snapshot (v5) for percentage threshold
P1: move pricing rules into per-platform sections in ChannelsView
P1: populate account name cache when editing existing channel rules
P1: sanitize email subject headers to prevent SMTP injection
P1: make Redis INCR+EXPIRE idempotent for rate limiting
P1: deep copy FeaturesConfig in Channel.Clone()
P2: clean up stale email="" placeholder comments
P2: replace log.Printf with slog in email_service.go
2026-04-13 13:59:35 +08:00
erio ff66bb5c36 chore: bump version to 0.1.110.19 2026-04-13 12:41:37 +08:00
erio 68f546e3ec chore: bump version to 0.1.110.18 2026-04-13 12:07:09 +08:00
erio ae9ea2e766 chore: bump version to 0.1.110.17 2026-04-13 11:37:08 +08:00
erio 834ba46da9 feat: WebSearch tri-state, account stats pricing fix, quota cache fix, usage tooltip
WebSearch tri-state switch:
- Account-level web_search_emulation changed from bool to tri-state
  string: "default" (follow channel) / "enabled" / "disabled"
- shouldEmulateWebSearch checks channel config when account is "default"
- SQL migration converts old bool values
- Frontend select replaces toggle in Edit/CreateAccountModal

Account stats pricing:
- resolveAccountStatsCost uses upstream model (post-mapping) for matching
- Priority: custom rules → model pricing file (when toggle on) → default
- Custom rules always configurable, independent of toggle
- Account ID field changed to searchable selector filtered by platform
- Description updated to reflect new behavior

Quota notification cache fix:
- CheckAccountQuotaAfterIncrement fetches real-time account from DB
- Reconstructs pre-increment usage for accurate threshold crossing detection
- New AccountQuotaReader interface (minimal: GetByID only)

Usage tooltip:
- Per-request/image billing shows per-request price instead of $0 token price
- Token billing continues to show input/output price per million tokens
2026-04-13 11:37:08 +08:00
erio 4f4267d646 chore: bump version to 0.1.110.16 2026-04-13 02:28:31 +08:00
erio e85ea0694b chore: bump version to 0.1.110.15 2026-04-13 01:40:13 +08:00
erio 621f767e29 chore: bump version to 0.1.110.14 2026-04-13 01:29:22 +08:00
erio 92ccda5859 chore: bump version to 0.1.110.13 2026-04-13 00:52:56 +08:00
erio adc5fa3ee1 chore: bump version to 0.1.110.12 2026-04-12 18:12:13 +08:00
erio 3ac935f047 fix(websearch): improve settings UI and hide config when globally disabled
- API Key show/copy buttons moved inside input field (inline icons)
- Proxy selector and test button on same row to save vertical space
- Test opens a dialog modal instead of inline display
- Hide all websearch config in channels/accounts when global toggle is off
2026-04-12 15:59:45 +08:00
erio a3da2465b7 chore: bump version to 0.1.110.10 2026-04-12 15:01:26 +08:00
erio 08235a462c chore: bump version to 0.1.110.9 2026-04-12 14:48:26 +08:00
erio 8fe7110d7f fix: address audit findings for websearch and balance notification
- Fix GetByKeyForAuth not selecting balance notify fields (notifications
  never triggered in gateway path)
- Fix provider-level ProxyURL never resolved: inject ProxyRepository into
  SettingService, resolve proxy URLs when building Manager
- Fix admin manual balance adjustment not updating total_recharged
- Add threshold_type input validation (reject invalid values)
- Fix user threshold_type inheritance: custom threshold defaults to "fixed"
  instead of inheriting global type (prevents $5 being treated as 5%)
- Add try-catch for clipboard.writeText (fails on non-HTTPS)
- Add SetTotalRecharged to user Update for admin balance operations
2026-04-12 14:43:12 +08:00
erio f059ad02be chore: bump version to 0.1.110.8 2026-04-12 13:18:30 +08:00
erio 9d3376cbdb Merge branch 'worktree-feature+balance_notify' into release/custom-0.1.110
# Conflicts:
#	backend/internal/handler/admin/setting_handler.go
#	backend/internal/service/domain_constants.go
#	backend/internal/service/setting_service.go
#	backend/internal/service/settings_view.go
2026-04-12 13:17:28 +08:00
erio 8f93b69584 feat(notify): add balance low & account quota notification system
- User balance low notification: email alert when balance drops below
  configurable threshold (user email + verified extra emails)
- Account quota notification: broadcast email to admin-configured
  recipients when daily/weekly/total quota usage exceeds alert threshold
- Admin settings: global enable/disable, default threshold, quota
  notification email list (Email Settings tab)
- User profile: enable/disable, custom threshold, add/remove extra
  notification emails with verification code flow
- Account quota: per-dimension alert toggle and threshold in quota
  control card
- Trigger logic: first-crossing only (old >= threshold && new < threshold
  for balance; old < threshold && new >= threshold for quota), naturally
  prevents duplicate notifications without Redis dedup
2026-04-12 02:48:57 +08:00
erio 6f24322ee6 chore: bump version to 0.1.110.7 2026-04-12 02:27:19 +08:00