2 Commits 71b7e2a8d1 ... db207c718b

Author SHA1 Message Date
  bai db207c718b 导入销售预测 4 months ago
  bai e22acaaf21 导入销售预测 4 months ago

+ 58 - 27
blade-service/blade-factory/src/main/java/org/springblade/factory/api/controller/SalesForecastSummaryController.java

@@ -1,6 +1,7 @@
 package org.springblade.factory.api.controller;
 
 
+import cn.hutool.core.collection.CollectionUtil;
 import com.alibaba.excel.EasyExcel;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -205,10 +206,8 @@ public class SalesForecastSummaryController {
 
 
 
-
-
 	@PostMapping("/importForecastData/{id}")
-	@ApiOperation(value = "导入销售预测数据(不删除原有数据)")
+	@ApiOperation(value = "导入销售预测数据(先删除原有数据,再保存新数据)")
 	public R<List<PcBladeSalesForecastSummary>> importForecastData(@PathVariable("id") Long id, @RequestParam("file") MultipartFile file) {
 
 		// 1. 基础参数校验
@@ -216,12 +215,13 @@ public class SalesForecastSummaryController {
 			return R.fail("预测ID不能为空");
 		}
 
+		// 2. 校验主表数据是否存在(保留原有逻辑)
 		PcBladeSalesForecastMain pcBladeDealerForecast = forecastMainService.getById(id);
 		if (pcBladeDealerForecast == null) {
 			return R.fail("预测主数据不存在");
 		}
 
-		// 2. 文件校验
+		// 3. 文件校验
 		if (file.isEmpty()) {
 			return R.fail("导入文件不能为空");
 		}
@@ -230,14 +230,14 @@ public class SalesForecastSummaryController {
 			return R.fail("仅支持.xlsx格式的Excel文件导入");
 		}
 
-		// 3. 从主表获取年月
+		// 4. 从主表获取年月
 		Integer forecastYear = pcBladeDealerForecast.getYear();
 		Integer forecastMonth = pcBladeDealerForecast.getMonth();
 		if (forecastYear == null || forecastMonth == null) {
 			return R.fail("预测主数据的年月不能为空");
 		}
 
-		// 4. 用户信息校验
+		// 5. 用户信息校验
 		Long userId = AuthUtil.getUserId();
 		if (userId == null) {
 			return R.fail("用户未登录");
@@ -248,11 +248,12 @@ public class SalesForecastSummaryController {
 		}
 
 		try {
-			// ========== 移除删除数据的逻辑 ==========
-			// 不再执行删除forecast_main_id = id的同年同月数据
-
-			// 5. 定义列表存储导入数据(无需线程安全,同步读取无并发)
-			List<PcBladeSalesForecastSummary> saveList = new ArrayList<>();
+			// ========== 核心修改:导入前先删除该forecast_main_id下的所有历史数据 ==========
+			boolean deleteSuccess = forecastService.physicallyDeleteByForecastMainId(id);
+			if (!deleteSuccess) {
+				// 这里可以根据业务选择:是抛出异常还是继续(建议继续,因为可能原本就没有数据)
+				// return R.fail("删除历史数据失败");
+			}
 
 			// 6. 同步读取Excel数据
 			List<SalesForecastImportDTO> dtoList = EasyExcel.read(file.getInputStream())
@@ -260,22 +261,38 @@ public class SalesForecastSummaryController {
 				.sheet()
 				.doReadSync();
 
-			// 7. 提前查询经销商信息(避免循环内重复查询,提升性能)
+			// 7. 定义列表存储导入数据
+			List<PcBladeSalesForecastSummary> saveList = new ArrayList<>();
+			// 用于记录Excel内重复的Key,避免同一Excel内重复
+			Set<String> excelUniqueKeySet = new HashSet<>();
+
+			// 8. 提前查询经销商信息(避免循环内重复查询)
 			QueryWrapper<ViewCustomerSel> customerQueryWrapper = new QueryWrapper<>();
 			customerQueryWrapper.eq("customer_id", user.getData().getCustomerId());
 			List<ViewCustomerSel> customerList = zcrmViewCustomerSelService.list(customerQueryWrapper);
-			if (customerList.isEmpty()) {
+			if (CollectionUtil.isEmpty(customerList)) {
 				return R.fail("经销商数据不存在");
 			}
 			ViewCustomerSel customerInfo = customerList.get(0);
 
-			// 8. 遍历解析的数据,转换为入库实体
+			// 9. 遍历解析的数据,转换为入库实体
 			for (SalesForecastImportDTO dto : dtoList) {
-				// 跳过空行(防止Excel空行导致无效数据)
+				// 跳过空行
 				if (dto.getItemCode() == null && dto.getItemName() == null && dto.getForecastQuantity() == null) {
 					continue;
 				}
 
+				// 处理物料编码
+				String itemCode = dto.getItemCode() == null ? "" : dto.getItemCode().trim();
+				// 生成唯一Key(用于Excel内去重)
+				String uniqueKey = buildUniqueKey(forecastYear, forecastMonth, user.getData().getCustomerId(), itemCode);
+
+				// 跳过Excel内重复的记录
+				if (excelUniqueKeySet.contains(uniqueKey)) {
+					continue;
+				}
+				excelUniqueKeySet.add(uniqueKey);
+
 				PcBladeSalesForecastSummary summary = new PcBladeSalesForecastSummary();
 
 				// 基础字段赋值
@@ -283,23 +300,23 @@ public class SalesForecastSummaryController {
 				summary.setMonth(forecastMonth);
 				summary.setForecastMainId(id); // 关联主预测表的ID
 
-				// 经销商信息赋值(统一使用提前查询的经销商信息)
+				// 经销商信息赋值
 				summary.setCustomerId(customerInfo.getId());
 				summary.setCustomerCode(customerInfo.getCustomerCode());
 				summary.setCustomerName(customerInfo.getCustomerName());
 
-				// Excel导入字段映射(处理空值和首尾空格)
-				summary.setItemCode(dto.getItemCode() == null ? "" : dto.getItemCode().trim());
+				// Excel导入字段映射
+				summary.setItemCode(itemCode);
 				summary.setItemName(dto.getItemName() == null ? "" : dto.getItemName().trim());
 				summary.setBrandName(dto.getBrandName() == null ? "" : dto.getBrandName().trim());
 				summary.setSpecs(dto.getSpecs() == null ? "" : dto.getSpecs().trim());
 				summary.setPattern(dto.getPattern() == null ? "" : dto.getPattern().trim());
 				summary.setForecastQuantity(dto.getForecastQuantity() == null ? BigDecimal.ZERO : dto.getForecastQuantity());
 
-				// 补充物料ID/品牌ID(关联库存表查询)
-				if (StringUtils.isNotBlank(dto.getItemCode())) {
+				// 补充物料ID/品牌ID
+				if (org.springframework.util.StringUtils.hasText(itemCode)) {
 					ViewWhqohSel stock = zcrmViewWhqohSelService.getOne(
-						new LambdaQueryWrapper<ViewWhqohSel>().eq(ViewWhqohSel::getItemCode, dto.getItemCode().trim())
+						new LambdaQueryWrapper<ViewWhqohSel>().eq(ViewWhqohSel::getItemCode, itemCode)
 					);
 					if (stock != null) {
 						summary.setItemId(stock.getItemId());
@@ -313,29 +330,43 @@ public class SalesForecastSummaryController {
 				saveList.add(summary);
 			}
 
-			// 9. 批量保存数据(仅当有有效数据时保存)
-			if (!saveList.isEmpty()) {
+			// 10. 批量保存数据(仅当有有效数据时保存)
+			int importCount = 0;
+			if (!CollectionUtil.isEmpty(saveList)) {
 				boolean saveSuccess = forecastService.saveBatch(saveList);
 				if (!saveSuccess) {
 					return R.fail("数据保存失败");
 				}
+				importCount = saveList.size();
 			}
 
-			// 10. 查询该forecast_main_id下的所有汇总明细数据并返回
+			// 11. 查询该forecast_main_id下的所有汇总明细数据并返回
 			LambdaQueryWrapper<PcBladeSalesForecastSummary> queryWrapper = new LambdaQueryWrapper<>();
-			queryWrapper.eq(PcBladeSalesForecastSummary::getForecastMainId, id);
-			// 可选:按物料号排序,返回数据更规整
-			queryWrapper.orderByAsc(PcBladeSalesForecastSummary::getItemCode);
+			queryWrapper.eq(PcBladeSalesForecastSummary::getForecastMainId, id)
+				.orderByAsc(PcBladeSalesForecastSummary::getItemCode);
 
 			List<PcBladeSalesForecastSummary> lists = forecastService.list(queryWrapper);
 
+			// 返回导入结果(包含导入数量)
 			return R.data(lists);
+
 		} catch (Exception e) {
 			e.printStackTrace();
 			return R.fail("导入失败:" + e.getMessage());
 		}
 	}
 
+	/**
+	 * 构建唯一Key(与数据库唯一索引uk_year_month_customer_item对应)
+	 * @param year 年份
+	 * @param month 月份
+	 * @param customerId 客户ID
+	 * @param itemCode 物料编码
+	 * @return 唯一标识字符串
+	 */
+	private String buildUniqueKey(Integer year, Integer month, Long customerId, String itemCode) {
+		return year + "_" + month + "_" + customerId + "_" + (itemCode == null ? "" : itemCode);
+	}
 
 	@GetMapping("/exportTemplate")
 	@ApiOperation(value="导出提交数据模板")

+ 12 - 0
blade-service/blade-factory/src/main/java/org/springblade/factory/mapper/PcBladeSalesForecastSummaryMapper.java

@@ -30,4 +30,16 @@ public interface PcBladeSalesForecastSummaryMapper extends BaseMapper<PcBladeSal
 		"</script>"
 	})
 	int deleteByIds(@Param("ids") List<Long> ids);
+
+
+
+	/**
+	 * 物理删除指定forecastMainId的所有明细数据
+	 * @param forecastMainId 预测主表ID
+	 * @return 删除的行数
+	 */
+	@Delete("DELETE FROM pc_blade_sales_forecast_summary WHERE forecast_main_id = #{forecastMainId}")
+	int physicallyDeleteByForecastMainId(@Param("forecastMainId") Long forecastMainId);
+
+
 }

+ 8 - 0
blade-service/blade-factory/src/main/java/org/springblade/factory/service/PcBladeSalesForecastSummaryService.java

@@ -195,4 +195,12 @@ public interface PcBladeSalesForecastSummaryService extends BaseService<PcBladeS
 	void exportMainData(Long userId, Integer year, Integer month, HttpServletResponse response) throws IOException;
 
 
+
+	/**
+	 * 物理删除指定forecastMainId的所有明细数据
+	 * @param forecastMainId 预测主表ID
+	 * @return 是否删除成功
+	 */
+	boolean physicallyDeleteByForecastMainId(Long forecastMainId);
+
 }

+ 12 - 0
blade-service/blade-factory/src/main/java/org/springblade/factory/service/impl/PcBladeSalesForecastSummaryServiceImpl.java

@@ -71,6 +71,18 @@ public class PcBladeSalesForecastSummaryServiceImpl extends BaseServiceImpl<PcBl
 	}
 
 
+	@Override
+	public boolean physicallyDeleteByForecastMainId(Long forecastMainId) {
+		if (forecastMainId == null) {
+			return false;
+		}
+		// 执行自定义的物理删除SQL
+		int deleteCount = baseMapper.physicallyDeleteByForecastMainId(forecastMainId);
+		// 只要删除行数 >= 0 就认为成功(0表示没有数据可删)
+		return deleteCount >= 0;
+	}
+
+
 	/**
 	 * 根据条件批量硬删除预测明细(先查ID再删)
 	 * @param wrapper 删除条件(年、月、客户ID、主表ID)