Compare commits

...

48 Commits

Author SHA1 Message Date
t0ng7u
e967094348 Merge branch 'sub' into feature/subscription 2026-02-03 02:10:04 +08:00
t0ng7u
47012e84c1 fix: standardize epay success response schema
Return subscription epay pay success responses via ApiSuccess to include the consistent success field and align with error schema.
2026-02-03 02:09:53 +08:00
t0ng7u
b8b40511f3 Merge branch 'sub' into feature/subscription 2026-02-03 02:07:12 +08:00
t0ng7u
58afec3771 fix: refine Japanese subscription status labels
Adjust Japanese UI wording for active-count labels to read more naturally and consistently.
2026-02-03 02:05:40 +08:00
t0ng7u
e48b74f469 Merge branch 'sub' into feature/subscription 2026-02-03 02:03:47 +08:00
t0ng7u
c1061b2d18 🛡️ fix: fail fast on epay form parse errors
Handle ParseForm errors in epay notify/return handlers by returning fail or redirecting to failure, avoiding unsafe fallback to query parameters.
2026-02-03 02:03:25 +08:00
t0ng7u
4e9c5bb45b Merge branch 'sub' into feature/subscription 2026-02-03 01:59:05 +08:00
t0ng7u
f578aa8e00 🔧 fix: harden billing flow and sidebar settings
Add missing strings import for subscription fallback checks, log failed subscription refunds after retries, and extend sidebar module settings with a subscription management toggle plus translations.
2026-02-03 01:58:49 +08:00
t0ng7u
732484ceaa Merge branch 'sub' into feature/subscription 2026-02-03 01:51:31 +08:00
t0ng7u
f521a430ce 🔧 fix: harden epay callbacks and billing fallbacks
Use POST and form parsing for epay notify/return routes, persist epay orders before provider calls with expiry on failure, and ensure notify handlers retry correctly.
Restrict subscription-first fallback to insufficient-subscription errors and log refund failures after retries to avoid silent quota drift.
2026-02-03 01:51:16 +08:00
t0ng7u
11eef1ce77 Merge branch 'sub' into feature/subscription 2026-02-03 01:29:45 +08:00
t0ng7u
1e2c039f40 Merge remote-tracking branch 'newapi/main' into sub 2026-02-03 01:29:19 +08:00
t0ng7u
3d177f3020 Merge branch 'sub' into feature/subscription 2026-02-03 01:24:40 +08:00
t0ng7u
0486a5d83b 🧾 fix: persist epay orders before purchase
Create the subscription order before initiating epay payment and expire it if the provider call fails, preventing orphaned transactions and improving reconciliation.
2026-02-03 01:24:25 +08:00
t0ng7u
2cdc37fdc4 Merge branch 'sub' into feature/subscription 2026-02-03 00:24:16 +08:00
t0ng7u
49ac355357 🔧 fix: normalize epay error handling and webhook retries
Standardize SubscriptionRequestEpay error responses via ApiErrorMsg for a consistent schema.
Return "fail" on non-success trade statuses in the epay webhook to preserve retry behavior.
2026-02-03 00:23:51 +08:00
t0ng7u
414f86fb4b Merge branch 'sub' into feature/subscription 2026-02-03 00:12:20 +08:00
t0ng7u
6b694c9c94 🚦 fix: guard epay return success on order completion
Redirect subscription return flow to failure when order completion fails, preventing false success states after payment verification.
2026-02-03 00:10:07 +08:00
t0ng7u
b942d4eebd Merge branch 'sub' into feature/subscription 2026-02-03 00:02:04 +08:00
t0ng7u
ef44a341a8 🔧 fix: make epay webhook and return flow subscription-aware
Ensure Epay webhook acknowledges success only after order completion, returning fail on processing errors to allow retries. Redirect subscription payment returns to the subscription page instead of top-up for correct user flow.
2026-02-03 00:01:24 +08:00
t0ng7u
70a8b30aab Merge branch 'sub' into feature/subscription 2026-02-02 23:45:05 +08:00
t0ng7u
34e5720773 feat: harden subscription billing and improve UI consistency
Improve subscription payment safety and data integrity by handling user/URL lookup failures, fixing Stripe subscription mode, persisting quota reset fields, and correcting subscription delta accounting and DB timestamp casting. Refine the UI with stricter custom duration validation, accurate currency rounding, conditional Epay labeling, rollback on preference update failure, and shared subscription formatting helpers plus clearer component naming.
2026-02-02 23:44:53 +08:00
t0ng7u
4057eedaff Merge branch 'sub' into feature/subscription 2026-02-02 23:09:44 +08:00
t0ng7u
1fba3c064b Add full i18n coverage for subscription-related UI across locales 2026-02-02 23:09:27 +08:00
t0ng7u
120256a52c 🚀 chore: Remove useless action 2026-02-02 17:06:15 +08:00
t0ng7u
16349c98cb Merge remote-tracking branch 'newapi/main' into sub
# Conflicts:
#	main.go
#	web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
#	web/src/pages/Setting/Payment/SettingsPaymentGatewayCreem.jsx
2026-02-02 17:03:02 +08:00
t0ng7u
a74cc93bbc 🔧 chore: remove unused Creem settings state
Drop the unused originInputs state and redundant updates to keep the Creem
settings form state minimal and easier to maintain.
2026-02-02 13:00:37 +08:00
t0ng7u
e8bd2e0d53 chore: Add upgrade group guidance in subscription editor
Add explanatory helper text under the upgrade group field to clarify automatic group upgrades, rollback conditions, and the expected delay before downgrading takes effect.
2026-02-01 15:47:34 +08:00
t0ng7u
de90e11cdf feat: Extract quota conversion helpers to shared utils
Move quota display/conversion helpers into web/src/helpers/quota.js and update the subscription plan editor to import and use the shared utilities instead of inline functions.
2026-02-01 15:40:26 +08:00
t0ng7u
f0e60df96e feat: Update subscription purchase modal display
Show total quota as currency with tooltip for raw quota, hide reset cycle when never, and display upgrade group when configured to match card display rules.
2026-02-01 02:28:50 +08:00
t0ng7u
96caec1626 feat: Add subscription upgrade group with auto downgrade 2026-02-01 02:17:17 +08:00
t0ng7u
c22ca9cdb3 🚀 chore: Remove duplicate subscription usage percentage display
Keep the usage percentage shown only in the total quota line to avoid redundant “已用 0%” text while preserving remaining days in the summary.
2026-02-01 00:43:09 +08:00
t0ng7u
6300c31d70 🚀 refactor: Simplify subscription quota to total amount model
Remove per-model subscription items and switch to a single total quota per plan and user subscription. Update billing, reset, and logging flows to operate on total quota, and refactor admin/user UI to configure and display total quota consistently.
2026-02-01 00:35:08 +08:00
t0ng7u
b92a4ee987 🎨 style: tag color to white 2026-01-31 15:05:09 +08:00
t0ng7u
cf67af3b14 feat: Add subscription limits and UI tags consistency
Add per-plan purchase limits with backend enforcement and UI disable states.
Expose limit configuration in admin plan editor and show limits in plan tables/cards.
Refine subscription UI tags with unified badge style and streamlined “My Subscriptions” layout.
2026-01-31 15:02:03 +08:00
t0ng7u
2297af731c 🔧 chore: Unify subscription plan status toggle with PATCH endpoint
Replace separate enable/disable flows with a single PATCH API that updates the enabled flag.
Update frontend hooks and table actions to call the unified endpoint and keep UI behavior consistent.
Introduce a minimal admin controller handler and route for the status update.
2026-01-31 14:27:01 +08:00
t0ng7u
28c5feb570 💸 chore: Align subscription pricing display with global currency settings
Unify subscription price rendering to use the site-wide currency symbol/rate on the wallet and admin views.
Make subscription plan currency read-only in the editor and force USD on create/update to avoid drift.
Use global currency display type when creating Creem checkout payloads.
2026-01-31 13:41:55 +08:00
t0ng7u
354da6ea6b 🔧 ci: Change workflow trigger to sub branch
Update the Docker image workflow to run on pushes to the sub branch instead of main.
2026-01-31 13:19:26 +08:00
t0ng7u
a0c23a0648 🐛 fix(subscription): avoid pre-consume lookup noise
Use a RowsAffected check for the idempotency lookup so missing records
no longer surface as "record not found" errors while preserving behavior.
2026-01-31 01:18:47 +08:00
t0ng7u
41489fc32a feat(subscription): cache plan lookups and stabilize pre-consume
Introduce hybrid caches for subscription plans, items, and plan info with explicit
invalidation on admin updates. Streamline pre-consume transactions to reduce
redundant queries while preserving idempotency and reset logic.
2026-01-31 01:12:54 +08:00
t0ng7u
ffebb35499 feat(subscription): harden subscription billing with resets, idempotency, and production-grade stability
Add plan-level quota reset periods and display/reset cadence in admin/UI
Enforce natural reset alignment with background reset task and cleanup job
Make subscription pre-consume/refund idempotent with request-scoped records and retries
Use database time for consistent resets across multi-instance deployments
Harden payment callbacks with locking and idempotent order completion
Record subscription purchases in topup history and billing logs
Optimize subscription queries and add critical composite indexes
2026-01-31 00:31:47 +08:00
t0ng7u
5707ee3492 feat(subscription): add quota reset periods and admin configuration
- Add reset period fields on subscription plans and user items
- Apply automatic quota resets during pre-consume based on plan schedule
- Expose reset-period configuration in the admin plan editor
- Display reset cadence in subscription cards and purchase modal
- Validate custom reset seconds on plan create/update
2026-01-31 00:06:13 +08:00
t0ng7u
ecf50b754a 🎨 style: format all code with gofmt and lint:fix
Apply consistent code formatting across the entire codebase using
gofmt and lint:fix tools. This ensures adherence to Go community
standards and improves code readability and maintainability.

Changes include:
- Run gofmt on all .go files to standardize formatting
- Apply lint:fix to automatically resolve linting issues
- Fix code style inconsistencies and formatting violations

No functional changes were made in this commit.
2026-01-30 23:43:27 +08:00
t0ng7u
697cbbf752 fix(subscription): finalize payments, log billing, and clean up dead code
Complete subscription orders by creating a matching top-up record and writing billing logs
Add Epay return handler to verify and finalize browser callbacks
Require Stripe/Creem webhook configuration before starting subscription payments
Show subscription purchases in topup history with clearer labels/methods
Remove unused subscription helper, legacy Creem webhook struct, and unused topup fields
Simplify subscription self API payload to active/all lists only
2026-01-30 23:40:01 +08:00
t0ng7u
a60783e99f feat(admin): streamline subscription plan benefits editor with bulk actions
Restore the avatar/icon header for the “Model Benefits” section
Replace scattered controls with a compact toolbar-style workflow
Support multi-select add with a default quota for new items
Add row selection with bulk apply-to-selected / apply-to-all quota updates
Enable delete-selected to manage benefits faster and reduce mistakes
2026-01-30 16:24:51 +08:00
t0ng7u
348ae6df73 feat(admin): add user subscription management and refine UI/pagination
Add admin APIs to list/create/invalidate/delete user subscriptions
Add model helpers to fetch all user subscriptions (incl. expired) and support cancel/hard-delete
Wire new admin routes for user subscription operations
Replace “Bind subscription plan” entry with a dedicated User Subscriptions SideSheet in Users table
Use CardTable with responsive layout and working client-side pagination inside the SideSheet
Improve subscription purchase modal empty-gateway state with a Banner notice
2026-01-30 14:29:56 +08:00
t0ng7u
009910b960 feat: add subscription billing system with admin management and user purchase flow
Implement a new subscription-based billing model alongside existing metered/per-request billing:

Backend:
- Add subscription plan models (SubscriptionPlan, SubscriptionPlanItem, UserSubscription, etc.)
- Implement CRUD APIs for subscription plan management (admin only)
- Add user subscription queries with support for multiple active/expired subscriptions
- Integrate payment gateways (Stripe, Creem, Epay) for subscription purchases
- Implement pre-consume and post-consume billing logic for subscription quota tracking
- Add billing preference settings (subscription_first, wallet_first, etc.)
- Enhance usage logs with subscription deduction details

Frontend - Admin:
- Add subscription management page with table view and drawer-based edit form
- Match UI/UX style with existing admin pages (redemption codes, users)
- Support enabling/disabling plans, configuring payment IDs, and model quotas
- Add user subscription binding modal in user management

Frontend - Wallet:
- Add subscription plans card with current subscription status display
- Show all subscriptions (active and expired) with remaining days/usage percentage
- Display purchasable plans with pricing cards following SaaS best practices
- Extract purchase modal to separate component matching payment confirm modal style
- Add skeleton loading states with active animation
- Implement billing preference selector in card header
- Handle payment gateway availability based on admin configuration

Frontend - Usage Logs:
- Display subscription deduction details in log entries
- Show step-by-step breakdown of subscription usage (pre-consumed, delta, final, remaining)
- Add subscription deduction tag for subscription-covered requests
2026-01-30 05:31:10 +08:00
t0ng7u
c6c12d340f ci: create docker automation 2026-01-30 01:58:59 +08:00
54 changed files with 6188 additions and 108 deletions

View File

@@ -106,6 +106,16 @@ func GetJsonString(data any) string {
return string(b)
}
// NormalizeBillingPreference clamps the billing preference to valid values.
func NormalizeBillingPreference(pref string) string {
switch strings.TrimSpace(pref) {
case "subscription_first", "wallet_first", "subscription_only", "wallet_only":
return strings.TrimSpace(pref)
default:
return "subscription_first"
}
}
// MaskEmail masks a user email to prevent PII leakage in logs
// Returns "***masked***" if email is empty, otherwise shows only the domain part
func MaskEmail(email string) string {

View File

@@ -159,7 +159,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
if priceData.FreeModel {
logger.LogInfo(c, fmt.Sprintf("模型 %s 免费,跳过预扣费", relayInfo.OriginModelName))
} else {
newAPIError = service.PreConsumeQuota(c, priceData.QuotaToPreConsume, relayInfo)
newAPIError = service.PreConsumeBilling(c, priceData.QuotaToPreConsume, relayInfo)
if newAPIError != nil {
return
}

367
controller/subscription.go Normal file
View File

@@ -0,0 +1,367 @@
package controller
import (
"strconv"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// ---- Shared types ----
type SubscriptionPlanDTO struct {
Plan model.SubscriptionPlan `json:"plan"`
}
type BillingPreferenceRequest struct {
BillingPreference string `json:"billing_preference"`
}
// ---- User APIs ----
func GetSubscriptionPlans(c *gin.Context) {
var plans []model.SubscriptionPlan
if err := model.DB.Where("enabled = ?", true).Order("sort_order desc, id desc").Find(&plans).Error; err != nil {
common.ApiError(c, err)
return
}
result := make([]SubscriptionPlanDTO, 0, len(plans))
for _, p := range plans {
result = append(result, SubscriptionPlanDTO{
Plan: p,
})
}
common.ApiSuccess(c, result)
}
func GetSubscriptionSelf(c *gin.Context) {
userId := c.GetInt("id")
settingMap, _ := model.GetUserSetting(userId, false)
pref := common.NormalizeBillingPreference(settingMap.BillingPreference)
// Get all subscriptions (including expired)
allSubscriptions, err := model.GetAllUserSubscriptions(userId)
if err != nil {
allSubscriptions = []model.SubscriptionSummary{}
}
// Get active subscriptions for backward compatibility
activeSubscriptions, err := model.GetAllActiveUserSubscriptions(userId)
if err != nil {
activeSubscriptions = []model.SubscriptionSummary{}
}
common.ApiSuccess(c, gin.H{
"billing_preference": pref,
"subscriptions": activeSubscriptions, // all active subscriptions
"all_subscriptions": allSubscriptions, // all subscriptions including expired
})
}
func UpdateSubscriptionPreference(c *gin.Context) {
userId := c.GetInt("id")
var req BillingPreferenceRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiErrorMsg(c, "参数错误")
return
}
pref := common.NormalizeBillingPreference(req.BillingPreference)
user, err := model.GetUserById(userId, true)
if err != nil {
common.ApiError(c, err)
return
}
current := user.GetSetting()
current.BillingPreference = pref
user.SetSetting(current)
if err := user.Update(false); err != nil {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, gin.H{"billing_preference": pref})
}
// ---- Admin APIs ----
func AdminListSubscriptionPlans(c *gin.Context) {
var plans []model.SubscriptionPlan
if err := model.DB.Order("sort_order desc, id desc").Find(&plans).Error; err != nil {
common.ApiError(c, err)
return
}
result := make([]SubscriptionPlanDTO, 0, len(plans))
for _, p := range plans {
result = append(result, SubscriptionPlanDTO{
Plan: p,
})
}
common.ApiSuccess(c, result)
}
type AdminUpsertSubscriptionPlanRequest struct {
Plan model.SubscriptionPlan `json:"plan"`
}
func AdminCreateSubscriptionPlan(c *gin.Context) {
var req AdminUpsertSubscriptionPlanRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiErrorMsg(c, "参数错误")
return
}
req.Plan.Id = 0
if strings.TrimSpace(req.Plan.Title) == "" {
common.ApiErrorMsg(c, "套餐标题不能为空")
return
}
if req.Plan.Currency == "" {
req.Plan.Currency = "USD"
}
req.Plan.Currency = "USD"
if req.Plan.DurationUnit == "" {
req.Plan.DurationUnit = model.SubscriptionDurationMonth
}
if req.Plan.DurationValue <= 0 && req.Plan.DurationUnit != model.SubscriptionDurationCustom {
req.Plan.DurationValue = 1
}
if req.Plan.MaxPurchasePerUser < 0 {
common.ApiErrorMsg(c, "购买上限不能为负数")
return
}
if req.Plan.TotalAmount < 0 {
common.ApiErrorMsg(c, "总额度不能为负数")
return
}
req.Plan.UpgradeGroup = strings.TrimSpace(req.Plan.UpgradeGroup)
if req.Plan.UpgradeGroup != "" {
if _, ok := ratio_setting.GetGroupRatioCopy()[req.Plan.UpgradeGroup]; !ok {
common.ApiErrorMsg(c, "升级分组不存在")
return
}
}
req.Plan.QuotaResetPeriod = model.NormalizeResetPeriod(req.Plan.QuotaResetPeriod)
if req.Plan.QuotaResetPeriod == model.SubscriptionResetCustom && req.Plan.QuotaResetCustomSeconds <= 0 {
common.ApiErrorMsg(c, "自定义重置周期需大于0秒")
return
}
err := model.DB.Create(&req.Plan).Error
if err != nil {
common.ApiError(c, err)
return
}
model.InvalidateSubscriptionPlanCache(req.Plan.Id)
common.ApiSuccess(c, req.Plan)
}
func AdminUpdateSubscriptionPlan(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if id <= 0 {
common.ApiErrorMsg(c, "无效的ID")
return
}
var req AdminUpsertSubscriptionPlanRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiErrorMsg(c, "参数错误")
return
}
if strings.TrimSpace(req.Plan.Title) == "" {
common.ApiErrorMsg(c, "套餐标题不能为空")
return
}
req.Plan.Id = id
if req.Plan.Currency == "" {
req.Plan.Currency = "USD"
}
req.Plan.Currency = "USD"
if req.Plan.DurationUnit == "" {
req.Plan.DurationUnit = model.SubscriptionDurationMonth
}
if req.Plan.DurationValue <= 0 && req.Plan.DurationUnit != model.SubscriptionDurationCustom {
req.Plan.DurationValue = 1
}
if req.Plan.MaxPurchasePerUser < 0 {
common.ApiErrorMsg(c, "购买上限不能为负数")
return
}
if req.Plan.TotalAmount < 0 {
common.ApiErrorMsg(c, "总额度不能为负数")
return
}
req.Plan.UpgradeGroup = strings.TrimSpace(req.Plan.UpgradeGroup)
if req.Plan.UpgradeGroup != "" {
if _, ok := ratio_setting.GetGroupRatioCopy()[req.Plan.UpgradeGroup]; !ok {
common.ApiErrorMsg(c, "升级分组不存在")
return
}
}
req.Plan.QuotaResetPeriod = model.NormalizeResetPeriod(req.Plan.QuotaResetPeriod)
if req.Plan.QuotaResetPeriod == model.SubscriptionResetCustom && req.Plan.QuotaResetCustomSeconds <= 0 {
common.ApiErrorMsg(c, "自定义重置周期需大于0秒")
return
}
err := model.DB.Transaction(func(tx *gorm.DB) error {
// update plan (allow zero values updates with map)
updateMap := map[string]interface{}{
"title": req.Plan.Title,
"subtitle": req.Plan.Subtitle,
"price_amount": req.Plan.PriceAmount,
"currency": req.Plan.Currency,
"duration_unit": req.Plan.DurationUnit,
"duration_value": req.Plan.DurationValue,
"custom_seconds": req.Plan.CustomSeconds,
"enabled": req.Plan.Enabled,
"sort_order": req.Plan.SortOrder,
"stripe_price_id": req.Plan.StripePriceId,
"creem_product_id": req.Plan.CreemProductId,
"max_purchase_per_user": req.Plan.MaxPurchasePerUser,
"total_amount": req.Plan.TotalAmount,
"upgrade_group": req.Plan.UpgradeGroup,
"quota_reset_period": req.Plan.QuotaResetPeriod,
"quota_reset_custom_seconds": req.Plan.QuotaResetCustomSeconds,
"updated_at": common.GetTimestamp(),
}
if err := tx.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Updates(updateMap).Error; err != nil {
return err
}
return nil
})
if err != nil {
common.ApiError(c, err)
return
}
model.InvalidateSubscriptionPlanCache(id)
common.ApiSuccess(c, nil)
}
type AdminUpdateSubscriptionPlanStatusRequest struct {
Enabled *bool `json:"enabled"`
}
func AdminUpdateSubscriptionPlanStatus(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if id <= 0 {
common.ApiErrorMsg(c, "无效的ID")
return
}
var req AdminUpdateSubscriptionPlanStatusRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Enabled == nil {
common.ApiErrorMsg(c, "参数错误")
return
}
if err := model.DB.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Update("enabled", *req.Enabled).Error; err != nil {
common.ApiError(c, err)
return
}
model.InvalidateSubscriptionPlanCache(id)
common.ApiSuccess(c, nil)
}
type AdminBindSubscriptionRequest struct {
UserId int `json:"user_id"`
PlanId int `json:"plan_id"`
}
func AdminBindSubscription(c *gin.Context) {
var req AdminBindSubscriptionRequest
if err := c.ShouldBindJSON(&req); err != nil || req.UserId <= 0 || req.PlanId <= 0 {
common.ApiErrorMsg(c, "参数错误")
return
}
msg, err := model.AdminBindSubscription(req.UserId, req.PlanId, "")
if err != nil {
common.ApiError(c, err)
return
}
if msg != "" {
common.ApiSuccess(c, gin.H{"message": msg})
return
}
common.ApiSuccess(c, nil)
}
// ---- Admin: user subscription management ----
func AdminListUserSubscriptions(c *gin.Context) {
userId, _ := strconv.Atoi(c.Param("id"))
if userId <= 0 {
common.ApiErrorMsg(c, "无效的用户ID")
return
}
subs, err := model.GetAllUserSubscriptions(userId)
if err != nil {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, subs)
}
type AdminCreateUserSubscriptionRequest struct {
PlanId int `json:"plan_id"`
}
// AdminCreateUserSubscription creates a new user subscription from a plan (no payment).
func AdminCreateUserSubscription(c *gin.Context) {
userId, _ := strconv.Atoi(c.Param("id"))
if userId <= 0 {
common.ApiErrorMsg(c, "无效的用户ID")
return
}
var req AdminCreateUserSubscriptionRequest
if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
common.ApiErrorMsg(c, "参数错误")
return
}
msg, err := model.AdminBindSubscription(userId, req.PlanId, "")
if err != nil {
common.ApiError(c, err)
return
}
if msg != "" {
common.ApiSuccess(c, gin.H{"message": msg})
return
}
common.ApiSuccess(c, nil)
}
// AdminInvalidateUserSubscription cancels a user subscription immediately.
func AdminInvalidateUserSubscription(c *gin.Context) {
subId, _ := strconv.Atoi(c.Param("id"))
if subId <= 0 {
common.ApiErrorMsg(c, "无效的订阅ID")
return
}
msg, err := model.AdminInvalidateUserSubscription(subId)
if err != nil {
common.ApiError(c, err)
return
}
if msg != "" {
common.ApiSuccess(c, gin.H{"message": msg})
return
}
common.ApiSuccess(c, nil)
}
// AdminDeleteUserSubscription hard-deletes a user subscription.
func AdminDeleteUserSubscription(c *gin.Context) {
subId, _ := strconv.Atoi(c.Param("id"))
if subId <= 0 {
common.ApiErrorMsg(c, "无效的订阅ID")
return
}
msg, err := model.AdminDeleteUserSubscription(subId)
if err != nil {
common.ApiError(c, err)
return
}
if msg != "" {
common.ApiSuccess(c, gin.H{"message": msg})
return
}
common.ApiSuccess(c, nil)
}

