mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:09:21 +08:00
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:
@@ -195,6 +195,32 @@ CREATE TABLE `ec_order_status` (
|
||||
CONSTRAINT `fk_ec_order_status_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-订单状态表' ;
|
||||
|
||||
-- ----------------------------
|
||||
-- 商品类目表
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `ec_category`;
|
||||
CREATE TABLE `ec_category` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '类目ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`parent_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '父级类目ID',
|
||||
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '类目名称',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_parent_id`(`parent_id` ASC) USING BTREE,
|
||||
INDEX `idx_sort_order`(`sort_order` ASC) USING BTREE,
|
||||
INDEX `fk_ec_category_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_ec_category_updater`(`update_by` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_category_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_category_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_category_parent` FOREIGN KEY (`parent_id`) REFERENCES `ec_category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_category_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品类目表' ;
|
||||
|
||||
-- ----------------------------
|
||||
-- 商品表
|
||||
-- ----------------------------
|
||||
@@ -202,6 +228,7 @@ DROP TABLE IF EXISTS `ec_product`;
|
||||
CREATE TABLE `ec_product` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商品ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`category_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '类目ID',
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品名称',
|
||||
`link_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '链接商品名称',
|
||||
`product_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品编码',
|
||||
@@ -213,9 +240,11 @@ CREATE TABLE `ec_product` (
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_product_code`(`product_code` ASC) USING BTREE,
|
||||
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_category_id`(`category_id` ASC) USING BTREE,
|
||||
INDEX `fk_ec_product_main_image`(`main_image_id` ASC) USING BTREE,
|
||||
INDEX `fk_ec_product_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_ec_product_updater`(`update_by` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_category` FOREIGN KEY (`category_id`) REFERENCES `ec_category` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_main_image` FOREIGN KEY (`main_image_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CategoryFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CreateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.UpdateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.vo.CategoryVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品类目管理控制器
|
||||
*/
|
||||
@Tag(name = "电商-商品类目管理", description = "商品类目的增删改查接口")
|
||||
@RestController
|
||||
@RequestMapping("/ec/category")
|
||||
public class CategoryController {
|
||||
|
||||
private final CategoryService categoryService;
|
||||
|
||||
public CategoryController(CategoryService categoryService) {
|
||||
this.categoryService = categoryService;
|
||||
}
|
||||
|
||||
@Operation(summary = "创建类目", description = "创建新的商品类目")
|
||||
@PostMapping("/create")
|
||||
@RequirePermission(value = "ecom:category:manage", description = "创建类目", allowSuper = true)
|
||||
public ApiResponse<CategoryVO> createCategory(@Valid @RequestBody CreateCategoryDTO createCategoryDTO) {
|
||||
CategoryVO categoryVO = categoryService.createCategory(createCategoryDTO);
|
||||
return ApiResponse.success("类目创建成功", categoryVO);
|
||||
}
|
||||
|
||||
@Operation(summary = "更新类目", description = "更新现有商品类目信息")
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission(value = "ecom:category:manage", description = "更新类目", allowSuper = true)
|
||||
public ApiResponse<CategoryVO> updateCategory(@Valid @RequestBody UpdateCategoryDTO updateCategoryDTO,
|
||||
@Parameter(description = "类目ID") @PathVariable Long id) {
|
||||
CategoryVO categoryVO = categoryService.updateCategory(updateCategoryDTO, id);
|
||||
return ApiResponse.success("类目更新成功", categoryVO);
|
||||
}
|
||||
|
||||
@Operation(summary = "删除类目", description = "删除指定商品类目")
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission(value = "ecom:category:manage", description = "删除类目", allowSuper = true)
|
||||
public ApiResponse<Void> deleteCategory(
|
||||
@Parameter(description = "类目ID") @PathVariable Long id) {
|
||||
categoryService.deleteCategory(id);
|
||||
return ApiResponse.success("类目删除成功", null);
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取类目列表", description = "分页获取类目列表,支持条件过滤")
|
||||
@PostMapping("/page")
|
||||
@RequirePermission(value = "ecom:category:read", description = "查询类目列表", allowSuper = true)
|
||||
public ApiResponse<PageResultVO<CategoryVO>> getCategoryPage(
|
||||
@Valid @RequestBody PageQueryDTO<CategoryFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<CategoryVO> result = categoryService.getCategoryPage(pageQueryDTO);
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取类目树形结构", description = "获取当前公司的所有类目,以树形结构返回")
|
||||
@GetMapping("/tree")
|
||||
@RequirePermission(value = "ecom:category:read", description = "查询类目树", allowSuper = true)
|
||||
public ApiResponse<List<CategoryVO>> getCategoryTree() {
|
||||
List<CategoryVO> tree = categoryService.getCategoryTree();
|
||||
return ApiResponse.success(tree);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取类目扁平列表", description = "获取当前公司的所有类目,以扁平列表返回,用于下拉选择")
|
||||
@GetMapping("/list")
|
||||
@RequirePermission(value = "ecom:category:read", description = "查询类目列表", allowSuper = true)
|
||||
public ApiResponse<List<CategoryVO>> getCategoryList() {
|
||||
List<CategoryVO> list = categoryService.getCategoryList();
|
||||
return ApiResponse.success(list);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 商品类目Mapper
|
||||
*/
|
||||
@Mapper
|
||||
public interface CategoryMapper extends BaseMapper<CategoryPO> {
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 类目分页查询过滤DTO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "类目分页查询过滤DTO")
|
||||
public class CategoryFilterDTO {
|
||||
|
||||
/**
|
||||
* 类目名称(模糊查询)
|
||||
*/
|
||||
@Schema(description = "类目名称(模糊查询)", example = "手机")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 父级类目ID(精确查询)
|
||||
*/
|
||||
@Schema(description = "父级类目ID(精确查询)", example = "1")
|
||||
private Long parentId;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 创建类目DTO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "创建类目DTO")
|
||||
public class CreateCategoryDTO {
|
||||
|
||||
/**
|
||||
* 父级类目ID
|
||||
*/
|
||||
@Schema(description = "父级类目ID(顶级类目不传)")
|
||||
private Long parentId;
|
||||
|
||||
/**
|
||||
* 类目名称
|
||||
*/
|
||||
@Schema(description = "类目名称", example = "手机数码", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@NotBlank(message = "类目名称不能为空")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
@Schema(description = "排序", example = "0")
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 更新类目DTO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "更新类目DTO")
|
||||
public class UpdateCategoryDTO {
|
||||
|
||||
/**
|
||||
* 父级类目ID
|
||||
*/
|
||||
@Schema(description = "父级类目ID(设为null表示顶级)")
|
||||
private Long parentId;
|
||||
|
||||
/**
|
||||
* 类目名称
|
||||
*/
|
||||
@Schema(description = "类目名称", example = "手机数码", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@NotBlank(message = "类目名称不能为空")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
@Schema(description = "排序", example = "0")
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 电商-商品类目实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("ec_category")
|
||||
public class CategoryPO {
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 公司ID
|
||||
*/
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 父级类目ID
|
||||
*/
|
||||
@TableField("parent_id")
|
||||
private Long parentId;
|
||||
|
||||
/**
|
||||
* 类目名称
|
||||
*/
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 类目VO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "类目VO")
|
||||
public class CategoryVO {
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@Schema(description = "类目ID", example = "1")
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 公司ID
|
||||
*/
|
||||
@Schema(description = "公司ID", example = "1")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 父级类目ID
|
||||
*/
|
||||
@Schema(description = "父级类目ID", example = "1")
|
||||
private Long parentId;
|
||||
|
||||
/**
|
||||
* 父级类目名称
|
||||
*/
|
||||
@Schema(description = "父级类目名称", example = "数码")
|
||||
private String parentName;
|
||||
|
||||
/**
|
||||
* 类目名称
|
||||
*/
|
||||
@Schema(description = "类目名称", example = "手机")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
@Schema(description = "排序", example = "0")
|
||||
private Integer sortOrder;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@Schema(description = "创建时间", example = "2024-01-01T10:00:00")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@Schema(description = "更新时间", example = "2024-01-01T10:00:00")
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
@Schema(description = "创建人ID", example = "1")
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
@Schema(description = "更新人ID", example = "1")
|
||||
private Long updateBy;
|
||||
|
||||
/**
|
||||
* 子类目列表
|
||||
*/
|
||||
@Schema(description = "子类目列表")
|
||||
private List<CategoryVO> children;
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CategoryFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CreateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.UpdateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.vo.CategoryVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品类目服务接口
|
||||
*/
|
||||
public interface CategoryService extends IService<CategoryPO> {
|
||||
|
||||
/**
|
||||
* 创建类目
|
||||
*
|
||||
* @param createCategoryDTO 创建类目DTO
|
||||
* @return 类目VO
|
||||
*/
|
||||
CategoryVO createCategory(CreateCategoryDTO createCategoryDTO);
|
||||
|
||||
/**
|
||||
* 更新类目
|
||||
*
|
||||
* @param updateCategoryDTO 更新类目DTO
|
||||
* @param id 类目ID
|
||||
* @return 类目VO
|
||||
*/
|
||||
CategoryVO updateCategory(UpdateCategoryDTO updateCategoryDTO, Long id);
|
||||
|
||||
/**
|
||||
* 删除类目
|
||||
*
|
||||
* @param id 类目ID
|
||||
*/
|
||||
void deleteCategory(Long id);
|
||||
|
||||
/**
|
||||
* 分页获取类目列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<CategoryVO> getCategoryPage(PageQueryDTO<CategoryFilterDTO> pageQueryDTO);
|
||||
|
||||
/**
|
||||
* 获取公司所有类目(树形结构)
|
||||
*
|
||||
* @return 树形类目列表
|
||||
*/
|
||||
List<CategoryVO> getCategoryTree();
|
||||
|
||||
/**
|
||||
* 获取公司所有类目(扁平列表)
|
||||
*
|
||||
* @return 扁平类目列表
|
||||
*/
|
||||
List<CategoryVO> getCategoryList();
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.category.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.mapper.CategoryMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CategoryFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.CreateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.dto.UpdateCategoryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.vo.CategoryVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品类目服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryPO> implements CategoryService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public CategoryServiceImpl(CurrentUserContext currentUserContext) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public CategoryVO createCategory(CreateCategoryDTO createCategoryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 验证父级类目(如果提供了parentId)
|
||||
if (createCategoryDTO.getParentId() != null) {
|
||||
CategoryPO parent = this.getById(createCategoryDTO.getParentId());
|
||||
if (parent == null || !parent.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("父级类目不存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 验证类目名称在同级下不重复
|
||||
LambdaQueryWrapper<CategoryPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CategoryPO::getCompanyId, companyId)
|
||||
.eq(CategoryPO::getParentId, createCategoryDTO.getParentId())
|
||||
.eq(CategoryPO::getName, createCategoryDTO.getName());
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("同级类目名称已存在");
|
||||
}
|
||||
|
||||
CategoryPO category = new CategoryPO();
|
||||
category.setCompanyId(companyId);
|
||||
category.setParentId(createCategoryDTO.getParentId());
|
||||
category.setName(createCategoryDTO.getName());
|
||||
category.setSortOrder(createCategoryDTO.getSortOrder() != null ? createCategoryDTO.getSortOrder() : 0);
|
||||
category.setCreateBy(currentUserContext.getCurrentUserId());
|
||||
|
||||
this.save(category);
|
||||
return convertToVO(category);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public CategoryVO updateCategory(UpdateCategoryDTO updateCategoryDTO, Long id) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
CategoryPO existing = this.getById(id);
|
||||
if (existing == null || !existing.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("类目不存在");
|
||||
}
|
||||
|
||||
// 不能把自己设为自己的父级
|
||||
if (updateCategoryDTO.getParentId() != null && updateCategoryDTO.getParentId().equals(id)) {
|
||||
throw new BusinessException("不能将类目设为自己或自己的子级");
|
||||
}
|
||||
|
||||
// 验证父级类目(如果提供了parentId)
|
||||
if (updateCategoryDTO.getParentId() != null) {
|
||||
CategoryPO parent = this.getById(updateCategoryDTO.getParentId());
|
||||
if (parent == null || !parent.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("父级类目不存在");
|
||||
}
|
||||
// 防止循环引用:检查新父级是不是自己的下级
|
||||
if (isDescendant(id, updateCategoryDTO.getParentId())) {
|
||||
throw new BusinessException("不能将类目设为自己或自己的子级");
|
||||
}
|
||||
}
|
||||
|
||||
// 验证同级下名称不重复(排除自己)
|
||||
LambdaQueryWrapper<CategoryPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CategoryPO::getCompanyId, companyId)
|
||||
.eq(CategoryPO::getParentId, updateCategoryDTO.getParentId())
|
||||
.eq(CategoryPO::getName, updateCategoryDTO.getName())
|
||||
.ne(CategoryPO::getId, id);
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("同级类目名称已存在");
|
||||
}
|
||||
|
||||
existing.setParentId(updateCategoryDTO.getParentId());
|
||||
existing.setName(updateCategoryDTO.getName());
|
||||
if (updateCategoryDTO.getSortOrder() != null) {
|
||||
existing.setSortOrder(updateCategoryDTO.getSortOrder());
|
||||
}
|
||||
existing.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
|
||||
this.updateById(existing);
|
||||
return convertToVO(existing);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteCategory(Long id) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
CategoryPO existing = this.getById(id);
|
||||
if (existing == null || !existing.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("类目不存在");
|
||||
}
|
||||
|
||||
// 检查是否有子类目
|
||||
LambdaQueryWrapper<CategoryPO> childWrapper = new LambdaQueryWrapper<>();
|
||||
childWrapper.eq(CategoryPO::getParentId, id);
|
||||
if (this.count(childWrapper) > 0) {
|
||||
throw new BusinessException("请先删除子类目");
|
||||
}
|
||||
|
||||
// 检查是否有商品引用(如果需要强校验的话,这里可以放开)
|
||||
// 目前设计为 ON DELETE SET NULL,所以直接删即可
|
||||
|
||||
this.removeById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<CategoryVO> getCategoryPage(PageQueryDTO<CategoryFilterDTO> pageQueryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
Page<CategoryPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
|
||||
LambdaQueryWrapper<CategoryPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CategoryPO::getCompanyId, companyId);
|
||||
|
||||
CategoryFilterDTO filter = pageQueryDTO.getFilters();
|
||||
if (filter != null) {
|
||||
if (filter.getName() != null && !filter.getName().trim().isEmpty()) {
|
||||
wrapper.like(CategoryPO::getName, filter.getName());
|
||||
}
|
||||
if (filter.getParentId() != null) {
|
||||
wrapper.eq(CategoryPO::getParentId, filter.getParentId());
|
||||
}
|
||||
}
|
||||
|
||||
wrapper.orderByAsc(CategoryPO::getSortOrder).orderByDesc(CategoryPO::getCreateTime);
|
||||
|
||||
IPage<CategoryPO> pageResult = this.page(page, wrapper);
|
||||
|
||||
// 预加载所有父级名称
|
||||
List<Long> parentIds = pageResult.getRecords().stream()
|
||||
.map(CategoryPO::getParentId)
|
||||
.filter(pid -> pid != null)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
Map<Long, String> parentNameMap = buildParentNameMap(parentIds, companyId);
|
||||
|
||||
List<CategoryVO> voList = pageResult.getRecords().stream()
|
||||
.map(po -> convertToVO(po, parentNameMap))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CategoryVO> getCategoryTree() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
LambdaQueryWrapper<CategoryPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CategoryPO::getCompanyId, companyId)
|
||||
.orderByAsc(CategoryPO::getSortOrder)
|
||||
.orderByDesc(CategoryPO::getCreateTime);
|
||||
List<CategoryPO> allCategories = this.list(wrapper);
|
||||
|
||||
Map<Long, String> parentNameMap = buildParentNameMap(
|
||||
allCategories.stream().map(CategoryPO::getParentId).filter(pid -> pid != null).distinct().collect(Collectors.toList()),
|
||||
companyId
|
||||
);
|
||||
|
||||
// 按 parentId 分组
|
||||
Map<Long, List<CategoryPO>> byParent = allCategories.stream()
|
||||
.collect(Collectors.groupingBy(c -> c.getParentId() == null ? 0L : c.getParentId()));
|
||||
|
||||
// 构建树,parentId == null 的视为顶级(用0作为key)
|
||||
return buildTree(new ArrayList<>(byParent.getOrDefault(0L, List.of())), byParent, parentNameMap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CategoryVO> getCategoryList() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
LambdaQueryWrapper<CategoryPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CategoryPO::getCompanyId, companyId)
|
||||
.orderByAsc(CategoryPO::getSortOrder)
|
||||
.orderByDesc(CategoryPO::getCreateTime);
|
||||
List<CategoryPO> categories = this.list(wrapper);
|
||||
|
||||
Map<Long, String> parentNameMap = buildParentNameMap(
|
||||
categories.stream().map(CategoryPO::getParentId).filter(pid -> pid != null).distinct().collect(Collectors.toList()),
|
||||
companyId
|
||||
);
|
||||
|
||||
return categories.stream()
|
||||
.map(po -> convertToVO(po, parentNameMap))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 targetId 是否是 ancestorId 的后代
|
||||
*/
|
||||
private boolean isDescendant(Long ancestorId, Long targetId) {
|
||||
if (targetId == null) return false;
|
||||
if (ancestorId.equals(targetId)) return true;
|
||||
CategoryPO target = this.getById(targetId);
|
||||
if (target == null) return false;
|
||||
return isDescendant(ancestorId, target.getParentId());
|
||||
}
|
||||
|
||||
private Map<Long, String> buildParentNameMap(List<Long> parentIds, Long companyId) {
|
||||
if (parentIds.isEmpty()) return Map.of();
|
||||
LambdaQueryWrapper<CategoryPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(CategoryPO::getCompanyId, companyId).in(CategoryPO::getId, parentIds);
|
||||
return this.list(w).stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName));
|
||||
}
|
||||
|
||||
private List<CategoryVO> buildTree(List<CategoryPO> nodes, Map<Long, List<CategoryPO>> byParent, Map<Long, String> parentNameMap) {
|
||||
return nodes.stream().map(node -> {
|
||||
CategoryVO vo = convertToVO(node, parentNameMap);
|
||||
Long key = node.getId();
|
||||
if (byParent.containsKey(key)) {
|
||||
vo.setChildren(buildTree(new ArrayList<>(byParent.get(key)), byParent, parentNameMap));
|
||||
}
|
||||
return vo;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private CategoryVO convertToVO(CategoryPO po) {
|
||||
return convertToVO(po, Map.of());
|
||||
}
|
||||
|
||||
private CategoryVO convertToVO(CategoryPO po, Map<Long, String> parentNameMap) {
|
||||
CategoryVO vo = new CategoryVO();
|
||||
BeanUtils.copyProperties(po, vo);
|
||||
if (po.getParentId() != null) {
|
||||
vo.setParentName(parentNameMap.getOrDefault(po.getParentId(), null));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+6
@@ -35,6 +35,12 @@ public class CreateProductDTO {
|
||||
@Schema(description = "商品编码", example = "IPHONE15PRO001")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@Schema(description = "类目ID", example = "1")
|
||||
private Long categoryId;
|
||||
|
||||
/**
|
||||
* 主图图片ID
|
||||
*/
|
||||
|
||||
+6
@@ -15,6 +15,12 @@ public class ProductFilterDTO {
|
||||
@Schema(description = "商品名称(模糊查询)", example = "iPhone")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 类目ID(精准查询)
|
||||
*/
|
||||
@Schema(description = "类目ID(精准查询)", example = "1")
|
||||
private Long categoryId;
|
||||
|
||||
/**
|
||||
* 商品编码(精准查询)
|
||||
*/
|
||||
|
||||
+6
@@ -35,6 +35,12 @@ public class UpdateProductDTO {
|
||||
@Schema(description = "商品编码", example = "IPHONE15PRO001")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@Schema(description = "类目ID", example = "1")
|
||||
private Long categoryId;
|
||||
|
||||
/**
|
||||
* 主图图片ID
|
||||
*/
|
||||
|
||||
+6
@@ -26,6 +26,12 @@ public class ProductPO {
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@TableField("category_id")
|
||||
private Long categoryId;
|
||||
|
||||
/**
|
||||
* 商品名称
|
||||
*/
|
||||
|
||||
+12
@@ -25,6 +25,18 @@ public class ProductVO {
|
||||
@Schema(description = "公司ID", example = "1")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 类目ID
|
||||
*/
|
||||
@Schema(description = "类目ID", example = "1")
|
||||
private Long categoryId;
|
||||
|
||||
/**
|
||||
* 类目名称
|
||||
*/
|
||||
@Schema(description = "类目名称", example = "手机数码")
|
||||
private String categoryName;
|
||||
|
||||
/**
|
||||
* 商品名称
|
||||
*/
|
||||
|
||||
+22
-5
@@ -16,7 +16,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductDTO
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductResultDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductResultDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductSpecDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
|
||||
@@ -24,6 +23,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.file.mapper.SysFileMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.file.model.po.SysFilePO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
@@ -42,11 +42,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final SysFileMapper sysFileMapper;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final CategoryService categoryService;
|
||||
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper, @Lazy ProductSpecService productSpecService) {
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper,
|
||||
@Lazy ProductSpecService productSpecService, @Lazy CategoryService categoryService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileMapper = sysFileMapper;
|
||||
this.productSpecService = productSpecService;
|
||||
this.categoryService = categoryService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -330,7 +333,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
if (filter.getProductCode() != null && !filter.getProductCode().trim().isEmpty()) {
|
||||
wrapper.eq(ProductPO::getProductCode, filter.getProductCode());
|
||||
}
|
||||
|
||||
|
||||
// 类目ID(精准查询)
|
||||
if (filter.getCategoryId() != null) {
|
||||
wrapper.eq(ProductPO::getCategoryId, filter.getCategoryId());
|
||||
}
|
||||
|
||||
// 处理规格相关的过滤条件
|
||||
if ((filter.getSpecCode() != null && !filter.getSpecCode().trim().isEmpty()) ||
|
||||
(filter.getSpecName() != null && !filter.getSpecName().trim().isEmpty())) {
|
||||
@@ -388,7 +396,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private ProductVO convertToVO(ProductPO product) {
|
||||
ProductVO productVO = new ProductVO();
|
||||
BeanUtils.copyProperties(product, productVO);
|
||||
|
||||
|
||||
// 查询主图文件信息并生成访问URL
|
||||
if (product.getMainImageId() != null) {
|
||||
SysFilePO mainImageFile = sysFileMapper.selectById(product.getMainImageId());
|
||||
@@ -397,7 +405,16 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
productVO.setMainImage(mainImageUrl);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 查询类目名称
|
||||
if (product.getCategoryId() != null) {
|
||||
top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO category =
|
||||
categoryService.getById(product.getCategoryId());
|
||||
if (category != null) {
|
||||
productVO.setCategoryName(category.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// 查询商品规格列表
|
||||
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
|
||||
specWrapper.eq(ProductSpecPO::getProductId, product.getId())
|
||||
|
||||
@@ -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[];
|
||||
}
|
||||
}
|
||||
+182
@@ -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>
|
||||
+30
-1
@@ -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">
|
||||
|
||||
+6
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user