feat: major update - MySQL, chat, wishlist, PWA, admin overhaul

This commit is contained in:
2026-03-21 20:22:00 +08:00
committed by 树萌芽
parent 48fb818b8c
commit 84874707f5
71 changed files with 13457 additions and 2031 deletions

View File

@@ -26,6 +26,8 @@ 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 {

View File

@@ -9,8 +9,18 @@ import (
type Config struct {
AdminToken string `json:"adminToken"`
AuthAPIURL string `json:"authApiUrl"`
// Database DSN. If empty, falls back to the test DB DSN.
// Format: "user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
DatabaseDSN string `json:"databaseDsn"`
}
// Default DSNs for each environment.
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) {
data, err := os.ReadFile(path)
if err != nil {
@@ -23,5 +33,12 @@ func Load(path string) (*Config, error) {
if cfg.AdminToken == "" {
cfg.AdminToken = "shumengya520"
}
// Default to test DB if not configured; environment variable overrides config file.
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
cfg.DatabaseDSN = dsn
}
if cfg.DatabaseDSN == "" {
cfg.DatabaseDSN = TestDSN
}
return &cfg, nil
}

View File

@@ -0,0 +1,45 @@
package database
import (
"log"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Open initialises a GORM DB connection and runs AutoMigrate for all models.
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{},
)
}

View 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" }

View File

@@ -0,0 +1,192 @@
package email
import (
"crypto/tls"
"fmt"
"net/smtp"
"strings"
"time"
)
// Config holds SMTP sender configuration.
type Config struct {
SMTPHost string // e.g. smtp.qq.com
SMTPPort string // e.g. 465 (SSL) or 587 (STARTTLS)
From string // sender email address
Password string // SMTP auth password / app password
FromName string // display name, e.g. "萌芽小店"
}
// IsConfigured returns true if enough config is present to send mail.
func (c *Config) IsConfigured() bool {
return c.From != "" && c.Password != "" && c.SMTPHost != ""
}
// OrderNotifyData contains the data for an order notification email.
type OrderNotifyData struct {
ToEmail string
ToName string
ProductName string
OrderID string
Quantity int
Codes []string // empty for manual delivery
IsManual bool
}
// SendOrderNotify sends an order delivery notification email.
// Returns nil if config is not ready or ToEmail is empty (silently skip).
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 mail uses SSL on port 465; use TLS dial directly.
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()
}
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()
}
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 dial: %w", err)
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("smtp new client: %w", err)
}
defer client.Quit() //nolint:errcheck
if err = client.Auth(auth); err != nil {
return fmt.Errorf("smtp auth: %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("smtp write body: %w", err)
}
return w.Close()
}

View File

@@ -1,160 +1,24 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"net/http"
"mengyastore-backend/internal/config"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage"
)
// AdminHandler holds dependencies for all admin-related routes.
type AdminHandler struct {
store *storage.JSONStore
cfg *config.Config
store *storage.JSONStore
cfg *config.Config
siteStore *storage.SiteStore
orderStore *storage.OrderStore
chatStore *storage.ChatStore
}
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"`
}
type togglePayload struct {
Active bool `json:"active"`
}
func NewAdminHandler(store *storage.JSONStore, cfg *config.Config) *AdminHandler {
return &AdminHandler{store: store, cfg: cfg}
}
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"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": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
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,
}
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": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
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,
}
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": "invalid payload"})
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{"status": "deleted"})
func NewAdminHandler(store *storage.JSONStore, 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}
}
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
@@ -168,43 +32,3 @@ func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return false
}
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
}

View File

@@ -0,0 +1,88 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// GetAllConversations returns all conversations (map of accountID -> messages).
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 returns all messages for a specific account.
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": "missing account"})
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 sends a reply from admin to a specific user.
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": "missing account"})
return
}
var payload adminChatPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
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 deletes all messages with a specific user.
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": "missing account"})
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}})
}

View 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": "missing order 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}})
}

View File