View File

@@ -0,0 +1,129 @@
package controller
import (
"bytes"
"io"
"log"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/thanhpk/randstr"
)
type SubscriptionCreemPayRequest struct {
PlanId int `json:"plan_id"`
}
func SubscriptionRequestCreemPay(c *gin.Context) {
var req SubscriptionCreemPayRequest
// Keep body for debugging consistency (like RequestCreemPay)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
log.Printf("read subscription creem pay req body err: %v", err)
c.JSON(200, gin.H{"message": "error", "data": "read query error"})
return
}
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
return
}
plan, err := model.GetSubscriptionPlanById(req.PlanId)
if err != nil {
common.ApiError(c, err)
return
}
if !plan.Enabled {
common.ApiErrorMsg(c, "套餐未启用")
return
}
if plan.CreemProductId == "" {
common.ApiErrorMsg(c, "该套餐未配置 CreemProductId")
return
}
if setting.CreemWebhookSecret == "" && !setting.CreemTestMode {
common.ApiErrorMsg(c, "Creem Webhook 未配置")
return
}
userId := c.GetInt("id")
user, err := model.GetUserById(userId, false)
if err != nil {
common.ApiError(c, err)
return
}
if user == nil {
common.ApiErrorMsg(c, "用户不存在")
return
}
if plan.MaxPurchasePerUser > 0 {
count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
if err != nil {
common.ApiError(c, err)
return
}
if count >= int64(plan.MaxPurchasePerUser) {
common.ApiErrorMsg(c, "已达到该套餐购买上限")
return
}
}
reference := "sub-creem-ref-" + randstr.String(6)
referenceId := "sub_ref_" + common.Sha1([]byte(reference+time.Now().String()+user.Username))
// create pending order first
order := &model.SubscriptionOrder{
UserId: userId,
PlanId: plan.Id,
Money: plan.PriceAmount,
TradeNo: referenceId,
PaymentMethod: PaymentMethodCreem,
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
return
}
// Reuse Creem checkout generator by building a lightweight product reference.
currency := "USD"
switch operation_setting.GetGeneralSetting().QuotaDisplayType {
case operation_setting.QuotaDisplayTypeCNY:
currency = "CNY"
case operation_setting.QuotaDisplayTypeUSD:
currency = "USD"
default:
currency = "USD"
}
product := &CreemProduct{
ProductId: plan.CreemProductId,
Name: plan.Title,
Price: plan.PriceAmount,
Currency: currency,
Quota: 0,
}
checkoutUrl, err := genCreemLink(referenceId, product, user.Email, user.Username)
if err != nil {
log.Printf("获取Creem支付链接失败: %v", err)
c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
return
}
c.JSON(200, gin.H{
"message": "success",
"data": gin.H{
"checkout_url": checkoutUrl,
"order_id": referenceId,
},
})
}

View File

@@ -0,0 +1,196 @@
package controller
import (
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/Calcium-Ion/go-epay/epay"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
"github.com/samber/lo"
)
type SubscriptionEpayPayRequest struct {
PlanId int `json:"plan_id"`
PaymentMethod string `json:"payment_method"`
}
func SubscriptionRequestEpay(c *gin.Context) {
var req SubscriptionEpayPayRequest
if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
common.ApiErrorMsg(c, "参数错误")
return
}
plan, err := model.GetSubscriptionPlanById(req.PlanId)
if err != nil {
common.ApiError(c, err)
return
}
if !plan.Enabled {
common.ApiErrorMsg(c, "套餐未启用")
return
}
if plan.PriceAmount < 0.01 {
common.ApiErrorMsg(c, "套餐金额过低")
return
}
if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
common.ApiErrorMsg(c, "支付方式不存在")
return
}
userId := c.GetInt("id")
if plan.MaxPurchasePerUser > 0 {
count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
if err != nil {
common.ApiError(c, err)
return
}
if count >= int64(plan.MaxPurchasePerUser) {
common.ApiErrorMsg(c, "已达到该套餐购买上限")
return
}
}
callBackAddress := service.GetCallbackAddress()
returnUrl, err := url.Parse(callBackAddress + "/api/subscription/epay/return")
if err != nil {
common.ApiErrorMsg(c, "回调地址配置错误")
return
}
notifyUrl, err := url.Parse(callBackAddress + "/api/subscription/epay/notify")
if err != nil {
common.ApiErrorMsg(c, "回调地址配置错误")
return
}
tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
tradeNo = fmt.Sprintf("SUBUSR%dNO%s", userId, tradeNo)
client := GetEpayClient()
if client == nil {
common.ApiErrorMsg(c, "当前管理员未配置支付信息")
return
}
order := &model.SubscriptionOrder{
UserId: userId,
PlanId: plan.Id,
Money: plan.PriceAmount,
TradeNo: tradeNo,
PaymentMethod: req.PaymentMethod,
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
common.ApiErrorMsg(c, "创建订单失败")
return
}
uri, params, err := client.Purchase(&epay.PurchaseArgs{
Type: req.PaymentMethod,
ServiceTradeNo: tradeNo,
Name: fmt.Sprintf("SUB:%s", plan.Title),
Money: strconv.FormatFloat(plan.PriceAmount, 'f', 2, 64),
Device: epay.PC,
NotifyUrl: notifyUrl,
ReturnUrl: returnUrl,
})
if err != nil {
_ = model.ExpireSubscriptionOrder(tradeNo)
common.ApiErrorMsg(c, "拉起支付失败")
return
}
common.ApiSuccess(c, gin.H{"data": params, "url": uri})
}
func SubscriptionEpayNotify(c *gin.Context) {
if err := c.Request.ParseForm(); err != nil {
_, _ = c.Writer.Write([]byte("fail"))
return
}
params := lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.PostForm.Get(t)
return r
}, map[string]string{})
if len(params) == 0 {
params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.URL.Query().Get(t)
return r
}, map[string]string{})
}
client := GetEpayClient()
if client == nil {
_, _ = c.Writer.Write([]byte("fail"))
return
}
verifyInfo, err := client.Verify(params)
if err != nil || !verifyInfo.VerifyStatus {
_, _ = c.Writer.Write([]byte("fail"))
return
}
if verifyInfo.TradeStatus != epay.StatusTradeSuccess {
_, _ = c.Writer.Write([]byte("fail"))
return
}
LockOrder(verifyInfo.ServiceTradeNo)
defer UnlockOrder(verifyInfo.ServiceTradeNo)
if err := model.CompleteSubscriptionOrder(verifyInfo.ServiceTradeNo, common.GetJsonString(verifyInfo)); err != nil {
_, _ = c.Writer.Write([]byte("fail"))
return
}
_, _ = c.Writer.Write([]byte("success"))
}
// SubscriptionEpayReturn handles browser return after payment.
// It verifies the payload and completes the order, then redirects to console.
func SubscriptionEpayReturn(c *gin.Context) {
if err := c.Request.ParseForm(); err != nil {
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=fail")
return
}
params := lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.PostForm.Get(t)
return r
}, map[string]string{})
if len(params) == 0 {
params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.URL.Query().Get(t)
return r
}, map[string]string{})
}
client := GetEpayClient()
if client == nil {
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=fail")
return
}
verifyInfo, err := client.Verify(params)
if err != nil || !verifyInfo.VerifyStatus {
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=fail")
return
}
if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
LockOrder(verifyInfo.ServiceTradeNo)
defer UnlockOrder(verifyInfo.ServiceTradeNo)
if err := model.CompleteSubscriptionOrder(verifyInfo.ServiceTradeNo, common.GetJsonString(verifyInfo)); err != nil {
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=fail")
return
}
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=success")
return
}
c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/subscription?pay=pending")
}

View File

@@ -0,0 +1,138 @@
package controller
import (
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
"github.com/stripe/stripe-go/v81"
"github.com/stripe/stripe-go/v81/checkout/session"
"github.com/thanhpk/randstr"
)
type SubscriptionStripePayRequest struct {
PlanId int `json:"plan_id"`
}
func SubscriptionRequestStripePay(c *gin.Context) {
var req SubscriptionStripePayRequest
if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
common.ApiErrorMsg(c, "参数错误")
return
}
plan, err := model.GetSubscriptionPlanById(req.PlanId)
if err != nil {
common.ApiError(c, err)
return
}
if !plan.Enabled {
common.ApiErrorMsg(c, "套餐未启用")
return
}
if plan.StripePriceId == "" {
common.ApiErrorMsg(c, "该套餐未配置 StripePriceId")
return
}
if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
common.ApiErrorMsg(c, "Stripe 未配置或密钥无效")
return
}
if setting.StripeWebhookSecret == "" {
common.ApiErrorMsg(c, "Stripe Webhook 未配置")
return
}
userId := c.GetInt("id")
user, err := model.GetUserById(userId, false)
if err != nil {
common.ApiError(c, err)
return
}
if user == nil {
common.ApiErrorMsg(c, "用户不存在")
return
}
if plan.MaxPurchasePerUser > 0 {
count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
if err != nil {
common.ApiError(c, err)
return
}
if count >= int64(plan.MaxPurchasePerUser) {
common.ApiErrorMsg(c, "已达到该套餐购买上限")
return
}
}
reference := fmt.Sprintf("sub-stripe-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
referenceId := "sub_ref_" + common.Sha1([]byte(reference))
payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId)
if err != nil {
log.Println("获取Stripe Checkout支付链接失败", err)
c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"})
return
}
order := &model.SubscriptionOrder{
UserId: userId,
PlanId: plan.Id,
Money: plan.PriceAmount,
TradeNo: referenceId,
PaymentMethod: PaymentMethodStripe,
CreateTime: time.Now().Unix(),
Status: common.TopUpStatusPending,
}
if err := order.Insert(); err != nil {
c.JSON(http.StatusOK, gin.H{"message": "error", "data": "创建订单失败"})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "success",
"data": gin.H{
"pay_link": payLink,
},
})
}
func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string) (string, error) {
stripe.Key = setting.StripeApiSecret
params := &stripe.CheckoutSessionParams{
ClientReferenceID: stripe.String(referenceId),
SuccessURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
CancelURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Price: stripe.String(priceId),
Quantity: stripe.Int64(1),
},
},
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
}
if "" == customerId {
if "" != email {
params.CustomerEmail = stripe.String(email)
}
params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
} else {
params.Customer = stripe.String(customerId)
}
result, err := session.New(params)
if err != nil {
return "", err
}
return result.URL, nil
}

View File

