feat(ecom-dmb): 新增商品类目模块,支持商品关联类目

后端:
- 新增 ec_category 表(支持多级分类)
- ec_product 表新增 category_id 字段(ON DELETE SET NULL)
- CategoryController: CRUD + 分页 + 树形接口
- ProductServiceImpl 支持 categoryId 写入和 categoryName 读取
- sys_menu 新增类目管理菜单(配置管理下)

前端:
- 新增类目管理 API 和页面(/ecommerce/config/category-config/)
- ProductFormModal 新增类目选择器
- 商品列表视图新增类目列
This commit is contained in:
小蟑螂
2026-04-17 17:37:04 +08:00
parent 5c4ef6c990
commit 99efd576ee
25 changed files with 1309 additions and 6 deletions
@@ -0,0 +1,51 @@
import type { CategoryDTO, CategoryVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
/**
* 商品类目管理API
*/
/**
* 创建类目
*/
export async function createCategoryApi(data: CategoryDTO.Create) {
return requestClient.post<CategoryVO.Info>('/ec/category/create', data);
}
/**
* 更新类目
*/
export async function updateCategoryApi(id: number, data: CategoryDTO.Update) {
return requestClient.put<CategoryVO.Info>(`/ec/category/update/${id}`, data);
}
/**
* 删除类目
*/
export async function deleteCategoryApi(id: number) {
return requestClient.delete(`/ec/category/delete/${id}`);
}
/**
* 分页获取类目列表
*/
export async function getCategoryPageApi(params: PageQueryDTO<CategoryDTO.Filters>) {
return requestClient.post<PageResultVO<CategoryVO.Info>>('/ec/category/page', params);
}
/**
* 获取类目树形结构
*/
export async function getCategoryTreeApi() {
return requestClient.get<CategoryVO.Info[]>('/ec/category/tree');
}
/**
* 获取类目扁平列表
*/
export async function getCategoryListApi() {
return requestClient.get<CategoryVO.Info[]>('/ec/category/list');
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,33 @@
/**
* 商品类目相关DTO类型定义
*/
export namespace CategoryDTO {
/** 创建类目参数 */
export interface Create {
/** 父级类目ID(顶级类目不传) */
parentId?: number;
/** 类目名称 */
name: string;
/** 排序 */
sortOrder?: number;
}
/** 更新类目参数 */
export interface Update {
/** 父级类目ID(设为null表示顶级) */
parentId?: number | null;
/** 类目名称 */
name: string;
/** 排序 */
sortOrder?: number;
}
/** 类目过滤条件 */
export interface Filters {
/** 类目名称(模糊查询) */
name?: string;
/** 父级类目ID(精确查询) */
parentId?: number;
}
}
@@ -0,0 +1,31 @@
/**
* 商品类目相关VO类型定义
*/
export namespace CategoryVO {
/** 类目信息 */
export interface Info {
/** 类目ID */
id: number;
/** 公司ID */
companyId?: number;
/** 父级类目ID */
parentId?: number;
/** 父级类目名称 */
parentName?: string;
/** 类目名称 */
name: string;
/** 排序 */
sortOrder?: number;
/** 创建时间 */
createTime: string;
/** 更新时间 */
updateTime: string;
/** 创建人ID */
createBy?: number;
/** 更新人ID */
updateBy?: number;
/** 子类目列表 */
children?: Info[];
}
}
@@ -0,0 +1,182 @@
<script lang="ts" setup>
import type { CategoryDTO, CategoryVO } from '#/api/ecommerce/category';
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, InputNumber, Select, message } from 'ant-design-vue';
import {
createCategoryApi,
getCategoryListApi,
updateCategoryApi,
} from '#/api/ecommerce/category';
const emit = defineEmits<{
cancel: [];
success: [];
}>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
onCancel() {
close();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<null | CategoryVO.Info>(null);
// 类目选项列表(用于父级选择)
const categoryOptions = ref<CategoryVO.Info[]>([]);
// 表单数据
const formData = ref<Partial<CategoryDTO.Create>>({
parentId: undefined,
name: '',
sortOrder: 0,
});
// 表单验证规则
const rules = {
name: [{ required: true, message: '请输入类目名称', trigger: 'blur' }],
};
// 表单引用
const formRef = ref();
// 加载类目列表(扁平,用于父级选择)
async function loadCategoryOptions() {
try {
const list = await getCategoryListApi();
categoryOptions.value = list ?? [];
} catch (error) {
console.error('加载类目列表失败:', error);
}
}
// 打开模态框
async function open(edit: boolean, record?: CategoryVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
await loadCategoryOptions();
modalApi.open();
if (edit && record) {
formData.value = {
parentId: record.parentId ?? undefined,
name: record.name,
sortOrder: record.sortOrder ?? 0,
};
} else {
formData.value = {
parentId: undefined,
name: '',
sortOrder: 0,
};
}
}
// 关闭模态框
function close() {
modalApi.close();
formRef.value?.resetFields();
emit('cancel');
}
// 提交表单
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentRecord.value) {
const updateData: CategoryDTO.Update = {
parentId: formData.value.parentId ?? null,
name: formData.value.name!,
sortOrder: formData.value.sortOrder,
};
await updateCategoryApi(currentRecord.value.id, updateData);
message.success('更新类目成功');
} else {
const createData: CategoryDTO.Create = {
parentId: formData.value.parentId,
name: formData.value.name!,
sortOrder: formData.value.sortOrder,
};
await createCategoryApi(createData);
message.success('创建类目成功');
}
emit('success');
close();
} catch (error) {
console.error('提交失败:', error);
} finally {
loading.value = false;
}
}
// 监听模态框关闭状态
watch(
() => modalApi.useStore?.()?.value?.isOpen,
(newVal) => {
if (!newVal) {
formRef.value?.resetFields();
}
},
);
// 暴露方法
defineExpose({
open,
close,
});
</script>
<template>
<Modal
:title="isEdit ? '编辑类目' : '添加类目'"
:confirm-loading="loading"
>
<Form
ref="formRef"
:model="formData"
:rules="rules as any"
layout="vertical"
>
<Form.Item label="父级类目" name="parentId">
<Select
v-model:value="formData.parentId"
placeholder="请选择父级类目(留空则为顶级)"
:options="[{ label: '(顶级类目)', value: undefined }, ...categoryOptions.map(c => ({ label: c.name, value: c.id }))]"
allow-clear
/>
</Form.Item>
<Form.Item label="类目名称" name="name">
<Input
v-model:value="formData.name"
placeholder="请输入类目名称"
/>
</Form.Item>
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,221 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CategoryVO } from '#/api/ecommerce/category';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteCategoryApi,
getCategoryTreeApi,
} from '#/api/ecommerce/category';
import CategoryFormModal from './components/CategoryFormModal.vue';
defineOptions({ name: 'CategoryConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const categoryFormModalRef = ref();
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
field: 'name',
title: '类目名称',
minWidth: 150,
slots: { default: 'name' },
},
{
field: 'parentName',
title: '上级类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
field: 'sortOrder',
title: '排序',
minWidth: 80,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 160,
},
{
title: '操作',
width: 160,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
highlightHoverRow: true,
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const tree = await getCategoryTreeApi();
// 将树扁平化用于表格展示
const flatData = flattenTree(tree ?? []);
return {
items: flatData,
total: flatData.length,
};
} catch (error) {
console.error('获取类目列表失败:', error);
message.error('获取类目列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
// 将树形结构扁平化
function flattenTree(tree: CategoryVO.Info[], level = 0): any[] {
const result: any[] = [];
for (const item of tree) {
result.push({ ...item, _level: level });
if (item.children && item.children.length > 0) {
result.push(...flattenTree(item.children, level + 1));
}
}
return result;
}
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入类目名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'name',
label: '类目名称',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '商品类目配置',
});
gridReloadRef.value = () => gridApi.reload();
function refreshTable() {
gridApi?.reload();
}
function handleAdd() {
categoryFormModalRef.value?.open(false);
}
function handleEdit(record: CategoryVO.Info) {
categoryFormModalRef.value?.open(true, record);
}
async function handleDelete(record: CategoryVO.Info) {
try {
await deleteCategoryApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除类目失败:', error);
message.error((error as any)?.response?.data?.message || '删除类目失败');
}
}
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
<Page title="商品类目配置" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理商品类目,支持多级分类
</div>
</template>
<Grid :loading="loading">
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加类目
</Button>
</Space>
</template>
<!-- 类目名称列 -->
<template #name="{ row }: { row: CategoryVO.Info & { _level: number } }">
<span :style="{ paddingLeft: `${(row._level ?? 0) * 20}px` }">
<span v-if="(row._level ?? 0) > 0" class="mr-1 text-gray-400">└</span>
{{ row.name }}
</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这个类目吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<CategoryFormModal
ref="categoryFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
@@ -13,6 +13,7 @@ import {
Input,
InputNumber,
message,
Select,
Space,
Table,
} from 'ant-design-vue';
@@ -24,6 +25,7 @@ import {
getProductSpecsByIdsApi,
} from '#/api/ecommerce/product-spec/apis';
import type { ProductSpecVO } from '#/api/ecommerce/product-spec/types';
import { getCategoryListApi } from '#/api/ecommerce/category';
import { uploadFileToOss } from '#/utils/oss-upload';
interface Emits {
@@ -127,9 +129,13 @@ const imageLoadError = ref(false); // 图片加载错误状态
const formData = ref({
name: '',
productCode: '',
categoryId: undefined as number | undefined,
mainImageId: undefined as number | undefined,
});
// 类目选项列表
const categoryOptions = ref<{ label: string; value: number }[]>([]);
// 规格数据 - 支持创建和更新
const specs = ref<Array<ProductDTO.Spec | ProductDTO.UpdateSpec>>([]);
const showSpecs = ref(false);
@@ -148,6 +154,7 @@ function initFormData() {
formData.value = {
name: currentProductData.value.name || '',
productCode: currentProductData.value.productCode || '',
categoryId: (currentProductData.value as any).categoryId ?? undefined,
mainImageId: undefined,
};
originalImageUrl.value = currentProductData.value.mainImage || '';
@@ -155,6 +162,7 @@ function initFormData() {
formData.value = {
name: currentProductData.value?.name || '',
productCode: currentProductData.value?.productCode || '',
categoryId: (currentProductData.value as any)?.categoryId ?? undefined,
mainImageId: undefined,
};
originalImageUrl.value = currentProductData.value?.mainImage || '';
@@ -205,6 +213,7 @@ function resetForm() {
imageLoadError.value = false;
specs.value = [];
showSpecs.value = false;
categoryOptions.value = [];
}
// 处理提交
@@ -237,6 +246,7 @@ async function handleSubmit() {
const updateData: ProductDTO.Update = {
name: submitData.name,
productCode: submitData.productCode || undefined,
categoryId: submitData.categoryId,
mainImageId: submitData.mainImageId,
...(specs.value.length > 0 && {
specs: specs.value as ProductDTO.UpdateSpec[],
@@ -254,6 +264,7 @@ async function handleSubmit() {
const createData: ProductDTO.Create = {
name: submitData.name,
productCode: submitData.productCode || undefined,
categoryId: submitData.categoryId,
mainImageId: submitData.mainImageId,
...(specs.value.length > 0 && { specs: specs.value }),
};
@@ -282,7 +293,7 @@ function close() {
}
// 暴露给父组件的方法
function open(
async function open(
editMode: boolean = false,
productData?: null | Partial<ProductVO.Info> | ProductVO.Info,
) {
@@ -297,6 +308,14 @@ function open(
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
// 加载类目选项
try {
const list = await getCategoryListApi();
categoryOptions.value = (list ?? []).map((c) => ({ label: c.name, value: c.id }));
} catch (error) {
console.error('加载类目列表失败:', error);
}
modalApi.open();
}
@@ -670,6 +689,16 @@ onUnmounted(() => {
/>
</Form.Item>
<Form.Item label="商品类目" name="categoryId">
<Select
v-model:value="formData.categoryId"
placeholder="请选择商品类目"
:options="[{ label: '(未分类)', value: undefined }, ...categoryOptions]"
allow-clear
style="width: 100%"
/>
</Form.Item>
<!-- 规格管理 -->
<Form.Item label="商品规格">
<div class="space-y-4">
@@ -107,6 +107,12 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 150,
showOverflow: 'tooltip' as const,
},
{
field: 'categoryName',
title: '类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
title: '规格数量',
minWidth: 100,