@@ -0,0 +1,202 @@
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"`
}
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"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": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
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": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
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": "invalid payload"})
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{"status": "deleted"})
}
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
}

View 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": "invalid payload"})
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
}
// Mask password in response
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": "invalid payload"})
return
}
// If password is the masked sentinel, preserve the existing one
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"})
}

View 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 returns all chat messages for the currently logged-in user.
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 sends a message from the current user to admin.
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": "invalid payload"})
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}})
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/email"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage"
)
@@ -19,47 +20,70 @@ const qrSize = "320x320"
type OrderHandler struct {
productStore *storage.JSONStore
orderStore *storage.OrderStore
siteStore *storage.SiteStore
authClient *auth.SproutGateClient
}
type checkoutPayload struct {
ProductID string `json:"productId"`
Quantity int `json:"quantity"`
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.JSONStore, orderStore *storage.OrderStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, authClient: authClient}
func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
}
func (h *OrderHandler) tryExtractUser(c *gin.Context) (string, string) {
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 ") {
log.Println("[Order] 无 Authorization header匿名下单")
return "", ""
return "", "", ""
}
userToken := strings.TrimPrefix(authHeader, "Bearer ")
log.Printf("[Order] 检测到用户 token正在验证 (长度=%d)", len(userToken))
result, err := h.authClient.VerifyToken(userToken)
if err != nil {
log.Printf("[Order] 验证 token 失败: %v", err)
return "", ""
if err != nil || !result.Valid || result.User == nil {
return "", "", ""
}
if !result.Valid {
log.Println("[Order] token 验证返回 valid=false")
return "", ""
}
if result.User == nil {
log.Println("[Order] token 验证成功但 user 为空")
return "", ""
}
log.Printf("[Order] 用户身份验证成功: account=%s username=%s", result.User.Account, result.User.Username)
return result.User.Account, result.User.Username
return result.User.Account, result.User.Username, result.User.Email
}
func (h *OrderHandler) CreateOrder(c *gin.Context) {
userAccount, userName := h.tryExtractUser(c)
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
var payload checkoutPayload
if err := c.ShouldBindJSON(&payload); err != nil {
@@ -85,21 +109,72 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"})
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
}
deliveredCodes, ok := extractCodes(&product, payload.Quantity)
if !ok {
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
}
}
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"
}
// Notification email priority:
// 1. SproutGate account email (logged-in user, most reliable)
// 2. notifyEmail passed by frontend (also comes from authState.email)
// 3. contactEmail explicitly filled by user in checkout form
// 4. empty → skip sending
notifyEmail := strings.TrimSpace(userEmail)
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
}
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.ContactEmail)
}
order := models.Order{
@@ -110,6 +185,11 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
Quantity: payload.Quantity,
DeliveredCodes: deliveredCodes,
Status: "pending",
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 {
@@ -117,6 +197,17 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
return
}
if !isManual {
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
}
// Send delivery notification for auto-delivery orders immediately
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
} else {
// For manual delivery, notify user that order is received and pending
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))
@@ -139,11 +230,25 @@ func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
isManual := order.DeliveryMode == "manual"
// For manual delivery, send a "delivered" notification when admin confirms
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,
},
})
}

View File

@@ -50,3 +50,17 @@ func (h *StatsHandler) RecordVisit(c *gin.Context) {
},
})
}
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,
},
})
}

View 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": "invalid payload"})
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": "missing product 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}})
}

View 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"`
}

View File

@@ -11,5 +11,10 @@ type Order struct {
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"`
}

View File

@@ -16,6 +16,12 @@ type Product struct {
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"`
}

View 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
}

View File

