feat: 易支付积分充值 + 站内公告 + OpenAI 视频修复 + grok/adobe 失败处理
充值/订单(易支付 mapi): - 订单表 + 30 分钟自动取消;支付弹窗(二维码/跳转监控、倒计时、轮询、5s 倒计时关闭) - 系统设置可配:开关/商户ID/密钥/支付地址(根地址拼 /mapi)/支付方式/最低额/积分比例(默认 1元=100积分) - 异步通知 MD5 验签、幂等到账;用户累计充值;前台/后台订单页(筛选+搜索+分页,前后台分风格);用户管理累计充值列 站内公告: - Markdown 公告,登录用户首次访问/刷新弹出;内容哈希做版本,改了就重新推;管理员不弹;空内容=下线 OpenAI 视频(/v1/videos)修复: - /content 拿不到视频:grok 资源 URL 需鉴权,改为用生成账号 token 取流;adobe/runway 公开 URL 直代理(不存 RustFS) - size→分辨率用短边判定(1280x720 = 720p,之前误判 1080p 被拒) 失败处理: - grok 429「Too many requests」/403 anti-bot 改判临时错误(不再误封号),真额度耗尽才算 quota - adobe 视频 408 / system under load 归为临时错误 → tempAsDead 封号 其它: - 充值默认关闭;签到格子浅色可见;登录验证码按钮浅色可读;并发/账户信息展示 - 创作记录/画图台只显示画图台作品(排除 API);日志页 API 视频预览显示 — - 视频去画中画/下载/投屏(全局);图片缩略图改背景图规避 Edge 视觉搜索 - 订单/兑换码/配置/日志菜单文案与图标;充值版块样式 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -104,6 +104,9 @@ func NewApp(ctx context.Context) (*App, error) {
|
||||
}
|
||||
concSvc := service.NewConcurrencyService(rdb)
|
||||
cgroupSvc := service.NewConcurrencyGroupService(cgroupRepo, concSvc)
|
||||
announcementSvc := service.NewAnnouncementService(siteRepo, userRepo)
|
||||
orderRepo := repo.NewOrderRepository(db)
|
||||
paymentSvc := service.NewPaymentService(orderRepo, userRepo, siteRepo)
|
||||
sessionSvc := service.NewSessionService(rdb, cfg.SessionTTL, cfg.SessionSlideAfter)
|
||||
emailCodeSvc := service.NewEmailCodeService(rdb)
|
||||
smtpSvc := service.NewSMTPService()
|
||||
@@ -150,11 +153,13 @@ func NewApp(ctx context.Context) (*App, error) {
|
||||
UserGen: handler.NewUserGenerationHandler(userGenSvc, adminReadSvc),
|
||||
ProviderAdmin: handler.NewProviderAdminHandler(tokenSvc, refreshSvc),
|
||||
ConcGroups: handler.NewConcurrencyGroupHandler(cgroupSvc),
|
||||
Announcement: handler.NewAnnouncementHandler(announcementSvc),
|
||||
Payment: handler.NewPaymentHandler(paymentSvc),
|
||||
})
|
||||
|
||||
// Background self-healing sweep (quota recovery, cookie refresh, stale-pending
|
||||
// cleanup, log retention) — the Go equivalent of the Python daemon thread.
|
||||
maintenanceSvc := service.NewMaintenanceService(tokenRepo, tokenSvc, eventRepo, userRepo, refreshSvc, siteRepo, rustfsClient, v1Svc.Inflight(), showcaseRepo)
|
||||
maintenanceSvc := service.NewMaintenanceService(tokenRepo, tokenSvc, eventRepo, userRepo, refreshSvc, siteRepo, rustfsClient, v1Svc.Inflight(), showcaseRepo, orderRepo)
|
||||
loopCtx, loopCancel := context.WithCancel(context.Background())
|
||||
go maintenanceSvc.Run(loopCtx)
|
||||
|
||||
|
||||
@@ -35,6 +35,11 @@ func seedDefaults(ctx context.Context, db *gorm.DB) error {
|
||||
{Key: "credits.invite_enabled", Value: "true"},
|
||||
{Key: "credits.invite_reward", Value: "3"},
|
||||
{Key: "credits.cdk_redeem_enabled", Value: "true"},
|
||||
{Key: "pay.enabled", Value: "false"},
|
||||
{Key: "pay.api_base", Value: "https://pay.v8jisu.cn/api/pay"},
|
||||
{Key: "pay.methods", Value: "wxpay,alipay"},
|
||||
{Key: "pay.min_amount", Value: "1"},
|
||||
{Key: "pay.points_ratio", Value: "100"},
|
||||
{Key: "logs.retention_days", Value: "30"},
|
||||
{Key: "media.retention_days", Value: "30"},
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ func userPublic(user model.User) gin.H {
|
||||
"status": user.Status,
|
||||
"credits": user.Credits,
|
||||
"notes": user.Notes,
|
||||
"recharge_total": user.RechargeTotal,
|
||||
"concurrency_group_id": user.ConcurrencyGroupID,
|
||||
"created_at": unixSec(user.CreatedAt),
|
||||
"last_login_at": unixSecPtr(user.LastLoginAt),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"backend/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type AnnouncementHandler struct {
|
||||
svc *service.AnnouncementService
|
||||
}
|
||||
|
||||
func NewAnnouncementHandler(svc *service.AnnouncementService) *AnnouncementHandler {
|
||||
return &AnnouncementHandler{svc: svc}
|
||||
}
|
||||
|
||||
// Get — logged-in user: the current announcement + whether THIS user has seen it.
|
||||
func (h *AnnouncementHandler) Get(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, h.svc.ForUser(c.Request.Context(), user))
|
||||
}
|
||||
|
||||
// MarkSeen — user dismissed the announcement of the given version.
|
||||
func (h *AnnouncementHandler) MarkSeen(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&body)
|
||||
if err := h.svc.MarkSeen(c.Request.Context(), user.ID, body.Version); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// AdminGet — admin editor: the raw markdown.
|
||||
func (h *AnnouncementHandler) AdminGet(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"content": h.svc.Content(c.Request.Context())})
|
||||
}
|
||||
|
||||
// AdminPut — admin saves new markdown (re-pops for everyone who hasn't seen it).
|
||||
func (h *AnnouncementHandler) AdminPut(c *gin.Context) {
|
||||
var body struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
|
||||
return
|
||||
}
|
||||
if err := h.svc.Save(c.Request.Context(), body.Content); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"backend/internal/model"
|
||||
"backend/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type PaymentHandler struct {
|
||||
pay *service.PaymentService
|
||||
}
|
||||
|
||||
func NewPaymentHandler(pay *service.PaymentService) *PaymentHandler {
|
||||
return &PaymentHandler{pay: pay}
|
||||
}
|
||||
|
||||
func orderJSON(o *model.Order) gin.H {
|
||||
h := gin.H{
|
||||
"id": o.ID,
|
||||
"amount": o.Amount,
|
||||
"points": o.Points,
|
||||
"pay_type": o.PayType,
|
||||
"status": o.Status,
|
||||
"pay_info": o.PayInfo,
|
||||
"pay_info_type": o.PayInfoType,
|
||||
"created_at": o.CreatedAt.Unix(),
|
||||
"expires_at": o.ExpiresAt.Unix(),
|
||||
"server_now": time.Now().Unix(), // lets the popup count down on server time
|
||||
}
|
||||
if o.PaidAt != nil {
|
||||
h["paid_at"] = o.PaidAt.Unix()
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// ---- user ----
|
||||
|
||||
// Config returns the recharge config for the user UI (enabled, methods, min, ratio).
|
||||
func (h *PaymentHandler) Config(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, h.pay.Public(c.Request.Context()))
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) Recharge(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Amount float64 `json:"amount"`
|
||||
Method string `json:"method"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
|
||||
return
|
||||
}
|
||||
order, err := h.pay.CreateOrder(c.Request.Context(), user, body.Amount, body.Method, requestBaseURL(c), clientIP(c))
|
||||
if err != nil {
|
||||
h.writeErr(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, orderJSON(order))
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) MyOrders(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
limit := parseInt(c.Query("limit"), 20)
|
||||
offset := parseInt(c.Query("offset"), 0)
|
||||
orders, total, err := h.pay.ListByUser(c.Request.Context(), user.ID, c.Query("status"), limit, offset)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load orders"})
|
||||
return
|
||||
}
|
||||
out := make([]gin.H, 0, len(orders))
|
||||
for i := range orders {
|
||||
out = append(out, orderJSON(&orders[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": out, "total": total})
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) OrderStatus(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
order, err := h.pay.GetForUser(c.Request.Context(), user.ID, c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "订单不存在"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, orderJSON(order))
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) ContinueOrder(c *gin.Context) {
|
||||
user := currentUser(c)
|
||||
if user == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
|
||||
return
|
||||
}
|
||||
order, err := h.pay.Continue(c.Request.Context(), user, c.Param("id"), requestBaseURL(c), clientIP(c))
|
||||
if err != nil {
|
||||
h.writeErr(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, orderJSON(order))
|
||||
}
|
||||
|
||||
// ---- admin ----
|
||||
|
||||
func (h *PaymentHandler) AdminOrders(c *gin.Context) {
|
||||
status := c.Query("status")
|
||||
limit := parseInt(c.Query("limit"), 100)
|
||||
offset := parseInt(c.Query("offset"), 0)
|
||||
orders, total, err := h.pay.ListAll(c.Request.Context(), status, limit, offset)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load orders"})
|
||||
return
|
||||
}
|
||||
names := h.pay.UserNames(c.Request.Context())
|
||||
out := make([]gin.H, 0, len(orders))
|
||||
for i := range orders {
|
||||
row := orderJSON(&orders[i])
|
||||
row["user_name"] = names[orders[i].UserID]
|
||||
out = append(out, row)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": out, "total": total})
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) SettingsGet(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, h.pay.Settings(c.Request.Context()))
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) SettingsSave(c *gin.Context) {
|
||||
var in service.PaySettings
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
|
||||
return
|
||||
}
|
||||
if err := h.pay.SaveSettings(c.Request.Context(), in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": strings.TrimSpace(err.Error())})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// ---- public async notify (no auth — called by the 易支付 server) ----
|
||||
|
||||
func (h *PaymentHandler) Notify(c *gin.Context) {
|
||||
params := map[string]string{}
|
||||
for k, v := range c.Request.URL.Query() {
|
||||
if len(v) > 0 {
|
||||
params[k] = v[0]
|
||||
}
|
||||
}
|
||||
if _, err := h.pay.HandleNotify(c.Request.Context(), params); err != nil {
|
||||
c.String(http.StatusOK, "fail")
|
||||
return
|
||||
}
|
||||
// 易支付 expects the literal string "success" to stop re-notifying.
|
||||
c.String(http.StatusOK, "success")
|
||||
}
|
||||
|
||||
func (h *PaymentHandler) writeErr(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrPayDisabled):
|
||||
c.JSON(http.StatusForbidden, gin.H{"detail": "充值已关闭"})
|
||||
case errors.Is(err, service.ErrPayNotConfig):
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"detail": "支付未配置"})
|
||||
case errors.Is(err, service.ErrPayMethod):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "不支持的支付方式"})
|
||||
case errors.Is(err, service.ErrPayAmount):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "金额低于最低充值额"})
|
||||
case errors.Is(err, service.ErrOrderNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "订单不存在"})
|
||||
case errors.Is(err, service.ErrOrderPaid):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "订单已支付"})
|
||||
default:
|
||||
c.JSON(http.StatusBadGateway, gin.H{"detail": strings.TrimSpace(err.Error())})
|
||||
}
|
||||
}
|
||||
@@ -259,12 +259,10 @@ func videoSizeToInternal(size string) (ratio, resolution string) {
|
||||
if w == 0 || h == 0 {
|
||||
return "16:9", "720p"
|
||||
}
|
||||
long := w
|
||||
if h > long {
|
||||
long = h
|
||||
}
|
||||
// The "p" resolution is the SHORT edge (720p = 1280×720, 1080p = 1920×1080),
|
||||
// so a standard 1280×720 must read as 720p — not 1080p off the long edge.
|
||||
resolution = "720p"
|
||||
if long >= 1080 {
|
||||
if min(w, h) >= 1080 {
|
||||
resolution = "1080p"
|
||||
}
|
||||
return guessRatioWH(w, h), resolution
|
||||
|
||||
@@ -26,6 +26,8 @@ type Handlers struct {
|
||||
UserGen *handler.UserGenerationHandler
|
||||
ProviderAdmin *handler.ProviderAdminHandler
|
||||
ConcGroups *handler.ConcurrencyGroupHandler
|
||||
Announcement *handler.AnnouncementHandler
|
||||
Payment *handler.PaymentHandler
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.Engine {
|
||||
@@ -62,6 +64,9 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
|
||||
publicAdmin.GET("/video-presets", handlers.UserGen.VideoPresets)
|
||||
publicAdmin.GET("/catalog", handlers.UserGen.Catalog)
|
||||
publicAdmin.GET("/models", handlers.UserGen.Models)
|
||||
// 易支付 async notify — called server-to-server by the pay platform, no auth.
|
||||
publicAdmin.GET("/pay/notify", handlers.Payment.Notify)
|
||||
publicAdmin.POST("/pay/notify", handlers.Payment.Notify)
|
||||
}
|
||||
|
||||
authGroup := engine.Group("/admin/api/auth")
|
||||
@@ -82,6 +87,13 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
|
||||
userAuthed.POST("/test", handlers.UserGen.Test)
|
||||
userAuthed.GET("/jobs/mine", handlers.UserGen.MyJobs)
|
||||
userAuthed.GET("/my-images", handlers.UserGen.MyImages)
|
||||
userAuthed.GET("/announcement", handlers.Announcement.Get)
|
||||
userAuthed.POST("/announcement/seen", handlers.Announcement.MarkSeen)
|
||||
userAuthed.GET("/pay/config", handlers.Payment.Config)
|
||||
userAuthed.POST("/pay/recharge", handlers.Payment.Recharge)
|
||||
userAuthed.GET("/pay/orders", handlers.Payment.MyOrders)
|
||||
userAuthed.GET("/pay/orders/:id", handlers.Payment.OrderStatus)
|
||||
userAuthed.POST("/pay/orders/:id/continue", handlers.Payment.ContinueOrder)
|
||||
}
|
||||
|
||||
authed := engine.Group("/admin/api")
|
||||
@@ -102,6 +114,7 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
|
||||
authed.PATCH("/concurrency-groups/:id", handlers.ConcGroups.Update)
|
||||
authed.POST("/concurrency-groups/:id/default", handlers.ConcGroups.SetDefault)
|
||||
authed.DELETE("/concurrency-groups/:id", handlers.ConcGroups.Delete)
|
||||
authed.GET("/pay/admin/orders", handlers.Payment.AdminOrders)
|
||||
authed.GET("/cdks", handlers.CDK.List)
|
||||
authed.POST("/cdks", handlers.CDK.Create)
|
||||
authed.POST("/cdks/delete-bulk", handlers.CDK.DeleteBulk)
|
||||
@@ -158,6 +171,10 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
|
||||
settings.PUT("/logs", handlers.AppSettings.LogsPut)
|
||||
settings.GET("/media", handlers.AppSettings.MediaGet)
|
||||
settings.PUT("/media", handlers.AppSettings.MediaPut)
|
||||
settings.GET("/announcement", handlers.Announcement.AdminGet)
|
||||
settings.PUT("/announcement", handlers.Announcement.AdminPut)
|
||||
settings.GET("/pay", handlers.Payment.SettingsGet)
|
||||
settings.PUT("/pay", handlers.Payment.SettingsSave)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ type User struct {
|
||||
Credits float64 `gorm:"not null;default:0"`
|
||||
Notes string `gorm:"type:text"`
|
||||
ConcurrencyGroupID string `gorm:"size:32;index"`
|
||||
AnnouncementSeen string `gorm:"size:32"` // version hash of the last announcement this user dismissed
|
||||
RechargeTotal float64 `gorm:"not null;default:0"` // 累计充值金额(元)
|
||||
InviteCode string `gorm:"size:32;uniqueIndex"`
|
||||
InvitedBy *string `gorm:"size:32;index"`
|
||||
InviteRewardDone bool `gorm:"not null;default:false"`
|
||||
@@ -205,9 +207,29 @@ func AutoMigrateModels() []any {
|
||||
&SiteSetting{},
|
||||
&StatCounter{},
|
||||
&ConcurrencyGroup{},
|
||||
&Order{},
|
||||
}
|
||||
}
|
||||
|
||||
// Order is a points-recharge order paid via 易支付 (epay). ID is our merchant
|
||||
// order number (out_trade_no). Status: pending | paid | cancelled. Unpaid orders
|
||||
// auto-cancel 30 min after creation (ExpiresAt).
|
||||
type Order struct {
|
||||
ID string `gorm:"primaryKey;size:40"`
|
||||
UserID string `gorm:"size:32;index;not null"`
|
||||
Amount float64 `gorm:"not null"` // 充值金额(元)
|
||||
Points int `gorm:"not null"` // 到账积分
|
||||
PayType string `gorm:"size:16"` // wxpay | alipay
|
||||
Status string `gorm:"size:16;index;not null"` // pending | paid | cancelled
|
||||
TradeNo string `gorm:"size:64;index"` // 易支付平台订单号
|
||||
PayInfo string `gorm:"type:text"` // 二维码 url / 跳转 url
|
||||
PayInfoType string `gorm:"size:16"` // qrcode | jump | html | ...
|
||||
ExpiresAt time.Time `gorm:"index"`
|
||||
PaidAt *time.Time
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// ConcurrencyGroup caps how many generations a member user may run AT ONCE
|
||||
// (across their API key + 画图台). MaxConcurrency 0 = unlimited. Exactly one
|
||||
// group is IsDefault — new users are bound to it and it can't be deleted.
|
||||
|
||||
@@ -604,7 +604,12 @@ func (c *Client) submitVideo(ctx context.Context, client tlsclient.HttpClient, t
|
||||
// it's a bad token, a missing scope, or a WAF/fingerprint block.
|
||||
return respBody, "", fmt.Errorf("%w (%d %s: %s)", ErrAuth, resp.StatusCode, resp.Header.Get("x-access-error"), clip(respBody, 300))
|
||||
}
|
||||
if resp.StatusCode == 429 || resp.StatusCode == 451 || resp.StatusCode >= 500 {
|
||||
if resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode == 451 || resp.StatusCode >= 500 {
|
||||
return respBody, "", ErrTemporaryUpstream
|
||||
}
|
||||
// "system under load" / timeout_error = adobe overload — treat as a temporary
|
||||
// error so the tempAsDead policy retires the account (same as the image path).
|
||||
if b := string(respBody); strings.Contains(b, "system under load") || strings.Contains(b, "timeout_error") {
|
||||
return respBody, "", ErrTemporaryUpstream
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// Package epay implements the 易支付 mapi (API 下单) interface with MD5 signing.
|
||||
// POST {api_base}/mapi → JSON {code, msg, trade_no, payurl, qrcode}.
|
||||
// Docs: 请求字段 pid/type/out_trade_no/notify_url/name/money/sign/sign_type.
|
||||
package epay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
APIBase string // 易支付 API 根地址,如 https://pay.v8jisu.cn/api/pay(自动拼 /mapi)
|
||||
PID string // 商户ID
|
||||
Key string // 商户密钥
|
||||
}
|
||||
|
||||
type CreateRequest struct {
|
||||
OutTradeNo string
|
||||
Type string // wxpay | alipay | unionpay
|
||||
Name string
|
||||
Money string // "10.00"
|
||||
NotifyURL string
|
||||
ReturnURL string
|
||||
ClientIP string // unused by mapi; kept for caller convenience
|
||||
}
|
||||
|
||||
type CreateResult struct {
|
||||
TradeNo string // 平台订单号
|
||||
PayType string // qrcode | jump
|
||||
PayInfo string // 二维码内容 或 跳转 url
|
||||
}
|
||||
|
||||
// mapiResp is the raw mapi response. code: 1 成功, -1 失败.
|
||||
type mapiResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
TradeNo string `json:"trade_no"`
|
||||
PayURL string `json:"payurl"`
|
||||
QRCode string `json:"qrcode"`
|
||||
}
|
||||
|
||||
var httpClient = &http.Client{Timeout: 20 * time.Second}
|
||||
|
||||
// sign builds the MD5 signature: take all params except sign/sign_type and empty
|
||||
// values, sort keys ASCII-ascending, join as k=v&k=v (raw values), append the
|
||||
// merchant key, MD5, lowercase hex.
|
||||
func sign(params map[string]string, key string) string {
|
||||
keys := make([]string, 0, len(params))
|
||||
for k, v := range params {
|
||||
if k == "sign" || k == "sign_type" || v == "" {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var b strings.Builder
|
||||
for i, k := range keys {
|
||||
if i > 0 {
|
||||
b.WriteByte('&')
|
||||
}
|
||||
b.WriteString(k)
|
||||
b.WriteByte('=')
|
||||
b.WriteString(params[k])
|
||||
}
|
||||
b.WriteString(key)
|
||||
sum := md5.Sum([]byte(b.String()))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Create places a mapi order and returns the payment info (qrcode preferred).
|
||||
func (c *Config) Create(ctx context.Context, req CreateRequest) (*CreateResult, error) {
|
||||
params := map[string]string{
|
||||
"pid": c.PID,
|
||||
"type": req.Type,
|
||||
"out_trade_no": req.OutTradeNo,
|
||||
"notify_url": req.NotifyURL,
|
||||
"name": req.Name,
|
||||
"money": req.Money,
|
||||
"sign_type": "MD5",
|
||||
}
|
||||
if req.ReturnURL != "" {
|
||||
params["return_url"] = req.ReturnURL
|
||||
}
|
||||
params["sign"] = sign(params, c.Key)
|
||||
|
||||
form := url.Values{}
|
||||
for k, v := range params {
|
||||
form.Set(k, v)
|
||||
}
|
||||
endpoint := strings.TrimRight(c.APIBase, "/") + "/mapi"
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := httpClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
var out mapiResp
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return nil, fmt.Errorf("epay: bad response: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
if out.Code != 1 {
|
||||
msg := out.Msg
|
||||
if msg == "" {
|
||||
msg = "下单失败"
|
||||
}
|
||||
return nil, fmt.Errorf("epay: %s", msg)
|
||||
}
|
||||
result := &CreateResult{TradeNo: out.TradeNo}
|
||||
if out.QRCode != "" {
|
||||
result.PayType = "qrcode"
|
||||
result.PayInfo = out.QRCode
|
||||
} else if out.PayURL != "" {
|
||||
result.PayType = "jump"
|
||||
result.PayInfo = out.PayURL
|
||||
} else {
|
||||
return nil, fmt.Errorf("epay: 响应缺少 qrcode/payurl")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// VerifyNotify validates an async-notify callback's MD5 signature.
|
||||
func (c *Config) VerifyNotify(params map[string]string) bool {
|
||||
got := strings.TrimSpace(params["sign"])
|
||||
if got == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(got, sign(params, c.Key))
|
||||
}
|
||||
@@ -224,6 +224,46 @@ func (c *Client) doPost(ctx context.Context, client tlsclient.HttpClient, token,
|
||||
return raw, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// OpenAsset streams a grok asset (e.g. a generated video) authenticated with the
|
||||
// account token — used by the async /v1/videos /content proxy. The caller MUST
|
||||
// close the returned ReadCloser.
|
||||
func (c *Client) OpenAsset(ctx context.Context, token, url string) (io.ReadCloser, string, error) {
|
||||
token = strings.TrimSpace(strings.TrimPrefix(token, "Bearer "))
|
||||
if token == "" {
|
||||
return nil, "", ErrAuth
|
||||
}
|
||||
client, err := c.newTLSClient()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
req = req.WithContext(ctx)
|
||||
req.Header = http.Header{
|
||||
"user-agent": {userAgent},
|
||||
"referer": {origin + "/"},
|
||||
"cookie": {"sso=" + token + "; sso-rw=" + token},
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == 401 || resp.StatusCode == 403 {
|
||||
return nil, "", fmt.Errorf("%w: asset %d", ErrAuth, resp.StatusCode)
|
||||
}
|
||||
return nil, "", fmt.Errorf("%w: asset %d", ErrTemporaryUpstream, resp.StatusCode)
|
||||
}
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
if ct == "" {
|
||||
ct = "video/mp4"
|
||||
}
|
||||
return resp.Body, ct, nil
|
||||
}
|
||||
|
||||
func (c *Client) download(ctx context.Context, client tlsclient.HttpClient, token, url string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
@@ -258,10 +298,20 @@ func mapStatus(path string, status int, raw []byte) error {
|
||||
switch {
|
||||
case status == 200:
|
||||
return nil
|
||||
case status == 403 && strings.Contains(strings.ToLower(string(raw)), "anti-bot"):
|
||||
// grok bot-detection (proxy/TLS fingerprint), NOT a dead token — transient,
|
||||
// so a good account isn't killed by an IP/anti-bot hiccup.
|
||||
return fmt.Errorf("%w: %s 403 %s", ErrTemporaryUpstream, path, clip(raw, 160))
|
||||
case status == 401 || status == 403:
|
||||
return fmt.Errorf("%w: %s %d %s", ErrAuth, path, status, clip(raw, 160))
|
||||
case status == 429:
|
||||
return fmt.Errorf("%w: %s 429 %s", ErrQuotaExhausted, path, clip(raw, 160))
|
||||
// 429 is grok RATE-LIMITING ("Too many requests") — a transient error that
|
||||
// must NOT kill the account. Only a body that names a credit/usage-pool
|
||||
// exhaustion is a real quota wall.
|
||||
if isCreditError(string(raw)) {
|
||||
return fmt.Errorf("%w: %s 429 %s", ErrQuotaExhausted, path, clip(raw, 160))
|
||||
}
|
||||
return fmt.Errorf("%w: %s 429 %s", ErrTemporaryUpstream, path, clip(raw, 160))
|
||||
case status >= 500:
|
||||
return fmt.Errorf("%w: %s %d %s", ErrTemporaryUpstream, path, status, clip(raw, 160))
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"backend/internal/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderRepository struct{ db *gorm.DB }
|
||||
|
||||
func NewOrderRepository(db *gorm.DB) *OrderRepository { return &OrderRepository{db: db} }
|
||||
|
||||
func (r *OrderRepository) Create(ctx context.Context, o *model.Order) error {
|
||||
return r.db.WithContext(ctx).Create(o).Error
|
||||
}
|
||||
|
||||
func (r *OrderRepository) Get(ctx context.Context, id string) (*model.Order, error) {
|
||||
var o model.Order
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&o).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &o, nil
|
||||
}
|
||||
|
||||
func (r *OrderRepository) Update(ctx context.Context, id string, patch map[string]any) error {
|
||||
return r.db.WithContext(ctx).Model(&model.Order{}).Where("id = ?", id).Updates(patch).Error
|
||||
}
|
||||
|
||||
// ListByUser returns a user's own orders, newest first, with pagination + total.
|
||||
func (r *OrderRepository) ListByUser(ctx context.Context, userID, status string, limit, offset int) ([]model.Order, int64, error) {
|
||||
var out []model.Order
|
||||
var total int64
|
||||
q := r.db.WithContext(ctx).Model(&model.Order{}).Where("user_id = ?", userID)
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
err := q.Order("created_at desc").Limit(limit).Offset(offset).Find(&out).Error
|
||||
return out, total, err
|
||||
}
|
||||
|
||||
// List returns all orders (admin) with optional status filter + pagination.
|
||||
func (r *OrderRepository) List(ctx context.Context, status string, limit, offset int) ([]model.Order, int64, error) {
|
||||
var out []model.Order
|
||||
var total int64
|
||||
q := r.db.WithContext(ctx).Model(&model.Order{})
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
err := q.Order("created_at desc").Limit(limit).Offset(offset).Find(&out).Error
|
||||
return out, total, err
|
||||
}
|
||||
|
||||
// MarkPaid flips a pending order to paid atomically. Returns true only on the
|
||||
// transition pending→paid, so a duplicate notify can never double-credit.
|
||||
func (r *OrderRepository) MarkPaid(ctx context.Context, id, tradeNo string, paidAt time.Time) (bool, error) {
|
||||
res := r.db.WithContext(ctx).Model(&model.Order{}).
|
||||
Where("id = ? AND status = ?", id, "pending").
|
||||
Updates(map[string]any{"status": "paid", "paid_at": paidAt, "trade_no": tradeNo})
|
||||
return res.RowsAffected > 0, res.Error
|
||||
}
|
||||
|
||||
// ExpirePending cancels every still-pending order whose ExpiresAt has passed and
|
||||
// returns how many it cancelled.
|
||||
func (r *OrderRepository) ExpirePending(ctx context.Context, now time.Time) (int64, error) {
|
||||
res := r.db.WithContext(ctx).Model(&model.Order{}).
|
||||
Where("status = ? AND expires_at < ?", "pending", now).
|
||||
Updates(map[string]any{"status": "cancelled"})
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"backend/internal/model"
|
||||
"backend/internal/repo"
|
||||
)
|
||||
|
||||
// AnnouncementService serves the site-wide 公告 (markdown). It tracks, per user,
|
||||
// the version they last dismissed so an updated announcement re-pops for everyone
|
||||
// who hasn't seen the new text. The "version" is a hash of the content, so saving
|
||||
// identical text doesn't re-notify; any edit does.
|
||||
type AnnouncementService struct {
|
||||
settings *repo.SiteSettingRepository
|
||||
users *repo.UserRepository
|
||||
}
|
||||
|
||||
func NewAnnouncementService(settings *repo.SiteSettingRepository, users *repo.UserRepository) *AnnouncementService {
|
||||
return &AnnouncementService{settings: settings, users: users}
|
||||
}
|
||||
|
||||
func announcementVersion(content string) string {
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.TrimSpace(content)))
|
||||
return hex.EncodeToString(sum[:8]) // 16 hex chars — plenty to detect a change
|
||||
}
|
||||
|
||||
// Content returns the raw markdown (admin editor).
|
||||
func (s *AnnouncementService) Content(ctx context.Context) string {
|
||||
v, _ := s.settings.GetValue(ctx, "announcement.content")
|
||||
return v
|
||||
}
|
||||
|
||||
// ForUser returns {content, version, seen} for the logged-in user.
|
||||
func (s *AnnouncementService) ForUser(ctx context.Context, user *model.User) map[string]any {
|
||||
content := s.Content(ctx)
|
||||
version := announcementVersion(content)
|
||||
// Admins never get the popup — they author/preview it in 系统设置 instead.
|
||||
seen := version == "" || (user != nil && (user.Role == "admin" || user.AnnouncementSeen == version))
|
||||
return map[string]any{
|
||||
"content": content,
|
||||
"version": version,
|
||||
"seen": seen,
|
||||
}
|
||||
}
|
||||
|
||||
// MarkSeen records that the user has dismissed the given version.
|
||||
func (s *AnnouncementService) MarkSeen(ctx context.Context, userID, version string) error {
|
||||
_, err := s.users.Update(ctx, userID, map[string]any{"announcement_seen": version})
|
||||
return err
|
||||
}
|
||||
|
||||
// Save persists new announcement markdown (admin). An empty string clears it.
|
||||
func (s *AnnouncementService) Save(ctx context.Context, content string) error {
|
||||
return s.settings.UpsertValue(ctx, "announcement.content", content)
|
||||
}
|
||||
@@ -456,6 +456,7 @@ func (s *AuthService) PublicUser(ctx context.Context, user *model.User) (map[str
|
||||
"role": user.Role,
|
||||
"status": user.Status,
|
||||
"credits": user.Credits,
|
||||
"recharge_total": user.RechargeTotal,
|
||||
"concurrency_group": concName,
|
||||
"concurrency_limit": concMax,
|
||||
"checkin_last": user.CheckinLast,
|
||||
|
||||
@@ -28,13 +28,14 @@ type MaintenanceService struct {
|
||||
store *storage.Client
|
||||
inflight *InflightRegistry
|
||||
showcase *repo.ShowcaseRepository
|
||||
orders *repo.OrderRepository
|
||||
interval time.Duration
|
||||
stalePending time.Duration
|
||||
mediaPruneEvery time.Duration
|
||||
lastMediaPrune time.Time
|
||||
}
|
||||
|
||||
func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService, events *repo.EventRepository, users *repo.UserRepository, refresh *RefreshProfileService, settings *repo.SiteSettingRepository, store *storage.Client, inflight *InflightRegistry, showcase *repo.ShowcaseRepository) *MaintenanceService {
|
||||
func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService, events *repo.EventRepository, users *repo.UserRepository, refresh *RefreshProfileService, settings *repo.SiteSettingRepository, store *storage.Client, inflight *InflightRegistry, showcase *repo.ShowcaseRepository, orders *repo.OrderRepository) *MaintenanceService {
|
||||
return &MaintenanceService{
|
||||
tokens: tokens,
|
||||
tokenSvc: tokenSvc,
|
||||
@@ -45,6 +46,7 @@ func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService,
|
||||
store: store,
|
||||
inflight: inflight,
|
||||
showcase: showcase,
|
||||
orders: orders,
|
||||
interval: 60 * time.Second,
|
||||
stalePending: 600 * time.Second,
|
||||
mediaPruneEvery: 60 * time.Second,
|
||||
@@ -99,6 +101,15 @@ func (m *MaintenanceService) syncRecoveredQuota(accs []model.TokenAccount) {
|
||||
}
|
||||
|
||||
func (m *MaintenanceService) tick(ctx context.Context) {
|
||||
// 0. Auto-cancel unpaid recharge orders past their 30-min TTL.
|
||||
if m.orders != nil {
|
||||
if n, err := m.orders.ExpirePending(ctx, time.Now()); err != nil {
|
||||
log.Printf("maintenance: expire orders: %v", err)
|
||||
} else if n > 0 {
|
||||
log.Printf("maintenance: cancelled %d expired order(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Re-activate quota-exhausted tokens whose reset time has passed, then
|
||||
// auto-sync their real balance — these providers only refresh quota when
|
||||
// accessed, so recovery alone would leave a stale 0/—. For krea the sync
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"backend/internal/model"
|
||||
"backend/internal/provider/epay"
|
||||
"backend/internal/repo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const orderTTL = 30 * time.Minute
|
||||
|
||||
var (
|
||||
ErrPayDisabled = errors.New("recharge is currently disabled")
|
||||
ErrPayNotConfig = errors.New("payment is not configured")
|
||||
ErrPayMethod = errors.New("unsupported payment method")
|
||||
ErrPayAmount = errors.New("amount below the minimum")
|
||||
ErrOrderNotFound = errors.New("order not found")
|
||||
ErrOrderPaid = errors.New("order already paid")
|
||||
)
|
||||
|
||||
// PaymentService drives 易支付 recharge orders: create → pay → async-notify →
|
||||
// credit points. Config lives in site settings (pay.*).
|
||||
type PaymentService struct {
|
||||
orders *repo.OrderRepository
|
||||
users *repo.UserRepository
|
||||
settings *repo.SiteSettingRepository
|
||||
}
|
||||
|
||||
func NewPaymentService(orders *repo.OrderRepository, users *repo.UserRepository, settings *repo.SiteSettingRepository) *PaymentService {
|
||||
return &PaymentService{orders: orders, users: users, settings: settings}
|
||||
}
|
||||
|
||||
type PaySettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
PID string `json:"pid"`
|
||||
Key string `json:"key"`
|
||||
APIBase string `json:"api_base"` // 易支付站点根地址,代码自动拼 /api/pay/create
|
||||
Methods []string `json:"methods"` // wxpay, alipay
|
||||
MinAmount float64 `json:"min_amount"`
|
||||
PointsRatio int `json:"points_ratio"` // 积分 per 元
|
||||
}
|
||||
|
||||
func (s *PaymentService) get(ctx context.Context, key string) string {
|
||||
v, _ := s.settings.GetValue(ctx, key)
|
||||
return v
|
||||
}
|
||||
|
||||
func (s *PaymentService) Settings(ctx context.Context) PaySettings {
|
||||
api := strings.TrimRight(strings.TrimSpace(s.get(ctx, "pay.api_base")), "/")
|
||||
if api == "" {
|
||||
api = "https://pay.v8jisu.cn/api/pay"
|
||||
}
|
||||
ratio, _ := strconv.Atoi(s.get(ctx, "pay.points_ratio"))
|
||||
if ratio <= 0 {
|
||||
ratio = 100
|
||||
}
|
||||
minAmt, _ := strconv.ParseFloat(s.get(ctx, "pay.min_amount"), 64)
|
||||
var methods []string
|
||||
for _, m := range strings.Split(s.get(ctx, "pay.methods"), ",") {
|
||||
if m = strings.TrimSpace(m); m != "" {
|
||||
methods = append(methods, m)
|
||||
}
|
||||
}
|
||||
if len(methods) == 0 {
|
||||
methods = []string{"wxpay", "alipay"}
|
||||
}
|
||||
return PaySettings{
|
||||
Enabled: s.get(ctx, "pay.enabled") == "true",
|
||||
PID: s.get(ctx, "pay.pid"),
|
||||
Key: s.get(ctx, "pay.key"),
|
||||
APIBase: api,
|
||||
Methods: methods,
|
||||
MinAmount: minAmt,
|
||||
PointsRatio: ratio,
|
||||
}
|
||||
}
|
||||
|
||||
// Public returns the recharge config for the user UI (no merchant secrets).
|
||||
func (s *PaymentService) Public(ctx context.Context) map[string]any {
|
||||
c := s.Settings(ctx)
|
||||
return map[string]any{
|
||||
"enabled": c.Enabled,
|
||||
"methods": c.Methods,
|
||||
"min_amount": c.MinAmount,
|
||||
"points_ratio": c.PointsRatio,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PaymentService) SaveSettings(ctx context.Context, in PaySettings) error {
|
||||
api := strings.TrimRight(strings.TrimSpace(in.APIBase), "/")
|
||||
pid := strings.TrimSpace(in.PID)
|
||||
key := strings.TrimSpace(in.Key)
|
||||
if api == "" {
|
||||
return errors.New("支付地址不能为空")
|
||||
}
|
||||
if pid == "" {
|
||||
return errors.New("商户ID不能为空")
|
||||
}
|
||||
if key == "" {
|
||||
return errors.New("商户密钥不能为空")
|
||||
}
|
||||
if in.PointsRatio <= 0 {
|
||||
in.PointsRatio = 100
|
||||
}
|
||||
if in.MinAmount < 0 {
|
||||
in.MinAmount = 0
|
||||
}
|
||||
return s.settings.UpsertValues(ctx, map[string]string{
|
||||
"pay.enabled": strconv.FormatBool(in.Enabled),
|
||||
"pay.pid": pid,
|
||||
"pay.key": key,
|
||||
"pay.api_base": api,
|
||||
"pay.methods": strings.Join(in.Methods, ","),
|
||||
"pay.min_amount": strconv.FormatFloat(in.MinAmount, 'f', -1, 64),
|
||||
"pay.points_ratio": strconv.Itoa(in.PointsRatio),
|
||||
})
|
||||
}
|
||||
|
||||
func (c PaySettings) allows(method string) bool {
|
||||
for _, m := range c.Methods {
|
||||
if m == method {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *PaymentService) client(c PaySettings) *epay.Config {
|
||||
return &epay.Config{APIBase: c.APIBase, PID: c.PID, Key: c.Key}
|
||||
}
|
||||
|
||||
// CreateOrder validates the request, persists a pending order, and places the
|
||||
// 易支付 order. notifyBase is the public site origin (e.g. https://vividai.run).
|
||||
func (s *PaymentService) CreateOrder(ctx context.Context, user *model.User, amount float64, method, notifyBase, clientIP string) (*model.Order, error) {
|
||||
cfg := s.Settings(ctx)
|
||||
if !cfg.Enabled {
|
||||
return nil, ErrPayDisabled
|
||||
}
|
||||
if cfg.PID == "" || cfg.Key == "" {
|
||||
return nil, ErrPayNotConfig
|
||||
}
|
||||
if !cfg.allows(method) {
|
||||
return nil, ErrPayMethod
|
||||
}
|
||||
amount = math.Round(amount*100) / 100
|
||||
if amount <= 0 || amount < cfg.MinAmount {
|
||||
return nil, ErrPayAmount
|
||||
}
|
||||
points := int(math.Round(amount * float64(cfg.PointsRatio)))
|
||||
now := time.Now()
|
||||
order := &model.Order{
|
||||
ID: "P" + strconv.FormatInt(now.Unix(), 10) + randomUpper(6),
|
||||
UserID: user.ID,
|
||||
Amount: amount,
|
||||
Points: points,
|
||||
PayType: method,
|
||||
Status: "pending",
|
||||
ExpiresAt: now.Add(orderTTL),
|
||||
}
|
||||
if err := s.orders.Create(ctx, order); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := s.client(cfg).Create(ctx, epay.CreateRequest{
|
||||
OutTradeNo: order.ID,
|
||||
Type: method,
|
||||
Name: fmt.Sprintf("积分充值 %d", points),
|
||||
Money: strconv.FormatFloat(amount, 'f', 2, 64),
|
||||
NotifyURL: strings.TrimRight(notifyBase, "/") + "/admin/api/pay/notify",
|
||||
ClientIP: clientIP,
|
||||
})
|
||||
if err != nil {
|
||||
_ = s.orders.Update(ctx, order.ID, map[string]any{"status": "cancelled"})
|
||||
return nil, err
|
||||
}
|
||||
order.TradeNo = res.TradeNo
|
||||
order.PayInfo = res.PayInfo
|
||||
order.PayInfoType = res.PayType
|
||||
_ = s.orders.Update(ctx, order.ID, map[string]any{
|
||||
"trade_no": res.TradeNo, "pay_info": res.PayInfo, "pay_info_type": res.PayType,
|
||||
})
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// Continue re-creates payment for an unpaid order (clones its amount/method into
|
||||
// a fresh order — keeps the old one as history). Used by 订单管理 "继续支付".
|
||||
func (s *PaymentService) Continue(ctx context.Context, user *model.User, orderID, notifyBase, clientIP string) (*model.Order, error) {
|
||||
old, err := s.orders.Get(ctx, orderID)
|
||||
if err != nil || old == nil || old.UserID != user.ID {
|
||||
return nil, ErrOrderNotFound
|
||||
}
|
||||
if old.Status == "paid" {
|
||||
return nil, ErrOrderPaid
|
||||
}
|
||||
// Reuse a still-valid pending order — return its saved qrcode/payurl directly,
|
||||
// no new upstream order (and the countdown keeps its original expiry).
|
||||
if old.Status == "pending" && old.PayInfo != "" && time.Now().Before(old.ExpiresAt) {
|
||||
return old, nil
|
||||
}
|
||||
// Expired / cancelled (or never got a pay_info) → place a fresh order.
|
||||
return s.CreateOrder(ctx, user, old.Amount, old.PayType, notifyBase, clientIP)
|
||||
}
|
||||
|
||||
// HandleNotify processes an 易支付 async callback. Returns true when this call is
|
||||
// the one that credited the user (first successful notify for the order).
|
||||
func (s *PaymentService) HandleNotify(ctx context.Context, params map[string]string) (bool, error) {
|
||||
cfg := s.Settings(ctx)
|
||||
if cfg.Key == "" {
|
||||
return false, ErrPayNotConfig
|
||||
}
|
||||
if !s.client(cfg).VerifyNotify(params) {
|
||||
return false, errors.New("bad sign")
|
||||
}
|
||||
if params["trade_status"] != "TRADE_SUCCESS" {
|
||||
return false, nil
|
||||
}
|
||||
orderID := params["out_trade_no"]
|
||||
order, err := s.orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
return false, ErrOrderNotFound
|
||||
}
|
||||
credited, err := s.orders.MarkPaid(ctx, order.ID, params["trade_no"], time.Now())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !credited {
|
||||
return false, nil // duplicate / already handled
|
||||
}
|
||||
// Credit points + bump the user's cumulative recharge total, atomically.
|
||||
_, err = s.users.Update(ctx, order.UserID, map[string]any{
|
||||
"credits": gorm.Expr("credits + ?", order.Points),
|
||||
"recharge_total": gorm.Expr("recharge_total + ?", order.Amount),
|
||||
})
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (s *PaymentService) GetForUser(ctx context.Context, userID, orderID string) (*model.Order, error) {
|
||||
o, err := s.orders.Get(ctx, orderID)
|
||||
if err != nil || o == nil || o.UserID != userID {
|
||||
return nil, ErrOrderNotFound
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) ListByUser(ctx context.Context, userID, status string, limit, offset int) ([]model.Order, int64, error) {
|
||||
return s.orders.ListByUser(ctx, userID, status, limit, offset)
|
||||
}
|
||||
|
||||
func (s *PaymentService) ListAll(ctx context.Context, status string, limit, offset int) ([]model.Order, int64, error) {
|
||||
return s.orders.List(ctx, status, limit, offset)
|
||||
}
|
||||
|
||||
// UserNames maps user id → display name (name, else email, else id) so the admin
|
||||
// 订单管理 list can show 用户名.
|
||||
func (s *PaymentService) UserNames(ctx context.Context) map[string]string {
|
||||
out := map[string]string{}
|
||||
users, err := s.users.List(ctx)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
for _, u := range users {
|
||||
n := u.Name
|
||||
if n == "" {
|
||||
n = u.Email
|
||||
}
|
||||
if n == "" {
|
||||
n = u.ID
|
||||
}
|
||||
out[u.ID] = n
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ExpireStale cancels pending orders past their TTL (called by the maintenance
|
||||
// sweep). Returns how many were cancelled.
|
||||
func (s *PaymentService) ExpireStale(ctx context.Context) (int64, error) {
|
||||
return s.orders.ExpirePending(ctx, time.Now())
|
||||
}
|
||||
@@ -722,6 +722,8 @@ func (s *V1Service) runVideoJob(ctx context.Context, principal *APIPrincipal, in
|
||||
defer s.cleanupReferenceImages(ctx, eventID, refFiles)
|
||||
startedAt := time.Now()
|
||||
|
||||
// No-store: capture only the UPSTREAM video URL. /content streams it on demand
|
||||
// (grok URLs are auth-gated → fetched with the generating account's token).
|
||||
var videoURL string
|
||||
var execErr error
|
||||
switch s.effectiveProvider(genCtx, modelItem) {
|
||||
@@ -748,7 +750,7 @@ func (s *V1Service) runVideoJob(ctx context.Context, principal *APIPrincipal, in
|
||||
_ = s.events.UpdateStatus(ctx, eventID, "failed", "upstream returned no video url", 0)
|
||||
return
|
||||
}
|
||||
// Store the upstream URL as the event's "file"; /content proxies it.
|
||||
// Store the upstream URL as the event's "file"; /content fetches it on demand.
|
||||
if err := s.events.MarkVideoReady(ctx, eventID, videoURL, int(time.Since(startedAt).Milliseconds())); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -787,6 +789,22 @@ func (s *V1Service) OpenVideoContent(ctx context.Context, principal *APIPrincipa
|
||||
if ev.Status != "success" || strings.TrimSpace(ev.File) == "" {
|
||||
return nil, "", ErrVideoNotReady
|
||||
}
|
||||
// grok asset URLs (assets.grok.com) are auth-gated — a plain GET 403s. Stream
|
||||
// them through the SAME account that generated the clip, using its token. If
|
||||
// that account is gone (grok pools churn often), the clip is unrecoverable.
|
||||
if ev.Provider == "grok" && s.grok != nil {
|
||||
if s.settings != nil {
|
||||
if proxy, perr := s.settings.GetValue(ctx, "proxy.url"); perr == nil {
|
||||
s.grok.SetProxy(proxy)
|
||||
}
|
||||
}
|
||||
acct, _ := s.tokens.Get(ctx, "grok", ev.AccountID)
|
||||
if acct == nil || strings.TrimSpace(acct.Value) == "" {
|
||||
return nil, "", fmt.Errorf("%w: grok account no longer available for this video", ErrProviderTemporary)
|
||||
}
|
||||
return s.grok.OpenAsset(ctx, acct.Value, ev.File)
|
||||
}
|
||||
// Other providers return publicly-fetchable URLs — proxy directly.
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ev.File, nil)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
@@ -1251,9 +1269,9 @@ const maxTempDeadAccounts = 3
|
||||
// • tempAsDead=false (default): retry the SAME account up to
|
||||
// maxSameAccountAttempts times (not counted); if still failing, STOP
|
||||
// (no fan-out — an upstream-wide blip fails identically everywhere).
|
||||
// • tempAsDead=true (adobe): treat the temporary error as a DEAD account —
|
||||
// mark it like a 401 and fail over to the next account, capped at
|
||||
// maxTempDeadAccounts accounts so a pool-wide blip can't kill everything.
|
||||
// • tempAsDead=true (adobe): BAN the account (mark dead/disabled) and fail
|
||||
// over to the next account, capped at maxTempDeadAccounts accounts so a
|
||||
// pool-wide blip can't kill everything. Dead accounts don't auto-recover.
|
||||
// - 参数错 / request-level (anything else) → return immediately, no retry, no
|
||||
// account penalty (the account isn't at fault).
|
||||
//
|
||||
@@ -1356,10 +1374,17 @@ func (s *V1Service) tryAccount(ctx context.Context, eventID, pool string, token
|
||||
if isTemp {
|
||||
if tempAsDead {
|
||||
// Ops policy (adobe): a temporary upstream error ("system under
|
||||
// load" etc.) means this account is effectively dead — mark it
|
||||
// like a 401 and fail over to the next account. The pool driver
|
||||
// caps how many accounts this is allowed to burn.
|
||||
s.markTokenFailure(ctx, pool, token, kind, true, false)
|
||||
// load" etc.) BANS this account — mark it dead/disabled and fail
|
||||
// over to the next account. The pool driver caps how many accounts
|
||||
// this is allowed to burn per request (maxTempDeadAccounts). Note:
|
||||
// dead accounts do NOT auto-recover — they need a manual re-enable.
|
||||
_, _ = s.tokens.Update(ctx, pool, token.ID, map[string]any{
|
||||
"status": "disabled",
|
||||
"dead": true,
|
||||
"last_used_at": time.Now(),
|
||||
"fail_total": gorm.Expr("fail_total + 1"),
|
||||
"fails": gorm.Expr("fails + 1"),
|
||||
})
|
||||
return nil, err, true, true
|
||||
}
|
||||
tempAttempts++
|
||||
|
||||
Generated
+321
-2
@@ -1,13 +1,15 @@
|
||||
{
|
||||
"name": "ai-gateway-frontend",
|
||||
"name": "vivid-frontend",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ai-gateway-frontend",
|
||||
"name": "vivid-frontend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"marked": "^18.0.5",
|
||||
"qrcode": "^1.5.4",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
@@ -1304,12 +1306,83 @@
|
||||
"integrity": "sha512-FTW0AFZNaK5/mOqvGBwVfUlNLU38TiQn4+DQgIFUnrBBJQ1crMJ82yeGQLV5jyKFsO8yRukpbuP7x+nRbH6aug==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmmirror.com/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
@@ -1320,6 +1393,18 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/enhanced-resolve": {
|
||||
"version": "5.21.6",
|
||||
"resolved": "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",
|
||||
@@ -1412,6 +1497,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1427,6 +1525,15 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
@@ -1434,6 +1541,15 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/jiti": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz",
|
||||
@@ -1705,6 +1821,18 @@
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz",
|
||||
@@ -1714,6 +1842,18 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/marked": {
|
||||
"version": "18.0.5",
|
||||
"resolved": "https://registry.npmmirror.com/marked/-/marked-18.0.5.tgz",
|
||||
"integrity": "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"marked": "bin/marked.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.12",
|
||||
"resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.12.tgz",
|
||||
@@ -1732,6 +1872,51 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -1751,6 +1936,15 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.15",
|
||||
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.15.tgz",
|
||||
@@ -1779,6 +1973,38 @@
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmmirror.com/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/rollup": {
|
||||
"version": "4.62.0",
|
||||
"resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.62.0.tgz",
|
||||
@@ -1824,6 +2050,12 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -1833,6 +2065,32 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/tailwindcss": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-4.3.1.tgz",
|
||||
@@ -1981,6 +2239,67 @@
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"marked": "^18.0.5",
|
||||
"qrcode": "^1.5.4",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
|
||||
+17
-3
@@ -2,13 +2,25 @@
|
||||
// App shell is layout-driven: each top-level route renders its own layout
|
||||
// (PublicLayout for /, /user; AdminLayout for /admin/*). The login modal is
|
||||
// mounted here so it can overlay any page instead of being a separate route.
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, watch } from 'vue'
|
||||
import LoginModal from './components/LoginModal.vue'
|
||||
import AnnouncementModal from './components/AnnouncementModal.vue'
|
||||
import PaymentModal from './components/PaymentModal.vue'
|
||||
import { auth, refreshMe, openRegister } from './auth'
|
||||
import { loadAnnouncement } from './announcement'
|
||||
|
||||
// Pull the 公告 whenever a user is (or becomes) logged in — at first paint AND
|
||||
// after a fresh login. It pops up only if this user hasn't seen the latest one.
|
||||
watch(() => auth.user?.id, (id) => { if (id) loadAnnouncement() }, { immediate: true })
|
||||
|
||||
// An invite link (/?ref=CODE) should drop a guest straight into registration
|
||||
// with the code attached. Logged-in users just ignore the ref.
|
||||
onMounted(async () => {
|
||||
// Validate the stored session on every page load / refresh — even on public
|
||||
// pages where the router guard doesn't. This populates auth.user, which fires
|
||||
// the watch above → the 公告 check runs on a plain refresh (no re-login).
|
||||
if (auth.token && !auth.ready) await refreshMe()
|
||||
|
||||
// An invite link (/?ref=CODE) should drop a guest straight into registration
|
||||
// with the code attached. Logged-in users just ignore the ref.
|
||||
const code = new URLSearchParams(location.search).get('ref')
|
||||
if (!code) return
|
||||
if (!auth.ready) await refreshMe()
|
||||
@@ -19,4 +31,6 @@ onMounted(async () => {
|
||||
<template>
|
||||
<router-view />
|
||||
<LoginModal />
|
||||
<AnnouncementModal />
|
||||
<PaymentModal />
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Site-wide 公告 (admin-authored markdown). Visible only to logged-in users; pops
|
||||
// up whenever the current user hasn't seen the latest version — at login AND on
|
||||
// any normal visit. An admin edit changes the version (content hash) so it
|
||||
// re-pops for everyone who hasn't seen the new text.
|
||||
import { reactive } from 'vue'
|
||||
import { api, jsonBody } from './api'
|
||||
|
||||
export const announcement = reactive({ content: '', version: '', show: false })
|
||||
|
||||
// Fetch the current announcement + this user's seen-state; show it if unseen.
|
||||
export async function loadAnnouncement() {
|
||||
try {
|
||||
const r = await api('/announcement')
|
||||
if (r.ok && r.data) {
|
||||
announcement.content = r.data.content || ''
|
||||
announcement.version = r.data.version || ''
|
||||
announcement.show = !r.data.seen && !!announcement.content.trim()
|
||||
}
|
||||
} catch { /* offline — skip */ }
|
||||
}
|
||||
|
||||
// Dismiss: hide + remember this version server-side so it won't re-pop.
|
||||
export async function dismissAnnouncement() {
|
||||
announcement.show = false
|
||||
if (announcement.version) {
|
||||
try { await api('/announcement/seen', jsonBody('POST', { version: announcement.version })) } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { marked } from 'marked'
|
||||
import { announcement, dismissAnnouncement } from '../announcement'
|
||||
import Icon from './Icon.vue'
|
||||
|
||||
marked.setOptions({ breaks: true, gfm: true })
|
||||
const html = computed(() => marked.parse(announcement.content || ''))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<transition name="ann-fade">
|
||||
<div v-if="announcement.show"
|
||||
class="fixed inset-0 z-[80] bg-slate-950/70 backdrop-blur-sm flex items-center justify-center p-4"
|
||||
@click.self="dismissAnnouncement">
|
||||
<div class="w-full max-w-lg rounded-2xl bg-white text-slate-800 shadow-2xl overflow-hidden flex flex-col max-h-[80vh]">
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between gap-3 shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-7 h-7 rounded-lg bg-violet-500/15 text-violet-600 grid place-items-center">
|
||||
<Icon name="spark" class="w-4 h-4" />
|
||||
</span>
|
||||
<h2 class="text-base font-semibold">公告</h2>
|
||||
</div>
|
||||
<button @click="dismissAnnouncement" class="text-slate-400 hover:text-slate-700 transition-colors">
|
||||
<Icon name="close" class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="ann-body px-6 py-5 overflow-y-auto" v-html="html"></div>
|
||||
<div class="px-6 py-4 border-t border-slate-100 flex justify-end shrink-0">
|
||||
<button @click="dismissAnnouncement"
|
||||
class="rounded-lg bg-slate-900 text-white hover:bg-slate-700 px-5 py-2 text-sm font-medium transition-colors">
|
||||
我知道了
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ann-fade-enter-active, .ann-fade-leave-active { transition: opacity 0.2s ease; }
|
||||
.ann-fade-enter-from, .ann-fade-leave-to { opacity: 0; }
|
||||
|
||||
/* Minimal markdown typography for the announcement body. */
|
||||
.ann-body { font-size: 0.9rem; line-height: 1.65; color: rgb(51 65 85); }
|
||||
.ann-body :deep(h1) { font-size: 1.25rem; font-weight: 700; margin: 0.6em 0 0.4em; color: rgb(15 23 42); }
|
||||
.ann-body :deep(h2) { font-size: 1.1rem; font-weight: 700; margin: 0.6em 0 0.4em; color: rgb(15 23 42); }
|
||||
.ann-body :deep(h3) { font-size: 1rem; font-weight: 600; margin: 0.6em 0 0.3em; color: rgb(15 23 42); }
|
||||
.ann-body :deep(p) { margin: 0.5em 0; }
|
||||
.ann-body :deep(ul), .ann-body :deep(ol) { margin: 0.5em 0; padding-left: 1.4em; }
|
||||
.ann-body :deep(ul) { list-style: disc; }
|
||||
.ann-body :deep(ol) { list-style: decimal; }
|
||||
.ann-body :deep(li) { margin: 0.2em 0; }
|
||||
.ann-body :deep(a) { color: rgb(124 58 237); text-decoration: underline; }
|
||||
.ann-body :deep(strong) { font-weight: 700; color: rgb(15 23 42); }
|
||||
.ann-body :deep(code) { background: rgb(241 245 249); padding: 0.1em 0.35em; border-radius: 0.3rem; font-size: 0.85em; }
|
||||
.ann-body :deep(pre) { background: rgb(241 245 249); padding: 0.8em; border-radius: 0.5rem; overflow-x: auto; margin: 0.6em 0; }
|
||||
.ann-body :deep(pre code) { background: none; padding: 0; }
|
||||
.ann-body :deep(blockquote) { border-left: 3px solid rgb(196 181 253); padding-left: 0.9em; color: rgb(100 116 139); margin: 0.6em 0; }
|
||||
.ann-body :deep(hr) { border: none; border-top: 1px solid rgb(226 232 240); margin: 1em 0; }
|
||||
.ann-body :deep(img) { max-width: 100%; border-radius: 0.5rem; margin: 0.5em 0; }
|
||||
</style>
|
||||
@@ -21,6 +21,7 @@ const PATHS = {
|
||||
chevron: '<path d="m6 9 6 6 6-6"/>',
|
||||
check: '<path d="M20 6 9 17l-5-5"/>',
|
||||
shield: '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',
|
||||
receipt: '<path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/><path d="M12 17.5v-11"/>',
|
||||
}
|
||||
|
||||
defineProps({ name: { type: String, required: true } })
|
||||
|
||||
@@ -347,12 +347,15 @@ html.dark .fld:-webkit-autofill:focus {
|
||||
min-width: 5.5rem; /* keep width stable between text / spinner */
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
font-size: 0.75rem; white-space: nowrap;
|
||||
color: rgb(196 181 253 / 0.95);
|
||||
background: rgb(167 139 250 / 0.1); border: 1px solid rgb(167 139 250 / 0.3);
|
||||
color: rgb(124 58 237); /* violet-600 — readable on the light card */
|
||||
background: rgb(167 139 250 / 0.12); border: 1px solid rgb(167 139 250 / 0.4);
|
||||
transition: background 0.15s, opacity 0.15s;
|
||||
}
|
||||
html.dark .code-btn { color: rgb(196 181 253 / 0.95); background: rgb(167 139 250 / 0.1); border-color: rgb(167 139 250 / 0.3); }
|
||||
.code-btn:hover:not(:disabled) { background: rgb(167 139 250 / 0.2); }
|
||||
.code-btn:disabled { opacity: 0.45; cursor: not-allowed; color: rgb(255 255 255 / 0.5); border-color: rgb(255 255 255 / 0.12); }
|
||||
/* Disabled (sending / countdown): just dim — keep the theme text color so it
|
||||
never washes out to invisible white on the light card. */
|
||||
.code-btn:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
.code-spin { width: 1.05rem; height: 1.05rem; animation: code-spin 0.7s linear infinite; }
|
||||
@keyframes code-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
<script setup>
|
||||
import { ref, computed, watch, onUnmounted } from 'vue'
|
||||
import QRCode from 'qrcode'
|
||||
import { api } from '../api'
|
||||
import { refreshMe } from '../auth'
|
||||
import { payment, closePayment } from '../payment'
|
||||
import Icon from './Icon.vue'
|
||||
|
||||
const qrUrl = ref('')
|
||||
const remaining = ref(0) // seconds until expiry
|
||||
const paid = ref(false)
|
||||
const closeIn = ref(5) // post-paid auto-close countdown
|
||||
let pollTimer = null, tickTimer = null, closeTimer = null
|
||||
let serverOffset = 0 // (client epoch − server epoch); makes the countdown clock-skew-proof
|
||||
|
||||
const order = computed(() => payment.order || {})
|
||||
const isJump = computed(() => order.value.pay_info_type === 'jump')
|
||||
// Dead = the order can no longer be paid: cancelled server-side, or the countdown
|
||||
// has hit zero (the QR is invalid even before the sweep flips the status).
|
||||
const dead = computed(() => !paid.value && (order.value.status === 'cancelled' || remaining.value <= 0))
|
||||
const methodLabel = computed(() => ({ wxpay: '微信支付', alipay: '支付宝' }[order.value.pay_type] || order.value.pay_type || ''))
|
||||
const statusLabel = computed(() => ({ pending: '待支付', paid: '已支付', cancelled: '已取消' }[order.value.status] || order.value.status))
|
||||
const mmss = computed(() => {
|
||||
const s = Math.max(0, remaining.value)
|
||||
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
|
||||
})
|
||||
function fmtTime(unix) {
|
||||
if (!unix) return '—'
|
||||
const d = new Date(unix * 1000)
|
||||
const p = (n) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
|
||||
}
|
||||
|
||||
function clearTimers() {
|
||||
clearInterval(pollTimer); clearInterval(tickTimer); clearInterval(closeTimer)
|
||||
pollTimer = tickTimer = closeTimer = null
|
||||
}
|
||||
|
||||
async function renderQR() {
|
||||
qrUrl.value = ''
|
||||
const info = order.value.pay_info
|
||||
if (!info) return
|
||||
try { qrUrl.value = await QRCode.toDataURL(info, { width: 220, margin: 1 }) } catch { qrUrl.value = '' }
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!order.value.id || paid.value) return
|
||||
const r = await api(`/pay/orders/${order.value.id}`)
|
||||
if (r.ok && r.data) {
|
||||
payment.order = { ...payment.order, ...r.data }
|
||||
if (r.data.status === 'paid') onPaid()
|
||||
else if (r.data.status === 'cancelled') { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
}
|
||||
|
||||
function onPaid() {
|
||||
if (paid.value) return
|
||||
paid.value = true
|
||||
clearTimers()
|
||||
refreshMe() // pull the new credits / 累计充值
|
||||
closeIn.value = 5
|
||||
closeTimer = setInterval(() => {
|
||||
closeIn.value -= 1
|
||||
if (closeIn.value <= 0) finish()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
function finish() {
|
||||
clearTimers()
|
||||
// Only run the onPaid callback (e.g. navigate to 设置) when the order was
|
||||
// actually paid — closing the popup without paying must not navigate.
|
||||
const cb = paid.value ? payment.onPaid : null
|
||||
closePayment()
|
||||
if (cb) cb()
|
||||
}
|
||||
|
||||
function tick() {
|
||||
const serverNow = Date.now() / 1000 - serverOffset
|
||||
remaining.value = Math.max(0, Math.floor((order.value.expires_at || 0) - serverNow))
|
||||
}
|
||||
|
||||
watch(() => payment.show, (show) => {
|
||||
clearTimers()
|
||||
paid.value = false
|
||||
if (!show) return
|
||||
// Anchor the countdown to the server clock so a wrong local clock can't make
|
||||
// 30 minutes read as 32.
|
||||
serverOffset = order.value.server_now ? (Date.now() / 1000 - order.value.server_now) : 0
|
||||
if (order.value.status === 'paid') { onPaid(); return }
|
||||
if (isJump.value && order.value.pay_info) {
|
||||
window.open(order.value.pay_info, '_blank') // auto-jump to the cashier
|
||||
} else {
|
||||
renderQR()
|
||||
}
|
||||
tick(); tickTimer = setInterval(tick, 1000)
|
||||
poll(); pollTimer = setInterval(poll, 3000)
|
||||
})
|
||||
|
||||
onUnmounted(clearTimers)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<transition name="pay-fade">
|
||||
<div v-if="payment.show" class="fixed inset-0 z-[85] bg-slate-950/70 backdrop-blur-sm flex items-center justify-center p-4"
|
||||
@click.self="!paid && finish()">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white text-slate-800 shadow-2xl overflow-hidden">
|
||||
<div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
|
||||
<h2 class="text-base font-semibold">{{ paid ? '支付成功' : dead ? '支付超时' : (isJump ? '支付监控中' : '扫码支付') }}</h2>
|
||||
<button v-if="!paid" @click="finish" class="text-slate-400 hover:text-slate-700"><Icon name="close" class="w-5 h-5" /></button>
|
||||
</div>
|
||||
|
||||
<!-- paid -->
|
||||
<div v-if="paid" class="px-6 py-10 text-center">
|
||||
<div class="w-16 h-16 mx-auto rounded-full bg-emerald-100 text-emerald-600 grid place-items-center mb-4">
|
||||
<Icon name="spark" class="w-8 h-8" />
|
||||
</div>
|
||||
<p class="text-lg font-semibold text-slate-800">充值成功</p>
|
||||
<p class="text-sm text-slate-500 mt-1">已到账 <strong class="text-emerald-600">{{ order.points }}</strong> 积分</p>
|
||||
<p class="text-xs text-slate-400 mt-4">{{ closeIn }} 秒后自动关闭</p>
|
||||
</div>
|
||||
|
||||
<!-- expired / cancelled -->
|
||||
<div v-else-if="dead" class="px-6 py-10 text-center">
|
||||
<div class="w-16 h-16 mx-auto rounded-full bg-slate-100 text-slate-400 grid place-items-center mb-4">
|
||||
<Icon name="close" class="w-8 h-8" />
|
||||
</div>
|
||||
<p class="text-lg font-semibold text-slate-700">支付超时</p>
|
||||
<p class="text-sm text-slate-500 mt-1">二维码已失效,订单已取消</p>
|
||||
<p class="text-xs text-slate-400 mt-1">如需充值请重新下单</p>
|
||||
<button @click="finish" class="mt-5 rounded-lg bg-slate-900 text-white hover:bg-slate-700 px-5 py-2 text-sm font-medium transition-colors">关闭</button>
|
||||
</div>
|
||||
|
||||
<!-- pending -->
|
||||
<div v-else class="px-6 py-5">
|
||||
<!-- qrcode: scan to pay -->
|
||||
<template v-if="!isJump">
|
||||
<div class="flex justify-center mb-3">
|
||||
<div class="w-[228px] h-[228px] rounded-2xl ring-1 ring-slate-200 shadow-sm grid place-items-center overflow-hidden bg-white p-3.5">
|
||||
<img v-if="qrUrl" :src="qrUrl" alt="支付二维码" class="w-full h-full rounded-lg" />
|
||||
<span v-else class="text-xs text-slate-400">二维码生成中…</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-center text-xs text-slate-500 mb-4">请使用<strong class="text-slate-700">{{ methodLabel }}</strong>扫码支付</p>
|
||||
</template>
|
||||
<!-- jump (no qrcode): the cashier opened in a new tab — just monitor -->
|
||||
<template v-else>
|
||||
<div class="flex flex-col items-center justify-center py-7 mb-2">
|
||||
<div class="w-12 h-12 rounded-full border-2 border-violet-200 border-t-violet-500 animate-spin mb-3"></div>
|
||||
<p class="text-sm font-medium text-slate-700">支付监控中…</p>
|
||||
<p class="text-xs text-slate-400 mt-1">已打开支付页面,完成后自动到账</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<dl class="text-sm space-y-2">
|
||||
<div class="flex justify-between"><dt class="text-slate-400">订单号</dt><dd class="font-mono text-xs text-slate-700">{{ order.id }}</dd></div>
|
||||
<div class="flex justify-between"><dt class="text-slate-400">状态</dt><dd class="text-amber-600 font-medium">{{ statusLabel }}</dd></div>
|
||||
<div class="flex justify-between"><dt class="text-slate-400">金额</dt><dd class="font-semibold text-slate-800">¥{{ order.amount }}</dd></div>
|
||||
<div class="flex justify-between"><dt class="text-slate-400">充值积分</dt><dd class="text-violet-600 font-semibold">{{ order.points }}</dd></div>
|
||||
<div class="flex justify-between"><dt class="text-slate-400">下单时间</dt><dd class="text-xs text-slate-600">{{ fmtTime(order.created_at) }}</dd></div>
|
||||
<div class="flex justify-between"><dt class="text-slate-400">支付倒计时</dt><dd class="tabular-nums font-medium" :class="remaining > 0 ? 'text-slate-700' : 'text-rose-500'">{{ remaining > 0 ? mmss : '已超时' }}</dd></div>
|
||||
</dl>
|
||||
<p class="text-[11px] text-slate-400 mt-4 text-center">支付完成后将自动到账,请勿关闭本窗口</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pay-fade-enter-active, .pay-fade-leave-active { transition: opacity 0.2s ease; }
|
||||
.pay-fade-enter-from, .pay-fade-leave-to { opacity: 0; }
|
||||
</style>
|
||||
@@ -14,12 +14,13 @@ const tabs = [
|
||||
{ label: '账号管理', to: '/admin/accounts', icon: 'plug' },
|
||||
{ label: '用户管理', to: '/admin/users', icon: 'accounts' },
|
||||
{ label: '并发分组', to: '/admin/concurrency', icon: 'shield' },
|
||||
{ label: '兑换码', to: '/admin/cdks', icon: 'spark' },
|
||||
{ label: '订单管理', to: '/admin/orders', icon: 'receipt' },
|
||||
{ label: '兑换码管理', to: '/admin/cdks', icon: 'spark' },
|
||||
{ label: '邀请日志', to: '/admin/invites', icon: 'accounts' },
|
||||
{ label: '图片管理', to: '/admin/images', icon: 'files' },
|
||||
{ label: '首页内容', to: '/admin/showcase', icon: 'spark' },
|
||||
{ label: '日志', to: '/admin/logs', icon: 'log' },
|
||||
{ label: '配置', to: '/admin/config', icon: 'config' },
|
||||
{ label: '日志管理', to: '/admin/logs', icon: 'log' },
|
||||
{ label: '系统配置', to: '/admin/config', icon: 'config' },
|
||||
]
|
||||
|
||||
const currentLabel = computed(() => route.meta?.label || '')
|
||||
|
||||
@@ -19,6 +19,7 @@ const nav = computed(() => {
|
||||
items.push({ to: '/logs', label: '图片', icon: 'files' })
|
||||
items.push({ to: '/mylogs', label: '日志', icon: 'log' })
|
||||
items.push({ to: '/invite', label: '邀请', icon: 'accounts' })
|
||||
items.push({ to: '/orders', label: '订单', icon: 'receipt' })
|
||||
}
|
||||
// 文档 + 关于 are public — visible to guests too.
|
||||
items.push({ to: '/docs', label: '文档', icon: 'log' })
|
||||
@@ -87,7 +88,7 @@ const currentLabel = computed(() => {
|
||||
</button>
|
||||
<router-link to="/settings" title="设置" @click="onSettings"
|
||||
:class="$route.path === '/settings' ? 'rail-bottom active' : 'rail-bottom'">
|
||||
<Icon name="config" class="w-4 h-4" />
|
||||
<Icon name="accounts" class="w-4 h-4" />
|
||||
</router-link>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
+30
-4
@@ -13,6 +13,8 @@ import PlaygroundView from './views/PlaygroundView.vue'
|
||||
import UserLogsView from './views/UserLogsView.vue'
|
||||
import UserLogsTableView from './views/UserLogsTableView.vue'
|
||||
import SettingsView from './views/SettingsView.vue'
|
||||
import OrdersView from './views/OrdersView.vue'
|
||||
import AdminOrdersView from './views/AdminOrdersView.vue'
|
||||
import InviteView from './views/InviteView.vue'
|
||||
import DocsView from './views/DocsView.vue'
|
||||
import AboutView from './views/AboutView.vue'
|
||||
@@ -40,6 +42,7 @@ const routes = [
|
||||
{ path: 'invite', component: InviteView, meta: { label: '邀请' } },
|
||||
{ path: 'docs', component: DocsView, meta: { label: '文档' } },
|
||||
{ path: 'about', component: AboutView, meta: { label: '关于' } },
|
||||
{ path: 'orders', component: OrdersView, meta: { label: '订单' } },
|
||||
{ path: 'settings', component: SettingsView, meta: { label: '设置' } },
|
||||
],
|
||||
},
|
||||
@@ -53,12 +56,13 @@ const routes = [
|
||||
{ path: 'accounts', component: AccountsView, meta: { label: '账号管理' } },
|
||||
{ path: 'users', component: UsersView, meta: { label: '用户管理' } },
|
||||
{ path: 'concurrency', component: ConcurrencyView, meta: { label: '并发分组' } },
|
||||
{ path: 'cdks', component: CdksView, meta: { label: '兑换码' } },
|
||||
{ path: 'orders', component: AdminOrdersView, meta: { label: '订单管理' } },
|
||||
{ path: 'cdks', component: CdksView, meta: { label: '兑换码管理' } },
|
||||
{ path: 'invites', component: InvitesAdminView, meta: { label: '邀请日志' } },
|
||||
{ path: 'images', component: ImagesView, meta: { label: '图片管理' } },
|
||||
{ path: 'showcase', component: ShowcaseView, meta: { label: '首页内容' } },
|
||||
{ path: 'logs', component: LogsView, meta: { label: '日志' } },
|
||||
{ path: 'config', component: ConfigView, meta: { label: '配置' } },
|
||||
{ path: 'logs', component: LogsView, meta: { label: '日志管理' } },
|
||||
{ path: 'config', component: ConfigView, meta: { label: '系统配置' } },
|
||||
],
|
||||
},
|
||||
// legacy redirects
|
||||
@@ -83,7 +87,7 @@ const router = createRouter({
|
||||
|
||||
// Pages that require a login. The home page (/) stays public; everything a
|
||||
// signed-in user touches (画图/记录/设置) and the whole admin area is gated.
|
||||
const PROTECTED = ['/user', '/logs', '/invite', '/settings']
|
||||
const PROTECTED = ['/user', '/logs', '/invite', '/settings', '/orders']
|
||||
function isProtected(path) {
|
||||
return path.startsWith('/admin') || PROTECTED.includes(path)
|
||||
}
|
||||
@@ -119,3 +123,25 @@ router.afterEach(applyTitle)
|
||||
loadSite().then(() => applyTitle(router.currentRoute.value))
|
||||
|
||||
createApp(App).use(router).mount('#app')
|
||||
|
||||
// Globally strip the browser's video extras (画中画/PiP、下载、投屏、播放速率/增强菜单)
|
||||
// from EVERY <video> — applied to existing nodes + anything Vue renders later.
|
||||
// (Edge's image "视觉搜索" is handled by rendering thumbnails as CSS background
|
||||
// images instead of <img>, since there's no attribute to disable it.)
|
||||
function hardenVideo(v) {
|
||||
try {
|
||||
v.disablePictureInPicture = true
|
||||
v.disableRemotePlayback = true
|
||||
v.setAttribute('controlslist', 'nodownload noremoteplayback noplaybackrate')
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
new MutationObserver((muts) => {
|
||||
for (const m of muts) {
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType !== 1) continue
|
||||
if (n.tagName === 'VIDEO') hardenVideo(n)
|
||||
else n.querySelectorAll && n.querySelectorAll('video').forEach(hardenVideo)
|
||||
}
|
||||
}
|
||||
}).observe(document.documentElement, { childList: true, subtree: true })
|
||||
document.querySelectorAll('video').forEach(hardenVideo)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Global payment-popup state. openPayment() shows the QR-scan modal for an order
|
||||
// (returned by POST /pay/recharge or /pay/orders/:id/continue); the modal polls
|
||||
// status and fires onPaid when the order is paid.
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const payment = reactive({ show: false, order: null, onPaid: null })
|
||||
|
||||
export function openPayment(order, opts = {}) {
|
||||
payment.order = order
|
||||
payment.onPaid = typeof opts.onPaid === 'function' ? opts.onPaid : null
|
||||
payment.show = true
|
||||
}
|
||||
|
||||
export function closePayment() {
|
||||
payment.show = false
|
||||
payment.order = null
|
||||
payment.onPaid = null
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* Edge: suppress the hover "visual search / 视觉搜索" overlay icon on images and
|
||||
videos (legacy-Edge -ms-touch-action trick). Doesn't affect clicks. */
|
||||
img,
|
||||
video {
|
||||
-ms-touch-action: none;
|
||||
}
|
||||
|
||||
:root {
|
||||
font-family: "Inter", ui-sans-serif, system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
--tw-ring-color: rgb(15 23 42 / 0.08);
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<script setup>
|
||||
// Admin 订单 page — all recharge orders, dark admin look (filter pills + search +
|
||||
// numbered pagination), read-only with 用户名.
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { api } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const items = ref([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const status = ref('')
|
||||
const search = ref('')
|
||||
const page = ref(1)
|
||||
const pageSize = 20
|
||||
|
||||
const STATUS = { pending: '待支付', paid: '已支付', cancelled: '已取消' }
|
||||
const METHOD = { wxpay: '微信', alipay: '支付宝' }
|
||||
const chipClass = (s) => ({
|
||||
paid: 'fp-emerald', pending: 'fp-amber', cancelled: '',
|
||||
}[s] || '')
|
||||
|
||||
function fmt(unix) {
|
||||
if (!unix) return '—'
|
||||
const d = new Date(unix * 1000)
|
||||
const p = (n) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
const qs = new URLSearchParams({ limit: String(pageSize), offset: String((page.value - 1) * pageSize) })
|
||||
if (status.value) qs.set('status', status.value)
|
||||
const r = await api('/pay/admin/orders?' + qs.toString())
|
||||
loading.value = false
|
||||
if (r.ok) {
|
||||
items.value = r.data?.data || []
|
||||
total.value = Number(r.data?.total ?? items.value.length)
|
||||
}
|
||||
}
|
||||
onMounted(load)
|
||||
|
||||
const displayed = computed(() => {
|
||||
const q = search.value.trim().toLowerCase()
|
||||
if (!q) return items.value
|
||||
return items.value.filter((o) =>
|
||||
(o.id || '').toLowerCase().includes(q) ||
|
||||
(o.user_name || '').toLowerCase().includes(q) ||
|
||||
String(o.amount).includes(q))
|
||||
})
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
const pageStart = computed(() => total.value === 0 ? 0 : (page.value - 1) * pageSize + 1)
|
||||
const pageEnd = computed(() => Math.min(total.value, page.value * pageSize))
|
||||
function setStatus(v) { status.value = v; page.value = 1; load() }
|
||||
const pageNumbers = computed(() => {
|
||||
const n = totalPages.value, cur = page.value
|
||||
if (n <= 7) return Array.from({ length: n }, (_, i) => i + 1)
|
||||
const want = new Set([1, n, cur - 1, cur, cur + 1])
|
||||
if (cur <= 3) { want.add(2); want.add(3); want.add(4) }
|
||||
if (cur >= n - 2) { want.add(n - 1); want.add(n - 2); want.add(n - 3) }
|
||||
const list = [...want].filter((x) => x >= 1 && x <= n).sort((a, b) => a - b)
|
||||
const out = []
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (i > 0 && list[i] - list[i - 1] > 1) out.push(null)
|
||||
out.push(list[i])
|
||||
}
|
||||
return out
|
||||
})
|
||||
function goPage(n) {
|
||||
const t = Math.max(1, Math.min(totalPages.value, n))
|
||||
if (t === page.value) return
|
||||
page.value = t; load()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="theme-text space-y-4">
|
||||
<div class="card p-4 flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">订单管理</h2>
|
||||
<p class="text-xs text-white/45 mt-0.5">{{ total }} 笔充值订单</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button v-for="s in [['','全部'],['pending','待支付'],['paid','已支付'],['cancelled','已取消']]" :key="s[0]"
|
||||
@click="setStatus(s[0])" class="fp" :class="status === s[0] && 'fp-on'">{{ s[1] }}</button>
|
||||
</div>
|
||||
<input v-model="search" class="field !py-1.5 text-xs !w-52" placeholder="搜索 订单号 / 用户名 / 金额…" />
|
||||
<button @click="load" class="btn-soft"><Icon name="refresh" class="w-3.5 h-3.5" /> 刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading && !items.length" class="card text-center text-sm text-white/40 py-20">加载中…</div>
|
||||
<div v-else-if="!total" class="card text-center text-sm text-white/40 py-20">暂无订单</div>
|
||||
|
||||
<div v-else class="card overflow-x-auto !p-0">
|
||||
<table class="w-full text-sm log-table min-w-[820px]">
|
||||
<thead>
|
||||
<tr class="text-[10px] uppercase tracking-[0.18em] text-white/40 border-b border-white/[0.06]">
|
||||
<th class="text-left px-5 py-3 font-medium">订单号</th>
|
||||
<th class="text-left px-3 py-3 font-medium">用户名</th>
|
||||
<th class="text-left px-3 py-3 font-medium">下单时间</th>
|
||||
<th class="text-left px-3 py-3 font-medium">支付时间</th>
|
||||
<th class="text-right px-3 py-3 font-medium">金额</th>
|
||||
<th class="text-right px-3 py-3 font-medium">充值积分</th>
|
||||
<th class="text-left px-3 py-3 font-medium">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="o in displayed" :key="o.id" class="log-row">
|
||||
<td class="px-5 py-3.5 align-middle font-mono text-xs text-white/80">{{ o.id }}</td>
|
||||
<td class="px-3 py-3.5 align-middle text-white/85 truncate max-w-[140px]" :title="o.user_name">{{ o.user_name || '—' }}</td>
|
||||
<td class="px-3 py-3.5 align-middle text-xs text-white/55 whitespace-nowrap">{{ fmt(o.created_at) }}</td>
|
||||
<td class="px-3 py-3.5 align-middle text-xs text-white/55 whitespace-nowrap">{{ fmt(o.paid_at) }}</td>
|
||||
<td class="px-3 py-3.5 align-middle text-right tabular-nums text-white/85">¥{{ o.amount }}</td>
|
||||
<td class="px-3 py-3.5 align-middle text-right tabular-nums text-violet-300">{{ o.points }}</td>
|
||||
<td class="px-3 py-3.5 align-middle">
|
||||
<span class="chip" :class="chipClass(o.status)">{{ STATUS[o.status] }}<span class="opacity-50 ml-1">· {{ METHOD[o.pay_type] || o.pay_type }}</span></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-if="total && totalPages > 1"
|
||||
class="flex items-center justify-between gap-3 border-t border-white/[0.06] px-5 py-3 text-xs text-white/50">
|
||||
<div><span class="tabular-nums text-white/75">{{ pageStart }}–{{ pageEnd }}</span><span class="ml-1">/ {{ total }} 笔</span></div>
|
||||
<div class="flex items-center gap-1">
|
||||
<template v-for="(n, i) in pageNumbers" :key="i">
|
||||
<span v-if="n === null" class="px-1 text-white/30">…</span>
|
||||
<button v-else @click="goPage(n)" class="pg" :class="page === n && 'pg-on'">{{ n }}</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.fp { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.35rem 0.7rem; font-size: 0.72rem; border-radius: 0.55rem; color: rgb(255 255 255 / 0.65); background: rgb(255 255 255 / 0.05); box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.06); transition: background 0.15s, color 0.15s; }
|
||||
.fp:hover { background: rgb(255 255 255 / 0.09); color: white; }
|
||||
.fp-on { background: rgb(255 255 255 / 0.92); color: rgb(15 23 42); box-shadow: none; }
|
||||
.fp-emerald { background: rgb(16 185 129 / 0.22); color: rgb(110 231 183); box-shadow: inset 0 0 0 1px rgb(110 231 183 / 0.45); }
|
||||
.fp-amber { background: rgb(245 158 11 / 0.22); color: rgb(252 211 77); box-shadow: inset 0 0 0 1px rgb(252 211 77 / 0.45); }
|
||||
.chip { display: inline-flex; align-items: center; gap: 0.3rem; padding: 0.18rem 0.55rem; font-size: 0.7rem; font-weight: 500; border-radius: 9999px; white-space: nowrap; background: rgb(255 255 255 / 0.06); color: rgb(255 255 255 / 0.55); box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.1); }
|
||||
.log-table { border-collapse: separate; border-spacing: 0; }
|
||||
.log-row td { border-bottom: 1px solid rgb(255 255 255 / 0.04); transition: background-color 0.15s ease, box-shadow 0.15s ease; }
|
||||
.log-row:hover td { background: rgb(255 255 255 / 0.025); }
|
||||
.log-row:hover td:first-child { box-shadow: inset 2px 0 0 rgb(167 139 250 / 0.55); }
|
||||
.log-row:last-child td { border-bottom: none; }
|
||||
.pg { min-width: 1.75rem; padding: 0.3rem 0.55rem; font-size: 0.72rem; font-weight: 500; text-align: center; border-radius: 0.45rem; color: rgb(255 255 255 / 0.7); background: rgb(255 255 255 / 0.04); box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.08); transition: background 0.15s, color 0.15s; }
|
||||
.pg:hover:not(.pg-on) { background: rgb(255 255 255 / 0.1); color: white; }
|
||||
.pg-on { background: rgb(255 255 255 / 0.92); color: rgb(15 23 42); box-shadow: none; }
|
||||
</style>
|
||||
@@ -120,6 +120,42 @@ const smtpBusy = ref(false); const smtpSaved = ref(false)
|
||||
const credits = reactive({ checkin_enabled: true, checkin_reward: 3, invite_enabled: true, invite_reward: 3, cdk_redeem_enabled: true })
|
||||
const credBusy = ref(false); const credSaved = ref(false)
|
||||
|
||||
// ---- announcement (公告, markdown; re-pops for users who haven't seen edits) ----
|
||||
const ann = reactive({ content: '' })
|
||||
const annBusy = ref(false); const annSaved = ref(false)
|
||||
async function loadAnnouncement() {
|
||||
const r = await api('/settings/announcement')
|
||||
if (r.ok && r.data) ann.content = r.data.content || ''
|
||||
}
|
||||
async function saveAnnouncement() {
|
||||
annBusy.value = true; annSaved.value = false
|
||||
const r = await api('/settings/announcement', jsonBody('PUT', { content: ann.content }))
|
||||
annBusy.value = false
|
||||
if (r.ok) { annSaved.value = true; setTimeout(() => (annSaved.value = false), 2000) }
|
||||
}
|
||||
|
||||
// ---- payment (易支付 充值) ----
|
||||
const pay = reactive({ enabled: false, pid: '', key: '', api_base: '', methods: ['wxpay', 'alipay'], min_amount: 1, points_ratio: 100 })
|
||||
const payBusy = ref(false); const paySaved = ref(false); const payErr = ref('')
|
||||
const PAY_METHODS = [{ v: 'wxpay', label: '微信' }, { v: 'alipay', label: '支付宝' }]
|
||||
async function loadPay() {
|
||||
const r = await api('/settings/pay')
|
||||
if (r.ok && r.data) Object.assign(pay, r.data, { methods: r.data.methods || [] })
|
||||
}
|
||||
function togglePayMethod(m) {
|
||||
const i = pay.methods.indexOf(m)
|
||||
if (i >= 0) pay.methods.splice(i, 1); else pay.methods.push(m)
|
||||
}
|
||||
async function savePay() {
|
||||
payBusy.value = true; paySaved.value = false; payErr.value = ''
|
||||
const r = await api('/settings/pay', jsonBody('PUT', {
|
||||
...pay, min_amount: Number(pay.min_amount) || 0, points_ratio: Number(pay.points_ratio) || 100,
|
||||
}))
|
||||
payBusy.value = false
|
||||
if (r.ok) { paySaved.value = true; setTimeout(() => (paySaved.value = false), 2000) }
|
||||
else payErr.value = r.data?.detail || '保存失败'
|
||||
}
|
||||
|
||||
// ---- proxy (carried when calling upstream during generation) ----
|
||||
const proxy = reactive({ proxy: '' })
|
||||
const proxyBusy = ref(false); const proxySaved = ref(false)
|
||||
@@ -233,7 +269,7 @@ async function saveCredits() {
|
||||
if (r.ok) { credSaved.value = true; setTimeout(() => (credSaved.value = false), 2000) }
|
||||
}
|
||||
|
||||
onMounted(() => { loadSite(); loadReg(); loadSmtp(); loadCredits(); loadProxy(); loadLogs(); loadMedia() })
|
||||
onMounted(() => { loadSite(); loadReg(); loadSmtp(); loadCredits(); loadAnnouncement(); loadPay(); loadProxy(); loadLogs(); loadMedia() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -426,6 +462,64 @@ onMounted(() => { loadSite(); loadReg(); loadSmtp(); loadCredits(); loadProxy();
|
||||
<div class="mt-4"><button @click="saveCredits" :disabled="credBusy" class="btn-primary">{{ credBusy ? '保存中…' : '保存设置' }}</button></div>
|
||||
</div>
|
||||
|
||||
<!-- announcement (公告) -->
|
||||
<div class="card p-5">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<h2 class="text-sm font-semibold">公告</h2>
|
||||
<span v-if="annSaved" class="text-xs text-emerald-500">已保存</span>
|
||||
</div>
|
||||
<p class="text-xs text-slate-400 mb-3">支持 Markdown。登录用户会在首次访问时弹出;<strong class="text-slate-500">更新内容后</strong>,所有没看过新版本的用户会重新弹出。留空则不显示。</p>
|
||||
<textarea v-model="ann.content" rows="8" placeholder="# 标题 支持 **加粗**、列表、[链接](https://...)、`代码` 等 Markdown 语法。"
|
||||
class="field font-mono text-xs leading-relaxed" style="resize:vertical"></textarea>
|
||||
<div class="mt-4"><button @click="saveAnnouncement" :disabled="annBusy" class="btn-primary">{{ annBusy ? '保存中…' : '保存设置' }}</button></div>
|
||||
</div>
|
||||
|
||||
<!-- payment (易支付充值) -->
|
||||
<div class="card p-5">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<h2 class="text-sm font-semibold">充值 (易支付)</h2>
|
||||
<span v-if="paySaved" class="text-xs text-emerald-500">已保存</span>
|
||||
</div>
|
||||
<p class="text-xs text-slate-400 mb-3">对接易支付。关闭后用户看不到充值入口。商户ID、密钥、支付地址不能为空。</p>
|
||||
<div class="space-y-3">
|
||||
<label class="row">
|
||||
<span><span class="lbl">开启充值</span><span class="hint">关闭后前台不显示充值入口,且无法下单。</span></span>
|
||||
<input type="checkbox" v-model="pay.enabled" class="sw" />
|
||||
</label>
|
||||
<label class="row">
|
||||
<span><span class="lbl">支付地址</span><span class="hint">易支付 API 根地址,自动拼 /mapi。</span></span>
|
||||
<input v-model="pay.api_base" placeholder="https://pay.v8jisu.cn/api/pay" class="field !w-64" />
|
||||
</label>
|
||||
<label class="row">
|
||||
<span><span class="lbl">商户ID (PID)</span></span>
|
||||
<input v-model="pay.pid" class="field !w-64" />
|
||||
</label>
|
||||
<label class="row">
|
||||
<span><span class="lbl">商户密钥</span></span>
|
||||
<input v-model="pay.key" type="password" class="field !w-64" />
|
||||
</label>
|
||||
<div class="row">
|
||||
<span><span class="lbl">支付方式</span><span class="hint">勾选哪些,前台就只显示哪些。</span></span>
|
||||
<div class="flex gap-3">
|
||||
<label v-for="m in PAY_METHODS" :key="m.v" class="inline-flex items-center gap-1.5 text-sm cursor-pointer">
|
||||
<input type="checkbox" :checked="pay.methods.includes(m.v)" @change="togglePayMethod(m.v)" />
|
||||
{{ m.label }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<label class="row">
|
||||
<span><span class="lbl">最低充值金额 (元)</span></span>
|
||||
<input type="number" min="0" step="0.01" v-model.number="pay.min_amount" class="num" />
|
||||
</label>
|
||||
<label class="row">
|
||||
<span><span class="lbl">积分充值比例</span><span class="hint">1 元 = 多少积分。例如 100 → 充 10 元到账 1000 积分。</span></span>
|
||||
<input type="number" min="1" v-model.number="pay.points_ratio" class="num" />
|
||||
</label>
|
||||
</div>
|
||||
<p v-if="payErr" class="text-xs text-rose-500 mt-3">{{ payErr }}</p>
|
||||
<div class="mt-4"><button @click="savePay" :disabled="payBusy" class="btn-primary">{{ payBusy ? '保存中…' : '保存设置' }}</button></div>
|
||||
</div>
|
||||
|
||||
<!-- logs retention -->
|
||||
<div class="card p-5">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
|
||||
@@ -144,8 +144,9 @@ onUnmounted(() => window.removeEventListener('keydown', onKey))
|
||||
@mouseenter="$event.target.play && $event.target.play()"
|
||||
@mouseleave="$event.target.pause && $event.target.pause()" />
|
||||
</template>
|
||||
<img v-else :src="generatedUrl(f.name)" loading="lazy"
|
||||
class="absolute inset-0 w-full h-full object-cover transition-transform duration-300 group-hover:scale-105" />
|
||||
<!-- background-image (not <img>) so Edge shows no 视觉搜索 overlay icon. -->
|
||||
<div v-else :style="{ backgroundImage: `url(${generatedUrl(f.name)})` }"
|
||||
class="absolute inset-0 w-full h-full bg-cover bg-center transition-transform duration-300 group-hover:scale-105"></div>
|
||||
|
||||
<!-- gradient veil (always visible so the prompt overlay reads) -->
|
||||
<div class="absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-black/85 via-black/40 to-transparent pointer-events-none"></div>
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
<script setup>
|
||||
// Front-end 订单 page — the signed-in user's own recharge orders. Same light look
|
||||
// as the 日志 page: filter pills + search + numbered pagination. Unpaid/cancelled
|
||||
// orders can be resumed via 继续支付.
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api, jsonBody } from '../api'
|
||||
import { openPayment } from '../payment'
|
||||
import { refreshMe } from '../auth'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const items = ref([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const status = ref('') // '' | pending | paid | cancelled
|
||||
const search = ref('')
|
||||
const page = ref(1)
|
||||
const pageSize = 20
|
||||
|
||||
const STATUS = { pending: '待支付', paid: '已支付', cancelled: '已取消' }
|
||||
const METHOD = { wxpay: '微信', alipay: '支付宝' }
|
||||
const statusPill = (s) => ({
|
||||
paid: 'bg-emerald-50 text-emerald-700 ring-emerald-200',
|
||||
pending: 'bg-amber-50 text-amber-700 ring-amber-200',
|
||||
cancelled: 'bg-slate-100 text-slate-500 ring-slate-200',
|
||||
}[s] || 'bg-slate-100 text-slate-500 ring-slate-200')
|
||||
const statusDot = (s) => ({ paid: 'bg-emerald-500', pending: 'bg-amber-500', cancelled: 'bg-slate-400' }[s] || 'bg-slate-400')
|
||||
|
||||
function fmt(unix) {
|
||||
if (!unix) return '—'
|
||||
const d = new Date(unix * 1000)
|
||||
const p = (n) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
const qs = new URLSearchParams({ limit: String(pageSize), offset: String((page.value - 1) * pageSize) })
|
||||
if (status.value) qs.set('status', status.value)
|
||||
const r = await api('/pay/orders?' + qs.toString())
|
||||
loading.value = false
|
||||
if (r.ok) {
|
||||
items.value = r.data?.data || []
|
||||
total.value = Number(r.data?.total ?? items.value.length)
|
||||
}
|
||||
}
|
||||
onMounted(load)
|
||||
|
||||
const displayed = computed(() => {
|
||||
const q = search.value.trim().toLowerCase()
|
||||
if (!q) return items.value
|
||||
return items.value.filter((o) =>
|
||||
(o.id || '').toLowerCase().includes(q) ||
|
||||
String(o.amount).includes(q) ||
|
||||
(METHOD[o.pay_type] || '').includes(q))
|
||||
})
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
const pageStart = computed(() => total.value === 0 ? 0 : (page.value - 1) * pageSize + 1)
|
||||
const pageEnd = computed(() => Math.min(total.value, page.value * pageSize))
|
||||
function setStatus(v) { status.value = v; page.value = 1; load() }
|
||||
const pageNumbers = computed(() => {
|
||||
const n = totalPages.value, cur = page.value
|
||||
if (n <= 7) return Array.from({ length: n }, (_, i) => i + 1)
|
||||
const want = new Set([1, n, cur - 1, cur, cur + 1])
|
||||
if (cur <= 3) { want.add(2); want.add(3); want.add(4) }
|
||||
if (cur >= n - 2) { want.add(n - 1); want.add(n - 2); want.add(n - 3) }
|
||||
const list = [...want].filter((x) => x >= 1 && x <= n).sort((a, b) => a - b)
|
||||
const out = []
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (i > 0 && list[i] - list[i - 1] > 1) out.push(null)
|
||||
out.push(list[i])
|
||||
}
|
||||
return out
|
||||
})
|
||||
function goPage(n) {
|
||||
const t = Math.max(1, Math.min(totalPages.value, n))
|
||||
if (t === page.value) return
|
||||
page.value = t; load()
|
||||
}
|
||||
|
||||
const continuingId = ref('')
|
||||
async function cont(o) {
|
||||
if (continuingId.value) return
|
||||
continuingId.value = o.id
|
||||
try {
|
||||
const r = await api(`/pay/orders/${o.id}/continue`, jsonBody('POST', {}))
|
||||
if (!r.ok) return
|
||||
openPayment(r.data, { onPaid: () => { refreshMe(); router.push('/settings') } })
|
||||
} finally {
|
||||
continuingId.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="space-y-5 log-page">
|
||||
<div class="flex items-end justify-between flex-wrap gap-3">
|
||||
<div>
|
||||
<h1 class="text-2xl font-semibold tracking-tight text-slate-900">订单</h1>
|
||||
<p class="text-sm text-slate-500 mt-1">{{ total }} 笔充值订单 · 未支付可继续支付</p>
|
||||
</div>
|
||||
<button @click="router.push('/settings')" class="btn-primary"><Icon name="spark" class="w-4 h-4" /> 去充值</button>
|
||||
</div>
|
||||
|
||||
<!-- Filter bar -->
|
||||
<div class="card p-3 flex items-center gap-3 flex-wrap">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button v-for="s in [['','全部'],['pending','待支付'],['paid','已支付'],['cancelled','已取消']]" :key="s[0]"
|
||||
@click="setStatus(s[0])"
|
||||
class="text-xs rounded-lg px-2.5 py-1.5 transition-colors"
|
||||
:class="status === s[0] ? 'bg-slate-900 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'">{{ s[1] }}</button>
|
||||
</div>
|
||||
<div class="flex-1 min-w-[180px]">
|
||||
<input v-model="search" class="field !py-1.5 text-xs" placeholder="搜索 订单号 / 金额 / 方式…" />
|
||||
</div>
|
||||
<button @click="load" class="btn-soft"><Icon name="refresh" class="w-3.5 h-3.5" /> 刷新</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading && !items.length" class="card text-center text-sm text-slate-400 py-24">加载中…</div>
|
||||
<div v-else-if="!total" class="card flex flex-col items-center gap-3 text-slate-400 py-24">
|
||||
<span class="w-14 h-14 rounded-2xl bg-slate-100 grid place-items-center"><Icon name="log" class="w-6 h-6" /></span>
|
||||
<span class="text-sm">还没有充值订单</span>
|
||||
</div>
|
||||
|
||||
<div v-else class="card overflow-hidden !p-0">
|
||||
<table class="w-full text-sm log-table">
|
||||
<thead>
|
||||
<tr class="text-[10px] uppercase tracking-[0.18em] text-slate-400 border-b border-slate-200">
|
||||
<th class="text-left px-4 py-3 font-medium">订单号</th>
|
||||
<th class="text-left px-3 py-3 font-medium">下单时间</th>
|
||||
<th class="text-left px-3 py-3 font-medium">支付时间</th>
|
||||
<th class="text-right px-3 py-3 font-medium">金额</th>
|
||||
<th class="text-right px-3 py-3 font-medium">充值积分</th>
|
||||
<th class="text-left px-3 py-3 font-medium">状态</th>
|
||||
<th class="text-right px-4 py-3 font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="o in displayed" :key="o.id" class="log-row">
|
||||
<td class="px-4 py-3 align-middle font-mono text-xs text-slate-700">{{ o.id }}</td>
|
||||
<td class="px-3 py-3 align-middle text-xs text-slate-500 whitespace-nowrap">{{ fmt(o.created_at) }}</td>
|
||||
<td class="px-3 py-3 align-middle text-xs text-slate-500 whitespace-nowrap">{{ fmt(o.paid_at) }}</td>
|
||||
<td class="px-3 py-3 align-middle text-right tabular-nums text-slate-800 font-medium">¥{{ o.amount }}</td>
|
||||
<td class="px-3 py-3 align-middle text-right tabular-nums text-violet-600 font-medium">{{ o.points }}</td>
|
||||
<td class="px-3 py-3 align-middle">
|
||||
<span class="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-medium ring-1 whitespace-nowrap" :class="statusPill(o.status)">
|
||||
<span class="w-1.5 h-1.5 rounded-full" :class="statusDot(o.status)"></span>{{ STATUS[o.status] }}
|
||||
<span class="text-slate-400">· {{ METHOD[o.pay_type] || o.pay_type }}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 align-middle text-right">
|
||||
<button v-if="o.status === 'pending'" @click="cont(o)" :disabled="continuingId === o.id"
|
||||
class="rounded-lg bg-violet-600 text-white hover:bg-violet-500 disabled:opacity-60 disabled:cursor-not-allowed px-3 py-1.5 text-xs font-medium transition-colors inline-flex items-center gap-1.5">
|
||||
<span v-if="continuingId === o.id" class="w-3 h-3 rounded-full border-2 border-white/40 border-t-white animate-spin"></span>
|
||||
{{ continuingId === o.id ? '处理中…' : '继续支付' }}
|
||||
</button>
|
||||
<span v-else class="text-xs text-slate-300">—</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-if="total && totalPages > 1"
|
||||
class="flex items-center justify-between gap-3 border-t border-slate-200 px-5 py-3 text-xs text-slate-500">
|
||||
<div><span class="tabular-nums text-slate-700">{{ pageStart }}–{{ pageEnd }}</span><span class="ml-1">/ {{ total }} 笔</span></div>
|
||||
<div class="flex items-center gap-1">
|
||||
<template v-for="(n, i) in pageNumbers" :key="i">
|
||||
<span v-if="n === null" class="px-1 text-slate-300">…</span>
|
||||
<button v-else @click="goPage(n)" class="pg" :class="page === n && 'pg-on'">{{ n }}</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.log-table { border-collapse: separate; border-spacing: 0; }
|
||||
.log-row td { border-bottom: 1px solid rgb(15 23 42 / 0.06); transition: background-color 0.15s ease, box-shadow 0.15s ease; }
|
||||
.log-row:hover td { background: rgb(15 23 42 / 0.025); }
|
||||
.log-row:hover td:first-child { box-shadow: inset 2px 0 0 rgb(124 58 237 / 0.6); }
|
||||
.log-row:last-child td { border-bottom: none; }
|
||||
.pg {
|
||||
min-width: 1.75rem; padding: 0.3rem 0.55rem; font-size: 0.72rem; font-weight: 500; text-align: center;
|
||||
border-radius: 0.45rem; color: rgb(71 85 105); background: rgb(241 245 249);
|
||||
box-shadow: inset 0 0 0 1px rgb(15 23 42 / 0.06); transition: background 0.15s, color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.pg:hover:not(.pg-on) { background: rgb(226 232 240); color: rgb(15 23 42); }
|
||||
.pg-on { background: rgb(15 23 42); color: white; box-shadow: none; }
|
||||
</style>
|
||||
@@ -360,7 +360,7 @@ let prevPending = 0
|
||||
async function loadHistory() {
|
||||
// Server-side filter: status IN (pending, success), newest 12 — exactly the
|
||||
// rows the grid shows, in one query (no client over-fetch).
|
||||
const r = await api('/logs?limit=10&statuses=pending,success')
|
||||
const r = await api('/logs?limit=10&statuses=pending,success&source=user')
|
||||
if (!r.ok) return
|
||||
history.value = (r.data?.data || [])
|
||||
.filter((e) => e.status === 'pending' || e.file)
|
||||
@@ -432,20 +432,16 @@ function lastFrameDataUrl(url) {
|
||||
})
|
||||
}
|
||||
|
||||
// Click a generated VIDEO. For a 首尾帧 (frame) model, set the video's LAST frame
|
||||
// as the 首帧 (first reference) — to continue the scene. Otherwise just zoom.
|
||||
async function onVideoClick(item) {
|
||||
if (refMode.value === 'frame' && maxRefs.value > 0 && item.url) {
|
||||
const dataUrl = await lastFrameDataUrl(item.url)
|
||||
if (dataUrl) {
|
||||
const ref = { name: 'frame', dataUrl }
|
||||
if (refImages.value.length === 0) refImages.value = [ref]
|
||||
else refImages.value.splice(0, 1, ref) // replace the 首帧 slot
|
||||
flash('已把视频末帧设为首帧')
|
||||
return
|
||||
}
|
||||
}
|
||||
lightbox.value = item
|
||||
// Use a generated VIDEO's LAST frame as the 首帧 (first reference) — 首尾帧
|
||||
// (frame) models only. Triggered by the small button; clicking the video zooms.
|
||||
async function useVideoFrame(item) {
|
||||
if (!item || !item.url) return
|
||||
const dataUrl = await lastFrameDataUrl(item.url)
|
||||
if (!dataUrl) { flash('截取末帧失败'); return }
|
||||
const ref = { name: 'frame', dataUrl }
|
||||
if (refImages.value.length === 0) refImages.value = [ref]
|
||||
else refImages.value.splice(0, 1, ref) // replace the 首帧 slot
|
||||
flash('已把视频末帧设为首帧')
|
||||
}
|
||||
|
||||
function onKey(e) { if (e.key === 'Escape') lightbox.value = null }
|
||||
@@ -639,26 +635,28 @@ onUnmounted(() => {
|
||||
<!-- done: media + caption -->
|
||||
<template v-if="item.status === 'done' && item.url">
|
||||
<video v-if="item.kind === 'video'" :src="item.url" muted loop preload="metadata"
|
||||
@click="onVideoClick(item)"
|
||||
:title="refMode === 'frame' && maxRefs > 0 ? '点击:把末帧设为首帧' : '点击放大'"
|
||||
class="absolute inset-0 w-full h-full object-cover cursor-pointer"
|
||||
@click="lightbox = item" title="点击放大"
|
||||
class="absolute inset-0 w-full h-full object-cover cursor-zoom-in"
|
||||
@mouseenter="$event.target.play && $event.target.play()"
|
||||
@mouseleave="$event.target.pause && $event.target.pause()" />
|
||||
<img v-else :src="item.url" loading="lazy" @click="useAsRef(item)"
|
||||
:title="maxRefs > 0 ? '点击作为参考图' : ''"
|
||||
class="absolute inset-0 w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
:class="maxRefs > 0 ? 'cursor-pointer' : 'cursor-default'" />
|
||||
<!-- background-image (not <img>) so Edge shows no 视觉搜索 overlay icon. -->
|
||||
<div v-else @click="lightbox = item" title="点击放大"
|
||||
:style="{ backgroundImage: `url(${item.url})` }"
|
||||
class="absolute inset-0 w-full h-full bg-cover bg-center cursor-zoom-in transition-transform duration-300 group-hover:scale-105"></div>
|
||||
<div class="absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-black/85 via-black/30 to-transparent pointer-events-none"></div>
|
||||
<!-- hover action: just zoom (clicking the image itself = 参考图) -->
|
||||
<!-- hover action: 上参考图. Image → use as reference; video → 末帧设为首帧
|
||||
(only shown when the model supports 首尾帧). Clicking the media zooms. -->
|
||||
<div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button @click.stop="lightbox = item" title="放大"
|
||||
<button v-if="item.kind === 'video' ? (refMode === 'frame' && maxRefs > 0) : (maxRefs > 0)"
|
||||
@click.stop="item.kind === 'video' ? useVideoFrame(item) : useAsRef(item)"
|
||||
:title="item.kind === 'video' ? '把末帧设为首帧' : '作为参考图'"
|
||||
class="w-7 h-7 rounded-lg bg-black/50 ring-1 ring-white/10 hover:bg-black/70 text-white grid place-items-center">
|
||||
<Icon name="open" class="w-3.5 h-3.5" />
|
||||
<Icon name="plus" class="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="absolute inset-x-0 bottom-0 p-2.5 pointer-events-none">
|
||||
<div class="text-[11px] leading-tight text-white font-medium line-clamp-2" :title="item.prompt">{{ item.prompt }}</div>
|
||||
<div class="text-[9px] text-white/55 mt-0.5 font-mono truncate">{{ item.model }}<span v-if="item.elapsed_ms"> · {{ (item.elapsed_ms / 1000).toFixed(1) }}s</span></div>
|
||||
<div class="pg-cap text-[11px] leading-tight font-medium line-clamp-2" :title="item.prompt">{{ item.prompt }}</div>
|
||||
<div class="pg-cap-sub text-[9px] mt-0.5 font-mono truncate">{{ item.model }}<span v-if="item.elapsed_ms"> · {{ (item.elapsed_ms / 1000).toFixed(1) }}s</span></div>
|
||||
</div>
|
||||
</template>
|
||||
<!-- pending / running -->
|
||||
@@ -705,4 +703,10 @@ onUnmounted(() => {
|
||||
<style scoped>
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity 0.15s ease; }
|
||||
.fade-enter-from, .fade-leave-to { opacity: 0; }
|
||||
|
||||
/* Card captions sit on a dark gradient — keep them white even in light theme.
|
||||
The global `.theme-text` remap would otherwise darken them (it turns
|
||||
over-image whites dark for the marketing pages), making them unreadable here. */
|
||||
.pg-cap { color: #fff !important; }
|
||||
.pg-cap-sub { color: rgb(255 255 255 / 0.62) !important; }
|
||||
</style>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { auth, refreshMe, logout as authLogout } from '../auth'
|
||||
import { api, jsonBody } from '../api'
|
||||
import { openPayment } from '../payment'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { points, pointsLabel } from '../credits'
|
||||
import { site } from '../site'
|
||||
@@ -174,6 +175,41 @@ function toast(m) {
|
||||
clearTimeout(toastTimer)
|
||||
toastTimer = setTimeout(() => (toastMsg.value = ''), 2200)
|
||||
}
|
||||
|
||||
// ---- Recharge (易支付) ----
|
||||
const payCfg = ref({ enabled: false, methods: [], min_amount: 0, points_ratio: 100 })
|
||||
const AMOUNTS = [10, 20, 50, 100]
|
||||
const picked = ref(10) // a preset number, or 'custom'
|
||||
const customAmount = ref('')
|
||||
const payMethod = ref('')
|
||||
const rechargeTotal = computed(() => Number(auth.user?.recharge_total || 0))
|
||||
const methodName = (m) => ({ wxpay: '微信', alipay: '支付宝' }[m] || m)
|
||||
const finalAmount = computed(() => Number(picked.value === 'custom' ? customAmount.value : picked.value) || 0)
|
||||
const pointsPreview = computed(() => Math.round(finalAmount.value * (payCfg.value.points_ratio || 0)))
|
||||
async function loadPayCfg() {
|
||||
const r = await api('/pay/config')
|
||||
if (r.ok && r.data) {
|
||||
payCfg.value = r.data
|
||||
if (r.data.methods?.length && !payMethod.value) payMethod.value = r.data.methods[0]
|
||||
}
|
||||
}
|
||||
onMounted(loadPayCfg)
|
||||
const recharging = ref(false)
|
||||
async function recharge() {
|
||||
if (recharging.value) return
|
||||
const amt = finalAmount.value
|
||||
if (!amt || amt <= 0) { toast('请输入有效金额'); return }
|
||||
if (amt < payCfg.value.min_amount) { toast(`最低充值 ${payCfg.value.min_amount} 元`); return }
|
||||
if (!payMethod.value) { toast('请选择支付方式'); return }
|
||||
recharging.value = true
|
||||
try {
|
||||
const r = await api('/pay/recharge', jsonBody('POST', { amount: amt, method: payMethod.value }))
|
||||
if (!r.ok) { toast(r.data?.detail || '下单失败'); return }
|
||||
openPayment(r.data, { onPaid: refreshMe })
|
||||
} finally {
|
||||
recharging.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -214,6 +250,10 @@ function toast(m) {
|
||||
<div class="text-[11px] text-white/40 uppercase tracking-wider mb-1">积分余额</div>
|
||||
<div class="text-amber-300 font-semibold tabular-nums">{{ pointsLabel(balance) }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-[11px] text-white/40 uppercase tracking-wider mb-1">累计充值</div>
|
||||
<div class="text-emerald-300 font-semibold tabular-nums">¥{{ rechargeTotal }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-[11px] text-white/40 uppercase tracking-wider mb-1">并发上限</div>
|
||||
<div class="text-white/90 truncate" :title="concurrencyLabel">{{ concurrencyLabel }}</div>
|
||||
@@ -302,9 +342,9 @@ function toast(m) {
|
||||
<div v-for="(d, i) in last7" :key="d.ds"
|
||||
class="flex-1 h-12 rounded-xl ring-1 transition-all flex flex-col items-center justify-center"
|
||||
:class="d.lit
|
||||
? 'bg-sky-400/25 ring-sky-300/50 text-sky-100'
|
||||
? 'bg-sky-500 ring-sky-400 text-white'
|
||||
: d.isToday
|
||||
? (checkedToday ? 'bg-sky-400/25 ring-sky-300/50 text-sky-100' : 'bg-white/[0.05] ring-white/15 text-white/60')
|
||||
? (checkedToday ? 'bg-sky-500 ring-sky-400 text-white' : 'bg-white/[0.05] ring-white/15 text-white/60')
|
||||
: 'bg-white/[0.02] ring-white/[0.06] text-white/30'">
|
||||
<Icon v-if="d.lit || (d.isToday && checkedToday)" name="spark" class="w-3 h-3" />
|
||||
<span v-else class="text-[10px] uppercase">{{ d.isToday ? '今' : i + 1 }}</span>
|
||||
@@ -317,6 +357,35 @@ function toast(m) {
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<!-- RECHARGE (易支付) — hidden unless the admin enabled 充值 -->
|
||||
<section v-if="payCfg.enabled" class="relative card p-7 md:p-8 overflow-hidden">
|
||||
<div class="inline-grid w-10 h-10 rounded-xl bg-emerald-500/15 ring-1 ring-emerald-400/30 grid place-items-center text-emerald-300">
|
||||
<Icon name="spark" class="w-4 h-4" />
|
||||
</div>
|
||||
<h2 class="text-xl font-bold mt-4">积分充值</h2>
|
||||
<p class="text-sm text-white/50 mt-2">累计充值 <strong class="text-emerald-300">¥{{ rechargeTotal }}</strong> · {{ payCfg.points_ratio }} 积分 / 元</p>
|
||||
|
||||
<div class="grid grid-cols-3 sm:grid-cols-5 gap-2 mt-5">
|
||||
<button v-for="a in AMOUNTS" :key="a" @click="picked = a" class="amt" :class="picked === a && 'amt-on'">{{ a }}元</button>
|
||||
<button @click="picked = 'custom'" class="amt" :class="picked === 'custom' && 'amt-on'">自定义</button>
|
||||
</div>
|
||||
<input v-if="picked === 'custom'" v-model="customAmount" type="number" min="1" step="1" placeholder="输入金额(元)"
|
||||
class="amt-input mt-3 w-full px-4 py-2.5 text-sm" />
|
||||
|
||||
<div class="flex gap-2 mt-4">
|
||||
<button v-for="m in payCfg.methods" :key="m" @click="payMethod = m" class="amt flex-1" :class="payMethod === m && 'amt-on'">{{ methodName(m) }}</button>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 flex items-center justify-between gap-3">
|
||||
<span class="text-sm text-white/60">到账 <strong class="text-violet-300 text-base tabular-nums">{{ pointsPreview }}</strong> 积分</span>
|
||||
<button @click="recharge" :disabled="recharging"
|
||||
class="rounded-xl bg-white text-black hover:bg-white/90 disabled:opacity-60 disabled:cursor-not-allowed px-6 py-2.5 text-sm font-semibold transition-colors inline-flex items-center gap-2">
|
||||
<span v-if="recharging" class="w-3.5 h-3.5 rounded-full border-2 border-black/30 border-t-black animate-spin"></span>
|
||||
{{ recharging ? '下单中…' : '立即充值' }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- CDK REDEEM — hidden when the admin turns the 兑换码 switch off -->
|
||||
<section v-if="site.cdkRedeemEnabled" class="relative card p-7 md:p-8 overflow-hidden">
|
||||
<div class="inline-grid w-10 h-10 rounded-xl bg-emerald-500/15 ring-1 ring-emerald-400/30 grid place-items-center text-emerald-300">
|
||||
@@ -398,4 +467,31 @@ function toast(m) {
|
||||
<style scoped>
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity 0.15s ease, transform 0.15s ease; }
|
||||
.fade-enter-from, .fade-leave-to { opacity: 0; transform: translateY(8px); }
|
||||
|
||||
/* Recharge amount / method buttons — theme-aware (clean in light AND dark).
|
||||
Selected uses the inverted solid-button color, not a harsh violet. */
|
||||
.amt {
|
||||
border-radius: 0.6rem;
|
||||
padding: 0.6rem 0;
|
||||
font-size: 0.875rem;
|
||||
text-align: center;
|
||||
color: var(--fg-2);
|
||||
background: var(--surface-2);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
transition: background 0.15s, color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.amt:hover { color: var(--fg); background: var(--hover); }
|
||||
.amt-on {
|
||||
background: var(--btn-solid-bg);
|
||||
color: var(--btn-solid-fg);
|
||||
box-shadow: none;
|
||||
}
|
||||
.amt-input {
|
||||
border-radius: 0.7rem;
|
||||
color: var(--fg);
|
||||
background: var(--surface-2);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
outline: none;
|
||||
}
|
||||
.amt-input:focus { box-shadow: inset 0 0 0 1px var(--fg-3); }
|
||||
</style>
|
||||
|
||||
@@ -209,7 +209,9 @@ const params = (e) => {
|
||||
<tbody>
|
||||
<tr v-for="e in displayed" :key="e.id" class="log-row">
|
||||
<td class="px-3 py-3 align-middle text-center">
|
||||
<button v-if="e.status === 'success' && e.file" @click="lightbox = e"
|
||||
<!-- API(v1) videos are no-store: file is an external provider URL
|
||||
(not a RustFS path), so it can't be previewed in-browser — show —. -->
|
||||
<button v-if="e.status === 'success' && e.file && !e.file.startsWith('http')" @click="lightbox = e"
|
||||
class="block w-11 h-11 mx-auto rounded-lg overflow-hidden ring-1 ring-slate-200 hover:ring-fuchsia-300 transition-all">
|
||||
<img v-if="e.kind !== 'video'" :src="generatedUrl(e.file)" loading="lazy" class="w-full h-full object-cover" />
|
||||
<video v-else :src="generatedUrl(e.file)" muted preload="metadata" class="w-full h-full object-cover" />
|
||||
|
||||
@@ -30,6 +30,7 @@ async function load() {
|
||||
offset: String((page.value - 1) * pageSize),
|
||||
status: 'success',
|
||||
has_file: '1',
|
||||
source: 'user', // 创作记录 = 画图台作品;排除 API(v1,无存储文件)+ 测试
|
||||
})
|
||||
if (kindFilter.value) qs.set('kind', kindFilter.value)
|
||||
const r = await api('/logs?' + qs.toString())
|
||||
@@ -160,8 +161,9 @@ onUnmounted(() => {
|
||||
class="absolute inset-0 w-full h-full object-cover"
|
||||
@mouseenter="$event.target.play && $event.target.play()"
|
||||
@mouseleave="$event.target.pause && $event.target.pause()" />
|
||||
<img v-else :src="generatedUrl(e.file)" loading="lazy"
|
||||
class="absolute inset-0 w-full h-full object-cover transition-transform duration-300 group-hover:scale-105" />
|
||||
<!-- background-image (not <img>) so Edge shows no 视觉搜索 overlay icon. -->
|
||||
<div v-else :style="{ backgroundImage: `url(${generatedUrl(e.file)})` }"
|
||||
class="absolute inset-0 w-full h-full bg-cover bg-center transition-transform duration-300 group-hover:scale-105"></div>
|
||||
<div class="absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-black/85 via-black/40 to-transparent pointer-events-none"></div>
|
||||
</template>
|
||||
<!-- pending / failed placeholders -->
|
||||
|
||||
@@ -272,6 +272,7 @@ async function quickCredits(u, delta) {
|
||||
<col class="w-20" /> <!-- role -->
|
||||
<col class="w-16" /> <!-- status switch -->
|
||||
<col class="w-24" /> <!-- credits -->
|
||||
<col class="w-24" /> <!-- recharge total -->
|
||||
<col class="w-20" /> <!-- generation count -->
|
||||
<col class="w-28" /> <!-- registered -->
|
||||
<col class="w-28" /> <!-- last login -->
|
||||
@@ -291,6 +292,7 @@ async function quickCredits(u, delta) {
|
||||
<th class="text-left px-3 py-3 font-medium">角色</th>
|
||||
<th class="text-left px-3 py-3 font-medium">状态</th>
|
||||
<th class="text-right px-3 py-3 font-medium">积分</th>
|
||||
<th class="text-right px-3 py-3 font-medium">累计充值</th>
|
||||
<th class="text-right px-3 py-3 font-medium">生图次数</th>
|
||||
<th class="text-left px-3 py-3 font-medium">注册时间</th>
|
||||
<th class="text-left px-3 py-3 font-medium">最近登录</th>
|
||||
@@ -340,6 +342,10 @@ async function quickCredits(u, delta) {
|
||||
<td class="px-3 py-3.5 align-middle text-right tabular-nums text-white/85 whitespace-nowrap">
|
||||
{{ points(u.credits).toLocaleString('en-US') }}
|
||||
</td>
|
||||
<td class="px-3 py-3.5 align-middle text-right tabular-nums whitespace-nowrap"
|
||||
:class="u.recharge_total > 0 ? 'text-emerald-300' : 'text-white/25'">
|
||||
¥{{ (u.recharge_total || 0).toLocaleString('en-US') }}
|
||||
</td>
|
||||
<td class="px-3 py-3.5 align-middle text-right tabular-nums whitespace-nowrap"
|
||||
:class="u.generation_count > 0 ? 'text-white/85' : 'text-white/25'">
|
||||
{{ (u.generation_count || 0).toLocaleString('en-US') }}
|
||||
|
||||
Reference in New Issue
Block a user