refactor: 重构项目结构,迁移后端至 mengyastore-backend-go,新增 Java 后端、前端功能更新及部署文档
This commit is contained in:
66
mengyastore-backend-go/internal/auth/sproutgate.go
Normal file
66
mengyastore-backend-go/internal/auth/sproutgate.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultAuthAPIURL = "https://auth.api.shumengya.top"
|
||||
|
||||
type SproutGateClient struct {
|
||||
apiURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type VerifyResult struct {
|
||||
Valid bool `json:"valid"`
|
||||
User *SproutGateUser `json:"user"`
|
||||
}
|
||||
|
||||
type SproutGateUser struct {
|
||||
Account string `json:"account"`
|
||||
Username string `json:"username"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Level int `json:"level"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func NewSproutGateClient(apiURL string) *SproutGateClient {
|
||||
if apiURL == "" {
|
||||
apiURL = defaultAuthAPIURL
|
||||
}
|
||||
return &SproutGateClient{
|
||||
apiURL: apiURL,
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
|
||||
body, _ := json.Marshal(map[string]string{"token": token})
|
||||
resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 验证请求失败: %v", err)
|
||||
return nil, fmt.Errorf("验证请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
rawBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 读取响应体失败: %v", err)
|
||||
return nil, fmt.Errorf("读取验证响应失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))
|
||||
|
||||
var result VerifyResult
|
||||
if err := json.Unmarshal(rawBody, &result); err != nil {
|
||||
log.Printf("[SproutGate] 解析响应失败: %v", err)
|
||||
return nil, fmt.Errorf("解析验证响应失败: %w", err)
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
45
mengyastore-backend-go/internal/config/config.go
Normal file
45
mengyastore-backend-go/internal/config/config.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AdminToken string `json:"adminToken"`
|
||||
AuthAPIURL string `json:"authApiUrl"`
|
||||
|
||||
// 数据库 DSN,为空时回退到测试数据库。
|
||||
// 格式:user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
|
||||
DatabaseDSN string `json:"databaseDsn"`
|
||||
}
|
||||
|
||||
// 各环境默认 DSN。
|
||||
const (
|
||||
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
)
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
var cfg Config
|
||||
data, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if jsonErr := json.Unmarshal(data, &cfg); jsonErr != nil {
|
||||
return nil, fmt.Errorf("解析配置文件 %s 失败: %w", path, jsonErr)
|
||||
}
|
||||
}
|
||||
// 文件不存在时使用默认值,环境变量在下方仍优先生效。
|
||||
|
||||
if cfg.AdminToken == "" {
|
||||
cfg.AdminToken = "changeme"
|
||||
}
|
||||
// DATABASE_DSN 环境变量优先于配置文件。
|
||||
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
|
||||
cfg.DatabaseDSN = dsn
|
||||
}
|
||||
if cfg.DatabaseDSN == "" {
|
||||
cfg.DatabaseDSN = TestDSN
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
45
mengyastore-backend-go/internal/database/db.go
Normal file
45
mengyastore-backend-go/internal/database/db.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Open 初始化 GORM 数据库连接并自动同步所有表结构。
|
||||
func Open(dsn string) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Warn),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDB.SetMaxIdleConns(5)
|
||||
sqlDB.SetMaxOpenConns(20)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
if err := autoMigrate(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Println("[DB] 数据库连接成功,表结构已同步")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func autoMigrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(
|
||||
&ProductRow{},
|
||||
&ProductCodeRow{},
|
||||
&OrderRow{},
|
||||
&SiteSettingRow{},
|
||||
&WishlistRow{},
|
||||
&ChatMessageRow{},
|
||||
)
|
||||
}
|
||||
121
mengyastore-backend-go/internal/database/models.go
Normal file
121
mengyastore-backend-go/internal/database/models.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StringSlice is a JSON-serialized string slice stored as a MySQL TEXT/JSON column.
|
||||
type StringSlice []string
|
||||
|
||||
func (s StringSlice) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return "[]", nil
|
||||
}
|
||||
b, err := json.Marshal(s)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func (s *StringSlice) Scan(src any) error {
|
||||
var raw []byte
|
||||
switch v := src.(type) {
|
||||
case string:
|
||||
raw = []byte(v)
|
||||
case []byte:
|
||||
raw = v
|
||||
default:
|
||||
return fmt.Errorf("StringSlice: unsupported type %T", src)
|
||||
}
|
||||
return json.Unmarshal(raw, s)
|
||||
}
|
||||
|
||||
// ─── Products ────────────────────────────────────────────────────────────────
|
||||
|
||||
// ProductRow is the GORM model for the `products` table.
|
||||
type ProductRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Price float64 `gorm:"not null;default:0"`
|
||||
DiscountPrice float64 `gorm:"default:0"`
|
||||
Tags StringSlice `gorm:"type:json"`
|
||||
CoverURL string `gorm:"size:500"`
|
||||
ScreenshotURLs StringSlice `gorm:"type:json"`
|
||||
VerificationURL string `gorm:"size:500;default:''"`
|
||||
Description string `gorm:"type:text"`
|
||||
Active bool `gorm:"default:true;index"`
|
||||
RequireLogin bool `gorm:"default:false"`
|
||||
MaxPerAccount int `gorm:"default:0"`
|
||||
TotalSold int `gorm:"default:0"`
|
||||
ViewCount int `gorm:"default:0"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
ShowNote bool `gorm:"default:false"`
|
||||
ShowContact bool `gorm:"default:false"`
|
||||
CreatedAt time.Time `gorm:"index"`
|
||||
}
|
||||
|
||||
func (ProductRow) TableName() string { return "products" }
|
||||
|
||||
// ProductCodeRow stores individual codes for a product (one row per code).
|
||||
type ProductCodeRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
Code string `gorm:"type:text;not null"`
|
||||
}
|
||||
|
||||
func (ProductCodeRow) TableName() string { return "product_codes" }
|
||||
|
||||
// ─── Orders ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type OrderRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
ProductName string `gorm:"size:255;not null"`
|
||||
UserAccount string `gorm:"size:255;index"`
|
||||
UserName string `gorm:"size:255"`
|
||||
Quantity int `gorm:"not null;default:1"`
|
||||
DeliveredCodes StringSlice `gorm:"type:json"`
|
||||
Status string `gorm:"size:20;not null;default:'pending';index"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
Note string `gorm:"type:text"`
|
||||
ContactPhone string `gorm:"size:50"`
|
||||
ContactEmail string `gorm:"size:255"`
|
||||
NotifyEmail string `gorm:"size:255"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (OrderRow) TableName() string { return "orders" }
|
||||
|
||||
// ─── Site settings ───────────────────────────────────────────────────────────
|
||||
|
||||
// SiteSettingRow stores arbitrary key-value pairs for site-wide settings.
|
||||
type SiteSettingRow struct {
|
||||
Key string `gorm:"primaryKey;size:64"`
|
||||
Value string `gorm:"type:text"`
|
||||
}
|
||||
|
||||
func (SiteSettingRow) TableName() string { return "site_settings" }
|
||||
|
||||
// ─── Wishlists ───────────────────────────────────────────────────────────────
|
||||
|
||||
type WishlistRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
AccountID string `gorm:"size:255;not null;index:idx_wishlist,unique"`
|
||||
ProductID string `gorm:"size:36;not null;index:idx_wishlist,unique"`
|
||||
}
|
||||
|
||||
func (WishlistRow) TableName() string { return "wishlists" }
|
||||
|
||||
// ─── Chat messages ───────────────────────────────────────────────────────────
|
||||
|
||||
type ChatMessageRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
AccountID string `gorm:"size:255;not null;index"`
|
||||
AccountName string `gorm:"size:255"`
|
||||
Content string `gorm:"type:text;not null"`
|
||||
SentAt time.Time `gorm:"not null"`
|
||||
FromAdmin bool `gorm:"default:false"`
|
||||
}
|
||||
|
||||
func (ChatMessageRow) TableName() string { return "chat_messages" }
|
||||
193
mengyastore-backend-go/internal/email/email.go
Normal file
193
mengyastore-backend-go/internal/email/email.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config 存储 SMTP 发件配置。
|
||||
type Config struct {
|
||||
SMTPHost string // 例:smtp.qq.com
|
||||
SMTPPort string // 例:465(SSL)或 587(STARTTLS)
|
||||
From string // 发件人邮箱地址
|
||||
Password string // SMTP 密码或授权码
|
||||
FromName string // 显示名称,例:"萌芽小店"
|
||||
}
|
||||
|
||||
// IsConfigured 判断配置是否充足,可以尝试发送邮件。
|
||||
func (c *Config) IsConfigured() bool {
|
||||
return c.From != "" && c.Password != "" && c.SMTPHost != ""
|
||||
}
|
||||
|
||||
// OrderNotifyData 包含发送订单通知邮件所需的数据。
|
||||
type OrderNotifyData struct {
|
||||
ToEmail string
|
||||
ToName string
|
||||
ProductName string
|
||||
OrderID string
|
||||
Quantity int
|
||||
Codes []string // 手动发货时为空
|
||||
IsManual bool
|
||||
}
|
||||
|
||||
// SendOrderNotify 发送订单发货通知邮件。
|
||||
// 若配置不完整或收件人为空,则静默跳过,返回 nil。
|
||||
func SendOrderNotify(cfg Config, data OrderNotifyData) error {
|
||||
if !cfg.IsConfigured() || data.ToEmail == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if cfg.SMTPPort == "" {
|
||||
cfg.SMTPPort = "465"
|
||||
}
|
||||
if cfg.SMTPHost == "" {
|
||||
cfg.SMTPHost = "smtp.qq.com"
|
||||
}
|
||||
fromName := cfg.FromName
|
||||
if fromName == "" {
|
||||
fromName = "萌芽小店"
|
||||
}
|
||||
|
||||
subject := "【萌芽小店】您的订单已发货"
|
||||
if data.IsManual {
|
||||
subject = "【萌芽小店】您的订单正在处理中"
|
||||
}
|
||||
|
||||
body := buildBody(data)
|
||||
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
|
||||
|
||||
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
|
||||
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
|
||||
|
||||
// QQ 邮箱使用 SSL(端口 465),需直接 TLS 拨号。
|
||||
if cfg.SMTPPort == "465" {
|
||||
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
|
||||
}
|
||||
return smtp.SendMail(addr, auth, cfg.From, []string{data.ToEmail}, []byte(msg))
|
||||
}
|
||||
|
||||
func buildBody(data OrderNotifyData) string {
|
||||
var sb strings.Builder
|
||||
now := time.Now().Format("2006 年 01 月 02 日 15:04:05")
|
||||
|
||||
recipient := data.ToName
|
||||
if recipient == "" {
|
||||
recipient = "用户"
|
||||
}
|
||||
|
||||
sb.WriteString("尊敬的 ")
|
||||
sb.WriteString(recipient)
|
||||
sb.WriteString(",\n\n")
|
||||
sb.WriteString(" 您好!感谢您在萌芽小店的支持与购买。\n\n")
|
||||
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 订单信息\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(fmt.Sprintf(" 商品名称:%s\n", data.ProductName))
|
||||
sb.WriteString(fmt.Sprintf(" 订单编号:%s\n", data.OrderID))
|
||||
sb.WriteString(fmt.Sprintf(" 购买数量:%d 件\n", data.Quantity))
|
||||
sb.WriteString(fmt.Sprintf(" 通知时间:%s\n", now))
|
||||
sb.WriteString("────────────────────────────────\n\n")
|
||||
|
||||
if data.IsManual {
|
||||
sb.WriteString(" 您的订单已成功提交,目前正在等待人工审核与处理。\n")
|
||||
sb.WriteString(" 工作人员将尽快为您安排发货,请耐心等候。\n")
|
||||
sb.WriteString(" 发货完成后,我们将另行发送邮件通知。\n\n")
|
||||
} else {
|
||||
sb.WriteString(" 您的订单已完成自动发货,发货内容如下:\n\n")
|
||||
if len(data.Codes) > 0 {
|
||||
for i, code := range data.Codes {
|
||||
sb.WriteString(fmt.Sprintf(" [%d] %s\n", i+1, code))
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
sb.WriteString(" 请妥善保管以上发货内容,切勿泄露给他人。\n\n")
|
||||
}
|
||||
|
||||
sb.WriteString(" 如有任何疑问,请联系在线客服,我们将竭诚为您服务。\n\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 此邮件由系统自动发送,请勿直接回复。\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMIMEMessage 构建符合 MIME 规范的邮件报文,支持 UTF-8 中文。
|
||||
func buildMIMEMessage(from, fromName, to, subject, body string) string {
|
||||
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
|
||||
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
|
||||
return fmt.Sprintf(
|
||||
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s",
|
||||
encodedFromName, from, to, encodedSubject, encodeBase64(body),
|
||||
)
|
||||
}
|
||||
|
||||
func encodeBase64(s string) string {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
b := []byte(s)
|
||||
var buf strings.Builder
|
||||
for i := 0; i < len(b); i += 3 {
|
||||
remaining := len(b) - i
|
||||
b0 := b[i]
|
||||
b1 := byte(0)
|
||||
b2 := byte(0)
|
||||
if remaining > 1 {
|
||||
b1 = b[i+1]
|
||||
}
|
||||
if remaining > 2 {
|
||||
b2 = b[i+2]
|
||||
}
|
||||
buf.WriteByte(chars[b0>>2])
|
||||
buf.WriteByte(chars[((b0&0x03)<<4)|(b1>>4)])
|
||||
if remaining > 1 {
|
||||
buf.WriteByte(chars[((b1&0x0f)<<2)|(b2>>6)])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
if remaining > 2 {
|
||||
buf.WriteByte(chars[b2&0x3f])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// sendSSL 通过 TLS 直接拨号发送邮件(适用于 465 端口 SSL 连接,如 QQ 邮箱)。
|
||||
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: host,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tls 拨号失败: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 SMTP 客户端失败: %w", err)
|
||||
}
|
||||
defer client.Quit() //nolint:errcheck
|
||||
|
||||
if err = client.Auth(auth); err != nil {
|
||||
return fmt.Errorf("SMTP 认证失败: %w", err)
|
||||
}
|
||||
if err = client.Mail(from); err != nil {
|
||||
return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
|
||||
}
|
||||
if err = client.Rcpt(to); err != nil {
|
||||
return fmt.Errorf("SMTP RCPT TO 失败: %w", err)
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP DATA 失败: %w", err)
|
||||
}
|
||||
if _, err = fmt.Fprint(w, msg); err != nil {
|
||||
return fmt.Errorf("写入邮件内容失败: %w", err)
|
||||
}
|
||||
return w.Close()
|
||||
}
|
||||
41
mengyastore-backend-go/internal/handlers/admin.go
Normal file
41
mengyastore-backend-go/internal/handlers/admin.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
// AdminHandler 持有所有管理员路由所需的依赖。
|
||||
type AdminHandler struct {
|
||||
store *storage.ProductStore
|
||||
cfg *config.Config
|
||||
siteStore *storage.SiteStore
|
||||
orderStore *storage.OrderStore
|
||||
chatStore *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewAdminHandler(store *storage.ProductStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler {
|
||||
return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore}
|
||||
}
|
||||
|
||||
// requireAdmin 校验管理员令牌。
|
||||
// 优先级:X-Admin-Token 请求头 > Authorization 请求头 > ?token 查询参数(旧版兼容)。
|
||||
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
|
||||
token := c.GetHeader("X-Admin-Token")
|
||||
if token == "" {
|
||||
token = c.GetHeader("Authorization")
|
||||
}
|
||||
if token == "" {
|
||||
// 兼容旧版客户端的 URL 查询参数回退
|
||||
token = c.Query("token")
|
||||
}
|
||||
if token != "" && token == h.cfg.AdminToken {
|
||||
return true
|
||||
}
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
88
mengyastore-backend-go/internal/handlers/admin_chat.go
Normal file
88
mengyastore-backend-go/internal/handlers/admin_chat.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetAllConversations 返回所有用户会话列表。
|
||||
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
convs, err := h.chatStore.ListConversations()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
|
||||
}
|
||||
|
||||
// GetConversation 返回指定账号的全部消息记录。
|
||||
func (h *AdminHandler) GetConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(accountID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type adminChatPayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// AdminReply 向指定用户发送管理员回复。
|
||||
func (h *AdminHandler) AdminReply(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
var payload adminChatPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
msg, err := h.chatStore.SendAdminMessage(accountID, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
|
||||
// ClearConversation 清除与指定用户的全部消息记录。
|
||||
func (h *AdminHandler) ClearConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
if err := h.chatStore.ClearConversation(accountID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
35
mengyastore-backend-go/internal/handlers/admin_orders.go
Normal file
35
mengyastore-backend-go/internal/handlers/admin_orders.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (h *AdminHandler) ListAllOrders(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orders, err := h.orderStore.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteOrder(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orderID := c.Param("id")
|
||||
if orderID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少订单 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.orderStore.Delete(orderID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
210
mengyastore-backend-go/internal/handlers/admin_product.go
Normal file
210
mengyastore-backend-go/internal/handlers/admin_product.go
Normal file
@@ -0,0 +1,210 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type productPayload struct {
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags string `json:"tags"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
Description string `json:"description"`
|
||||
Active *bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
}
|
||||
|
||||
type togglePayload struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// VerifyAdminToken 验证管理员令牌是否正确,返回 {"valid": true/false},不暴露实际令牌值。
|
||||
func (h *AdminHandler) VerifyAdminToken(c *gin.Context) {
|
||||
var payload struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.Token == "" {
|
||||
c.JSON(http.StatusOK, gin.H{"valid": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"valid": payload.Token == h.cfg.AdminToken})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
items, err := h.store.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := true
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
product := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
created, err := h.store.Create(product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": created})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := false
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
patch := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
updated, err := h.store.Update(id, patch)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ToggleProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload togglePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
updated, err := h.store.Toggle(id, payload.Active)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
if err := h.store.Delete(id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
|
||||
func normalizeScreenshotURLs(urls []string) ([]string, bool) {
|
||||
cleaned := make([]string, 0, len(urls))
|
||||
for _, url := range urls {
|
||||
trimmed := strings.TrimSpace(url)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, trimmed)
|
||||
if len(cleaned) > 5 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return cleaned, true
|
||||
}
|
||||
|
||||
func normalizeTags(tagsCSV string) []string {
|
||||
if tagsCSV == "" {
|
||||
return []string{}
|
||||
}
|
||||
parts := strings.Split(tagsCSV, ",")
|
||||
clean := make([]string, 0, len(parts))
|
||||
seen := map[string]bool{}
|
||||
for _, p := range parts {
|
||||
t := strings.TrimSpace(p)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
73
mengyastore-backend-go/internal/handlers/admin_site.go
Normal file
73
mengyastore-backend-go/internal/handlers/admin_site.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type maintenancePayload struct {
|
||||
Maintenance bool `json:"maintenance"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetMaintenance(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload maintenancePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": payload.Maintenance,
|
||||
"reason": payload.Reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 响应中对密码脱敏处理
|
||||
masked := cfg
|
||||
if masked.Password != "" {
|
||||
masked.Password = "••••••••"
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": masked})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload storage.SMTPConfig
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
// 若密码为脱敏占位符,则保留数据库中原有的密码
|
||||
if payload.Password == "••••••••" {
|
||||
existing, _ := h.siteStore.GetSMTPConfig()
|
||||
payload.Password = existing.Password
|
||||
}
|
||||
if err := h.siteStore.SetSMTPConfig(payload); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": "ok"})
|
||||
}
|
||||
82
mengyastore-backend-go/internal/handlers/chat.go
Normal file
82
mengyastore-backend-go/internal/handlers/chat.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatStore *storage.ChatStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewChatHandler(chatStore *storage.ChatStore, authClient *auth.SproutGateClient) *ChatHandler {
|
||||
return &ChatHandler{chatStore: chatStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", "", false
|
||||
}
|
||||
return result.User.Account, result.User.Username, true
|
||||
}
|
||||
|
||||
// GetMyMessages 返回当前登录用户的全部聊天消息。
|
||||
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
|
||||
account, _, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type chatMessagePayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// SendMyMessage 向管理员发送一条用户消息。
|
||||
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
|
||||
account, name, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload chatMessagePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
msg, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if rateLimited {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁,请稍候"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
295
mengyastore-backend-go/internal/handlers/order.go
Normal file
295
mengyastore-backend-go/internal/handlers/order.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/email"
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
const qrSize = "320x320"
|
||||
|
||||
type OrderHandler struct {
|
||||
productStore *storage.ProductStore
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
type checkoutPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
Quantity int `json:"quantity"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
}
|
||||
|
||||
func NewOrderHandler(productStore *storage.ProductStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
|
||||
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *OrderHandler) sendOrderNotify(toEmail, toName, productName, orderID string, qty int, codes []string, isManual bool) {
|
||||
if toEmail == "" {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil || !cfg.IsConfiguredEmail() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
emailCfg := email.Config{
|
||||
SMTPHost: cfg.Host,
|
||||
SMTPPort: cfg.Port,
|
||||
From: cfg.Email,
|
||||
Password: cfg.Password,
|
||||
FromName: cfg.FromName,
|
||||
}
|
||||
if err := email.SendOrderNotify(emailCfg, email.OrderNotifyData{
|
||||
ToEmail: toEmail,
|
||||
ToName: toName,
|
||||
ProductName: productName,
|
||||
OrderID: orderID,
|
||||
Quantity: qty,
|
||||
Codes: codes,
|
||||
IsManual: isManual,
|
||||
}); err != nil {
|
||||
log.Printf("[Email] 发送通知失败 order=%s to=%s: %v", orderID, toEmail, err)
|
||||
} else {
|
||||
log.Printf("[Email] 发送通知成功 order=%s to=%s", orderID, toEmail)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (h *OrderHandler) tryExtractUserWithEmail(c *gin.Context) (account, username, userEmail string) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
return "", "", ""
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
return "", "", ""
|
||||
}
|
||||
return result.User.Account, result.User.Username, result.User.Email
|
||||
}
|
||||
|
||||
func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
|
||||
|
||||
var payload checkoutPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
|
||||
payload.ProductID = strings.TrimSpace(payload.ProductID)
|
||||
if payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必填字段"})
|
||||
return
|
||||
}
|
||||
if payload.Quantity <= 0 {
|
||||
payload.Quantity = 1
|
||||
}
|
||||
|
||||
product, err := h.productStore.GetByID(payload.ProductID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !product.Active {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "商品暂时无法购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.RequireLogin && userAccount == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "该商品需要登录后才能购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.MaxPerAccount > 0 && userAccount != "" {
|
||||
purchased, err := h.orderStore.CountPurchasedByAccount(userAccount, product.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if purchased+payload.Quantity > product.MaxPerAccount {
|
||||
remain := product.MaxPerAccount - purchased
|
||||
if remain <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您已达上限", product.MaxPerAccount)})
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您还可购买 %d 个", product.MaxPerAccount, remain)})
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if product.Quantity < payload.Quantity {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := product.DeliveryMode == "manual"
|
||||
|
||||
var deliveredCodes []string
|
||||
var updatedProduct models.Product
|
||||
|
||||
if isManual {
|
||||
updatedProduct = product
|
||||
} else {
|
||||
var ok bool
|
||||
deliveredCodes, ok = extractCodes(&product, payload.Quantity)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
|
||||
return
|
||||
}
|
||||
product.Quantity = len(product.Codes)
|
||||
updatedProduct, err = h.productStore.Update(product.ID, product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
deliveryMode := product.DeliveryMode
|
||||
if deliveryMode == "" {
|
||||
deliveryMode = "auto"
|
||||
}
|
||||
|
||||
// 通知邮箱优先级:
|
||||
// 1. SproutGate 账号邮箱(已登录用户,最可靠)
|
||||
// 2. 前端传入的 notifyEmail(来自 authState.email)
|
||||
// 3. 用户在结账表单填写的联系邮箱
|
||||
// 4. 均为空则不发送
|
||||
notifyEmail := strings.TrimSpace(userEmail)
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
|
||||
}
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.ContactEmail)
|
||||
}
|
||||
|
||||
// 自动发货订单立即设为已完成(卡密已提取);手动发货订单初始状态为待处理,由管理员确认。
|
||||
orderStatus := "pending"
|
||||
if !isManual {
|
||||
orderStatus = "completed"
|
||||
}
|
||||
|
||||
order := models.Order{
|
||||
ProductID: updatedProduct.ID,
|
||||
ProductName: updatedProduct.Name,
|
||||
UserAccount: userAccount,
|
||||
UserName: userName,
|
||||
Quantity: payload.Quantity,
|
||||
DeliveredCodes: deliveredCodes,
|
||||
Status: orderStatus,
|
||||
DeliveryMode: deliveryMode,
|
||||
Note: strings.TrimSpace(payload.Note),
|
||||
ContactPhone: strings.TrimSpace(payload.ContactPhone),
|
||||
ContactEmail: strings.TrimSpace(payload.ContactEmail),
|
||||
NotifyEmail: notifyEmail,
|
||||
}
|
||||
created, err := h.orderStore.Create(order)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if !isManual {
|
||||
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
|
||||
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
|
||||
}
|
||||
// 自动发货:立即发送卡密通知邮件
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
|
||||
} else {
|
||||
// 手动发货:告知用户订单已收到,等待发货
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
|
||||
}
|
||||
|
||||
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID)
|
||||
qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": created.ID,
|
||||
"qrCodeUrl": qrURL,
|
||||
"productId": created.ProductID,
|
||||
"productQty": created.Quantity,
|
||||
"viewCount": updatedProduct.ViewCount,
|
||||
"status": created.Status,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
|
||||
orderID := c.Param("id")
|
||||
order, err := h.orderStore.Confirm(orderID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := order.DeliveryMode == "manual"
|
||||
|
||||
// 手动发货确认后,发送"已发货"通知邮件
|
||||
if isManual {
|
||||
confirmNotifyEmail := order.NotifyEmail
|
||||
if confirmNotifyEmail == "" {
|
||||
confirmNotifyEmail = order.ContactEmail
|
||||
}
|
||||
h.sendOrderNotify(confirmNotifyEmail, order.UserName, order.ProductName, order.ID, order.Quantity, order.DeliveredCodes, false)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": order.ID,
|
||||
"status": order.Status,
|
||||
"deliveryMode": order.DeliveryMode,
|
||||
"deliveredCodes": order.DeliveredCodes,
|
||||
"isManual": isManual,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ListMyOrders(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return
|
||||
}
|
||||
|
||||
orders, err := h.orderStore.ListByAccount(result.User.Account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func extractCodes(product *models.Product, count int) ([]string, bool) {
|
||||
if count <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
if len(product.Codes) < count {
|
||||
return nil, false
|
||||
}
|
||||
delivered := make([]string, count)
|
||||
copy(delivered, product.Codes[:count])
|
||||
product.Codes = product.Codes[count:]
|
||||
return delivered, true
|
||||
}
|
||||
|
||||
62
mengyastore-backend-go/internal/handlers/public.go
Normal file
62
mengyastore-backend-go/internal/handlers/public.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type PublicHandler struct {
|
||||
store *storage.ProductStore
|
||||
}
|
||||
|
||||
func NewPublicHandler(store *storage.ProductStore) *PublicHandler {
|
||||
return &PublicHandler{store: store}
|
||||
}
|
||||
|
||||
func (h *PublicHandler) ListProducts(c *gin.Context) {
|
||||
items, err := h.store.ListActive()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": sanitizeForPublic(items)})
|
||||
}
|
||||
|
||||
func (h *PublicHandler) RecordProductView(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
fingerprint := buildViewerFingerprint(c)
|
||||
product, counted, err := h.store.IncrementView(id, fingerprint)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"id": product.ID,
|
||||
"viewCount": product.ViewCount,
|
||||
"counted": counted,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func buildViewerFingerprint(c *gin.Context) string {
|
||||
clientIP := strings.TrimSpace(c.ClientIP())
|
||||
userAgent := strings.TrimSpace(c.GetHeader("User-Agent"))
|
||||
language := strings.TrimSpace(c.GetHeader("Accept-Language"))
|
||||
return clientIP + "|" + userAgent + "|" + language
|
||||
}
|
||||
|
||||
func sanitizeForPublic(items []models.Product) []models.Product {
|
||||
out := make([]models.Product, len(items))
|
||||
for i, item := range items {
|
||||
item.Codes = nil
|
||||
out[i] = item
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
66
mengyastore-backend-go/internal/handlers/stats.go
Normal file
66
mengyastore-backend-go/internal/handlers/stats.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type StatsHandler struct {
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
}
|
||||
|
||||
func NewStatsHandler(orderStore *storage.OrderStore, siteStore *storage.SiteStore) *StatsHandler {
|
||||
return &StatsHandler{orderStore: orderStore, siteStore: siteStore}
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetStats(c *gin.Context) {
|
||||
totalOrders, err := h.orderStore.Count()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
totalVisits, err := h.siteStore.GetTotalVisits()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalOrders": totalOrders,
|
||||
"totalVisits": totalVisits,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) RecordVisit(c *gin.Context) {
|
||||
fingerprint := buildViewerFingerprint(c)
|
||||
totalVisits, counted, err := h.siteStore.RecordVisit(fingerprint)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalVisits": totalVisits,
|
||||
"counted": counted,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetMaintenance(c *gin.Context) {
|
||||
enabled, reason, err := h.siteStore.GetMaintenance()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": enabled,
|
||||
"reason": reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
88
mengyastore-backend-go/internal/handlers/wishlist.go
Normal file
88
mengyastore-backend-go/internal/handlers/wishlist.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type WishlistHandler struct {
|
||||
wishlistStore *storage.WishlistStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewWishlistHandler(wishlistStore *storage.WishlistStore, authClient *auth.SproutGateClient) *WishlistHandler {
|
||||
return &WishlistHandler{wishlistStore: wishlistStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) requireUser(c *gin.Context) (string, bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", false
|
||||
}
|
||||
return result.User.Account, true
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) GetWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ids, err := h.wishlistStore.Get(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
type wishlistItemPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload wishlistItemPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
productID := c.Param("id")
|
||||
if productID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Remove(account, productID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
12
mengyastore-backend-go/internal/models/chat.go
Normal file
12
mengyastore-backend-go/internal/models/chat.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type ChatMessage struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountId"`
|
||||
AccountName string `json:"accountName"`
|
||||
Content string `json:"content"`
|
||||
SentAt time.Time `json:"sentAt"`
|
||||
FromAdmin bool `json:"fromAdmin"`
|
||||
}
|
||||
20
mengyastore-backend-go/internal/models/order.go
Normal file
20
mengyastore-backend-go/internal/models/order.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Order struct {
|
||||
ID string `json:"id"`
|
||||
ProductID string `json:"productId"`
|
||||
ProductName string `json:"productName"`
|
||||
UserAccount string `json:"userAccount"`
|
||||
UserName string `json:"userName"`
|
||||
Quantity int `json:"quantity"`
|
||||
DeliveredCodes []string `json:"deliveredCodes"`
|
||||
Status string `json:"status"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
27
mengyastore-backend-go/internal/models/product.go
Normal file
27
mengyastore-backend-go/internal/models/product.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Product struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags []string `json:"tags"`
|
||||
Quantity int `json:"quantity"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
VerificationURL string `json:"verificationUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ViewCount int `json:"viewCount"`
|
||||
Description string `json:"description"`
|
||||
Active bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
TotalSold int `json:"totalSold"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
99
mengyastore-backend-go/internal/storage/chatstore.go
Normal file
99
mengyastore-backend-go/internal/storage/chatstore.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
lastSent map[string]time.Time
|
||||
}
|
||||
|
||||
func NewChatStore(db *gorm.DB) (*ChatStore, error) {
|
||||
return &ChatStore{db: db, lastSent: make(map[string]time.Time)}, nil
|
||||
}
|
||||
|
||||
func chatRowToModel(row database.ChatMessageRow) models.ChatMessage {
|
||||
return models.ChatMessage{
|
||||
ID: row.ID,
|
||||
AccountID: row.AccountID,
|
||||
AccountName: row.AccountName,
|
||||
Content: row.Content,
|
||||
SentAt: row.SentAt,
|
||||
FromAdmin: row.FromAdmin,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetMessages(accountID string) ([]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Order("sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs := make([]models.ChatMessage, len(rows))
|
||||
for i, r := range rows {
|
||||
msgs[i] = chatRowToModel(r)
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListConversations() (map[string][]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Order("account_id, sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[string][]models.ChatMessage)
|
||||
for _, r := range rows {
|
||||
result[r.AccountID] = append(result[r.AccountID], chatRowToModel(r))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendUserMessage(accountID, accountName, content string) (models.ChatMessage, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if last, ok := s.lastSent[accountID]; ok && time.Since(last) < time.Second {
|
||||
return models.ChatMessage{}, true, nil
|
||||
}
|
||||
s.lastSent[accountID] = time.Now()
|
||||
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: accountName,
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: false,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, false, err
|
||||
}
|
||||
return chatRowToModel(row), false, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendAdminMessage(accountID, content string) (models.ChatMessage, error) {
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: "管理员",
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: true,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, err
|
||||
}
|
||||
return chatRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ClearConversation(accountID string) error {
|
||||
return s.db.Where("account_id = ?", accountID).Delete(&database.ChatMessageRow{}).Error
|
||||
}
|
||||
140
mengyastore-backend-go/internal/storage/orderstore.go
Normal file
140
mengyastore-backend-go/internal/storage/orderstore.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type OrderStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
|
||||
return &OrderStore{db: db}, nil
|
||||
}
|
||||
|
||||
func orderRowToModel(row database.OrderRow) models.Order {
|
||||
return models.Order{
|
||||
ID: row.ID,
|
||||
ProductID: row.ProductID,
|
||||
ProductName: row.ProductName,
|
||||
UserAccount: row.UserAccount,
|
||||
UserName: row.UserName,
|
||||
Quantity: row.Quantity,
|
||||
DeliveredCodes: row.DeliveredCodes,
|
||||
Status: row.Status,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
Note: row.Note,
|
||||
ContactPhone: row.ContactPhone,
|
||||
ContactEmail: row.ContactEmail,
|
||||
NotifyEmail: row.NotifyEmail,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
|
||||
if order.ID == "" {
|
||||
order.ID = uuid.NewString()
|
||||
}
|
||||
if len(order.DeliveredCodes) == 0 {
|
||||
order.DeliveredCodes = []string{}
|
||||
}
|
||||
row := database.OrderRow{
|
||||
ID: order.ID,
|
||||
ProductID: order.ProductID,
|
||||
ProductName: order.ProductName,
|
||||
UserAccount: order.UserAccount,
|
||||
UserName: order.UserName,
|
||||
Quantity: order.Quantity,
|
||||
DeliveredCodes: database.StringSlice(order.DeliveredCodes),
|
||||
Status: order.Status,
|
||||
DeliveryMode: order.DeliveryMode,
|
||||
Note: order.Note,
|
||||
ContactPhone: order.ContactPhone,
|
||||
ContactEmail: order.ContactEmail,
|
||||
NotifyEmail: order.NotifyEmail,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
order.CreatedAt = row.CreatedAt
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) GetByID(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) Confirm(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
row.Status = "completed"
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Where("user_account = ?", account).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListAll() ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
|
||||
var total int64
|
||||
// 统计 pending(手动待发货)和 completed 两种状态,防止用户快速下单绕过购买数量限制。
|
||||
err := s.db.Model(&database.OrderRow{}).
|
||||
Where("user_account = ? AND product_id = ? AND status IN ?", account, productID, []string{"pending", "completed"}).
|
||||
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
|
||||
return int(total), err
|
||||
}
|
||||
|
||||
// Count 返回所有订单的总数量。
|
||||
func (s *OrderStore) Count() (int, error) {
|
||||
var count int64
|
||||
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
// Delete 根据 ID 删除单条订单。
|
||||
func (s *OrderStore) Delete(id string) error {
|
||||
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// UpdateCodes 更新订单的已发货卡密列表。
|
||||
func (s *OrderStore) UpdateCodes(id string, codes []string) error {
|
||||
return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
|
||||
Update("delivered_codes", database.StringSlice(codes)).Error
|
||||
}
|
||||
328
mengyastore-backend-go/internal/storage/productstore.go
Normal file
328
mengyastore-backend-go/internal/storage/productstore.go
Normal file
@@ -0,0 +1,328 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png"
|
||||
const viewCooldown = 6 * time.Hour
|
||||
const maxScreenshotURLs = 5
|
||||
|
||||
type ProductStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
recentViews map[string]time.Time
|
||||
}
|
||||
|
||||
func NewProductStore(db *gorm.DB) (*ProductStore, error) {
|
||||
return &ProductStore{
|
||||
db: db,
|
||||
recentViews: make(map[string]time.Time),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// rowToModel 将数据库行(含卡密)转换为业务模型。
|
||||
func rowToModel(row database.ProductRow, codes []string) models.Product {
|
||||
return models.Product{
|
||||
ID: row.ID,
|
||||
Name: row.Name,
|
||||
Price: row.Price,
|
||||
DiscountPrice: row.DiscountPrice,
|
||||
Tags: row.Tags,
|
||||
CoverURL: row.CoverURL,
|
||||
ScreenshotURLs: row.ScreenshotURLs,
|
||||
VerificationURL: row.VerificationURL,
|
||||
Description: row.Description,
|
||||
Active: row.Active,
|
||||
RequireLogin: row.RequireLogin,
|
||||
MaxPerAccount: row.MaxPerAccount,
|
||||
TotalSold: row.TotalSold,
|
||||
ViewCount: row.ViewCount,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
ShowNote: row.ShowNote,
|
||||
ShowContact: row.ShowContact,
|
||||
Codes: codes,
|
||||
Quantity: len(codes),
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProductStore) loadCodes(productID string) ([]string, error) {
|
||||
var rows []database.ProductCodeRow
|
||||
if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codes := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
codes[i] = r.Code
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) replaceCodes(productID string, codes []string) error {
|
||||
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows := make([]database.ProductCodeRow, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
rows = append(rows, database.ProductCodeRow{ProductID: productID, Code: code})
|
||||
}
|
||||
return s.db.CreateInBatches(rows, 100).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListAll() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
codes, _ := s.loadCodes(row.ID)
|
||||
products = append(products, rowToModel(row, codes))
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListActive() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
// 公开接口不暴露卡密,但需要统计剩余库存数量
|
||||
var count int64
|
||||
s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count)
|
||||
row.Active = true
|
||||
p := rowToModel(row, nil)
|
||||
p.Quantity = int(count)
|
||||
p.Codes = nil
|
||||
products = append(products, p)
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) GetByID(id string) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Create(p models.Product) (models.Product, error) {
|
||||
p = normalizeProduct(p)
|
||||
p.ID = uuid.NewString()
|
||||
now := time.Now()
|
||||
p.CreatedAt = now
|
||||
|
||||
row := database.ProductRow{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Price: p.Price,
|
||||
DiscountPrice: p.DiscountPrice,
|
||||
Tags: database.StringSlice(p.Tags),
|
||||
CoverURL: p.CoverURL,
|
||||
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
|
||||
VerificationURL: p.VerificationURL,
|
||||
Description: p.Description,
|
||||
Active: p.Active,
|
||||
RequireLogin: p.RequireLogin,
|
||||
MaxPerAccount: p.MaxPerAccount,
|
||||
TotalSold: p.TotalSold,
|
||||
ViewCount: p.ViewCount,
|
||||
DeliveryMode: p.DeliveryMode,
|
||||
ShowNote: p.ShowNote,
|
||||
ShowContact: p.ShowContact,
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(p.ID, p.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
p.Quantity = len(p.Codes)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Update(id string, patch models.Product) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
normalized := normalizeProduct(patch)
|
||||
|
||||
if err := s.db.Model(&row).Updates(map[string]interface{}{
|
||||
"name": normalized.Name,
|
||||
"price": normalized.Price,
|
||||
"discount_price": normalized.DiscountPrice,
|
||||
"tags": database.StringSlice(normalized.Tags),
|
||||
"cover_url": normalized.CoverURL,
|
||||
"screenshot_urls": database.StringSlice(normalized.ScreenshotURLs),
|
||||
"verification_url": normalized.VerificationURL,
|
||||
"description": normalized.Description,
|
||||
"active": normalized.Active,
|
||||
"require_login": normalized.RequireLogin,
|
||||
"max_per_account": normalized.MaxPerAccount,
|
||||
"delivery_mode": normalized.DeliveryMode,
|
||||
"show_note": normalized.ShowNote,
|
||||
"show_contact": normalized.ShowContact,
|
||||
}).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(id, normalized.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
|
||||
var updated database.ProductRow
|
||||
s.db.First(&updated, "id = ?", id)
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(updated, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Toggle(id string, active bool) (models.Product, error) {
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementSold(id string, count int) error {
|
||||
return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
s.cleanupRecentViews(now)
|
||||
key := buildViewKey(id, fingerprint)
|
||||
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), false, nil
|
||||
}
|
||||
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("view_count", gorm.Expr("view_count + 1")).Error; err != nil {
|
||||
return models.Product{}, false, err
|
||||
}
|
||||
s.recentViews[key] = now
|
||||
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), true, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Delete(id string) error {
|
||||
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// normalizeProduct 对商品字段进行规范化处理(清理空白、设默认值等)。
|
||||
func normalizeProduct(item models.Product) models.Product {
|
||||
item.CoverURL = strings.TrimSpace(item.CoverURL)
|
||||
if item.CoverURL == "" {
|
||||
item.CoverURL = defaultCoverURL
|
||||
}
|
||||
if item.Tags == nil {
|
||||
item.Tags = []string{}
|
||||
}
|
||||
item.Tags = sanitizeTags(item.Tags)
|
||||
if item.ScreenshotURLs == nil {
|
||||
item.ScreenshotURLs = []string{}
|
||||
}
|
||||
if len(item.ScreenshotURLs) > maxScreenshotURLs {
|
||||
item.ScreenshotURLs = item.ScreenshotURLs[:maxScreenshotURLs]
|
||||
}
|
||||
if item.Codes == nil {
|
||||
item.Codes = []string{}
|
||||
}
|
||||
if item.DiscountPrice <= 0 || item.DiscountPrice >= item.Price {
|
||||
item.DiscountPrice = 0
|
||||
}
|
||||
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
|
||||
item.Codes = sanitizeCodes(item.Codes)
|
||||
item.Quantity = len(item.Codes)
|
||||
if item.DeliveryMode == "" {
|
||||
item.DeliveryMode = "auto"
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func sanitizeCodes(codes []string) []string {
|
||||
clean := make([]string, 0, len(codes))
|
||||
seen := map[string]bool{}
|
||||
for _, code := range codes {
|
||||
trimmed := strings.TrimSpace(code)
|
||||
if trimmed == "" || seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
clean = append(clean, trimmed)
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func sanitizeTags(tags []string) []string {
|
||||
clean := make([]string, 0, len(tags))
|
||||
seen := map[string]bool{}
|
||||
for _, tag := range tags {
|
||||
t := strings.TrimSpace(tag)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func buildViewKey(id, fingerprint string) string {
|
||||
sum := sha256.Sum256([]byte(id + "|" + fingerprint))
|
||||
return fmt.Sprintf("%x", sum)
|
||||
}
|
||||
|
||||
func (s *ProductStore) cleanupRecentViews(now time.Time) {
|
||||
for key, lastViewedAt := range s.recentViews {
|
||||
if now.Sub(lastViewedAt) >= viewCooldown {
|
||||
delete(s.recentViews, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
146
mengyastore-backend-go/internal/storage/sitestore.go
Normal file
146
mengyastore-backend-go/internal/storage/sitestore.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type SiteStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
|
||||
return &SiteStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) get(key string) (string, error) {
|
||||
var row database.SiteSettingRow
|
||||
// `key` 是 MySQL 保留字,需用反引号转义以避免 SQL 语法错误。
|
||||
if err := s.db.Where("`key` = ?", key).First(&row).Error; err != nil {
|
||||
return "", nil // 键不存在时返回零值
|
||||
}
|
||||
return row.Value, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) set(key, value string) error {
|
||||
return s.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
||||
}).Create(&database.SiteSettingRow{Key: key, Value: value}).Error
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetTotalVisits() (int, error) {
|
||||
v, err := s.get("totalVisits")
|
||||
if err != nil || v == "" {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := strconv.Atoi(v)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) IncrementVisits() (int, error) {
|
||||
current, err := s.GetTotalVisits()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
current++
|
||||
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
|
||||
v, err := s.get("maintenance")
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
enabled = v == "true"
|
||||
reason, err = s.get("maintenanceReason")
|
||||
return enabled, reason, err
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
|
||||
v := "false"
|
||||
if enabled {
|
||||
v = "true"
|
||||
}
|
||||
if err := s.set("maintenance", v); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.set("maintenanceReason", reason)
|
||||
}
|
||||
|
||||
// RecordVisit 递增访问计数,返回 (总访问量, 是否计入, 错误)。
|
||||
// 去重逻辑由上层 handler 的内存指纹完成,此处无条件累加。
|
||||
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
|
||||
total, err := s.IncrementVisits()
|
||||
return total, true, err
|
||||
}
|
||||
|
||||
// SMTPConfig 存储数据库中的发件 SMTP 配置。
|
||||
type SMTPConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
FromName string `json:"fromName"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
}
|
||||
|
||||
// IsConfiguredEmail 判断邮件通知是否已启用且 SMTP 配置完整。
|
||||
func (c SMTPConfig) IsConfiguredEmail() bool {
|
||||
return c.Enabled && c.Email != "" && c.Password != "" && c.Host != ""
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
|
||||
cfg := SMTPConfig{
|
||||
Enabled: true, // 默认启用
|
||||
Host: "smtp.qq.com",
|
||||
Port: "465",
|
||||
}
|
||||
if v, _ := s.get("smtpEnabled"); v == "false" {
|
||||
cfg.Enabled = false
|
||||
}
|
||||
if v, _ := s.get("smtpEmail"); v != "" {
|
||||
cfg.Email = v
|
||||
}
|
||||
if v, _ := s.get("smtpPassword"); v != "" {
|
||||
cfg.Password = v
|
||||
}
|
||||
if v, _ := s.get("smtpFromName"); v != "" {
|
||||
cfg.FromName = v
|
||||
}
|
||||
if v, _ := s.get("smtpHost"); v != "" {
|
||||
cfg.Host = v
|
||||
}
|
||||
if v, _ := s.get("smtpPort"); v != "" {
|
||||
cfg.Port = v
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
|
||||
enabledVal := "true"
|
||||
if !cfg.Enabled {
|
||||
enabledVal = "false"
|
||||
}
|
||||
pairs := [][2]string{
|
||||
{"smtpEnabled", enabledVal},
|
||||
{"smtpEmail", cfg.Email},
|
||||
{"smtpPassword", cfg.Password},
|
||||
{"smtpFromName", cfg.FromName},
|
||||
{"smtpHost", cfg.Host},
|
||||
{"smtpPort", cfg.Port},
|
||||
}
|
||||
for _, p := range pairs {
|
||||
if err := s.set(p[0], p[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
38
mengyastore-backend-go/internal/storage/wishliststore.go
Normal file
38
mengyastore-backend-go/internal/storage/wishliststore.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type WishlistStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewWishlistStore(db *gorm.DB) (*WishlistStore, error) {
|
||||
return &WishlistStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Get(accountID string) ([]string, error) {
|
||||
var rows []database.WishlistRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
ids[i] = r.ProductID
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Add(accountID, productID string) error {
|
||||
return s.db.Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&database.WishlistRow{AccountID: accountID, ProductID: productID}).Error
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Remove(accountID, productID string) error {
|
||||
return s.db.Where("account_id = ? AND product_id = ?", accountID, productID).
|
||||
Delete(&database.WishlistRow{}).Error
|
||||
}
|
||||
Reference in New Issue
Block a user