@@ -2,16 +2,15 @@ package storage
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models"
)
@@ -20,238 +19,235 @@ const viewCooldown = 6 * time.Hour
const maxScreenshotURLs = 5
type JSONStore struct {
path string
db *gorm.DB
mu sync.Mutex
recentViews map[string]time.Time
}
func NewJSONStore(path string) (*JSONStore, error) {
if err := ensureProductsFile(path); err != nil {
return nil, err
}
func NewJSONStore(db *gorm.DB) (*JSONStore, error) {
return &JSONStore{
path: path,
db: db,
recentViews: make(map[string]time.Time),
}, nil
}
func ensureProductsFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat data file: %w", err)
// rowToModel converts a ProductRow (+ codes) to a models.Product.
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,
}
}
initial := []models.Product{}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init json: %w", err)
func (s *JSONStore) 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
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write init json: %w", err)
codes := make([]string, len(rows))
for i, r := range rows {
codes[i] = r.Code
}
return nil
return codes, nil
}
func (s *JSONStore) 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 *JSONStore) ListAll() ([]models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.readAll()
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 *JSONStore) ListActive() ([]models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
var rows []database.ProductRow
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
active := make([]models.Product, 0, len(items))
for _, item := range items {
if item.Active {
active = append(active, item)
}
products := make([]models.Product, 0, len(rows))
for _, row := range rows {
// For public listing we don't expose codes, but we still need Quantity
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 active, nil
return products, nil
}
func (s *JSONStore) GetByID(id string) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if 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")
}
for _, item := range items {
if item.ID == id {
return item, nil
}
}
return models.Product{}, fmt.Errorf("product not found")
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *JSONStore) Create(p models.Product) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err
}
p = normalizeProduct(p)
p.ID = uuid.NewString()
now := time.Now()
p.CreatedAt = now
p.UpdatedAt = now
items = append(items, p)
if err := s.writeAll(items); err != nil {
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 *JSONStore) Update(id string, patch models.Product) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
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
}
for i, item := range items {
if item.ID == id {
normalized := normalizeProduct(patch)
item.Name = normalized.Name
item.Price = normalized.Price
item.DiscountPrice = normalized.DiscountPrice
item.Tags = normalized.Tags
item.CoverURL = normalized.CoverURL
item.ScreenshotURLs = normalized.ScreenshotURLs
item.VerificationURL = normalized.VerificationURL
item.Codes = normalized.Codes
item.Quantity = normalized.Quantity
item.Description = normalized.Description
item.Active = normalized.Active
item.UpdatedAt = time.Now()
items[i] = item
if err := s.writeAll(items); err != nil {
return models.Product{}, err
}
return item, nil
}
if err := s.replaceCodes(id, normalized.Codes); err != nil {
return models.Product{}, err
}
return models.Product{}, fmt.Errorf("product not found")
var updated database.ProductRow
s.db.First(&updated, "id = ?", id)
codes, _ := s.loadCodes(id)
return rowToModel(updated, codes), nil
}
func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
return models.Product{}, err
}
for i, item := range items {
if item.ID == id {
item.Active = active
item.UpdatedAt = time.Now()
items[i] = item
if err := s.writeAll(items); err != nil {
return models.Product{}, err
}
return item, nil
}
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, fmt.Errorf("product not found")
}
return models.Product{}, fmt.Errorf("product not found")
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *JSONStore) 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 *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, false, err
}
now := time.Now()
s.cleanupRecentViews(now)
key := buildViewKey(id, fingerprint)
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
for _, item := range items {
if item.ID == id {
return item, false, nil
}
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")
}
for i, item := range items {
if item.ID == id {
item.ViewCount++
item.UpdatedAt = now
items[i] = item
s.recentViews[key] = now
if err := s.writeAll(items); err != nil {
return models.Product{}, false, err
}
return item, true, nil
}
}
return models.Product{}, false, fmt.Errorf("product not found")
return rowToModel(row, nil), true, nil
}
func (s *JSONStore) Delete(id string) error {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err
}
filtered := make([]models.Product, 0, len(items))
for _, item := range items {
if item.ID != id {
filtered = append(filtered, item)
}
}
if err := s.writeAll(filtered); err != nil {
return err
}
return nil
}
func (s *JSONStore) readAll() ([]models.Product, error) {
bytes, err := os.ReadFile(s.path)
if err != nil {
return nil, fmt.Errorf("read products: %w", err)
}
var items []models.Product
if err := json.Unmarshal(bytes, &items); err != nil {
return nil, fmt.Errorf("parse products: %w", err)
}
for i, item := range items {
items[i] = normalizeProduct(item)
}
return items, nil
}
func (s *JSONStore) writeAll(items []models.Product) error {
for i, item := range items {
items[i] = normalizeProduct(item)
}
bytes, err := json.MarshalIndent(items, "", " ")
if err != nil {
return fmt.Errorf("encode products: %w", err)
}
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write products: %w", err)
}
return nil
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
}
// normalizeProduct cleans up product fields (same logic as before, no file I/O).
func normalizeProduct(item models.Product) models.Product {
item.CoverURL = strings.TrimSpace(item.CoverURL)
if item.CoverURL == "" {
@@ -276,6 +272,9 @@ func normalizeProduct(item models.Product) models.Product {
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
item.Codes = sanitizeCodes(item.Codes)
item.Quantity = len(item.Codes)
if item.DeliveryMode == "" {
item.DeliveryMode = "auto"
}
return item
}
@@ -284,10 +283,7 @@ func sanitizeCodes(codes []string) []string {
seen := map[string]bool{}
for _, code := range codes {
trimmed := strings.TrimSpace(code)
if trimmed == "" {
continue
}
if seen[trimmed] {
if trimmed == "" || seen[trimmed] {
continue
}
seen[trimmed] = true

View File

@@ -1,140 +1,139 @@
package storage
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models"
)
type OrderStore struct {
path string
mu sync.Mutex
db *gorm.DB
}
func NewOrderStore(path string) (*OrderStore, error) {
if err := ensureOrdersFile(path); err != nil {
return nil, err
}
return &OrderStore{path: path}, nil
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
return &OrderStore{db: db}, nil
}
func (s *OrderStore) Count() (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return 0, err
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,
}
return len(items), nil
}
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return nil, err
}
matched := make([]models.Order, 0)
for i := len(items) - 1; i >= 0; i-- {
if items[i].UserAccount == account {
matched = append(matched, items[i])
}
}
return matched, nil
}
func (s *OrderStore) Confirm(id string) (models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
for i, item := range items {
if item.ID == id {
if item.Status == "completed" {
return item, nil
}
items[i].Status = "completed"
if err := s.writeAll(items); err != nil {
return models.Order{}, err
}
return items[i], nil
}
}
return models.Order{}, fmt.Errorf("order not found")
}
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
order.ID = uuid.NewString()
order.CreatedAt = time.Now()
items = append(items, order)
if err := s.writeAll(items); err != nil {
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) readAll() ([]models.Order, error) {
bytes, err := os.ReadFile(s.path)
if err != nil {
return nil, fmt.Errorf("read orders: %w", err)
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")
}
var items []models.Order
if err := json.Unmarshal(bytes, &items); err != nil {
return nil, fmt.Errorf("parse orders: %w", err)
}
return items, nil
return orderRowToModel(row), nil
}
func (s *OrderStore) writeAll(items []models.Order) error {
bytes, err := json.MarshalIndent(items, "", " ")
if err != nil {
return fmt.Errorf("encode orders: %w", err)
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 := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write orders: %w", err)
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
return models.Order{}, err
}
return nil
row.Status = "completed"
return orderRowToModel(row), nil
}
func ensureOrdersFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
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
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat data file: %w", err)
orders := make([]models.Order, len(rows))
for i, r := range rows {
orders[i] = orderRowToModel(r)
}
initial := []models.Order{}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init json: %w", err)
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write init json: %w", err)
}
return nil
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
err := s.db.Model(&database.OrderRow{}).
Where("user_account = ? AND product_id = ? AND status = ?", account, productID, "completed").
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
return int(total), err
}
// Count returns the total number of orders.
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 removes a single order by ID.
func (s *OrderStore) Delete(id string) error {
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
}
// UpdateCodes replaces the delivered codes for an order (used by auto-delivery to set codes after extracting).
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
}