@@ -65,12 +65,10 @@ func GetTopUpInfo(c *gin.Context) {
type EpayRequest struct {
Amount int64 `json:"amount"`
PaymentMethod string `json:"payment_method"`
TopUpCode string `json:"top_up_code"`
}
type AmountRequest struct {
Amount int64 `json:"amount"`
TopUpCode string `json:"top_up_code"`
Amount int64 `json:"amount"`
}
func GetEpayClient() *epay.Client {
@@ -230,10 +228,21 @@ func UnlockOrder(tradeNo string) {
}
func EpayNotify(c *gin.Context) {
params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.URL.Query().Get(t)
if err := c.Request.ParseForm(); err != nil {
log.Println("易支付回调解析失败:", err)
_, _ = c.Writer.Write([]byte("fail"))
return
}
params := lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.PostForm.Get(t)
return r
}, map[string]string{})
if len(params) == 0 {
params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.URL.Query().Get(t)
return r
}, map[string]string{})
}
client := GetEpayClient()
if client == nil {
log.Println("易支付回调失败 未找到配置信息")

View File

@@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
@@ -227,16 +228,6 @@ type CreemWebhookEvent struct {
} `json:"object"`
}
// 保留旧的结构体作为兼容
type CreemWebhookData struct {
Type string `json:"type"`
Data struct {
RequestId string `json:"request_id"`
Status string `json:"status"`
Metadata map[string]string `json:"metadata"`
} `json:"data"`
}
func CreemWebhook(c *gin.Context) {
// 读取body内容用于打印同时保留原始数据供后续使用
bodyBytes, err := io.ReadAll(c.Request.Body)
@@ -308,7 +299,19 @@ func handleCheckoutCompleted(c *gin.Context, event *CreemWebhookEvent) {
return
}
// 验证订单类型,目前只处理一次性付款
// Try complete subscription order first
LockOrder(referenceId)
defer UnlockOrder(referenceId)
if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(event)); err == nil {
c.Status(http.StatusOK)
return
} else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
log.Printf("Creem订阅订单处理失败: %s, 订单号: %s", err.Error(), referenceId)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// 验证订单类型,目前只处理一次性付款(充值)
if event.Object.Order.Type != "onetime" {
log.Printf("暂不支持的订单类型: %s, 跳过处理", event.Object.Order.Type)
c.Status(http.StatusOK)

View File

@@ -1,6 +1,7 @@
package controller
import (
"errors"
"fmt"
"io"
"log"
@@ -185,6 +186,22 @@ func sessionCompleted(event stripe.Event) {
return
}
// Try complete subscription order first
LockOrder(referenceId)
defer UnlockOrder(referenceId)
payload := map[string]any{
"customer": customerId,
"amount_total": event.GetObjectValue("amount_total"),
"currency": strings.ToUpper(event.GetObjectValue("currency")),
"event_type": string(event.Type),
}
if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload)); err == nil {
return
} else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
log.Println("complete subscription order failed:", err.Error(), referenceId)
return
}
err := model.Recharge(referenceId, customerId)
if err != nil {
log.Println(err.Error(), referenceId)
@@ -209,6 +226,16 @@ func sessionExpired(event stripe.Event) {
return
}
// Subscription order expiration
LockOrder(referenceId)
defer UnlockOrder(referenceId)
if err := model.ExpireSubscriptionOrder(referenceId); err == nil {
return
} else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
log.Println("过期订阅订单失败", referenceId, ", err:", err.Error())
return
}
topUp := model.GetTopUpByTradeNo(referenceId)
if topUp == nil {
log.Println("充值订单不存在", referenceId)

View File

@@ -13,6 +13,7 @@ type UserSetting struct {
AcceptUnsetRatioModel bool `json:"accept_unset_model_ratio_model,omitempty"` // AcceptUnsetRatioModel 是否接受未设置价格的模型
RecordIpLog bool `json:"record_ip_log,omitempty"` // 是否记录请求和错误日志IP
SidebarModules string `json:"sidebar_modules,omitempty"` // SidebarModules 左侧边栏模块配置
BillingPreference string `json:"billing_preference,omitempty"` // BillingPreference 扣费策略(订阅/钱包)
}
var (

View File

@@ -106,6 +106,9 @@ func main() {
// Codex credential auto-refresh check every 10 minutes, refresh when expires within 1 day
service.StartCodexCredentialAutoRefreshTask()
// Subscription quota reset task (daily/weekly/monthly/custom)
service.StartSubscriptionQuotaResetTask()
if common.IsMasterNode && constant.UpdateTask {
gopool.Go(func() {
controller.UpdateMidjourneyTaskBulk()

22
model/db_time.go Normal file
View File

@@ -0,0 +1,22 @@
package model
import "github.com/QuantumNous/new-api/common"
// GetDBTimestamp returns a UNIX timestamp from database time.
// Falls back to application time on error.
func GetDBTimestamp() int64 {
var ts int64
var err error
switch {
case common.UsingPostgreSQL:
err = DB.Raw("SELECT EXTRACT(EPOCH FROM NOW())::bigint").Scan(&ts).Error
case common.UsingSQLite:
err = DB.Raw("SELECT strftime('%s','now')").Scan(&ts).Error
default:
err = DB.Raw("SELECT UNIX_TIMESTAMP()").Scan(&ts).Error
}
if err != nil || ts <= 0 {
return common.GetTimestamp()
}
return ts
}

View File

@@ -268,6 +268,10 @@ func migrateDB() error {
&TwoFA{},
&TwoFABackupCode{},
&Checkin{},
&SubscriptionPlan{},
&SubscriptionOrder{},
&UserSubscription{},
&SubscriptionPreConsumeRecord{},
)
if err != nil {
return err
@@ -302,6 +306,10 @@ func migrateDBFast() error {
{&TwoFA{}, "TwoFA"},
{&TwoFABackupCode{}, "TwoFABackupCode"},
{&Checkin{}, "Checkin"},
{&SubscriptionPlan{}, "SubscriptionPlan"},
{&SubscriptionOrder{}, "SubscriptionOrder"},
{&UserSubscription{}, "UserSubscription"},
{&SubscriptionPreConsumeRecord{}, "SubscriptionPreConsumeRecord"},
}
// 动态计算migration数量确保errChan缓冲区足够大
errChan := make(chan error, len(migrations))

1176
model/subscription.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -204,6 +204,10 @@ func updateUserGroupCache(userId int, group string) error {
return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
}
func UpdateUserGroupCache(userId int, group string) error {
return updateUserGroupCache(userId, group)
}
func updateUserNameCache(userId int, username string) error {
if !common.RedisEnabled {
return nil

View File

@@ -113,9 +113,26 @@ type RelayInfo struct {
UserQuota int
RelayFormat types.RelayFormat
SendResponseCount int
FinalPreConsumedQuota int // 最终预消耗的配额
IsClaudeBetaQuery bool // /v1/messages?beta=true
IsChannelTest bool // channel test request
FinalPreConsumedQuota int // 最终预消耗的配额
// BillingSource indicates whether this request is billed from wallet quota or subscription.
// "" or "wallet" => wallet; "subscription" => subscription
BillingSource string
// SubscriptionId is the user_subscriptions.id used when BillingSource == "subscription"
SubscriptionId int
// SubscriptionPreConsumed is the amount pre-consumed on subscription item (quota units or 1)
SubscriptionPreConsumed int64
// SubscriptionPostDelta is the post-consume delta applied to amount_used (quota units; can be negative).
SubscriptionPostDelta int64
// SubscriptionPlanId / SubscriptionPlanTitle are used for logging/UI display.
SubscriptionPlanId int
SubscriptionPlanTitle string
// RequestId is used for idempotent pre-consume/refund
RequestId string
// SubscriptionAmountTotal / SubscriptionAmountUsedAfterPreConsume are used to compute remaining in logs.
SubscriptionAmountTotal int64
SubscriptionAmountUsedAfterPreConsume int64
IsClaudeBetaQuery bool // /v1/messages?beta=true
IsChannelTest bool // channel test request
PriceData types.PriceData
@@ -400,9 +417,14 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
// firstResponseTime = time.Now() - 1 second
reqId := common.GetContextKeyString(c, common.RequestIdKey)
if reqId == "" {
reqId = common.GetTimeString() + common.GetRandomString(8)
}
info := &RelayInfo{
Request: request,
RequestId: reqId,
UserId: common.GetContextKeyInt(c, constant.ContextKeyUserId),
UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),

View File

@@ -58,7 +58,7 @@ func SetApiRouter(router *gin.Engine) {
userRoute.POST("/passkey/login/finish", middleware.CriticalRateLimit(), controller.PasskeyLoginFinish)
//userRoute.POST("/tokenlog", middleware.CriticalRateLimit(), controller.TokenLog)
userRoute.GET("/logout", controller.Logout)
userRoute.GET("/epay/notify", controller.EpayNotify)
userRoute.POST("/epay/notify", controller.EpayNotify)
userRoute.GET("/groups", controller.GetUserGroups)
selfRoute := userRoute.Group("/")
@@ -119,6 +119,38 @@ func SetApiRouter(router *gin.Engine) {
adminRoute.DELETE("/:id/2fa", controller.AdminDisable2FA)
}
}
// Subscription billing (plans, purchase, admin management)
subscriptionRoute := apiRouter.Group("/subscription")
subscriptionRoute.Use(middleware.UserAuth())
{
subscriptionRoute.GET("/plans", controller.GetSubscriptionPlans)
subscriptionRoute.GET("/self", controller.GetSubscriptionSelf)
subscriptionRoute.PUT("/self/preference", controller.UpdateSubscriptionPreference)
subscriptionRoute.POST("/epay/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestEpay)
subscriptionRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestStripePay)
subscriptionRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestCreemPay)
}
subscriptionAdminRoute := apiRouter.Group("/subscription/admin")
subscriptionAdminRoute.Use(middleware.AdminAuth())
{
subscriptionAdminRoute.GET("/plans", controller.AdminListSubscriptionPlans)
subscriptionAdminRoute.POST("/plans", controller.AdminCreateSubscriptionPlan)
subscriptionAdminRoute.PUT("/plans/:id", controller.AdminUpdateSubscriptionPlan)
subscriptionAdminRoute.PATCH("/plans/:id", controller.AdminUpdateSubscriptionPlanStatus)
subscriptionAdminRoute.POST("/bind", controller.AdminBindSubscription)
// User subscription management (admin)
subscriptionAdminRoute.GET("/users/:id/subscriptions", controller.AdminListUserSubscriptions)
subscriptionAdminRoute.POST("/users/:id/subscriptions", controller.AdminCreateUserSubscription)
subscriptionAdminRoute.POST("/user_subscriptions/:id/invalidate", controller.AdminInvalidateUserSubscription)
subscriptionAdminRoute.DELETE("/user_subscriptions/:id", controller.AdminDeleteUserSubscription)
}
// Subscription payment callbacks (no auth)
apiRouter.POST("/subscription/epay/notify", controller.SubscriptionEpayNotify)
apiRouter.GET("/subscription/epay/return", controller.SubscriptionEpayReturn)
apiRouter.POST("/subscription/epay/return", controller.SubscriptionEpayReturn)
optionRoute := apiRouter.Group("/option")
optionRoute.Use(middleware.RootAuth())
{

106
service/billing.go Normal file
View File

@@ -0,0 +1,106 @@
package service
import (
"fmt"
"net/http"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
)
const (
BillingSourceWallet = "wallet"
BillingSourceSubscription = "subscription"
)
// PreConsumeBilling decides whether to pre-consume from subscription or wallet based on user preference.
// It also always pre-consumes token quota in quota units (same as legacy flow).
func PreConsumeBilling(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) *types.NewAPIError {
if relayInfo == nil {
return types.NewError(fmt.Errorf("relayInfo is nil"), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
}
pref := common.NormalizeBillingPreference(relayInfo.UserSetting.BillingPreference)
trySubscription := func() *types.NewAPIError {
quotaType := 0
// For total quota: consume preConsumedQuota quota units.
subConsume := int64(preConsumedQuota)
if subConsume <= 0 {
subConsume = 1
}
// Pre-consume token quota in quota units to keep token limits consistent.
if preConsumedQuota > 0 {
if err := PreConsumeTokenQuota(relayInfo, preConsumedQuota); err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodePreConsumeTokenQuotaFailed, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
}
}
res, err := model.PreConsumeUserSubscription(relayInfo.RequestId, relayInfo.UserId, relayInfo.OriginModelName, quotaType, subConsume)
if err != nil {
// revert token pre-consume when subscription fails
if preConsumedQuota > 0 && !relayInfo.IsPlayground {
_ = model.IncreaseTokenQuota(relayInfo.TokenId, relayInfo.TokenKey, preConsumedQuota)
}
errMsg := err.Error()
if strings.Contains(errMsg, "no active subscription") || strings.Contains(errMsg, "subscription quota insufficient") {
return types.NewErrorWithStatusCode(fmt.Errorf("订阅额度不足或未配置订阅: %s", errMsg), types.ErrorCodeInsufficientUserQuota, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
}
return types.NewErrorWithStatusCode(fmt.Errorf("订阅预扣失败: %s", errMsg), types.ErrorCodeQueryDataError, http.StatusInternalServerError)
}
relayInfo.BillingSource = BillingSourceSubscription
relayInfo.SubscriptionId = res.UserSubscriptionId
relayInfo.SubscriptionPreConsumed = res.PreConsumed
relayInfo.SubscriptionPostDelta = 0
relayInfo.SubscriptionAmountTotal = res.AmountTotal
relayInfo.SubscriptionAmountUsedAfterPreConsume = res.AmountUsedAfter
if planInfo, err := model.GetSubscriptionPlanInfoByUserSubscriptionId(res.UserSubscriptionId); err == nil && planInfo != nil {
relayInfo.SubscriptionPlanId = planInfo.PlanId
relayInfo.SubscriptionPlanTitle = planInfo.PlanTitle
}
relayInfo.FinalPreConsumedQuota = preConsumedQuota
logger.LogInfo(c, fmt.Sprintf("用户 %d 使用订阅计费预扣:订阅=%dtoken_quota=%d", relayInfo.UserId, res.PreConsumed, preConsumedQuota))
return nil
}
tryWallet := func() *types.NewAPIError {
relayInfo.BillingSource = BillingSourceWallet
relayInfo.SubscriptionId = 0
relayInfo.SubscriptionPreConsumed = 0
return PreConsumeQuota(c, preConsumedQuota, relayInfo)
}
switch pref {
case "subscription_only":
return trySubscription()
case "wallet_only":
return tryWallet()
case "wallet_first":
if err := tryWallet(); err != nil {
// only fallback for insufficient wallet quota
if err.GetErrorCode() == types.ErrorCodeInsufficientUserQuota {
return trySubscription()
}
return err
}
return nil
case "subscription_first":
fallthrough
default:
if err := trySubscription(); err != nil {
// fallback only when subscription not available/insufficient
if err.GetErrorCode() == types.ErrorCodeInsufficientUserQuota {
return tryWallet()
}
return err
}
return nil
}
}

View File

@@ -73,9 +73,64 @@ func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, m
other["admin_info"] = adminInfo
appendRequestPath(ctx, relayInfo, other)
appendRequestConversionChain(relayInfo, other)
appendBillingInfo(relayInfo, other)
return other
}
func appendBillingInfo(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
if relayInfo == nil || other == nil {
return
}
// billing_source: "wallet" or "subscription"
if relayInfo.BillingSource != "" {
other["billing_source"] = relayInfo.BillingSource
}
if relayInfo.UserSetting.BillingPreference != "" {
other["billing_preference"] = relayInfo.UserSetting.BillingPreference
}
if relayInfo.BillingSource == "subscription" {
if relayInfo.SubscriptionId != 0 {
other["subscription_id"] = relayInfo.SubscriptionId
}
if relayInfo.SubscriptionPreConsumed > 0 {
other["subscription_pre_consumed"] = relayInfo.SubscriptionPreConsumed
}
// post_delta: settlement delta applied after actual usage is known (can be negative for refund)
if relayInfo.SubscriptionPostDelta != 0 {
other["subscription_post_delta"] = relayInfo.SubscriptionPostDelta
}
if relayInfo.SubscriptionPlanId != 0 {
other["subscription_plan_id"] = relayInfo.SubscriptionPlanId
}
if relayInfo.SubscriptionPlanTitle != "" {
other["subscription_plan_title"] = relayInfo.SubscriptionPlanTitle
}
// Compute "this request" subscription consumed + remaining
consumed := relayInfo.SubscriptionPreConsumed + relayInfo.SubscriptionPostDelta
usedFinal := relayInfo.SubscriptionAmountUsedAfterPreConsume + relayInfo.SubscriptionPostDelta
if consumed < 0 {
consumed = 0
}
if usedFinal < 0 {
usedFinal = 0
}
if relayInfo.SubscriptionAmountTotal > 0 {
remain := relayInfo.SubscriptionAmountTotal - usedFinal
if remain < 0 {
remain = 0
}
other["subscription_total"] = relayInfo.SubscriptionAmountTotal
other["subscription_used"] = usedFinal
other["subscription_remain"] = remain
}
if consumed > 0 {
other["subscription_consumed"] = consumed
}
// Wallet quota is not deducted when billed from subscription.
other["wallet_quota_deducted"] = 0
}
}
func appendRequestConversionChain(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
if relayInfo == nil || other == nil {
return

View File

@@ -3,6 +3,7 @@ package service
import (
"fmt"
"net/http"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
@@ -15,17 +16,61 @@ import (
)
func ReturnPreConsumedQuota(c *gin.Context, relayInfo *relaycommon.RelayInfo) {
if relayInfo.FinalPreConsumedQuota != 0 {
logger.LogInfo(c, fmt.Sprintf("用户 %d 请求失败, 返还预扣费额度 %s", relayInfo.UserId, logger.FormatQuota(relayInfo.FinalPreConsumedQuota)))
gopool.Go(func() {
relayInfoCopy := *relayInfo
// Always refund subscription pre-consumed (can be non-zero even when FinalPreConsumedQuota is 0)
needRefundSub := relayInfo.BillingSource == BillingSourceSubscription && relayInfo.SubscriptionId != 0 && relayInfo.SubscriptionPreConsumed > 0
needRefundToken := relayInfo.FinalPreConsumedQuota != 0
if !needRefundSub && !needRefundToken {
return
}
logger.LogInfo(c, fmt.Sprintf("用户 %d 请求失败, 返还预扣费token_quota=%s, subscription=%d",
relayInfo.UserId,
logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
relayInfo.SubscriptionPreConsumed,
))
gopool.Go(func() {
relayInfoCopy := *relayInfo
if relayInfoCopy.BillingSource == BillingSourceSubscription {
if needRefundSub {
if err := refundWithRetry(func() error {
return model.RefundSubscriptionPreConsume(relayInfoCopy.RequestId)
}); err != nil {
common.SysLog("error refund subscription pre-consume: " + err.Error())
}
}
// refund token quota only
if needRefundToken && !relayInfoCopy.IsPlayground {
_ = model.IncreaseTokenQuota(relayInfoCopy.TokenId, relayInfoCopy.TokenKey, relayInfoCopy.FinalPreConsumedQuota)
}
return
}
// wallet refund uses existing path (user quota + token quota)
if needRefundToken {
err := PostConsumeQuota(&relayInfoCopy, -relayInfoCopy.FinalPreConsumedQuota, 0, false)
if err != nil {
common.SysLog("error return pre-consumed quota: " + err.Error())
}
})
}
})
}
func refundWithRetry(fn func() error) error {
if fn == nil {
return nil
}
const maxAttempts = 3
var lastErr error
for i := 0; i < maxAttempts; i++ {
if err := fn(); err == nil {
return nil
} else {
lastErr = err
}
if i < maxAttempts-1 {
time.Sleep(time.Duration(200*(i+1)) * time.Millisecond)
}
}
return lastErr
}
// PreConsumeQuota checks if the user has enough quota to pre-consume.

View File

@@ -503,13 +503,28 @@ func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error {
func PostConsumeQuota(relayInfo *relaycommon.RelayInfo, quota int, preConsumedQuota int, sendEmail bool) (err error) {
if quota > 0 {
err = model.DecreaseUserQuota(relayInfo.UserId, quota)
// 1) Consume from wallet quota OR subscription item
if relayInfo != nil && relayInfo.BillingSource == BillingSourceSubscription {
if relayInfo.SubscriptionId == 0 {
return errors.New("subscription id is missing")
}
delta := int64(quota)
if delta != 0 {
if err := model.PostConsumeUserSubscriptionDelta(relayInfo.SubscriptionId, delta); err != nil {
return err
}
relayInfo.SubscriptionPostDelta += delta
}
} else {
err = model.IncreaseUserQuota(relayInfo.UserId, -quota, false)
}
if err != nil {
return err
// Wallet
if quota > 0 {
err = model.DecreaseUserQuota(relayInfo.UserId, quota)
} else {
err = model.IncreaseUserQuota(relayInfo.UserId, -quota, false)
}
if err != nil {
return err
}
}
if !relayInfo.IsPlayground {

View File

@@ -0,0 +1,93 @@
package service
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/bytedance/gopkg/util/gopool"
)
const (
subscriptionResetTickInterval = 1 * time.Minute
subscriptionResetBatchSize = 300
subscriptionCleanupInterval = 30 * time.Minute
)
var (
subscriptionResetOnce sync.Once
subscriptionResetRunning atomic.Bool
subscriptionCleanupLast atomic.Int64
)
func StartSubscriptionQuotaResetTask() {
subscriptionResetOnce.Do(func() {
if !common.IsMasterNode {
return
}
gopool.Go(func() {
logger.LogInfo(context.Background(), fmt.Sprintf("subscription quota reset task started: tick=%s", subscriptionResetTickInterval))
ticker := time.NewTicker(subscriptionResetTickInterval)
defer ticker.Stop()
runSubscriptionQuotaResetOnce()
for range ticker.C {
runSubscriptionQuotaResetOnce()
}
})
})
}
func runSubscriptionQuotaResetOnce() {
if !subscriptionResetRunning.CompareAndSwap(false, true) {
return
}
defer subscriptionResetRunning.Store(false)
ctx := context.Background()
totalReset := 0
totalExpired := 0
for {
n, err := model.ExpireDueSubscriptions(subscriptionResetBatchSize)
if err != nil {
logger.LogWarn(ctx, fmt.Sprintf("subscription expire task failed: %v", err))
return
}
if n == 0 {
break
}
totalExpired += n
if n < subscriptionResetBatchSize {
break
}
}
for {
n, err := model.ResetDueSubscriptions(subscriptionResetBatchSize)
if err != nil {
logger.LogWarn(ctx, fmt.Sprintf("subscription quota reset task failed: %v", err))
return
}
if n == 0 {
break
}
totalReset += n
if n < subscriptionResetBatchSize {
break
}
}
lastCleanup := time.Unix(subscriptionCleanupLast.Load(), 0)
if time.Since(lastCleanup) >= subscriptionCleanupInterval {
if _, err := model.CleanupSubscriptionPreConsumeRecords(7 * 24 * 3600); err == nil {
subscriptionCleanupLast.Store(time.Now().Unix())
}
}
if common.DebugEnabled && (totalReset > 0 || totalExpired > 0) {
logger.LogDebug(ctx, "subscription maintenance: reset_count=%d, expired_count=%d", totalReset, totalExpired)
}
}

View File

@@ -44,6 +44,7 @@ import Task from './pages/Task';
import ModelPage from './pages/Model';
import ModelDeploymentPage from './pages/ModelDeployment';
import Playground from './pages/Playground';
import Subscription from './pages/Subscription';
import OAuth2Callback from './components/auth/OAuth2Callback';
import PersonalSetting from './components/settings/PersonalSetting';
import Setup from './pages/Setup';
@@ -117,6 +118,14 @@ function App() {
</AdminRoute>
}
/>
<Route
path='/console/subscription'
element={
<AdminRoute>
<Subscription />
</AdminRoute>
}
/>
<Route
path='/console/channel'
element={

View File

@@ -37,6 +37,7 @@ const routerMap = {
redemption: '/console/redemption',
topup: '/console/topup',
user: '/console/user',
subscription: '/console/subscription',
log: '/console/log',
midjourney: '/console/midjourney',
setting: '/console/setting',
@@ -152,6 +153,12 @@ const SiderBar = ({ onNavigate = () => {} }) => {
to: '/channel',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('订阅管理'),
itemKey: 'subscription',
to: '/subscription',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('模型管理'),
itemKey: 'models',

View File

@@ -0,0 +1,38 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Button } from '@douyinfe/semi-ui';
const SubscriptionsActions = ({ openCreate, t }) => {
return (
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='primary'
className='w-full md:w-auto'
onClick={openCreate}
size='small'
>
{t('新建套餐')}
</Button>
</div>
);
};
export default SubscriptionsActions;

View File

@@ -0,0 +1,357 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Button,
Modal,
Space,
Tag,
Typography,
Popover,
Divider,
Badge,
Tooltip,
} from '@douyinfe/semi-ui';
import { renderQuota } from '../../../helpers';
import { convertUSDToCurrency } from '../../../helpers/render';
const { Text } = Typography;
function formatDuration(plan, t) {
if (!plan) return '';
const u = plan.duration_unit || 'month';
if (u === 'custom') {
return `${t('自定义')} ${plan.custom_seconds || 0}s`;
}
const unitMap = {
year: t('年'),
month: t('月'),
day: t('日'),
hour: t('小时'),
};
return `${plan.duration_value || 0}${unitMap[u] || u}`;
}
function formatResetPeriod(plan, t) {
const period = plan?.quota_reset_period || 'never';
if (period === 'daily') return t('每天');
if (period === 'weekly') return t('每周');
if (period === 'monthly') return t('每月');
if (period === 'custom') {
const seconds = Number(plan?.quota_reset_custom_seconds || 0);
if (seconds >= 86400) return `${Math.floor(seconds / 86400)} ${t('天')}`;
if (seconds >= 3600) return `${Math.floor(seconds / 3600)} ${t('小时')}`;
if (seconds >= 60) return `${Math.floor(seconds / 60)} ${t('分钟')}`;
return `${seconds} ${t('秒')}`;
}
return t('不重置');
}
const renderPlanTitle = (text, record, t) => {
const subtitle = record?.plan?.subtitle;
const plan = record?.plan;
const popoverContent = (
<div style={{ width: 260 }}>
<Text strong>{text}</Text>
{subtitle && (
<Text type='tertiary' style={{ display: 'block', marginTop: 4 }}>
{subtitle}
</Text>
)}
<Divider margin={12} />
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
<Text type='tertiary'>{t('价格')}</Text>
<Text strong style={{ color: 'var(--semi-color-success)' }}>
{convertUSDToCurrency(Number(plan?.price_amount || 0), 2)}
</Text>
<Text type='tertiary'>{t('总额度')}</Text>
{plan?.total_amount > 0 ? (
<Tooltip content={`${t('原生额度')}${plan.total_amount}`}>
<Text>{renderQuota(plan.total_amount)}</Text>
</Tooltip>
) : (
<Text>{t('不限')}</Text>
)}
<Text type='tertiary'>{t('升级分组')}</Text>
<Text>{plan?.upgrade_group ? plan.upgrade_group : t('不升级')}</Text>
<Text type='tertiary'>{t('购买上限')}</Text>
<Text>
{plan?.max_purchase_per_user > 0
? plan.max_purchase_per_user
: t('不限')}
</Text>
<Text type='tertiary'>{t('有效期')}</Text>
<Text>{formatDuration(plan, t)}</Text>
<Text type='tertiary'>{t('重置')}</Text>
<Text>{formatResetPeriod(plan, t)}</Text>
</div>
</div>
);
return (
<Popover content={popoverContent} position='rightTop' showArrow>
<div style={{ cursor: 'pointer', maxWidth: 180 }}>
<Text strong ellipsis={{ showTooltip: false }}>
{text}
</Text>
{subtitle && (
<Text
type='tertiary'
ellipsis={{ showTooltip: false }}
style={{ display: 'block' }}
>
{subtitle}
</Text>
)}
</div>
</Popover>
);
};
const renderPrice = (text) => {
return (
<Text strong style={{ color: 'var(--semi-color-success)' }}>
{convertUSDToCurrency(Number(text || 0), 2)}
</Text>
);
};
const renderPurchaseLimit = (text, record, t) => {
const limit = Number(record?.plan?.max_purchase_per_user || 0);
return (
<Text type={limit > 0 ? 'secondary' : 'tertiary'}>
{limit > 0 ? limit : t('不限')}
</Text>
);
};
const renderDuration = (text, record, t) => {
return <Text type='secondary'>{formatDuration(record?.plan, t)}</Text>;
};
const renderEnabled = (text, record, t) => {
return text ? (
<Tag
color='white'
shape='circle'
type='light'
prefixIcon={<Badge dot type='success' />}
>
{t('启用')}
</Tag>
) : (
<Tag
color='white'
shape='circle'
type='light'
prefixIcon={<Badge dot type='danger' />}
>
{t('禁用')}
</Tag>
);
};
const renderTotalAmount = (text, record, t) => {
const total = Number(record?.plan?.total_amount || 0);
return (
<Text type={total > 0 ? 'secondary' : 'tertiary'}>
{total > 0 ? (
<Tooltip content={`${t('原生额度')}${total}`}>
<span>{renderQuota(total)}</span>
</Tooltip>
) : (
t('不限')
)}
</Text>
);
};
const renderUpgradeGroup = (text, record, t) => {
const group = record?.plan?.upgrade_group || '';
return (
<Text type={group ? 'secondary' : 'tertiary'}>
{group ? group : t('不升级')}
</Text>
);
};
const renderResetPeriod = (text, record, t) => {
const period = record?.plan?.quota_reset_period || 'never';
const isNever = period === 'never';
return (
<Text type={isNever ? 'tertiary' : 'secondary'}>
{formatResetPeriod(record?.plan, t)}
</Text>
);
};
const renderPaymentConfig = (text, record, t, enableEpay) => {
const hasStripe = !!record?.plan?.stripe_price_id;
const hasCreem = !!record?.plan?.creem_product_id;
const hasEpay = !!enableEpay;
return (
<Space spacing={4}>
{hasStripe && (
<Tag color='violet' shape='circle'>
Stripe
</Tag>
)}
{hasCreem && (
<Tag color='cyan' shape='circle'>
Creem
</Tag>
)}
{hasEpay && (
<Tag color='light-green' shape='circle'>
{t('易支付')}
</Tag>
)}
</Space>
);
};
const renderOperations = (text, record, { openEdit, setPlanEnabled, t }) => {
const isEnabled = record?.plan?.enabled;
const handleToggle = () => {
if (isEnabled) {
Modal.confirm({
title: t('确认禁用'),
content: t('禁用后用户端不再展示,但历史订单不受影响。是否继续?'),
centered: true,
onOk: () => setPlanEnabled(record, false),
});
} else {
Modal.confirm({
title: t('确认启用'),
content: t('启用后套餐将在用户端展示。是否继续?'),
centered: true,
onOk: () => setPlanEnabled(record, true),
});
}
};
return (
<Space spacing={8}>
<Button
theme='light'
type='tertiary'
size='small'
onClick={() => openEdit(record)}
>
{t('编辑')}
</Button>
{isEnabled ? (
<Button theme='light' type='danger' size='small' onClick={handleToggle}>
{t('禁用')}
</Button>
) : (
<Button
theme='light'
type='primary'
size='small'
onClick={handleToggle}
>
{t('启用')}
</Button>
)}
</Space>
);
};
export const getSubscriptionsColumns = ({
t,
openEdit,
setPlanEnabled,
enableEpay,
}) => {
return [
{
title: 'ID',
dataIndex: ['plan', 'id'],
width: 60,
render: (text) => <Text type='tertiary'>#{text}</Text>,
},
{
title: t('套餐'),
dataIndex: ['plan', 'title'],
width: 200,
render: (text, record) => renderPlanTitle(text, record, t),
},
{
title: t('价格'),
dataIndex: ['plan', 'price_amount'],
width: 100,
render: (text) => renderPrice(text),
},
{
title: t('购买上限'),
width: 90,
render: (text, record) => renderPurchaseLimit(text, record, t),
},
{
title: t('优先级'),
dataIndex: ['plan', 'sort_order'],
width: 80,
render: (text) => <Text type='tertiary'>{Number(text || 0)}</Text>,
},
{
title: t('有效期'),
width: 100,
render: (text, record) => renderDuration(text, record, t),
},
{
title: t('重置'),
width: 80,
render: (text, record) => renderResetPeriod(text, record, t),
},
{
title: t('状态'),
dataIndex: ['plan', 'enabled'],
width: 80,
render: (text, record) => renderEnabled(text, record, t),
},
{
title: t('支付渠道'),
width: 180,
render: (text, record) =>
renderPaymentConfig(text, record, t, enableEpay),
},
{
title: t('总额度'),
width: 100,
render: (text, record) => renderTotalAmount(text, record, t),
},
{
title: t('升级分组'),
width: 100,
render: (text, record) => renderUpgradeGroup(text, record, t),
},
{
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 160,
render: (text, record) =>
renderOperations(text, record, { openEdit, setPlanEnabled, t }),
},
];
};

View File

@@ -0,0 +1,44 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Typography } from '@douyinfe/semi-ui';
import { CalendarClock } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const SubscriptionsDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-blue-500'>
<CalendarClock size={16} className='mr-2' />
<Text>{t('订阅管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default SubscriptionsDescription;

View File

@@ -0,0 +1,86 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { getSubscriptionsColumns } from './SubscriptionsColumnDefs';
const SubscriptionsTable = (subscriptionsData) => {
const {
plans,
loading,
compactMode,
openEdit,
setPlanEnabled,
t,
enableEpay,
} = subscriptionsData;
const columns = useMemo(() => {
return getSubscriptionsColumns({
t,
openEdit,
setPlanEnabled,
enableEpay,
});
}, [t, openEdit, setPlanEnabled, enableEpay]);
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<CardTable
columns={tableColumns}
dataSource={plans}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={false}
hidePagination={true}
loading={loading}
rowKey={(row) => row?.plan?.id}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无订阅套餐')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
size='middle'
/>
);
};
export default SubscriptionsTable;

View File

@@ -0,0 +1,103 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useContext } from 'react';
import { Banner } from '@douyinfe/semi-ui';
import CardPro from '../../common/ui/CardPro';
import SubscriptionsTable from './SubscriptionsTable';
import SubscriptionsActions from './SubscriptionsActions';
import SubscriptionsDescription from './SubscriptionsDescription';
import AddEditSubscriptionModal from './modals/AddEditSubscriptionModal';
import { useSubscriptionsData } from '../../../hooks/subscriptions/useSubscriptionsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
import { StatusContext } from '../../../context/Status';
const SubscriptionsPage = () => {
const subscriptionsData = useSubscriptionsData();
const isMobile = useIsMobile();
const [statusState] = useContext(StatusContext);
const enableEpay = !!statusState?.status?.enable_online_topup;
const {
showEdit,
editingPlan,
sheetPlacement,
closeEdit,
refresh,
openCreate,
compactMode,
setCompactMode,
t,
} = subscriptionsData;
return (
<>
<AddEditSubscriptionModal
visible={showEdit}
handleClose={closeEdit}
editingPlan={editingPlan}
placement={sheetPlacement}
refresh={refresh}
t={t}
/>
<CardPro
type='type1'
descriptionArea={
<SubscriptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
{/* Mobile: actions first; Desktop: actions left */}
<div className='order-1 md:order-0 w-full md:w-auto'>
<SubscriptionsActions openCreate={openCreate} t={t} />
</div>
<Banner
type='info'
description={t('Stripe/Creem 需在第三方平台创建商品并填入 ID')}
closeIcon={null}
// Mobile: banner below; Desktop: banner right
className='!rounded-lg order-2 md:order-1'
style={{ maxWidth: '100%' }}
/>
</div>
}
paginationArea={createCardProPagination({
currentPage: subscriptionsData.activePage,
pageSize: subscriptionsData.pageSize,
total: subscriptionsData.planCount,
onPageChange: subscriptionsData.handlePageChange,
onPageSizeChange: subscriptionsData.handlePageSizeChange,
isMobile,
t: subscriptionsData.t,
})}
t={t}
>
<SubscriptionsTable {...subscriptionsData} enableEpay={enableEpay} />
</CardPro>
</>
);
};
export default SubscriptionsPage;

View File

@@ -0,0 +1,553 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef } from 'react';
import {
Avatar,
Button,
Card,
Col,
Form,
Row,
Select,
SideSheet,
Space,
Spin,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import {
IconCalendarClock,
IconClose,
IconCreditCard,
IconSave,
} from '@douyinfe/semi-icons';
import { Clock, RefreshCw } from 'lucide-react';
import { API, showError, showSuccess } from '../../../../helpers';
import {
quotaToDisplayAmount,
displayAmountToQuota,
} from '../../../../helpers/quota';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography;
const durationUnitOptions = [
{ value: 'year', label: '年' },
{ value: 'month', label: '月' },
{ value: 'day', label: '日' },
{ value: 'hour', label: '小时' },
{ value: 'custom', label: '自定义(秒)' },
];
const resetPeriodOptions = [
{ value: 'never', label: '不重置' },
{ value: 'daily', label: '每天' },
{ value: 'weekly', label: '每周' },
{ value: 'monthly', label: '每月' },
{ value: 'custom', label: '自定义(秒)' },
];
const AddEditSubscriptionModal = ({
visible,
handleClose,
editingPlan,
placement = 'left',
refresh,
t,
}) => {
const [loading, setLoading] = useState(false);
const [groupOptions, setGroupOptions] = useState([]);
const [groupLoading, setGroupLoading] = useState(false);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const isEdit = editingPlan?.plan?.id !== undefined;
const formKey = isEdit ? `edit-${editingPlan?.plan?.id}` : 'create';
const getInitValues = () => ({
title: '',
subtitle: '',
price_amount: 0,
currency: 'USD',
duration_unit: 'month',
duration_value: 1,
custom_seconds: 0,
quota_reset_period: 'never',
quota_reset_custom_seconds: 0,
enabled: true,
sort_order: 0,
max_purchase_per_user: 0,
total_amount: 0,
upgrade_group: '',
stripe_price_id: '',
creem_product_id: '',
});
const buildFormValues = () => {
const base = getInitValues();
if (editingPlan?.plan?.id === undefined) return base;
const p = editingPlan.plan || {};
return {
...base,
title: p.title || '',
subtitle: p.subtitle || '',
price_amount: Number(p.price_amount || 0),
currency: 'USD',
duration_unit: p.duration_unit || 'month',
duration_value: Number(p.duration_value || 1),
custom_seconds: Number(p.custom_seconds || 0),
quota_reset_period: p.quota_reset_period || 'never',
quota_reset_custom_seconds: Number(p.quota_reset_custom_seconds || 0),
enabled: p.enabled !== false,
sort_order: Number(p.sort_order || 0),
max_purchase_per_user: Number(p.max_purchase_per_user || 0),
total_amount: Number(
quotaToDisplayAmount(p.total_amount || 0).toFixed(2),
),
upgrade_group: p.upgrade_group || '',
stripe_price_id: p.stripe_price_id || '',
creem_product_id: p.creem_product_id || '',
};
};
useEffect(() => {
if (!visible) return;
setGroupLoading(true);
API.get('/api/group')
.then((res) => {
if (res.data?.success) {
setGroupOptions(res.data?.data || []);
} else {
setGroupOptions([]);
}
})
.catch(() => setGroupOptions([]))
.finally(() => setGroupLoading(false));
}, [visible]);
const submit = async (values) => {
if (!values.title || values.title.trim() === '') {
showError(t('套餐标题不能为空'));
return;
}
setLoading(true);
try {
const payload = {
plan: {
...values,
price_amount: Number(values.price_amount || 0),
currency: 'USD',
duration_value: Number(values.duration_value || 0),
custom_seconds: Number(values.custom_seconds || 0),
quota_reset_period: values.quota_reset_period || 'never',
quota_reset_custom_seconds:
values.quota_reset_period === 'custom'
? Number(values.quota_reset_custom_seconds || 0)
: 0,
sort_order: Number(values.sort_order || 0),
max_purchase_per_user: Number(values.max_purchase_per_user || 0),
total_amount: displayAmountToQuota(values.total_amount),
upgrade_group: values.upgrade_group || '',
},
};
if (editingPlan?.plan?.id) {
const res = await API.put(
`/api/subscription/admin/plans/${editingPlan.plan.id}`,
payload,
);
if (res.data?.success) {
showSuccess(t('更新成功'));
handleClose();
refresh?.();
} else {
showError(res.data?.message || t('更新失败'));
}
} else {
const res = await API.post('/api/subscription/admin/plans', payload);
if (res.data?.success) {
showSuccess(t('创建成功'));
handleClose();
refresh?.();
} else {
showError(res.data?.message || t('创建失败'));
}
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
return (
<>
<SideSheet
placement={placement}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新套餐信息') : t('创建新的订阅套餐')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={visible}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end bg-white'>
<Space>
<Button
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
type='primary'
onClick={handleClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
onCancel={handleClose}
>
<Spin spinning={loading}>
<Form
key={formKey}
initValues={buildFormValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0 mb-4'>
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='blue'
className='mr-2 shadow-md'
>
<IconCalendarClock size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('基本信息')}
</Text>
<div className='text-xs text-gray-600'>
{t('套餐的基本信息和定价')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='title'
label={t('套餐标题')}
placeholder={t('例如:基础套餐')}
required
rules={[
{ required: true, message: t('请输入套餐标题') },
]}
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='subtitle'
label={t('套餐副标题')}
placeholder={t('例如:适合轻度使用')}
showClear
/>
</Col>
<Col span={12}>
<Form.InputNumber
field='price_amount'
label={t('实付金额')}
required
min={0}
precision={2}
rules={[{ required: true, message: t('请输入金额') }]}
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Form.InputNumber
field='total_amount'
label={t('总额度')}
required
min={0}
precision={2}
rules={[{ required: true, message: t('请输入总额度') }]}
extraText={`${t('0 表示不限')} · ${t('原生额度')}${displayAmountToQuota(
values.total_amount,
)}`}
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Form.Select
field='upgrade_group'
label={t('升级分组')}
showClear
loading={groupLoading}
placeholder={t('不升级')}
extraText={t(
'购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。',
)}
>
<Select.Option value=''>{t('不升级')}</Select.Option>
{(groupOptions || []).map((g) => (
<Select.Option key={g} value={g}>
{g}
</Select.Option>
))}
</Form.Select>
</Col>
<Col span={12}>
<Form.Input
field='currency'
label={t('币种')}
disabled
extraText={t('由全站货币展示设置统一控制')}
/>
</Col>
<Col span={12}>
<Form.InputNumber
field='sort_order'
label={t('排序')}
precision={0}
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Form.InputNumber
field='max_purchase_per_user'
label={t('购买上限')}
min={0}
precision={0}
extraText={t('0 表示不限')}
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Form.Switch
field='enabled'
label={t('启用状态')}
size='large'
/>
</Col>
</Row>
</Card>
{/* 有效期设置 */}
<Card className='!rounded-2xl shadow-sm border-0 mb-4'>
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='green'
className='mr-2 shadow-md'
>
<Clock size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('有效期设置')}
</Text>
<div className='text-xs text-gray-600'>
{t('配置套餐的有效时长')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={12}>
<Form.Select
field='duration_unit'
label={t('有效期单位')}
required
rules={[{ required: true }]}
>
{durationUnitOptions.map((o) => (
<Select.Option key={o.value} value={o.value}>
{o.label}
</Select.Option>
))}
</Form.Select>
</Col>
<Col span={12}>
{values.duration_unit === 'custom' ? (
<Form.InputNumber
field='custom_seconds'
label={t('自定义秒数')}
required
min={1}
precision={0}
rules={[{ required: true, message: t('请输入秒数') }]}
style={{ width: '100%' }}
/>
) : (
<Form.InputNumber
field='duration_value'
label={t('有效期数值')}
required
min={1}
precision={0}
rules={[{ required: true, message: t('请输入数值') }]}
style={{ width: '100%' }}
/>
)}
</Col>
</Row>
</Card>
{/* 额度重置 */}
<Card className='!rounded-2xl shadow-sm border-0 mb-4'>
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='orange'
className='mr-2 shadow-md'
>
<RefreshCw size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('额度重置')}
</Text>
<div className='text-xs text-gray-600'>
{t('支持周期性重置套餐权益额度')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={12}>
<Form.Select
field='quota_reset_period'
label={t('重置周期')}
>
{resetPeriodOptions.map((o) => (
<Select.Option key={o.value} value={o.value}>
{o.label}
</Select.Option>
))}
</Form.Select>
</Col>
<Col span={12}>
{values.quota_reset_period === 'custom' ? (
<Form.InputNumber
field='quota_reset_custom_seconds'
label={t('自定义秒数')}
required
min={60}
precision={0}
rules={[{ required: true, message: t('请输入秒数') }]}
style={{ width: '100%' }}
/>
) : (
<Form.InputNumber
field='quota_reset_custom_seconds'
label={t('自定义秒数')}
min={0}
precision={0}
style={{ width: '100%' }}
disabled
/>
)}
</Col>
</Row>
</Card>
{/* 第三方支付配置 */}
<Card className='!rounded-2xl shadow-sm border-0 mb-4'>
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='purple'
className='mr-2 shadow-md'
>
<IconCreditCard size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('第三方支付配置')}
</Text>
<div className='text-xs text-gray-600'>
{t('Stripe/Creem 商品ID可选')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='stripe_price_id'
label='Stripe PriceId'
placeholder='price_...'
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='creem_product_id'
label='Creem ProductId'
placeholder='prod_...'
showClear
/>
</Col>
</Row>
</Card>
</div>
)}
</Form>
</Spin>
</SideSheet>
</>
);
};
export default AddEditSubscriptionModal;

View File

@@ -211,6 +211,18 @@ function renderFirstUseTime(type, t) {
}
}
function renderBillingTag(record, t) {
const other = getLogOther(record.other);
if (other?.billing_source === 'subscription') {
return (
<Tag color='green' shape='circle'>
{t('订阅抵扣')}
</Tag>
);
}
return null;
}
function renderModelName(record, copyText, t) {
let other = getLogOther(record.other);
let modelMapped =
@@ -487,11 +499,20 @@ export const getLogsColumns = ({
title: t('花费'),
dataIndex: 'quota',
render: (text, record, index) => {
return record.type === 0 || record.type === 2 || record.type === 5 ? (
<>{renderQuota(text, 6)}</>
) : (
<></>
);
if (!(record.type === 0 || record.type === 2 || record.type === 5)) {
return <></>;
}
const other = getLogOther(record.other);
const isSubscription = other?.billing_source === 'subscription';
if (isSubscription) {
// Subscription billed: show only tag (no $0), but keep tooltip for equivalent cost.
return (
<Tooltip content={`${t('由订阅抵扣')}${renderQuota(text, 6)}`}>
<span>{renderBillingTag(record, t)}</span>
</Tooltip>
);
}
return <>{renderQuota(text, 6)}</>;
},
},
{
@@ -698,6 +719,10 @@ export const getLogsColumns = ({
other?.is_system_prompt_overwritten,
'openai',
);
// Do not add billing source here; keep details clean.
const summary = [content, text ? `${t('详情')}${text}` : null]
.filter(Boolean)
.join('\n');
return (
<Typography.Paragraph
ellipsis={{
@@ -705,7 +730,7 @@ export const getLogsColumns = ({
}}
style={{ maxWidth: 240, whiteSpace: 'pre-line' }}
>
{content}
{summary}
</Typography.Paragraph>
);
},

View File

@@ -208,6 +208,7 @@ const renderOperations = (
showDeleteModal,
showResetPasskeyModal,
showResetTwoFAModal,
showUserSubscriptionsModal,
t,
},
) => {
@@ -216,6 +217,14 @@ const renderOperations = (
}
const moreMenu = [
{
node: 'item',
name: t('订阅管理'),
onClick: () => showUserSubscriptionsModal(record),
},
{
node: 'divider',
},
{
node: 'item',
name: t('重置 Passkey'),
@@ -299,6 +308,7 @@ export const getUsersColumns = ({
showDeleteModal,
showResetPasskeyModal,
showResetTwoFAModal,
showUserSubscriptionsModal,
}) => {
return [
{
@@ -355,6 +365,7 @@ export const getUsersColumns = ({
showDeleteModal,
showResetPasskeyModal,
showResetTwoFAModal,
showUserSubscriptionsModal,
t,
}),
},

View File

@@ -31,6 +31,7 @@ import EnableDisableUserModal from './modals/EnableDisableUserModal';
import DeleteUserModal from './modals/DeleteUserModal';
import ResetPasskeyModal from './modals/ResetPasskeyModal';
import ResetTwoFAModal from './modals/ResetTwoFAModal';
import UserSubscriptionsModal from './modals/UserSubscriptionsModal';
const UsersTable = (usersData) => {
const {
@@ -61,6 +62,8 @@ const UsersTable = (usersData) => {
const [enableDisableAction, setEnableDisableAction] = useState('');
const [showResetPasskeyModal, setShowResetPasskeyModal] = useState(false);
const [showResetTwoFAModal, setShowResetTwoFAModal] = useState(false);
const [showUserSubscriptionsModal, setShowUserSubscriptionsModal] =
useState(false);
// Modal handlers
const showPromoteUserModal = (user) => {
@@ -94,6 +97,11 @@ const UsersTable = (usersData) => {
setShowResetTwoFAModal(true);
};
const showUserSubscriptionsUserModal = (user) => {
setModalUser(user);
setShowUserSubscriptionsModal(true);
};
// Modal confirm handlers
const handlePromoteConfirm = () => {
manageUser(modalUser.id, 'promote', modalUser);
@@ -132,6 +140,7 @@ const UsersTable = (usersData) => {
showDeleteModal: showDeleteUserModal,
showResetPasskeyModal: showResetPasskeyUserModal,
showResetTwoFAModal: showResetTwoFAUserModal,
showUserSubscriptionsModal: showUserSubscriptionsUserModal,
});
}, [
t,
@@ -143,6 +152,7 @@ const UsersTable = (usersData) => {
showDeleteUserModal,
showResetPasskeyUserModal,
showResetTwoFAUserModal,
showUserSubscriptionsUserModal,
]);
// Handle compact mode by removing fixed positioning
@@ -242,6 +252,14 @@ const UsersTable = (usersData) => {
user={modalUser}
t={t}
/>
<UserSubscriptionsModal
visible={showUserSubscriptionsModal}
onCancel={() => setShowUserSubscriptionsModal(false)}
user={modalUser}
t={t}
onSuccess={() => refresh?.()}
/>
</>
);
};

View File

@@ -0,0 +1,123 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useState } from 'react';
import { Modal, Select, Space, Typography } from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../../helpers';
const { Text } = Typography;
const BindSubscriptionModal = ({ visible, onCancel, user, t, onSuccess }) => {
const [loading, setLoading] = useState(false);
const [plans, setPlans] = useState([]);
const [selectedPlanId, setSelectedPlanId] = useState(null);
const loadPlans = async () => {
setLoading(true);
try {
const res = await API.get('/api/subscription/admin/plans');
if (res.data?.success) {
setPlans(res.data.data || []);
} else {
showError(res.data?.message || t('加载失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible) {
setSelectedPlanId(null);
loadPlans();
}
}, [visible]);
const planOptions = useMemo(() => {
return (plans || []).map((p) => ({
label: `${p?.plan?.title || ''} (${p?.plan?.currency || 'USD'} ${Number(p?.plan?.price_amount || 0)})`,
value: p?.plan?.id,
}));
}, [plans]);
const bind = async () => {
if (!user?.id) {
showError(t('用户信息缺失'));
return;
}
if (!selectedPlanId) {
showError(t('请选择订阅套餐'));
return;
}
setLoading(true);
try {
const res = await API.post('/api/subscription/admin/bind', {
user_id: user.id,
plan_id: selectedPlanId,
});
if (res.data?.success) {
showSuccess(t('绑定成功'));
onSuccess?.();
onCancel?.();
} else {
showError(res.data?.message || t('绑定失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
return (
<Modal
title={t('绑定订阅套餐')}
visible={visible}
onCancel={onCancel}
onOk={bind}
confirmLoading={loading}
maskClosable={false}
centered
>
<Space vertical style={{ width: '100%' }} spacing='medium'>
<div className='text-sm'>
<Text strong>{t('用户')}</Text>
<Text>{user?.username}</Text>
<Text type='tertiary'> (ID: {user?.id})</Text>
</div>
<Select
placeholder={t('选择订阅套餐')}
optionList={planOptions}
value={selectedPlanId}
onChange={setSelectedPlanId}
loading={loading}
filter
style={{ width: '100%' }}
/>
<div className='text-xs text-gray-500'>
{t('绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。')}
</div>
</Space>
</Modal>
);
};
export default BindSubscriptionModal;

View File

@@ -0,0 +1,433 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useState } from 'react';
import {
Button,
Empty,
Modal,
Select,
SideSheet,
Space,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { IconPlusCircle } from '@douyinfe/semi-icons';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { API, showError, showSuccess } from '../../../../helpers';
import { convertUSDToCurrency } from '../../../../helpers/render';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import CardTable from '../../../common/ui/CardTable';
const { Text } = Typography;
function formatTs(ts) {
if (!ts) return '-';
return new Date(ts * 1000).toLocaleString();
}
function renderStatusTag(sub, t) {
const now = Date.now() / 1000;
const end = sub?.end_time || 0;
const status = sub?.status || '';
const isExpiredByTime = end > 0 && end < now;
const isActive = status === 'active' && !isExpiredByTime;
if (isActive) {
return (
<Tag color='green' shape='circle' size='small'>
{t('生效')}
</Tag>
);
}
if (status === 'cancelled') {
return (
<Tag color='grey' shape='circle' size='small'>
{t('已作废')}
</Tag>
);
}
return (
<Tag color='grey' shape='circle' size='small'>
{t('已过期')}
</Tag>
);
}
const UserSubscriptionsModal = ({ visible, onCancel, user, t, onSuccess }) => {
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const [creating, setCreating] = useState(false);
const [plansLoading, setPlansLoading] = useState(false);
const [plans, setPlans] = useState([]);
const [selectedPlanId, setSelectedPlanId] = useState(null);
const [subs, setSubs] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 10;
const planTitleMap = useMemo(() => {
const map = new Map();
(plans || []).forEach((p) => {
const id = p?.plan?.id;
const title = p?.plan?.title;
if (id) map.set(id, title || `#${id}`);
});
return map;
}, [plans]);
const pagedSubs = useMemo(() => {
const start = Math.max(0, (Number(currentPage || 1) - 1) * pageSize);
const end = start + pageSize;
return (subs || []).slice(start, end);
}, [subs, currentPage]);
const planOptions = useMemo(() => {
return (plans || []).map((p) => ({
label: `${p?.plan?.title || ''} (${convertUSDToCurrency(
Number(p?.plan?.price_amount || 0),
2,
)})`,
value: p?.plan?.id,
}));
}, [plans]);
const loadPlans = async () => {
setPlansLoading(true);
try {
const res = await API.get('/api/subscription/admin/plans');
if (res.data?.success) {
setPlans(res.data.data || []);
} else {
showError(res.data?.message || t('加载失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setPlansLoading(false);
}
};
const loadUserSubscriptions = async () => {
if (!user?.id) return;
setLoading(true);
try {
const res = await API.get(
`/api/subscription/admin/users/${user.id}/subscriptions`,
);
if (res.data?.success) {
const next = res.data.data || [];
setSubs(next);
setCurrentPage(1);
} else {
showError(res.data?.message || t('加载失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (!visible) return;
setSelectedPlanId(null);
setCurrentPage(1);
loadPlans();
loadUserSubscriptions();
}, [visible]);
const handlePageChange = (page) => {
setCurrentPage(page);
};
const createSubscription = async () => {
if (!user?.id) {
showError(t('用户信息缺失'));
return;
}
if (!selectedPlanId) {
showError(t('请选择订阅套餐'));
return;
}
setCreating(true);
try {
const res = await API.post(
`/api/subscription/admin/users/${user.id}/subscriptions`,
{
plan_id: selectedPlanId,
},
);
if (res.data?.success) {
const msg = res.data?.data?.message;
showSuccess(msg ? msg : t('新增成功'));
setSelectedPlanId(null);
await loadUserSubscriptions();
onSuccess?.();
} else {
showError(res.data?.message || t('新增失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setCreating(false);
}
};
const invalidateSubscription = (subId) => {
Modal.confirm({
title: t('确认作废'),
content: t('作废后该订阅将立即失效,历史记录不受影响。是否继续?'),
centered: true,
onOk: async () => {
try {
const res = await API.post(
`/api/subscription/admin/user_subscriptions/${subId}/invalidate`,
);
if (res.data?.success) {
const msg = res.data?.data?.message;
showSuccess(msg ? msg : t('已作废'));
await loadUserSubscriptions();
onSuccess?.();
} else {
showError(res.data?.message || t('操作失败'));
}
} catch (e) {
showError(t('请求失败'));
}
},
});
};
const deleteSubscription = (subId) => {
Modal.confirm({
title: t('确认删除'),
content: t('删除会彻底移除该订阅记录(含权益明细)。是否继续?'),
centered: true,
okType: 'danger',
onOk: async () => {
try {
const res = await API.delete(
`/api/subscription/admin/user_subscriptions/${subId}`,
);
if (res.data?.success) {
const msg = res.data?.data?.message;
showSuccess(msg ? msg : t('已删除'));
await loadUserSubscriptions();
onSuccess?.();
} else {
showError(res.data?.message || t('删除失败'));
}
} catch (e) {
showError(t('请求失败'));
}
},
});
};
const columns = useMemo(() => {
return [
{
title: 'ID',
dataIndex: ['subscription', 'id'],
key: 'id',
width: 70,
},
{
title: t('套餐'),
key: 'plan',
width: 180,
render: (_, record) => {
const sub = record?.subscription;
const planId = sub?.plan_id;
const title =
planTitleMap.get(planId) || (planId ? `#${planId}` : '-');
return (
<div className='min-w-0'>
<div className='font-medium truncate'>{title}</div>
<div className='text-xs text-gray-500'>
{t('来源')}: {sub?.source || '-'}
</div>
</div>
);
},
},
{
title: t('状态'),
key: 'status',
width: 90,
render: (_, record) => renderStatusTag(record?.subscription, t),
},
{
title: t('有效期'),
key: 'validity',
width: 200,
render: (_, record) => {
const sub = record?.subscription;
return (
<div className='text-xs text-gray-600'>
<div>
{t('开始')}: {formatTs(sub?.start_time)}
</div>
<div>
{t('结束')}: {formatTs(sub?.end_time)}
</div>
</div>
);
},
},
{
title: t('总额度'),
key: 'total',
width: 120,
render: (_, record) => {
const sub = record?.subscription;
const total = Number(sub?.amount_total || 0);
const used = Number(sub?.amount_used || 0);
return (
<Text type={total > 0 ? 'secondary' : 'tertiary'}>
{total > 0 ? `${used}/${total}` : t('不限')}
</Text>
);
},
},
{
title: '',
key: 'operate',
width: 140,
fixed: 'right',
render: (_, record) => {
const sub = record?.subscription;
const now = Date.now() / 1000;
const isExpired =
(sub?.end_time || 0) > 0 && (sub?.end_time || 0) < now;
const isActive = sub?.status === 'active' && !isExpired;
const isCancelled = sub?.status === 'cancelled';
return (
<Space>
<Button
size='small'
type='warning'
theme='light'
disabled={!isActive || isCancelled}
onClick={() => invalidateSubscription(sub?.id)}
>
{t('作废')}
</Button>
<Button
size='small'
type='danger'
theme='light'
onClick={() => deleteSubscription(sub?.id)}
>
{t('删除')}
</Button>
</Space>
);
},
},
];
}, [t, planTitleMap]);
return (
<SideSheet
visible={visible}
placement='right'
width={isMobile ? '100%' : 920}
bodyStyle={{ padding: 0 }}
onCancel={onCancel}
title={
<Space>
<Tag color='blue' shape='circle'>
{t('管理')}
</Tag>
<Typography.Title heading={4} className='m-0'>
{t('用户订阅管理')}
</Typography.Title>
<Text type='tertiary' className='ml-2'>
{user?.username || '-'} (ID: {user?.id || '-'})
</Text>
</Space>
}
>
<div className='p-4'>
{/* 顶部操作栏:新增订阅 */}
<div className='flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4'>
<div className='flex gap-2 flex-1'>
<Select
placeholder={t('选择订阅套餐')}
optionList={planOptions}
value={selectedPlanId}
onChange={setSelectedPlanId}
loading={plansLoading}
filter
style={{ minWidth: isMobile ? undefined : 300, flex: 1 }}
/>
<Button
type='primary'
theme='solid'
icon={<IconPlusCircle />}
loading={creating}
onClick={createSubscription}
>
{t('新增订阅')}
</Button>
</div>
</div>
{/* 订阅列表 */}
<CardTable
columns={columns}
dataSource={pagedSubs}
rowKey={(row) => row?.subscription?.id}
loading={loading}
scroll={{ x: 'max-content' }}
hidePagination={false}
pagination={{
currentPage,
pageSize,
total: subs.length,
pageSizeOpts: [10, 20, 50],
showSizeChanger: false,
onPageChange: handlePageChange,
}}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无订阅记录')}
style={{ padding: 30 }}
/>
}
size='middle'
/>
</div>
</SideSheet>
);
};
export default UserSubscriptionsModal;

View File

@@ -0,0 +1,629 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo, useState } from 'react';
import {
Avatar,
Badge,
Button,
Card,
Divider,
Select,
Skeleton,
Space,
Tag,
Tooltip,
Typography,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess, renderQuota } from '../../helpers';
import { getCurrencyConfig } from '../../helpers/render';
import { Crown, RefreshCw, Sparkles } from 'lucide-react';
import SubscriptionPurchaseModal from './modals/SubscriptionPurchaseModal';
import {
formatSubscriptionDuration,
formatSubscriptionResetPeriod,
} from '../../helpers/subscriptionFormat';
const { Text } = Typography;
// 过滤易支付方式
function getEpayMethods(payMethods = []) {
return (payMethods || []).filter(
(m) => m?.type && m.type !== 'stripe' && m.type !== 'creem',
);
}
// 提交易支付表单
function submitEpayForm({ url, params }) {
const form = document.createElement('form');
form.action = url;
form.method = 'POST';
const isSafari =
navigator.userAgent.indexOf('Safari') > -1 &&
navigator.userAgent.indexOf('Chrome') < 1;
if (!isSafari) form.target = '_blank';
Object.keys(params || {}).forEach((key) => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
const SubscriptionPlansCard = ({
t,
loading = false,
plans = [],
payMethods = [],
enableOnlineTopUp = false,
enableStripeTopUp = false,
enableCreemTopUp = false,
billingPreference,
onChangeBillingPreference,
activeSubscriptions = [],
allSubscriptions = [],
reloadSubscriptionSelf,
}) => {
const [open, setOpen] = useState(false);
const [selectedPlan, setSelectedPlan] = useState(null);
const [paying, setPaying] = useState(false);
const [selectedEpayMethod, setSelectedEpayMethod] = useState('');
const [refreshing, setRefreshing] = useState(false);
const epayMethods = useMemo(() => getEpayMethods(payMethods), [payMethods]);
const openBuy = (p) => {
setSelectedPlan(p);
setSelectedEpayMethod(epayMethods?.[0]?.type || '');
setOpen(true);
};
const closeBuy = () => {
setOpen(false);
setSelectedPlan(null);
setPaying(false);
};
const handleRefresh = async () => {
setRefreshing(true);
try {
await reloadSubscriptionSelf?.();
} finally {
setRefreshing(false);
}
};
const payStripe = async () => {
if (!selectedPlan?.plan?.stripe_price_id) {
showError(t('该套餐未配置 Stripe'));
return;
}
setPaying(true);
try {
const res = await API.post('/api/subscription/stripe/pay', {
plan_id: selectedPlan.plan.id,
});
if (res.data?.message === 'success') {
window.open(res.data.data?.pay_link, '_blank');
showSuccess(t('已打开支付页面'));
closeBuy();
} else {
showError(res.data?.data || res.data?.message || t('支付失败'));
}
} catch (e) {
showError(t('支付请求失败'));
} finally {
setPaying(false);
}
};
const payCreem = async () => {
if (!selectedPlan?.plan?.creem_product_id) {
showError(t('该套餐未配置 Creem'));
return;
}
setPaying(true);
try {
const res = await API.post('/api/subscription/creem/pay', {
plan_id: selectedPlan.plan.id,
});
if (res.data?.message === 'success') {
window.open(res.data.data?.checkout_url, '_blank');
showSuccess(t('已打开支付页面'));
closeBuy();
} else {
showError(res.data?.data || res.data?.message || t('支付失败'));
}
} catch (e) {
showError(t('支付请求失败'));
} finally {
setPaying(false);
}
};
const payEpay = async () => {
if (!selectedEpayMethod) {
showError(t('请选择支付方式'));
return;
}
setPaying(true);
try {
const res = await API.post('/api/subscription/epay/pay', {
plan_id: selectedPlan.plan.id,
payment_method: selectedEpayMethod,
});
if (res.data?.message === 'success') {
submitEpayForm({ url: res.data.url, params: res.data.data });
showSuccess(t('已发起支付'));
closeBuy();
} else {
showError(res.data?.data || res.data?.message || t('支付失败'));
}
} catch (e) {
showError(t('支付请求失败'));
} finally {
setPaying(false);
}
};
// 当前订阅信息 - 支持多个订阅
const hasActiveSubscription = activeSubscriptions.length > 0;
const hasAnySubscription = allSubscriptions.length > 0;
const planPurchaseCountMap = useMemo(() => {
const map = new Map();
(allSubscriptions || []).forEach((sub) => {
const planId = sub?.subscription?.plan_id;
if (!planId) return;
map.set(planId, (map.get(planId) || 0) + 1);
});
return map;
}, [allSubscriptions]);
const planTitleMap = useMemo(() => {
const map = new Map();
(plans || []).forEach((p) => {
const plan = p?.plan;
if (!plan?.id) return;
map.set(plan.id, plan.title || '');
});
return map;
}, [plans]);
const getPlanPurchaseCount = (planId) =>
planPurchaseCountMap.get(planId) || 0;
// 计算单个订阅的剩余天数
const getRemainingDays = (sub) => {
if (!sub?.subscription?.end_time) return 0;
const now = Date.now() / 1000;
const remaining = sub.subscription.end_time - now;
return Math.max(0, Math.ceil(remaining / 86400));
};
// 计算单个订阅的使用进度
const getUsagePercent = (sub) => {
const total = Number(sub?.subscription?.amount_total || 0);
const used = Number(sub?.subscription?.amount_used || 0);
if (total <= 0) return 0;
return Math.round((used / total) * 100);
};
return (
<Card className='!rounded-2xl shadow-sm border-0'>
{/* 卡片头部 */}
<div className='flex items-center justify-between mb-3'>
<div className='flex items-center'>
<Avatar size='small' color='violet' className='mr-3 shadow-md'>
<Crown size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('订阅套餐')}</Text>
<div className='text-xs'>{t('购买订阅获得模型额度/次数')}</div>
</div>
</div>
{/* 扣费策略 - 右上角 */}
<Select
value={billingPreference}
onChange={onChangeBillingPreference}
size='small'
optionList={[
{ value: 'subscription_first', label: t('优先订阅') },
{ value: 'wallet_first', label: t('优先钱包') },
{ value: 'subscription_only', label: t('仅用订阅') },
{ value: 'wallet_only', label: t('仅用钱包') },
]}
/>
</div>
{loading ? (
<div className='space-y-4'>
{/* 我的订阅骨架屏 */}
<Card className='!rounded-xl w-full' bodyStyle={{ padding: '12px' }}>
<div className='flex items-center justify-between mb-3'>
<Skeleton.Title active style={{ width: 100, height: 20 }} />
<Skeleton.Button active style={{ width: 24, height: 24 }} />
</div>
<div className='space-y-2'>
<Skeleton.Paragraph active rows={2} />
</div>
</Card>
{/* 套餐列表骨架屏 */}
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4'>
{[1, 2, 3].map((i) => (
<Card key={i} className='!rounded-xl' bodyStyle={{ padding: 16 }}>
<Skeleton.Title
active
style={{ width: '60%', height: 24, marginBottom: 8 }}
/>
<Skeleton.Paragraph
active
rows={1}
style={{ marginBottom: 12 }}
/>
<div className='text-center py-4'>
<Skeleton.Title
active
style={{ width: '40%', height: 32, margin: '0 auto' }}
/>
</div>
<Skeleton.Paragraph active rows={3} style={{ marginTop: 12 }} />
<Skeleton.Button
active
block
style={{ marginTop: 16, height: 32 }}
/>
</Card>
))}
</div>
</div>
) : (
<Space vertical style={{ width: '100%' }} spacing={8}>
{/* 当前订阅状态 */}
<Card className='!rounded-xl w-full' bodyStyle={{ padding: '12px' }}>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Text strong>{t('我的订阅')}</Text>
{hasActiveSubscription ? (
<Tag
color='white'
size='small'
shape='circle'
prefixIcon={<Badge dot type='success' />}
>
{activeSubscriptions.length} {t('个生效中')}
</Tag>
) : (
<Tag color='white' size='small' shape='circle'>
{t('无生效')}
</Tag>
)}
{allSubscriptions.length > activeSubscriptions.length && (
<Tag color='white' size='small' shape='circle'>
{allSubscriptions.length - activeSubscriptions.length}{' '}
{t('个已过期')}
</Tag>
)}
</div>
<Button
size='small'
theme='light'
type='tertiary'
icon={
<RefreshCw
size={12}
className={refreshing ? 'animate-spin' : ''}
/>
}
onClick={handleRefresh}
loading={refreshing}
/>
</div>
{hasAnySubscription ? (
<>
<Divider margin={8} />
<div className='max-h-64 overflow-y-auto pr-1 semi-table-body'>
{allSubscriptions.map((sub, subIndex) => {
const isLast = subIndex === allSubscriptions.length - 1;
const subscription = sub.subscription;
const totalAmount = Number(subscription?.amount_total || 0);
const usedAmount = Number(subscription?.amount_used || 0);
const remainAmount =
totalAmount > 0
? Math.max(0, totalAmount - usedAmount)
: 0;
const planTitle =
planTitleMap.get(subscription?.plan_id) || '';
const remainDays = getRemainingDays(sub);
const usagePercent = getUsagePercent(sub);
const now = Date.now() / 1000;
const isExpired = (subscription?.end_time || 0) < now;
const isActive =
subscription?.status === 'active' && !isExpired;
return (
<div key={subscription?.id || subIndex}>
{/* 订阅概要 */}
<div className='flex items-center justify-between text-xs mb-2'>
<div className='flex items-center gap-2'>
<span className='font-medium'>
{planTitle
? `${planTitle} · ${t('订阅')} #${subscription?.id}`
: `${t('订阅')} #${subscription?.id}`}
</span>
{isActive ? (
<Tag
color='white'
size='small'
shape='circle'
prefixIcon={<Badge dot type='success' />}
>
{t('生效')}
</Tag>
) : (
<Tag color='white' size='small' shape='circle'>
{t('已过期')}
</Tag>
)}
</div>
{isActive && (
<span className='text-gray-500'>
{t('剩余')} {remainDays} {t('天')}
</span>
)}
</div>
<div className='text-xs text-gray-500 mb-2'>
{isActive ? t('至') : t('过期于')}{' '}
{new Date(
(subscription?.end_time || 0) * 1000,
).toLocaleString()}
</div>
<div className='text-xs text-gray-500 mb-2'>
{t('总额度')}:{' '}
{totalAmount > 0 ? (
<Tooltip
content={`${t('原生额度')}${usedAmount}/${totalAmount} · ${t('剩余')} ${remainAmount}`}
>
<span>
{renderQuota(usedAmount)}/
{renderQuota(totalAmount)} · {t('剩余')}{' '}
{renderQuota(remainAmount)}
</span>
</Tooltip>
) : (
t('不限')
)}
{totalAmount > 0 && (
<span className='ml-2'>
{t('已用')} {usagePercent}%
</span>
)}
</div>
{!isLast && <Divider margin={12} />}
</div>
);
})}
</div>
</>
) : (
<div className='text-xs text-gray-500'>
{t('购买套餐后即可享受模型权益')}
</div>
)}
</Card>
{/* 可购买套餐 - 标准定价卡片 */}
{plans.length > 0 ? (
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4'>
{plans.map((p, index) => {
const plan = p?.plan;
const totalAmount = Number(plan?.total_amount || 0);
const { symbol, rate } = getCurrencyConfig();
const price = Number(plan?.price_amount || 0);
const convertedPrice = price * rate;
const displayPrice = convertedPrice.toFixed(
Number.isInteger(convertedPrice) ? 0 : 2,
);
const isPopular = index === 0 && plans.length > 1;
const limit = Number(plan?.max_purchase_per_user || 0);
const limitLabel = limit > 0 ? `${t('限购')} ${limit}` : null;
const totalLabel =
totalAmount > 0
? `${t('总额度')}: ${renderQuota(totalAmount)}`
: `${t('总额度')}: ${t('不限')}`;
const upgradeLabel = plan?.upgrade_group
? `${t('升级分组')}: ${plan.upgrade_group}`
: null;
const resetLabel =
formatSubscriptionResetPeriod(plan, t) === t('不重置')
? null
: `${t('额度重置')}: ${formatSubscriptionResetPeriod(plan, t)}`;
const planBenefits = [
{
label: `${t('有效期')}: ${formatSubscriptionDuration(plan, t)}`,
},
resetLabel ? { label: resetLabel } : null,
totalAmount > 0
? {
label: totalLabel,
tooltip: `${t('原生额度')}${totalAmount}`,
}
: { label: totalLabel },
limitLabel ? { label: limitLabel } : null,
upgradeLabel ? { label: upgradeLabel } : null,
].filter(Boolean);
return (
<Card
key={plan?.id}
className={`!rounded-xl transition-all hover:shadow-lg ${
isPopular ? 'ring-2 ring-purple-500' : ''
}`}
bodyStyle={{ padding: 0 }}
>
<div className='p-4'>
{/* 推荐标签 */}
{isPopular && (
<div className='text-center mb-2'>
<Tag color='purple' shape='circle' size='small'>
<Sparkles size={10} className='mr-1' />
{t('推荐')}
</Tag>
</div>
)}
{/* 套餐名称 */}
<div className='text-center mb-3'>
<Typography.Title
heading={5}
ellipsis={{ rows: 1, showTooltip: true }}
style={{ margin: 0 }}
>
{plan?.title || t('订阅套餐')}
</Typography.Title>
{plan?.subtitle && (
<Text
type='tertiary'
size='small'
ellipsis={{ rows: 1, showTooltip: true }}
style={{ display: 'block' }}
>
{plan.subtitle}
</Text>
)}
</div>
{/* 价格区域 */}
<div className='text-center py-2'>
<div className='flex items-baseline justify-center'>
<span className='text-xl font-bold text-purple-600'>
{symbol}
</span>
<span className='text-3xl font-bold text-purple-600'>
{displayPrice}
</span>
</div>
</div>
{/* 套餐权益描述 */}
<div className='flex flex-col items-center gap-1 pb-2'>
{planBenefits.map((item) => {
const content = (
<div className='flex items-center gap-2 text-xs text-gray-500'>
<Badge dot type='tertiary' />
<span>{item.label}</span>
</div>
);
if (!item.tooltip) {
return (
<div
key={item.label}
className='w-full flex justify-center'
>
{content}
</div>
);
}
return (
<Tooltip key={item.label} content={item.tooltip}>
<div className='w-full flex justify-center'>
{content}
</div>
</Tooltip>
);
})}
</div>
<Divider margin={12} />
{/* 购买按钮 */}
{(() => {
const count = getPlanPurchaseCount(p?.plan?.id);
const reached = limit > 0 && count >= limit;
const tip = reached
? t('已达到购买上限') + ` (${count}/${limit})`
: '';
const buttonEl = (
<Button
theme='outline'
type='tertiary'
block
disabled={reached}
onClick={() => {
if (!reached) openBuy(p);
}}
>
{reached ? t('已达上限') : t('立即订阅')}
</Button>
);
return reached ? (
<Tooltip content={tip} position='top'>
{buttonEl}
</Tooltip>
) : (
buttonEl
);
})()}
</div>
</Card>
);
})}
</div>
) : (
<div className='text-center text-gray-400 text-sm py-4'>
{t('暂无可购买套餐')}
</div>
)}
</Space>
)}
{/* 购买确认弹窗 */}
<SubscriptionPurchaseModal
t={t}
visible={open}
onCancel={closeBuy}
selectedPlan={selectedPlan}
paying={paying}
selectedEpayMethod={selectedEpayMethod}
setSelectedEpayMethod={setSelectedEpayMethod}
epayMethods={epayMethods}
enableOnlineTopUp={enableOnlineTopUp}
enableStripeTopUp={enableStripeTopUp}
enableCreemTopUp={enableCreemTopUp}
purchaseLimitInfo={
selectedPlan?.plan?.id
? {
limit: Number(selectedPlan?.plan?.max_purchase_per_user || 0),
count: getPlanPurchaseCount(selectedPlan?.plan?.id),
}
: null
}
onPayStripe={payStripe}
onPayCreem={payCreem}
onPayEpay={payEpay}
/>
</Card>
);
};
export default SubscriptionPlansCard;

View File

@@ -35,6 +35,7 @@ import { StatusContext } from '../../context/Status';
import RechargeCard from './RechargeCard';
import InvitationCard from './InvitationCard';
import SubscriptionPlansCard from './SubscriptionPlansCard';
import TransferModal from './modals/TransferModal';
import PaymentConfirmModal from './modals/PaymentConfirmModal';
import TopupHistoryModal from './modals/TopupHistoryModal';
@@ -87,6 +88,14 @@ const TopUp = () => {
// 账单Modal状态
const [openHistory, setOpenHistory] = useState(false);
// 订阅相关
const [subscriptionPlans, setSubscriptionPlans] = useState([]);
const [subscriptionLoading, setSubscriptionLoading] = useState(true);
const [billingPreference, setBillingPreference] =
useState('subscription_first');
const [activeSubscriptions, setActiveSubscriptions] = useState([]);
const [allSubscriptions, setAllSubscriptions] = useState([]);
// 预设充值额度选项
const [presetAmounts, setPresetAmounts] = useState([]);
const [selectedPreset, setSelectedPreset] = useState(null);
@@ -313,6 +322,61 @@ const TopUp = () => {
}
};
const getSubscriptionPlans = async () => {
setSubscriptionLoading(true);
try {
const res = await API.get('/api/subscription/plans');
if (res.data?.success) {
setSubscriptionPlans(res.data.data || []);
}
} catch (e) {
setSubscriptionPlans([]);
} finally {
setSubscriptionLoading(false);
}
};
const getSubscriptionSelf = async () => {
try {
const res = await API.get('/api/subscription/self');
if (res.data?.success) {
setBillingPreference(
res.data.data?.billing_preference || 'subscription_first',
);
// Active subscriptions
const activeSubs = res.data.data?.subscriptions || [];
setActiveSubscriptions(activeSubs);
// All subscriptions (including expired)
const allSubs = res.data.data?.all_subscriptions || [];
setAllSubscriptions(allSubs);
}
} catch (e) {
// ignore
}
};
const updateBillingPreference = async (pref) => {
const previousPref = billingPreference;
setBillingPreference(pref);
try {
const res = await API.put('/api/subscription/self/preference', {
billing_preference: pref,
});
if (res.data?.success) {
showSuccess(t('更新成功'));
const normalizedPref =
res.data?.data?.billing_preference || pref || previousPref;
setBillingPreference(normalizedPref);
} else {
showError(res.data?.message || t('更新失败'));
setBillingPreference(previousPref);
}
} catch (e) {
showError(t('请求失败'));
setBillingPreference(previousPref);
}
};
// 获取充值配置信息
const getTopupInfo = async () => {
try {
@@ -479,6 +543,8 @@ const TopUp = () => {
// 在 statusState 可用时获取充值信息
useEffect(() => {
getTopupInfo().then();
getSubscriptionPlans().then();
getSubscriptionSelf().then();
}, []);
useEffect(() => {
@@ -662,60 +728,72 @@ const TopUp = () => {
)}
</Modal>
{/* 用户信息头部 */}
<div className='space-y-6'>
<div className='grid grid-cols-1 lg:grid-cols-12 gap-6'>
{/* 左侧充值区域 */}
<div className='lg:col-span-7 space-y-6 w-full'>
<RechargeCard
t={t}
enableOnlineTopUp={enableOnlineTopUp}
enableStripeTopUp={enableStripeTopUp}
enableCreemTopUp={enableCreemTopUp}
creemProducts={creemProducts}
creemPreTopUp={creemPreTopUp}
presetAmounts={presetAmounts}
selectedPreset={selectedPreset}
selectPresetAmount={selectPresetAmount}
formatLargeNumber={formatLargeNumber}
priceRatio={priceRatio}
topUpCount={topUpCount}
minTopUp={minTopUp}
renderQuotaWithAmount={renderQuotaWithAmount}
getAmount={getAmount}
setTopUpCount={setTopUpCount}
setSelectedPreset={setSelectedPreset}
renderAmount={renderAmount}
amountLoading={amountLoading}
payMethods={payMethods}
preTopUp={preTopUp}
paymentLoading={paymentLoading}
payWay={payWay}
redemptionCode={redemptionCode}
setRedemptionCode={setRedemptionCode}
topUp={topUp}
isSubmitting={isSubmitting}
topUpLink={topUpLink}
openTopUpLink={openTopUpLink}
userState={userState}
renderQuota={renderQuota}
statusLoading={statusLoading}
topupInfo={topupInfo}
onOpenHistory={handleOpenHistory}
/>
</div>
{/* 主布局区域 */}
<div className='grid grid-cols-1 lg:grid-cols-12 gap-6'>
{/* 左侧 - 订阅套餐 */}
<div className='lg:col-span-7'>
<SubscriptionPlansCard
t={t}
loading={subscriptionLoading}
plans={subscriptionPlans}
payMethods={payMethods}
enableOnlineTopUp={enableOnlineTopUp}
enableStripeTopUp={enableStripeTopUp}
enableCreemTopUp={enableCreemTopUp}
billingPreference={billingPreference}
onChangeBillingPreference={updateBillingPreference}
activeSubscriptions={activeSubscriptions}
allSubscriptions={allSubscriptions}
reloadSubscriptionSelf={getSubscriptionSelf}
/>
</div>
{/* 右侧信息区域 */}
<div className='lg:col-span-5'>
<InvitationCard
t={t}
userState={userState}
renderQuota={renderQuota}
setOpenTransfer={setOpenTransfer}
affLink={affLink}
handleAffLinkClick={handleAffLinkClick}
/>
</div>
{/* 右侧 - 账户充值 + 邀请奖励 */}
<div className='lg:col-span-5 flex flex-col gap-6'>
<RechargeCard
t={t}
enableOnlineTopUp={enableOnlineTopUp}
enableStripeTopUp={enableStripeTopUp}
enableCreemTopUp={enableCreemTopUp}
creemProducts={creemProducts}
creemPreTopUp={creemPreTopUp}
presetAmounts={presetAmounts}
selectedPreset={selectedPreset}
selectPresetAmount={selectPresetAmount}
formatLargeNumber={formatLargeNumber}
priceRatio={priceRatio}
topUpCount={topUpCount}
minTopUp={minTopUp}
renderQuotaWithAmount={renderQuotaWithAmount}
getAmount={getAmount}
setTopUpCount={setTopUpCount}
setSelectedPreset={setSelectedPreset}
renderAmount={renderAmount}
amountLoading={amountLoading}
payMethods={payMethods}
preTopUp={preTopUp}
paymentLoading={paymentLoading}
payWay={payWay}
redemptionCode={redemptionCode}
setRedemptionCode={setRedemptionCode}
topUp={topUp}
isSubmitting={isSubmitting}
topUpLink={topUpLink}
openTopUpLink={openTopUpLink}
userState={userState}
renderQuota={renderQuota}
statusLoading={statusLoading}
topupInfo={topupInfo}
onOpenHistory={handleOpenHistory}
/>
<InvitationCard
t={t}
userState={userState}
renderQuota={renderQuota}
setOpenTransfer={setOpenTransfer}
affLink={affLink}
handleAffLinkClick={handleAffLinkClick}
/>
</div>
</div>
</div>

View File

@@ -0,0 +1,259 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Banner,
Modal,
Typography,
Card,
Button,
Select,
Divider,
Tooltip,
} from '@douyinfe/semi-ui';
import { Crown, CalendarClock, Package } from 'lucide-react';
import { SiStripe } from 'react-icons/si';
import { IconCreditCard } from '@douyinfe/semi-icons';
import { renderQuota } from '../../../helpers';
import { getCurrencyConfig } from '../../../helpers/render';
import {
formatSubscriptionDuration,
formatSubscriptionResetPeriod,
} from '../../../helpers/subscriptionFormat';
const { Text } = Typography;
const SubscriptionPurchaseModal = ({
t,
visible,
onCancel,
selectedPlan,
paying,
selectedEpayMethod,
setSelectedEpayMethod,
epayMethods = [],
enableOnlineTopUp = false,
enableStripeTopUp = false,
enableCreemTopUp = false,
purchaseLimitInfo = null,
onPayStripe,
onPayCreem,
onPayEpay,
}) => {
const plan = selectedPlan?.plan;
const totalAmount = Number(plan?.total_amount || 0);
const { symbol, rate } = getCurrencyConfig();
const price = plan ? Number(plan.price_amount || 0) : 0;
const convertedPrice = price * rate;
const displayPrice = convertedPrice.toFixed(
Number.isInteger(convertedPrice) ? 0 : 2,
);
// 只有当管理员开启支付网关 AND 套餐配置了对应的支付ID时才显示
const hasStripe = enableStripeTopUp && !!plan?.stripe_price_id;
const hasCreem = enableCreemTopUp && !!plan?.creem_product_id;
const hasEpay = enableOnlineTopUp && epayMethods.length > 0;
const hasAnyPayment = hasStripe || hasCreem || hasEpay;
const purchaseLimit = Number(purchaseLimitInfo?.limit || 0);
const purchaseCount = Number(purchaseLimitInfo?.count || 0);
const purchaseLimitReached =
purchaseLimit > 0 && purchaseCount >= purchaseLimit;
return (
<Modal
title={
<div className='flex items-center'>
<Crown className='mr-2' size={18} />
{t('购买订阅套餐')}
</div>
}
visible={visible}
onCancel={onCancel}
footer={null}
size='small'
centered
>
{plan ? (
<div className='space-y-4 pb-10'>
{/* 套餐信息 */}
<Card className='!rounded-xl !border-0 bg-slate-50 dark:bg-slate-800'>
<div className='space-y-3'>
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('套餐名称')}
</Text>
<Typography.Text
ellipsis={{ rows: 1, showTooltip: true }}
className='text-slate-900 dark:text-slate-100'
style={{ maxWidth: 200 }}
>
{plan.title}
</Typography.Text>
</div>
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('有效期')}
</Text>
<div className='flex items-center'>
<CalendarClock size={14} className='mr-1 text-slate-500' />
<Text className='text-slate-900 dark:text-slate-100'>
{formatSubscriptionDuration(plan, t)}
</Text>
</div>
</div>
{formatSubscriptionResetPeriod(plan, t) !== t('不重置') && (
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('重置周期')}
</Text>
<Text className='text-slate-900 dark:text-slate-100'>
{formatSubscriptionResetPeriod(plan, t)}
</Text>
</div>
)}
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('总额度')}
</Text>
<div className='flex items-center'>
<Package size={14} className='mr-1 text-slate-500' />
{totalAmount > 0 ? (
<Tooltip content={`${t('原生额度')}${totalAmount}`}>
<Text className='text-slate-900 dark:text-slate-100'>
{renderQuota(totalAmount)}
</Text>
</Tooltip>
) : (
<Text className='text-slate-900 dark:text-slate-100'>
{t('不限')}
</Text>
)}
</div>
</div>
{plan?.upgrade_group ? (
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('升级分组')}
</Text>
<Text className='text-slate-900 dark:text-slate-100'>
{plan.upgrade_group}
</Text>
</div>
) : null}
<Divider margin={8} />
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('应付金额')}
</Text>
<Text strong className='text-xl text-purple-600'>
{symbol}
{displayPrice}
</Text>
</div>
</div>
</Card>
{/* 支付方式 */}
{purchaseLimitReached && (
<Banner
type='warning'
description={`${t('已达到购买上限')} (${purchaseCount}/${purchaseLimit})`}
className='!rounded-xl'
closeIcon={null}
/>
)}
{hasAnyPayment ? (
<div className='space-y-3'>
<Text size='small' type='tertiary'>
{t('选择支付方式')}
</Text>
{/* Stripe / Creem */}
{(hasStripe || hasCreem) && (
<div className='flex gap-2'>
{hasStripe && (
<Button
theme='light'
className='flex-1'
icon={<SiStripe size={14} color='#635BFF' />}
onClick={onPayStripe}
loading={paying}
disabled={purchaseLimitReached}
>
Stripe
</Button>
)}
{hasCreem && (
<Button
theme='light'
className='flex-1'
icon={<IconCreditCard />}
onClick={onPayCreem}
loading={paying}
disabled={purchaseLimitReached}
>
Creem
</Button>
)}
</div>
)}
{/* 易支付 */}
{hasEpay && (
<div className='flex gap-2'>
<Select
value={selectedEpayMethod}
onChange={setSelectedEpayMethod}
style={{ flex: 1 }}
size='default'
placeholder={t('选择支付方式')}
optionList={epayMethods.map((m) => ({
value: m.type,
label: m.name || m.type,
}))}
disabled={purchaseLimitReached}
/>
<Button
theme='solid'
type='primary'
onClick={onPayEpay}
loading={paying}
disabled={!selectedEpayMethod || purchaseLimitReached}
>
{t('支付')}
</Button>
</div>
)}
</div>
) : (
<Banner
type='info'
description={t('管理员未开启在线支付功能,请联系管理员配置。')}
className='!rounded-xl'
closeIcon={null}
/>
)}
</div>
) : null}
</Modal>
);
};
export default SubscriptionPurchaseModal;

View File

@@ -26,6 +26,7 @@ import {
Empty,
Button,
Input,
Tag,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
@@ -49,6 +50,7 @@ const STATUS_CONFIG = {
// 支付方式映射
const PAYMENT_METHOD_MAP = {
stripe: 'Stripe',
creem: 'Creem',
alipay: '支付宝',
wxpay: '微信',
};
@@ -150,6 +152,11 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
return <Text>{displayName ? t(displayName) : pm || '-'}</Text>;
};
const isSubscriptionTopup = (record) => {
const tradeNo = (record?.trade_no || '').toLowerCase();
return Number(record?.amount || 0) === 0 && tradeNo.startsWith('sub');
};
// 检查是否为管理员
const userIsAdmin = useMemo(() => isAdmin(), []);
@@ -171,12 +178,21 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
title: t('充值额度'),
dataIndex: 'amount',
key: 'amount',
render: (amount) => (
<span className='flex items-center gap-1'>
<Coins size={16} />
<Text>{amount}</Text>
</span>
),
render: (amount, record) => {
if (isSubscriptionTopup(record)) {
return (
<Tag color='purple' shape='circle' size='small'>
{t('订阅套餐')}
</Tag>
);
}
return (
<span className='flex items-center gap-1'>
<Coins size={16} />
<Text>{amount}</Text>
</span>
);
},
},
{
title: t('支付金额'),

25
web/src/helpers/quota.js Normal file
View File

@@ -0,0 +1,25 @@
import { getCurrencyConfig } from './render';
export const getQuotaPerUnit = () => {
const raw = parseFloat(localStorage.getItem('quota_per_unit') || '1');
return Number.isFinite(raw) && raw > 0 ? raw : 1;
};
export const quotaToDisplayAmount = (quota) => {
const q = Number(quota || 0);
if (!Number.isFinite(q) || q <= 0) return 0;
const { type, rate } = getCurrencyConfig();
if (type === 'TOKENS') return q;
const usd = q / getQuotaPerUnit();
if (type === 'USD') return usd;
return usd * (rate || 1);
};
export const displayAmountToQuota = (amount) => {
const val = Number(amount || 0);
if (!Number.isFinite(val) || val <= 0) return 0;
const { type, rate } = getCurrencyConfig();
if (type === 'TOKENS') return Math.round(val);
const usd = type === 'USD' ? val : val / (rate || 1);
return Math.round(usd * getQuotaPerUnit());
};

View File

@@ -74,6 +74,7 @@ import {
CircleUser,
Package,
Server,
CalendarClock,
} from 'lucide-react';
// 获取侧边栏Lucide图标组件
@@ -117,6 +118,8 @@ export function getLucideIcon(key, selected = false) {
return <Package {...commonProps} color={iconColor} />;
case 'deployment':
return <Server {...commonProps} color={iconColor} />;
case 'subscription':
return <CalendarClock {...commonProps} color={iconColor} />;
case 'setting':
return <Settings {...commonProps} color={iconColor} />;
default:

View File

@@ -0,0 +1,34 @@
export function formatSubscriptionDuration(plan, t) {
const unit = plan?.duration_unit || 'month';
const value = plan?.duration_value || 1;
const unitLabels = {
year: t('年'),
month: t('个月'),
day: t('天'),
hour: t('小时'),
custom: t('自定义'),
};
if (unit === 'custom') {
const seconds = plan?.custom_seconds || 0;
if (seconds >= 86400) return `${Math.floor(seconds / 86400)} ${t('天')}`;
if (seconds >= 3600) return `${Math.floor(seconds / 3600)} ${t('小时')}`;
return `${seconds} ${t('秒')}`;
}
return `${value} ${unitLabels[unit] || unit}`;
}
export function formatSubscriptionResetPeriod(plan, t) {
const period = plan?.quota_reset_period || 'never';
if (period === 'never') return t('不重置');
if (period === 'daily') return t('每天');
if (period === 'weekly') return t('每周');
if (period === 'monthly') return t('每月');
if (period === 'custom') {
const seconds = Number(plan?.quota_reset_custom_seconds || 0);
if (seconds >= 86400) return `${Math.floor(seconds / 86400)} ${t('天')}`;
if (seconds >= 3600) return `${Math.floor(seconds / 3600)} ${t('小时')}`;
if (seconds >= 60) return `${Math.floor(seconds / 60)} ${t('分钟')}`;
return `${seconds} ${t('秒')}`;
}
return t('不重置');
}

View File

@@ -51,6 +51,7 @@ export const DEFAULT_ADMIN_CONFIG = {
deployment: true,
redemption: true,
user: true,
subscription: true,
setting: true,
},
};

View File

@@ -0,0 +1,166 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useSubscriptionsData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('subscriptions');
// State management
const [allPlans, setAllPlans] = useState([]);
const [loading, setLoading] = useState(true);
// Pagination (client-side for now)
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(10);
// Drawer states
const [showEdit, setShowEdit] = useState(false);
const [editingPlan, setEditingPlan] = useState(null);
const [sheetPlacement, setSheetPlacement] = useState('left'); // 'left' | 'right'
// Load subscription plans
const loadPlans = async () => {
setLoading(true);
try {
const res = await API.get('/api/subscription/admin/plans');
if (res.data?.success) {
const next = res.data.data || [];
setAllPlans(next);
// Keep page in range after data changes
const totalPages = Math.max(1, Math.ceil(next.length / pageSize));
setActivePage((p) => Math.min(p || 1, totalPages));
} else {
showError(res.data?.message || t('加载失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
// Refresh data
const refresh = async () => {
await loadPlans();
};
const handlePageChange = (page) => {
setActivePage(page);
};
const handlePageSizeChange = (size) => {
setPageSize(size);
setActivePage(1);
};
// Update plan enabled status (single endpoint)
const setPlanEnabled = async (planRecordOrId, enabled) => {
const planId =
typeof planRecordOrId === 'number'
? planRecordOrId
: planRecordOrId?.plan?.id;
if (!planId) return;
setLoading(true);
try {
const res = await API.patch(`/api/subscription/admin/plans/${planId}`, {
enabled: !!enabled,
});
if (res.data?.success) {
showSuccess(enabled ? t('已启用') : t('已禁用'));
await loadPlans();
} else {
showError(res.data?.message || t('操作失败'));
}
} catch (e) {
showError(t('请求失败'));
} finally {
setLoading(false);
}
};
// Modal control functions
const closeEdit = () => {
setShowEdit(false);
setEditingPlan(null);
};
const openCreate = () => {
setSheetPlacement('left');
setEditingPlan(null);
setShowEdit(true);
};
const openEdit = (planRecord) => {
setSheetPlacement('right');
setEditingPlan(planRecord);
setShowEdit(true);
};
// Initialize data on component mount
useEffect(() => {
loadPlans();
}, []);
const planCount = allPlans.length;
const plans = allPlans.slice(
Math.max(0, (activePage - 1) * pageSize),
Math.max(0, (activePage - 1) * pageSize) + pageSize,
);
return {
// Data state
plans,
planCount,
loading,
// Modal state
showEdit,
editingPlan,
sheetPlacement,
setShowEdit,
setEditingPlan,
// UI state
compactMode,
setCompactMode,
// Pagination
activePage,
pageSize,
handlePageChange,
handlePageSizeChange,
// Actions
loadPlans,
setPlanEnabled,
refresh,
closeEdit,
openCreate,
openEdit,
// Translation
t,
};
};

View File

@@ -533,6 +533,55 @@ export const useLogsData = () => {
value: other.request_path,
});
}
if (other?.billing_source === 'subscription') {
const planId = other?.subscription_plan_id;
const planTitle = other?.subscription_plan_title || '';
const subscriptionId = other?.subscription_id;
const unit = t('额度');
const pre = other?.subscription_pre_consumed ?? 0;
const postDelta = other?.subscription_post_delta ?? 0;
const finalConsumed = other?.subscription_consumed ?? pre + postDelta;
const remain = other?.subscription_remain;
const total = other?.subscription_total;
// Use multiple Description items to avoid an overlong single line.
if (planId) {
expandDataLocal.push({
key: t('订阅套餐'),
value: `#${planId} ${planTitle}`.trim(),
});
}
if (subscriptionId) {
expandDataLocal.push({
key: t('订阅实例'),
value: `#${subscriptionId}`,
});
}
const settlementLines = [
`${t('预扣')}${pre} ${unit}`,
`${t('结算差额')}${postDelta > 0 ? '+' : ''}${postDelta} ${unit}`,
`${t('最终抵扣')}${finalConsumed} ${unit}`,
]
.filter(Boolean)
.join('\n');
expandDataLocal.push({
key: t('订阅结算'),
value: (
<div style={{ whiteSpace: 'pre-line' }}>{settlementLines}</div>
),
});
if (remain !== undefined && total !== undefined) {
expandDataLocal.push({
key: t('订阅剩余'),
value: `${remain}/${total} ${unit}`,
});
}
expandDataLocal.push({
key: t('订阅说明'),
value: t(
'token 会按倍率换算成“额度/次数”,请求结束后再做差额结算(补扣/返还)。',
),
});
}
if (isAdminUser) {
expandDataLocal.push({
key: t('请求转换'),

View File

@@ -2461,7 +2461,6 @@
"重新生成备用码失败": "Failed to regenerate backup codes",
"重新生成备用码将使现有的备用码失效,请确保您已保存了当前的备用码。": "Regenerating backup codes will invalidate existing backup codes. Please ensure you have saved the current backup codes.",
"重绘": "Vary",
"重置": "Reset",
"重置 2FA": "Reset Two-Factor Authentication",
"重置 Passkey": "Reset Passkey",
"重置为默认": "Reset to Default",
@@ -2602,6 +2601,92 @@
"关闭后将不再显示此提示(仅对当前浏览器生效)。确定要关闭吗?": "After closing, this notice will no longer be shown (only for this browser). Are you sure you want to close it?",
"关闭提示": "Close notice",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "Note: Tests on this page use non-streaming requests. If a channel only supports streaming responses, tests may fail. Please rely on actual usage.",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Notice: Endpoint mapping is for Model Marketplace display only and does not affect real model invocation. To configure real invocation, please go to Channel Management."
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Notice: Endpoint mapping is for Model Marketplace display only and does not affect real model invocation. To configure real invocation, please go to Channel Management.",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem products must be created on the third-party platform and the ID filled in",
"暂无订阅套餐": "No subscription plans",
"订阅管理": "Subscription Management",
"订阅套餐管理": "Subscription Plan Management",
"新建套餐": "Create Plan",
"套餐": "Plan",
"支付渠道": "Payment Channels",
"购买上限": "Purchase Limit",
"有效期": "Validity",
"重置": "Reset",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "After disabling, it will no longer be shown to users, but historical orders are not affected. Continue?",
"启用后套餐将在用户端展示。是否继续?": "After enabling, the plan will be shown to users. Continue?",
"更新套餐信息": "Update Plan Info",
"创建新的订阅套餐": "Create a New Subscription Plan",
"套餐的基本信息和定价": "Basic plan info and pricing",
"套餐标题": "Plan Title",
"请输入套餐标题": "Please enter plan title",
"套餐副标题": "Plan Subtitle",
"例如:适合轻度使用": "e.g.: Suitable for light usage",
"请输入金额": "Please enter amount",
"请输入总额度": "Please enter total quota",
"0 表示不限": "0 means unlimited",
"原生额度": "Raw quota",
"升级分组": "Upgrade Group",
"不升级": "No upgrade",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "Purchasing or manually adding a subscription will upgrade to this group. When the plan expires or is invalidated/deleted, it will revert to the previous group. The rollback is not immediate and usually takes a few minutes.",
"币种": "Currency",
"由全站货币展示设置统一控制": "Controlled by the site-wide currency display settings",
"排序": "Sort Order",
"启用状态": "Enabled Status",
"有效期设置": "Validity Settings",
"配置套餐的有效时长": "Configure the plan validity duration",
"有效期单位": "Validity Unit",
"自定义秒数": "Custom seconds",
"请输入秒数": "Please enter seconds",
"有效期数值": "Validity Value",
"额度重置": "Quota Reset",
"支持周期性重置套餐权益额度": "Supports periodic reset of plan quota",
"重置周期": "Reset Period",
"第三方支付配置": "Third-party Payment Configuration",
"Stripe/Creem 商品ID可选": "Stripe/Creem Product ID (optional)",
"生效": "Active",
"已作废": "Invalidated",
"用户订阅管理": "User Subscription Management",
"选择订阅套餐": "Select subscription plan",
"新增订阅": "Add subscription",
"暂无订阅记录": "No subscription records",
"来源": "Source",
"开始": "Start",
"结束": "End",
"作废": "Invalidate",
"确认作废": "Confirm invalidation",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "After invalidation, the subscription becomes invalid immediately. History is not affected. Continue?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "Deletion will permanently remove this subscription record (including benefit details). Continue?",
"绑定订阅套餐": "Bind Subscription Plan",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "After binding, a user subscription is created immediately (no payment required); validity follows the plan configuration.",
"订阅套餐": "Subscription Plans",
"购买订阅获得模型额度/次数": "Purchase a subscription to get model quota/usage",
"优先订阅": "Subscription first",
"优先钱包": "Wallet first",
"仅用订阅": "Subscription only",
"仅用钱包": "Wallet only",
"我的订阅": "My Subscriptions",
"个生效中": "active",
"无生效": "No active",
"个已过期": "expired",
"订阅": "Subscription",
"至": "until",
"过期于": "Expires at",
"购买套餐后即可享受模型权益": "Enjoy model benefits after purchasing a plan",
"限购": "Limit",
"推荐": "Recommended",
"已达到购买上限": "Purchase limit reached",
"已达上限": "Limit reached",
"立即订阅": "Subscribe now",
"暂无可购买套餐": "No plans available for purchase",
"该套餐未配置 Stripe": "This plan is not configured for Stripe",
"已打开支付页面": "Payment page opened",
"支付失败": "Payment failed",
"该套餐未配置 Creem": "This plan is not configured for Creem",
"已发起支付": "Payment initiated",
"购买订阅套餐": "Purchase Subscription Plan",
"套餐名称": "Plan Name",
"应付金额": "Amount Due",
"支付": "Pay",
"管理员未开启在线支付功能,请联系管理员配置。": "Online payment is not enabled by the admin. Please contact the administrator."
}
}

View File

@@ -2463,7 +2463,6 @@
"重新生成备用码失败": "Échec de la régénération des codes de sauvegarde",
"重新生成备用码将使现有的备用码失效,请确保您已保存了当前的备用码。": "La régénération des codes de sauvegarde invalidera les codes de sauvegarde existants. Veuillez vous assurer que vous avez enregistré les codes de sauvegarde actuels.",
"重绘": "Varier",
"重置": "Réinitialiser",
"重置 2FA": "Réinitialiser 2FA",
"重置 Passkey": "Réinitialiser le Passkey",
"重置为默认": "Réinitialiser aux valeurs par défaut",
@@ -2604,6 +2603,92 @@
"格式化 JSON": "Formater le JSON",
"关闭提示": "Fermer lavertissement",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "Remarque : les tests sur cette page utilisent des requêtes non-streaming. Si un canal ne prend en charge que les réponses en streaming, les tests peuvent échouer. Veuillez vous référer à lusage réel.",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Remarque : la correspondance des endpoints sert uniquement à laffichage dans la place de marché des modèles et naffecte pas linvocation réelle. Pour configurer linvocation réelle, veuillez aller dans « Gestion des canaux »."
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Remarque : la correspondance des endpoints sert uniquement à laffichage dans la place de marché des modèles et naffecte pas linvocation réelle. Pour configurer linvocation réelle, veuillez aller dans « Gestion des canaux ».",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Les produits Stripe/Creem doivent être créés sur la plateforme tierce et l'ID doit être renseigné",
"暂无订阅套餐": "Aucun plan d'abonnement",
"订阅管理": "Gestion des abonnements",
"订阅套餐管理": "Gestion des plans d'abonnement",
"新建套餐": "Créer un plan",
"套餐": "Plan",
"支付渠道": "Canaux de paiement",
"购买上限": "Limite d'achat",
"有效期": "Validité",
"重置": "Réinitialisation",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "Après désactivation, il ne sera plus affiché côté utilisateur, mais les commandes historiques ne sont pas affectées. Continuer ?",
"启用后套餐将在用户端展示。是否继续?": "Après activation, le plan sera affiché côté utilisateur. Continuer ?",
"更新套餐信息": "Mettre à jour le plan",
"创建新的订阅套餐": "Créer un nouveau plan d'abonnement",
"套餐的基本信息和定价": "Informations de base et tarification du plan",
"套餐标题": "Titre du plan",
"请输入套餐标题": "Veuillez saisir le titre du plan",
"套餐副标题": "Sous-titre du plan",
"例如:适合轻度使用": "Ex. : Convient à un usage léger",
"请输入金额": "Veuillez saisir le montant",
"请输入总额度": "Veuillez saisir le quota total",
"0 表示不限": "0 signifie illimité",
"原生额度": "Quota brut",
"升级分组": "Groupe de mise à niveau",
"不升级": "Pas de mise à niveau",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "L'achat ou l'ajout manuel d'un abonnement mettra à niveau vers ce groupe. À l'expiration ou en cas d'invalidation/suppression, il reviendra au groupe précédent. Le retour n'est pas immédiat et prend généralement quelques minutes.",
"币种": "Devise",
"由全站货币展示设置统一控制": "Contrôlé par les paramètres globaux d'affichage des devises",
"排序": "Ordre",
"启用状态": "Statut d'activation",
"有效期设置": "Paramètres de validité",
"配置套餐的有效时长": "Configurer la durée de validité du plan",
"有效期单位": "Unité de validité",
"自定义秒数": "Secondes personnalisées",
"请输入秒数": "Veuillez saisir le nombre de secondes",
"有效期数值": "Valeur de validité",
"额度重置": "Réinitialisation du quota",
"支持周期性重置套餐权益额度": "Prend en charge la réinitialisation périodique du quota du plan",
"重置周期": "Période de réinitialisation",
"第三方支付配置": "Configuration des paiements tiers",
"Stripe/Creem 商品ID可选": "ID produit Stripe/Creem (optionnel)",
"生效": "Actif",
"已作废": "Invalidé",
"用户订阅管理": "Gestion des abonnements utilisateur",
"选择订阅套餐": "Sélectionner un plan d'abonnement",
"新增订阅": "Ajouter un abonnement",
"暂无订阅记录": "Aucun enregistrement d'abonnement",
"来源": "Source",
"开始": "Début",
"结束": "Fin",
"作废": "Invalider",
"确认作废": "Confirmer l'invalidation",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "Après invalidation, l'abonnement devient immédiatement invalide. L'historique n'est pas affecté. Continuer ?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "La suppression retirera définitivement cet enregistrement d'abonnement (y compris les détails des avantages). Continuer ?",
"绑定订阅套餐": "Lier un plan d'abonnement",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "Après liaison, un abonnement utilisateur est créé immédiatement (sans paiement) ; la validité suit la configuration du plan.",
"订阅套餐": "Plans d'abonnement",
"购买订阅获得模型额度/次数": "Acheter un abonnement pour obtenir des quotas/usages de modèles",
"优先订阅": "Abonnement en priorité",
"优先钱包": "Portefeuille en priorité",
"仅用订阅": "Abonnement uniquement",
"仅用钱包": "Portefeuille uniquement",
"我的订阅": "Mes abonnements",
"个生效中": "actifs",
"无生效": "Aucun actif",
"个已过期": "expirés",
"订阅": "Abonnement",
"至": "jusqu'à",
"过期于": "Expire le",
"购买套餐后即可享受模型权益": "Profitez des avantages du modèle après l'achat d'un plan",
"限购": "Limite",
"推荐": "Recommandé",
"已达到购买上限": "Limite d'achat atteinte",
"已达上限": "Limite atteinte",
"立即订阅": "S'abonner maintenant",
"暂无可购买套餐": "Aucun plan disponible à l'achat",
"该套餐未配置 Stripe": "Ce plan n'est pas configuré pour Stripe",
"已打开支付页面": "Page de paiement ouverte",
"支付失败": "Paiement échoué",
"该套餐未配置 Creem": "Ce plan n'est pas configuré pour Creem",
"已发起支付": "Paiement initié",
"购买订阅套餐": "Acheter un plan d'abonnement",
"套餐名称": "Nom du plan",
"应付金额": "Montant à payer",
"支付": "Payer",
"管理员未开启在线支付功能,请联系管理员配置。": "Le paiement en ligne n'est pas activé par l'administrateur. Veuillez contacter l'administrateur."
}
}

View File

@@ -2446,7 +2446,6 @@
"重新生成备用码失败": "バックアップコードの再生成に失敗しました",
"重新生成备用码将使现有的备用码失效,请确保您已保存了当前的备用码。": "バックアップコードを再生成すると、既存のバックアップコードは無効になります。現在のバックアップコードを保存済みであることをご確認ください。",
"重绘": "再生成",
"重置": "リセット",
"重置 2FA": "2要素認証のリセット",
"重置 Passkey": "Passkeyリセット",
"重置为默认": "デフォルトへのリセット",
@@ -2587,6 +2586,92 @@
"格式化 JSON": "JSON を整形",
"关闭提示": "お知らせを閉じる",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "注意: このページのテストは非ストリーミングリクエストです。チャネルがストリーミング応答のみ対応の場合、テストが失敗することがあります。実際の利用結果を優先してください。",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "注意: エンドポイントマッピングは「モデル広場」での表示専用で、実際の呼び出しには影響しません。実際の呼び出し設定は「チャネル管理」で行ってください。"
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "注意: エンドポイントマッピングは「モデル広場」での表示専用で、実際の呼び出しには影響しません。実際の呼び出し設定は「チャネル管理」で行ってください。",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem の商品は外部プラットフォームで作成し、ID を入力してください",
"暂无订阅套餐": "利用可能なサブスクリプションプランがありません",
"订阅管理": "サブスクリプション管理",
"订阅套餐管理": "サブスクリプションプラン管理",
"新建套餐": "プラン作成",
"套餐": "プラン",
"支付渠道": "決済チャネル",
"购买上限": "購入上限",
"有效期": "有効期限",
"重置": "リセット",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "無効化するとユーザー側に表示されなくなりますが、過去の注文には影響しません。続行しますか?",
"启用后套餐将在用户端展示。是否继续?": "有効化するとユーザー側に表示されます。続行しますか?",
"更新套餐信息": "プラン情報を更新",
"创建新的订阅套餐": "新しいサブスクリプションプランを作成",
"套餐的基本信息和定价": "プランの基本情報と価格",
"套餐标题": "プラン名",
"请输入套餐标题": "プラン名を入力してください",
"套餐副标题": "プランのサブタイトル",
"例如:适合轻度使用": "例:軽めの利用に最適",
"请输入金额": "金額を入力してください",
"请输入总额度": "総クォータを入力してください",
"0 表示不限": "0 は無制限を意味します",
"原生额度": "生クォータ",
"升级分组": "アップグレードグループ",
"不升级": "アップグレードしない",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "購入または手動での追加によりこのグループにアップグレードされます。プランの失効/期限切れ、無効化/削除後は元のグループに戻ります。反映には数分かかる場合があります。",
"币种": "通貨",
"由全站货币展示设置统一控制": "サイト全体の通貨表示設定で統一して管理",
"排序": "並び順",
"启用状态": "有効状態",
"有效期设置": "有効期限設定",
"配置套餐的有效时长": "プランの有効期間を設定",
"有效期单位": "有効期限の単位",
"自定义秒数": "秒数を指定",
"请输入秒数": "秒数を入力してください",
"有效期数值": "有効期限の値",
"额度重置": "クォータリセット",
"支持周期性重置套餐权益额度": "プランのクォータを定期的にリセット可能",
"重置周期": "リセット周期",
"第三方支付配置": "サードパーティ決済設定",
"Stripe/Creem 商品ID可选": "Stripe/Creem 商品ID任意",
"生效": "有効",
"已作废": "無効化済み",
"用户订阅管理": "ユーザーサブスクリプション管理",
"选择订阅套餐": "サブスクリプションプランを選択",
"新增订阅": "サブスクリプションを追加",
"暂无订阅记录": "サブスクリプション記録がありません",
"来源": "ソース",
"开始": "開始",
"结束": "終了",
"作废": "無効化",
"确认作废": "無効化の確認",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "無効化するとこのサブスクリプションは直ちに失効します。履歴には影響しません。続行しますか?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "削除するとこのサブスクリプション記録(特典詳細を含む)が完全に削除されます。続行しますか?",
"绑定订阅套餐": "サブスクリプションプランを紐付け",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "紐付け後、ユーザーサブスクリプションが即時に作成されます(支払い不要)。有効期限はプラン設定に従います。",
"订阅套餐": "サブスクリプションプラン",
"购买订阅获得模型额度/次数": "サブスクリプション購入でモデルのクォータ/回数を取得",
"优先订阅": "サブスクリプション優先",
"优先钱包": "ウォレット優先",
"仅用订阅": "サブスクリプションのみ",
"仅用钱包": "ウォレットのみ",
"我的订阅": "私のサブスクリプション",
"个生效中": "件有効中",
"无生效": "有効なし",
"个已过期": "件期限切れ",
"订阅": "サブスクリプション",
"至": "まで",
"过期于": "有効期限",
"购买套餐后即可享受模型权益": "プラン購入後にモデル特典を利用できます",
"限购": "購入制限",
"推荐": "おすすめ",
"已达到购买上限": "購入上限に達しました",
"已达上限": "上限に達しました",
"立即订阅": "今すぐサブスクリプション",
"暂无可购买套餐": "購入可能なプランがありません",
"该套餐未配置 Stripe": "このプランには Stripe が設定されていません",
"已打开支付页面": "決済ページを開きました",
"支付失败": "支払いに失敗しました",
"该套餐未配置 Creem": "このプランには Creem が設定されていません",
"已发起支付": "支払いを開始しました",
"购买订阅套餐": "サブスクリプションプランを購入",
"套餐名称": "プラン名",
"应付金额": "支払金額",
"支付": "支払う",
"管理员未开启在线支付功能,请联系管理员配置。": "管理者がオンライン決済を有効にしていません。管理者に連絡してください。"
}
}

View File

@@ -2476,7 +2476,6 @@
"重新生成备用码失败": "Не удалось сгенерировать резервные коды заново",
"重新生成备用码将使现有的备用码失效,请确保您已保存了当前的备用码。": "Повторная генерация резервных кодов сделает существующие резервные коды недействительными, убедитесь, что вы сохранили текущие резервные коды.",
"重绘": "Перерисовать",
"重置": "Сброс",
"重置 2FA": "Сброс 2FA",
"重置 Passkey": "Сброс Passkey",
"重置为默认": "Сбросить по умолчанию",
@@ -2617,6 +2616,92 @@
"格式化 JSON": "Форматировать JSON",
"关闭提示": "Закрыть уведомление",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "Примечание: тесты на этой странице используют нестриминговые запросы. Если канал поддерживает только стриминговые ответы, тест может завершиться неудачей. Ориентируйтесь на реальное использование.",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Примечание: сопоставление endpoint'ов используется только для отображения в «Маркетплейсе моделей» и не влияет на реальный вызов. Чтобы настроить реальное поведение вызовов, перейдите в «Управление каналами»."
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Примечание: сопоставление эндпоинтов используется только для отображения в «Маркетплейсе моделей» и не влияет на реальный вызов. Чтобы настроить реальное поведение вызовов, перейдите в «Управление каналами».",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Товары Stripe/Creem нужно создать на сторонней платформе и указать их ID",
"暂无订阅套餐": "Нет тарифных планов",
"订阅管理": "Управление подписками",
"订阅套餐管理": "Управление тарифами подписки",
"新建套餐": "Создать план",
"套餐": "План",
"支付渠道": "Платежные каналы",
"购买上限": "Лимит покупок",
"有效期": "Срок действия",
"重置": "Сброс",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "После отключения план не будет отображаться пользователям, но история заказов не затрагивается. Продолжить?",
"启用后套餐将在用户端展示。是否继续?": "После включения план будет отображаться пользователям. Продолжить?",
"更新套餐信息": "Обновить информацию о плане",
"创建新的订阅套餐": "Создать новый план подписки",
"套餐的基本信息和定价": "Основная информация и цена плана",
"套餐标题": "Название плана",
"请输入套餐标题": "Введите название плана",
"套餐副标题": "Подзаголовок плана",
"例如:适合轻度使用": "Например: для легкого использования",
"请输入金额": "Введите сумму",
"请输入总额度": "Введите общий лимит",
"0 表示不限": "0 означает без лимита",
"原生额度": "Исходный лимит",
"升级分组": "Группа повышения",
"不升级": "Не повышать",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "Покупка или ручное добавление подписки повысит группу до этой. При истечении/аннулировании/удалении плана произойдет возврат к предыдущей группе. Возврат обычно занимает несколько минут.",
"币种": "Валюта",
"由全站货币展示设置统一控制": "Управляется глобальными настройками отображения валюты",
"排序": "Порядок",
"启用状态": "Статус включения",
"有效期设置": "Настройки срока действия",
"配置套餐的有效时长": "Настроить срок действия плана",
"有效期单位": "Единица срока",
"自定义秒数": "Пользовательские секунды",
"请输入秒数": "Введите количество секунд",
"有效期数值": "Значение срока",
"额度重置": "Сброс лимита",
"支持周期性重置套餐权益额度": "Поддерживает периодический сброс лимита плана",
"重置周期": "Период сброса",
"第三方支付配置": "Настройки сторонних платежей",
"Stripe/Creem 商品ID可选": "ID продукта Stripe/Creem (необязательно)",
"生效": "Активно",
"已作废": "Аннулировано",
"用户订阅管理": "Управление подписками пользователей",
"选择订阅套餐": "Выберите план подписки",
"新增订阅": "Добавить подписку",
"暂无订阅记录": "Нет записей подписок",
"来源": "Источник",
"开始": "Начало",
"结束": "Окончание",
"作废": "Аннулировать",
"确认作废": "Подтвердить аннулирование",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "После аннулирования подписка сразу станет недействительной. История не изменится. Продолжить?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "Удаление полностью удалит запись подписки (включая детали прав). Продолжить?",
"绑定订阅套餐": "Привязать план подписки",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "После привязки подписка будет создана сразу (без оплаты); срок действия рассчитывается по настройкам плана.",
"订阅套餐": "Планы подписки",
"购买订阅获得模型额度/次数": "Купите подписку, чтобы получить лимит/количество использования моделей",
"优先订阅": "Сначала подписка",
"优先钱包": "Сначала кошелек",
"仅用订阅": "Только подписка",
"仅用钱包": "Только кошелек",
"我的订阅": "Мои подписки",
"个生效中": "активных",
"无生效": "Нет активных",
"个已过期": "истекших",
"订阅": "Подписка",
"至": "до",
"过期于": "Истекает",
"购买套餐后即可享受模型权益": "После покупки плана доступны преимущества моделей",
"限购": "Лимит",
"推荐": "Рекомендуется",
"已达到购买上限": "Достигнут лимит покупок",
"已达上限": "Лимит достигнут",
"立即订阅": "Оформить сейчас",
"暂无可购买套餐": "Нет доступных для покупки планов",
"该套餐未配置 Stripe": "Для этого плана не настроен Stripe",
"已打开支付页面": "Страница оплаты открыта",
"支付失败": "Оплата не удалась",
"该套餐未配置 Creem": "Для этого плана не настроен Creem",
"已发起支付": "Оплата инициирована",
"购买订阅套餐": "Купить план подписки",
"套餐名称": "Название плана",
"应付金额": "К оплате",
"支付": "Оплатить",
"管理员未开启在线支付功能,请联系管理员配置。": "Онлайн-оплата не включена администратором. Пожалуйста, свяжитесь с администратором."
}
}

View File

@@ -3167,6 +3167,89 @@
"格式化 JSON": "Định dạng JSON",
"关闭提示": "Đóng thông báo",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "Lưu ý: Bài kiểm tra trên trang này sử dụng yêu cầu không streaming. Nếu kênh chỉ hỗ trợ phản hồi streaming, bài kiểm tra có thể thất bại. Vui lòng dựa vào sử dụng thực tế.",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Lưu ý: Ánh xạ endpoint chỉ dùng để hiển thị trong \"Chợ mô hình\" và không ảnh hưởng đến việc gọi thực tế. Để cấu hình gọi thực tế, vui lòng vào \"Quản lý kênh\"."
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "Lưu ý: Ánh xạ endpoint chỉ dùng để hiển thị trong \"Chợ mô hình\" và không ảnh hưởng đến việc gọi thực tế. Để cấu hình gọi thực tế, vui lòng vào \"Quản lý kênh\".",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Sản phẩm Stripe/Creem phải được tạo trên nền tảng bên thứ ba và điền ID",
"暂无订阅套餐": "Chưa có gói đăng ký",
"订阅管理": "Quản lý đăng ký",
"订阅套餐管理": "Quản lý gói đăng ký",
"新建套餐": "Tạo gói",
"套餐": "Gói",
"支付渠道": "Kênh thanh toán",
"购买上限": "Giới hạn mua",
"有效期": "Thời hạn",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "Sau khi tắt, gói sẽ không hiển thị cho người dùng nhưng lịch sử đơn hàng không bị ảnh hưởng. Tiếp tục?",
"启用后套餐将在用户端展示。是否继续?": "Sau khi bật, gói sẽ hiển thị cho người dùng. Tiếp tục?",
"更新套餐信息": "Cập nhật thông tin gói",
"创建新的订阅套餐": "Tạo gói đăng ký mới",
"套餐的基本信息和定价": "Thông tin cơ bản và giá của gói",
"套餐标题": "Tiêu đề gói",
"请输入套餐标题": "Vui lòng nhập tiêu đề gói",
"套餐副标题": "Phụ đề gói",
"例如:适合轻度使用": "Ví dụ: Phù hợp dùng nhẹ",
"请输入总额度": "Vui lòng nhập tổng hạn mức",
"0 表示不限": "0 nghĩa là không giới hạn",
"原生额度": "Hạn mức gốc",
"升级分组": "Nhóm nâng cấp",
"不升级": "Không nâng cấp",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "Mua hoặc thêm thủ công đăng ký sẽ nâng cấp lên nhóm này. Khi gói hết hạn/vô hiệu/xóa, sẽ quay lại nhóm trước. Việc quay lại không áp dụng ngay và thường mất vài phút.",
"币种": "Tiền tệ",
"由全站货币展示设置统一控制": "Được điều khiển bởi cài đặt hiển thị tiền tệ toàn site",
"排序": "Thứ tự",
"启用状态": "Trạng thái bật",
"有效期设置": "Cài đặt thời hạn",
"配置套餐的有效时长": "Cấu hình thời lượng hiệu lực của gói",
"有效期单位": "Đơn vị thời hạn",
"自定义秒数": "Số giây tùy chỉnh",
"请输入秒数": "Vui lòng nhập số giây",
"有效期数值": "Giá trị thời hạn",
"额度重置": "Đặt lại hạn mức",
"支持周期性重置套餐权益额度": "Hỗ trợ đặt lại định kỳ hạn mức quyền lợi của gói",
"重置周期": "Chu kỳ đặt lại",
"第三方支付配置": "Cấu hình thanh toán bên thứ ba",
"Stripe/Creem 商品ID可选": "ID sản phẩm Stripe/Creem (tùy chọn)",
"生效": "Có hiệu lực",
"已作废": "Đã vô hiệu",
"用户订阅管理": "Quản lý đăng ký người dùng",
"选择订阅套餐": "Chọn gói đăng ký",
"新增订阅": "Thêm đăng ký",
"暂无订阅记录": "Chưa có bản ghi đăng ký",
"来源": "Nguồn",
"开始": "Bắt đầu",
"结束": "Kết thúc",
"作废": "Vô hiệu",
"确认作废": "Xác nhận vô hiệu",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "Sau khi vô hiệu, đăng ký sẽ mất hiệu lực ngay. Lịch sử không bị ảnh hưởng. Tiếp tục?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "Xóa sẽ loại bỏ hoàn toàn bản ghi đăng ký (bao gồm chi tiết quyền lợi). Tiếp tục?",
"绑定订阅套餐": "Liên kết gói đăng ký",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "Sau khi liên kết, sẽ tạo đăng ký cho người dùng ngay (không cần thanh toán); thời hạn theo cấu hình gói.",
"订阅套餐": "Gói đăng ký",
"购买订阅获得模型额度/次数": "Mua đăng ký để nhận hạn mức/lượt dùng mô hình",
"优先订阅": "Ưu tiên đăng ký",
"优先钱包": "Ưu tiên ví",
"仅用订阅": "Chỉ dùng đăng ký",
"仅用钱包": "Chỉ dùng ví",
"我的订阅": "Đăng ký của tôi",
"个生效中": "gói đăng ký đang hiệu lực",
"无生效": "Không có gói đăng ký hiệu lực",
"个已过期": "gói đăng ký đã hết hạn",
"订阅": "Đăng ký",
"过期于": "Hết hạn vào",
"购买套餐后即可享受模型权益": "Mua gói để nhận quyền lợi mô hình",
"限购": "Giới hạn mua",
"推荐": "Đề xuất",
"已达到购买上限": "Đã đạt giới hạn mua",
"已达上限": "Đã đạt giới hạn",
"立即订阅": "Đăng ký ngay",
"暂无可购买套餐": "Không có gói có thể mua",
"该套餐未配置 Stripe": "Gói này chưa cấu hình Stripe",
"已打开支付页面": "Đã mở trang thanh toán",
"支付失败": "Thanh toán thất bại",
"该套餐未配置 Creem": "Gói này chưa cấu hình Creem",
"已发起支付": "Đã khởi tạo thanh toán",
"购买订阅套餐": "Mua gói đăng ký",
"套餐名称": "Tên gói",
"应付金额": "Số tiền phải trả",
"支付": "Thanh toán",
"管理员未开启在线支付功能,请联系管理员配置。": "Quản trị viên chưa bật thanh toán trực tuyến, vui lòng liên hệ quản trị viên."
}
}

View File

@@ -2556,7 +2556,6 @@
"默认补全倍率": "默认补全倍率",
"每日签到": "每日签到",
"今日已签到,累计签到": "今日已签到,累计签到",
"天": "天",
"每日签到可获得随机额度奖励": "每日签到可获得随机额度奖励",
"今日已签到": "今日已签到",
"立即签到": "立即签到",
@@ -2588,6 +2587,91 @@
"关闭后将不再显示此提示(仅对当前浏览器生效)。确定要关闭吗?": "关闭后将不再显示此提示(仅对当前浏览器生效)。确定要关闭吗?",
"关闭提示": "关闭提示",
"说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。": "说明:本页测试为非流式请求;若渠道仅支持流式返回,可能出现测试失败,请以实际使用为准。",
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。"
"提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。": "提示:端点映射仅用于模型广场展示,不会影响模型真实调用。如需配置真实调用,请前往「渠道管理」。",
"Stripe/Creem 需在第三方平台创建商品并填入 ID": "Stripe/Creem 需在第三方平台创建商品并填入 ID",
"暂无订阅套餐": "暂无订阅套餐",
"订阅管理": "订阅管理",
"订阅套餐管理": "订阅套餐管理",
"新建套餐": "新建套餐",
"套餐": "套餐",
"支付渠道": "支付渠道",
"购买上限": "购买上限",
"有效期": "有效期",
"禁用后用户端不再展示,但历史订单不受影响。是否继续?": "禁用后用户端不再展示,但历史订单不受影响。是否继续?",
"启用后套餐将在用户端展示。是否继续?": "启用后套餐将在用户端展示。是否继续?",
"更新套餐信息": "更新套餐信息",
"创建新的订阅套餐": "创建新的订阅套餐",
"套餐的基本信息和定价": "套餐的基本信息和定价",
"套餐标题": "套餐标题",
"请输入套餐标题": "请输入套餐标题",
"套餐副标题": "套餐副标题",
"例如:适合轻度使用": "例如:适合轻度使用",
"请输入金额": "请输入金额",
"请输入总额度": "请输入总额度",
"0 表示不限": "0 表示不限",
"原生额度": "原生额度",
"升级分组": "升级分组",
"不升级": "不升级",
"购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。": "购买或手动新增订阅会升级到该分组;当套餐失效/过期或手动作废/删除后,将回退到升级前分组。回退不会立即生效,通常会有几分钟延迟。",
"币种": "币种",
"由全站货币展示设置统一控制": "由全站货币展示设置统一控制",
"排序": "排序",
"启用状态": "启用状态",
"有效期设置": "有效期设置",
"配置套餐的有效时长": "配置套餐的有效时长",
"有效期单位": "有效期单位",
"自定义秒数": "自定义秒数",
"请输入秒数": "请输入秒数",
"有效期数值": "有效期数值",
"额度重置": "额度重置",
"支持周期性重置套餐权益额度": "支持周期性重置套餐权益额度",
"重置周期": "重置周期",
"第三方支付配置": "第三方支付配置",
"Stripe/Creem 商品ID可选": "Stripe/Creem 商品ID可选",
"生效": "生效",
"已作废": "已作废",
"用户订阅管理": "用户订阅管理",
"选择订阅套餐": "选择订阅套餐",
"新增订阅": "新增订阅",
"暂无订阅记录": "暂无订阅记录",
"来源": "来源",
"开始": "开始",
"结束": "结束",
"作废": "作废",
"确认作废": "确认作废",
"作废后该订阅将立即失效,历史记录不受影响。是否继续?": "作废后该订阅将立即失效,历史记录不受影响。是否继续?",
"删除会彻底移除该订阅记录(含权益明细)。是否继续?": "删除会彻底移除该订阅记录(含权益明细)。是否继续?",
"绑定订阅套餐": "绑定订阅套餐",
"绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。": "绑定后会立即生成用户订阅(无需支付),有效期按套餐配置计算。",
"订阅套餐": "订阅套餐",
"购买订阅获得模型额度/次数": "购买订阅获得模型额度/次数",
"优先订阅": "优先订阅",
"优先钱包": "优先钱包",
"仅用订阅": "仅用订阅",
"仅用钱包": "仅用钱包",
"我的订阅": "我的订阅",
"个生效中": "个生效中",
"无生效": "无生效",
"个已过期": "个已过期",
"订阅": "订阅",
"至": "至",
"过期于": "过期于",
"购买套餐后即可享受模型权益": "购买套餐后即可享受模型权益",
"限购": "限购",
"推荐": "推荐",
"已达到购买上限": "已达到购买上限",
"已达上限": "已达上限",
"立即订阅": "立即订阅",
"暂无可购买套餐": "暂无可购买套餐",
"该套餐未配置 Stripe": "该套餐未配置 Stripe",
"已打开支付页面": "已打开支付页面",
"支付失败": "支付失败",
"该套餐未配置 Creem": "该套餐未配置 Creem",
"已发起支付": "已发起支付",
"购买订阅套餐": "购买订阅套餐",
"套餐名称": "套餐名称",
"应付金额": "应付金额",
"支付": "支付",
"管理员未开启在线支付功能,请联系管理员配置。": "管理员未开启在线支付功能,请联系管理员配置。"
}
}

View File

@@ -65,6 +65,7 @@ export default function SettingsSidebarModulesAdmin(props) {
deployment: true,
redemption: true,
user: true,
subscription: true,
setting: true,
},
});
@@ -125,6 +126,7 @@ export default function SettingsSidebarModulesAdmin(props) {
deployment: true,
redemption: true,
user: true,
subscription: true,
setting: true,
},
};
@@ -193,6 +195,7 @@ export default function SettingsSidebarModulesAdmin(props) {
deployment: true,
redemption: true,
user: true,
subscription: true,
setting: true,
},
};
@@ -257,6 +260,11 @@ export default function SettingsSidebarModulesAdmin(props) {
title: t('模型部署'),
description: t('模型部署管理'),
},
{
key: 'subscription',
title: t('订阅管理'),
description: t('订阅套餐管理'),
},
{
key: 'redemption',
title: t('兑换码管理'),

View File

@@ -107,6 +107,7 @@ export default function SettingsSidebarModulesUser() {
deployment: isSidebarModuleAllowed('admin', 'deployment'),
redemption: isSidebarModuleAllowed('admin', 'redemption'),
user: isSidebarModuleAllowed('admin', 'user'),
subscription: isSidebarModuleAllowed('admin', 'subscription'),
setting: isSidebarModuleAllowed('admin', 'setting'),
};
}
@@ -344,6 +345,11 @@ export default function SettingsSidebarModulesUser() {
title: t('模型部署'),
description: t('模型部署管理'),
},
{
key: 'subscription',
title: t('订阅管理'),
description: t('订阅套餐管理'),
},
{
key: 'redemption',
title: t('兑换码管理'),

View File

@@ -0,0 +1,31 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import SubscriptionsPage from '../../components/table/subscriptions';
const Subscription = () => {
return (
<div className='mt-[60px] px-2'>
<SubscriptionsPage />
</div>
);
};
export default Subscription;