refactor: 重构内部推广费模块

This commit is contained in:
2026-08-17 10:20:34 +08:00
parent b4455a4788
commit d91b7cd168
60 changed files with 901 additions and 2586 deletions
+1 -1
View File
@@ -81,7 +81,7 @@ ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/
| 店铺按品类汇总导出 | POST /api/bi/shop/export/summary-by-category | Excel |
| 商品概览 | POST /api/bi/product/overview | 单商品统计 |
| 订单 | /ec/order/* | CRUD |
| 推广费 | /ec/promotion-fee/* | CRUD |
| 广告费 | /ec/ad-fee/* | CRUD |
| 刷单 | /ec/brush-order/* | CRUD |
| 商品 | /ec/product/* | CRUD |
@@ -2,10 +2,10 @@
-- 拼多多商品广告费/推广费(按日)数据库设计
--
-- 设计原则:
-- 1. 与 ec_promotion_fee(内部经营推广费)分离,本表存渠道侧按日统计原始/同步数据
-- 1. 与 ec_ad_fee(内部经营广告费)分离,本表存渠道侧按日统计原始/同步数据
-- 2. 广告费维度跟随 channel_pdd_goods(SPU),用 goods_id(+ channel_shop_id)关联商品
-- 3. 统计粒度为「渠道店铺商品 × 自然日」一条;同日重复同步按唯一键覆盖/幂等写入
-- 4. 金额单位:元(decimal),与 ec_promotion_fee.fee_amount 一致;后续若接口以分为单位需入库前换算
-- 4. 金额单位:元(decimal),与 ec_ad_fee.fee_amount 一致;后续若接口以分为单位需入库前换算
-- 5. channel_shop_id = channel_pdd_shop.id(非 ec_shop.id);mall_id 为拼多多侧店铺号
-- ========================================
@@ -0,0 +1,35 @@
-- ========================================
-- 电商-广告推广费域设计
-- ec_ad_fee
-- ========================================
-- ----------------------------
-- 广告推广费记录表
-- ----------------------------
DROP TABLE IF EXISTS `ec_ad_fee`;
CREATE TABLE `ec_ad_fee` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '广告推广费记录ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品ID(与 fee_date 联合唯一;为空时不参与唯一约束)',
`campaign_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '推广活动名称',
`fee_amount` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费金额',
`fee_date` date NOT NULL COMMENT '推广费发生日期',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL 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,
UNIQUE INDEX `uk_ec_ad_fee_product_date`(`product_id` ASC, `fee_date` ASC) USING BTREE,
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
INDEX `idx_shop_id`(`shop_id` ASC) USING BTREE,
INDEX `idx_fee_date`(`fee_date` ASC) USING BTREE,
INDEX `fk_ec_ad_fee_creator`(`create_by` ASC) USING BTREE,
INDEX `fk_ec_ad_fee_updater`(`update_by` ASC) USING BTREE,
CONSTRAINT `fk_ec_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_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 = '电商-广告推广费记录表' ;
@@ -1,69 +0,0 @@
-- ========================================
-- 电商-推广费域设计
-- ec_promotion_fee_type / ec_promotion_fee
-- ========================================
-- ----------------------------
-- 推广费类型表
-- ----------------------------
DROP TABLE IF EXISTS `ec_promotion_fee_type`;
CREATE TABLE `ec_promotion_fee_type` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '推广费类型ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`type_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '类型名称',
`description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '类型描述',
`calculation_method` tinyint NOT NULL DEFAULT 1 COMMENT '计算方式 1固定金额 2按比例 3按点击 4按展示',
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序',
`is_active` tinyint NOT NULL DEFAULT 1 COMMENT '是否启用 0禁用 1启用',
`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,
UNIQUE INDEX `uk_company_type_name`(`company_id` ASC, `type_name` ASC) USING BTREE,
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
INDEX `idx_sort_order`(`sort_order` ASC) USING BTREE,
INDEX `idx_is_active`(`is_active` ASC) USING BTREE,
INDEX `fk_ec_promotion_fee_type_creator`(`create_by` ASC) USING BTREE,
INDEX `fk_ec_promotion_fee_type_updater`(`update_by` ASC) USING BTREE,
CONSTRAINT `fk_ec_promotion_fee_type_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_type_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_type_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_promotion_fee`;
CREATE TABLE `ec_promotion_fee` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '推广费记录ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID',
`category_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '类目ID(可选,无商品时可用于类目级推广费)',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品ID(可选)',
`fee_type_id` bigint UNSIGNED NOT NULL COMMENT '推广费类型ID',
`campaign_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '推广活动名称',
`fee_amount` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费金额',
`fee_date` date NOT NULL COMMENT '推广费发生日期',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL 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_shop_id`(`shop_id` ASC) USING BTREE,
INDEX `idx_category_id`(`category_id` ASC) USING BTREE,
INDEX `idx_product_id`(`product_id` ASC) USING BTREE,
INDEX `idx_fee_type_id`(`fee_type_id` ASC) USING BTREE,
INDEX `idx_fee_date`(`fee_date` ASC) USING BTREE,
INDEX `fk_ec_promotion_fee_creator`(`create_by` ASC) USING BTREE,
INDEX `fk_ec_promotion_fee_updater`(`update_by` ASC) USING BTREE,
CONSTRAINT `fk_ec_promotion_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_category` FOREIGN KEY (`category_id`) REFERENCES `ec_category` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_type` FOREIGN KEY (`fee_type_id`) REFERENCES `ec_promotion_fee_type` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_ec_promotion_fee_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 = '电商-推广费记录表' ;
@@ -0,0 +1,51 @@
-- ec_promotion_fee → ec_ad_fee:去掉推广费类型、类目,并删除类型表
-- 1) 去掉对类型 / 类目的外键与索引、列
ALTER TABLE `ec_promotion_fee`
DROP FOREIGN KEY `fk_ec_promotion_fee_type`,
DROP FOREIGN KEY `fk_ec_promotion_fee_category`;
ALTER TABLE `ec_promotion_fee`
DROP INDEX `idx_fee_type_id`,
DROP INDEX `idx_category_id`;
ALTER TABLE `ec_promotion_fee`
DROP COLUMN `fee_type_id`,
DROP COLUMN `category_id`;
-- 2) 重命名表
RENAME TABLE `ec_promotion_fee` TO `ec_ad_fee`;
-- 3) 外键 / 索引名对齐新表(先删旧约束再重建)
ALTER TABLE `ec_ad_fee`
DROP FOREIGN KEY `fk_ec_promotion_fee_company`,
DROP FOREIGN KEY `fk_ec_promotion_fee_creator`,
DROP FOREIGN KEY `fk_ec_promotion_fee_shop`,
DROP FOREIGN KEY `fk_ec_promotion_fee_product`,
DROP FOREIGN KEY `fk_ec_promotion_fee_updater`;
ALTER TABLE `ec_ad_fee`
DROP INDEX `fk_ec_promotion_fee_creator`,
DROP INDEX `fk_ec_promotion_fee_updater`;
ALTER TABLE `ec_ad_fee`
ADD INDEX `fk_ec_ad_fee_creator`(`create_by` ASC) USING BTREE,
ADD INDEX `fk_ec_ad_fee_updater`(`update_by` ASC) USING BTREE,
ADD CONSTRAINT `fk_ec_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_ad_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_ad_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_ad_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_ad_fee_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `ec_ad_fee` COMMENT = '电商-广告推广费记录表';
-- 4) 删除推广费类型表
DROP TABLE IF EXISTS `ec_promotion_fee_type`;
-- 5) 下线「推广费用类型」菜单(若存在)
UPDATE `sys_menu`
SET `status` = 0,
`update_time` = CURRENT_TIMESTAMP
WHERE `name` IN ('推广费用类型', 'PromotionFeeType')
OR `path` IN ('/promotion-fee-type', 'promotion-fee-type')
OR `component` LIKE '%promotion-fee-type%';
@@ -0,0 +1,73 @@
-- 模块命名:promotion-fee → ad-fee(仅菜单路径/标题;不提供广告费开放接口)
-- 1) 清理广告费相关开放 scope(含旧 promotion_fee 与误加的 ad_fee)
DELETE oakp
FROM `open_api_key_permission` oakp
INNER JOIN `org_company_permission` ocp ON ocp.id = oakp.company_permission_id
INNER JOIN `sys_permission` p ON p.id = ocp.permission_id
WHERE p.`code` IN (
'open:scope:promotion_fee:import',
'open:scope:promotion_fee:read',
'open:scope:ad_fee:import',
'open:scope:ad_fee:read'
);
DELETE ocp
FROM `org_company_permission` ocp
INNER JOIN `sys_permission` p ON p.id = ocp.permission_id
WHERE p.`code` IN (
'open:scope:promotion_fee:import',
'open:scope:promotion_fee:read',
'open:scope:ad_fee:import',
'open:scope:ad_fee:read'
);
DELETE mp
FROM `sys_menu_permission` mp
INNER JOIN `sys_permission` p ON p.id = mp.permission_id
WHERE p.`code` IN (
'open:scope:promotion_fee:import',
'open:scope:promotion_fee:read',
'open:scope:ad_fee:import',
'open:scope:ad_fee:read'
);
DELETE pp
FROM `org_position_permission` pp
INNER JOIN `sys_permission` p ON p.id = pp.permission_id
WHERE p.`code` IN (
'open:scope:promotion_fee:import',
'open:scope:promotion_fee:read',
'open:scope:ad_fee:import',
'open:scope:ad_fee:read'
);
DELETE FROM `sys_permission`
WHERE `code` IN (
'open:scope:promotion_fee:import',
'open:scope:promotion_fee:read',
'open:scope:ad_fee:import',
'open:scope:ad_fee:read'
);
-- 2) 菜单:广告费导入
UPDATE `sys_menu`
SET `title` = '广告费导入',
`name` = '广告费导入',
`path` = '/import/ad-fee',
`component` = '/ecommerce/import/ad-fee/index',
`update_time` = CURRENT_TIMESTAMP
WHERE `path` IN ('/import/promotion-fee', '/import/ad-fee')
OR `component` LIKE '%import/promotion-fee%'
OR `name` IN ('推广导入', '广告费导入');
-- 3) 菜单:广告费管理
UPDATE `sys_menu`
SET `title` = '广告费管理',
`name` = '广告费管理',
`path` = 'ad-fee',
`component` = '/ecommerce/ad-fee/index',
`update_time` = CURRENT_TIMESTAMP
WHERE `path` IN ('promotion-fee', 'ad-fee')
OR `component` LIKE '%/promotion-fee/index%'
OR `name` IN ('推广管理', '广告费管理');
@@ -0,0 +1,14 @@
-- ec_ad_fee:商品 + 推广日期联合唯一
-- 先清掉 (product_id, fee_date) 重复行(保留最小 id),再加唯一索引
DELETE t1
FROM `ec_ad_fee` t1
INNER JOIN `ec_ad_fee` t2
ON t1.`product_id` IS NOT NULL
AND t1.`product_id` = t2.`product_id`
AND t1.`fee_date` = t2.`fee_date`
AND t1.`id` > t2.`id`;
ALTER TABLE `ec_ad_fee`
DROP INDEX `idx_product_id`,
ADD UNIQUE INDEX `uk_ec_ad_fee_product_date`(`product_id` ASC, `fee_date` ASC) USING BTREE;
@@ -6,8 +6,10 @@ import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.ec.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po.AdFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import java.math.BigDecimal;
import java.time.LocalDate;
@@ -16,6 +18,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 工作台费用侧:推广费 / 刷单仍读 MySQL 小表(不进 Mongo)。
@@ -24,8 +28,9 @@ import java.util.Map;
@RequiredArgsConstructor
public class BiWorkbenchFeeLoader {
private final PromotionFeeMapper promotionFeeMapper;
private final AdFeeMapper adFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final ProductMapper productMapper;
public FeeBundle load(Long companyId, List<Long> shopIds, LocalDate start, LocalDate end) {
if (companyId == null || shopIds == null || shopIds.isEmpty() || start == null || end == null) {
@@ -37,24 +42,24 @@ public class BiWorkbenchFeeLoader {
private List<OverviewAggRows.PromotionRow> loadPromotionRows(
Long companyId, List<Long> shopIds, LocalDate start, LocalDate end) {
List<PromotionFeePO> fees = promotionFeeMapper.selectList(new LambdaQueryWrapper<PromotionFeePO>()
.eq(PromotionFeePO::getCompanyId, companyId)
.in(PromotionFeePO::getShopId, shopIds)
.ge(PromotionFeePO::getFeeDate, start)
.le(PromotionFeePO::getFeeDate, end));
List<AdFeePO> fees = adFeeMapper.selectList(new LambdaQueryWrapper<AdFeePO>()
.eq(AdFeePO::getCompanyId, companyId)
.in(AdFeePO::getShopId, shopIds)
.ge(AdFeePO::getFeeDate, start)
.le(AdFeePO::getFeeDate, end));
Map<Long, Long> productCategoryIds = loadProductCategoryIds(fees);
Map<String, OverviewAggRows.PromotionRow> merged = new HashMap<>();
for (PromotionFeePO fee : fees) {
for (AdFeePO fee : fees) {
if (fee == null || fee.getShopId() == null) {
continue;
}
Long productId = fee.getProductId();
Long categoryId = fee.getCategoryId();
String key = fee.getShopId() + ":" + productId + ":" + categoryId;
String key = fee.getShopId() + ":" + productId;
OverviewAggRows.PromotionRow row = merged.computeIfAbsent(key, k -> {
OverviewAggRows.PromotionRow r = new OverviewAggRows.PromotionRow();
r.setShopId(fee.getShopId());
r.setProductId(productId);
r.setCategoryId(categoryId);
r.setCategoryId(productId != null ? productCategoryIds.get(productId) : null);
r.setFeeAmount(BigDecimal.ZERO);
return r;
});
@@ -63,6 +68,24 @@ public class BiWorkbenchFeeLoader {
return new ArrayList<>(merged.values());
}
private Map<Long, Long> loadProductCategoryIds(List<AdFeePO> fees) {
List<Long> productIds = fees.stream()
.map(AdFeePO::getProductId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (productIds.isEmpty()) {
return Map.of();
}
Map<Long, Long> map = new HashMap<>();
for (ProductPO p : productMapper.selectBatchIds(productIds)) {
if (p != null && p.getId() != null) {
map.put(p.getId(), p.getCategoryId());
}
}
return map;
}
private List<OverviewAggRows.BrushRow> loadBrushRows(
Long companyId, List<Long> shopIds, LocalDate start, LocalDate end) {
LocalDateTime startDt = start.atStartOfDay();
@@ -0,0 +1,83 @@
package top.xyquan.ecomdmbbackend.modules.ec.adfee.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 lombok.RequiredArgsConstructor;
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.ec.adfee.model.dto.CreateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.AdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.UpdateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo.AdFeeFieldVO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo.AdFeeFieldConstants;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo.AdFeeVO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.service.AdFeeService;
import java.util.List;
/**
* 广告费记录控制器
*/
@RestController
@RequestMapping("/api/ec/ad-fee")
@RequiredArgsConstructor
@Tag(name = "电商-广告费记录管理", description = "广告费记录相关接口")
public class AdFeeController {
private final AdFeeService adFeeService;
@PostMapping
@Operation(summary = "创建广告费记录", description = "创建新的广告费记录")
@RequirePermission(value = "ec:order:create", description = "创建广告费记录", allowSuper = true)
public ApiResponse<Long> createAdFee(@Valid @RequestBody CreateAdFeeDTO dto) {
Long id = adFeeService.createAdFee(dto);
return ApiResponse.success("广告费记录创建成功", id);
}
@PutMapping
@Operation(summary = "更新广告费记录", description = "更新广告费记录信息")
@RequirePermission(value = "ec:order:update", description = "更新广告费记录", allowSuper = true)
public ApiResponse<Void> updateAdFee(@Valid @RequestBody UpdateAdFeeDTO dto) {
adFeeService.updateAdFee(dto);
return ApiResponse.success("广告费记录更新成功");
}
@DeleteMapping("/{id}")
@Operation(summary = "删除广告费记录", description = "删除指定的广告费记录")
@RequirePermission(value = "ec:order:delete", description = "删除广告费记录", allowSuper = true)
public ApiResponse<Void> deleteAdFee(
@Parameter(description = "记录ID", required = true) @PathVariable Long id) {
adFeeService.deleteAdFee(id);
return ApiResponse.success("广告费记录删除成功");
}
@GetMapping("/{id}")
@Operation(summary = "查询广告费记录详情", description = "根据ID查询广告费记录详情")
@RequirePermission(value = "ec:order:read", description = "查询广告费记录详情", allowSuper = true)
public ApiResponse<AdFeeVO> getAdFeeById(
@Parameter(description = "记录ID", required = true) @PathVariable Long id) {
AdFeeVO vo = adFeeService.getAdFeeById(id);
return ApiResponse.success("获取广告费记录详情成功", vo);
}
@PostMapping("/list")
@Operation(summary = "分页查询广告费记录", description = "分页查询广告费记录列表")
@RequirePermission(value = "ec:order:read", description = "查询广告费记录列表", allowSuper = true)
public ApiResponse<PageResultVO<AdFeeVO>> getAdFeePage(
@Valid @RequestBody PageQueryDTO<AdFeeFilterDTO> pageQueryDTO) {
PageResultVO<AdFeeVO> result = adFeeService.getAdFeePage(pageQueryDTO);
return ApiResponse.success("获取广告费记录列表成功", result);
}
@GetMapping("/fields")
@Operation(summary = "获取广告费导入字段定义", description = "获取广告费导入时可映射的系统字段列表")
@RequirePermission(value = "ec:order:read", description = "查询导入字段", allowSuper = true)
public ApiResponse<List<AdFeeFieldVO>> getAdFeeFields() {
return ApiResponse.success("获取广告费导入字段成功", AdFeeFieldConstants.FIELDS);
}
}
@@ -0,0 +1,21 @@
package top.xyquan.ecomdmbbackend.modules.ec.adfee.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po.AdFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.AdFeeFilterDTO;
/**
* 广告费记录Mapper
*/
@Mapper
public interface AdFeeMapper extends BaseMapper<AdFeePO> {
/**
* 分页查询广告费记录
*/
IPage<AdFeePO> selectPageWithFilter(Page<AdFeePO> page, @Param("filter") AdFeeFilterDTO filter);
}
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -6,11 +6,11 @@ import lombok.Data;
import java.time.LocalDate;
/**
* 推广费记录筛选DTO
* 广告费记录筛选DTO
*/
@Data
@Schema(description = "推广费记录筛选DTO")
public class PromotionFeeFilterDTO {
@Schema(description = "广告费记录筛选DTO")
public class AdFeeFilterDTO {
/**
* 店铺ID
@@ -18,24 +18,12 @@ public class PromotionFeeFilterDTO {
@Schema(description = "店铺ID", example = "1")
private Long shopId;
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1")
private Long feeTypeId;
/**
* 商品ID(可选)
*/
@Schema(description = "商品ID(可选)", example = "1")
private Long productId;
/**
* 类目ID(可选)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 推广费发生日期开始
*/
@@ -47,4 +35,4 @@ public class PromotionFeeFilterDTO {
*/
@Schema(description = "推广费发生日期结束", example = "2024-01-31")
private LocalDate feeDateEnd;
}
}
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
@@ -8,18 +8,11 @@ import java.math.BigDecimal;
import java.time.LocalDate;
/**
* 更新推广费记录DTO
* 创建广告费记录DTO
*/
@Data
@Schema(description = "更新推广费记录DTO")
public class UpdatePromotionFeeDTO {
/**
* 推广费记录ID
*/
@Schema(description = "推广费记录ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广费记录ID不能为空")
private Long id;
@Schema(description = "创建广告费记录DTO")
public class CreateAdFeeDTO {
/**
* 店铺ID
@@ -28,19 +21,6 @@ public class UpdatePromotionFeeDTO {
@NotNull(message = "店铺ID不能为空")
private Long shopId;
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广费类型ID不能为空")
private Long feeTypeId;
/**
* 类目ID(可选,类目级推广费)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 商品ID(可选,关联到具体商品)
*/
@@ -72,4 +52,4 @@ public class UpdatePromotionFeeDTO {
*/
@Schema(description = "备注", example = "双十一期间推广费用")
private String remark;
}
}
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
@@ -8,11 +8,18 @@ import java.math.BigDecimal;
import java.time.LocalDate;
/**
* 创建推广费记录DTO
* 更新广告费记录DTO
*/
@Data
@Schema(description = "创建推广费记录DTO")
public class CreatePromotionFeeDTO {
@Schema(description = "更新广告费记录DTO")
public class UpdateAdFeeDTO {
/**
* 广告费记录ID
*/
@Schema(description = "广告费记录ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "广告费记录ID不能为空")
private Long id;
/**
* 店铺ID
@@ -21,19 +28,6 @@ public class CreatePromotionFeeDTO {
@NotNull(message = "店铺ID不能为空")
private Long shopId;
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广费类型ID不能为空")
private Long feeTypeId;
/**
* 类目ID(可选,类目级推广费)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 商品ID(可选,关联到具体商品)
*/
@@ -65,4 +59,4 @@ public class CreatePromotionFeeDTO {
*/
@Schema(description = "备注", example = "双十一期间推广费用")
private String remark;
}
}
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -9,15 +9,15 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 电商-推广费记录实体
* 电商-广告费记录实体(表 ec_ad_fee)
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ec_promotion_fee")
public class PromotionFeePO {
@TableName("ec_ad_fee")
public class AdFeePO {
/**
* 推广费记录ID
* 广告费记录ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@@ -34,18 +34,6 @@ public class PromotionFeePO {
@TableField("shop_id")
private Long shopId;
/**
* 类目ID(可选,无商品时可用于类目级推广费)
*/
@TableField("category_id")
private Long categoryId;
/**
* 推广费类型ID
*/
@TableField("fee_type_id")
private Long feeTypeId;
/**
* 商品ID(可选)
*/
@@ -53,19 +41,19 @@ public class PromotionFeePO {
private Long productId;
/**
* 推广活动名称
* 广告活动名称
*/
@TableField("campaign_name")
private String campaignName;
/**
* 推广费金额
* 广告费金额
*/
@TableField("fee_amount")
private BigDecimal feeAmount;
/**
* 推广费发生日期
* 广告费发生日期
*/
@TableField("fee_date")
private LocalDate feeDate;
@@ -1,18 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo;
import java.util.Arrays;
import java.util.List;
public class PromotionFeeFieldConstants {
public class AdFeeFieldConstants {
public static final List<PromotionFeeFieldVO> FIELDS = Arrays.asList(
public static final List<AdFeeFieldVO> FIELDS = Arrays.asList(
create("campaignName", "推广活动名称", "推广活动名称", true, 1, "string"),
create("feeAmount", "推广费金额", "推广费金额(元)", true, 2, "number")
);
private static PromotionFeeFieldVO create(String fieldName, String fieldLabel, String fileFieldName,
private static AdFeeFieldVO create(String fieldName, String fieldLabel, String fileFieldName,
boolean required, int sort, String dataType) {
PromotionFeeFieldVO vo = new PromotionFeeFieldVO();
AdFeeFieldVO vo = new AdFeeFieldVO();
vo.setFieldName(fieldName);
vo.setFieldLabel(fieldLabel);
vo.setFileFieldName(fileFieldName);
@@ -1,11 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "推广费导入字段信息VO")
public class PromotionFeeFieldVO {
@Schema(description = "广告费导入字段信息VO")
public class AdFeeFieldVO {
@Schema(description = "数据库字段名", example = "campaign_name")
private String fieldName;
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -8,16 +8,16 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 推广费记录VO
* 广告费记录VO
*/
@Data
@Schema(description = "推广费记录VO")
public class PromotionFeeVO {
@Schema(description = "广告费记录VO")
public class AdFeeVO {
/**
* 推广费记录ID
* 广告费记录ID
*/
@Schema(description = "推广费记录ID", example = "1")
@Schema(description = "广告费记录ID", example = "1")
private Long id;
/**
@@ -38,30 +38,6 @@ public class PromotionFeeVO {
@Schema(description = "店铺名称", example = "旗舰店")
private String shopName;
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1")
private Long feeTypeId;
/**
* 推广费类型名称
*/
@Schema(description = "推广费类型名称", example = "直通车")
private String feeTypeName;
/**
* 类目ID(可选)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 类目名称
*/
@Schema(description = "类目名称", example = "数码")
private String categoryName;
/**
* 商品ID(可选)
*/
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.ec.adfee.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.CreateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.AdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.UpdateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo.AdFeeVO;
/**
* 广告费记录服务接口
*/
public interface AdFeeService {
/**
* 创建广告费记录
*/
Long createAdFee(CreateAdFeeDTO dto);
/**
* 更新广告费记录
*/
void updateAdFee(UpdateAdFeeDTO dto);
/**
* 删除广告费记录
*/
void deleteAdFee(Long id);
/**
* 根据ID查询广告费记录
*/
AdFeeVO getAdFeeById(Long id);
/**
* 分页查询广告费记录
*/
PageResultVO<AdFeeVO> getAdFeePage(PageQueryDTO<AdFeeFilterDTO> pageQueryDTO);
}
@@ -1,5 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.service.impl;
package top.xyquan.ecomdmbbackend.modules.ec.adfee.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
@@ -12,8 +13,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.po.ImportTaskPO;
import top.xyquan.ecomdmbbackend.modules.ec.importtask.util.ImportTaskMessageAppender;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po.AdFeePO;
import java.io.*;
import java.math.BigDecimal;
@@ -22,17 +23,18 @@ import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 推广费导入处理器
* 广告费导入处理器
* 负责解析 CSV/Excel 文件中的推广费数据,按字段映射提取 campaignName/feeAmount,
* 从文件列中直接读取 feeTypeId/categoryId/productId,批量写入 ec_promotion_fee 表。
* 从文件列中直接读取 productId,按 product_id + fee_date 联合唯一 upsert 写入 ec_ad_fee。
*/
@Service
public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper, PromotionFeePO> {
public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
private static final Logger log = LoggerFactory.getLogger(PromotionFeeImportProcessor.class);
/** 每批插入条数 */
private static final Logger log = LoggerFactory.getLogger(AdFeeImportProcessor.class);
/** 每批处理条数 */
private static final int BATCH_SIZE = 500;
/** 推广费金额不合规时的统一失败原因 */
private static final String INVALID_FEE_AMOUNT_REASON = "推广费金额为空或须大于0";
@@ -52,33 +54,99 @@ public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper,
return new ImportResult(0, 0, 0, "文件中没有有效数据");
}
List<AdFeePO> records = collapseByProductDate(parseResult.records);
int success = 0;
int insertFailCount = 0;
int upsertFailCount = 0;
ImportTaskMessageAppender detailMessages = parseResult.detailMessages;
for (int i = 0; i < parseResult.records.size(); i += BATCH_SIZE) {
int end = Math.min(i + BATCH_SIZE, parseResult.records.size());
List<PromotionFeePO> batch = parseResult.records.subList(i, end);
for (int i = 0; i < records.size(); i += BATCH_SIZE) {
int end = Math.min(i + BATCH_SIZE, records.size());
List<AdFeePO> batch = records.subList(i, end);
try {
saveBatch(batch);
success += batch.size();
success += upsertBatch(batch);
} catch (Exception e) {
insertFailCount += batch.size();
int startRow = parseResult.recordStartRows.get(i);
int endRow = parseResult.recordStartRows.get(end - 1);
detailMessages.appendDetailLine(String.format("第%d~%d行:批量插入失败,%s",
startRow, endRow, e.getMessage()));
log.error("批量插入推广费记录失败", e);
upsertFailCount += batch.size();
detailMessages.appendDetailLine(String.format("第%d~%d条:批量写入失败,%s",
i + 1, end, e.getMessage()));
log.error("批量写入广告费记录失败", e);
}
}
return new ImportResult(
parseResult.totalCount,
success,
parseResult.failCount + insertFailCount,
parseResult.failCount + upsertFailCount,
detailMessages.build());
}
/**
* 同文件内相同 productId + feeDate 保留最后一行,避免撞唯一键。
*/
private List<AdFeePO> collapseByProductDate(List<AdFeePO> records) {
LinkedHashMap<String, AdFeePO> withProduct = new LinkedHashMap<>();
List<AdFeePO> withoutProduct = new ArrayList<>();
for (AdFeePO po : records) {
if (po.getProductId() == null) {
withoutProduct.add(po);
continue;
}
withProduct.put(po.getProductId() + "|" + po.getFeeDate(), po);
}
List<AdFeePO> result = new ArrayList<>(withProduct.values());
result.addAll(withoutProduct);
return result;
}
private int upsertBatch(List<AdFeePO> batch) {
if (batch.isEmpty()) {
return 0;
}
LocalDate feeDate = batch.get(0).getFeeDate();
List<Long> productIds = batch.stream()
.map(AdFeePO::getProductId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
Map<Long, AdFeePO> existingByProduct = new HashMap<>();
if (!productIds.isEmpty() && feeDate != null) {
List<AdFeePO> existing = list(new LambdaQueryWrapper<AdFeePO>()
.eq(AdFeePO::getFeeDate, feeDate)
.in(AdFeePO::getProductId, productIds));
for (AdFeePO po : existing) {
existingByProduct.put(po.getProductId(), po);
}
}
List<AdFeePO> toInsert = new ArrayList<>();
List<AdFeePO> toUpdate = new ArrayList<>();
for (AdFeePO incoming : batch) {
if (incoming.getProductId() == null) {
toInsert.add(incoming);
continue;
}
AdFeePO existing = existingByProduct.get(incoming.getProductId());
if (existing == null) {
toInsert.add(incoming);
continue;
}
existing.setShopId(incoming.getShopId());
existing.setCampaignName(incoming.getCampaignName());
existing.setFeeAmount(incoming.getFeeAmount());
existing.setRemark(incoming.getRemark());
existing.setUpdateBy(incoming.getUpdateBy());
toUpdate.add(existing);
}
if (!toInsert.isEmpty()) {
saveBatch(toInsert);
}
if (!toUpdate.isEmpty()) {
updateBatchById(toUpdate);
}
return batch.size();
}
private ParseResult parseCsv(File file, Charset charset,
Map<String, String> fieldMapping, String feeDateStr,
ImportTaskPO task) throws IOException {
@@ -190,12 +258,10 @@ public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper,
BigDecimal feeAmount = new BigDecimal(normalizeFeeAmount(feeAmountStr));
PromotionFeePO po = new PromotionFeePO();
AdFeePO po = new AdFeePO();
po.setCompanyId(task.getCompanyId());
po.setShopId(task.getShopId());
po.setFeeDate(feeDate);
po.setFeeTypeId(parseLong(cellGetter.apply("feeTypeId")));
po.setCategoryId(parseLong(cellGetter.apply("categoryId")));
po.setProductId(parseLong(cellGetter.apply("productId")));
po.setCampaignName(campaignName);
po.setFeeAmount(feeAmount);
@@ -325,7 +391,7 @@ public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper,
}
private static class ParseResult {
final List<PromotionFeePO> records = new ArrayList<>();
final List<AdFeePO> records = new ArrayList<>();
/** 与 records 一一对应,用于插入失败时标注行号 */
final List<Integer> recordStartRows = new ArrayList<>();
final ImportTaskMessageAppender detailMessages = new ImportTaskMessageAppender();
@@ -334,17 +400,17 @@ public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper,
}
private static class RowBuildResult {
final PromotionFeePO po;
final AdFeePO po;
final String failReason;
final String campaignName;
private RowBuildResult(PromotionFeePO po, String failReason, String campaignName) {
private RowBuildResult(AdFeePO po, String failReason, String campaignName) {
this.po = po;
this.failReason = failReason;
this.campaignName = campaignName;
}
static RowBuildResult ok(PromotionFeePO po) {
static RowBuildResult ok(AdFeePO po) {
return new RowBuildResult(po, null, null);
}
@@ -0,0 +1,211 @@
package top.xyquan.ecomdmbbackend.modules.ec.adfee.service.impl;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ec.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.CreateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.AdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.dto.UpdateAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po.AdFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.vo.AdFeeVO;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.service.AdFeeService;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 广告费记录服务实现类
*/
@Service
public class AdFeeServiceImpl implements AdFeeService {
private final AdFeeMapper adFeeMapper;
private final CurrentUserContext currentUserContext;
private final ShopService shopService;
private final ProductService productService;
public AdFeeServiceImpl(AdFeeMapper adFeeMapper,
CurrentUserContext currentUserContext,
ShopService shopService,
ProductService productService) {
this.adFeeMapper = adFeeMapper;
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
}
/**
* 创建广告费记录
* @param dto 创建广告费记录DTO
* @return 广告费记录ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Long createAdFee(CreateAdFeeDTO dto) {
assertProductDateUnique(dto.getProductId(), dto.getFeeDate(), null);
AdFeePO po = new AdFeePO();
BeanCopyUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
adFeeMapper.insert(po);
return po.getId();
}
/**
* 更新广告费记录
* @param dto 更新广告费记录DTO
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAdFee(UpdateAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
AdFeePO existing = adFeeMapper.selectById(dto.getId());
if (existing == null || !existing.getCompanyId().equals(companyId)) {
throw new BusinessException("广告费记录不存在");
}
assertProductDateUnique(dto.getProductId(), dto.getFeeDate(), dto.getId());
AdFeePO po = new AdFeePO();
BeanCopyUtils.copyProperties(dto, po);
po.setUpdateBy(currentUserContext.getCurrentUserId());
po.setCompanyId(companyId);
adFeeMapper.updateById(po);
}
/**
* 删除广告费记录
* @param id 广告费记录ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAdFee(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
AdFeePO existing = adFeeMapper.selectById(id);
if (existing == null || !existing.getCompanyId().equals(companyId)) {
throw new BusinessException("广告费记录不存在");
}
adFeeMapper.deleteById(id);
}
/**
* 根据ID查询广告费记录
* @param id 广告费记录ID
* @return 广告费记录VO
*/
@Override
public AdFeeVO getAdFeeById(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
AdFeePO po = adFeeMapper.selectById(id);
if (po == null || !po.getCompanyId().equals(companyId)) {
throw new BusinessException("广告费记录不存在");
}
return convertToVO(po);
}
/**
* 获取广告费记录分页列表
* @param pageQueryDTO 分页查询DTO
* @return 分页结果VO
*/
@Override
public PageResultVO<AdFeeVO> getAdFeePage(PageQueryDTO<AdFeeFilterDTO> pageQueryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
Page<AdFeePO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
LambdaQueryWrapper<AdFeePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AdFeePO::getCompanyId, companyId);
AdFeeFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getShopId() != null) {
wrapper.eq(AdFeePO::getShopId, filter.getShopId());
}
if (filter.getProductId() != null) {
wrapper.eq(AdFeePO::getProductId, filter.getProductId());
}
if (filter.getFeeDateStart() != null) {
wrapper.ge(AdFeePO::getFeeDate, filter.getFeeDateStart());
}
if (filter.getFeeDateEnd() != null) {
wrapper.le(AdFeePO::getFeeDate, filter.getFeeDateEnd());
}
}
wrapper.orderByDesc(AdFeePO::getFeeDate)
.orderByDesc(AdFeePO::getCreateTime);
IPage<AdFeePO> pageResult = adFeeMapper.selectPage(page, wrapper);
List<AdFeeVO> voList = pageResult.getRecords().stream()
.map(this::convertToVO)
.collect(Collectors.toList());
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
/**
* 转换为VO
*/
private AdFeeVO convertToVO(AdFeePO po) {
AdFeeVO vo = new AdFeeVO();
BeanCopyUtils.copyProperties(po, vo);
// 填充店铺名称
if (po.getShopId() != null) {
try {
var shop = shopService.getById(po.getShopId());
if (shop != null) {
vo.setShopName(shop.getName());
}
} catch (Exception ignored) {
}
}
// 填充商品名称和编码
if (po.getProductId() != null) {
try {
ProductPO product = productService.getById(po.getProductId());
if (product != null) {
vo.setProductName(product.getName());
vo.setProductCode(product.getProductCode());
}
} catch (Exception ignored) {
}
}
return vo;
}
/**
* 商品 + 推广日期联合唯一(product_id 为空时不校验)
*/
private void assertProductDateUnique(Long productId, LocalDate feeDate, Long excludeId) {
if (productId == null || feeDate == null) {
return;
}
LambdaQueryWrapper<AdFeePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AdFeePO::getProductId, productId)
.eq(AdFeePO::getFeeDate, feeDate);
if (excludeId != null) {
wrapper.ne(AdFeePO::getId, excludeId);
}
Long count = adFeeMapper.selectCount(wrapper);
if (count != null && count > 0) {
throw new BusinessException("该商品在此推广日期已存在广告费记录");
}
}
}
@@ -17,7 +17,7 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.impl.PromotionFeeImportProcessor;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.service.impl.AdFeeImportProcessor;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopProductRelationMapper;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
@@ -52,7 +52,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 提取出的处理器(构造时组装,不单独持有 helper 的中间依赖)
private final OrderImportProcessor orderImportProcessor;
private final PromotionFeeImportProcessor promotionFeeImportProcessor;
private final AdFeeImportProcessor adFeeImportProcessor;
private final LicenseFeatureGuard licenseFeatureGuard;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
@@ -67,7 +67,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
SqlSessionFactory sqlSessionFactory,
OssService ossService,
SysFileService sysFileService,
PromotionFeeImportProcessor promotionFeeImportProcessor,
AdFeeImportProcessor adFeeImportProcessor,
LicenseFeatureGuard licenseFeatureGuard) {
this.importTaskService = importTaskService;
this.licenseFeatureGuard = licenseFeatureGuard;
@@ -76,7 +76,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
this.objectMapper = objectMapper;
this.ossService = ossService;
this.sysFileService = sysFileService;
this.promotionFeeImportProcessor = promotionFeeImportProcessor;
this.adFeeImportProcessor = adFeeImportProcessor;
ProductSkuImportHelper productSkuImportHelper = new ProductSkuImportHelper(
productMapper, productSkuService, productSkuCostService, shopProductRelationMapper);
@@ -101,7 +101,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
} else if ("product".equals(task.getType())) {
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
} else if ("promotion_record".equals(task.getType())) {
processPromotionFeeImport(task);
processAdFeeImport(task);
} else {
throw new BusinessException("不支持的导入类型: " + task.getType());
}
@@ -209,7 +209,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
private void processPromotionFeeImport(ImportTaskPO task) throws Exception {
private void processAdFeeImport(ImportTaskPO task) throws Exception {
com.fasterxml.jackson.databind.JsonNode rootNode;
try {
rootNode = objectMapper.readTree(task.getMapping());
@@ -250,7 +250,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
csvFile = localFile;
} else {
String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv";
tempOssFile = java.io.File.createTempFile("import-promotion-fee-", fileExt);
tempOssFile = java.io.File.createTempFile("import-ad-fee-", fileExt);
if (!ossService.downloadFile(storagePath, tempOssFile)) {
throw new BusinessException("从对象存储下载文件失败");
}
@@ -259,10 +259,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 前端 wizard 生成的 patched CSV 固定为 UTF-8,避免被误判为 GBK 导致表头乱码
boolean isPatchedPromotionCsv = filename != null
&& filename.toLowerCase().contains("promotion_fee_import_patched");
&& filename.toLowerCase().contains("ad_fee_import_patched");
Charset charset = isExcel || isPatchedPromotionCsv ? StandardCharsets.UTF_8
: detectFileEncoding(new java.io.BufferedInputStream(new java.io.FileInputStream(csvFile)));
PromotionFeeImportProcessor.ImportResult result = promotionFeeImportProcessor.processImport(
AdFeeImportProcessor.ImportResult result = adFeeImportProcessor.processImport(
task, csvFile, charset, fieldMapping, feeDateStr);
String finalStatus = result.failCount == 0 ? "success" : (result.successCount > 0 ? "success" : "failed");
@@ -1,83 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.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 lombok.RequiredArgsConstructor;
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.ec.promotion.model.dto.CreatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.PromotionFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeFieldVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeFieldConstants;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeService;
import java.util.List;
/**
* 推广费记录控制器
*/
@RestController
@RequestMapping("/api/ec/promotion-fee")
@RequiredArgsConstructor
@Tag(name = "电商-推广费记录管理", description = "推广费记录相关接口")
public class PromotionFeeController {
private final PromotionFeeService promotionFeeService;
@PostMapping
@Operation(summary = "创建推广费记录", description = "创建新的推广费记录")
@RequirePermission(value = "ec:order:create", description = "创建推广费记录", allowSuper = true)
public ApiResponse<Long> createPromotionFee(@Valid @RequestBody CreatePromotionFeeDTO dto) {
Long id = promotionFeeService.createPromotionFee(dto);
return ApiResponse.success("推广费记录创建成功", id);
}
@PutMapping
@Operation(summary = "更新推广费记录", description = "更新推广费记录信息")
@RequirePermission(value = "ec:order:update", description = "更新推广费记录", allowSuper = true)
public ApiResponse<Void> updatePromotionFee(@Valid @RequestBody UpdatePromotionFeeDTO dto) {
promotionFeeService.updatePromotionFee(dto);
return ApiResponse.success("推广费记录更新成功");
}
@DeleteMapping("/{id}")
@Operation(summary = "删除推广费记录", description = "删除指定的推广费记录")
@RequirePermission(value = "ec:order:delete", description = "删除推广费记录", allowSuper = true)
public ApiResponse<Void> deletePromotionFee(
@Parameter(description = "记录ID", required = true) @PathVariable Long id) {
promotionFeeService.deletePromotionFee(id);
return ApiResponse.success("推广费记录删除成功");
}
@GetMapping("/{id}")
@Operation(summary = "查询推广费记录详情", description = "根据ID查询推广费记录详情")
@RequirePermission(value = "ec:order:read", description = "查询推广费记录详情", allowSuper = true)
public ApiResponse<PromotionFeeVO> getPromotionFeeById(
@Parameter(description = "记录ID", required = true) @PathVariable Long id) {
PromotionFeeVO vo = promotionFeeService.getPromotionFeeById(id);
return ApiResponse.success("获取推广费记录详情成功", vo);
}
@PostMapping("/list")
@Operation(summary = "分页查询推广费记录", description = "分页查询推广费记录列表")
@RequirePermission(value = "ec:order:read", description = "查询推广费记录列表", allowSuper = true)
public ApiResponse<PageResultVO<PromotionFeeVO>> getPromotionFeePage(
@Valid @RequestBody PageQueryDTO<PromotionFeeFilterDTO> pageQueryDTO) {
PageResultVO<PromotionFeeVO> result = promotionFeeService.getPromotionFeePage(pageQueryDTO);
return ApiResponse.success("获取推广费记录列表成功", result);
}
@GetMapping("/fields")
@Operation(summary = "获取推广费导入字段定义", description = "获取推广费导入时可映射的系统字段列表")
@RequirePermission(value = "ec:order:read", description = "查询导入字段", allowSuper = true)
public ApiResponse<List<PromotionFeeFieldVO>> getPromotionFeeFields() {
return ApiResponse.success("获取推广费导入字段成功", PromotionFeeFieldConstants.FIELDS);
}
}
@@ -1,86 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.CreatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeTypeVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeTypeService;
import java.util.List;
/**
* 推广费类型控制器
*/
@RestController
@RequestMapping("/api/ec/promotion-fee-type")
@RequiredArgsConstructor
@Tag(name = "电商-推广费类型管理", description = "推广费类型相关接口")
public class PromotionFeeTypeController {
private final PromotionFeeTypeService promotionFeeTypeService;
@PostMapping
@Operation(summary = "创建推广费类型", description = "创建新的推广费类型")
@RequirePermission(value = "ec:order:create", description = "创建推广费类型", allowSuper = true)
public ApiResponse<Long> createPromotionFeeType(@Valid @RequestBody CreatePromotionFeeTypeDTO dto) {
Long id = promotionFeeTypeService.createPromotionFeeType(dto);
return ApiResponse.success("推广费类型创建成功", id);
}
@PutMapping
@Operation(summary = "更新推广费类型", description = "更新推广费类型信息")
@RequirePermission(value = "ec:order:update", description = "更新推广费类型", allowSuper = true)
public ApiResponse<Void> updatePromotionFeeType(@Valid @RequestBody UpdatePromotionFeeTypeDTO dto) {
promotionFeeTypeService.updatePromotionFeeType(dto);
return ApiResponse.success("推广费类型更新成功");
}
@DeleteMapping("/{id}")
@Operation(summary = "删除推广费类型", description = "删除指定的推广费类型")
@RequirePermission(value = "ec:order:delete", description = "删除推广费类型", allowSuper = true)
public ApiResponse<Void> deletePromotionFeeType(
@Parameter(description = "类型ID", required = true) @PathVariable Long id) {
promotionFeeTypeService.deletePromotionFeeType(id);
return ApiResponse.success("推广费类型删除成功");
}
@GetMapping("/{id}")
@Operation(summary = "查询推广费类型详情", description = "根据ID查询推广费类型详情")
@RequirePermission(value = "ec:order:read", description = "查询推广费类型详情", allowSuper = true)
public ApiResponse<PromotionFeeTypeVO> getPromotionFeeTypeById(
@Parameter(description = "类型ID", required = true) @PathVariable Long id) {
PromotionFeeTypeVO vo = promotionFeeTypeService.getPromotionFeeTypeById(id);
return ApiResponse.success("获取推广费类型详情成功", vo);
}
@GetMapping("/active")
@Operation(summary = "查询启用的推广费类型列表", description = "查询所有启用的推广费类型")
@RequirePermission(value = "ec:order:read", description = "查询启用的推广费类型", allowSuper = true)
public ApiResponse<List<PromotionFeeTypeVO>> getActivePromotionFeeTypeList() {
List<PromotionFeeTypeVO> list = promotionFeeTypeService.getActivePromotionFeeTypeList();
return ApiResponse.success("获取启用的推广费类型列表成功", list);
}
@GetMapping("/all")
@Operation(summary = "查询所有推广费类型列表", description = "查询所有推广费类型(包括禁用的)")
@RequirePermission(value = "ec:order:read", description = "查询所有推广费类型", allowSuper = true)
public ApiResponse<List<PromotionFeeTypeVO>> getAllPromotionFeeTypeList() {
List<PromotionFeeTypeVO> list = promotionFeeTypeService.getAllPromotionFeeTypeList();
return ApiResponse.success("获取所有推广费类型列表成功", list);
}
@PostMapping("/init")
@Operation(summary = "初始化推广费类型数据", description = "为当前公司初始化默认的推广费类型数据")
@RequirePermission(value = "ec:order:create", description = "初始化推广费类型", allowSuper = true)
public ApiResponse<Void> initPromotionFeeType() {
promotionFeeTypeService.initPromotionFeeTypeForCurrentCompany();
return ApiResponse.success("推广费类型初始化成功");
}
}
@@ -1,21 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.PromotionFeeFilterDTO;
/**
* 推广费记录Mapper
*/
@Mapper
public interface PromotionFeeMapper extends BaseMapper<PromotionFeePO> {
/**
* 分页查询推广费记录
*/
IPage<PromotionFeePO> selectPageWithFilter(Page<PromotionFeePO> page, @Param("filter") PromotionFeeFilterDTO filter);
}
@@ -1,19 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeeTypePO;
import java.util.List;
/**
* 推广费类型Mapper
*/
@Mapper
public interface PromotionFeeTypeMapper extends BaseMapper<PromotionFeeTypePO> {
/**
* 查询启用的推广费类型列表
*/
List<PromotionFeeTypePO> selectActiveTypeList();
}
@@ -1,18 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
@Data
@Schema(description = "批量导入推广费 DTO")
public class BatchImportPromotionFeeDTO {
@NotEmpty(message = "推广费记录不能为空")
@Valid
@Schema(description = "推广费记录列表")
private List<CreatePromotionFeeDTO> items;
}
@@ -1,44 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.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 CreatePromotionFeeTypeDTO {
/**
* 类型名称
*/
@Schema(description = "类型名称", example = "直通车", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "类型名称不能为空")
private String typeName;
/**
* 类型描述
*/
@Schema(description = "类型描述", example = "淘宝直通车推广费用")
private String description;
/**
* 计算方式 1固定金额 2按比例 3按点击 4按展示
*/
@Schema(description = "计算方式", example = "1", allowableValues = {"1", "2", "3", "4"})
private Integer calculationMethod;
/**
* 排序
*/
@Schema(description = "排序", example = "1")
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
*/
@Schema(description = "是否启用", example = "1", allowableValues = {"0", "1"})
private Integer isActive;
}
@@ -1,59 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* 更新推广费类型DTO
*/
@Data
@Schema(description = "更新推广费类型DTO")
public class UpdatePromotionFeeTypeDTO {
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广费类型ID不能为空")
private Long id;
/**
* 类型编码
*/
@Schema(description = "类型编码", example = "DIRECT_TRAFFIC", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "类型编码不能为空")
private String typeCode;
/**
* 类型名称
*/
@Schema(description = "类型名称", example = "直通车", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "类型名称不能为空")
private String typeName;
/**
* 类型描述
*/
@Schema(description = "类型描述", example = "淘宝直通车推广费用")
private String description;
/**
* 计算方式 1固定金额 2按比例 3按点击 4按展示
*/
@Schema(description = "计算方式", example = "1", allowableValues = {"1", "2", "3", "4"})
private Integer calculationMethod;
/**
* 排序
*/
@Schema(description = "排序", example = "1")
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
*/
@Schema(description = "是否启用", example = "1", allowableValues = {"0", "1"})
private Integer isActive;
}
@@ -1,82 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 电商-推广费类型实体
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ec_promotion_fee_type")
public class PromotionFeeTypePO {
/**
* 推广费类型ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公司ID
*/
@TableField("company_id")
private Long companyId;
/**
* 类型名称
*/
@TableField("type_name")
private String typeName;
/**
* 类型描述
*/
@TableField("description")
private String description;
/**
* 计算方式 1固定金额 2按比例 3按点击 4按展示
*/
@TableField("calculation_method")
private Integer calculationMethod;
/**
* 排序
*/
@TableField("sort_order")
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
*/
@TableField("is_active")
private Integer isActive;
/**
* 创建时间
*/
@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;
}
@@ -1,40 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(description = "推广费批量导入结果")
public class BatchImportPromotionFeeResultVO {
@Schema(description = "总数量")
private Integer totalCount;
@Schema(description = "成功数量")
private Integer successCount;
@Schema(description = "失败数量")
private Integer failureCount;
@Schema(description = "成功创建的记录ID")
private List<Long> successIds;
@Schema(description = "失败记录")
private List<ImportFailureRecord> failureRecords;
@Data
@Schema(description = "导入失败记录")
public static class ImportFailureRecord {
@Schema(description = "失败行号")
private Integer rowNumber;
@Schema(description = "店铺ID")
private Long shopId;
@Schema(description = "失败原因")
private String failureReason;
}
}
@@ -1,92 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 推广费类型VO
*/
@Data
@Schema(description = "推广费类型VO")
public class PromotionFeeTypeVO {
/**
* 推广费类型ID
*/
@Schema(description = "推广费类型ID", example = "1")
private Long id;
/**
* 公司ID
*/
@Schema(description = "公司ID", example = "1")
private Long companyId;
/**
* 类型编码
*/
@Schema(description = "类型编码", example = "DIRECT_TRAFFIC")
private String typeCode;
/**
* 类型名称
*/
@Schema(description = "类型名称", example = "直通车")
private String typeName;
/**
* 类型描述
*/
@Schema(description = "类型描述", example = "淘宝直通车推广费用")
private String description;
/**
* 计算方式 1固定金额 2按比例 3按点击 4按展示
*/
@Schema(description = "计算方式", example = "1")
private Integer calculationMethod;
/**
* 计算方式描述
*/
@Schema(description = "计算方式描述", example = "按点击")
private String calculationMethodDesc;
/**
* 排序
*/
@Schema(description = "排序", example = "1")
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
*/
@Schema(description = "是否启用", example = "1")
private Integer isActive;
/**
* 创建时间
*/
@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;
}
@@ -1,46 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.BatchImportPromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.CreatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.PromotionFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.BatchImportPromotionFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeVO;
/**
* 推广费记录服务接口
*/
public interface PromotionFeeService {
/**
* 创建推广费记录
*/
Long createPromotionFee(CreatePromotionFeeDTO dto);
/**
* 更新推广费记录
*/
void updatePromotionFee(UpdatePromotionFeeDTO dto);
/**
* 删除推广费记录
*/
void deletePromotionFee(Long id);
/**
* 根据ID查询推广费记录
*/
PromotionFeeVO getPromotionFeeById(Long id);
/**
* 分页查询推广费记录
*/
PageResultVO<PromotionFeeVO> getPromotionFeePage(PageQueryDTO<PromotionFeeFilterDTO> pageQueryDTO);
/**
* 批量导入推广费记录
*/
BatchImportPromotionFeeResultVO batchImportPromotionFees(BatchImportPromotionFeeDTO dto);
}
@@ -1,61 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.service;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.CreatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeTypeVO;
import java.util.List;
/**
* 推广费类型服务接口
*/
public interface PromotionFeeTypeService {
/**
* 创建推广费类型
*/
Long createPromotionFeeType(CreatePromotionFeeTypeDTO dto);
/**
* 更新推广费类型
*/
void updatePromotionFeeType(UpdatePromotionFeeTypeDTO dto);
/**
* 删除推广费类型
*/
void deletePromotionFeeType(Long id);
/**
* 根据ID查询推广费类型
*/
PromotionFeeTypeVO getPromotionFeeTypeById(Long id);
/**
* 查询启用的推广费类型列表
*/
List<PromotionFeeTypeVO> getActivePromotionFeeTypeList();
/**
* 查询所有推广费类型列表
*/
List<PromotionFeeTypeVO> getAllPromotionFeeTypeList();
/**
* 初始化公司推广费类型数据
*/
void initPromotionFeeTypeForCompany(Long companyId);
/**
* 初始化公司推广费类型数据(指定创建人)
*
* @param companyId 公司ID
* @param creatorId 创建人ID
*/
void initPromotionFeeTypeForCompany(Long companyId, Long creatorId);
/**
* 初始化当前公司推广费类型数据
*/
void initPromotionFeeTypeForCurrentCompany();
}
@@ -1,289 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.service.impl;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ec.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.BatchImportPromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.CreatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.PromotionFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.BatchImportPromotionFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeService;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 推广费记录服务实现类
*/
@Service
public class PromotionFeeServiceImpl implements PromotionFeeService {
private final PromotionFeeMapper promotionFeeMapper;
private final CurrentUserContext currentUserContext;
private final ShopService shopService;
private final PromotionFeeTypeService promotionFeeTypeService;
private final ProductService productService;
private final CategoryService categoryService;
public PromotionFeeServiceImpl(PromotionFeeMapper promotionFeeMapper,
CurrentUserContext currentUserContext,
ShopService shopService,
PromotionFeeTypeService promotionFeeTypeService,
ProductService productService,
CategoryService categoryService) {
this.promotionFeeMapper = promotionFeeMapper;
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.promotionFeeTypeService = promotionFeeTypeService;
this.productService = productService;
this.categoryService = categoryService;
}
/**
* 创建推广费记录
* @param dto 创建推广费记录DTO
* @return 推广费记录ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Long createPromotionFee(CreatePromotionFeeDTO dto) {
assertOptionalCategoryInCompany(dto.getCategoryId());
PromotionFeePO po = new PromotionFeePO();
BeanCopyUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
promotionFeeMapper.insert(po);
return po.getId();
}
/**
* 更新推广费记录
* @param dto 更新推广费记录DTO
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePromotionFee(UpdatePromotionFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
PromotionFeePO existing = promotionFeeMapper.selectById(dto.getId());
if (existing == null || !existing.getCompanyId().equals(companyId)) {
throw new BusinessException("推广费记录不存在");
}
assertOptionalCategoryInCompany(dto.getCategoryId());
PromotionFeePO po = new PromotionFeePO();
BeanCopyUtils.copyProperties(dto, po);
po.setUpdateBy(currentUserContext.getCurrentUserId());
po.setCompanyId(companyId);
promotionFeeMapper.updateById(po);
}
/**
* 删除推广费记录
* @param id 推广费记录ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deletePromotionFee(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
PromotionFeePO existing = promotionFeeMapper.selectById(id);
if (existing == null || !existing.getCompanyId().equals(companyId)) {
throw new BusinessException("推广费记录不存在");
}
promotionFeeMapper.deleteById(id);
}
/**
* 根据ID查询推广费记录
* @param id 推广费记录ID
* @return 推广费记录VO
*/
@Override
public PromotionFeeVO getPromotionFeeById(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
PromotionFeePO po = promotionFeeMapper.selectById(id);
if (po == null || !po.getCompanyId().equals(companyId)) {
throw new BusinessException("推广费记录不存在");
}
return convertToVO(po);
}
/**
* 获取推广费记录分页列表
* @param pageQueryDTO 分页查询DTO
* @return 分页结果VO
*/
@Override
public PageResultVO<PromotionFeeVO> getPromotionFeePage(PageQueryDTO<PromotionFeeFilterDTO> pageQueryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
Page<PromotionFeePO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
LambdaQueryWrapper<PromotionFeePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PromotionFeePO::getCompanyId, companyId);
PromotionFeeFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getShopId() != null) {
wrapper.eq(PromotionFeePO::getShopId, filter.getShopId());
}
if (filter.getFeeTypeId() != null) {
wrapper.eq(PromotionFeePO::getFeeTypeId, filter.getFeeTypeId());
}
if (filter.getProductId() != null) {
wrapper.eq(PromotionFeePO::getProductId, filter.getProductId());
}
if (filter.getCategoryId() != null) {
wrapper.eq(PromotionFeePO::getCategoryId, filter.getCategoryId());
}
if (filter.getFeeDateStart() != null) {
wrapper.ge(PromotionFeePO::getFeeDate, filter.getFeeDateStart());
}
if (filter.getFeeDateEnd() != null) {
wrapper.le(PromotionFeePO::getFeeDate, filter.getFeeDateEnd());
}
}
wrapper.orderByDesc(PromotionFeePO::getFeeDate)
.orderByDesc(PromotionFeePO::getCreateTime);
IPage<PromotionFeePO> pageResult = promotionFeeMapper.selectPage(page, wrapper);
List<PromotionFeeVO> voList = pageResult.getRecords().stream()
.map(this::convertToVO)
.collect(Collectors.toList());
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
/**
* 转换为VO
*/
private PromotionFeeVO convertToVO(PromotionFeePO po) {
PromotionFeeVO vo = new PromotionFeeVO();
BeanCopyUtils.copyProperties(po, vo);
// 填充店铺名称
if (po.getShopId() != null) {
try {
var shop = shopService.getById(po.getShopId());
if (shop != null) {
vo.setShopName(shop.getName());
}
} catch (Exception ignored) {
}
}
// 填充推广费类型名称
if (po.getFeeTypeId() != null) {
try {
var feeTypeVO = promotionFeeTypeService.getPromotionFeeTypeById(po.getFeeTypeId());
if (feeTypeVO != null) {
vo.setFeeTypeName(feeTypeVO.getTypeName());
}
} catch (Exception ignored) {
}
}
// 填充商品名称和编码
if (po.getProductId() != null) {
try {
ProductPO product = productService.getById(po.getProductId());
if (product != null) {
vo.setProductName(product.getName());
vo.setProductCode(product.getProductCode());
}
} catch (Exception ignored) {
}
}
if (po.getCategoryId() != null) {
try {
CategoryPO category = categoryService.getById(po.getCategoryId());
if (category != null) {
vo.setCategoryName(category.getName());
}
} catch (Exception ignored) {
}
} else if (po.getProductId() != null) {
// 列表/详情展示:记录未选类目时,带出商品所属类目(便于与「仅选商品」的旧数据对齐)
try {
ProductPO p = productService.getById(po.getProductId());
if (p != null && p.getCategoryId() != null) {
vo.setCategoryId(p.getCategoryId());
CategoryPO category = categoryService.getById(p.getCategoryId());
if (category != null) {
vo.setCategoryName(category.getName());
}
}
} catch (Exception ignored) {
}
}
return vo;
}
@Override
@Transactional(rollbackFor = Exception.class)
public BatchImportPromotionFeeResultVO batchImportPromotionFees(BatchImportPromotionFeeDTO dto) {
List<CreatePromotionFeeDTO> items = dto.getItems();
List<Long> successIds = new ArrayList<>();
List<BatchImportPromotionFeeResultVO.ImportFailureRecord> failureRecords = new ArrayList<>();
int successCount = 0;
int failureCount = 0;
for (int i = 0; i < items.size(); i++) {
CreatePromotionFeeDTO item = items.get(i);
try {
Long id = createPromotionFee(item);
successIds.add(id);
successCount++;
} catch (Exception e) {
BatchImportPromotionFeeResultVO.ImportFailureRecord record =
new BatchImportPromotionFeeResultVO.ImportFailureRecord();
record.setRowNumber(i + 1);
record.setShopId(item.getShopId());
record.setFailureReason(e.getMessage());
failureRecords.add(record);
failureCount++;
}
}
BatchImportPromotionFeeResultVO result = new BatchImportPromotionFeeResultVO();
result.setTotalCount(items.size());
result.setSuccessCount(successCount);
result.setFailureCount(failureCount);
result.setSuccessIds(successIds);
result.setFailureRecords(failureRecords);
return result;
}
private void assertOptionalCategoryInCompany(Long categoryId) {
if (categoryId == null) {
return;
}
Long companyId = currentUserContext.getCurrentCompanyId();
CategoryPO category = categoryService.getById(categoryId);
if (category == null || !companyId.equals(category.getCompanyId())) {
throw new BusinessException("类目不存在或不属于当前公司");
}
}
}
@@ -1,276 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.ec.promotion.service.impl;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeTypeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.CreatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.UpdatePromotionFeeTypeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeeTypePO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeTypeVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.stream.Collectors;
/**
* 推广费类型服务实现类
*/
@Service
@RequiredArgsConstructor
public class PromotionFeeTypeServiceImpl implements PromotionFeeTypeService {
private final PromotionFeeTypeMapper promotionFeeTypeMapper;
private final CurrentUserContext currentUserContext;
/**
* 创建推广费类型
* @param dto 创建推广费类型DTO
* @return 推广费类型ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Long createPromotionFeeType(CreatePromotionFeeTypeDTO dto) {
// 检查类型名称是否重复
LambdaQueryWrapper<PromotionFeeTypePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PromotionFeeTypePO::getCompanyId, currentUserContext.getCurrentCompanyId())
.eq(PromotionFeeTypePO::getTypeName, dto.getTypeName());
if (promotionFeeTypeMapper.selectCount(wrapper) > 0) {
throw new RuntimeException("该类型名称已存在");
}
PromotionFeeTypePO po = new PromotionFeeTypePO();
BeanCopyUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
promotionFeeTypeMapper.insert(po);
return po.getId();
}
/**
* 更新推广费类型
* @param dto 更新推广费类型DTO
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePromotionFeeType(UpdatePromotionFeeTypeDTO dto) {
PromotionFeeTypePO po = new PromotionFeeTypePO();
BeanCopyUtils.copyProperties(dto, po);
po.setUpdateBy(currentUserContext.getCurrentUserId());
promotionFeeTypeMapper.updateById(po);
}
/**
* 删除推广费类型
* @param id 推广费类型ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deletePromotionFeeType(Long id) {
// 硬删除推广费类型(外键约束会自动处理相关数据)
promotionFeeTypeMapper.deleteById(id);
}
/**
* 根据ID查询推广费类型
* @param id 推广费类型ID
* @return 推广费类型VO
*/
@Override
public PromotionFeeTypeVO getPromotionFeeTypeById(Long id) {
PromotionFeeTypePO po = promotionFeeTypeMapper.selectById(id);
if (po == null) {
return null;
}
PromotionFeeTypeVO vo = new PromotionFeeTypeVO();
BeanCopyUtils.copyProperties(po, vo);
// 设置计算方式描述
if (po.getCalculationMethod() != null) {
switch (po.getCalculationMethod()) {
case 1:
vo.setCalculationMethodDesc("固定金额");
break;
case 2:
vo.setCalculationMethodDesc("按比例");
break;
case 3:
vo.setCalculationMethodDesc("按点击");
break;
case 4:
vo.setCalculationMethodDesc("按展示");
break;
default:
vo.setCalculationMethodDesc("未知");
break;
}
}
return vo;
}
/**
* 获取所有启用的推广费类型列表
* @return 推广费类型VO列表
*/
@Override
public List<PromotionFeeTypeVO> getActivePromotionFeeTypeList() {
LambdaQueryWrapper<PromotionFeeTypePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PromotionFeeTypePO::getCompanyId, currentUserContext.getCurrentCompanyId())
.eq(PromotionFeeTypePO::getIsActive, 1)
.orderByAsc(PromotionFeeTypePO::getSortOrder);
List<PromotionFeeTypePO> poList = promotionFeeTypeMapper.selectList(wrapper);
return poList.stream()
.map(po -> {
PromotionFeeTypeVO vo = new PromotionFeeTypeVO();
BeanCopyUtils.copyProperties(po, vo);
// 设置计算方式描述
if (po.getCalculationMethod() != null) {
switch (po.getCalculationMethod()) {
case 1:
vo.setCalculationMethodDesc("固定金额");
break;
case 2:
vo.setCalculationMethodDesc("按比例");
break;
case 3:
vo.setCalculationMethodDesc("按点击");
break;
case 4:
vo.setCalculationMethodDesc("按展示");
break;
default:
vo.setCalculationMethodDesc("未知");
break;
}
}
return vo;
})
.collect(Collectors.toList());
}
/**
* 获取所有推广费类型列表
* @return 推广费类型VO列表
*/
@Override
public List<PromotionFeeTypeVO> getAllPromotionFeeTypeList() {
LambdaQueryWrapper<PromotionFeeTypePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PromotionFeeTypePO::getCompanyId, currentUserContext.getCurrentCompanyId())
.orderByAsc(PromotionFeeTypePO::getSortOrder);
List<PromotionFeeTypePO> poList = promotionFeeTypeMapper.selectList(wrapper);
return poList.stream()
.map(po -> {
PromotionFeeTypeVO vo = new PromotionFeeTypeVO();
BeanCopyUtils.copyProperties(po, vo);
// 设置计算方式描述
if (po.getCalculationMethod() != null) {
switch (po.getCalculationMethod()) {
case 1:
vo.setCalculationMethodDesc("固定金额");
break;
case 2:
vo.setCalculationMethodDesc("按比例");
break;
case 3:
vo.setCalculationMethodDesc("按点击");
break;
case 4:
vo.setCalculationMethodDesc("按展示");
break;
default:
vo.setCalculationMethodDesc("未知");
break;
}
}
return vo;
})
.collect(Collectors.toList());
}
/**
* 初始化公司推广费类型数据
* @param companyId 公司ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void initPromotionFeeTypeForCompany(Long companyId) {
initPromotionFeeTypeForCompany(companyId, null);
}
@Override
public void initPromotionFeeTypeForCompany(Long companyId, Long creatorId) {
// 检查是否已经初始化过
LambdaQueryWrapper<PromotionFeeTypePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PromotionFeeTypePO::getCompanyId, companyId);
if (promotionFeeTypeMapper.selectCount(wrapper) > 0) {
return; // 已经初始化过,直接返回
}
// 初始化推广费类型数据
List<PromotionFeeTypePO> initialTypes = List.of(
createPromotionFeeTypePO(companyId, "直通车", "淘宝直通车推广费用", 3, 1, creatorId),
createPromotionFeeTypePO(companyId, "钻展", "钻石展位推广费用", 4, 2, creatorId),
createPromotionFeeTypePO(companyId, "超级推荐", "超级推荐推广费用", 3, 3, creatorId),
createPromotionFeeTypePO(companyId, "平台佣金", "平台交易佣金", 2, 4, creatorId),
createPromotionFeeTypePO(companyId, "分销佣金", "分销商佣金", 2, 5, creatorId),
createPromotionFeeTypePO(companyId, "活动费用", "平台活动参与费用", 1, 6, creatorId),
createPromotionFeeTypePO(companyId, "站外广告", "站外广告投放费用", 1, 7, creatorId),
createPromotionFeeTypePO(companyId, "直播推广", "直播推广费用", 1, 8, creatorId)
);
// 批量插入
for (PromotionFeeTypePO type : initialTypes) {
promotionFeeTypeMapper.insert(type);
}
}
/**
* 初始化当前公司推广费类型数据
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void initPromotionFeeTypeForCurrentCompany() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new RuntimeException("用户未关联公司");
}
initPromotionFeeTypeForCompany(companyId);
}
/**
* 创建推广费类型PO对象
* @param companyId 公司ID
* @param typeName 类型名称
* @param description 描述
* @param calculationMethod 计算方式
* @param sortOrder 排序
* @return 推广费类型PO对象
*/
private PromotionFeeTypePO createPromotionFeeTypePO(Long companyId, String typeName, String description, Integer calculationMethod, Integer sortOrder, Long creatorId) {
PromotionFeeTypePO po = new PromotionFeeTypePO();
po.setCompanyId(companyId);
po.setTypeName(typeName);
po.setDescription(description);
po.setCalculationMethod(calculationMethod);
po.setSortOrder(sortOrder);
po.setIsActive(1);
// create_by / update_by 可为 null(外键 ON DELETE SET NULL);禁止写死不存在的用户 id
po.setCreateBy(creatorId);
po.setUpdateBy(creatorId);
return po;
}
}
@@ -11,8 +11,6 @@ public final class OpenApiScopeConstants {
public static final String ORDER_IMPORT = "open:scope:order:import";
public static final String ORDER_READ = "open:scope:order:read";
public static final String PROMOTION_FEE_IMPORT = "open:scope:promotion_fee:import";
public static final String PROMOTION_FEE_READ = "open:scope:promotion_fee:read";
public static final String IMPORT_TASK_READ = "open:scope:import_task:read";
public static final String META_READ = "open:scope:meta:read";
public static final String PDD_GOODS_AD_FEE_IMPORT = "open:scope:pdd_goods_ad_fee:import";
@@ -22,8 +20,6 @@ public final class OpenApiScopeConstants {
public static final List<String> ALL = List.of(
ORDER_IMPORT,
ORDER_READ,
PROMOTION_FEE_IMPORT,
PROMOTION_FEE_READ,
IMPORT_TASK_READ,
META_READ,
PDD_GOODS_AD_FEE_IMPORT,
@@ -11,8 +11,6 @@ import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.vo.OrderStatusMetaVO;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusMetaSupport;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeTypeVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.dto.ShopFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
@@ -27,7 +25,6 @@ import java.util.List;
public class OpenMetaController {
private final ShopService shopService;
private final PromotionFeeTypeService promotionFeeTypeService;
@PostMapping("/shop/list")
@RequireOpenScope(value = OpenApiScopeConstants.META_READ, description = "查询店铺列表")
@@ -44,12 +41,4 @@ public class OpenMetaController {
public ApiResponse<List<OrderStatusMetaVO>> getAllOrderStatuses() {
return ApiResponse.success("获取订单状态列表成功", OrderStatusMetaSupport.allMeta());
}
@GetMapping("/promotion-fee-type/list")
@RequireOpenScope(value = OpenApiScopeConstants.META_READ, description = "查询推广费类型列表")
@Operation(summary = "获取启用的推广费类型列表")
public ApiResponse<List<PromotionFeeTypeVO>> getActivePromotionFeeTypeList() {
List<PromotionFeeTypeVO> list = promotionFeeTypeService.getActivePromotionFeeTypeList();
return ApiResponse.success("获取推广费类型列表成功", list);
}
}
@@ -1,42 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.open.api.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.dto.BatchImportPromotionFeeDTO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.BatchImportPromotionFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeFieldConstants;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.vo.PromotionFeeFieldVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeService;
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
import java.util.List;
@RestController
@RequestMapping("/api/open/v1/ec/promotion-fee")
@RequiredArgsConstructor
@Tag(name = "开放接口-推广费", description = "API Key 认证,镜像 /ec/promotion-fee")
public class OpenPromotionFeeController {
private final PromotionFeeService promotionFeeService;
@GetMapping("/fields")
@RequireOpenScope(value = OpenApiScopeConstants.PROMOTION_FEE_READ, description = "查询推广费字段")
@Operation(summary = "获取推广费导入字段定义")
public ApiResponse<List<PromotionFeeFieldVO>> getPromotionFeeFields() {
return ApiResponse.success("获取推广费字段成功", PromotionFeeFieldConstants.FIELDS);
}
@PostMapping("/batch-import")
@RequireOpenScope(value = OpenApiScopeConstants.PROMOTION_FEE_IMPORT, description = "批量导入推广费")
@Operation(summary = "批量导入推广费")
public ApiResponse<BatchImportPromotionFeeResultVO> batchImportPromotionFees(
@Valid @RequestBody BatchImportPromotionFeeDTO dto) {
BatchImportPromotionFeeResultVO result = promotionFeeService.batchImportPromotionFees(dto);
return ApiResponse.success("批量导入推广费成功", result);
}
}
@@ -19,7 +19,6 @@ import top.xyquan.ecomdmbbackend.modules.org.company.model.vo.CompanyVO;
import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.ec.promotion.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.modules.org.company.menu.service.CompanyMenuService;
import top.xyquan.ecomdmbbackend.modules.org.department.service.DepartmentService;
import top.xyquan.ecomdmbbackend.modules.org.position.service.PositionService;
@@ -54,7 +53,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
private final CurrentUserContext currentUserContext;
private final SysFileService sysFileService;
private final PromotionFeeTypeService promotionFeeTypeService;
private final CompanyMenuService companyMenuService;
private final DepartmentService departmentService;
private final PositionService positionService;
@@ -65,14 +63,12 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
private final LicenseValidator licenseValidator;
public CompanyServiceImpl(@Lazy CurrentUserContext currentUserContext, SysFileService sysFileService,
PromotionFeeTypeService promotionFeeTypeService,
CompanyMenuService companyMenuService, DepartmentService departmentService,
PositionService positionService, MenuService menuService,
@Lazy UserService userService, @Lazy CompanyMemberService companyMemberService,
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator) {
this.currentUserContext = currentUserContext;
this.sysFileService = sysFileService;
this.promotionFeeTypeService = promotionFeeTypeService;
this.companyMenuService = companyMenuService;
this.departmentService = departmentService;
this.positionService = positionService;
@@ -157,9 +153,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 将拥有者加入公司成员(owner角色)
companyMemberService.create(ownerUser.getId(), company.getId(), CompanyMemberRole.owner, null, creatorId);
// 初始化推广费类型数据
promotionFeeTypeService.initPromotionFeeTypeForCompany(company.getId(), creatorId);
// 初始化公司菜单(非超级菜单)
initCompanyMenus(company.getId());
@@ -153,20 +153,12 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 5202, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:order:read', '开放-订单字段查询', 'api', 1, 'GET /open/v1/ec/order/fields', 20
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:order:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 5203, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:promotion_fee:import', '开放-推广费导入', 'api', 1, 'POST /open/v1/ec/promotion-fee/batch-import', 30
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:promotion_fee:import');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 5204, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:promotion_fee:read', '开放-推广费字段查询', 'api', 1, 'GET /open/v1/ec/promotion-fee/fields', 40
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:promotion_fee:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 5205, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:import_task:read', '开放-导入任务查询', 'api', 1, 'GET /open/v1/ec/import-task/detail/{id}', 50
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:import_task:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 5206, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:meta:read', '开放-元数据查询', 'api', 1, 'shop/order-status/promotion-fee-type 等元数据', 60
SELECT 5206, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:meta:read', '开放-元数据查询', 'api', 1, 'shop/order-status 等元数据', 60
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:meta:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
@@ -370,8 +362,8 @@ SELECT 12012, NULL, 0, '订单导入', '订单导入', '/import/order', '/ecomme
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '订单导入');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12013, NULL, 0, '推广导入', '推广导入', '/import/promotion-fee', '/ecommerce/import/promotion-fee/index', '', 'hugeicons:promotion', 'menu', 1, 1, 0, 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '推广导入');
SELECT 12013, NULL, 0, '广告费导入', '广告费导入', '/import/ad-fee', '/ecommerce/import/ad-fee/index', '', 'hugeicons:promotion', 'menu', 1, 1, 0, 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` IN ('广告费导入', '推广导入'));
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12014, NULL, 0, '店铺管理', '店铺管理', 'shop/list', '/ecommerce/shop/list/index', '', 'lucide:store', 'menu', 1, 1, 0, 5
@@ -386,8 +378,8 @@ SELECT 12017, NULL, 0, '订单管理', '订单管理', 'order/list', '/ecommerce
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '订单管理');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12018, NULL, 0, '推广管理', '推广管理', 'promotion-fee', '/ecommerce/promotion-fee/index', '', 'hugeicons:promotion', 'menu', 1, 1, 0, 9
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '推广管理');
SELECT 12018, NULL, 0, '广告费管理', '广告费管理', 'ad-fee', '/ecommerce/ad-fee/index', '', 'hugeicons:promotion', 'menu', 1, 1, 0, 9
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` IN ('广告费管理', '推广管理'));
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12019, NULL, 0, '刷单管理', '刷单管理', 'shop/brush-order', '/ecommerce/brush-order/index', '', 'mdi:ticket-outline', 'menu', 1, 1, 0, 10
@@ -497,9 +489,10 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `co
SELECT 13002, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '商品类目', '商品类目', '/category', '/ecommerce/config/category-config/index', '', 'iconamoon:category-bold', 'menu', 1, 1, 0, 12
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '商品类目');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 13003, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '推广费用类型', '推广费用类型', '/promotion-fee-type', '/ecommerce/config/promotion-fee-type-config/index', '', 'lucide:percent', 'menu', 1, 1, 0, 13
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '推广费用类型');
-- 推广费用类型菜单已下线(ec_ad_fee 重构后不再维护类型表)
-- INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
-- SELECT 13003, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '推广费用类型', '推广费用类型', '/promotion-fee-type', '/ecommerce/config/promotion-fee-type-config/index', '', 'lucide:percent', 'menu', 1, 1, 0, 13
-- FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '推广费用类型');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 13004, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '字段映射模板', '字段映射模板', '/config-management/field-mapping', '/config/management/field-mapping/index', '', 'lucide:key', 'menu', 1, 1, 1, 14
@@ -578,7 +571,7 @@ INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('ecom:order:import', 'data:import') WHERE m.name = '订单导入';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'data:import' WHERE m.name = '推广导入';
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'data:import' WHERE m.name IN ('广告费导入', '推广导入');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'open:api-key:manage' WHERE m.name = 'OpenApiKeyManagement';
@@ -0,0 +1,50 @@
import { requestClient } from '#/api/request';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import type { AdFeeDTO, AdFeeVO, AdFeeFieldVO } from './types';
/**
* 广告费管理API
*/
/**
* 分页获取广告费记录列表
*/
export async function getAdFeePageApi(params: PageQueryDTO<AdFeeDTO.Filters>) {
return requestClient.post<PageResultVO<AdFeeVO.Info>>('/ec/ad-fee/list', params);
}
/**
* 创建广告费记录
*/
export async function createAdFeeApi(data: AdFeeDTO.Create) {
return requestClient.post<number>('/ec/ad-fee', data);
}
/**
* 更新广告费记录
*/
export async function updateAdFeeApi(data: AdFeeDTO.Update) {
return requestClient.put<void>('/ec/ad-fee', data);
}
/**
* 删除广告费记录
*/
export async function deleteAdFeeApi(id: number) {
return requestClient.delete<void>(`/ec/ad-fee/${id}`);
}
/**
* 获取广告费记录详情
*/
export async function getAdFeeByIdApi(id: number) {
return requestClient.get<AdFeeVO.Info>(`/ec/ad-fee/${id}`);
}
/**
* 获取广告费导入字段定义
*/
export async function getAdFeeFieldsApi() {
return requestClient.get<AdFeeFieldVO.Info[]>('/ec/ad-fee/fields');
}
@@ -1,61 +1,49 @@
/**
* 推广费管理相关DTO类型定义
* 广告费管理相关DTO类型定义
*/
export namespace PromotionFeeDTO {
/** 推广费查询过滤条件 */
export namespace AdFeeDTO {
/** 广告费查询过滤条件 */
export interface Filters {
/** 店铺ID */
shopId?: number;
/** 推广费类型ID */
feeTypeId?: number;
/** 类目ID(可选) */
categoryId?: number;
/** 商品ID(可选) */
productId?: number;
/** 推广费发生日期开始 */
/** 广告费发生日期开始 */
feeDateStart?: string;
/** 推广费发生日期结束 */
/** 广告费发生日期结束 */
feeDateEnd?: string;
}
/** 创建推广费记录 */
/** 创建广告费记录 */
export interface Create {
/** 店铺ID */
shopId: number;
/** 推广费类型ID */
feeTypeId: number;
/** 类目ID(可选,类目级推广费) */
categoryId?: number;
/** 商品ID(可选,关联到具体商品) */
productId?: number;
/** 推广活动名称 */
campaignName?: string;
/** 推广费金额 */
/** 广告费金额 */
feeAmount: number;
/** 推广费发生日期 */
/** 广告费发生日期 */
feeDate: string;
/** 备注 */
remark?: string;
}
/** 更新推广费记录 */
/** 更新广告费记录 */
export interface Update {
/** 推广费记录ID */
/** 广告费记录ID */
id: number;
/** 店铺ID */
shopId: number;
/** 推广费类型ID */
feeTypeId: number;
/** 类目ID(可选,类目级推广费) */
categoryId?: number;
/** 商品ID(可选,关联到具体商品) */
productId?: number;
/** 推广活动名称 */
campaignName?: string;
/** 推广费金额 */
/** 广告费金额 */
feeAmount: number;
/** 推广费发生日期 */
/** 广告费发生日期 */
feeDate: string;
/** 备注 */
remark?: string;
@@ -1,11 +1,11 @@
/**
* 推广费管理相关VO类型定义
* 广告费管理相关VO类型定义
*/
export namespace PromotionFeeVO {
/** 推广费记录信息 */
export namespace AdFeeVO {
/** 广告费记录信息 */
export interface Info {
/** 推广费记录ID */
/** 广告费记录ID */
id: number;
/** 公司ID */
companyId: number;
@@ -13,14 +13,6 @@ export namespace PromotionFeeVO {
shopId: number;
/** 店铺名称 */
shopName?: string;
/** 推广费类型ID */
feeTypeId: number;
/** 推广费类型名称 */
feeTypeName?: string;
/** 类目ID(可选) */
categoryId?: number;
/** 类目名称 */
categoryName?: string;
/** 商品ID(可选) */
productId?: number;
/** 商品名称 */
@@ -29,9 +21,9 @@ export namespace PromotionFeeVO {
productCode?: string;
/** 推广活动名称 */
campaignName?: string;
/** 推广费金额 */
/** 广告费金额 */
feeAmount: number;
/** 推广费发生日期 */
/** 广告费发生日期 */
feeDate: string;
/** 备注 */
remark?: string;
@@ -46,8 +38,8 @@ export namespace PromotionFeeVO {
}
}
export namespace PromotionFeeFieldVO {
/** 推广费导入字段信息 */
export namespace AdFeeFieldVO {
/** 广告费导入字段信息 */
export interface Info {
fieldName: string;
fieldLabel: string;
@@ -1,50 +0,0 @@
import { requestClient } from '#/api/request';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import type { PromotionFeeDTO, PromotionFeeVO, PromotionFeeFieldVO } from './types';
/**
* 推广费管理API
*/
/**
* 分页获取推广费记录列表
*/
export async function getPromotionFeePageApi(params: PageQueryDTO<PromotionFeeDTO.Filters>) {
return requestClient.post<PageResultVO<PromotionFeeVO.Info>>('/ec/promotion-fee/list', params);
}
/**
* 创建推广费记录
*/
export async function createPromotionFeeApi(data: PromotionFeeDTO.Create) {
return requestClient.post<number>('/ec/promotion-fee', data);
}
/**
* 更新推广费记录
*/
export async function updatePromotionFeeApi(data: PromotionFeeDTO.Update) {
return requestClient.put<void>('/ec/promotion-fee', data);
}
/**
* 删除推广费记录
*/
export async function deletePromotionFeeApi(id: number) {
return requestClient.delete<void>(`/ec/promotion-fee/${id}`);
}
/**
* 获取推广费记录详情
*/
export async function getPromotionFeeByIdApi(id: number) {
return requestClient.get<PromotionFeeVO.Info>(`/ec/promotion-fee/${id}`);
}
/**
* 获取推广费导入字段定义
*/
export async function getPromotionFeeFieldsApi() {
return requestClient.get<PromotionFeeFieldVO.Info[]>('/ec/promotion-fee/fields');
}
@@ -1,59 +0,0 @@
import type { PromotionFeeTypeDTO, PromotionFeeTypeVO } from './types';
import { requestClient } from '#/api/request';
/**
* 推广费类型管理API
*/
/**
* 创建推广费类型
*/
export async function createPromotionFeeTypeApi(
data: PromotionFeeTypeDTO.Create,
) {
return requestClient.post<number>('/ec/promotion-fee-type', data);
}
/**
* 更新推广费类型
*/
export async function updatePromotionFeeTypeApi(
data: PromotionFeeTypeDTO.Update,
) {
return requestClient.put('/ec/promotion-fee-type', data);
}
/**
* 删除推广费类型
*/
export async function deletePromotionFeeTypeApi(id: number) {
return requestClient.delete(`/ec/promotion-fee-type/${id}`);
}
/**
* 获取推广费类型详情
*/
export async function getPromotionFeeTypeByIdApi(id: number) {
return requestClient.get<PromotionFeeTypeVO.Info>(
`/ec/promotion-fee-type/${id}`,
);
}
/**
* 获取启用的推广费类型列表
*/
export async function getActivePromotionFeeTypeListApi() {
return requestClient.get<PromotionFeeTypeVO.Info[]>(
'/ec/promotion-fee-type/active',
);
}
/**
* 获取所有推广费类型列表
*/
export async function getAllPromotionFeeTypeListApi() {
return requestClient.get<PromotionFeeTypeVO.Info[]>(
'/ec/promotion-fee-type/all',
);
}
@@ -1,6 +0,0 @@
/**
* 推广费类型管理模块API导出
*/
export * from './apis';
export * from './types';
@@ -1,6 +0,0 @@
/**
* 推广费类型管理模块类型定义导出
*/
export * from './types.dto';
export * from './types.vo';
@@ -1,35 +0,0 @@
/**
* 推广费类型相关DTO类型定义
*/
export namespace PromotionFeeTypeDTO {
/** 创建推广费类型参数 */
export interface Create {
/** 类型名称 */
typeName: string;
/** 类型描述 */
description?: string;
/** 计算方式 1固定金额 2按比例 3按点击 4按展示 */
calculationMethod?: number;
/** 排序 */
sortOrder?: number;
/** 是否启用 0禁用 1启用 */
isActive?: number;
}
/** 更新推广费类型参数 */
export interface Update {
/** 推广费类型ID */
id: number;
/** 类型名称 */
typeName: string;
/** 类型描述 */
description?: string;
/** 计算方式 1固定金额 2按比例 3按点击 4按展示 */
calculationMethod?: number;
/** 排序 */
sortOrder?: number;
/** 是否启用 0禁用 1启用 */
isActive?: number;
}
}
@@ -1,35 +0,0 @@
/**
* 推广费类型相关VO类型定义
*/
export namespace PromotionFeeTypeVO {
/** 推广费类型信息 */
export interface Info {
/** 推广费类型ID */
id: number;
/** 公司ID */
companyId: number;
/** 类型编码 */
typeCode: string;
/** 类型名称 */
typeName: string;
/** 类型描述 */
description?: string;
/** 计算方式 1固定金额 2按比例 3按点击 4按展示 */
calculationMethod?: number;
/** 计算方式描述 */
calculationMethodDesc?: string;
/** 排序 */
sortOrder?: number;
/** 是否启用 0禁用 1启用 */
isActive?: number;
/** 创建时间 */
createTime: string;
/** 更新时间 */
updateTime: string;
/** 创建人ID */
createBy?: number;
/** 更新人ID */
updateBy?: number;
}
}
@@ -100,7 +100,7 @@ const summaryTablesPanel = computed(
const router = useRouter();
const ImportOrderIcon = createIconifyIcon('lucide:upload');
const PromotionFeeIcon = createIconifyIcon('lucide:dollar-sign');
const AdFeeIcon = createIconifyIcon('lucide:dollar-sign');
const ToolbarToggleIcon = createIconifyIcon('lucide:sliders-horizontal');
const ReceiptIcon = createIconifyIcon('lucide:receipt');
const CalendarIcon = createIconifyIcon('lucide:calendar');
@@ -110,8 +110,8 @@ function goToImportOrder() {
void router.push('/import/order');
}
function goToImportPromotionFee() {
void router.push('/import/promotion-fee');
function goToImportAdFee() {
void router.push('/import/ad-fee');
}
/** 快捷区间 + 自定义 RangePicker */
@@ -171,15 +171,15 @@ const importMenuItems: MenuProps['items'] = [
icon: () => h(ImportOrderIcon, { class: 'size-4' }),
},
{
key: 'promotion',
label: '导入推广费',
icon: () => h(PromotionFeeIcon, { class: 'size-4' }),
key: 'ad-fee',
label: '导入广告费',
icon: () => h(AdFeeIcon, { class: 'size-4' }),
},
];
const onImportMenuClick: MenuProps['onClick'] = ({ key }) => {
if (key === 'order') goToImportOrder();
else if (key === 'promotion') goToImportPromotionFee();
else if (key === 'ad-fee') goToImportAdFee();
};
const switchTimeRange = (type: TimeRangeKey) => {
@@ -1,13 +1,12 @@
<script setup lang="ts">
import type { PromotionFeeTypeVO } from '#/api/ec/promotion-fee/type';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/ec/promotion-fee/types';
AdFeeDTO,
AdFeeVO,
} from '#/api/ec/ad-fee/types';
import type { ProductVO } from '#/api/ec/product/types';
import type { ShopVO } from '#/api/ec/shop/types';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { nextTick, onMounted, ref, watch } from 'vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
@@ -21,23 +20,20 @@ import {
InputNumber,
message,
Select,
TreeSelect,
} from 'ant-design-vue';
import {
createPromotionFeeApi,
updatePromotionFeeApi,
} from '#/api/ec/promotion-fee';
import { getCategoryTreeApi } from '#/api/ec/product/category';
import { getActivePromotionFeeTypeListApi } from '#/api/ec/promotion-fee/type';
createAdFeeApi,
updateAdFeeApi,
} from '#/api/ec/ad-fee';
import { getProductPageApi } from '#/api/ec/product';
import { getShopPageApi } from '#/api/ec/shop';
defineOptions({ name: 'PromotionFeeFormModal' });
defineOptions({ name: 'AdFeeFormModal' });
interface Props {
open: boolean;
promotionFeeData?: null | PromotionFeeVO.Info;
adFeeData?: null | AdFeeVO.Info;
/** 新增时预填店铺(编辑时忽略) */
presetShopId?: number | null;
}
@@ -76,14 +72,12 @@ const formRef = ref();
const isEdit = ref(false);
/** 表单内用 Dayjs,提交时再格式化为 YYYY-MM-DD */
type PromotionFeeFormState = Omit<PromotionFeeDTO.Create, 'feeDate'> & {
type AdFeeFormState = Omit<AdFeeDTO.Create, 'feeDate'> & {
feeDate?: Dayjs;
};
const formData = ref<PromotionFeeFormState>({
const formData = ref<AdFeeFormState>({
shopId: undefined as any,
feeTypeId: undefined as any,
categoryId: undefined,
productId: undefined,
campaignName: '',
feeAmount: undefined as any,
@@ -93,10 +87,7 @@ const formData = ref<PromotionFeeFormState>({
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
feeTypeId: [
{ required: true, message: '请选择推广费类型', trigger: 'change' },
],
feeAmount: [{ required: true, message: '请输入推广费金额', trigger: 'blur' }],
feeAmount: [{ required: true, message: '请输入广告费金额', trigger: 'blur' }],
feeDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
} as any;
@@ -104,40 +95,10 @@ const rules = {
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 推广费类型列表
const feeTypeList = ref<PromotionFeeTypeVO.Info[]>([]);
const feeTypeListLoading = ref(false);
// 类目树(与商品卡片 TreeSelect 一致:label=name, value=id)
const categoryOptions = ref<any[]>([]);
const categoryTreeLoading = ref(false);
// 商品列表
const productList = ref<ProductVO.Info[]>([]);
const productListLoading = ref(false);
const filteredProductList = computed(() => {
const cid = formData.value.categoryId;
if (cid == null) {
return productList.value;
}
return productList.value.filter((p) => p.categoryId === cid);
});
watch(
() => formData.value.categoryId,
(cid) => {
const pid = formData.value.productId;
if (pid == null || cid == null) {
return;
}
const p = productList.value.find((x) => x.id === pid);
if (p && p.categoryId !== cid) {
formData.value.productId = undefined;
}
},
);
watch(
() => props.open,
async (newVal) => {
@@ -145,19 +106,17 @@ watch(
modalApi.close();
return;
}
isEdit.value = !!props.promotionFeeData;
if (props.promotionFeeData) {
isEdit.value = !!props.adFeeData;
if (props.adFeeData) {
formData.value = {
shopId: props.promotionFeeData.shopId,
feeTypeId: props.promotionFeeData.feeTypeId,
categoryId: props.promotionFeeData.categoryId,
productId: props.promotionFeeData.productId,
campaignName: props.promotionFeeData.campaignName || '',
feeAmount: props.promotionFeeData.feeAmount,
feeDate: props.promotionFeeData.feeDate
? dayjs(props.promotionFeeData.feeDate)
shopId: props.adFeeData.shopId,
productId: props.adFeeData.productId,
campaignName: props.adFeeData.campaignName || '',
feeAmount: props.adFeeData.feeAmount,
feeDate: props.adFeeData.feeDate
? dayjs(props.adFeeData.feeDate)
: undefined,
remark: props.promotionFeeData.remark || '',
remark: props.adFeeData.remark || '',
};
} else {
resetFormData();
@@ -169,18 +128,6 @@ watch(
modalApi.open();
await nextTick();
formRef.value?.clearValidate?.();
if (props.promotionFeeData?.productId && productList.value.length > 0) {
const p = productList.value.find(
(x) => x.id === props.promotionFeeData!.productId,
);
if (
p?.categoryId != null &&
(formData.value.categoryId == null || formData.value.categoryId === undefined)
) {
formData.value.categoryId = p.categoryId;
}
}
},
);
@@ -200,30 +147,6 @@ const loadShopList = async () => {
}
};
const loadFeeTypeList = async () => {
feeTypeListLoading.value = true;
try {
const response = await getActivePromotionFeeTypeListApi();
feeTypeList.value = response;
} catch (error) {
console.error('加载推广费类型列表失败:', error);
} finally {
feeTypeListLoading.value = false;
}
};
const loadCategoryTree = async () => {
categoryTreeLoading.value = true;
try {
categoryOptions.value = (await getCategoryTreeApi()) ?? [];
} catch (error) {
console.error('加载类目树失败:', error);
categoryOptions.value = [];
} finally {
categoryTreeLoading.value = false;
}
};
const loadProductList = async () => {
productListLoading.value = true;
try {
@@ -243,8 +166,6 @@ const loadProductList = async () => {
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
feeTypeId: undefined as any,
categoryId: undefined,
productId: undefined,
campaignName: '',
feeAmount: undefined as any,
@@ -257,7 +178,7 @@ const resetFormData = () => {
const feeDateToApiString = (v: Dayjs) => dayjs(v).format('YYYY-MM-DD');
function productSelectFilterOption(input: string, option?: any) {
const o = filteredProductList.value.find((x) => x.id === option?.value);
const o = productList.value.find((x) => x.id === option?.value);
return (o?.name ?? '').toLowerCase().includes(input.toLowerCase());
}
@@ -267,16 +188,16 @@ const handleOk = async () => {
const feeDate = feeDateToApiString(formData.value.feeDate!);
if (isEdit.value && props.promotionFeeData) {
const updateData: PromotionFeeDTO.Update = {
id: props.promotionFeeData.id,
if (isEdit.value && props.adFeeData) {
const updateData: AdFeeDTO.Update = {
id: props.adFeeData.id,
...formData.value,
feeDate,
};
await updatePromotionFeeApi(updateData);
await updateAdFeeApi(updateData);
message.success('更新成功');
} else {
await createPromotionFeeApi({
await createAdFeeApi({
...formData.value,
feeDate,
});
@@ -298,14 +219,12 @@ const handleCancel = () => {
onMounted(() => {
loadShopList();
loadFeeTypeList();
loadCategoryTree();
loadProductList();
});
</script>
<template>
<Modal :title="isEdit ? '编辑推广费记录' : '新增推广费记录'">
<Modal :title="isEdit ? '编辑广告费记录' : '新增广告费记录'">
<Form
ref="formRef"
:model="formData"
@@ -329,46 +248,17 @@ onMounted(() => {
</Select>
</Form.Item>
<Form.Item label="推广费类型" name="feeTypeId">
<Select
v-model:value="formData.feeTypeId"
placeholder="请选择推广费类型"
:loading="feeTypeListLoading"
>
<Select.Option
v-for="feeType in feeTypeList"
:key="feeType.id"
:value="feeType.id"
>
{{ feeType.typeName }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="类目(可选)" name="categoryId">
<TreeSelect
v-model:value="formData.categoryId"
class="w-full"
placeholder="请选择类目(可选,用于类目级推广费或筛选商品)"
:tree-data="categoryOptions"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
:loading="categoryTreeLoading"
allow-clear
tree-default-expand-all
/>
</Form.Item>
<Form.Item label="商品(可选)" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选;已选类目时仅显示该类目下商品)"
placeholder="请选择商品(可选)"
:loading="productListLoading"
allow-clear
show-search
:filter-option="productSelectFilterOption"
>
<Select.Option
v-for="product in filteredProductList"
v-for="product in productList"
:key="product.id"
:value="product.id"
>
@@ -384,10 +274,10 @@ onMounted(() => {
/>
</Form.Item>
<Form.Item label="推广费金额" name="feeAmount">
<Form.Item label="广告费金额" name="feeAmount">
<InputNumber
v-model:value="formData.feeAmount"
placeholder="请输入推广费金额"
placeholder="请输入广告费金额"
:min="0"
:precision="2"
style="width: 100%"
@@ -397,7 +287,7 @@ onMounted(() => {
<Form.Item label="发生日期" name="feeDate">
<DatePicker
v-model:value="formData.feeDate"
placeholder="请选择推广费发生日期"
placeholder="请选择广告费发生日期"
style="width: 100%"
/>
</Form.Item>
@@ -1,12 +1,12 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/ec/promotion-fee/types';
AdFeeDTO,
AdFeeVO,
} from '#/api/ec/ad-fee/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref, watch } from 'vue';
import { computed, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
@@ -18,21 +18,19 @@ import {
Flex,
message,
Popconfirm,
Select,
Space,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePromotionFeeApi,
getPromotionFeePageApi,
} from '#/api/ec/promotion-fee';
import { getAllPromotionFeeTypeListApi } from '#/api/ec/promotion-fee/type/apis';
deleteAdFeeApi,
getAdFeePageApi,
} from '#/api/ec/ad-fee';
import ShopSidebarList from '#/views/ec/components/ShopSidebarList.vue';
import PromotionFeeFormModal from './components/PromotionFeeFormModal.vue';
import AdFeeFormModal from './components/AdFeeFormModal.vue';
defineOptions({ name: 'PromotionFeeManagement' });
defineOptions({ name: 'AdFeeManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
@@ -43,34 +41,10 @@ const selectedShopId = ref<number | undefined>(undefined);
const selectedShopName = ref<string | undefined>(undefined);
const formModalVisible = ref(false);
const currentPromotionFeeData = ref<null | PromotionFeeVO.Info>(null);
const currentAdFeeData = ref<null | AdFeeVO.Info>(null);
const presetShopIdForModal = ref<number | null>(null);
const feeTypeOptions = ref<{ label: string; value: number }[]>([]);
const feeTypeLoading = ref(false);
const feeTypeFetched = ref(false);
async function fetchFeeTypeOptions() {
if (feeTypeFetched.value || feeTypeLoading.value) return;
feeTypeLoading.value = true;
try {
const data = await getAllPromotionFeeTypeListApi();
feeTypeOptions.value = (data || []).map(
(type: { id: number; typeName: string }) => ({
label: type.typeName,
value: type.id,
}),
);
feeTypeFetched.value = true;
} catch {
message.error('获取推广费类型失败');
} finally {
feeTypeLoading.value = false;
}
}
const searchForm = ref({
feeTypeId: undefined as number | undefined,
feeDateStart: undefined as string | undefined,
feeDateEnd: undefined as string | undefined,
});
@@ -93,12 +67,12 @@ function onShopSelect(shop: { id: number; name: string } | null) {
}
function handleAddForShop(shopId: number) {
currentPromotionFeeData.value = null;
currentAdFeeData.value = null;
presetShopIdForModal.value = shopId;
formModalVisible.value = true;
}
const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
const gridOptions: VxeGridProps<AdFeeVO.Info> = {
columns: [
{
type: 'seq' as const,
@@ -111,13 +85,6 @@ const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
field: 'categoryName',
title: '类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
slots: { default: 'category' },
},
{
field: 'productName',
title: '商品',
@@ -125,12 +92,6 @@ const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
showOverflow: 'tooltip' as const,
slots: { default: 'product' },
},
{
field: 'feeTypeName',
title: '推广费类型',
minWidth: 110,
showOverflow: 'tooltip' as const,
},
{
field: 'campaignName',
title: '推广活动',
@@ -138,7 +99,7 @@ const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
showOverflow: 'tooltip' as const,
},
{
title: '推广费金额',
title: '广告费金额',
minWidth: 110,
slots: { default: 'feeAmount' },
},
@@ -194,20 +155,19 @@ const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<PromotionFeeDTO.Filters> = {
const params: PageQueryDTO<AdFeeDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
shopId: selectedShopId.value,
feeTypeId: searchForm.value.feeTypeId || undefined,
feeDateStart: searchForm.value.feeDateStart || undefined,
feeDateEnd: searchForm.value.feeDateEnd || undefined,
},
};
const data = await getPromotionFeePageApi(params);
const data = await getAdFeePageApi(params);
return { items: data.records, total: data.total };
} catch {
message.error('获取推广费记录列表失败');
message.error('获取广告费记录列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
@@ -231,29 +191,25 @@ watch(selectedShopId, () => {
gridApi.reload();
});
onMounted(() => {
void fetchFeeTypeOptions();
});
function resetModalPreset() {
presetShopIdForModal.value = null;
}
const handleAdd = () => {
currentPromotionFeeData.value = null;
currentAdFeeData.value = null;
resetModalPreset();
formModalVisible.value = true;
};
const handleEdit = (record: PromotionFeeVO.Info) => {
const handleEdit = (record: AdFeeVO.Info) => {
resetModalPreset();
currentPromotionFeeData.value = record;
currentAdFeeData.value = record;
formModalVisible.value = true;
};
async function handleDelete(id: number) {
try {
await deletePromotionFeeApi(id);
await deleteAdFeeApi(id);
message.success('删除成功');
refreshTable();
} catch {
@@ -275,10 +231,10 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</script>
<template>
<Page title="推广费管理" :auto-content-height="true">
<Page title="广告费管理" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择店铺筛选右侧推广记录;未选店铺时展示全部记录。可在店铺行快捷新增该店铺推广费。
左侧选择店铺筛选右侧推广记录;未选店铺时展示全部记录。可在店铺行快捷新增该店铺广告费。
</div>
</template>
@@ -286,7 +242,7 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
新增推广费
新增广告费
</Button>
</Space>
</template>
@@ -313,20 +269,6 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</template>
<template #extra>
<Space wrap size="small" class="max-w-[min(100%,42rem)]">
<Select
v-model:value="searchForm.feeTypeId"
allow-clear
show-search
:options="feeTypeOptions"
:loading="feeTypeLoading"
placeholder="类型"
class="min-w-[120px]"
option-filter-prop="label"
@dropdown-visible-change="
(open: boolean) => open && fetchFeeTypeOptions()
"
@change="() => refreshTable()"
/>
<DatePicker
v-model:value="searchForm.feeDateStart"
value-format="YYYY-MM-DD"
@@ -359,14 +301,10 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
<Grid :loading="loading" class="h-full min-h-0">
<template #toolbar-tools>
<span class="text-xs text-muted-foreground">
使用上方类型与日期筛选;表格在区域内滚动
使用上方日期筛选;表格在区域内滚动
</span>
</template>
<template #category="{ row }">
<span>{{ row.categoryName || '—' }}</span>
</template>
<template #feeAmount="{ row }">
<span class="font-semibold text-red-600">
{{ formatAmount(row.feeAmount) }}
@@ -389,7 +327,7 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这条推广费记录吗?"
title="确定要删除这条广告费记录吗?"
@confirm="handleDelete(row.id)"
>
<Button size="small" danger>删除</Button>
@@ -401,9 +339,9 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</Card>
</Flex>
<PromotionFeeFormModal
<AdFeeFormModal
v-model:open="formModalVisible"
:promotion-fee-data="currentPromotionFeeData"
:ad-fee-data="currentAdFeeData"
:preset-shop-id="presetShopIdForModal"
@success="handleFormSuccess"
@cancel="handleFormCancel"
@@ -5,7 +5,7 @@ import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'PromotionFeeFileUploadArea' });
defineOptions({ name: 'AdFeeFileUploadArea' });
const props = withDefaults(
defineProps<{
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { PromotionFeeFieldVO } from '#/api/ec/promotion-fee/types';
import type { AdFeeFieldVO } from '#/api/ec/ad-fee/types';
import type { ImportMappingVO } from '#/api/ec/import/mapping';
import type { ImportTaskDTO } from '#/api/ec/import/task';
import type { ShopVO } from '#/api/ec/shop/types';
@@ -16,7 +16,7 @@ import {
ImportMappingType,
updateImportMappingApi,
} from '#/api/ec/import/mapping';
import { getPromotionFeeFieldsApi } from '#/api/ec/promotion-fee/apis';
import { getAdFeeFieldsApi } from '#/api/ec/ad-fee/apis';
import { getShopPageApi } from '#/api/ec/shop';
import { createImportTaskApi } from '#/api/ec/import/task';
import { useImportTaskStore } from '#/store';
@@ -30,7 +30,7 @@ interface FieldMappingItem {
required: boolean;
}
defineOptions({ name: 'PromotionFeeImportTaskWizard' });
defineOptions({ name: 'AdFeeImportTaskWizard' });
const emit = defineEmits<{
success: [];
@@ -54,9 +54,9 @@ const shopSearchValue = ref('');
const feeDate = ref<any>(undefined);
const fieldDefs = ref<PromotionFeeFieldVO.Info[]>([]);
const fieldDefs = ref<AdFeeFieldVO.Info[]>([]);
const fieldMappings = ref<
Record<string, { fieldDef: PromotionFeeFieldVO.Info; mappedHeader?: string }>
Record<string, { fieldDef: AdFeeFieldVO.Info; mappedHeader?: string }>
>({});
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
@@ -178,8 +178,8 @@ const handleShopScroll = (e: any) => {
const fetchFieldDefs = async () => {
try {
fieldDefsLoading.value = true;
const result = await getPromotionFeeFieldsApi();
fieldDefs.value = (result || []) as unknown as PromotionFeeFieldVO.Info[];
const result = await getAdFeeFieldsApi();
fieldDefs.value = (result || []) as unknown as AdFeeFieldVO.Info[];
initFieldMappings();
} catch (error) {
console.error('获取字段定义失败:', error);
@@ -392,11 +392,9 @@ const handlePrev = () => {
};
const buildPatchedCsv = (): File => {
const headers = [...csvHeaders.value, 'feeTypeId', 'categoryId', 'productId'];
const headers = [...csvHeaders.value, 'productId'];
const rows = previewData.value.map((row: any) =>
headers.map((h: string) => {
if (h === 'feeTypeId') return row._feeTypeId ?? '';
if (h === 'categoryId') return row._categoryId ?? '';
if (h === 'productId') return row._productId ?? '';
return row[h] ?? '';
}),
@@ -411,7 +409,7 @@ const buildPatchedCsv = (): File => {
};
const buildPatchedFileName = (_original: string): string => {
return 'promotion_fee_import_patched.csv';
return 'ad_fee_import_patched.csv';
};
const handleCreateTask = async () => {
@@ -424,7 +422,7 @@ const handleCreateTask = async () => {
return;
}
if (!feeDate.value) {
message.warning('请选择推广费发生日期');
message.warning('请选择广告费发生日期');
return;
}
@@ -433,7 +431,7 @@ const handleCreateTask = async () => {
message.loading('正在上传文件...', 0);
const patchedFile = buildPatchedCsv();
const fileInfo = await uploadFileToOss(patchedFile, {
category: 'promotion-fee-import',
category: 'ad-fee-import',
errorMessage: '文件上传失败,请重试',
});
message.destroy();
@@ -572,7 +570,7 @@ const shopOptions = computed(() => {
>
<div class="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 gap-y-3">
<div class="text-sm text-gray-600 dark:text-gray-300">
请为每个推广费字段选择对应的CSV列,必填字段必须绑定
请为每个广告费字段选择对应的CSV列,必填字段必须绑定
</div>
<div class="flex items-center space-x-2">
<Select
@@ -651,7 +649,7 @@ const shopOptions = computed(() => {
系统
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
推广费字段
广告费字段
</span>
</div>
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
@@ -753,7 +751,7 @@ const shopOptions = computed(() => {
<Form.Item label="发生日期" required>
<DatePicker
v-model:value="feeDate"
placeholder="选择推广费发生日期"
placeholder="选择广告费发生日期"
style="width: 100%"
/>
</Form.Item>
@@ -783,7 +781,7 @@ const shopOptions = computed(() => {
<span class="font-medium">{{ Object.values(fieldMappings).filter((m) => m.mappedHeader).length }}/{{ fieldDefs.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">推广费类型/类目/商品</span>
<span class="text-gray-600 dark:text-gray-300">商品</span>
<span class="font-medium text-green-600">表格中逐行设置</span>
</div>
</div>
@@ -11,14 +11,10 @@ import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from '#/views/ec/import/order/utils/fileParser';
import { getActivePromotionFeeTypeListApi } from '#/api/ec/promotion-fee/type/apis';
import { getCategoryTreeApi } from '#/api/ec/product/category/apis';
import { getProductPageApi } from '#/api/ec/product/apis';
import type { PromotionFeeTypeVO } from '#/api/ec/promotion-fee/type/types';
import type { CategoryVO } from '#/api/ec/product/category/types';
import type { ProductVO } from '#/api/ec/product/types';
defineOptions({ name: 'PromotionFeeImport' });
defineOptions({ name: 'AdFeeImport' });
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
@@ -29,27 +25,21 @@ const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
const feeTypeOptions = ref<PromotionFeeTypeVO.Info[]>([]);
const categoryTree = ref<CategoryVO.Info[]>([]);
const productList = ref<ProductVO.Info[]>([]);
const loadReferenceData = async () => {
try {
const [feeTypesRes, categoryRes, productRes] = await Promise.all([
getActivePromotionFeeTypeListApi(),
getCategoryTreeApi(),
getProductPageApi({ page: 1, pageSize: 9999, filters: {} }),
]);
feeTypeOptions.value = feeTypesRes as unknown as PromotionFeeTypeVO.Info[];
categoryTree.value = categoryRes as unknown as CategoryVO.Info[];
const productRes = await getProductPageApi({
page: 1,
pageSize: 9999,
filters: {},
});
productList.value = ((productRes as any).records || []) as ProductVO.Info[];
} catch (e) {
console.error('加载参考数据失败', e);
}
};
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) return [];
@@ -66,64 +56,26 @@ const gridColumns = computed(() => {
});
});
columns.push(
{
field: '_feeTypeId',
title: '推广费类型',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: feeTypeOptions.value.map((t) => ({
label: t.typeName,
value: t.id,
})),
allowClear: true,
placeholder: '请选择',
},
columns.push({
field: '_productId',
title: '商品',
width: 180,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: productList.value.map((p) => ({
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
value: p.id,
})),
allowClear: true,
placeholder: '请选择商品',
showSearch: true,
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
},
},
{
field: '_categoryId',
title: '类目',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellTreeSelect',
props: {
treeData: categoryTree.value,
fieldNames: { label: 'name', value: 'id', children: 'children' },
allowClear: true,
placeholder: '请选择',
treeDefaultExpandAll: false,
},
},
},
{
field: '_productId',
title: '商品',
width: 180,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: productList.value.map((p) => ({
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
value: p.id,
categoryId: (p as any).categoryId,
})),
filterByRowField: '_categoryId',
filterOptionKey: 'categoryId',
allowClear: true,
placeholder: '请选择商品',
showSearch: true,
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
},
},
},
);
});
return columns;
});
@@ -311,12 +263,12 @@ onUnmounted(() => {
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
推广费导入中心
广告费导入中心
</h1>
<p
class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base"
>
请上传 CSV / Excel 格式的推广费原始数据
请上传 CSV / Excel 格式的广告费原始数据
</p>
</div>
<div
@@ -1,221 +0,0 @@
<script lang="ts" setup>
import type {
PromotionFeeTypeDTO,
PromotionFeeTypeVO,
} from '#/api/ec/promotion-fee/type';
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
Form,
Input,
InputNumber,
message,
Select,
Switch,
} from 'ant-design-vue';
import {
createPromotionFeeTypeApi,
updatePromotionFeeTypeApi,
} from '#/api/ec/promotion-fee/type';
const emit = defineEmits<{
cancel: [];
success: [];
}>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[600px]',
onCancel() {
close();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<null | PromotionFeeTypeVO.Info>(null);
// 表单数据
const formData = ref<Partial<PromotionFeeTypeDTO.Create>>({
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
});
// 计算方式选项
const calculationMethodOptions = [
{ label: '固定金额', value: 1 },
{ label: '按比例', value: 2 },
{ label: '按点击', value: 3 },
{ label: '按展示', value: 4 },
];
// 表单验证规则
const rules = {
typeCode: [{ required: true, message: '请输入类型编码', trigger: 'blur' }],
typeName: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }],
};
// 表单引用
const formRef = ref();
// 打开模态框
function open(edit: boolean, record?: PromotionFeeTypeVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
modalApi.open();
// 根据模式填充表单数据
formData.value =
edit && record
? {
typeName: record.typeName,
description: record.description || '',
calculationMethod: record.calculationMethod || 1,
sortOrder: record.sortOrder || 0,
isActive: record.isActive || 1,
}
: {
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
};
}
// 关闭模态框
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: PromotionFeeTypeDTO.Update = {
id: currentRecord.value.id,
typeName: formData.value.typeName!,
description: formData.value.description,
calculationMethod: formData.value.calculationMethod,
sortOrder: formData.value.sortOrder,
isActive: formData.value.isActive,
};
await updatePromotionFeeTypeApi(updateData);
message.success('更新推广费类型成功');
} else {
// 创建推广费类型
const createData: PromotionFeeTypeDTO.Create = {
typeName: formData.value.typeName!,
description: formData.value.description,
calculationMethod: formData.value.calculationMethod,
sortOrder: formData.value.sortOrder,
isActive: formData.value.isActive,
};
await createPromotionFeeTypeApi(createData);
message.success('创建推广费类型成功');
}
emit('success');
close();
} catch (error) {
console.error('提交推广费类型失败:', (error as any).message);
} finally {
loading.value = false;
}
}
// 监听 modal 关闭状态
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"
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="类型名称" name="typeName">
<Input
v-model:value="formData.typeName"
placeholder="请输入类型名称"
/>
</Form.Item>
</div>
<Form.Item label="类型描述" name="description">
<Input.TextArea
v-model:value="formData.description"
placeholder="请输入类型描述(可选)"
:rows="3"
/>
</Form.Item>
<div class="grid grid-cols-3 gap-4">
<Form.Item label="计算方式" name="calculationMethod">
<Select
v-model:value="formData.calculationMethod"
placeholder="请选择计算方式"
:options="calculationMethodOptions"
/>
</Form.Item>
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
<Form.Item label="启用状态" name="isActive">
<Switch
v-model:checked="formData.isActive"
:checked-value="1"
:un-checked-value="0"
checked-children="启用"
un-checked-children="禁用"
/>
</Form.Item>
</div>
</Form>
</Modal>
</template>
@@ -1,265 +0,0 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PromotionFeeTypeVO } from '#/api/ec/promotion-fee/type';
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 {
deletePromotionFeeTypeApi,
getAllPromotionFeeTypeListApi,
} from '#/api/ec/promotion-fee/type';
import PromotionFeeTypeFormModal from './components/PromotionFeeTypeFormModal.vue';
defineOptions({ name: 'PromotionFeeTypeConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false);
const promotionFeeTypeFormModalRef = ref();
// 计算方式选项
const calculationMethodOptions = [
{ label: '固定金额', value: 1 },
{ label: '按比例', value: 2 },
{ label: '按点击', value: 3 },
{ label: '按展示', value: 4 },
];
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
field: 'typeName',
title: '类型名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'description',
title: '类型描述',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
title: '计算方式',
minWidth: 'auto',
slots: { default: 'calculationMethod' },
},
{
field: 'sortOrder',
title: '排序',
minWidth: 'auto',
},
{
title: '状态',
minWidth: 'auto',
slots: { default: 'status' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 'auto',
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: 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 data = await getAllPromotionFeeTypeListApi();
return {
items: data,
total: data.length,
};
} catch (error) {
console.error('获取推广费类型列表失败:', error);
message.error('获取推广费类型列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入类型名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'typeName',
label: '类型名称',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择状态',
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
allowClear: true,
onChange: () => gridReloadRef.value?.(),
},
fieldName: 'isActive',
label: '状态',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '推广费用类型配置',
});
gridReloadRef.value = () => gridApi.reload();
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
// 处理添加推广费类型
function handleAdd() {
promotionFeeTypeFormModalRef.value?.open(false);
}
// 处理编辑推广费类型
function handleEdit(record: PromotionFeeTypeVO.Info) {
promotionFeeTypeFormModalRef.value?.open(true, record);
}
// 处理删除推广费类型
async function handleDelete(record: PromotionFeeTypeVO.Info) {
try {
await deletePromotionFeeTypeApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除推广费类型失败:', error);
message.error('删除推广费类型失败');
}
}
// 处理模态框成功
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
<Page title="推广费用类型配置" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理推广费用类型,包括费用类型名称、描述、计算方式和启用状态
</div>
</template>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加类型
</Button>
</Space>
</template>
<!-- 计算方式列 -->
<template #calculationMethod="{ row }: { row: any }">
<Tag color="blue">
{{
calculationMethodOptions.find(
(opt) => opt.value === row.calculationMethod,
)?.label || '未设置'
}}
</Tag>
</template>
<!-- 状态列 -->
<template #status="{ row }: { row: any }">
<Tag :color="row.isActive === 1 ? 'green' : 'red'">
{{ row.isActive === 1 ? '启用' : '禁用' }}
</Tag>
</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>
<!-- 推广费类型表单模态框 -->
<PromotionFeeTypeFormModal
ref="promotionFeeTypeFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
@@ -28,8 +28,6 @@ const createModalRef = ref<InstanceType<typeof CreateApiKeyModal>>();
const permissionLabelMap: Record<string, string> = {
'open:scope:order:import': '订单导入',
'open:scope:order:read': '订单字段',
'open:scope:promotion_fee:import': '推广费导入',
'open:scope:promotion_fee:read': '推广费字段',
'open:scope:import_task:read': '导入任务',
'open:scope:meta:read': '元数据',
};