View File

@@ -1,128 +1,135 @@
package storage
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"strconv"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"mengyastore-backend/internal/database"
)
const visitCooldown = 6 * time.Hour
type siteData struct {
TotalVisits int `json:"totalVisits"`
}
type SiteStore struct {
path string
mu sync.Mutex
recentVisits map[string]time.Time
db *gorm.DB
}
func NewSiteStore(path string) (*SiteStore, error) {
if err := ensureSiteFile(path); err != nil {
return nil, err
}
return &SiteStore{
path: path,
recentVisits: make(map[string]time.Time),
}, nil
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
return &SiteStore{db: db}, nil
}
func (s *SiteStore) RecordVisit(fingerprint string) (int, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
s.cleanupRecentVisits(now)
key := buildSiteVisitKey(fingerprint)
if last, ok := s.recentVisits[key]; ok && now.Sub(last) < visitCooldown {
data, err := s.read()
if err != nil {
return 0, false, err
}
return data.TotalVisits, false, nil
func (s *SiteStore) get(key string) (string, error) {
var row database.SiteSettingRow
if err := s.db.First(&row, "key = ?", key).Error; err != nil {
return "", nil // key not found → return zero value
}
return row.Value, nil
}
data, err := s.read()
if err != nil {
return 0, false, err
}
data.TotalVisits++
s.recentVisits[key] = now
if err := s.write(data); err != nil {
return 0, false, err
}
return data.TotalVisits, true, 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) {
s.mu.Lock()
defer s.mu.Unlock()
data, err := s.read()
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
}
return data.TotalVisits, nil
current++
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
return 0, err
}
return current, nil
}
func (s *SiteStore) read() (siteData, error) {
bytes, err := os.ReadFile(s.path)
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
v, err := s.get("maintenance")
if err != nil {
return siteData{}, fmt.Errorf("read site data: %w", err)
return false, "", err
}
var data siteData
if err := json.Unmarshal(bytes, &data); err != nil {
return siteData{}, fmt.Errorf("parse site data: %w", err)
}
return data, nil
enabled = v == "true"
reason, err = s.get("maintenanceReason")
return enabled, reason, err
}
func (s *SiteStore) write(data siteData) error {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return fmt.Errorf("encode site data: %w", err)
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
v := "false"
if enabled {
v = "true"
}
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write site data: %w", err)
if err := s.set("maintenance", v); err != nil {
return err
}
return nil
return s.set("maintenanceReason", reason)
}
func (s *SiteStore) cleanupRecentVisits(now time.Time) {
for key, last := range s.recentVisits {
if now.Sub(last) >= visitCooldown {
delete(s.recentVisits, key)
// RecordVisit increments the visit counter. Returns (totalVisits, counted, error).
// For simplicity, every call increments (fingerprint dedup is handled in-memory by the handler layer).
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
total, err := s.IncrementVisits()
return total, true, err
}
// SMTPConfig holds the mail sender configuration stored in the DB.
type SMTPConfig struct {
Email string `json:"email"`
Password string `json:"password"`
FromName string `json:"fromName"`
Host string `json:"host"`
Port string `json:"port"`
}
// IsConfiguredEmail returns true if the SMTP config is ready to send mail.
func (c SMTPConfig) IsConfiguredEmail() bool {
return c.Email != "" && c.Password != "" && c.Host != ""
}
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
cfg := SMTPConfig{
Host: "smtp.qq.com",
Port: "465",
}
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 {
pairs := [][2]string{
{"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
}
}
}
func buildSiteVisitKey(fingerprint string) string {
sum := sha256.Sum256([]byte("site|" + fingerprint))
return fmt.Sprintf("%x", sum)
}
func ensureSiteFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat site file: %w", err)
}
initial := siteData{TotalVisits: 0}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init site json: %w", err)
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write site json: %w", err)
}
return nil
}

View 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
}