新增摸大红业务并修复后台链接按钮白字

支持分类筛选、搜索、下单支付建群与固定二维码;合并迁移种子数据;后台表格编辑/详情链接恢复主题色可见。
This commit is contained in:
yml2213
2026-07-16 18:08:18 +08:00
parent 97a34e0329
commit 6d61027318
49 changed files with 9533 additions and 20 deletions
+1
View File
@@ -10,6 +10,7 @@ type ChatConversation struct {
ID uint64 `gorm:"primaryKey" json:"id"`
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
ListingID *uint64 `gorm:"index" json:"listing_id"`
MohongOrderID *uint64 `gorm:"column:mohong_order_id;uniqueIndex" json:"mohong_order_id"`
Type string `gorm:"size:32;not null;default:'order_group'" json:"type"`
Title string `gorm:"size:128;not null" json:"title"`
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
+98
View File
@@ -0,0 +1,98 @@
package model
import (
"time"
"gorm.io/datatypes"
)
// MohongCategory 摸大红商品分类。
type MohongCategory struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:64;not null;uniqueIndex" json:"name"`
Code string `gorm:"size:64;not null;default:''" json:"code"`
SortOrder int `gorm:"column:sort_order;not null;default:0" json:"sort_order"`
Status string `gorm:"size:16;not null;default:'enabled'" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (MohongCategory) TableName() string {
return "mohong_categories"
}
// MohongProductCategory 商品与分类多对多(同一商品可出现在大红/九格等)。
type MohongProductCategory struct {
ProductID uint64 `gorm:"column:product_id;primaryKey" json:"product_id"`
CategoryID uint64 `gorm:"column:category_id;primaryKey;index" json:"category_id"`
}
func (MohongProductCategory) TableName() string {
return "mohong_product_categories"
}
// MohongProduct 摸大红商品。
type MohongProduct struct {
ID uint64 `gorm:"primaryKey" json:"id"`
CategoryID *uint64 `gorm:"column:category_id;index" json:"category_id"` // 主分类(展示用)
Title string `gorm:"size:128;not null" json:"title"`
CoverURL string `gorm:"column:cover_url;size:512;not null;default:''" json:"cover_url"`
ImageURLs datatypes.JSON `gorm:"column:image_urls" json:"image_urls"`
Description string `gorm:"type:text;not null" json:"description"`
PriceCent int64 `gorm:"column:price_cent;not null;default:0" json:"-"`
OriginalPriceCent int64 `gorm:"column:original_price_cent;not null;default:0" json:"-"`
Unit string `gorm:"size:32;not null;default:'份'" json:"unit"`
Stock int `gorm:"not null;default:-1" json:"stock"`
SortOrder int `gorm:"column:sort_order;not null;default:0" json:"sort_order"`
Status string `gorm:"size:16;not null;default:'draft'" json:"status"`
QrcodeImageURL string `gorm:"column:qrcode_image_url;size:512;not null;default:''" json:"qrcode_image_url"`
CreatedBy *uint64 `gorm:"column:created_by" json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (MohongProduct) TableName() string {
return "mohong_products"
}
// MohongOrder 摸大红订单。
type MohongOrder struct {
ID uint64 `gorm:"primaryKey" json:"id"`
OrderNo string `gorm:"size:64;not null;uniqueIndex" json:"order_no"`
UserID uint64 `gorm:"not null;index" json:"user_id"`
ProductID uint64 `gorm:"not null;index" json:"product_id"`
Quantity int `gorm:"not null;default:1" json:"quantity"`
UnitPriceCent int64 `gorm:"column:unit_price_cent;not null;default:0" json:"-"`
AmountCent int64 `gorm:"column:amount_cent;not null;default:0" json:"-"`
Status string `gorm:"size:32;not null;default:'pending_payment';index" json:"status"`
ProductSnapshot datatypes.JSON `gorm:"column:product_snapshot" json:"product_snapshot"`
QrcodeURLSnapshot string `gorm:"column:qrcode_url_snapshot;size:512;not null;default:''" json:"qrcode_url_snapshot"`
CopyText string `gorm:"type:text;not null" json:"copy_text"`
ConversationID *uint64 `gorm:"column:conversation_id" json:"conversation_id"`
PaidAt *time.Time `json:"paid_at"`
CompletedAt *time.Time `json:"completed_at"`
CancelledAt *time.Time `json:"cancelled_at"`
CancelReason string `gorm:"size:255;not null;default:''" json:"cancel_reason"`
AdminRemark string `gorm:"size:255;not null;default:''" json:"admin_remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (MohongOrder) TableName() string {
return "mohong_orders"
}
const (
MohongCategoryStatusEnabled = "enabled"
MohongCategoryStatusDisabled = "disabled"
MohongProductStatusDraft = "draft"
MohongProductStatusOnSale = "on_sale"
MohongProductStatusOffSale = "off_sale"
MohongOrderStatusPendingPayment = "pending_payment"
MohongOrderStatusPaid = "paid"
MohongOrderStatusCompleted = "completed"
MohongOrderStatusCancelled = "cancelled"
MohongOrderStatusRefunded = "refunded"
)
+36
View File
@@ -0,0 +1,36 @@
package chat
import (
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
)
// DefaultSupportAdminID 导出默认客服选择逻辑,供其他业务模块建群时复用。
func DefaultSupportAdminID(tx *gorm.DB) uint64 {
return defaultSupportAdminID(tx)
}
// SendSystemMessageForTx 在事务内发送系统文本消息。
func SendSystemMessageForTx(tx *gorm.DB, conversationID uint64, content string) error {
return sendSystemMessage(tx, conversationID, content)
}
// SendImageMessageForTx 在事务内发送系统图片消息。
func SendImageMessageForTx(tx *gorm.DB, conversationID uint64, content, imageURL string) error {
if content == "" {
content = "👇 请扫码联系客服"
}
message := model.ChatMessage{
ConversationID: conversationID,
SenderType: "system",
SenderRole: "system",
ContentType: "image",
Content: content,
AttachmentURLS: encodeStringList([]string{imageURL}),
}
if err := tx.Create(&message).Error; err != nil {
return err
}
return updateConversationLastMessage(tx, conversationID, &message)
}
+6 -1
View File
@@ -65,7 +65,12 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
response.BadRequest(c, "文件 key 不正确")
return
}
if publicOnly && !strings.HasPrefix(key, "home-banner/") && !strings.HasPrefix(key, "avatar/") && !strings.HasPrefix(key, "payment-cert/") && !strings.HasPrefix(key, "announcement/") {
if publicOnly &&
!strings.HasPrefix(key, "home-banner/") &&
!strings.HasPrefix(key, "avatar/") &&
!strings.HasPrefix(key, "payment-cert/") &&
!strings.HasPrefix(key, "announcement/") &&
!strings.HasPrefix(key, "mohong/") {
response.Error(c, http.StatusNotFound, "not_found", "文件不存在或暂不可访问")
return
}
+2 -2
View File
@@ -106,7 +106,7 @@ func normalizeContentType(contentType string, data []byte) string {
func fileURLForScene(scene string, key string) string {
fileURL := "/api/files/object?key=" + url.QueryEscape(key)
if scene == "home-banner" || scene == "avatar" || scene == "payment-cert" || scene == "announcement" {
if scene == "home-banner" || scene == "avatar" || scene == "payment-cert" || scene == "announcement" || scene == "mohong" {
fileURL = "/api/public/files/object?key=" + url.QueryEscape(key)
}
return fileURL
@@ -115,7 +115,7 @@ func fileURLForScene(scene string, key string) string {
func normalizeScene(scene string) string {
scene = strings.TrimSpace(strings.ToLower(scene))
switch scene {
case "listing", "handoff", "dispute", "realname", "avatar", "home-banner", "chat", "payment-cert", "announcement", "qrcode":
case "listing", "handoff", "dispute", "realname", "avatar", "home-banner", "chat", "payment-cert", "announcement", "qrcode", "mohong":
return scene
default:
return "misc"
@@ -0,0 +1,204 @@
package mohong
import (
"context"
"strings"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
)
func (r *Repository) ListPublicCategories(ctx context.Context) ([]CategoryDTO, error) {
var rows []model.MohongCategory
if err := r.db.WithContext(ctx).
Where("status = ?", model.MohongCategoryStatusEnabled).
Order("sort_order ASC, id ASC").
Find(&rows).Error; err != nil {
return nil, err
}
return r.attachCategoryCounts(ctx, rows, true)
}
func (r *Repository) AdminListCategories(ctx context.Context) ([]CategoryDTO, error) {
var rows []model.MohongCategory
if err := r.db.WithContext(ctx).
Order("sort_order ASC, id ASC").
Find(&rows).Error; err != nil {
return nil, err
}
return r.attachCategoryCounts(ctx, rows, false)
}
func (r *Repository) attachCategoryCounts(ctx context.Context, rows []model.MohongCategory, onlyOnSale bool) ([]CategoryDTO, error) {
type countRow struct {
CategoryID uint64
Cnt int64
}
var counts []countRow
// 优先按多对多关联统计;兼容仅写了主分类 category_id 的旧数据
q := r.db.WithContext(ctx).Table("mohong_product_categories AS pc").
Select("pc.category_id AS category_id, COUNT(DISTINCT pc.product_id) AS cnt").
Joins("JOIN mohong_products p ON p.id = pc.product_id")
if onlyOnSale {
q = q.Where("p.status = ?", model.MohongProductStatusOnSale)
}
if err := q.Group("pc.category_id").Scan(&counts).Error; err != nil {
return nil, err
}
// 补充仅有主分类、未写入关联表的商品
var fallback []countRow
fq := r.db.WithContext(ctx).Model(&model.MohongProduct{}).
Select("category_id AS category_id, COUNT(*) AS cnt").
Where("category_id IS NOT NULL").
Where("id NOT IN (SELECT product_id FROM mohong_product_categories)")
if onlyOnSale {
fq = fq.Where("status = ?", model.MohongProductStatusOnSale)
}
_ = fq.Group("category_id").Scan(&fallback).Error
for _, c := range fallback {
counts = append(counts, c)
}
countMap := map[uint64]int64{}
for _, c := range counts {
countMap[c.CategoryID] = c.Cnt
}
items := make([]CategoryDTO, 0, len(rows))
for _, row := range rows {
items = append(items, CategoryDTO{
ID: row.ID,
Name: row.Name,
Code: row.Code,
SortOrder: row.SortOrder,
Status: row.Status,
ProductCount: countMap[row.ID],
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
})
}
return items, nil
}
func (r *Repository) CreateCategory(ctx context.Context, req CreateCategoryRequest) (*CategoryDTO, error) {
name := strings.TrimSpace(req.Name)
if name == "" {
return nil, ErrInvalidRequest
}
status := strings.TrimSpace(req.Status)
if status == "" {
status = model.MohongCategoryStatusEnabled
}
if status != model.MohongCategoryStatusEnabled && status != model.MohongCategoryStatusDisabled {
return nil, ErrInvalidRequest
}
row := model.MohongCategory{
Name: name,
Code: strings.TrimSpace(req.Code),
SortOrder: req.SortOrder,
Status: status,
}
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
return nil, err
}
return &CategoryDTO{
ID: row.ID,
Name: row.Name,
Code: row.Code,
SortOrder: row.SortOrder,
Status: row.Status,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}, nil
}
func (r *Repository) UpdateCategory(ctx context.Context, id uint64, req UpdateCategoryRequest) (*CategoryDTO, error) {
var row model.MohongCategory
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrInvalidRequest
}
return nil, err
}
updates := map[string]any{}
if req.Name != nil {
name := strings.TrimSpace(*req.Name)
if name == "" {
return nil, ErrInvalidRequest
}
updates["name"] = name
}
if req.Code != nil {
updates["code"] = strings.TrimSpace(*req.Code)
}
if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder
}
if req.Status != nil {
status := strings.TrimSpace(*req.Status)
if status != model.MohongCategoryStatusEnabled && status != model.MohongCategoryStatusDisabled {
return nil, ErrInvalidRequest
}
updates["status"] = status
}
if len(updates) > 0 {
if err := r.db.WithContext(ctx).Model(&row).Updates(updates).Error; err != nil {
return nil, err
}
}
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
return nil, err
}
items, err := r.attachCategoryCounts(ctx, []model.MohongCategory{row}, false)
if err != nil {
return nil, err
}
return &items[0], nil
}
func (r *Repository) DeleteCategory(ctx context.Context, id uint64) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&model.MohongProduct{}).
Where("category_id = ?", id).
Update("category_id", nil).Error; err != nil {
return err
}
res := tx.Delete(&model.MohongCategory{}, id)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrInvalidRequest
}
return nil
})
}
func (r *Repository) loadCategoryNameMap(ctx context.Context, ids []uint64) map[uint64]string {
out := map[uint64]string{}
if len(ids) == 0 {
return out
}
uniq := make([]uint64, 0, len(ids))
seen := map[uint64]struct{}{}
for _, id := range ids {
if id == 0 {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
uniq = append(uniq, id)
}
if len(uniq) == 0 {
return out
}
var rows []model.MohongCategory
if err := r.db.WithContext(ctx).Where("id IN ?", uniq).Find(&rows).Error; err != nil {
return out
}
for _, row := range rows {
out[row.ID] = row.Name
}
return out
}
+117
View File
@@ -0,0 +1,117 @@
package mohong
import (
"context"
"strings"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
configKeyDefaultQrcodeURL = "mohong.default_qrcode_url"
configKeyGroupWelcomeText = "mohong.group_welcome_text"
configKeyOrderCopyTemplate = "mohong.order_copy_template"
defaultGroupWelcomeText = "订单已支付,请扫码联系客服,并将下方订单信息复制发送给客服。"
defaultOrderCopyTemplate = "【摸大红订单】\n订单号:{{order_no}}\n下单时间:{{created_at}}\n商品:{{product_title}}\n数量:{{quantity}}\n金额:{{amount}}\n下单人:{{buyer_name}}{{buyer_phone}}"
)
func (r *Repository) GetConfig(ctx context.Context) (*ConfigDTO, error) {
if r.db == nil {
return nil, ErrDependencyUnavailable
}
keys := []string{configKeyDefaultQrcodeURL, configKeyGroupWelcomeText, configKeyOrderCopyTemplate}
var rows []model.SystemConfig
if err := r.db.WithContext(ctx).Where("`key` IN ?", keys).Find(&rows).Error; err != nil {
return nil, err
}
values := map[string]string{}
for _, row := range rows {
values[row.Key] = row.Value
}
return &ConfigDTO{
DefaultQrcodeURL: strings.TrimSpace(values[configKeyDefaultQrcodeURL]),
GroupWelcomeText: firstNonEmpty(values[configKeyGroupWelcomeText], defaultGroupWelcomeText),
OrderCopyTemplate: firstNonEmpty(values[configKeyOrderCopyTemplate], defaultOrderCopyTemplate),
}, nil
}
func (r *Repository) UpdateConfig(ctx context.Context, req UpdateConfigRequest) (*ConfigDTO, error) {
if r.db == nil {
return nil, ErrDependencyUnavailable
}
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if req.DefaultQrcodeURL != nil {
if err := upsertConfig(tx, configKeyDefaultQrcodeURL, strings.TrimSpace(*req.DefaultQrcodeURL), "摸大红全局默认固定二维码图片URL"); err != nil {
return err
}
}
if req.GroupWelcomeText != nil {
if err := upsertConfig(tx, configKeyGroupWelcomeText, strings.TrimSpace(*req.GroupWelcomeText), "摸大红订单群欢迎语"); err != nil {
return err
}
}
if req.OrderCopyTemplate != nil {
if err := upsertConfig(tx, configKeyOrderCopyTemplate, strings.TrimSpace(*req.OrderCopyTemplate), "摸大红订单一键复制文案模板"); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
return r.GetConfig(ctx)
}
func upsertConfig(tx *gorm.DB, key, value, description string) error {
row := model.SystemConfig{
Key: key,
Value: value,
Description: description,
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "key"}},
DoUpdates: clause.AssignmentColumns([]string{"value", "description"}),
}).Create(&row).Error
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return ""
}
func (r *Repository) resolveQrcodeURL(tx *gorm.DB, productQrcode string) string {
productQrcode = strings.TrimSpace(productQrcode)
if productQrcode != "" {
return productQrcode
}
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", configKeyDefaultQrcodeURL).First(&cfg).Error; err == nil {
return strings.TrimSpace(cfg.Value)
}
return ""
}
func (r *Repository) loadWelcomeText(tx *gorm.DB) string {
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", configKeyGroupWelcomeText).First(&cfg).Error; err == nil && strings.TrimSpace(cfg.Value) != "" {
return strings.TrimSpace(cfg.Value)
}
return defaultGroupWelcomeText
}
func (r *Repository) loadCopyTemplate(tx *gorm.DB) string {
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", configKeyOrderCopyTemplate).First(&cfg).Error; err == nil && strings.TrimSpace(cfg.Value) != "" {
return strings.TrimSpace(cfg.Value)
}
return defaultOrderCopyTemplate
}
+167
View File
@@ -0,0 +1,167 @@
package mohong
import "time"
type CategoryDTO struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
SortOrder int `json:"sort_order"`
Status string `json:"status"`
ProductCount int64 `json:"product_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CreateCategoryRequest struct {
Name string `json:"name" binding:"required,max=64"`
Code string `json:"code"`
SortOrder int `json:"sort_order"`
Status string `json:"status"`
}
type UpdateCategoryRequest struct {
Name *string `json:"name"`
Code *string `json:"code"`
SortOrder *int `json:"sort_order"`
Status *string `json:"status"`
}
type ProductDTO struct {
ID uint64 `json:"id"`
CategoryID *uint64 `json:"category_id"`
CategoryName string `json:"category_name,omitempty"`
Title string `json:"title"`
CoverURL string `json:"cover_url"`
ImageURLs []string `json:"image_urls"`
Description string `json:"description"`
PriceCent int64 `json:"price_cent"`
Price string `json:"price"`
OriginalPriceCent int64 `json:"original_price_cent"`
OriginalPrice string `json:"original_price,omitempty"`
Unit string `json:"unit"`
Stock int `json:"stock"`
SortOrder int `json:"sort_order"`
Status string `json:"status"`
QrcodeImageURL string `json:"qrcode_image_url,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ProductListQuery struct {
Keyword string
Status string
CategoryID uint64
Page int
PageSize int
}
type CreateProductRequest struct {
CategoryID *uint64 `json:"category_id"`
Title string `json:"title" binding:"required,max=128"`
CoverURL string `json:"cover_url"`
ImageURLs []string `json:"image_urls"`
Description string `json:"description"`
PriceCent int64 `json:"price_cent" binding:"required,min=1"`
OriginalPriceCent int64 `json:"original_price_cent"`
Unit string `json:"unit"`
Stock *int `json:"stock"`
SortOrder int `json:"sort_order"`
Status string `json:"status"`
QrcodeImageURL string `json:"qrcode_image_url"`
}
type UpdateProductRequest struct {
CategoryID *uint64 `json:"category_id"`
ClearCategory bool `json:"clear_category"`
Title *string `json:"title"`
CoverURL *string `json:"cover_url"`
ImageURLs []string `json:"image_urls"`
Description *string `json:"description"`
PriceCent *int64 `json:"price_cent"`
OriginalPriceCent *int64 `json:"original_price_cent"`
Unit *string `json:"unit"`
Stock *int `json:"stock"`
SortOrder *int `json:"sort_order"`
Status *string `json:"status"`
QrcodeImageURL *string `json:"qrcode_image_url"`
}
type CreateOrderRequest struct {
ProductID uint64 `json:"product_id" binding:"required"`
Quantity int `json:"quantity" binding:"required,min=1,max=99"`
}
type OrderDTO struct {
ID uint64 `json:"id"`
OrderNo string `json:"order_no"`
UserID uint64 `json:"user_id"`
ProductID uint64 `json:"product_id"`
Quantity int `json:"quantity"`
UnitPriceCent int64 `json:"unit_price_cent"`
UnitPrice string `json:"unit_price"`
AmountCent int64 `json:"amount_cent"`
Amount string `json:"amount"`
Status string `json:"status"`
ProductTitle string `json:"product_title"`
ProductCoverURL string `json:"product_cover_url"`
ProductUnit string `json:"product_unit"`
QrcodeURLSnapshot string `json:"qrcode_url_snapshot"`
CopyText string `json:"copy_text"`
ConversationID *uint64 `json:"conversation_id"`
BuyerNickname string `json:"buyer_nickname,omitempty"`
BuyerPhone string `json:"buyer_phone,omitempty"`
AdminRemark string `json:"admin_remark,omitempty"`
CancelReason string `json:"cancel_reason,omitempty"`
PaidAt *time.Time `json:"paid_at"`
CompletedAt *time.Time `json:"completed_at"`
CancelledAt *time.Time `json:"cancelled_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type OrderListQuery struct {
UserID uint64
Status string
Keyword string
Page int
PageSize int
}
type AdminCompleteOrderRequest struct {
Remark string `json:"remark"`
}
type AdminCancelOrderRequest struct {
Reason string `json:"reason"`
}
type ConfigDTO struct {
DefaultQrcodeURL string `json:"default_qrcode_url"`
GroupWelcomeText string `json:"group_welcome_text"`
OrderCopyTemplate string `json:"order_copy_template"`
}
type UpdateConfigRequest struct {
DefaultQrcodeURL *string `json:"default_qrcode_url"`
GroupWelcomeText *string `json:"group_welcome_text"`
OrderCopyTemplate *string `json:"order_copy_template"`
}
type PaginatedResult struct {
Items any `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
type productSnapshot struct {
ID uint64 `json:"id"`
Title string `json:"title"`
CoverURL string `json:"cover_url"`
ImageURLs []string `json:"image_urls"`
Description string `json:"description"`
PriceCent int64 `json:"price_cent"`
Unit string `json:"unit"`
QrcodeImageURL string `json:"qrcode_image_url"`
}
+16
View File
@@ -0,0 +1,16 @@
package mohong
import "errors"
var (
ErrDependencyUnavailable = errors.New("dependency unavailable")
ErrProductNotFound = errors.New("product not found")
ErrProductUnavailable = errors.New("product unavailable")
ErrStockInsufficient = errors.New("stock insufficient")
ErrInvalidRequest = errors.New("invalid request")
ErrOrderNotFound = errors.New("order not found")
ErrOrderCannotPay = errors.New("order cannot pay")
ErrOrderCannotCancel = errors.New("order cannot cancel")
ErrOrderCannotComplete = errors.New("order cannot complete")
ErrUnauthorized = errors.New("unauthorized")
)
+415
View File
@@ -0,0 +1,415 @@
package mohong
import (
"errors"
"strconv"
"strings"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) ListCategories(c *gin.Context) {
items, err := h.service.ListPublicCategories(c.Request.Context())
if err != nil {
response.InternalServerError(c, "获取分类失败")
return
}
response.OK(c, items)
}
func (h *Handler) ListProducts(c *gin.Context) {
query := ProductListQuery{Keyword: c.Query("keyword")}
if catID, err := strconv.ParseUint(c.Query("category_id"), 10, 64); err == nil {
query.CategoryID = catID
}
query.Page, query.PageSize = parsePagination(c)
result, err := h.service.ListPublicProducts(c.Request.Context(), query)
if err != nil {
response.InternalServerError(c, "获取商品列表失败")
return
}
response.OK(c, result)
}
func (h *Handler) GetProduct(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.FindPublicProduct(c.Request.Context(), id)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) CreateOrder(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
var req CreateOrderRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.CreateOrder(c.Request.Context(), userID, req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) ListMyOrders(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
query := OrderListQuery{Status: c.Query("status"), Keyword: c.Query("keyword")}
query.Page, query.PageSize = parsePagination(c)
result, err := h.service.ListOrdersForUser(c.Request.Context(), userID, query)
if err != nil {
response.InternalServerError(c, "获取订单列表失败")
return
}
response.OK(c, result)
}
func (h *Handler) GetMyOrder(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.FindOrderForUser(c.Request.Context(), userID, id)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) CancelMyOrder(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
var body struct {
Reason string `json:"reason"`
}
_ = c.ShouldBindJSON(&body)
item, err := h.service.CancelOrder(c.Request.Context(), userID, id, body.Reason)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminListCategories(c *gin.Context) {
items, err := h.service.AdminListCategories(c.Request.Context())
if err != nil {
response.InternalServerError(c, "获取分类失败")
return
}
response.OK(c, items)
}
func (h *Handler) AdminCreateCategory(c *gin.Context) {
var req CreateCategoryRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.CreateCategory(c.Request.Context(), req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminUpdateCategory(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req UpdateCategoryRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.UpdateCategory(c.Request.Context(), id, req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminDeleteCategory(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.service.DeleteCategory(c.Request.Context(), id); err != nil {
writeError(c, err)
return
}
response.OK(c, gin.H{"message": "删除成功"})
}
func (h *Handler) AdminListProducts(c *gin.Context) {
query := ProductListQuery{
Keyword: c.Query("keyword"),
Status: c.Query("status"),
}
if catID, err := strconv.ParseUint(c.Query("category_id"), 10, 64); err == nil {
query.CategoryID = catID
}
query.Page, query.PageSize = parsePagination(c)
result, err := h.service.AdminListProducts(c.Request.Context(), query)
if err != nil {
response.InternalServerError(c, "获取商品列表失败")
return
}
response.OK(c, result)
}
func (h *Handler) AdminGetProduct(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.AdminFindProduct(c.Request.Context(), id)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminCreateProduct(c *gin.Context) {
adminID, ok := currentAdminID(c)
if !ok {
response.Unauthorized(c, "未授权")
return
}
var req CreateProductRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.CreateProduct(c.Request.Context(), adminID, req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminUpdateProduct(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req UpdateProductRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.UpdateProduct(c.Request.Context(), id, req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminDeleteProduct(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.service.DeleteProduct(c.Request.Context(), id); err != nil {
writeError(c, err)
return
}
response.OK(c, gin.H{"message": "删除成功"})
}
func (h *Handler) AdminListOrders(c *gin.Context) {
query := OrderListQuery{
Status: c.Query("status"),
Keyword: c.Query("keyword"),
}
if userID, err := strconv.ParseUint(c.Query("user_id"), 10, 64); err == nil {
query.UserID = userID
}
query.Page, query.PageSize = parsePagination(c)
result, err := h.service.AdminListOrders(c.Request.Context(), query)
if err != nil {
response.InternalServerError(c, "获取订单列表失败")
return
}
response.OK(c, result)
}
func (h *Handler) AdminGetOrder(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.AdminFindOrder(c.Request.Context(), id)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminCompleteOrder(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req AdminCompleteOrderRequest
_ = c.ShouldBindJSON(&req)
item, err := h.service.AdminCompleteOrder(c.Request.Context(), id, req.Remark)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminCancelOrder(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req AdminCancelOrderRequest
_ = c.ShouldBindJSON(&req)
item, err := h.service.AdminCancelOrder(c.Request.Context(), id, req.Reason)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdminGetConfig(c *gin.Context) {
item, err := h.service.GetConfig(c.Request.Context())
if err != nil {
response.InternalServerError(c, "获取配置失败")
return
}
response.OK(c, item)
}
func (h *Handler) AdminUpdateConfig(c *gin.Context) {
var req UpdateConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求参数不正确")
return
}
item, err := h.service.UpdateConfig(c.Request.Context(), req)
if err != nil {
response.InternalServerError(c, "更新配置失败")
return
}
response.OK(c, item)
}
func writeError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrProductNotFound), errors.Is(err, ErrOrderNotFound):
response.NotFound(c, err.Error())
case errors.Is(err, ErrProductUnavailable):
response.Error(c, 409, "product_unavailable", "商品不可购买")
case errors.Is(err, ErrStockInsufficient):
response.Error(c, 409, "stock_insufficient", "库存不足")
case errors.Is(err, ErrOrderCannotPay):
response.Error(c, 409, "order_cannot_pay", "订单无法支付")
case errors.Is(err, ErrOrderCannotCancel):
response.Error(c, 409, "order_cannot_cancel", "订单无法取消")
case errors.Is(err, ErrOrderCannotComplete):
response.Error(c, 409, "order_cannot_complete", "订单无法完成")
case errors.Is(err, ErrInvalidRequest):
response.BadRequest(c, "请求参数不正确")
case errors.Is(err, ErrUnauthorized):
response.Unauthorized(c, "未授权")
default:
msg := strings.TrimSpace(err.Error())
if msg == "" {
msg = "操作失败"
}
response.InternalServerError(c, msg)
}
}
func parseID(c *gin.Context) (uint64, bool) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
response.BadRequest(c, "ID不正确")
return 0, false
}
return id, true
}
func parsePagination(c *gin.Context) (int, int) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
if pageSize > 100 {
pageSize = 100
}
return page, pageSize
}
func currentUserID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextUserID)
if !ok {
return 0, false
}
id, ok := value.(uint64)
return id, ok
}
func currentAdminID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextAdminID)
if !ok {
return 0, false
}
id, ok := value.(uint64)
return id, ok
}
@@ -0,0 +1,470 @@
package mohong
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/chat"
"hfb_sys/backend/internal/modules/notification"
"hfb_sys/backend/internal/modules/supportgroup"
"hfb_sys/backend/internal/timeutil"
"hfb_sys/backend/pkg/money"
"gorm.io/datatypes"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const ConversationTypeMohongOrder = "mohong_order"
func (r *Repository) CreateOrder(ctx context.Context, userID uint64, req CreateOrderRequest) (*OrderDTO, error) {
if userID == 0 || req.ProductID == 0 || req.Quantity < 1 || req.Quantity > 99 {
return nil, ErrInvalidRequest
}
var createdID uint64
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var product model.MohongProduct
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&product, req.ProductID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return ErrProductNotFound
}
return err
}
if product.Status != model.MohongProductStatusOnSale {
return ErrProductUnavailable
}
if product.PriceCent <= 0 {
return ErrProductUnavailable
}
if product.Stock >= 0 && product.Stock < req.Quantity {
return ErrStockInsufficient
}
// 下单时预扣库存,取消未支付订单时归还。
if product.Stock >= 0 {
product.Stock -= req.Quantity
if err := tx.Save(&product).Error; err != nil {
return err
}
}
orderNo, err := newMohongOrderNo()
if err != nil {
return err
}
images := decodeStringList(product.ImageURLs)
snap := productSnapshot{
ID: product.ID,
Title: product.Title,
CoverURL: product.CoverURL,
ImageURLs: images,
Description: product.Description,
PriceCent: product.PriceCent,
Unit: product.Unit,
QrcodeImageURL: product.QrcodeImageURL,
}
snapRaw, err := json.Marshal(snap)
if err != nil {
return err
}
amount := product.PriceCent * int64(req.Quantity)
order := model.MohongOrder{
OrderNo: orderNo,
UserID: userID,
ProductID: product.ID,
Quantity: req.Quantity,
UnitPriceCent: product.PriceCent,
AmountCent: amount,
Status: model.MohongOrderStatusPendingPayment,
ProductSnapshot: datatypes.JSON(snapRaw),
CopyText: "",
}
if err := tx.Create(&order).Error; err != nil {
return err
}
orderID := order.ID
if err := notification.Append(tx, notification.Entry{
UserID: userID,
Type: "order",
Title: "摸大红订单已创建",
Content: "订单已创建,请在有效时间内完成支付。",
BizType: "mohong_order",
BizID: &orderID,
}); err != nil {
return err
}
createdID = order.ID
return nil
})
if err != nil {
return nil, err
}
return r.FindOrderForUser(ctx, userID, createdID)
}
func (r *Repository) FindOrderForUser(ctx context.Context, userID, orderID uint64) (*OrderDTO, error) {
var row model.MohongOrder
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", orderID, userID).First(&row).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrOrderNotFound
}
return nil, err
}
return r.orderDTO(ctx, row, false)
}
func (r *Repository) AdminFindOrder(ctx context.Context, orderID uint64) (*OrderDTO, error) {
var row model.MohongOrder
if err := r.db.WithContext(ctx).First(&row, orderID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrOrderNotFound
}
return nil, err
}
return r.orderDTO(ctx, row, true)
}
func (r *Repository) ListOrdersForUser(ctx context.Context, userID uint64, query OrderListQuery) (*PaginatedResult, error) {
query.UserID = userID
return r.listOrders(ctx, query, false)
}
func (r *Repository) AdminListOrders(ctx context.Context, query OrderListQuery) (*PaginatedResult, error) {
return r.listOrders(ctx, query, true)
}
func (r *Repository) listOrders(ctx context.Context, query OrderListQuery, includeAdmin bool) (*PaginatedResult, error) {
if query.Page < 1 {
query.Page = 1
}
if query.PageSize < 1 {
query.PageSize = 20
}
if query.PageSize > 100 {
query.PageSize = 100
}
db := r.db.WithContext(ctx).Model(&model.MohongOrder{})
if query.UserID > 0 {
db = db.Where("user_id = ?", query.UserID)
}
if status := strings.TrimSpace(query.Status); status != "" {
db = db.Where("status = ?", status)
}
if kw := strings.TrimSpace(query.Keyword); kw != "" {
like := "%" + kw + "%"
db = db.Where("order_no LIKE ? OR CAST(id AS CHAR) = ?", like, kw)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, err
}
var rows []model.MohongOrder
if err := db.Order("id DESC").
Offset((query.Page - 1) * query.PageSize).
Limit(query.PageSize).
Find(&rows).Error; err != nil {
return nil, err
}
items := make([]OrderDTO, 0, len(rows))
for _, row := range rows {
dto, err := r.orderDTO(ctx, row, includeAdmin)
if err != nil {
return nil, err
}
items = append(items, *dto)
}
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
}
func (r *Repository) CancelOrder(ctx context.Context, userID, orderID uint64, reason string) (*OrderDTO, error) {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var order model.MohongOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ? AND user_id = ?", orderID, userID).
First(&order).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return ErrOrderNotFound
}
return err
}
if order.Status != model.MohongOrderStatusPendingPayment {
return ErrOrderCannotCancel
}
return r.cancelPendingOrderTx(tx, &order, firstNonEmpty(reason, "用户取消"))
})
if err != nil {
return nil, err
}
return r.FindOrderForUser(ctx, userID, orderID)
}
func (r *Repository) AdminCancelOrder(ctx context.Context, orderID uint64, reason string) (*OrderDTO, error) {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var order model.MohongOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return ErrOrderNotFound
}
return err
}
if order.Status != model.MohongOrderStatusPendingPayment && order.Status != model.MohongOrderStatusPaid {
return ErrOrderCannotCancel
}
if order.Status == model.MohongOrderStatusPendingPayment {
return r.cancelPendingOrderTx(tx, &order, firstNonEmpty(reason, "后台取消"))
}
// 已支付:仅标记取消(退款后续可接支付退款)。
now := time.Now()
order.Status = model.MohongOrderStatusCancelled
order.CancelledAt = &now
order.CancelReason = firstNonEmpty(reason, "后台取消")
return tx.Save(&order).Error
})
if err != nil {
return nil, err
}
return r.AdminFindOrder(ctx, orderID)
}
func (r *Repository) AdminCompleteOrder(ctx context.Context, orderID uint64, remark string) (*OrderDTO, error) {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var order model.MohongOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return ErrOrderNotFound
}
return err
}
if order.Status != model.MohongOrderStatusPaid {
return ErrOrderCannotComplete
}
now := time.Now()
order.Status = model.MohongOrderStatusCompleted
order.CompletedAt = &now
if strings.TrimSpace(remark) != "" {
order.AdminRemark = strings.TrimSpace(remark)
}
return tx.Save(&order).Error
})
if err != nil {
return nil, err
}
return r.AdminFindOrder(ctx, orderID)
}
// ConfirmPaidFromChannelTx 支付成功后推进摸大红订单:建群、发固定码、写复制文案。
func (r *Repository) ConfirmPaidFromChannelTx(tx *gorm.DB, orderID uint64) (uint64, error) {
var order model.MohongOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
return 0, err
}
if order.Status == model.MohongOrderStatusPaid ||
order.Status == model.MohongOrderStatusCompleted {
if order.ConversationID != nil {
return *order.ConversationID, nil
}
return 0, nil
}
if order.Status != model.MohongOrderStatusPendingPayment {
return 0, ErrOrderCannotPay
}
var user model.User
if err := tx.First(&user, order.UserID).Error; err != nil {
return 0, err
}
snap := decodeProductSnapshot(order.ProductSnapshot)
qrcodeURL := r.resolveQrcodeURL(tx, snap.QrcodeImageURL)
copyText := buildCopyText(r.loadCopyTemplate(tx), order, snap, user)
now := time.Now()
conv, err := ensureMohongOrderConversation(tx, order, user)
if err != nil {
return 0, err
}
welcome := r.loadWelcomeText(tx)
if err := chat.SendSystemMessageForTx(tx, conv.ID, welcome); err != nil {
return 0, err
}
if qrcodeURL != "" {
if err := chat.SendImageMessageForTx(tx, conv.ID, "👇 请扫码联系客服", qrcodeURL); err != nil {
return 0, err
}
} else {
if err := chat.SendSystemMessageForTx(tx, conv.ID, "固定二维码尚未配置,请将下方订单信息复制后联系客服。"); err != nil {
return 0, err
}
}
if copyText != "" {
if err := chat.SendSystemMessageForTx(tx, conv.ID, copyText+"\n\n(长按/复制后发送给客服)"); err != nil {
return 0, err
}
}
order.Status = model.MohongOrderStatusPaid
order.PaidAt = &now
order.QrcodeURLSnapshot = qrcodeURL
order.CopyText = copyText
order.ConversationID = &conv.ID
if err := tx.Save(&order).Error; err != nil {
return 0, err
}
orderIDCopy := order.ID
if err := notification.Append(tx, notification.Entry{
UserID: order.UserID,
Type: "order",
Title: "摸大红订单支付成功",
Content: "支付已完成,请在群内查看二维码与订单信息。",
BizType: "mohong_order",
BizID: &orderIDCopy,
}); err != nil {
return 0, err
}
return conv.ID, nil
}
func (r *Repository) NotifyNewConversation(conversationID uint64) {
if conversationID > 0 && r.chatNotifier != nil {
r.chatNotifier.NotifyNewConversation(conversationID)
}
}
func (r *Repository) cancelPendingOrderTx(tx *gorm.DB, order *model.MohongOrder, reason string) error {
// 归还预扣库存
if order.Quantity > 0 {
var product model.MohongProduct
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&product, order.ProductID).Error; err == nil {
if product.Stock >= 0 {
product.Stock += order.Quantity
if err := tx.Save(&product).Error; err != nil {
return err
}
}
}
}
now := time.Now()
order.Status = model.MohongOrderStatusCancelled
order.CancelledAt = &now
order.CancelReason = reason
return tx.Save(order).Error
}
func (r *Repository) orderDTO(ctx context.Context, row model.MohongOrder, includeAdmin bool) (*OrderDTO, error) {
snap := decodeProductSnapshot(row.ProductSnapshot)
var nickname, phone string
var user model.User
if err := r.db.WithContext(ctx).Select("id", "nickname", "phone").First(&user, row.UserID).Error; err == nil {
nickname = user.Nickname
phone = user.Phone
}
dto := toOrderDTO(row, snap, nickname, phone, includeAdmin)
return &dto, nil
}
func ensureMohongOrderConversation(tx *gorm.DB, order model.MohongOrder, user model.User) (*model.ChatConversation, error) {
var existing model.ChatConversation
err := tx.Where("mohong_order_id = ?", order.ID).First(&existing).Error
if err == nil {
return &existing, nil
}
if err != gorm.ErrRecordNotFound {
return nil, err
}
now := time.Now()
title := "摸大红 " + order.OrderNo
if name := strings.TrimSpace(user.Nickname); name != "" {
title = "摸大红-" + name
}
conversation := model.ChatConversation{
MohongOrderID: &order.ID,
Type: ConversationTypeMohongOrder,
Title: title,
Status: "active",
}
if err := tx.Create(&conversation).Error; err != nil {
return nil, err
}
participants := []model.ChatParticipant{
{
ConversationID: conversation.ID,
ParticipantType: "user",
ParticipantID: order.UserID,
Role: "buyer",
JoinedAt: now,
LastReadAt: &now,
},
}
supportID, err := supportgroup.PickSupportAdmin(tx, supportgroup.GroupCodeRenterHandoff)
if err != nil {
return nil, err
}
if supportID <= 0 {
supportID = chat.DefaultSupportAdminID(tx)
}
if supportID > 0 {
participants = append(participants, model.ChatParticipant{
ConversationID: conversation.ID,
ParticipantType: "admin",
ParticipantID: supportID,
Role: "support",
JoinedAt: now,
})
}
for _, p := range participants {
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&p).Error; err != nil {
return nil, err
}
}
return &conversation, nil
}
func buildCopyText(template string, order model.MohongOrder, snap productSnapshot, user model.User) string {
if strings.TrimSpace(template) == "" {
template = defaultOrderCopyTemplate
}
buyerName := strings.TrimSpace(user.Nickname)
if buyerName == "" {
buyerName = "用户"
}
replacer := strings.NewReplacer(
"{{order_no}}", order.OrderNo,
"{{created_at}}", timeutil.ShanghaiNow().Format("2006-01-02 15:04:05"),
"{{product_title}}", snap.Title,
"{{quantity}}", fmt.Sprintf("%d", order.Quantity),
"{{amount}}", money.FormatWithSymbol(order.AmountCent),
"{{buyer_name}}", buyerName,
"{{buyer_phone}}", maskPhone(user.Phone),
"{{unit}}", snap.Unit,
)
// 下单时间用订单创建时间更准确
created := order.CreatedAt
if !created.IsZero() {
replacer = strings.NewReplacer(
"{{order_no}}", order.OrderNo,
"{{created_at}}", created.In(timeutil.ShanghaiLocation()).Format("2006-01-02 15:04:05"),
"{{product_title}}", snap.Title,
"{{quantity}}", fmt.Sprintf("%d", order.Quantity),
"{{amount}}", money.FormatWithSymbol(order.AmountCent),
"{{buyer_name}}", buyerName,
"{{buyer_phone}}", maskPhone(user.Phone),
"{{unit}}", snap.Unit,
)
}
return replacer.Replace(template)
}
func newMohongOrderNo() (string, error) {
var b [4]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return fmt.Sprintf("MH%s%s", time.Now().Format("20060102150405"), strings.ToUpper(hex.EncodeToString(b[:]))), nil
}
@@ -0,0 +1,132 @@
package mohong
import (
"encoding/json"
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/pkg/money"
)
func toProductDTO(row model.MohongProduct, includeAdminFields bool) ProductDTO {
images := decodeStringList(row.ImageURLs)
dto := ProductDTO{
ID: row.ID,
CategoryID: row.CategoryID,
Title: row.Title,
CoverURL: row.CoverURL,
ImageURLs: images,
Description: row.Description,
PriceCent: row.PriceCent,
Price: money.Format(row.PriceCent),
OriginalPriceCent: row.OriginalPriceCent,
Unit: row.Unit,
Stock: row.Stock,
SortOrder: row.SortOrder,
Status: row.Status,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if row.OriginalPriceCent > 0 {
dto.OriginalPrice = money.Format(row.OriginalPriceCent)
}
if includeAdminFields {
dto.QrcodeImageURL = row.QrcodeImageURL
}
return dto
}
func toProductDTOWithCategory(row model.MohongProduct, categoryName string, includeAdminFields bool) ProductDTO {
dto := toProductDTO(row, includeAdminFields)
dto.CategoryName = categoryName
return dto
}
func toOrderDTO(row model.MohongOrder, snap productSnapshot, buyerNickname, buyerPhone string, includeAdmin bool) OrderDTO {
dto := OrderDTO{
ID: row.ID,
OrderNo: row.OrderNo,
UserID: row.UserID,
ProductID: row.ProductID,
Quantity: row.Quantity,
UnitPriceCent: row.UnitPriceCent,
UnitPrice: money.Format(row.UnitPriceCent),
AmountCent: row.AmountCent,
Amount: money.Format(row.AmountCent),
Status: row.Status,
ProductTitle: snap.Title,
ProductCoverURL: snap.CoverURL,
ProductUnit: snap.Unit,
QrcodeURLSnapshot: row.QrcodeURLSnapshot,
CopyText: row.CopyText,
ConversationID: row.ConversationID,
CancelReason: row.CancelReason,
PaidAt: row.PaidAt,
CompletedAt: row.CompletedAt,
CancelledAt: row.CancelledAt,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if includeAdmin {
dto.BuyerNickname = buyerNickname
dto.BuyerPhone = maskPhone(buyerPhone)
dto.AdminRemark = row.AdminRemark
} else {
dto.BuyerNickname = buyerNickname
dto.BuyerPhone = maskPhone(buyerPhone)
}
return dto
}
func decodeStringList(raw []byte) []string {
if len(raw) == 0 {
return []string{}
}
var list []string
if err := json.Unmarshal(raw, &list); err != nil {
return []string{}
}
out := make([]string, 0, len(list))
for _, item := range list {
item = strings.TrimSpace(item)
if item != "" {
out = append(out, item)
}
}
return out
}
func encodeStringList(list []string) []byte {
clean := make([]string, 0, len(list))
for _, item := range list {
item = strings.TrimSpace(item)
if item != "" {
clean = append(clean, item)
}
}
if len(clean) == 0 {
return []byte("[]")
}
raw, err := json.Marshal(clean)
if err != nil {
return []byte("[]")
}
return raw
}
func decodeProductSnapshot(raw []byte) productSnapshot {
var snap productSnapshot
if len(raw) == 0 {
return snap
}
_ = json.Unmarshal(raw, &snap)
return snap
}
func maskPhone(phone string) string {
phone = strings.TrimSpace(phone)
if len(phone) < 7 {
return phone
}
return phone[:3] + "****" + phone[len(phone)-4:]
}
@@ -0,0 +1,303 @@
package mohong
import (
"context"
"strings"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func (r *Repository) ListPublicProducts(ctx context.Context, query ProductListQuery) (*PaginatedResult, error) {
query = normalizePage(query)
db := r.db.WithContext(ctx).Model(&model.MohongProduct{}).Where("status = ?", model.MohongProductStatusOnSale)
if query.CategoryID > 0 {
// 多对多分类 + 主分类兜底
db = db.Where(
`(id IN (SELECT product_id FROM mohong_product_categories WHERE category_id = ?) OR category_id = ?)`,
query.CategoryID, query.CategoryID,
)
}
if kw := strings.TrimSpace(query.Keyword); kw != "" {
like := "%" + kw + "%"
db = db.Where("(title LIKE ? OR description LIKE ?)", like, like)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, err
}
var rows []model.MohongProduct
if err := db.Order("sort_order DESC, id DESC").
Offset((query.Page - 1) * query.PageSize).
Limit(query.PageSize).
Find(&rows).Error; err != nil {
return nil, err
}
return r.productPageDTO(ctx, rows, total, query, false)
}
func (r *Repository) FindPublicProduct(ctx context.Context, id uint64) (*ProductDTO, error) {
var row model.MohongProduct
if err := r.db.WithContext(ctx).
Where("id = ? AND status = ?", id, model.MohongProductStatusOnSale).
First(&row).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrProductNotFound
}
return nil, err
}
name := ""
if row.CategoryID != nil {
name = r.loadCategoryNameMap(ctx, []uint64{*row.CategoryID})[*row.CategoryID]
}
dto := toProductDTOWithCategory(row, name, false)
return &dto, nil
}
func (r *Repository) AdminListProducts(ctx context.Context, query ProductListQuery) (*PaginatedResult, error) {
query = normalizePage(query)
db := r.db.WithContext(ctx).Model(&model.MohongProduct{})
if status := strings.TrimSpace(query.Status); status != "" {
db = db.Where("status = ?", status)
}
if query.CategoryID > 0 {
db = db.Where(
`(id IN (SELECT product_id FROM mohong_product_categories WHERE category_id = ?) OR category_id = ?)`,
query.CategoryID, query.CategoryID,
)
}
if kw := strings.TrimSpace(query.Keyword); kw != "" {
like := "%" + kw + "%"
db = db.Where("(title LIKE ? OR description LIKE ?)", like, like)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, err
}
var rows []model.MohongProduct
if err := db.Order("sort_order DESC, id DESC").
Offset((query.Page - 1) * query.PageSize).
Limit(query.PageSize).
Find(&rows).Error; err != nil {
return nil, err
}
return r.productPageDTO(ctx, rows, total, query, true)
}
func (r *Repository) productPageDTO(ctx context.Context, rows []model.MohongProduct, total int64, query ProductListQuery, admin bool) (*PaginatedResult, error) {
ids := make([]uint64, 0, len(rows))
for _, row := range rows {
if row.CategoryID != nil {
ids = append(ids, *row.CategoryID)
}
}
names := r.loadCategoryNameMap(ctx, ids)
items := make([]ProductDTO, 0, len(rows))
for _, row := range rows {
name := ""
if row.CategoryID != nil {
name = names[*row.CategoryID]
}
items = append(items, toProductDTOWithCategory(row, name, admin))
}
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
}
func (r *Repository) AdminFindProduct(ctx context.Context, id uint64) (*ProductDTO, error) {
var row model.MohongProduct
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrProductNotFound
}
return nil, err
}
name := ""
if row.CategoryID != nil {
name = r.loadCategoryNameMap(ctx, []uint64{*row.CategoryID})[*row.CategoryID]
}
dto := toProductDTOWithCategory(row, name, true)
return &dto, nil
}
func (r *Repository) CreateProduct(ctx context.Context, adminID uint64, req CreateProductRequest) (*ProductDTO, error) {
status := strings.TrimSpace(req.Status)
if status == "" {
status = model.MohongProductStatusDraft
}
if !isValidProductStatus(status) {
return nil, ErrInvalidRequest
}
stock := -1
if req.Stock != nil {
stock = *req.Stock
}
unit := strings.TrimSpace(req.Unit)
if unit == "" {
unit = "份"
}
row := model.MohongProduct{
CategoryID: normalizeCategoryID(req.CategoryID),
Title: strings.TrimSpace(req.Title),
CoverURL: strings.TrimSpace(req.CoverURL),
ImageURLs: encodeStringList(req.ImageURLs),
Description: strings.TrimSpace(req.Description),
PriceCent: req.PriceCent,
OriginalPriceCent: maxInt64(req.OriginalPriceCent, 0),
Unit: unit,
Stock: stock,
SortOrder: req.SortOrder,
Status: status,
QrcodeImageURL: strings.TrimSpace(req.QrcodeImageURL),
CreatedBy: &adminID,
}
if row.Title == "" || row.PriceCent <= 0 {
return nil, ErrInvalidRequest
}
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&row).Error; err != nil {
return err
}
return syncProductCategories(tx, row.ID, row.CategoryID)
}); err != nil {
return nil, err
}
return r.AdminFindProduct(ctx, row.ID)
}
func (r *Repository) UpdateProduct(ctx context.Context, id uint64, req UpdateProductRequest) (*ProductDTO, error) {
var row model.MohongProduct
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrProductNotFound
}
return nil, err
}
updates := map[string]any{}
if req.ClearCategory {
updates["category_id"] = nil
} else if req.CategoryID != nil {
updates["category_id"] = normalizeCategoryID(req.CategoryID)
}
if req.Title != nil {
title := strings.TrimSpace(*req.Title)
if title == "" {
return nil, ErrInvalidRequest
}
updates["title"] = title
}
if req.CoverURL != nil {
updates["cover_url"] = strings.TrimSpace(*req.CoverURL)
}
if req.ImageURLs != nil {
updates["image_urls"] = encodeStringList(req.ImageURLs)
}
if req.Description != nil {
updates["description"] = strings.TrimSpace(*req.Description)
}
if req.PriceCent != nil {
if *req.PriceCent <= 0 {
return nil, ErrInvalidRequest
}
updates["price_cent"] = *req.PriceCent
}
if req.OriginalPriceCent != nil {
updates["original_price_cent"] = maxInt64(*req.OriginalPriceCent, 0)
}
if req.Unit != nil {
unit := strings.TrimSpace(*req.Unit)
if unit == "" {
unit = "份"
}
updates["unit"] = unit
}
if req.Stock != nil {
updates["stock"] = *req.Stock
}
if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder
}
if req.Status != nil {
status := strings.TrimSpace(*req.Status)
if !isValidProductStatus(status) {
return nil, ErrInvalidRequest
}
updates["status"] = status
}
if req.QrcodeImageURL != nil {
updates["qrcode_image_url"] = strings.TrimSpace(*req.QrcodeImageURL)
}
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if len(updates) > 0 {
if err := tx.Model(&row).Updates(updates).Error; err != nil {
return err
}
}
// 刷新主分类后同步关联表(至少保证主分类在关联里)
var latest model.MohongProduct
if err := tx.First(&latest, id).Error; err != nil {
return err
}
return syncProductCategories(tx, latest.ID, latest.CategoryID)
}); err != nil {
return nil, err
}
return r.AdminFindProduct(ctx, id)
}
// syncProductCategories 保证主分类写入多对多表;不删除其它已有关联(种子数据可挂多分类)。
func syncProductCategories(tx *gorm.DB, productID uint64, primary *uint64) error {
if primary == nil || *primary == 0 {
return nil
}
rel := model.MohongProductCategory{ProductID: productID, CategoryID: *primary}
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&rel).Error
}
func (r *Repository) DeleteProduct(ctx context.Context, id uint64) error {
res := r.db.WithContext(ctx).Delete(&model.MohongProduct{}, id)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrProductNotFound
}
return nil
}
func isValidProductStatus(status string) bool {
switch status {
case model.MohongProductStatusDraft, model.MohongProductStatusOnSale, model.MohongProductStatusOffSale:
return true
default:
return false
}
}
func normalizePage(query ProductListQuery) ProductListQuery {
if query.Page < 1 {
query.Page = 1
}
if query.PageSize < 1 {
query.PageSize = 20
}
if query.PageSize > 100 {
query.PageSize = 100
}
return query
}
func maxInt64(a, b int64) int64 {
if a > b {
return a
}
return b
}
func normalizeCategoryID(id *uint64) *uint64 {
if id == nil || *id == 0 {
return nil
}
return id
}
@@ -0,0 +1,19 @@
package mohong
import "gorm.io/gorm"
// ChatNotifier 会话创建后的异步通知接口。
type ChatNotifier interface {
NotifyNewConversation(conversationID uint64)
}
// Repository 摸大红数据访问。
type Repository struct {
db *gorm.DB
chatNotifier ChatNotifier
}
// NewRepository 创建仓库。
func NewRepository(db *gorm.DB, chatNotifier ChatNotifier) *Repository {
return &Repository{db: db, chatNotifier: chatNotifier}
}
+173
View File
@@ -0,0 +1,173 @@
package mohong
import "context"
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) ListPublicCategories(ctx context.Context) ([]CategoryDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListPublicCategories(ctx)
}
func (s *Service) AdminListCategories(ctx context.Context) ([]CategoryDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminListCategories(ctx)
}
func (s *Service) CreateCategory(ctx context.Context, req CreateCategoryRequest) (*CategoryDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.CreateCategory(ctx, req)
}
func (s *Service) UpdateCategory(ctx context.Context, id uint64, req UpdateCategoryRequest) (*CategoryDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.UpdateCategory(ctx, id, req)
}
func (s *Service) DeleteCategory(ctx context.Context, id uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.DeleteCategory(ctx, id)
}
func (s *Service) ListPublicProducts(ctx context.Context, query ProductListQuery) (*PaginatedResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListPublicProducts(ctx, query)
}
func (s *Service) FindPublicProduct(ctx context.Context, id uint64) (*ProductDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.FindPublicProduct(ctx, id)
}
func (s *Service) AdminListProducts(ctx context.Context, query ProductListQuery) (*PaginatedResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminListProducts(ctx, query)
}
func (s *Service) AdminFindProduct(ctx context.Context, id uint64) (*ProductDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminFindProduct(ctx, id)
}
func (s *Service) CreateProduct(ctx context.Context, adminID uint64, req CreateProductRequest) (*ProductDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.CreateProduct(ctx, adminID, req)
}
func (s *Service) UpdateProduct(ctx context.Context, id uint64, req UpdateProductRequest) (*ProductDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.UpdateProduct(ctx, id, req)
}
func (s *Service) DeleteProduct(ctx context.Context, id uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.DeleteProduct(ctx, id)
}
func (s *Service) CreateOrder(ctx context.Context, userID uint64, req CreateOrderRequest) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.CreateOrder(ctx, userID, req)
}
func (s *Service) FindOrderForUser(ctx context.Context, userID, orderID uint64) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.FindOrderForUser(ctx, userID, orderID)
}
func (s *Service) ListOrdersForUser(ctx context.Context, userID uint64, query OrderListQuery) (*PaginatedResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListOrdersForUser(ctx, userID, query)
}
func (s *Service) CancelOrder(ctx context.Context, userID, orderID uint64, reason string) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.CancelOrder(ctx, userID, orderID, reason)
}
func (s *Service) AdminListOrders(ctx context.Context, query OrderListQuery) (*PaginatedResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminListOrders(ctx, query)
}
func (s *Service) AdminFindOrder(ctx context.Context, orderID uint64) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminFindOrder(ctx, orderID)
}
func (s *Service) AdminCompleteOrder(ctx context.Context, orderID uint64, remark string) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminCompleteOrder(ctx, orderID, remark)
}
func (s *Service) AdminCancelOrder(ctx context.Context, orderID uint64, reason string) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.AdminCancelOrder(ctx, orderID, reason)
}
func (s *Service) GetConfig(ctx context.Context) (*ConfigDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.GetConfig(ctx)
}
func (s *Service) UpdateConfig(ctx context.Context, req UpdateConfigRequest) (*ConfigDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.UpdateConfig(ctx, req)
}
// Repo 暴露给支付模块注入。
func (s *Service) Repo() *Repository {
if s == nil {
return nil
}
return s.repo
}
@@ -45,8 +45,21 @@ func isOrderPaymentTerminalStatus(status string) bool {
}
func (r *Repository) confirmPaid(ctx context.Context, payment *model.PaymentOrder, status string, paidAt time.Time, raw map[string]string, source string) error {
var newConvID uint64
var notifyFn func(uint64)
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if payment.OrderID != 0 {
switch payment.BizType {
case "mohong_pay":
if r.mohongRepo == nil {
return ErrDependencyUnavailable
}
convID, err := r.mohongRepo.ConfirmPaidFromChannelTx(tx, payment.OrderID)
if err != nil {
return err
}
newConvID = convID
notifyFn = r.mohongRepo.NotifyNewConversation
default:
if r.orderRepo == nil {
return ErrDependencyUnavailable
}
@@ -55,6 +68,8 @@ func (r *Repository) confirmPaid(ctx context.Context, payment *model.PaymentOrde
return err
}
newConvID = convID
notifyFn = r.orderRepo.NotifyNewConversation
}
}
var latest model.PaymentOrder
@@ -75,8 +90,8 @@ func (r *Repository) confirmPaid(ctx context.Context, payment *model.PaymentOrde
if err != nil {
return err
}
if newConvID > 0 && r.orderRepo != nil {
r.orderRepo.NotifyNewConversation(newConvID)
if newConvID > 0 && notifyFn != nil {
notifyFn(newConvID)
}
if latest, err := r.findPaymentByID(ctx, payment.ID); err == nil {
if runtimeConfig, err := r.runtimeConfigForPayment(ctx, latest); err == nil {
@@ -91,6 +91,26 @@ func (h *Handler) Start(c *gin.Context) {
response.OK(c, item)
}
func (h *Handler) StartMohong(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
orderID, ok := parseID(c)
if !ok {
return
}
var req StartPaymentRequest
_ = c.ShouldBindJSON(&req)
item, err := h.service.StartMohong(c.Request.Context(), userID, orderID, req, c.ClientIP())
if err != nil {
writePaymentError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) Query(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
@@ -109,6 +129,24 @@ func (h *Handler) Query(c *gin.Context) {
response.OK(c, item)
}
func (h *Handler) QueryMohong(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
orderID, ok := parseID(c)
if !ok {
return
}
item, err := h.service.QueryMohong(c.Request.Context(), userID, orderID)
if err != nil {
writePaymentError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) QueryRefundStatus(c *gin.Context) {
orderID, ok := parseID(c)
if !ok {
@@ -0,0 +1,245 @@
package payment
import (
"context"
"time"
"hfb_sys/backend/internal/model"
"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const bizTypeMohongPay = "mohong_pay"
// StartMohong 发起摸大红订单支付。
func (r *Repository) StartMohong(ctx context.Context, userID uint64, orderID uint64, req StartPaymentRequest, clientIP string) (*PaymentDTO, error) {
req.PayWay = normalizePayWay(req.PayWay)
defaultConfig, err := r.defaultRuntimeConfig(ctx, req.PayWay)
if err != nil {
return nil, ErrPaymentUnavailable
}
payment, orderRow, err := r.prepareMohongPayment(ctx, userID, orderID, req, *defaultConfig)
if err != nil {
return nil, err
}
runtimeConfig, err := r.runtimeConfigForPayment(ctx, payment)
if err != nil {
return nil, ErrPaymentUnavailable
}
if payment.Status == "paid" {
r.recordConfigUsage(ctx, runtimeConfig, payment)
dto := toDTO(*payment)
return &dto, nil
}
if runtimeConfig.isMockMode() {
if err := r.confirmPaid(ctx, payment, "2", time.Now(), map[string]string{
"mock": "true",
"third_order_id": payment.ThirdOrderID,
"leshua_order_id": payment.ProviderOrderID,
"status": "2",
}, channelSourceMock); err != nil {
return nil, err
}
latest, err := r.findPaymentByID(ctx, payment.ID)
if err != nil {
return nil, err
}
r.recordConfigUsage(ctx, runtimeConfig, latest)
dto := toDTO(*latest)
return &dto, nil
}
if payment.Status == "paying" && (payment.TDCode != "" || payment.JSPayURL != "" || payment.JSPayInfo != "") {
r.recordConfigUsage(ctx, runtimeConfig, payment)
dto := toDTO(*payment)
return &dto, nil
}
if runtimeConfig.Channel == nil {
_ = r.markPaymentFailed(ctx, payment.ID, nil, "payment channel unavailable")
return nil, ErrPaymentUnavailable
}
r.log().Info("mohong payment start", paymentLogFields(ctx, appendFields(
paymentOrderFields(payment),
runtimeConfigFields(runtimeConfig),
)...,
)...)
resp, err := runtimeConfig.Channel.CreatePayment(ctx, channelCreatePaymentRequest{
ThirdOrderID: payment.ThirdOrderID,
AmountCent: payment.AmountCent,
PayWay: payment.PayWay,
JSPayFlag: payment.JSPayFlag,
NotifyURL: runtimeConfig.NotifyURL,
JumpURL: runtimeConfig.JumpURL,
ClientIP: clientIP,
Body: "摸大红订单 " + orderRow.OrderNo,
Attach: orderRow.OrderNo,
})
if err != nil {
_ = r.markPaymentFailed(ctx, payment.ID, nil, err.Error())
r.log().Warn("mohong payment request failed", paymentLogFields(ctx, appendFields(
paymentOrderFields(payment),
runtimeConfigFields(runtimeConfig),
[]zap.Field{zap.Error(err)},
)...,
)...)
return nil, err
}
if !resp.OK {
_ = r.markPaymentFailed(ctx, payment.ID, resp.Raw, resp.ErrorMessage)
return nil, ErrPaymentUnavailable
}
if err := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
"status": "paying",
"provider_order_id": resp.ProviderOrderID,
"pay_way": firstNonEmpty(resp.PayWay, payment.PayWay),
"td_code": resp.TDCode,
"jspay_url": resp.JSPayURL,
"jspay_info": resp.JSPayInfo,
"raw_request": jsonMap(resp.RawRequest),
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceCreate)),
}).Error; err != nil {
return nil, err
}
latest, err := r.findPaymentByID(ctx, payment.ID)
if err != nil {
return nil, err
}
r.recordConfigUsage(ctx, runtimeConfig, latest)
dto := toDTO(*latest)
return &dto, nil
}
func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, orderID uint64, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (*model.PaymentOrder, *model.MohongOrder, error) {
var paymentID uint64
var orderRow model.MohongOrder
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var row model.MohongOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ? AND user_id = ?", orderID, userID).
First(&row).Error; err != nil {
return err
}
if row.Status != model.MohongOrderStatusPendingPayment {
return ErrPaymentCannotStart
}
if row.AmountCent <= 0 {
return ErrPaymentCannotStart
}
var existing model.PaymentOrder
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("order_id = ? AND biz_type = ?", row.ID, bizTypeMohongPay).
Order("id DESC").
First(&existing).Error
if err == nil {
if canReuseOrderPayment(existing, runtimeConfig) {
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
existing.AmountCent = row.AmountCent
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
if existing.Provider == "mock" && existing.ProviderOrderID == "" {
existing.ProviderOrderID = "MOCK" + existing.ThirdOrderID
}
if err := tx.Save(&existing).Error; err != nil {
return err
}
paymentID = existing.ID
orderRow = row
return nil
}
} else if err != gorm.ErrRecordNotFound {
return err
}
payment, err := newMohongPayment(row, req, runtimeConfig)
if err != nil {
return err
}
if err := tx.Create(&payment).Error; err != nil {
return err
}
paymentID = payment.ID
orderRow = row
return nil
})
if err != nil {
return nil, nil, err
}
payment, err := r.findPaymentByID(ctx, paymentID)
if err != nil {
return nil, nil, err
}
return payment, &orderRow, nil
}
func newMohongPayment(row model.MohongOrder, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (model.PaymentOrder, error) {
paymentNo, err := newPaymentNo()
if err != nil {
return model.PaymentOrder{}, err
}
payment := model.PaymentOrder{
PaymentNo: paymentNo,
OrderID: row.ID,
OrderNo: row.OrderNo,
UserID: row.UserID,
PaymentConfigID: runtimeConfig.ID,
Provider: runtimeConfig.Provider,
MerchantID: runtimeConfig.MerchantID,
ThirdOrderID: paymentNo,
ProviderOrderID: "",
PayWay: firstNonEmpty(req.PayWay, runtimeConfig.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, runtimeConfig.JSPayFlag, "2"),
AmountCent: row.AmountCent,
BizType: bizTypeMohongPay,
Status: "created",
}
if runtimeConfig.isMockMode() {
payment.ProviderOrderID = "MOCK" + paymentNo
payment.TDCode = "mock://payment/pay/" + paymentNo
}
return payment, nil
}
// QueryMohong 查询摸大红订单支付状态。
func (r *Repository) QueryMohong(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
var payment model.PaymentOrder
if err := r.db.WithContext(ctx).
Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, bizTypeMohongPay).
Order("id DESC").
First(&payment).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrPaymentNotFound
}
return nil, err
}
if isOrderPaymentTerminalStatus(payment.Status) {
dto := toDTO(payment)
return &dto, nil
}
runtimeConfig, err := r.runtimeConfigForPayment(ctx, &payment)
if err != nil {
return nil, ErrPaymentUnavailable
}
if runtimeConfig.isMockMode() {
dto := toDTO(payment)
return &dto, nil
}
if runtimeConfig.Channel == nil {
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.QueryPayment(ctx, payment.ThirdOrderID, payment.ProviderOrderID)
if err != nil {
return nil, err
}
if err := r.applyChannelStatus(ctx, &payment, resp.Status, resp.PayTime, resp.Raw, channelSourceQuery); err != nil {
return nil, err
}
latest, err := r.findPaymentByID(ctx, payment.ID)
if err != nil {
return nil, err
}
dto := toDTO(*latest)
return &dto, nil
}
+15 -1
View File
@@ -13,10 +13,17 @@ import (
"gorm.io/gorm"
)
// MohongOrderConfirmer 摸大红订单支付确认接口,避免 payment 与 mohong 循环依赖。
type MohongOrderConfirmer interface {
ConfirmPaidFromChannelTx(tx *gorm.DB, orderID uint64) (uint64, error)
NotifyNewConversation(conversationID uint64)
}
type Repository struct {
db *gorm.DB
configRepo *paymentconfig.Repository
orderRepo *order.Repository
mohongRepo MohongOrderConfirmer
logger *zap.Logger
}
@@ -82,6 +89,13 @@ func WithLogger(logger *zap.Logger) RepositoryOption {
}
}
// WithMohongRepo 注入摸大红订单确认器。
func WithMohongRepo(repo MohongOrderConfirmer) RepositoryOption {
return func(r *Repository) {
r.mohongRepo = repo
}
}
func (r *Repository) log() *zap.Logger {
if r == nil || r.logger == nil {
return zap.NewNop()
@@ -237,7 +251,7 @@ func (r *Repository) recordConfigUsage(ctx context.Context, runtimeConfig *runti
if r.configRepo == nil || runtimeConfig == nil || payment == nil || runtimeConfig.ID == 0 {
return
}
if payment.BizType != "order_pay" || payment.Status != "paid" {
if (payment.BizType != "order_pay" && payment.BizType != "mohong_pay") || payment.Status != "paid" {
return
}
if err := r.configRepo.RecordUsage(ctx, runtimeConfig.ID, payment.ID, runtimeConfig.Provider, runtimeConfig.MerchantID, payment.AmountCent, payment.BizType); err != nil {
@@ -32,6 +32,16 @@ func (s *Service) Start(ctx context.Context, userID uint64, orderID uint64, req
return s.repo.Start(ctx, userID, orderID, req, clientIP)
}
func (s *Service) StartMohong(ctx context.Context, userID uint64, orderID uint64, req StartPaymentRequest, clientIP string) (*PaymentDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if userID == 0 || orderID == 0 {
return nil, ErrPaymentCannotStart
}
return s.repo.StartMohong(ctx, userID, orderID, req, clientIP)
}
func (s *Service) Query(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
@@ -42,6 +52,16 @@ func (s *Service) Query(ctx context.Context, userID uint64, orderID uint64) (*Pa
return s.repo.Query(ctx, userID, orderID)
}
func (s *Service) QueryMohong(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if userID == 0 || orderID == 0 {
return nil, ErrPaymentNotFound
}
return s.repo.QueryMohong(ctx, userID, orderID)
}
func (s *Service) HandleLeshuaNotify(ctx context.Context, params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
+55 -1
View File
@@ -24,6 +24,7 @@ import (
"hfb_sys/backend/internal/modules/dispute"
filemodule "hfb_sys/backend/internal/modules/file"
"hfb_sys/backend/internal/modules/listing"
"hfb_sys/backend/internal/modules/mohong"
"hfb_sys/backend/internal/modules/notification"
"hfb_sys/backend/internal/modules/order"
"hfb_sys/backend/internal/modules/payment"
@@ -254,8 +255,21 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
paymentConfigHandler = paymentconfig.NewHandler(paymentConfigService)
}
var mohongRepo *mohong.Repository
var mohongService *mohong.Service
var mohongHandler *mohong.Handler
if deps.DB != nil {
paymentRepo = payment.NewRepository(deps.DB, paymentConfigRepo, orderRepo, payment.WithLogger(logger))
mohongRepo = mohong.NewRepository(deps.DB, chatRepo)
mohongService = mohong.NewService(mohongRepo)
mohongHandler = mohong.NewHandler(mohongService)
}
if deps.DB != nil {
paymentOpts := []payment.RepositoryOption{payment.WithLogger(logger)}
if mohongRepo != nil {
paymentOpts = append(paymentOpts, payment.WithMohongRepo(mohongRepo))
}
paymentRepo = payment.NewRepository(deps.DB, paymentConfigRepo, orderRepo, paymentOpts...)
}
paymentService := payment.NewService(paymentRepo)
paymentHandler := payment.NewHandler(paymentService, payment.WithHandlerLogger(logger))
@@ -414,6 +428,25 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
sellerPickupRoutes.GET("", pickupHandler.ListForSeller)
}
// 摸大红:商品公开,下单需登录+实名
if mohongHandler != nil {
mohongPublic := api.Group("/mohong")
{
mohongPublic.GET("/categories", mohongHandler.ListCategories)
mohongPublic.GET("/products", mohongHandler.ListProducts)
mohongPublic.GET("/products/:id", mohongHandler.GetProduct)
}
mohongAuth := api.Group("/mohong", requireAuth)
{
mohongAuth.POST("/orders", requireRealname, mohongHandler.CreateOrder)
mohongAuth.GET("/orders", mohongHandler.ListMyOrders)
mohongAuth.GET("/orders/:id", mohongHandler.GetMyOrder)
mohongAuth.POST("/orders/:id/cancel", mohongHandler.CancelMyOrder)
mohongAuth.POST("/orders/:id/start-payment", requireRealname, paymentHandler.StartMohong)
mohongAuth.GET("/orders/:id/query-payment", paymentHandler.QueryMohong)
}
}
orderRoutes := api.Group("/orders", requireAuth)
{
orderRoutes.POST("", requireRealname, orderHandler.Create)
@@ -565,6 +598,27 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
adminRoutes.POST("/listings/:id/reject", requirePerm("listing:reject"), listingHandler.Reject)
adminRoutes.POST("/listings/:id/offline", requirePerm("listing:offline"), listingHandler.AdminOffline)
adminRoutes.POST("/listings/:id/mark-abnormal", requirePerm("listing:offline"), listingHandler.AdminMarkAbnormal)
// 摸大红
if mohongHandler != nil {
// 商品编辑需要拉分类列表,故 GET 用 product_view
adminRoutes.GET("/mohong/categories", requirePerm("mohong:product_view"), mohongHandler.AdminListCategories)
adminRoutes.POST("/mohong/categories", requirePerm("mohong:category"), mohongHandler.AdminCreateCategory)
adminRoutes.PUT("/mohong/categories/:id", requirePerm("mohong:category"), mohongHandler.AdminUpdateCategory)
adminRoutes.DELETE("/mohong/categories/:id", requirePerm("mohong:category"), mohongHandler.AdminDeleteCategory)
adminRoutes.GET("/mohong/products", requirePerm("mohong:product_view"), mohongHandler.AdminListProducts)
adminRoutes.GET("/mohong/products/:id", requirePerm("mohong:product_view"), mohongHandler.AdminGetProduct)
adminRoutes.POST("/mohong/products", requirePerm("mohong:product_manage"), mohongHandler.AdminCreateProduct)
adminRoutes.PUT("/mohong/products/:id", requirePerm("mohong:product_manage"), mohongHandler.AdminUpdateProduct)
adminRoutes.DELETE("/mohong/products/:id", requirePerm("mohong:product_manage"), mohongHandler.AdminDeleteProduct)
adminRoutes.GET("/mohong/orders", requirePerm("mohong:order_view"), mohongHandler.AdminListOrders)
adminRoutes.GET("/mohong/orders/:id", requirePerm("mohong:order_view"), mohongHandler.AdminGetOrder)
adminRoutes.POST("/mohong/orders/:id/complete", requirePerm("mohong:order_manage"), mohongHandler.AdminCompleteOrder)
adminRoutes.POST("/mohong/orders/:id/cancel", requirePerm("mohong:order_manage"), mohongHandler.AdminCancelOrder)
adminRoutes.GET("/mohong/config", requirePerm("mohong:config"), mohongHandler.AdminGetConfig)
adminRoutes.PUT("/mohong/config", requirePerm("mohong:config"), mohongHandler.AdminUpdateConfig)
}
adminRoutes.GET("/disputes", requirePerm("dispute:view"), disputeHandler.AdminList)
adminRoutes.POST("/disputes/:id/arbitrate", requirePerm("dispute:arbitrate"), disputeHandler.AdminArbitrate)
adminRoutes.GET("/finance/dashboard", requirePerm("wallet:view"), adminFinanceHandler.Dashboard)
+125
View File
@@ -0,0 +1,125 @@
-- +goose Up
-- +goose StatementBegin
-- 摸大红商品表
CREATE TABLE IF NOT EXISTS mohong_products (
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(128) NOT NULL COMMENT '商品标题',
cover_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '封面图',
image_urls JSON NULL COMMENT '详情图列表',
description TEXT NOT NULL COMMENT '商品描述',
price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '售价(分)',
original_price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '原价(分,0表示不展示)',
unit VARCHAR(32) NOT NULL DEFAULT '' COMMENT '单位',
stock INT NOT NULL DEFAULT -1 COMMENT '库存,-1表示不限',
sort_order INT NOT NULL DEFAULT 0 COMMENT '排序,越大越靠前',
status VARCHAR(16) NOT NULL DEFAULT 'draft' COMMENT 'draft草稿 on_sale上架 off_sale下架',
qrcode_image_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '专属固定二维码,空则用全局默认',
created_by BIGINT UNSIGNED NULL COMMENT '创建管理员',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY idx_mohong_products_status_sort (status, sort_order, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='摸大红商品';
-- 摸大红订单表
CREATE TABLE IF NOT EXISTS mohong_orders (
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(64) NOT NULL COMMENT '订单号',
user_id BIGINT UNSIGNED NOT NULL COMMENT '下单用户',
product_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
quantity INT NOT NULL DEFAULT 1 COMMENT '数量',
unit_price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '下单单价快照(分)',
amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '应付总额(分)',
status VARCHAR(32) NOT NULL DEFAULT 'pending_payment' COMMENT 'pending_payment/paid/completed/cancelled/refunded',
product_snapshot JSON NULL COMMENT '商品快照',
qrcode_url_snapshot VARCHAR(512) NOT NULL DEFAULT '' COMMENT '支付时解析的二维码快照',
copy_text TEXT NOT NULL COMMENT '可复制订单文案',
conversation_id BIGINT UNSIGNED NULL COMMENT '订单群会话ID',
paid_at DATETIME NULL COMMENT '支付时间',
completed_at DATETIME NULL COMMENT '完成时间',
cancelled_at DATETIME NULL COMMENT '取消时间',
cancel_reason VARCHAR(255) NOT NULL DEFAULT '' COMMENT '取消原因',
admin_remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '后台备注',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_mohong_orders_order_no (order_no),
KEY idx_mohong_orders_user_status (user_id, status, id),
KEY idx_mohong_orders_product (product_id),
KEY idx_mohong_orders_status_created (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='摸大红订单';
-- 会话表增加摸大红订单关联
ALTER TABLE chat_conversations
ADD COLUMN mohong_order_id BIGINT UNSIGNED NULL COMMENT '摸大红订单ID' AFTER listing_id,
ADD UNIQUE KEY uk_chat_conversations_mohong_order_id (mohong_order_id);
-- 业务配置
INSERT INTO system_configs (`key`, `value`, description) VALUES
('mohong.default_qrcode_url', '', '摸大红全局默认固定二维码图片URL'),
('mohong.group_welcome_text', '订单已支付,请扫码联系客服,并将下方订单信息复制发送给客服。', '摸大红订单群欢迎语'),
('mohong.order_copy_template', '【摸大红订单】\n订单号:{{order_no}}\n下单时间:{{created_at}}\n商品:{{product_title}}\n数量:{{quantity}}\n金额:{{amount}}\n下单人:{{buyer_name}}{{buyer_phone}}', '摸大红订单一键复制文案模板')
ON DUPLICATE KEY UPDATE description = VALUES(description);
-- 权限
INSERT INTO permissions (code, name, resource, action) VALUES
('mohong:product_view', '查看摸大红商品', 'mohong', 'product_view'),
('mohong:product_manage', '管理摸大红商品', 'mohong', 'product_manage'),
('mohong:order_view', '查看摸大红订单', 'mohong', 'order_view'),
('mohong:order_manage', '管理摸大红订单', 'mohong', 'order_manage'),
('mohong:config', '摸大红业务配置', 'mohong', 'config')
ON DUPLICATE KEY UPDATE
name = VALUES(name),
resource = VALUES(resource),
action = VALUES(action);
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
'mohong:product_view', 'mohong:product_manage',
'mohong:order_view', 'mohong:order_manage',
'mohong:config'
)
WHERE r.code = 'super_admin';
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
'mohong:product_view', 'mohong:order_view', 'mohong:order_manage'
)
WHERE r.code = 'cs';
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code IN (
'mohong:product_view', 'mohong:product_manage',
'mohong:order_view', 'mohong:order_manage',
'mohong:config'
);
DELETE FROM permissions WHERE code IN (
'mohong:product_view', 'mohong:product_manage',
'mohong:order_view', 'mohong:order_manage',
'mohong:config'
);
DELETE FROM system_configs WHERE `key` IN (
'mohong.default_qrcode_url',
'mohong.group_welcome_text',
'mohong.order_copy_template'
);
ALTER TABLE chat_conversations
DROP INDEX uk_chat_conversations_mohong_order_id,
DROP COLUMN mohong_order_id;
DROP TABLE IF EXISTS mohong_orders;
DROP TABLE IF EXISTS mohong_products;
-- +goose StatementEnd
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
{
"source": "/Users/yml/Desktop/抓包/大红抓包 2.har",
"note": "seed embedded in migrations/000029_mohong_categories_and_seed.sql",
"unique_products": 92,
"relations": 133,
"categories": [
{
"name": "炫彩",
"count": 33
},
{
"name": "任务",
"count": 4
},
{
"name": "AW",
"count": 2
},
{
"name": "大红",
"count": 52
},
{
"name": "四格大红",
"count": 8
},
{
"name": "六格大红",
"count": 11
},
{
"name": "九格大红",
"count": 14
},
{
"name": "十二格大红",
"count": 8
},
{
"name": "哈弗币",
"count": 1
}
]
}
@@ -0,0 +1,184 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import {
createAdminMohongCategory,
deleteAdminMohongCategory,
fetchAdminMohongCategories,
updateAdminMohongCategory,
type MohongCategory,
} from '@/features/mohong/api/mohong'
import { readError } from '@/shared/utils/error'
const loading = ref(false)
const items = ref<MohongCategory[]>([])
const dialogVisible = ref(false)
const saving = ref(false)
const editingId = ref<number | null>(null)
const form = reactive({
name: '',
code: '',
sort_order: 0,
status: 'enabled',
})
onMounted(load)
async function load() {
loading.value = true
try {
items.value = await fetchAdminMohongCategories()
} catch (error) {
ElMessage.error(readError(error, '加载失败'))
} finally {
loading.value = false
}
}
function openCreate() {
editingId.value = null
Object.assign(form, { name: '', code: '', sort_order: 0, status: 'enabled' })
dialogVisible.value = true
}
function openEdit(item: MohongCategory) {
editingId.value = item.id
Object.assign(form, {
name: item.name,
code: item.code || '',
sort_order: item.sort_order,
status: item.status,
})
dialogVisible.value = true
}
async function handleSave() {
if (!form.name.trim()) {
ElMessage.warning('请填写分类名称')
return
}
saving.value = true
try {
if (editingId.value) {
await updateAdminMohongCategory(editingId.value, { ...form })
ElMessage.success('已更新')
} else {
await createAdminMohongCategory({ ...form })
ElMessage.success('已创建')
}
dialogVisible.value = false
await load()
} catch (error) {
ElMessage.error(readError(error, '保存失败'))
} finally {
saving.value = false
}
}
async function handleDelete(item: MohongCategory) {
try {
await ElMessageBox.confirm(
`确认删除分类「${item.name}」?其下商品将变为未分类。`,
'提示',
{ type: 'warning' }
)
await deleteAdminMohongCategory(item.id)
ElMessage.success('已删除')
await load()
} catch (error) {
if (error !== 'cancel') ElMessage.error(readError(error, '删除失败'))
}
}
</script>
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>摸大红分类</h2>
<p>大红 / 四格大红 / 炫彩等分类前台左侧筛选使用</p>
</div>
<div class="actions">
<el-button :icon="Refresh" @click="load">刷新</el-button>
<el-button type="primary" :icon="Plus" @click="openCreate">新建分类</el-button>
</div>
</div>
<el-table v-loading="loading" :data="items" border stripe>
<el-table-column prop="name" label="名称" min-width="140" />
<el-table-column prop="code" label="编码" width="140" />
<el-table-column prop="sort_order" label="排序" width="90" />
<el-table-column label="商品数" width="90">
<template #default="{ row }">{{ row.product_count }}</template>
</el-table-column>
<el-table-column label="状态" width="100">
<template #default="{ row }">
{{ row.status === 'enabled' ? '启用' : '停用' }}
</template>
</el-table-column>
<el-table-column label="操作" width="160" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog
v-model="dialogVisible"
:title="editingId ? '编辑分类' : '新建分类'"
width="480px"
destroy-on-close
>
<el-form label-width="80px">
<el-form-item label="名称" required>
<el-input v-model="form.name" maxlength="64" />
</el-form-item>
<el-form-item label="编码">
<el-input v-model="form.code" maxlength="64" placeholder="可选" />
</el-form-item>
<el-form-item label="排序">
<el-input-number v-model="form.sort_order" />
<span class="hint">越小越靠前</span>
</el-form-item>
<el-form-item label="状态">
<el-select v-model="form.status" style="width: 160px">
<el-option label="启用" value="enabled" />
<el-option label="停用" value="disabled" />
</el-select>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
</template>
</el-dialog>
</div>
</template>
<style scoped>
.admin-page {
display: grid;
gap: 16px;
}
.page-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.page-head h2 {
margin: 0 0 4px;
}
.page-head p {
margin: 0;
color: #6b7a90;
font-size: 13px;
}
.hint {
margin-left: 8px;
color: #8a94a6;
font-size: 12px;
}
</style>
@@ -0,0 +1,149 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import {
fetchAdminMohongConfig,
updateAdminMohongConfig,
type MohongConfig,
} from '@/features/mohong/api/mohong'
import { uploadAdminFile } from '@/shared/api/files'
import { readError } from '@/shared/utils/error'
const loading = ref(false)
const saving = ref(false)
const form = reactive<MohongConfig>({
default_qrcode_url: '',
group_welcome_text: '',
order_copy_template: '',
})
onMounted(load)
async function load() {
loading.value = true
try {
const config = await fetchAdminMohongConfig()
Object.assign(form, config)
} catch (error) {
ElMessage.error(readError(error, '加载配置失败'))
} finally {
loading.value = false
}
}
async function handleSave() {
saving.value = true
try {
const config = await updateAdminMohongConfig({
default_qrcode_url: form.default_qrcode_url,
group_welcome_text: form.group_welcome_text,
order_copy_template: form.order_copy_template,
})
Object.assign(form, config)
ElMessage.success('已保存')
} catch (error) {
ElMessage.error(readError(error, '保存失败'))
} finally {
saving.value = false
}
}
async function uploadQrcode(file: File) {
try {
const uploaded = await uploadAdminFile(file, 'mohong')
form.default_qrcode_url = uploaded.url
ElMessage.success('上传成功')
} catch (error) {
ElMessage.error(readError(error, '上传失败'))
}
return false
}
</script>
<template>
<div v-loading="loading" class="admin-page">
<div class="page-head">
<div>
<h2>摸大红配置</h2>
<p>全局默认固定二维码群欢迎语订单复制模板商品可覆盖默认二维码</p>
</div>
<el-button type="primary" :loading="saving" @click="handleSave">保存配置</el-button>
</div>
<el-form label-width="140px" class="config-form">
<el-form-item label="默认固定二维码">
<div class="qr-row">
<el-image
v-if="form.default_qrcode_url"
:src="form.default_qrcode_url"
fit="contain"
style="width: 160px; height: 160px; border-radius: 12px; background: #f7f9fc"
/>
<div class="qr-actions">
<el-upload :show-file-list="false" accept="image/*" :before-upload="uploadQrcode">
<el-button :icon="Upload">上传二维码</el-button>
</el-upload>
<el-input v-model="form.default_qrcode_url" placeholder="或直接填写图片 URL" />
</div>
</div>
</el-form-item>
<el-form-item label="群欢迎语">
<el-input v-model="form.group_welcome_text" type="textarea" :rows="3" />
</el-form-item>
<el-form-item label="复制文案模板">
<el-input v-model="form.order_copy_template" type="textarea" :rows="8" />
<div class="hint">
可用变量&#123;&#123;order_no&#125;&#125; &#123;&#123;created_at&#125;&#125;
&#123;&#123;product_title&#125;&#125; &#123;&#123;quantity&#125;&#125; &#123;&#123;amount&#125;&#125;
&#123;&#123;buyer_name&#125;&#125; &#123;&#123;buyer_phone&#125;&#125; &#123;&#123;unit&#125;&#125;
</div>
</el-form-item>
</el-form>
</div>
</template>
<style scoped>
.admin-page {
display: grid;
gap: 16px;
}
.page-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.page-head h2 {
margin: 0 0 4px;
}
.page-head p {
margin: 0;
color: #6b7a90;
font-size: 13px;
}
.config-form {
max-width: 820px;
padding: 20px;
border-radius: 12px;
background: #fff;
border: 1px solid #eef1f5;
}
.qr-row {
display: flex;
gap: 16px;
align-items: flex-start;
width: 100%;
}
.qr-actions {
flex: 1;
display: grid;
gap: 10px;
}
.hint {
margin-top: 8px;
color: #8a94a6;
font-size: 12px;
line-height: 1.5;
}
</style>
@@ -0,0 +1,244 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import {
cancelAdminMohongOrder,
completeAdminMohongOrder,
fetchAdminMohongOrders,
mohongOrderStatusLabel,
type MohongOrder,
} from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
import { formatDateTime } from '@/shared/utils/time'
import { readError } from '@/shared/utils/error'
import AdminTablePagination from '../components/AdminTablePagination.vue'
const loading = ref(false)
const items = ref<MohongOrder[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const keyword = ref('')
const status = ref('')
const detail = ref<MohongOrder | null>(null)
onMounted(load)
async function load() {
loading.value = true
try {
const result = await fetchAdminMohongOrders({
keyword: keyword.value || undefined,
status: status.value || undefined,
page: page.value,
page_size: pageSize.value,
})
items.value = result.items || []
total.value = result.total || 0
} catch (error) {
ElMessage.error(readError(error, '加载失败'))
} finally {
loading.value = false
}
}
async function handleComplete(row: MohongOrder) {
try {
await ElMessageBox.confirm(`确认将订单 ${row.order_no} 标记为已完成?`, '提示', {
type: 'warning',
})
await completeAdminMohongOrder(row.id)
ElMessage.success('已完成')
await load()
} catch (error) {
if (error !== 'cancel') ElMessage.error(readError(error, '操作失败'))
}
}
async function handleCancel(row: MohongOrder) {
try {
const { value } = await ElMessageBox.prompt('请输入取消原因', '取消订单', {
inputPlaceholder: '可选',
confirmButtonText: '确认取消',
cancelButtonText: '返回',
})
await cancelAdminMohongOrder(row.id, value || '后台取消')
ElMessage.success('已取消')
await load()
} catch (error) {
if (error !== 'cancel') ElMessage.error(readError(error, '操作失败'))
}
}
async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text)
ElMessage.success('已复制')
} catch {
ElMessage.error('复制失败')
}
}
</script>
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>摸大红订单</h2>
<p>查看订单完成履约复制用户订单信息</p>
</div>
<el-button :icon="Refresh" @click="load">刷新</el-button>
</div>
<div class="filters">
<el-input v-model="keyword" clearable placeholder="订单号" style="width: 220px" @keyup.enter="load" />
<el-select v-model="status" clearable placeholder="状态" style="width: 140px">
<el-option label="待支付" value="pending_payment" />
<el-option label="已支付" value="paid" />
<el-option label="已完成" value="completed" />
<el-option label="已取消" value="cancelled" />
</el-select>
<el-button type="primary" @click=";(page = 1), load()">查询</el-button>
</div>
<el-table v-loading="loading" :data="items" border stripe>
<el-table-column prop="order_no" label="订单号" min-width="170" />
<el-table-column prop="product_title" label="商品" min-width="140" />
<el-table-column label="数量" width="70" prop="quantity" />
<el-table-column label="金额" width="100">
<template #default="{ row }">¥{{ row.amount || formatCent(row.amount_cent) }}</template>
</el-table-column>
<el-table-column label="买家" min-width="140">
<template #default="{ row }">
{{ row.buyer_nickname || '-' }}
<div class="sub">{{ row.buyer_phone || '' }}</div>
</template>
</el-table-column>
<el-table-column label="状态" width="100">
<template #default="{ row }">{{ mohongOrderStatusLabel(row.status) }}</template>
</el-table-column>
<el-table-column label="下单时间" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
</el-table-column>
<el-table-column label="操作" width="220" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="detail = row">详情</el-button>
<el-button
v-if="row.status === 'paid'"
link
type="success"
@click="handleComplete(row)"
>
完成
</el-button>
<el-button
v-if="row.status === 'pending_payment' || row.status === 'paid'"
link
type="danger"
@click="handleCancel(row)"
>
取消
</el-button>
</template>
</el-table-column>
</el-table>
<AdminTablePagination
:current-page="page"
:page-size="pageSize"
:total="total"
@update:current-page="page = $event"
@update:page-size="pageSize = $event"
@page-change="load"
/>
<el-drawer
:model-value="Boolean(detail)"
size="420px"
title="订单详情"
destroy-on-close
@update:model-value="(v: boolean) => !v && (detail = null)"
>
<template v-if="detail">
<el-descriptions :column="1" border>
<el-descriptions-item label="订单号">{{ detail.order_no }}</el-descriptions-item>
<el-descriptions-item label="状态">
{{ mohongOrderStatusLabel(detail.status) }}
</el-descriptions-item>
<el-descriptions-item label="商品">{{ detail.product_title }}</el-descriptions-item>
<el-descriptions-item label="数量">{{ detail.quantity }}</el-descriptions-item>
<el-descriptions-item label="金额">
¥{{ detail.amount || formatCent(detail.amount_cent) }}
</el-descriptions-item>
<el-descriptions-item label="买家">
{{ detail.buyer_nickname }} {{ detail.buyer_phone }}
</el-descriptions-item>
<el-descriptions-item label="会话ID">
{{ detail.conversation_id || '-' }}
</el-descriptions-item>
</el-descriptions>
<div v-if="detail.copy_text" class="copy-box">
<div class="copy-head">
<strong>复制文案</strong>
<el-button size="small" @click="copyText(detail.copy_text)">复制</el-button>
</div>
<pre>{{ detail.copy_text }}</pre>
</div>
<div v-if="detail.qrcode_url_snapshot" class="qr-box">
<strong>二维码快照</strong>
<el-image :src="detail.qrcode_url_snapshot" fit="contain" style="width: 180px; height: 180px" />
</div>
</template>
</el-drawer>
</div>
</template>
<style scoped>
.admin-page {
display: grid;
gap: 16px;
}
.page-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.page-head h2 {
margin: 0 0 4px;
}
.page-head p,
.sub {
margin: 0;
color: #6b7a90;
font-size: 12px;
}
.filters {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.copy-box,
.qr-box {
margin-top: 16px;
}
.copy-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.copy-box pre {
margin: 0;
padding: 12px;
background: #f7f9fc;
border-radius: 8px;
white-space: pre-wrap;
font-size: 13px;
line-height: 1.6;
}
.qr-box {
display: grid;
gap: 8px;
}
</style>
@@ -0,0 +1,418 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Upload } from '@element-plus/icons-vue'
import {
createAdminMohongProduct,
deleteAdminMohongProduct,
fetchAdminMohongCategories,
fetchAdminMohongProducts,
mohongProductStatusLabel,
updateAdminMohongProduct,
type MohongCategory,
type MohongProduct,
} from '@/features/mohong/api/mohong'
import { uploadAdminFile } from '@/shared/api/files'
import { formatCent, yuanToCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
import AdminTablePagination from '../components/AdminTablePagination.vue'
const loading = ref(false)
const items = ref<MohongProduct[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const keyword = ref('')
const status = ref('')
const categoryId = ref<number | undefined>()
const categories = ref<MohongCategory[]>([])
const dialogVisible = ref(false)
const saving = ref(false)
const editingId = ref<number | null>(null)
const form = reactive({
category_id: undefined as number | undefined,
title: '',
cover_url: '',
image_urls: [] as string[],
description: '',
price_yuan: 0,
original_price_yuan: 0,
unit: '份',
stock: -1,
sort_order: 0,
status: 'draft',
qrcode_image_url: '',
use_custom_qrcode: false,
})
onMounted(async () => {
await loadCategories()
await load()
})
async function loadCategories() {
try {
categories.value = await fetchAdminMohongCategories()
} catch {
categories.value = []
}
}
async function load() {
loading.value = true
try {
const result = await fetchAdminMohongProducts({
keyword: keyword.value || undefined,
status: status.value || undefined,
category_id: categoryId.value,
page: page.value,
page_size: pageSize.value,
})
items.value = result.items || []
total.value = result.total || 0
} catch (error) {
ElMessage.error(readError(error, '加载失败'))
} finally {
loading.value = false
}
}
function openCreate() {
editingId.value = null
Object.assign(form, {
category_id: categoryId.value,
title: '',
cover_url: '',
image_urls: [],
description: '',
price_yuan: 0,
original_price_yuan: 0,
unit: '份',
stock: -1,
sort_order: 0,
status: 'on_sale',
qrcode_image_url: '',
use_custom_qrcode: false,
})
dialogVisible.value = true
}
function openEdit(item: MohongProduct) {
editingId.value = item.id
Object.assign(form, {
category_id: item.category_id || undefined,
title: item.title,
cover_url: item.cover_url,
image_urls: [...(item.image_urls || [])],
description: item.description,
price_yuan: item.price_cent / 100,
original_price_yuan: (item.original_price_cent || 0) / 100,
unit: item.unit || '份',
stock: item.stock,
sort_order: item.sort_order,
status: item.status,
qrcode_image_url: item.qrcode_image_url || '',
use_custom_qrcode: Boolean(item.qrcode_image_url),
})
dialogVisible.value = true
}
async function handleSave() {
if (!form.title.trim()) {
ElMessage.warning('请填写标题')
return
}
if (form.price_yuan <= 0) {
ElMessage.warning('请填写有效价格')
return
}
saving.value = true
try {
const payload: Record<string, unknown> = {
title: form.title.trim(),
cover_url: form.cover_url,
image_urls: form.image_urls,
description: form.description,
price_cent: yuanToCent(form.price_yuan),
original_price_cent: yuanToCent(form.original_price_yuan),
unit: form.unit || '份',
stock: form.stock,
sort_order: form.sort_order,
status: form.status,
qrcode_image_url: form.use_custom_qrcode ? form.qrcode_image_url : '',
}
if (form.category_id) {
payload.category_id = form.category_id
} else if (editingId.value) {
payload.clear_category = true
}
if (editingId.value) {
await updateAdminMohongProduct(editingId.value, payload)
ElMessage.success('已更新')
} else {
await createAdminMohongProduct(
payload as Partial<MohongProduct> & { title: string; price_cent: number }
)
ElMessage.success('已创建')
}
dialogVisible.value = false
await load()
} catch (error) {
ElMessage.error(readError(error, '保存失败'))
} finally {
saving.value = false
}
}
async function handleDelete(item: MohongProduct) {
try {
await ElMessageBox.confirm(`确认删除商品「${item.title}」?`, '提示', { type: 'warning' })
await deleteAdminMohongProduct(item.id)
ElMessage.success('已删除')
await load()
} catch (error) {
if (error !== 'cancel') ElMessage.error(readError(error, '删除失败'))
}
}
async function uploadImage(file: File, target: 'cover' | 'gallery' | 'qrcode') {
try {
const uploaded = await uploadAdminFile(file, 'mohong')
if (target === 'cover') form.cover_url = uploaded.url
else if (target === 'qrcode') form.qrcode_image_url = uploaded.url
else form.image_urls.push(uploaded.url)
ElMessage.success('上传成功')
} catch (error) {
ElMessage.error(readError(error, '上传失败'))
}
return false
}
function removeGallery(url: string) {
form.image_urls = form.image_urls.filter(item => item !== url)
}
</script>
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>摸大红商品</h2>
<p>管理商品图片价格库存与专属二维码</p>
</div>
<div class="actions">
<el-button :icon="Refresh" @click="load">刷新</el-button>
<el-button type="primary" :icon="Plus" @click="openCreate">新建商品</el-button>
</div>
</div>
<div class="filters">
<el-input v-model="keyword" clearable placeholder="搜索标题" style="width: 220px" @keyup.enter="load" />
<el-select v-model="categoryId" clearable placeholder="分类" style="width: 140px">
<el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
</el-select>
<el-select v-model="status" clearable placeholder="状态" style="width: 140px">
<el-option label="草稿" value="draft" />
<el-option label="上架中" value="on_sale" />
<el-option label="已下架" value="off_sale" />
</el-select>
<el-button type="primary" @click=";(page = 1), load()">查询</el-button>
</div>
<el-table v-loading="loading" :data="items" border stripe>
<el-table-column label="封面" width="80">
<template #default="{ row }">
<el-image
v-if="row.cover_url"
:src="row.cover_url"
style="width: 48px; height: 48px; border-radius: 8px"
fit="cover"
/>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column prop="title" label="标题" min-width="160" />
<el-table-column label="分类" width="110">
<template #default="{ row }">{{ row.category_name || '-' }}</template>
</el-table-column>
<el-table-column label="价格" width="100">
<template #default="{ row }">¥{{ row.price || formatCent(row.price_cent) }}</template>
</el-table-column>
<el-table-column label="库存" width="90">
<template #default="{ row }">{{ row.stock < 0 ? '不限' : row.stock }}</template>
</el-table-column>
<el-table-column label="状态" width="100">
<template #default="{ row }">{{ mohongProductStatusLabel(row.status) }}</template>
</el-table-column>
<el-table-column prop="sort_order" label="排序" width="80" />
<el-table-column label="专属码" width="90">
<template #default="{ row }">{{ row.qrcode_image_url ? '是' : '默认' }}</template>
</el-table-column>
<el-table-column label="操作" width="160" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<AdminTablePagination
:current-page="page"
:page-size="pageSize"
:total="total"
@update:current-page="page = $event"
@update:page-size="pageSize = $event"
@page-change="load"
/>
<el-dialog
v-model="dialogVisible"
:title="editingId ? '编辑商品' : '新建商品'"
width="640px"
destroy-on-close
>
<el-form label-width="100px">
<el-form-item label="分类">
<el-select v-model="form.category_id" clearable placeholder="选择分类" style="width: 100%">
<el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
</el-select>
</el-form-item>
<el-form-item label="标题" required>
<el-input v-model="form.title" maxlength="128" />
</el-form-item>
<el-form-item label="封面">
<div class="upload-row">
<el-image
v-if="form.cover_url"
:src="form.cover_url"
style="width: 80px; height: 80px; border-radius: 8px"
fit="cover"
/>
<el-upload :show-file-list="false" accept="image/*" :before-upload="(f: File) => uploadImage(f, 'cover')">
<el-button :icon="Upload">上传封面</el-button>
</el-upload>
</div>
</el-form-item>
<el-form-item label="详情图">
<div class="gallery">
<div v-for="url in form.image_urls" :key="url" class="gallery-item">
<el-image :src="url" fit="cover" />
<button type="button" @click="removeGallery(url)">×</button>
</div>
<el-upload :show-file-list="false" accept="image/*" :before-upload="(f: File) => uploadImage(f, 'gallery')">
<el-button :icon="Upload">添加图片</el-button>
</el-upload>
</div>
</el-form-item>
<el-form-item label="描述">
<el-input v-model="form.description" type="textarea" :rows="4" />
</el-form-item>
<el-form-item label="售价()" required>
<el-input-number v-model="form.price_yuan" :min="0.1" :step="0.1" :precision="1" />
</el-form-item>
<el-form-item label="原价()">
<el-input-number v-model="form.original_price_yuan" :min="0" :step="0.1" :precision="1" />
</el-form-item>
<el-form-item label="单位">
<el-input v-model="form.unit" style="width: 120px" />
</el-form-item>
<el-form-item label="库存">
<el-input-number v-model="form.stock" :min="-1" />
<span class="hint">-1 表示不限库存</span>
</el-form-item>
<el-form-item label="排序">
<el-input-number v-model="form.sort_order" />
</el-form-item>
<el-form-item label="状态">
<el-select v-model="form.status" style="width: 160px">
<el-option label="草稿" value="draft" />
<el-option label="上架" value="on_sale" />
<el-option label="下架" value="off_sale" />
</el-select>
</el-form-item>
<el-form-item label="专属二维码">
<el-switch v-model="form.use_custom_qrcode" active-text="覆盖默认" inactive-text="用默认" />
<div v-if="form.use_custom_qrcode" class="upload-row" style="margin-top: 8px">
<el-image
v-if="form.qrcode_image_url"
:src="form.qrcode_image_url"
style="width: 100px; height: 100px; border-radius: 8px"
fit="contain"
/>
<el-upload
:show-file-list="false"
accept="image/*"
:before-upload="(f: File) => uploadImage(f, 'qrcode')"
>
<el-button :icon="Upload">上传二维码</el-button>
</el-upload>
</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
</template>
</el-dialog>
</div>
</template>
<style scoped>
.admin-page {
display: grid;
gap: 16px;
}
.page-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.page-head h2 {
margin: 0 0 4px;
}
.page-head p {
margin: 0;
color: #6b7a90;
font-size: 13px;
}
.filters {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.upload-row,
.gallery {
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: center;
}
.gallery-item {
position: relative;
width: 72px;
height: 72px;
}
.gallery-item :deep(.el-image) {
width: 72px;
height: 72px;
border-radius: 8px;
}
.gallery-item button {
position: absolute;
top: -6px;
right: -6px;
width: 20px;
height: 20px;
border: 0;
border-radius: 50%;
background: #ef4444;
color: #fff;
cursor: pointer;
}
.hint {
margin-left: 8px;
color: #8a94a6;
font-size: 12px;
}
</style>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import {
defaultHomeAnnouncements,
defaultHomeBanners,
@@ -255,6 +255,17 @@ loadHome()
<HomeStats :stats="statCards" />
</div>
<div class="biz-entry-grid" aria-label="业务入口">
<RouterLink class="biz-entry" to="/">
<strong>租号大厅</strong>
<small>高哈夫币 · 安全交接 · 随租随玩</small>
</RouterLink>
<RouterLink class="biz-entry mohong" to="/mohong">
<strong>摸大红 <em>NEW</em></strong>
<small>选购商品 · 支付后进群联系客服</small>
</RouterLink>
</div>
<HomeFilters
:filters="filters"
:total-listings="totalListings"
@@ -326,6 +337,51 @@ loadHome()
min-width: 0;
}
.biz-entry-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.biz-entry {
display: flex;
flex-direction: column;
gap: 6px;
padding: 16px 18px;
border-radius: 14px;
border: 1px solid #eef1f5;
background: #fff;
text-decoration: none;
transition:
border-color 0.18s ease,
box-shadow 0.18s ease;
}
.biz-entry:hover {
border-color: #ffd4b0;
box-shadow: 0 6px 16px rgba(255, 106, 0, 0.08);
}
.biz-entry strong {
color: #17233d;
font-size: 16px;
}
.biz-entry small {
color: #7b8798;
font-size: 13px;
}
.biz-entry.mohong strong em {
margin-left: 6px;
padding: 1px 6px;
border-radius: 999px;
background: #ff6a00;
color: #fff;
font-size: 11px;
font-style: normal;
}
.infinite-load-state {
padding: 6px 0 18px;
color: #94a3b8;
@@ -343,6 +343,75 @@
font-weight: 800;
}
.biz-entry-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.biz-entry {
position: relative;
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
padding: 12px 12px 12px 14px;
border-radius: 14px;
background: #ffffff;
border: 1px solid #eef1f5;
text-decoration: none;
box-shadow: 0 4px 14px rgba(23, 35, 61, 0.04);
}
.biz-entry-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
border-radius: 9px;
font-size: 13px;
font-weight: 800;
margin-bottom: 2px;
}
.biz-entry-icon.rental {
background: #fff1e6;
color: #ff6a00;
}
.biz-entry-icon.mohong {
background: #fee2e2;
color: #dc2626;
}
.biz-entry strong {
color: #17233d;
font-size: 15px;
}
.biz-entry small {
color: #8a94a6;
font-size: 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.biz-entry-badge {
position: absolute;
top: 10px;
right: 10px;
padding: 2px 6px;
border-radius: 999px;
background: #ff6a00;
color: #fff;
font-size: 10px;
font-style: normal;
font-weight: 800;
}
.zone-strip {
display: flex;
gap: 6px;
@@ -815,6 +815,20 @@ syncMobileHomeQuery()
</van-swipe-item>
</van-swipe>
<div class="biz-entry-grid" aria-label="业务入口">
<RouterLink class="biz-entry" to="/">
<span class="biz-entry-icon rental"></span>
<strong>租号大厅</strong>
<small>高哈夫币 · 随租随玩</small>
</RouterLink>
<RouterLink class="biz-entry" to="/mohong">
<span class="biz-entry-icon mohong"></span>
<strong>摸大红</strong>
<small>选购商品 · 一键找客服</small>
<em class="biz-entry-badge">NEW</em>
</RouterLink>
</div>
<div class="zone-strip" aria-label="账号专区">
<button
v-for="zone in visibleZoneOptions"
+290
View File
@@ -0,0 +1,290 @@
import { apiClient } from '@/shared/api/client'
import type { ApiResponse } from '@/shared/types/types'
import type { PaymentOrder, PaymentPayWay } from '@/features/orders/api/orders'
export interface MohongCategory {
id: number
name: string
code: string
sort_order: number
status: string
product_count: number
created_at: string
updated_at: string
}
export interface MohongProduct {
id: number
category_id?: number | null
category_name?: string
title: string
cover_url: string
image_urls: string[]
description: string
price_cent: number
price: string
original_price_cent: number
original_price?: string
unit: string
stock: number
sort_order: number
status: string
qrcode_image_url?: string
created_at: string
updated_at: string
}
export interface MohongOrder {
id: number
order_no: string
user_id: number
product_id: number
quantity: number
unit_price_cent: number
unit_price: string
amount_cent: number
amount: string
status: string
product_title: string
product_cover_url: string
product_unit: string
qrcode_url_snapshot: string
copy_text: string
conversation_id?: number | null
buyer_nickname?: string
buyer_phone?: string
admin_remark?: string
cancel_reason?: string
paid_at?: string | null
completed_at?: string | null
cancelled_at?: string | null
created_at: string
updated_at: string
}
export interface MohongConfig {
default_qrcode_url: string
group_welcome_text: string
order_copy_template: string
}
export interface Paginated<T> {
items: T[]
total: number
page: number
page_size: number
}
export async function fetchMohongCategories() {
const { data } = await apiClient.get<ApiResponse<MohongCategory[]>>('/mohong/categories')
return data.data || []
}
export async function fetchMohongProducts(params?: {
keyword?: string
category_id?: number
page?: number
page_size?: number
}) {
const { data } = await apiClient.get<ApiResponse<Paginated<MohongProduct>>>('/mohong/products', {
params,
})
return data.data
}
export async function fetchMohongProduct(id: number | string) {
const { data } = await apiClient.get<ApiResponse<MohongProduct>>(`/mohong/products/${id}`)
return data.data
}
export async function createMohongOrder(productId: number, quantity: number) {
const { data } = await apiClient.post<ApiResponse<MohongOrder>>('/mohong/orders', {
product_id: productId,
quantity,
})
return data.data
}
export async function fetchMyMohongOrders(params?: {
status?: string
page?: number
page_size?: number
}) {
const { data } = await apiClient.get<ApiResponse<Paginated<MohongOrder>>>('/mohong/orders', {
params,
})
return data.data
}
export async function fetchMyMohongOrder(id: number | string) {
const { data } = await apiClient.get<ApiResponse<MohongOrder>>(`/mohong/orders/${id}`)
return data.data
}
export async function cancelMyMohongOrder(id: number | string, reason?: string) {
const { data } = await apiClient.post<ApiResponse<MohongOrder>>(`/mohong/orders/${id}/cancel`, {
reason: reason || '',
})
return data.data
}
export async function startMohongPayment(
orderId: number,
payWay: PaymentPayWay | string,
jsPayFlag?: string
) {
const { data } = await apiClient.post<ApiResponse<PaymentOrder>>(
`/mohong/orders/${orderId}/start-payment`,
{
pay_way: payWay || 'ZFBZF',
jspay_flag: jsPayFlag || '',
}
)
return data.data
}
export async function queryMohongPayment(orderId: number) {
const { data } = await apiClient.get<ApiResponse<PaymentOrder>>(
`/mohong/orders/${orderId}/query-payment`
)
return data.data
}
// Admin APIs
export async function fetchAdminMohongCategories() {
const { data } = await apiClient.get<ApiResponse<MohongCategory[]>>('/admin/mohong/categories')
return data.data || []
}
export async function createAdminMohongCategory(payload: {
name: string
code?: string
sort_order?: number
status?: string
}) {
const { data } = await apiClient.post<ApiResponse<MohongCategory>>(
'/admin/mohong/categories',
payload
)
return data.data
}
export async function updateAdminMohongCategory(
id: number,
payload: Partial<{ name: string; code: string; sort_order: number; status: string }>
) {
const { data } = await apiClient.put<ApiResponse<MohongCategory>>(
`/admin/mohong/categories/${id}`,
payload
)
return data.data
}
export async function deleteAdminMohongCategory(id: number) {
const { data } = await apiClient.delete<ApiResponse<{ message: string }>>(
`/admin/mohong/categories/${id}`
)
return data.data
}
export async function fetchAdminMohongProducts(params?: {
keyword?: string
status?: string
category_id?: number
page?: number
page_size?: number
}) {
const { data } = await apiClient.get<ApiResponse<Paginated<MohongProduct>>>(
'/admin/mohong/products',
{ params }
)
return data.data
}
export async function fetchAdminMohongProduct(id: number | string) {
const { data } = await apiClient.get<ApiResponse<MohongProduct>>(`/admin/mohong/products/${id}`)
return data.data
}
export async function createAdminMohongProduct(payload: Partial<MohongProduct> & { title: string; price_cent: number }) {
const { data } = await apiClient.post<ApiResponse<MohongProduct>>('/admin/mohong/products', payload)
return data.data
}
export async function updateAdminMohongProduct(id: number, payload: Record<string, unknown>) {
const { data } = await apiClient.put<ApiResponse<MohongProduct>>(
`/admin/mohong/products/${id}`,
payload
)
return data.data
}
export async function deleteAdminMohongProduct(id: number) {
const { data } = await apiClient.delete<ApiResponse<{ message: string }>>(
`/admin/mohong/products/${id}`
)
return data.data
}
export async function fetchAdminMohongOrders(params?: {
status?: string
keyword?: string
page?: number
page_size?: number
}) {
const { data } = await apiClient.get<ApiResponse<Paginated<MohongOrder>>>('/admin/mohong/orders', {
params,
})
return data.data
}
export async function fetchAdminMohongOrder(id: number | string) {
const { data } = await apiClient.get<ApiResponse<MohongOrder>>(`/admin/mohong/orders/${id}`)
return data.data
}
export async function completeAdminMohongOrder(id: number, remark?: string) {
const { data } = await apiClient.post<ApiResponse<MohongOrder>>(
`/admin/mohong/orders/${id}/complete`,
{ remark: remark || '' }
)
return data.data
}
export async function cancelAdminMohongOrder(id: number, reason?: string) {
const { data } = await apiClient.post<ApiResponse<MohongOrder>>(
`/admin/mohong/orders/${id}/cancel`,
{ reason: reason || '' }
)
return data.data
}
export async function fetchAdminMohongConfig() {
const { data } = await apiClient.get<ApiResponse<MohongConfig>>('/admin/mohong/config')
return data.data
}
export async function updateAdminMohongConfig(payload: Partial<MohongConfig>) {
const { data } = await apiClient.put<ApiResponse<MohongConfig>>('/admin/mohong/config', payload)
return data.data
}
export function mohongOrderStatusLabel(status: string) {
const map: Record<string, string> = {
pending_payment: '待支付',
paid: '已支付',
completed: '已完成',
cancelled: '已取消',
refunded: '已退款',
}
return map[status] || status
}
export function mohongProductStatusLabel(status: string) {
const map: Record<string, string> = {
draft: '草稿',
on_sale: '上架中',
off_sale: '已下架',
}
return map[status] || status
}
@@ -0,0 +1,177 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { RouterLink } from 'vue-router'
import type { MohongProduct } from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
const props = defineProps<{ product: MohongProduct }>()
const imgFailed = ref(false)
const coverURL = computed(() => props.product.cover_url || props.product.image_urls?.[0] || '')
const showImage = computed(() => Boolean(coverURL.value) && !imgFailed.value)
const priceText = computed(() => props.product.price || formatCent(props.product.price_cent))
const stockLabel = computed(() => {
if (props.product.stock < 0) return ''
if (props.product.stock === 0) return '缺货'
return `${props.product.stock}`
})
</script>
<template>
<RouterLink class="mohong-card" :to="`/mohong/${product.id}`">
<div class="card-cover">
<img
v-if="showImage"
:src="coverURL"
:alt="product.title"
loading="lazy"
decoding="async"
@error="imgFailed = true"
/>
<div v-else class="empty-cover">{{ product.title.slice(0, 1) || '红' }}</div>
<span v-if="stockLabel" class="stock-tag" :class="{ danger: product.stock === 0 }">
{{ stockLabel }}
</span>
</div>
<div class="card-body">
<h3 :title="product.title">{{ product.title }}</h3>
<div class="row">
<div class="price">
<strong>¥{{ priceText }}</strong>
<small v-if="product.original_price">¥{{ product.original_price }}</small>
</div>
<span class="buy">购买</span>
</div>
</div>
</RouterLink>
</template>
<style scoped>
.mohong-card {
display: flex;
flex-direction: column;
width: 200px;
min-width: 200px;
max-width: 200px;
overflow: hidden;
border: 1px solid #e8edf5;
border-radius: 14px;
background: #fff;
text-decoration: none;
color: inherit;
transition:
border-color 0.18s ease,
box-shadow 0.18s ease,
transform 0.18s ease;
}
.mohong-card:hover {
border-color: #ffb27a;
box-shadow: 0 10px 24px rgba(255, 106, 0, 0.12);
transform: translateY(-2px);
}
.card-cover {
position: relative;
width: 200px;
height: 200px;
background: #f4f6fa;
overflow: hidden;
flex-shrink: 0;
}
.card-cover img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.empty-cover {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: linear-gradient(145deg, #fff7ed, #ffe4cc);
color: #ff6a00;
font-size: 28px;
font-weight: 900;
}
.stock-tag {
position: absolute;
top: 8px;
left: 8px;
padding: 2px 7px;
border-radius: 999px;
background: rgba(15, 23, 42, 0.62);
color: #fff;
font-size: 11px;
font-weight: 700;
line-height: 1.4;
}
.stock-tag.danger {
background: rgba(220, 38, 38, 0.88);
}
.card-body {
display: grid;
gap: 8px;
padding: 10px 12px 12px;
}
.card-body h3 {
margin: 0;
color: #1f2937;
font-size: 14px;
font-weight: 700;
line-height: 1.35;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.price {
display: flex;
align-items: baseline;
gap: 6px;
min-width: 0;
}
.price strong {
color: #ff6a00;
font-size: 18px;
font-weight: 800;
line-height: 1;
}
.price small {
color: #c0c8d4;
font-size: 12px;
text-decoration: line-through;
}
.buy {
flex-shrink: 0;
padding: 5px 10px;
border-radius: 8px;
background: #ff6a00;
color: #fff;
font-size: 12px;
font-weight: 700;
}
.mohong-card:hover .buy {
background: #ea580c;
}
</style>
@@ -0,0 +1,318 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import MobilePayWaySelectPopup from '@/features/orders/components/MobilePayWaySelectPopup.vue'
import MobilePaymentCashierPopup from '@/features/orders/components/MobilePaymentCashierPopup.vue'
import { useMobilePayWaySelect } from '@/features/orders/composables/useMobilePayWaySelect'
import { useMobilePaymentCashier } from '@/features/orders/composables/useMobilePaymentCashier'
import {
createMohongOrder,
fetchMohongProduct,
queryMohongPayment,
startMohongPayment,
type MohongProduct,
} from '@/features/mohong/api/mohong'
import { useSessionStore } from '@/stores/session'
import { formatCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
const route = useRoute()
const router = useRouter()
const session = useSessionStore()
const product = ref<MohongProduct | null>(null)
const loading = ref(true)
const quantity = ref(1)
const submitting = ref(false)
const payWaySelect = useMobilePayWaySelect()
const {
paymentPopupVisible,
activePayment,
payURL,
paymentQRCodeURL,
qrGenerating,
checkingPayment,
openMobilePaymentCashier,
refreshPaymentStatus,
} = useMobilePaymentCashier({
queryPayment: queryMohongPayment,
paidMessage: '支付成功',
})
const images = computed(() => {
if (!product.value) return []
const list = [...(product.value.image_urls || [])]
if (product.value.cover_url && !list.includes(product.value.cover_url)) {
list.unshift(product.value.cover_url)
}
return list
})
const totalPrice = computed(() => {
if (!product.value) return '0'
const cent = product.value.price_cent * quantity.value
return formatCent(cent)
})
const canBuy = computed(() => {
if (!product.value) return false
if (product.value.stock === 0) return false
if (product.value.stock > 0 && quantity.value > product.value.stock) return false
return true
})
onMounted(loadProduct)
async function loadProduct() {
loading.value = true
try {
product.value = await fetchMohongProduct(String(route.params.id))
} catch (error) {
showToast({ message: readError(error, '商品不存在'), icon: 'cross' })
} finally {
loading.value = false
}
}
async function ensureAuthReady() {
if (!session.isLoggedIn) {
router.push({ path: '/m/login', query: { redirect: route.fullPath } })
return false
}
try {
await session.loadMe()
} catch {
// ignore
}
if (session.realnameStatus !== 'verified') {
router.push({ path: '/m/realname', query: { redirect: route.fullPath } })
return false
}
return true
}
async function handleBuy() {
if (!product.value || submitting.value) return
if (!(await ensureAuthReady())) return
if (!canBuy.value) {
showToast({ message: '库存不足', icon: 'cross' })
return
}
const payWay = await payWaySelect.select()
if (!payWay) return
submitting.value = true
try {
const order = await createMohongOrder(product.value.id, quantity.value)
const payment = await startMohongPayment(order.id, payWay)
if (payment.paid || payment.status === 'paid') {
showToast({ message: '支付成功', icon: 'passed' })
await router.push(`/mohong/orders/${order.id}`)
return
}
await openMobilePaymentCashier(payment, async () => {
await router.push(`/mohong/orders/${order.id}`)
})
} catch (error) {
showToast({ message: readError(error, '下单失败'), icon: 'cross' })
} finally {
submitting.value = false
}
}
</script>
<template>
<main class="detail-shell">
<header class="page-header">
<button type="button" class="back-btn" @click="router.back()">
<van-icon name="arrow-left" :size="20" />
</button>
<h1>商品详情</h1>
</header>
<van-loading v-if="loading" class="state-loading" size="24px" vertical>加载中...</van-loading>
<template v-else-if="product">
<van-swipe v-if="images.length" class="gallery" :autoplay="4000">
<van-swipe-item v-for="(url, idx) in images" :key="idx">
<img :src="url" :alt="product.title" />
</van-swipe-item>
</van-swipe>
<div v-else class="gallery empty">暂无图片</div>
<section class="panel">
<div class="price-row">
<strong>¥{{ product.price || formatCent(product.price_cent) }}</strong>
<span v-if="product.original_price" class="origin">¥{{ product.original_price }}</span>
<em>/ {{ product.unit || '份' }}</em>
</div>
<h2>{{ product.title }}</h2>
<p class="stock">
库存
<template v-if="product.stock < 0">充足</template>
<template v-else>{{ product.stock }}</template>
</p>
</section>
<section class="panel">
<h3>商品说明</h3>
<p class="desc">{{ product.description || '暂无说明' }}</p>
</section>
<section class="panel qty-panel">
<span>购买数量</span>
<van-stepper v-model="quantity" :min="1" :max="product.stock > 0 ? product.stock : 99" />
</section>
<div class="buy-bar">
<div class="sum">
合计 <strong>¥{{ totalPrice }}</strong>
</div>
<van-button
type="primary"
color="#ff6a00"
round
:loading="submitting"
:disabled="!canBuy"
@click="handleBuy"
>
{{ canBuy ? '立即购买' : '暂时缺货' }}
</van-button>
</div>
</template>
<van-empty v-else description="商品不存在" />
<MobilePayWaySelectPopup
v-model:show="payWaySelect.visible.value"
@choose="payWaySelect.choose"
@closed="payWaySelect.handleClosed"
/>
<MobilePaymentCashierPopup
v-model:show="paymentPopupVisible"
:payment="activePayment"
:pay-url="payURL"
:qr-code-url="paymentQRCodeURL"
:qr-generating="qrGenerating"
:checking="checkingPayment"
@refresh="refreshPaymentStatus(false)"
/>
</main>
</template>
<style scoped>
.detail-shell {
min-height: 100vh;
background: #f5f7fb;
padding-bottom: 88px;
}
.page-header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
gap: 8px;
padding: 12px 14px;
background: #fff;
border-bottom: 1px solid #eef1f5;
}
.back-btn {
border: 0;
background: transparent;
}
.page-header h1 {
margin: 0;
font-size: 17px;
}
.state-loading {
padding: 48px 0;
}
.gallery {
height: 280px;
background: #fff;
}
.gallery img {
width: 100%;
height: 280px;
object-fit: cover;
}
.gallery.empty {
display: flex;
align-items: center;
justify-content: center;
color: #a0aec0;
}
.panel {
margin: 10px 12px;
padding: 14px;
border-radius: 14px;
background: #fff;
}
.price-row {
display: flex;
align-items: baseline;
gap: 8px;
margin-bottom: 8px;
}
.price-row strong {
color: #ff6a00;
font-size: 24px;
}
.price-row .origin {
color: #b0b8c4;
text-decoration: line-through;
font-size: 13px;
}
.price-row em {
font-style: normal;
color: #8a94a6;
font-size: 13px;
}
.panel h2 {
margin: 0 0 8px;
font-size: 17px;
color: #17233d;
}
.stock,
.desc {
margin: 0;
color: #6b7a90;
font-size: 13px;
line-height: 1.6;
white-space: pre-wrap;
}
.panel h3 {
margin: 0 0 8px;
font-size: 14px;
color: #17233d;
}
.qty-panel {
display: flex;
align-items: center;
justify-content: space-between;
}
.buy-bar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
background: #fff;
border-top: 1px solid #eef1f5;
}
.sum {
color: #6b7a90;
font-size: 13px;
}
.sum strong {
color: #ff6a00;
font-size: 20px;
margin-left: 4px;
}
.buy-bar :deep(.van-button) {
min-width: 128px;
}
</style>
@@ -0,0 +1,386 @@
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import MobileBottomNav from '@/components/MobileBottomNav.vue'
import {
fetchMohongCategories,
fetchMohongProducts,
type MohongCategory,
type MohongProduct,
} from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const products = ref<MohongProduct[]>([])
const categories = ref<MohongCategory[]>([])
const total = ref(0)
const page = ref(1)
const hasMore = ref(true)
const loadingMore = ref(false)
const keyword = ref('')
const activeCategoryId = ref<number | null>(null)
const failedCover = ref<Record<number, boolean>>({})
let searchTimer: ReturnType<typeof setTimeout> | null = null
onMounted(async () => {
await loadCategories()
applyRouteQuery()
await loadProducts(true)
})
watch(
() => route.query,
() => {
applyRouteQuery()
loadProducts(true)
}
)
function applyRouteQuery() {
const q = route.query
keyword.value = typeof q.keyword === 'string' ? q.keyword : ''
const cat = Number(q.category_id || 0)
activeCategoryId.value = cat > 0 ? cat : null
}
async function loadCategories() {
try {
categories.value = await fetchMohongCategories()
if (!activeCategoryId.value && categories.value.length) {
const dahong = categories.value.find(c => c.name === '大红')
const first = categories.value.find(c => c.product_count > 0) || categories.value[0]
if (dahong || first) {
activeCategoryId.value = (dahong || first)!.id
syncQuery()
}
}
} catch (error) {
showToast({ message: readError(error, '加载分类失败'), icon: 'cross' })
}
}
async function loadProducts(reset = true) {
if (loadingMore.value) return
if (reset) {
loading.value = true
page.value = 1
hasMore.value = true
} else {
if (!hasMore.value) return
loadingMore.value = true
}
try {
const result = await fetchMohongProducts({
page: page.value,
page_size: 20,
keyword: keyword.value.trim() || undefined,
category_id: activeCategoryId.value || undefined,
})
products.value = reset ? result.items || [] : [...products.value, ...(result.items || [])]
total.value = result.total || 0
hasMore.value = products.value.length < total.value
page.value += 1
} catch (error) {
showToast({ message: readError(error, '加载商品失败'), icon: 'cross' })
} finally {
loading.value = false
loadingMore.value = false
}
}
function selectCategory(id: number | null) {
activeCategoryId.value = id
syncQuery()
loadProducts(true)
}
function onSearchInput() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
syncQuery()
loadProducts(true)
}, 280)
}
function syncQuery() {
const query: Record<string, string> = {}
if (keyword.value.trim()) query.keyword = keyword.value.trim()
if (activeCategoryId.value) query.category_id = String(activeCategoryId.value)
router.replace({ path: '/mohong', query })
}
function goDetail(id: number) {
router.push(`/mohong/${id}`)
}
function markCoverFailed(id: number) {
failedCover.value = { ...failedCover.value, [id]: true }
}
function showCover(item: MohongProduct) {
return Boolean(item.cover_url) && !failedCover.value[item.id]
}
</script>
<template>
<main class="mohong-shell">
<header class="page-header">
<button type="button" class="back-btn" @click="router.push('/')">
<van-icon name="arrow-left" :size="20" />
</button>
<div class="search-wrap">
<van-icon name="search" :size="16" />
<input
v-model="keyword"
type="search"
placeholder="搜索商品"
@input="onSearchInput"
/>
</div>
<button type="button" class="orders-btn" @click="router.push('/mohong/orders')">订单</button>
</header>
<div class="shop-body">
<aside class="cat-sidebar">
<button
type="button"
class="cat-item"
:class="{ active: !activeCategoryId }"
@click="selectCategory(null)"
>
全部
</button>
<button
v-for="cat in categories"
:key="cat.id"
type="button"
class="cat-item"
:class="{ active: activeCategoryId === cat.id }"
@click="selectCategory(cat.id)"
>
{{ cat.name }}
</button>
</aside>
<section class="list-panel">
<van-loading v-if="loading" class="state-loading" size="24px" vertical>加载中...</van-loading>
<van-empty v-else-if="products.length === 0" description="暂无商品" />
<div v-else class="product-list">
<button
v-for="item in products"
:key="item.id"
type="button"
class="product-row"
@click="goDetail(item.id)"
>
<div class="cover">
<img
v-if="showCover(item)"
:src="item.cover_url"
:alt="item.title"
@error="markCoverFailed(item.id)"
/>
<span v-else class="cover-fallback">{{ item.title.slice(0, 1) || '红' }}</span>
</div>
<div class="info">
<h2>{{ item.title }}</h2>
<div class="price-row">
<strong>¥{{ item.price || formatCent(item.price_cent) }}</strong>
<small v-if="item.original_price">¥{{ item.original_price }}</small>
</div>
</div>
<span class="buy-icon"></span>
</button>
</div>
<van-button
v-if="hasMore && products.length"
size="small"
plain
block
:loading="loadingMore"
class="load-more"
@click="loadProducts(false)"
>
加载更多
</van-button>
</section>
</div>
<MobileBottomNav />
</main>
</template>
<style scoped>
.mohong-shell {
min-height: 100vh;
background: #f5f7fb;
padding-bottom: calc(64px + env(safe-area-inset-bottom));
display: flex;
flex-direction: column;
}
.page-header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
background: #fff;
border-bottom: 1px solid #eef1f5;
}
.back-btn,
.orders-btn {
border: 0;
background: transparent;
color: #17233d;
flex-shrink: 0;
}
.orders-btn {
color: #ff6a00;
font-size: 14px;
font-weight: 600;
}
.search-wrap {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 6px;
height: 34px;
padding: 0 12px;
border-radius: 999px;
background: #f3f5f9;
color: #94a3b8;
}
.search-wrap input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font-size: 14px;
color: #17233d;
}
.shop-body {
flex: 1;
display: grid;
grid-template-columns: 88px minmax(0, 1fr);
min-height: 0;
}
.cat-sidebar {
background: #f7f8fa;
overflow-y: auto;
padding: 8px 0 16px;
}
.cat-item {
display: block;
width: 100%;
padding: 14px 8px;
border: 0;
border-left: 3px solid transparent;
background: transparent;
color: #64748b;
font-size: 13px;
text-align: center;
cursor: pointer;
}
.cat-item.active {
background: #fff;
border-left-color: #ff4d4f;
color: #ff4d4f;
font-weight: 700;
}
.list-panel {
background: #fff;
overflow-y: auto;
padding: 0 0 12px;
min-height: 0;
}
.state-loading {
padding: 40px 0;
}
.product-list {
display: flex;
flex-direction: column;
}
.product-row {
display: grid;
grid-template-columns: 88px minmax(0, 1fr) 36px;
gap: 12px;
align-items: center;
width: 100%;
padding: 12px;
border: 0;
border-bottom: 1px solid #f1f5f9;
background: #fff;
text-align: left;
}
.cover {
width: 88px;
height: 88px;
border-radius: 10px;
overflow: hidden;
background: #111;
}
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.cover-fallback {
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
background: linear-gradient(145deg, #fff7ed, #ffe4cc);
color: #ff6a00;
font-size: 22px;
font-weight: 900;
}
.info h2 {
margin: 0 0 8px;
font-size: 15px;
color: #17233d;
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.price-row {
display: flex;
align-items: baseline;
gap: 6px;
}
.price-row strong {
color: #ff4d4f;
font-size: 18px;
font-weight: 800;
}
.price-row small {
color: #c0c8d4;
text-decoration: line-through;
font-size: 12px;
}
.buy-icon {
width: 28px;
height: 28px;
border-radius: 50%;
border: 1px solid #ffb4b4;
color: #ff4d4f;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 12px;
font-weight: 700;
}
.load-more {
margin: 12px;
width: calc(100% - 24px);
}
</style>
@@ -0,0 +1,339 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import MobilePayWaySelectPopup from '@/features/orders/components/MobilePayWaySelectPopup.vue'
import MobilePaymentCashierPopup from '@/features/orders/components/MobilePaymentCashierPopup.vue'
import { useMobilePayWaySelect } from '@/features/orders/composables/useMobilePayWaySelect'
import { useMobilePaymentCashier } from '@/features/orders/composables/useMobilePaymentCashier'
import {
cancelMyMohongOrder,
fetchMyMohongOrder,
mohongOrderStatusLabel,
queryMohongPayment,
startMohongPayment,
type MohongOrder,
} from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
const route = useRoute()
const router = useRouter()
const order = ref<MohongOrder | null>(null)
const loading = ref(true)
const acting = ref(false)
const payWaySelect = useMobilePayWaySelect()
const {
paymentPopupVisible,
activePayment,
payURL,
paymentQRCodeURL,
qrGenerating,
checkingPayment,
openMobilePaymentCashier,
refreshPaymentStatus,
} = useMobilePaymentCashier({
queryPayment: queryMohongPayment,
paidMessage: '支付成功',
})
const statusText = computed(() =>
order.value ? mohongOrderStatusLabel(order.value.status) : ''
)
onMounted(loadOrder)
async function loadOrder() {
loading.value = true
try {
order.value = await fetchMyMohongOrder(String(route.params.id))
} catch (error) {
showToast({ message: readError(error, '订单不存在'), icon: 'cross' })
} finally {
loading.value = false
}
}
async function handlePay() {
if (!order.value || acting.value) return
const payWay = await payWaySelect.select()
if (!payWay) return
acting.value = true
try {
const payment = await startMohongPayment(order.value.id, payWay)
if (payment.paid || payment.status === 'paid') {
showToast({ message: '支付成功', icon: 'passed' })
await loadOrder()
return
}
await openMobilePaymentCashier(payment, async () => {
await loadOrder()
})
} catch (error) {
showToast({ message: readError(error, '支付失败'), icon: 'cross' })
} finally {
acting.value = false
}
}
async function handleCancel() {
if (!order.value || acting.value) return
acting.value = true
try {
order.value = await cancelMyMohongOrder(order.value.id)
showToast({ message: '已取消', icon: 'passed' })
} catch (error) {
showToast({ message: readError(error, '取消失败'), icon: 'cross' })
} finally {
acting.value = false
}
}
async function copyText() {
if (!order.value?.copy_text) {
showToast({ message: '暂无可复制信息', icon: 'warning-o' })
return
}
try {
await navigator.clipboard.writeText(order.value.copy_text)
showToast({ message: '已复制订单信息', icon: 'passed' })
} catch {
showToast({ message: '复制失败', icon: 'cross' })
}
}
function openChat() {
if (!order.value?.conversation_id) {
showToast({ message: '群聊尚未创建', icon: 'warning-o' })
return
}
router.push(`/chats/${order.value.conversation_id}`)
}
</script>
<template>
<main class="order-shell">
<header class="page-header">
<button type="button" class="back-btn" @click="router.back()">
<van-icon name="arrow-left" :size="20" />
</button>
<h1>订单详情</h1>
</header>
<van-loading v-if="loading" class="state-loading" size="24px" vertical>加载中...</van-loading>
<template v-else-if="order">
<section class="panel status-panel">
<strong>{{ statusText }}</strong>
<p>订单号 {{ order.order_no }}</p>
</section>
<section class="panel product-panel">
<div class="cover">
<img v-if="order.product_cover_url" :src="order.product_cover_url" alt="" />
<span v-else></span>
</div>
<div>
<h2>{{ order.product_title }}</h2>
<p>
¥{{ order.unit_price || formatCent(order.unit_price_cent) }} × {{ order.quantity }}
{{ order.product_unit }}
</p>
<strong>合计 ¥{{ order.amount || formatCent(order.amount_cent) }}</strong>
</div>
</section>
<section v-if="order.copy_text" class="panel">
<div class="copy-head">
<h3>订单信息发给客服</h3>
<button type="button" @click="copyText">一键复制</button>
</div>
<pre class="copy-text">{{ order.copy_text }}</pre>
</section>
<section v-if="order.qrcode_url_snapshot" class="panel qr-panel">
<h3>客服二维码</h3>
<img :src="order.qrcode_url_snapshot" alt="客服二维码" />
</section>
<div class="actions">
<van-button
v-if="order.status === 'pending_payment'"
type="primary"
color="#ff6a00"
block
round
:loading="acting"
@click="handlePay"
>
去支付
</van-button>
<van-button
v-if="order.status === 'pending_payment'"
plain
block
round
:loading="acting"
@click="handleCancel"
>
取消订单
</van-button>
<van-button
v-if="order.conversation_id"
type="primary"
color="#ff6a00"
block
round
@click="openChat"
>
进入订单群
</van-button>
<van-button v-if="order.copy_text" plain block round @click="copyText">
复制订单信息
</van-button>
</div>
</template>
<van-empty v-else description="订单不存在" />
<MobilePayWaySelectPopup
v-model:show="payWaySelect.visible.value"
@choose="payWaySelect.choose"
@closed="payWaySelect.handleClosed"
/>
<MobilePaymentCashierPopup
v-model:show="paymentPopupVisible"
:payment="activePayment"
:pay-url="payURL"
:qr-code-url="paymentQRCodeURL"
:qr-generating="qrGenerating"
:checking="checkingPayment"
@refresh="refreshPaymentStatus(false)"
/>
</main>
</template>
<style scoped>
.order-shell {
min-height: 100vh;
background: #f5f7fb;
padding-bottom: 24px;
}
.page-header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
gap: 8px;
padding: 12px 14px;
background: #fff;
border-bottom: 1px solid #eef1f5;
}
.back-btn {
border: 0;
background: transparent;
}
.page-header h1 {
margin: 0;
font-size: 17px;
}
.state-loading {
padding: 48px 0;
}
.panel {
margin: 10px 12px;
padding: 14px;
border-radius: 14px;
background: #fff;
}
.status-panel strong {
display: block;
font-size: 20px;
color: #ff6a00;
margin-bottom: 4px;
}
.status-panel p {
margin: 0;
color: #8a94a6;
font-size: 13px;
}
.product-panel {
display: grid;
grid-template-columns: 72px 1fr;
gap: 12px;
}
.cover {
width: 72px;
height: 72px;
border-radius: 10px;
overflow: hidden;
background: #f0f3f8;
display: flex;
align-items: center;
justify-content: center;
color: #a0aec0;
}
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-panel h2 {
margin: 0 0 6px;
font-size: 15px;
}
.product-panel p {
margin: 0 0 6px;
color: #8a94a6;
font-size: 13px;
}
.product-panel strong {
color: #ff6a00;
}
.copy-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.copy-head h3,
.qr-panel h3 {
margin: 0;
font-size: 14px;
}
.copy-head button {
border: 0;
background: #fff4ea;
color: #ff6a00;
border-radius: 999px;
padding: 4px 10px;
font-size: 12px;
}
.copy-text {
margin: 0;
padding: 12px;
border-radius: 10px;
background: #f7f9fc;
color: #334155;
font-size: 13px;
line-height: 1.6;
white-space: pre-wrap;
word-break: break-all;
}
.qr-panel {
text-align: center;
}
.qr-panel img {
margin-top: 10px;
width: 180px;
height: 180px;
object-fit: contain;
border-radius: 12px;
background: #f7f9fc;
}
.actions {
padding: 8px 12px 20px;
display: flex;
flex-direction: column;
gap: 10px;
}
</style>
@@ -0,0 +1,154 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import {
fetchMyMohongOrders,
mohongOrderStatusLabel,
type MohongOrder,
} from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
const router = useRouter()
const loading = ref(false)
const orders = ref<MohongOrder[]>([])
onMounted(loadOrders)
async function loadOrders() {
loading.value = true
try {
const result = await fetchMyMohongOrders({ page: 1, page_size: 50 })
orders.value = result.items || []
} catch (error) {
showToast({ message: readError(error, '加载订单失败'), icon: 'cross' })
} finally {
loading.value = false
}
}
</script>
<template>
<main class="orders-shell">
<header class="page-header">
<button type="button" class="back-btn" @click="router.back()">
<van-icon name="arrow-left" :size="20" />
</button>
<h1>摸大红订单</h1>
</header>
<van-loading v-if="loading" class="state-loading" size="24px" vertical>加载中...</van-loading>
<van-empty v-else-if="orders.length === 0" description="暂无订单" />
<div v-else class="list">
<button
v-for="item in orders"
:key="item.id"
type="button"
class="card"
@click="router.push(`/mohong/orders/${item.id}`)"
>
<div class="top">
<span>{{ item.order_no }}</span>
<em>{{ mohongOrderStatusLabel(item.status) }}</em>
</div>
<div class="body">
<div class="cover">
<img v-if="item.product_cover_url" :src="item.product_cover_url" alt="" />
<span v-else></span>
</div>
<div>
<h2>{{ item.product_title }}</h2>
<p>x{{ item.quantity }} · ¥{{ item.amount || formatCent(item.amount_cent) }}</p>
</div>
</div>
</button>
</div>
</main>
</template>
<style scoped>
.orders-shell {
min-height: 100vh;
background: #f5f7fb;
}
.page-header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
gap: 8px;
padding: 12px 14px;
background: #fff;
border-bottom: 1px solid #eef1f5;
}
.back-btn {
border: 0;
background: transparent;
}
.page-header h1 {
margin: 0;
font-size: 17px;
}
.state-loading {
padding: 48px 0;
}
.list {
padding: 12px;
display: flex;
flex-direction: column;
gap: 10px;
}
.card {
width: 100%;
border: 0;
border-radius: 14px;
background: #fff;
padding: 12px;
text-align: left;
}
.top {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
font-size: 12px;
color: #8a94a6;
}
.top em {
font-style: normal;
color: #ff6a00;
font-weight: 600;
}
.body {
display: grid;
grid-template-columns: 64px 1fr;
gap: 10px;
}
.cover {
width: 64px;
height: 64px;
border-radius: 10px;
overflow: hidden;
background: #f0f3f8;
display: flex;
align-items: center;
justify-content: center;
color: #a0aec0;
}
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
}
.body h2 {
margin: 0 0 6px;
font-size: 15px;
color: #17233d;
}
.body p {
margin: 0;
color: #8a94a6;
font-size: 13px;
}
</style>
@@ -0,0 +1,531 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
createMohongOrder,
fetchMohongProduct,
queryMohongPayment,
startMohongPayment,
type MohongProduct,
} from '@/features/mohong/api/mohong'
import type { PaymentPayWay } from '@/features/orders/api/orders'
import { useOrderPaymentCashier } from '@/features/orders/composables/useOrderPaymentCashier'
import { useSessionStore } from '@/stores/session'
import { formatCent } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
const route = useRoute()
const router = useRouter()
const session = useSessionStore()
const product = ref<MohongProduct | null>(null)
const loading = ref(true)
const quantity = ref(1)
const submitting = ref(false)
const activeImage = ref('')
const payWayDialogVisible = ref(false)
let payWayResolver: ((value: PaymentPayWay | null) => void) | null = null
const cashier = useOrderPaymentCashier({
notifySuccess: msg => ElMessage.success(msg),
notifyError: msg => ElMessage.error(msg),
notifyInfo: msg => ElMessage.info(msg),
notifyFallback: msg => ElMessage.warning(msg),
paidMessage: '支付成功',
pollIntervalMs: 3000,
qrWidth: 240,
queryPayment: queryMohongPayment,
})
const images = computed(() => {
if (!product.value) return [] as string[]
const list = [...(product.value.image_urls || [])]
if (product.value.cover_url && !list.includes(product.value.cover_url)) {
list.unshift(product.value.cover_url)
}
return list
})
const totalPrice = computed(() => {
if (!product.value) return '0.0'
return formatCent(product.value.price_cent * quantity.value)
})
const canBuy = computed(() => {
if (!product.value) return false
if (product.value.stock === 0) return false
if (product.value.stock > 0 && quantity.value > product.value.stock) return false
return true
})
const activePayWayLabel = computed(() => {
const map: Record<string, string> = { WXZF: '微信', ZFBZF: '支付宝' }
return map[cashier.activePayment.value?.pay_way || ''] || '微信/支付宝'
})
onMounted(loadProduct)
async function loadProduct() {
loading.value = true
try {
product.value = await fetchMohongProduct(String(route.params.id))
activeImage.value = images.value[0] || ''
} catch (error) {
ElMessage.error(readError(error, '商品不存在'))
} finally {
loading.value = false
}
}
function selectPayWay(): Promise<PaymentPayWay | null> {
payWayDialogVisible.value = true
return new Promise(resolve => {
payWayResolver = resolve
})
}
function choosePayWay(payWay: PaymentPayWay) {
payWayResolver?.(payWay)
payWayResolver = null
payWayDialogVisible.value = false
}
function handlePayWayDialogClosed() {
payWayResolver?.(null)
payWayResolver = null
}
async function ensureAuthReady() {
if (!session.isLoggedIn) {
router.push({ path: '/login', query: { redirect: route.fullPath } })
return false
}
try {
await session.loadMe()
} catch {
// ignore
}
if (session.realnameStatus !== 'verified') {
router.push({ path: '/realname', query: { redirect: route.fullPath } })
return false
}
return true
}
async function handleBuy() {
if (!product.value || submitting.value) return
if (!(await ensureAuthReady())) return
if (!canBuy.value) {
ElMessage.warning('库存不足')
return
}
const payWay = await selectPayWay()
if (!payWay) return
submitting.value = true
try {
const order = await createMohongOrder(product.value.id, quantity.value)
const payment = await startMohongPayment(order.id, payWay)
if (payment.paid || payment.status === 'paid') {
ElMessage.success('支付成功')
await router.push(`/mohong/orders/${order.id}`)
return
}
await cashier.openPaymentCashier(payment, async () => {
await router.push(`/mohong/orders/${order.id}`)
})
} catch (error) {
ElMessage.error(readError(error, '下单失败'))
} finally {
submitting.value = false
}
}
</script>
<template>
<section v-loading="loading" class="mohong-detail-page">
<template v-if="product">
<div class="detail-layout">
<div class="gallery-panel">
<div class="main-image">
<img v-if="activeImage" :src="activeImage" :alt="product.title" />
<div v-else class="empty-image">暂无图片</div>
</div>
<div v-if="images.length > 1" class="thumbs">
<button
v-for="(url, idx) in images"
:key="idx"
type="button"
class="thumb"
:class="{ active: url === activeImage }"
@click="activeImage = url"
>
<img :src="url" :alt="`${product.title}-${idx + 1}`" />
</button>
</div>
</div>
<div class="info-panel">
<p class="eyebrow">摸大红商品</p>
<h1>{{ product.title }}</h1>
<p class="desc">{{ product.description || '暂无说明' }}</p>
<div class="price-box">
<div>
<small>售价</small>
<strong>¥{{ product.price || formatCent(product.price_cent) }}</strong>
<em>/ {{ product.unit || '份' }}</em>
</div>
<span v-if="product.original_price" class="origin">
原价 ¥{{ product.original_price }}
</span>
</div>
<div class="meta-rows">
<div class="meta-row">
<span>库存</span>
<strong>
<template v-if="product.stock < 0">充足</template>
<template v-else>{{ product.stock }}</template>
</strong>
</div>
<div class="meta-row">
<span>数量</span>
<el-input-number
v-model="quantity"
:min="1"
:max="product.stock > 0 ? product.stock : 99"
/>
</div>
<div class="meta-row">
<span>合计</span>
<strong class="total">¥{{ totalPrice }}</strong>
</div>
</div>
<div class="actions">
<el-button
type="primary"
size="large"
color="#ff6a00"
:loading="submitting"
:disabled="!canBuy"
@click="handleBuy"
>
{{ canBuy ? '立即购买' : '暂时缺货' }}
</el-button>
<el-button size="large" @click="router.push('/mohong')">返回列表</el-button>
</div>
<div class="tips">
<p>购买须知</p>
<ul>
<li>下单需登录并完成实名认证</li>
<li>支付成功后自动创建订单群发送固定客服二维码</li>
<li>群内与订单详情可一键复制订单信息发给客服</li>
</ul>
</div>
</div>
</div>
</template>
<el-empty v-else-if="!loading" description="商品不存在" />
<el-dialog
v-model="payWayDialogVisible"
title="选择支付方式"
width="420px"
append-to-body
@closed="handlePayWayDialogClosed"
>
<p class="pay-way-tip">选择渠道后将生成对应的支付二维码</p>
<div class="pay-way-options">
<button type="button" class="pay-way-option wechat" @click="choosePayWay('WXZF')">
<strong>微信支付</strong>
<small>使用微信扫码完成支付</small>
</button>
<button type="button" class="pay-way-option alipay" @click="choosePayWay('ZFBZF')">
<strong>支付宝支付</strong>
<small>使用支付宝扫码完成支付</small>
</button>
</div>
</el-dialog>
<el-dialog
v-model="cashier.paymentPopupVisible.value"
title="订单支付"
width="520px"
append-to-body
@closed="cashier.stopPaymentPolling"
>
<div v-if="cashier.activePayment.value" class="pay-dialog-body">
<div class="pay-amount">
支付金额
<strong>¥{{ formatCent(cashier.activePayment.value.amount_cent) }}</strong>
</div>
<div v-if="cashier.payURL.value" class="pay-qr">
<img
v-if="cashier.paymentQRCodeURL.value"
:src="cashier.paymentQRCodeURL.value"
alt="支付二维码"
/>
<p>请使用{{ activePayWayLabel }}扫码支付</p>
</div>
<p v-else class="pay-hint">支付单已创建请完成付款后刷新状态</p>
</div>
<template #footer>
<el-button
type="primary"
:loading="cashier.checkingPayment.value"
@click="cashier.refreshPaymentStatus(false)"
>
我已支付刷新状态
</el-button>
</template>
</el-dialog>
</section>
</template>
<style scoped>
.mohong-detail-page {
width: 100%;
max-width: 1200px;
}
.detail-layout {
display: grid;
grid-template-columns: minmax(0, 1.05fr) minmax(320px, 0.95fr);
gap: 28px;
align-items: start;
}
.gallery-panel,
.info-panel {
background: #fff;
border: 1px solid #eef1f5;
border-radius: 16px;
padding: 18px;
}
.main-image {
aspect-ratio: 1;
border-radius: 12px;
overflow: hidden;
background: #f3f6fb;
}
.main-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.empty-image {
display: flex;
height: 100%;
align-items: center;
justify-content: center;
color: #a0aec0;
}
.thumbs {
display: flex;
gap: 8px;
margin-top: 12px;
flex-wrap: wrap;
}
.thumb {
width: 64px;
height: 64px;
padding: 0;
border: 2px solid transparent;
border-radius: 10px;
overflow: hidden;
background: #f3f6fb;
cursor: pointer;
}
.thumb.active {
border-color: #ff6a00;
}
.thumb img {
width: 100%;
height: 100%;
object-fit: cover;
}
.eyebrow {
margin: 0 0 8px;
color: #ff6a00;
font-size: 13px;
font-weight: 700;
}
.info-panel h1 {
margin: 0 0 12px;
font-size: 28px;
color: #17233d;
line-height: 1.25;
}
.desc {
margin: 0 0 18px;
color: #6b7a90;
font-size: 14px;
line-height: 1.7;
white-space: pre-wrap;
}
.price-box {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 18px;
padding: 16px;
border-radius: 12px;
background: #fff7ed;
}
.price-box small {
display: block;
color: #9a3412;
font-size: 12px;
margin-bottom: 4px;
}
.price-box strong {
color: #ff6a00;
font-size: 32px;
font-weight: 900;
}
.price-box em {
margin-left: 6px;
color: #9a3412;
font-style: normal;
font-size: 14px;
}
.origin {
color: #b0b8c4;
text-decoration: line-through;
font-size: 13px;
}
.meta-rows {
display: grid;
gap: 14px;
margin-bottom: 20px;
}
.meta-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #6b7a90;
font-size: 14px;
}
.meta-row .total {
color: #ff6a00;
font-size: 22px;
}
.actions {
display: flex;
gap: 12px;
margin-bottom: 20px;
}
.tips {
padding-top: 16px;
border-top: 1px solid #eef1f5;
color: #6b7a90;
font-size: 13px;
}
.tips p {
margin: 0 0 8px;
color: #17233d;
font-weight: 700;
}
.tips ul {
margin: 0;
padding-left: 18px;
line-height: 1.7;
}
.pay-way-tip {
margin: 0 0 14px;
color: #6b7a90;
font-size: 13px;
}
.pay-way-options {
display: grid;
gap: 10px;
}
.pay-way-option {
display: grid;
gap: 4px;
width: 100%;
padding: 14px 16px;
border: 1px solid #e7edf6;
border-radius: 12px;
background: #fff;
text-align: left;
cursor: pointer;
}
.pay-way-option:hover {
border-color: #ff6a00;
}
.pay-way-option strong {
color: #17233d;
}
.pay-way-option small {
color: #8a94a6;
}
.pay-dialog-body {
display: grid;
gap: 16px;
justify-items: center;
text-align: center;
}
.pay-amount {
color: #6b7a90;
}
.pay-amount strong {
display: block;
margin-top: 6px;
color: #ff6a00;
font-size: 28px;
}
.pay-qr img {
width: 220px;
height: 220px;
border-radius: 12px;
background: #f7f9fc;
}
.pay-hint {
color: #6b7a90;
}
@media (max-width: 960px) {
.detail-layout {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,406 @@
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Tickets } from '@element-plus/icons-vue'
import MohongProductCard from '@/features/mohong/components/MohongProductCard.vue'
import {
fetchMohongCategories,
fetchMohongProducts,
type MohongCategory,
type MohongProduct,
} from '@/features/mohong/api/mohong'
import { readError } from '@/shared/utils/error'
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const loadingMore = ref(false)
const products = ref<MohongProduct[]>([])
const categories = ref<MohongCategory[]>([])
const total = ref(0)
const page = ref(1)
const hasMore = ref(true)
const keyword = ref('')
const activeCategoryId = ref<number | null>(null)
let searchTimer: ReturnType<typeof setTimeout> | null = null
onMounted(async () => {
await loadCategories()
applyRouteQuery()
await loadProducts(true)
})
watch(
() => route.query,
() => {
applyRouteQuery()
loadProducts(true)
}
)
function applyRouteQuery() {
const q = route.query
keyword.value = typeof q.keyword === 'string' ? q.keyword : ''
const cat = Number(q.category_id || 0)
activeCategoryId.value = cat > 0 ? cat : null
}
async function loadCategories() {
try {
categories.value = await fetchMohongCategories()
// 默认选中「大红」或第一个有商品的分类
if (!activeCategoryId.value && categories.value.length) {
const dahong = categories.value.find(c => c.name === '大红')
const first = categories.value.find(c => c.product_count > 0) || categories.value[0]
if (dahong || first) {
activeCategoryId.value = (dahong || first)!.id
syncQuery()
}
}
} catch (error) {
ElMessage.error(readError(error, '加载分类失败'))
}
}
async function loadProducts(reset = true) {
if (loadingMore.value) return
if (reset) {
loading.value = true
page.value = 1
hasMore.value = true
} else {
if (!hasMore.value) return
loadingMore.value = true
}
try {
const result = await fetchMohongProducts({
page: page.value,
page_size: 24,
keyword: keyword.value.trim() || undefined,
category_id: activeCategoryId.value || undefined,
})
const items = result.items || []
products.value = reset ? items : [...products.value, ...items]
total.value = result.total || 0
hasMore.value = products.value.length < total.value
page.value += 1
} catch (error) {
ElMessage.error(readError(error, '加载商品失败'))
} finally {
loading.value = false
loadingMore.value = false
}
}
function selectCategory(id: number | null) {
activeCategoryId.value = id
syncQuery()
loadProducts(true)
}
function onKeywordInput() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
syncQuery()
loadProducts(true)
}, 280)
}
function syncQuery() {
const query: Record<string, string> = {}
if (keyword.value.trim()) query.keyword = keyword.value.trim()
if (activeCategoryId.value) query.category_id = String(activeCategoryId.value)
router.replace({ path: '/mohong', query })
}
const activeCategoryName = () => {
if (!activeCategoryId.value) return '全部'
return categories.value.find(c => c.id === activeCategoryId.value)?.name || '全部'
}
</script>
<template>
<section class="mohong-pc-page">
<header class="toolbar">
<div class="title-block">
<h1>摸大红</h1>
<span class="count">{{ total }} </span>
<span class="tip">{{ activeCategoryName() }} · 支付后自动进群</span>
</div>
<div class="actions">
<div class="search-box">
<el-icon><Search /></el-icon>
<input
v-model="keyword"
type="search"
placeholder="搜索商品名称"
@input="onKeywordInput"
/>
</div>
<el-button size="small" :icon="Tickets" @click="router.push('/mohong/orders')">
我的订单
</el-button>
<el-button size="small" plain @click="router.push('/')">租号大厅</el-button>
</div>
</header>
<div class="shop-layout">
<aside class="cat-sidebar">
<button
type="button"
class="cat-item"
:class="{ active: !activeCategoryId }"
@click="selectCategory(null)"
>
全部
</button>
<button
v-for="cat in categories"
:key="cat.id"
type="button"
class="cat-item"
:class="{ active: activeCategoryId === cat.id }"
@click="selectCategory(cat.id)"
>
<span>{{ cat.name }}</span>
<em v-if="cat.product_count">{{ cat.product_count }}</em>
</button>
</aside>
<div class="shop-main">
<div v-if="!loading && products.length === 0" class="empty-state">
<strong>暂无商品</strong>
<span>试试切换分类或清空搜索关键词</span>
</div>
<div v-else v-loading="loading" class="product-grid">
<MohongProductCard v-for="item in products" :key="item.id" :product="item" />
</div>
<div v-if="!loading && products.length" class="load-state">
<el-button v-if="hasMore" :loading="loadingMore" @click="loadProducts(false)">
加载更多
</el-button>
<span v-else class="end">已经到底了</span>
</div>
</div>
</div>
</section>
</template>
<style scoped>
.mohong-pc-page {
display: grid;
gap: 14px;
width: 100%;
}
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
width: 100%;
padding: 8px 0;
}
.title-block {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 8px 12px;
min-width: 0;
}
.title-block h1 {
margin: 0;
color: #17233d;
font-size: 20px;
font-weight: 800;
}
.count {
padding: 1px 8px;
border-radius: 999px;
background: #fff4ea;
color: #ff6a00;
font-size: 12px;
font-weight: 700;
}
.tip {
color: #8a94a6;
font-size: 12px;
}
.actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.search-box {
display: flex;
align-items: center;
gap: 6px;
width: 220px;
height: 32px;
padding: 0 10px;
border: 1px solid #e4e7ed;
border-radius: 8px;
background: #fff;
color: #94a3b8;
}
.search-box input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
color: #17233d;
font-size: 13px;
}
.shop-layout {
display: grid;
grid-template-columns: 140px minmax(0, 1fr);
gap: 16px;
align-items: start;
min-height: 480px;
}
.cat-sidebar {
position: sticky;
top: 12px;
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px 0;
border-radius: 12px;
background: #fff;
border: 1px solid #eef1f5;
overflow: hidden;
}
.cat-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
padding: 12px 14px;
border: 0;
border-left: 3px solid transparent;
background: transparent;
color: #52616f;
font-size: 14px;
text-align: left;
cursor: pointer;
transition:
background 0.15s,
color 0.15s,
border-color 0.15s;
}
.cat-item:hover {
background: #f8fafc;
color: #17233d;
}
.cat-item.active {
background: #fff7ed;
border-left-color: #ff6a00;
color: #ff6a00;
font-weight: 700;
}
.cat-item em {
font-style: normal;
color: #b0b8c4;
font-size: 12px;
font-weight: 600;
}
.cat-item.active em {
color: #ff9a4d;
}
.shop-main {
min-width: 0;
}
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 14px;
width: 100%;
}
.product-grid :deep(.mohong-card) {
justify-self: center;
}
.empty-state {
display: grid;
gap: 6px;
justify-items: center;
width: 100%;
padding: 64px 20px;
border-radius: 14px;
border: 1px dashed #dbe3ee;
background: #fff;
color: #8a94a6;
}
.empty-state strong {
color: #17233d;
}
.load-state {
display: flex;
justify-content: center;
width: 100%;
padding: 12px 0 8px;
}
.end {
color: #b0b8c4;
font-size: 12px;
}
@media (max-width: 900px) {
.shop-layout {
grid-template-columns: 1fr;
}
.cat-sidebar {
position: static;
flex-direction: row;
overflow-x: auto;
padding: 6px;
gap: 4px;
}
.cat-item {
flex: 0 0 auto;
border-left: 0;
border-radius: 8px;
padding: 8px 12px;
white-space: nowrap;
}
.cat-item.active {
border-left-color: transparent;
}
.toolbar {
flex-direction: column;
align-items: stretch;
}
.search-box {
width: 100%;
}
}
</style>
@@ -0,0 +1,437 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
cancelMyMohongOrder,
fetchMyMohongOrder,
mohongOrderStatusLabel,
queryMohongPayment,
startMohongPayment,
type MohongOrder,
} from '@/features/mohong/api/mohong'
import type { PaymentPayWay } from '@/features/orders/api/orders'
import { useOrderPaymentCashier } from '@/features/orders/composables/useOrderPaymentCashier'
import { formatCent } from '@/shared/utils/money'
import { formatDateTime } from '@/shared/utils/time'
import { readError } from '@/shared/utils/error'
const route = useRoute()
const router = useRouter()
const order = ref<MohongOrder | null>(null)
const loading = ref(true)
const acting = ref(false)
const payWayDialogVisible = ref(false)
let payWayResolver: ((value: PaymentPayWay | null) => void) | null = null
const cashier = useOrderPaymentCashier({
notifySuccess: msg => ElMessage.success(msg),
notifyError: msg => ElMessage.error(msg),
notifyInfo: msg => ElMessage.info(msg),
notifyFallback: msg => ElMessage.warning(msg),
paidMessage: '支付成功',
pollIntervalMs: 3000,
qrWidth: 240,
queryPayment: queryMohongPayment,
})
const statusText = computed(() =>
order.value ? mohongOrderStatusLabel(order.value.status) : ''
)
const activePayWayLabel = computed(() => {
const map: Record<string, string> = { WXZF: '微信', ZFBZF: '支付宝' }
return map[cashier.activePayment.value?.pay_way || ''] || '微信/支付宝'
})
onMounted(loadOrder)
async function loadOrder() {
loading.value = true
try {
order.value = await fetchMyMohongOrder(String(route.params.id))
} catch (error) {
ElMessage.error(readError(error, '订单不存在'))
} finally {
loading.value = false
}
}
function selectPayWay(): Promise<PaymentPayWay | null> {
payWayDialogVisible.value = true
return new Promise(resolve => {
payWayResolver = resolve
})
}
function choosePayWay(payWay: PaymentPayWay) {
payWayResolver?.(payWay)
payWayResolver = null
payWayDialogVisible.value = false
}
function handlePayWayDialogClosed() {
payWayResolver?.(null)
payWayResolver = null
}
async function handlePay() {
if (!order.value || acting.value) return
const payWay = await selectPayWay()
if (!payWay) return
acting.value = true
try {
const payment = await startMohongPayment(order.value.id, payWay)
if (payment.paid || payment.status === 'paid') {
ElMessage.success('支付成功')
await loadOrder()
return
}
await cashier.openPaymentCashier(payment, async () => {
await loadOrder()
})
} catch (error) {
ElMessage.error(readError(error, '支付失败'))
} finally {
acting.value = false
}
}
async function handleCancel() {
if (!order.value || acting.value) return
acting.value = true
try {
order.value = await cancelMyMohongOrder(order.value.id)
ElMessage.success('已取消')
} catch (error) {
ElMessage.error(readError(error, '取消失败'))
} finally {
acting.value = false
}
}
async function copyText() {
if (!order.value?.copy_text) {
ElMessage.warning('暂无可复制信息')
return
}
try {
await navigator.clipboard.writeText(order.value.copy_text)
ElMessage.success('已复制订单信息')
} catch {
ElMessage.error('复制失败')
}
}
function openChat() {
if (!order.value?.conversation_id) {
ElMessage.warning('群聊尚未创建')
return
}
router.push(`/messages/${order.value.conversation_id}`)
}
</script>
<template>
<section v-loading="loading" class="order-detail-page">
<template v-if="order">
<header class="page-header">
<div>
<p class="eyebrow">订单详情</p>
<h1>{{ statusText }}</h1>
<p class="sub">订单号 {{ order.order_no }} · {{ formatDateTime(order.created_at) }}</p>
</div>
<el-button @click="router.push('/mohong/orders')">返回列表</el-button>
</header>
<div class="layout">
<div class="main-card">
<div class="product-row">
<div class="cover">
<img v-if="order.product_cover_url" :src="order.product_cover_url" alt="" />
<span v-else></span>
</div>
<div>
<h2>{{ order.product_title }}</h2>
<p>
¥{{ order.unit_price || formatCent(order.unit_price_cent) }} × {{ order.quantity }}
{{ order.product_unit }}
</p>
<strong>合计 ¥{{ order.amount || formatCent(order.amount_cent) }}</strong>
</div>
</div>
<div v-if="order.copy_text" class="copy-box">
<div class="copy-head">
<h3>订单信息发给客服</h3>
<el-button type="primary" plain size="small" @click="copyText">一键复制</el-button>
</div>
<pre>{{ order.copy_text }}</pre>
</div>
<div v-if="order.qrcode_url_snapshot" class="qr-box">
<h3>客服二维码</h3>
<img :src="order.qrcode_url_snapshot" alt="客服二维码" />
</div>
</div>
<aside class="side-card">
<h3>操作</h3>
<el-button
v-if="order.status === 'pending_payment'"
type="primary"
color="#ff6a00"
:loading="acting"
@click="handlePay"
>
去支付
</el-button>
<el-button
v-if="order.status === 'pending_payment'"
:loading="acting"
@click="handleCancel"
>
取消订单
</el-button>
<el-button v-if="order.conversation_id" type="primary" plain @click="openChat">
进入订单群
</el-button>
<el-button v-if="order.copy_text" plain @click="copyText">复制订单信息</el-button>
<el-button plain @click="router.push('/mohong')">继续选购</el-button>
</aside>
</div>
</template>
<el-empty v-else-if="!loading" description="订单不存在" />
<el-dialog
v-model="payWayDialogVisible"
title="选择支付方式"
width="420px"
append-to-body
@closed="handlePayWayDialogClosed"
>
<div class="pay-way-options">
<button type="button" class="pay-way-option" @click="choosePayWay('WXZF')">
<strong>微信支付</strong>
</button>
<button type="button" class="pay-way-option" @click="choosePayWay('ZFBZF')">
<strong>支付宝支付</strong>
</button>
</div>
</el-dialog>
<el-dialog
v-model="cashier.paymentPopupVisible.value"
title="订单支付"
width="520px"
append-to-body
@closed="cashier.stopPaymentPolling"
>
<div v-if="cashier.activePayment.value" class="pay-dialog-body">
<div class="pay-amount">
支付金额
<strong>¥{{ formatCent(cashier.activePayment.value.amount_cent) }}</strong>
</div>
<div v-if="cashier.paymentQRCodeURL.value" class="pay-qr">
<img :src="cashier.paymentQRCodeURL.value" alt="支付二维码" />
<p>请使用{{ activePayWayLabel }}扫码支付</p>
</div>
</div>
<template #footer>
<el-button
type="primary"
:loading="cashier.checkingPayment.value"
@click="cashier.refreshPaymentStatus(false)"
>
我已支付刷新状态
</el-button>
</template>
</el-dialog>
</section>
</template>
<style scoped>
.order-detail-page {
width: 100%;
max-width: 1100px;
display: grid;
gap: 18px;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.eyebrow {
margin: 0 0 6px;
color: #ff6a00;
font-size: 13px;
font-weight: 700;
}
.page-header h1 {
margin: 0 0 6px;
font-size: 28px;
color: #17233d;
}
.sub {
margin: 0;
color: #8a94a6;
font-size: 13px;
}
.layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 240px;
gap: 16px;
align-items: start;
}
.main-card,
.side-card {
background: #fff;
border: 1px solid #eef1f5;
border-radius: 16px;
padding: 18px;
}
.product-row {
display: grid;
grid-template-columns: 88px 1fr;
gap: 14px;
margin-bottom: 18px;
}
.cover {
width: 88px;
height: 88px;
border-radius: 12px;
overflow: hidden;
background: #f3f6fb;
display: flex;
align-items: center;
justify-content: center;
color: #a0aec0;
}
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-row h2 {
margin: 0 0 8px;
font-size: 18px;
}
.product-row p {
margin: 0 0 8px;
color: #8a94a6;
}
.product-row strong {
color: #ff6a00;
font-size: 18px;
}
.copy-box,
.qr-box {
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #eef1f5;
}
.copy-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.copy-box h3,
.qr-box h3,
.side-card h3 {
margin: 0;
font-size: 15px;
color: #17233d;
}
.copy-box pre {
margin: 0;
padding: 12px;
border-radius: 10px;
background: #f7f9fc;
white-space: pre-wrap;
font-size: 13px;
line-height: 1.6;
color: #334155;
}
.qr-box {
text-align: center;
}
.qr-box img {
margin-top: 12px;
width: 180px;
height: 180px;
object-fit: contain;
border-radius: 12px;
background: #f7f9fc;
}
.side-card {
display: grid;
gap: 10px;
}
.side-card :deep(.el-button) {
width: 100%;
margin: 0;
}
.pay-way-options {
display: grid;
gap: 10px;
}
.pay-way-option {
width: 100%;
padding: 14px 16px;
border: 1px solid #e7edf6;
border-radius: 12px;
background: #fff;
text-align: left;
cursor: pointer;
}
.pay-dialog-body {
display: grid;
gap: 14px;
justify-items: center;
text-align: center;
}
.pay-amount strong {
display: block;
margin-top: 6px;
color: #ff6a00;
font-size: 28px;
}
.pay-qr img {
width: 220px;
height: 220px;
}
@media (max-width: 900px) {
.layout {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
fetchMyMohongOrders,
mohongOrderStatusLabel,
type MohongOrder,
} from '@/features/mohong/api/mohong'
import { formatCent } from '@/shared/utils/money'
import { formatDateTime } from '@/shared/utils/time'
import { readError } from '@/shared/utils/error'
const router = useRouter()
const loading = ref(false)
const orders = ref<MohongOrder[]>([])
onMounted(loadOrders)
async function loadOrders() {
loading.value = true
try {
const result = await fetchMyMohongOrders({ page: 1, page_size: 50 })
orders.value = result.items || []
} catch (error) {
ElMessage.error(readError(error, '加载订单失败'))
} finally {
loading.value = false
}
}
</script>
<template>
<section class="mohong-orders-page">
<header class="page-header">
<div>
<p class="eyebrow">My Orders</p>
<h1>摸大红订单</h1>
</div>
<el-button @click="router.push('/mohong')">返回商品列表</el-button>
</header>
<el-table v-loading="loading" :data="orders" border stripe empty-text="暂无订单">
<el-table-column prop="order_no" label="订单号" min-width="180" />
<el-table-column prop="product_title" label="商品" min-width="160" />
<el-table-column label="数量" width="80" prop="quantity" />
<el-table-column label="金额" width="110">
<template #default="{ row }">¥{{ row.amount || formatCent(row.amount_cent) }}</template>
</el-table-column>
<el-table-column label="状态" width="110">
<template #default="{ row }">{{ mohongOrderStatusLabel(row.status) }}</template>
</el-table-column>
<el-table-column label="下单时间" min-width="170">
<template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
</el-table-column>
<el-table-column label="操作" width="120" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="router.push(`/mohong/orders/${row.id}`)">
详情
</el-button>
</template>
</el-table-column>
</el-table>
</section>
</template>
<style scoped>
.mohong-orders-page {
display: grid;
gap: 18px;
width: 100%;
max-width: 1200px;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.eyebrow {
margin: 0 0 8px;
color: #ff6a00;
font-size: 13px;
font-weight: 700;
}
.page-header h1 {
margin: 0;
font-size: 28px;
color: #17233d;
}
</style>
@@ -1,5 +1,6 @@
import { showDialog, showToast } from 'vant'
import type { PaymentOrder } from '@/features/orders/api/orders'
import {
paymentPayURL,
useOrderPaymentCashier,
@@ -14,7 +15,11 @@ export { paymentPayURL as mobilePaymentPayURL }
* 并处理微信 / 支付宝内嵌浏览器的直接跳转拉起支付。对外 API 名保持不变,
* Mobile 视图无需改动。
*/
export function useMobilePaymentCashier() {
export function useMobilePaymentCashier(options?: {
queryPayment?: (orderId: number) => Promise<PaymentOrder>
paidMessage?: string
}) {
function isInAppPaymentBrowser(): boolean {
if (typeof navigator === 'undefined') return false
const ua = navigator.userAgent || ''
@@ -32,9 +37,10 @@ export function useMobilePaymentCashier() {
confirmButtonText: '知道了',
})
},
paidMessage: '支付成功,正在进入群消息',
paidMessage: options?.paidMessage || '支付成功,正在进入群消息',
pollIntervalMs: 2500,
qrWidth: 220,
queryPayment: options?.queryPayment,
openExternalURL: url => {
if (isHTTPURL(url) && isInAppPaymentBrowser()) {
window.location.href = url
@@ -41,6 +41,11 @@ export interface UseOrderPaymentCashierOptions {
*/
openExternalURL?: (url: string) => boolean
/** 弹窗显隐控制方式。PC 用 el-dialogv-model 一个 ref),Mobile 用 van-popup。返回 true 表示用 reffalse 表示 composable 内部 ref。 */
/**
* 自定义支付状态查询。默认走租号订单 `/orders/:id/query-payment`。
* 摸大红等独立业务可注入自己的查询函数。
*/
queryPayment?: (orderId: number) => Promise<PaymentOrder>
}
/**
@@ -131,7 +136,8 @@ export function useOrderPaymentCashier(options: UseOrderPaymentCashierOptions) {
checkingPayment.value = true
const previousPayURL = payURL.value
try {
const payment = await queryOrderPayment(activePayment.value.order_id)
const query = options.queryPayment || queryOrderPayment
const payment = await query(activePayment.value.order_id)
activePayment.value = payment
if (payment.paid) {
await handlePaid()
+25
View File
@@ -15,6 +15,7 @@ import {
Money,
Operation,
Picture,
Present,
ScaleToOriginal,
Service,
Shop,
@@ -103,6 +104,30 @@ const allNavGroups: NavGroup[] = [
icon: DocumentChecked,
permission: 'listing:approve',
},
{
label: '摸大红分类',
to: adminPath('mohong/categories'),
icon: Present,
permission: 'mohong:category',
},
{
label: '摸大红商品',
to: adminPath('mohong/products'),
icon: Present,
permission: 'mohong:product_view',
},
{
label: '摸大红订单',
to: adminPath('mohong/orders'),
icon: Tickets,
permission: 'mohong:order_view',
},
{
label: '摸大红配置',
to: adminPath('mohong/config'),
icon: Setting,
permission: 'mohong:config',
},
],
},
{
+24
View File
@@ -72,6 +72,30 @@ export const adminRoutes: RouteRecordRaw[] = [
component: () => import('@/features/admin/views/AdminListingReviewView.vue'),
meta: adminMeta,
},
{
path: adminPath('mohong/categories'),
name: 'admin-mohong-categories',
component: () => import('@/features/admin/views/AdminMohongCategoriesView.vue'),
meta: adminMeta,
},
{
path: adminPath('mohong/products'),
name: 'admin-mohong-products',
component: () => import('@/features/admin/views/AdminMohongProductsView.vue'),
meta: adminMeta,
},
{
path: adminPath('mohong/orders'),
name: 'admin-mohong-orders',
component: () => import('@/features/admin/views/AdminMohongOrdersView.vue'),
meta: adminMeta,
},
{
path: adminPath('mohong/config'),
name: 'admin-mohong-config',
component: () => import('@/features/admin/views/AdminMohongConfigView.vue'),
meta: adminMeta,
},
{
path: adminPath('disputes'),
name: 'admin-disputes',
+6
View File
@@ -23,6 +23,9 @@ export function getMobilePath(path: string): string {
if (path === '/listings' || path.startsWith('/listings/')) {
return `/m${path}`
}
if (path === '/mohong' || path.startsWith('/mohong/')) {
return `/m${path}`
}
if (path === '/orders' || path.startsWith('/orders/')) {
return `/m${path}`
}
@@ -65,6 +68,9 @@ export function getPcPath(path: string): string {
if (subPath === '/listings' || subPath.startsWith('/listings/')) {
return subPath
}
if (subPath === '/mohong' || subPath.startsWith('/mohong/')) {
return subPath
}
if (subPath === '/orders' || subPath.startsWith('/orders/')) {
return subPath
}
+24
View File
@@ -91,6 +91,30 @@ export const mobileRoutes: RouteRecordRaw[] = [
component: () => import('@/features/wallet/views/MobileWithdrawalView.vue'),
meta: { layout: 'blank', requiresAuth: true },
},
{
path: '/m/mohong',
name: 'mobile-mohong-list',
component: () => import('@/features/mohong/views/MobileMohongListView.vue'),
meta: { layout: 'blank' },
},
{
path: '/m/mohong/orders',
name: 'mobile-mohong-orders',
component: () => import('@/features/mohong/views/MobileMohongOrdersView.vue'),
meta: { layout: 'blank', requiresAuth: true },
},
{
path: '/m/mohong/orders/:id',
name: 'mobile-mohong-order-detail',
component: () => import('@/features/mohong/views/MobileMohongOrderDetailView.vue'),
meta: { layout: 'blank', requiresAuth: true },
},
{
path: '/m/mohong/:id',
name: 'mobile-mohong-detail',
component: () => import('@/features/mohong/views/MobileMohongDetailView.vue'),
meta: { layout: 'blank' },
},
{
path: '/m/orders',
name: 'mobile-orders',
+23
View File
@@ -16,4 +16,27 @@ export const publicRoutes: RouteRecordRaw[] = [
name: 'listing-detail',
component: () => import('@/features/listings/views/ListingDetailView.vue'),
},
// 摸大红 PC 端;移动端访问会被守卫重写到 /m/mohong*
{
path: '/mohong',
name: 'mohong-list',
component: () => import('@/features/mohong/views/MohongListView.vue'),
},
{
path: '/mohong/orders',
name: 'mohong-orders',
component: () => import('@/features/mohong/views/MohongOrdersView.vue'),
meta: { requiresAuth: true },
},
{
path: '/mohong/orders/:id',
name: 'mohong-order-detail',
component: () => import('@/features/mohong/views/MohongOrderDetailView.vue'),
meta: { requiresAuth: true },
},
{
path: '/mohong/:id',
name: 'mohong-detail',
component: () => import('@/features/mohong/views/MohongDetailView.vue'),
},
]
+14 -2
View File
@@ -348,19 +348,31 @@
}
/* ========== Button Enhancements ========== */
.el-button--primary:not(.is-text) {
/* 仅实体主按钮强制白字;link/text 需保留主题色,否则表格「编辑」等会白字看不见 */
.el-button--primary:not(.is-text):not(.is-link) {
font-weight: 700 !important;
--el-button-text-color: #ffffff;
--el-button-hover-text-color: #ffffff;
--el-button-active-text-color: #ffffff;
}
.el-button--primary:not(.is-text) span {
.el-button--primary:not(.is-text):not(.is-link) span {
color: #ffffff !important;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
font-weight: 700;
}
.el-button.is-link.el-button--primary {
--el-button-text-color: var(--el-color-primary);
--el-button-hover-text-color: var(--el-color-primary-light-3);
--el-button-active-text-color: var(--el-color-primary-dark-2);
}
.el-button.is-link.el-button--primary span {
color: inherit !important;
text-shadow: none;
}
.eyebrow {
margin: 0 0 8px;
color: #4f7cff;