feat: 添加购买分组功能,替代跨分类购物选项
Build and Push Docker Image / build-and-push (push) Successful in 1m0s
Build and Push Docker Image / deploy (push) Successful in 7s
Docker Build / Build and Push Docker Image (push) Has been cancelled
Docker Build / Deploy to Server (push) Has been cancelled

This commit is contained in:
2026-07-05 21:51:32 +08:00
parent b26fea9621
commit 4e86a9a6ad
12 changed files with 336 additions and 67 deletions
+13 -13
View File
@@ -49,17 +49,17 @@ func (h *CategoryHandler) Create(c *gin.Context) {
} }
category := models.Category{ category := models.Category{
Name: req.Name, Name: req.Name,
Description: req.Description, Description: req.Description,
ParentID: req.ParentID, ParentID: req.ParentID,
MinAmount: req.MinAmount, PurchaseGroupID: req.PurchaseGroupID,
MaxAmount: req.MaxAmount, MinAmount: req.MinAmount,
MinQuantity: req.MinQuantity, MaxAmount: req.MaxAmount,
MaxQuantity: req.MaxQuantity, MinQuantity: req.MinQuantity,
MinWeight: req.MinWeight, MaxQuantity: req.MaxQuantity,
MaxWeight: req.MaxWeight, MinWeight: req.MinWeight,
AllowCrossCategory: req.AllowCrossCategory != nil && *req.AllowCrossCategory, MaxWeight: req.MaxWeight,
SortOrder: req.SortOrder, SortOrder: req.SortOrder,
} }
if err := utils.DB.Create(&category).Error; err != nil { if err := utils.DB.Create(&category).Error; err != nil {
@@ -123,8 +123,8 @@ func (h *CategoryHandler) Update(c *gin.Context) {
if req.SortOrder != nil { if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder updates["sort_order"] = *req.SortOrder
} }
if req.AllowCrossCategory != nil { if req.PurchaseGroupID != nil {
updates["allow_cross_category"] = *req.AllowCrossCategory updates["purchase_group_id"] = *req.PurchaseGroupID
} }
utils.DB.Model(&category).Updates(updates) utils.DB.Model(&category).Updates(updates)
@@ -0,0 +1,105 @@
package handlers
import (
"net/http"
"strconv"
"sale/internal/models"
"sale/internal/schemas"
"sale/internal/utils"
"github.com/gin-gonic/gin"
)
type PurchaseGroupHandler struct{}
func NewPurchaseGroupHandler() *PurchaseGroupHandler {
return &PurchaseGroupHandler{}
}
func (h *PurchaseGroupHandler) List(c *gin.Context) {
var groups []models.PurchaseGroup
utils.DB.Order("sort_order ASC, id ASC").Preload("Categories").Find(&groups)
c.JSON(http.StatusOK, gin.H{"data": groups})
}
func (h *PurchaseGroupHandler) Create(c *gin.Context) {
var req schemas.CreatePurchaseGroupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var existing models.PurchaseGroup
if err := utils.DB.Where("name = ?", req.Name).First(&existing).Error; err == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "分组名称已存在"})
return
}
group := models.PurchaseGroup{
Name: req.Name,
Description: req.Description,
SortOrder: req.SortOrder,
}
if err := utils.DB.Create(&group).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create purchase group"})
return
}
c.JSON(http.StatusCreated, gin.H{"data": group})
}
func (h *PurchaseGroupHandler) Update(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var group models.PurchaseGroup
if err := utils.DB.First(&group, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Purchase group not found"})
return
}
var req schemas.UpdatePurchaseGroupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.Name != nil && *req.Name != group.Name {
var existing models.PurchaseGroup
if err := utils.DB.Where("name = ? AND id != ?", *req.Name, id).First(&existing).Error; err == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "分组名称已存在"})
return
}
}
updates := make(map[string]interface{})
if req.Name != nil {
updates["name"] = *req.Name
}
if req.Description != nil {
updates["description"] = *req.Description
}
if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder
}
utils.DB.Model(&group).Updates(updates)
c.JSON(http.StatusOK, gin.H{"data": group})
}
func (h *PurchaseGroupHandler) Delete(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var categoryCount int64
utils.DB.Model(&models.Category{}).Where("purchase_group_id = ?", id).Count(&categoryCount)
if categoryCount > 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "该分组下有分类,无法删除"})
return
}
if err := utils.DB.Delete(&models.PurchaseGroup{}, id).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete purchase group"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Purchase group deleted successfully"})
}
+9
View File
@@ -26,6 +26,7 @@ func SetupRoutes(r *gin.Engine) {
paymentChannelHandler := handlers.NewPaymentChannelHandler() paymentChannelHandler := handlers.NewPaymentChannelHandler()
paymentHandler := handlers.NewPaymentHandler() paymentHandler := handlers.NewPaymentHandler()
logHandler := handlers.NewLogHandler() logHandler := handlers.NewLogHandler()
purchaseGroupHandler := handlers.NewPurchaseGroupHandler()
r.Use(middlewares.CORSMiddleware()) r.Use(middlewares.CORSMiddleware())
@@ -154,6 +155,14 @@ func SetupRoutes(r *gin.Engine) {
adminCategories.DELETE("/:id", categoryHandler.Delete) adminCategories.DELETE("/:id", categoryHandler.Delete)
} }
adminPurchaseGroups := admin.Group("/purchase-groups")
{
adminPurchaseGroups.GET("", purchaseGroupHandler.List)
adminPurchaseGroups.POST("", purchaseGroupHandler.Create)
adminPurchaseGroups.PUT("/:id", purchaseGroupHandler.Update)
adminPurchaseGroups.DELETE("/:id", purchaseGroupHandler.Delete)
}
adminBrands := admin.Group("/brands") adminBrands := admin.Group("/brands")
{ {
adminBrands.GET("", brandHandler.List) adminBrands.GET("", brandHandler.List)
+18 -17
View File
@@ -7,23 +7,24 @@ import (
) )
type Category struct { type Category struct {
ID uint `gorm:"primaryKey" json:"id"` ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:100;not null;uniqueIndex" json:"name"` Name string `gorm:"size:100;not null;uniqueIndex" json:"name"`
Description string `json:"description"` Description string `json:"description"`
ParentID *uint `json:"parent_id"` ParentID *uint `json:"parent_id"`
MinAmount *float64 `json:"min_amount"` PurchaseGroupID *uint `json:"purchase_group_id"`
MaxAmount *float64 `json:"max_amount"` PurchaseGroup *PurchaseGroup `gorm:"foreignKey:PurchaseGroupID" json:"purchase_group,omitempty"`
MinQuantity *int `json:"min_quantity"` MinAmount *float64 `json:"min_amount"`
MaxQuantity *int `json:"max_quantity"` MaxAmount *float64 `json:"max_amount"`
MinWeight *float64 `json:"min_weight"` MinQuantity *int `json:"min_quantity"`
MaxWeight *float64 `json:"max_weight"` MaxQuantity *int `json:"max_quantity"`
AllowCrossCategory bool `gorm:"default:false" json:"allow_cross_category"` MinWeight *float64 `json:"min_weight"`
SortOrder int `gorm:"default:0" json:"sort_order"` MaxWeight *float64 `json:"max_weight"`
CreatedAt time.Time `json:"created_at"` SortOrder int `gorm:"default:0" json:"sort_order"`
UpdatedAt time.Time `json:"updated_at"` CreatedAt time.Time `json:"created_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` UpdatedAt time.Time `json:"updated_at"`
ProductCount int64 `gorm:"-" json:"product_count"` DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Children []Category `gorm:"foreignKey:ParentID" json:"children,omitempty"` ProductCount int64 `gorm:"-" json:"product_count"`
Children []Category `gorm:"foreignKey:ParentID" json:"children,omitempty"`
} }
func (Category) TableName() string { func (Category) TableName() string {
+22
View File
@@ -0,0 +1,22 @@
package models
import (
"time"
"gorm.io/gorm"
)
type PurchaseGroup struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:100;not null;uniqueIndex" json:"name"`
Description string `json:"description"`
SortOrder int `gorm:"default:0" json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Categories []Category `gorm:"foreignKey:PurchaseGroupID" json:"categories,omitempty"`
}
func (PurchaseGroup) TableName() string {
return "purchase_groups"
}
+34 -22
View File
@@ -1,31 +1,43 @@
package schemas package schemas
type CreateCategoryRequest struct { type CreateCategoryRequest struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
Description string `json:"description"` Description string `json:"description"`
ParentID *uint `json:"parent_id"` ParentID *uint `json:"parent_id"`
MinAmount *float64 `json:"min_amount"` PurchaseGroupID *uint `json:"purchase_group_id"`
MaxAmount *float64 `json:"max_amount"` MinAmount *float64 `json:"min_amount"`
MinQuantity *int `json:"min_quantity"` MaxAmount *float64 `json:"max_amount"`
MaxQuantity *int `json:"max_quantity"` MinQuantity *int `json:"min_quantity"`
MinWeight *float64 `json:"min_weight"` MaxQuantity *int `json:"max_quantity"`
MaxWeight *float64 `json:"max_weight"` MinWeight *float64 `json:"min_weight"`
AllowCrossCategory *bool `json:"allow_cross_category"` MaxWeight *float64 `json:"max_weight"`
SortOrder int `json:"sort_order"` SortOrder int `json:"sort_order"`
} }
type UpdateCategoryRequest struct { type UpdateCategoryRequest struct {
Name *string `json:"name"` Name *string `json:"name"`
Description *string `json:"description"` Description *string `json:"description"`
ParentID *uint `json:"parent_id"` ParentID *uint `json:"parent_id"`
MinAmount *float64 `json:"min_amount"` PurchaseGroupID *uint `json:"purchase_group_id"`
MaxAmount *float64 `json:"max_amount"` MinAmount *float64 `json:"min_amount"`
MinQuantity *int `json:"min_quantity"` MaxAmount *float64 `json:"max_amount"`
MaxQuantity *int `json:"max_quantity"` MinQuantity *int `json:"min_quantity"`
MinWeight *float64 `json:"min_weight"` MaxQuantity *int `json:"max_quantity"`
MaxWeight *float64 `json:"max_weight"` MinWeight *float64 `json:"min_weight"`
AllowCrossCategory *bool `json:"allow_cross_category"` MaxWeight *float64 `json:"max_weight"`
SortOrder *int `json:"sort_order"` SortOrder *int `json:"sort_order"`
}
type CreatePurchaseGroupRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
SortOrder int `json:"sort_order"`
}
type UpdatePurchaseGroupRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
SortOrder *int `json:"sort_order"`
} }
type CreateProductRequest struct { type CreateProductRequest struct {
+1
View File
@@ -63,6 +63,7 @@ func AutoMigrate() {
err := DB.AutoMigrate( err := DB.AutoMigrate(
&models.User{}, &models.User{},
&models.Category{}, &models.Category{},
&models.PurchaseGroup{},
&models.Brand{}, &models.Brand{},
&models.Product{}, &models.Product{},
&models.ProductCustomField{}, &models.ProductCustomField{},
+5
View File
@@ -124,6 +124,11 @@ export const adminApi = {
updateCategory: (id: number, data: any) => api.put(`/admin/categories/${id}`, data), updateCategory: (id: number, data: any) => api.put(`/admin/categories/${id}`, data),
deleteCategory: (id: number) => api.delete(`/admin/categories/${id}`), deleteCategory: (id: number) => api.delete(`/admin/categories/${id}`),
getPurchaseGroups: () => api.get('/admin/purchase-groups'),
createPurchaseGroup: (data: any) => api.post('/admin/purchase-groups', data),
updatePurchaseGroup: (id: number, data: any) => api.put(`/admin/purchase-groups/${id}`, data),
deletePurchaseGroup: (id: number) => api.delete(`/admin/purchase-groups/${id}`),
getBrands: () => api.get('/admin/brands'), getBrands: () => api.get('/admin/brands'),
createBrand: (data: any) => api.post('/admin/brands', data), createBrand: (data: any) => api.post('/admin/brands', data),
updateBrand: (id: number, data: any) => api.put(`/admin/brands/${id}`, data), updateBrand: (id: number, data: any) => api.put(`/admin/brands/${id}`, data),
+6 -1
View File
@@ -25,6 +25,10 @@
<el-icon><Folder /></el-icon> <el-icon><Folder /></el-icon>
<span class="nav-text">{{ $t('admin.categoryManagement') }}</span> <span class="nav-text">{{ $t('admin.categoryManagement') }}</span>
</router-link> </router-link>
<router-link to="/admin/purchase-groups" class="nav-link">
<el-icon><Grid /></el-icon>
<span class="nav-text">购买分组</span>
</router-link>
<router-link to="/admin/brands" class="nav-link"> <router-link to="/admin/brands" class="nav-link">
<el-icon><Stamp /></el-icon> <el-icon><Stamp /></el-icon>
<span class="nav-text">{{ $t('admin.brandManagement') }}</span> <span class="nav-text">{{ $t('admin.brandManagement') }}</span>
@@ -164,7 +168,7 @@
import { ref, computed } from 'vue' import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router' import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { DataAnalysis, User, Folder, Stamp, Goods, List, Van, Trophy, ChatDotSquare, Setting, Document, Picture, Compass, Fold, Expand, HomeFilled, FullScreen, ArrowDown, SwitchButton, ArrowRight, Wallet, Notebook } from '@element-plus/icons-vue' import { DataAnalysis, User, Folder, Grid, Stamp, Goods, List, Van, Trophy, ChatDotSquare, Setting, Document, Picture, Compass, Fold, Expand, HomeFilled, FullScreen, ArrowDown, SwitchButton, ArrowRight, Wallet, Notebook } from '@element-plus/icons-vue'
import { useUserStore } from '../store/user' import { useUserStore } from '../store/user'
import { useCartStore } from '../store/cart' import { useCartStore } from '../store/cart'
@@ -182,6 +186,7 @@ const pageTitles: Record<string, string> = {
'/admin': '控制台', '/admin': '控制台',
'/admin/users': '用户管理', '/admin/users': '用户管理',
'/admin/categories': '分类管理', '/admin/categories': '分类管理',
'/admin/purchase-groups': '购买分组',
'/admin/brands': '品牌管理', '/admin/brands': '品牌管理',
'/admin/products': '商品管理', '/admin/products': '商品管理',
'/admin/orders': '订单管理', '/admin/orders': '订单管理',
+1
View File
@@ -41,6 +41,7 @@ const routes = [
{ path: '', name: 'AdminDashboard', component: () => import('../views/admin/Dashboard.vue') }, { path: '', name: 'AdminDashboard', component: () => import('../views/admin/Dashboard.vue') },
{ path: 'users', name: 'AdminUsers', component: () => import('../views/admin/Users.vue') }, { path: 'users', name: 'AdminUsers', component: () => import('../views/admin/Users.vue') },
{ path: 'categories', name: 'AdminCategories', component: () => import('../views/admin/Categories.vue') }, { path: 'categories', name: 'AdminCategories', component: () => import('../views/admin/Categories.vue') },
{ path: 'purchase-groups', name: 'AdminPurchaseGroups', component: () => import('../views/admin/PurchaseGroups.vue') },
{ path: 'brands', name: 'AdminBrands', component: () => import('../views/admin/Brands.vue') }, { path: 'brands', name: 'AdminBrands', component: () => import('../views/admin/Brands.vue') },
{ path: 'products', name: 'AdminProducts', component: () => import('../views/admin/Products.vue') }, { path: 'products', name: 'AdminProducts', component: () => import('../views/admin/Products.vue') },
{ path: 'orders', name: 'AdminOrders', component: () => import('../views/admin/Orders.vue') }, { path: 'orders', name: 'AdminOrders', component: () => import('../views/admin/Orders.vue') },
+24 -14
View File
@@ -8,19 +8,18 @@
<el-table-column prop="id" label="ID" width="80" /> <el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="name" label="分类名称" /> <el-table-column prop="name" label="分类名称" />
<el-table-column prop="description" label="描述" /> <el-table-column prop="description" label="描述" />
<el-table-column label="购买分组" width="120">
<template #default="{ row }">
<el-tag v-if="row.purchase_group" size="small">{{ row.purchase_group.name }}</el-tag>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column label="金额限制" width="200"> <el-table-column label="金额限制" width="200">
<template #default="{ row }"> <template #default="{ row }">
<span v-if="row.min_amount || row.max_amount">¥{{ row.min_amount || 0 }}~{{ row.max_amount || '' }}</span> <span v-if="row.min_amount || row.max_amount">¥{{ row.min_amount || 0 }}~{{ row.max_amount || '' }}</span>
<span v-else>-</span> <span v-else>-</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="跨分类购物" width="100">
<template #default="{ row }">
<el-tag :type="row.allow_cross_category ? 'success' : 'info'" size="small">
{{ row.allow_cross_category ? '允许' : '不允许' }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="120"> <el-table-column label="操作" width="120">
<template #default="{ row }"> <template #default="{ row }">
<el-button link type="primary" size="small" @click="editCat(row)">编辑</el-button> <el-button link type="primary" size="small" @click="editCat(row)">编辑</el-button>
@@ -42,15 +41,17 @@
<el-form :model="form" label-width="100px"> <el-form :model="form" label-width="100px">
<el-form-item label="名称"><el-input v-model="form.name" /></el-form-item> <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
<el-form-item label="描述"><el-input v-model="form.description" type="textarea" /></el-form-item> <el-form-item label="描述"><el-input v-model="form.description" type="textarea" /></el-form-item>
<el-form-item label="购买分组">
<el-select v-model="form.purchase_group_id" placeholder="请选择购买分组" clearable style="width: 100%">
<el-option v-for="group in purchaseGroups" :key="group.id" :label="group.name" :value="group.id" />
</el-select>
</el-form-item>
<el-form-item label="最小金额"><el-input-number v-model="form.min_amount" :precision="2" /></el-form-item> <el-form-item label="最小金额"><el-input-number v-model="form.min_amount" :precision="2" /></el-form-item>
<el-form-item label="最大金额"><el-input-number v-model="form.max_amount" :precision="2" /></el-form-item> <el-form-item label="最大金额"><el-input-number v-model="form.max_amount" :precision="2" /></el-form-item>
<el-form-item label="最小数量"><el-input-number v-model="form.min_quantity" /></el-form-item> <el-form-item label="最小数量"><el-input-number v-model="form.min_quantity" /></el-form-item>
<el-form-item label="最大数量"><el-input-number v-model="form.max_quantity" /></el-form-item> <el-form-item label="最大数量"><el-input-number v-model="form.max_quantity" /></el-form-item>
<el-form-item label="最小重量"><el-input-number v-model="form.min_weight" :precision="2" /></el-form-item> <el-form-item label="最小重量"><el-input-number v-model="form.min_weight" :precision="2" /></el-form-item>
<el-form-item label="最大重量"><el-input-number v-model="form.max_weight" :precision="2" /></el-form-item> <el-form-item label="最大重量"><el-input-number v-model="form.max_weight" :precision="2" /></el-form-item>
<el-form-item label="跨分类购物">
<el-switch v-model="form.allow_cross_category" active-text="允许" inactive-text="不允许" />
</el-form-item>
</el-form> </el-form>
<template #footer> <template #footer>
<el-button @click="showAdd = false">取消</el-button> <el-button @click="showAdd = false">取消</el-button>
@@ -66,6 +67,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi, categoryApi } from '../../api' import { adminApi, categoryApi } from '../../api'
const categories = ref<any[]>([]) const categories = ref<any[]>([])
const purchaseGroups = ref<any[]>([])
const showAdd = ref(false) const showAdd = ref(false)
const editing = ref<any>(null) const editing = ref<any>(null)
const page = ref(1) const page = ref(1)
@@ -75,7 +77,7 @@ const paginatedCategories = computed(() => {
const start = (page.value - 1) * pageSize const start = (page.value - 1) * pageSize
return categories.value.slice(start, start + pageSize) return categories.value.slice(start, start + pageSize)
}) })
const form = reactive({ name: '', description: '', min_amount: undefined as number | undefined, max_amount: undefined as number | undefined, min_quantity: undefined as number | undefined, max_quantity: undefined as number | undefined, min_weight: undefined as number | undefined, max_weight: undefined as number | undefined, allow_cross_category: false }) const form = reactive({ name: '', description: '', purchase_group_id: undefined as number | undefined, min_amount: undefined as number | undefined, max_amount: undefined as number | undefined, min_quantity: undefined as number | undefined, max_quantity: undefined as number | undefined, min_weight: undefined as number | undefined, max_weight: undefined as number | undefined })
function handlePageChange() { function handlePageChange() {
window.scrollTo({ top: 0, behavior: 'smooth' }) window.scrollTo({ top: 0, behavior: 'smooth' })
@@ -86,15 +88,20 @@ async function fetchCategories() {
categories.value = res.data || [] categories.value = res.data || []
} }
async function fetchPurchaseGroups() {
const res: any = await adminApi.getPurchaseGroups()
purchaseGroups.value = res.data || []
}
function openAdd() { function openAdd() {
editing.value = null editing.value = null
Object.assign(form, { name: '', description: '', min_amount: undefined, max_amount: undefined, min_quantity: undefined, max_quantity: undefined, min_weight: undefined, max_weight: undefined, allow_cross_category: false }) Object.assign(form, { name: '', description: '', purchase_group_id: undefined, min_amount: undefined, max_amount: undefined, min_quantity: undefined, max_quantity: undefined, min_weight: undefined, max_weight: undefined })
showAdd.value = true showAdd.value = true
} }
function editCat(row: any) { function editCat(row: any) {
editing.value = row editing.value = row
Object.assign(form, { name: row.name, description: row.description || '', min_amount: row.min_amount, max_amount: row.max_amount, min_quantity: row.min_quantity, max_quantity: row.max_quantity, min_weight: row.min_weight, max_weight: row.max_weight, allow_cross_category: row.allow_cross_category || false }) Object.assign(form, { name: row.name, description: row.description || '', purchase_group_id: row.purchase_group_id, min_amount: row.min_amount, max_amount: row.max_amount, min_quantity: row.min_quantity, max_quantity: row.max_quantity, min_weight: row.min_weight, max_weight: row.max_weight })
showAdd.value = true showAdd.value = true
} }
@@ -122,7 +129,10 @@ async function deleteCat(id: number) {
await fetchCategories() await fetchCategories()
} }
onMounted(fetchCategories) onMounted(() => {
fetchCategories()
fetchPurchaseGroups()
})
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@@ -0,0 +1,98 @@
<template>
<div class="purchase-groups-page">
<div class="page-header">
<el-button type="primary" @click="openAdd">创建分组</el-button>
</div>
<div class="table-card">
<el-table :data="groups">
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="name" label="分组名称" />
<el-table-column prop="description" label="描述" />
<el-table-column label="关联分类" width="200">
<template #default="{ row }">
<span v-if="row.categories && row.categories.length">
{{ row.categories.map((c: any) => c.name).join('、') }}
</span>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column label="操作" width="120">
<template #default="{ row }">
<el-button link type="primary" size="small" @click="editGroup(row)">编辑</el-button>
<el-button link type="danger" size="small" @click="deleteGroup(row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<el-dialog v-model="showAdd" :title="editing ? '编辑分组' : '创建分组'" width="500px">
<el-form :model="form" label-width="80px">
<el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
<el-form-item label="描述"><el-input v-model="form.description" type="textarea" /></el-form-item>
</el-form>
<template #footer>
<el-button @click="showAdd = false">取消</el-button>
<el-button type="primary" @click="saveGroup">保存</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '../../api'
const groups = ref<any[]>([])
const showAdd = ref(false)
const editing = ref<any>(null)
const form = reactive({ name: '', description: '' })
async function fetchGroups() {
const res: any = await adminApi.getPurchaseGroups()
groups.value = res.data || []
}
function openAdd() {
editing.value = null
Object.assign(form, { name: '', description: '' })
showAdd.value = true
}
function editGroup(row: any) {
editing.value = row
Object.assign(form, { name: row.name, description: row.description || '' })
showAdd.value = true
}
async function saveGroup() {
try {
if (editing.value) {
await adminApi.updatePurchaseGroup(editing.value.id, form)
} else {
await adminApi.createPurchaseGroup(form)
}
ElMessage.success('保存成功')
showAdd.value = false
editing.value = null
await fetchGroups()
} catch (error: any) {
const msg = error.response?.data?.error || '保存失败'
ElMessage.error(msg)
}
}
async function deleteGroup(id: number) {
await ElMessageBox.confirm('确定删除此分组?', '确认')
await adminApi.deletePurchaseGroup(id)
ElMessage.success('删除成功')
await fetchGroups()
}
onMounted(fetchGroups)
</script>
<style scoped lang="scss">
.purchase-groups-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }
</style>