Browse Source

Savings统计表

master
qiankanghui 1 day ago
parent
commit
20a2bf841d
  1. 79
      src/main/java/com/xujie/modules/order/controller/SrmSavingsReportController.java
  2. 26
      src/main/java/com/xujie/modules/order/dao/SrmSavingsReportMapper.java
  3. 75
      src/main/java/com/xujie/modules/order/entity/SrmSavingsReport.java
  4. 42
      src/main/java/com/xujie/modules/order/service/Iface/ISrmSavingsReportService.java
  5. 642
      src/main/java/com/xujie/modules/order/service/Impl/SrmSavingsReportServiceImpl.java
  6. 48
      src/main/java/com/xujie/modules/order/vo/SrmSavingsReportRowVo.java
  7. 27
      src/main/java/com/xujie/modules/order/vo/SrmSavingsReportSaveVo.java
  8. 30
      src/main/resources/mapper/order/SrmSavingsReportMapper.xml
  9. 8
      src/test/java/com/xujie/service/DynamicDataSourceTestService.java

79
src/main/java/com/xujie/modules/order/controller/SrmSavingsReportController.java

@ -0,0 +1,79 @@
package com.xujie.modules.order.controller;
import com.xujie.common.utils.R;
import com.xujie.modules.order.entity.SrmSavingsReport;
import com.xujie.modules.order.service.Iface.ISrmSavingsReportService;
import com.xujie.modules.order.vo.SrmSavingsReportRowVo;
import com.xujie.modules.order.vo.SrmSavingsReportSaveVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* 国外 Savings 统计报表导入。
*/
@Api(tags = "Savings报表导入")
@RestController
@RequestMapping("/srm/srmSavingsReport")
public class SrmSavingsReportController {
@Autowired
private ISrmSavingsReportService srmSavingsReportService;
@GetMapping("/template")
@ApiOperation("下载Savings导入模板")
public ResponseEntity<Resource> downloadTemplate() {
byte[] bytes = srmSavingsReportService.buildTemplate();
String fileName = URLEncoder.encode("Savings报表导入模板.xlsx", StandardCharsets.UTF_8)
.replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(bytes.length))
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new ByteArrayResource(bytes));
}
@PostMapping("/page")
@ApiOperation("主页面分页查询")
public R page(@RequestBody(required = false) SrmSavingsReport query) {
return R.ok().put("page", srmSavingsReportService.page(query));
}
@PostMapping("/preview")
@ApiOperation("解析Excel并逐行校验,返回预览数据")
public R preview(@RequestParam("file") MultipartFile file, @RequestParam("site") String site) {
List<SrmSavingsReportRowVo> rows = srmSavingsReportService.preview(file, site);
return R.ok().put("data", rows).put("total", rows.size());
}
@GetMapping("/count")
@ApiOperation("统计指定年月已导入数据条数")
public R count(@RequestParam("year") Integer year, @RequestParam("month") Integer month) {
Integer count = srmSavingsReportService.countByYearMonth(year, month);
return R.ok().put("count", count);
}
@PostMapping("/save")
@ApiOperation("保存导入数据(overwrite覆盖 / append追加)")
public R save(@RequestBody SrmSavingsReportSaveVo data) {
Map<String, Object> result = srmSavingsReportService.save(data);
return R.ok().put("savedCount", result.get("savedCount")).put("skippedCount", result.get("skippedCount"));
}
}

26
src/main/java/com/xujie/modules/order/dao/SrmSavingsReportMapper.java

@ -0,0 +1,26 @@
package com.xujie.modules.order.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xujie.modules.order.entity.SrmSavingsReport;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface SrmSavingsReportMapper extends BaseMapper<SrmSavingsReport> {
/**
* 按供应商全称(已去空格并转大写)批量查询供应商编码。
* 返回 nameKey / supplierNo 两列;同名多行时取任一编码。
*/
List<Map<String, Object>> listSupplierByNameKeys(@Param("site") String site,
@Param("nameKeys") List<String> nameKeys);
/** 统计指定年月已导入的数据条数 */
Integer countByYearMonth(@Param("year") Integer year, @Param("month") Integer month);
/** 覆盖模式:删除指定年月的全部数据 */
int deleteByYearMonth(@Param("year") Integer year, @Param("month") Integer month);
}

75
src/main/java/com/xujie/modules/order/entity/SrmSavingsReport.java

@ -0,0 +1,75 @@
package com.xujie.modules.order.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xujie.common.utils.QueryPage;
import lombok.Data;
import org.apache.ibatis.type.JdbcType;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 国外 Savings 统计报表(按月导入)。
*/
@Data
@TableName("srm_savings_report")
public class SrmSavingsReport extends QueryPage implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 导入时页面选择的年份 */
@TableField("[year]")
private Integer year;
/** 导入时页面选择的月份(1-12) */
@TableField("[month]")
private Integer month;
private String poNumber;
/** 供应商全称,导入时校验并解析 supplier_no */
private String vendorName;
/** 由 vendor_name 匹配 srm_supplier 得到的供应商编码 */
private String supplierNo;
/** SQL Server 下日期列写 null 必须显式声明 jdbcType,否则驱动按 varbinary 发送导致隐式转换报错。 */
@TableField(jdbcType = JdbcType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date issuedDate;
private String itemCode;
private BigDecimal unitPrice;
@TableField(jdbcType = JdbcType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date receivedDate;
@TableField(jdbcType = JdbcType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date needByDate;
private BigDecimal qty;
private BigDecimal oldPrice;
private BigDecimal variance;
private BigDecimal extAmount;
/** 导入人 */
private String createBy;
@TableField(jdbcType = JdbcType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;
}

42
src/main/java/com/xujie/modules/order/service/Iface/ISrmSavingsReportService.java

@ -0,0 +1,42 @@
package com.xujie.modules.order.service.Iface;
import com.xujie.common.utils.PageUtils;
import com.xujie.modules.order.entity.SrmSavingsReport;
import com.xujie.modules.order.vo.SrmSavingsReportRowVo;
import com.xujie.modules.order.vo.SrmSavingsReportSaveVo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* 国外 Savings 统计报表导入。
*/
public interface ISrmSavingsReportService {
/**
* 生成 Savings 导入模板(固定 11 列表头,与 CNREPORT.xlsx 一致)。
*/
byte[] buildTemplate();
/**
* 主页面分页查询:支持年月精确、PO单号/供应商名称模糊筛选。
*/
PageUtils page(SrmSavingsReport query);
/**
* 解析 Excel 并逐行校验,返回预览行数据(不写库)。
*/
List<SrmSavingsReportRowVo> preview(MultipartFile file, String site);
/**
* 统计指定年月已导入的数据条数,供前端决定覆盖/新增。
*/
Integer countByYearMonth(Integer year, Integer month);
/**
* 保存导入数据。服务端逐行重新校验;overwrite 先删该年月数据再插入,append 直接追加。
* 返回 savedCount / skippedCount。
*/
Map<String, Object> save(SrmSavingsReportSaveVo data);
}

642
src/main/java/com/xujie/modules/order/service/Impl/SrmSavingsReportServiceImpl.java

@ -0,0 +1,642 @@
package com.xujie.modules.order.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.common.utils.PageUtils;
import com.xujie.common.utils.ShiroUtils;
import com.xujie.modules.order.dao.SrmSavingsReportMapper;
import com.xujie.modules.order.entity.SrmSavingsReport;
import com.xujie.modules.order.service.Iface.ISrmSavingsReportService;
import com.xujie.modules.order.vo.SrmSavingsReportRowVo;
import com.xujie.modules.order.vo.SrmSavingsReportSaveVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 国外 Savings 统计报表导入。
* 预览与保存使用同一套解析校验规则;保存不信任前端 valid,服务端逐行重新校验。
*/
@Slf4j
@Service
public class SrmSavingsReportServiceImpl extends ServiceImpl<SrmSavingsReportMapper, SrmSavingsReport>
implements ISrmSavingsReportService {
/** Excel 固定 11 列表头(顺序与业务样表一致,校验忽略大小写和首尾空格)。 */
private static final List<String> HEADER_LABELS = Arrays.asList(
"PONumber", "VendorName", "Issued_Date", "ItemCode", "UnitPrice",
"Received_Date", "need_by_date", "Qty", "OldPrice", "Variance", "ExtAmount");
private static final int COLUMN_COUNT = HEADER_LABELS.size();
/** 列下标常量,避免魔法数字散落。 */
private static final int COL_PO_NUMBER = 0;
private static final int COL_VENDOR_NAME = 1;
private static final int COL_ISSUED_DATE = 2;
private static final int COL_ITEM_CODE = 3;
private static final int COL_UNIT_PRICE = 4;
private static final int COL_RECEIVED_DATE = 5;
private static final int COL_NEED_BY_DATE = 6;
private static final int COL_QTY = 7;
private static final int COL_OLD_PRICE = 8;
private static final int COL_VARIANCE = 9;
private static final int COL_EXT_AMOUNT = 10;
private static final int MAX_IMPORT_ROWS = 5000;
private static final int MAX_CONSECUTIVE_EMPTY_ROWS = 50;
private static final int SUPPLIER_IN_BATCH = 500;
private static final String IMPORT_MODE_OVERWRITE = "overwrite";
private static final String IMPORT_MODE_APPEND = "append";
private static final String DATE_TIME_DISPLAY = "yyyy-MM-dd HH:mm:ss";
private static final String SKIPPED_MESSAGE = "未收货,跳过不导入";
private static final DataFormatter DATA_FORMATTER = new DataFormatter(Locale.ENGLISH);
private static final DateTimeFormatter OUTPUT_FORMATTER =
DateTimeFormatter.ofPattern(DATE_TIME_DISPLAY, Locale.ENGLISH);
/** 文本日期兼容带秒/不带秒及常见分隔符;Excel 日期单元格直接取 getDateCellValue。 */
private static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("yyyy-M-d H:m:s", Locale.ENGLISH),
DateTimeFormatter.ofPattern("yyyy/M/d H:m:s", Locale.ENGLISH),
DateTimeFormatter.ofPattern("yyyy-M-d H:m", Locale.ENGLISH),
DateTimeFormatter.ofPattern("yyyy/M/d H:m", Locale.ENGLISH),
DateTimeFormatter.ofPattern("M/d/yyyy H:m:s", Locale.ENGLISH),
DateTimeFormatter.ofPattern("M/d/yyyy H:m", Locale.ENGLISH));
private static final List<DateTimeFormatter> DATE_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("yyyy-M-d", Locale.ENGLISH),
DateTimeFormatter.ofPattern("yyyy/M/d", Locale.ENGLISH),
DateTimeFormatter.ofPattern("M/d/yyyy", Locale.ENGLISH));
/** 生成与 CNREPORT.xlsx 一致的固定 11 列表头模板,表头加粗并冻结首行。 */
@Override
public byte[] buildTemplate() {
try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
XSSFFont font = workbook.createFont();
font.setBold(true);
XSSFCellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFont(font);
Sheet sheet = workbook.createSheet("Sheet1");
Row header = sheet.createRow(0);
for (int i = 0; i < HEADER_LABELS.size(); i++) {
Cell cell = header.createCell(i);
cell.setCellValue(HEADER_LABELS.get(i));
cell.setCellStyle(headerStyle);
sheet.setColumnWidth(i, 18 * 256);
}
sheet.createFreezePane(0, 1);
workbook.write(output);
return output.toByteArray();
} catch (Exception ex) {
throw new RuntimeException("生成Savings导入模板失败", ex);
}
}
/** 主页面分页查询:年月精确、PO单号/供应商名称模糊;空条件不拼接,按年月倒序、同批次按插入顺序倒序。 */
@Override
public PageUtils page(SrmSavingsReport query) {
if (query == null) {
query = new SrmSavingsReport();
}
LambdaQueryWrapper<SrmSavingsReport> wrapper = new LambdaQueryWrapper<SrmSavingsReport>()
.eq(query.getYear() != null, SrmSavingsReport::getYear, query.getYear())
.eq(query.getMonth() != null, SrmSavingsReport::getMonth, query.getMonth())
.like(StringUtils.hasText(query.getPoNumber()), SrmSavingsReport::getPoNumber, trimToNull(query.getPoNumber()))
.like(StringUtils.hasText(query.getVendorName()), SrmSavingsReport::getVendorName, trimToNull(query.getVendorName()))
.orderByDesc(SrmSavingsReport::getYear)
.orderByDesc(SrmSavingsReport::getMonth)
.orderByDesc(SrmSavingsReport::getId);
IPage<SrmSavingsReport> iPage = this.baseMapper.selectPage(query.toMybatisPage(), wrapper);
return new PageUtils(iPage);
}
@Override
public List<SrmSavingsReportRowVo> preview(MultipartFile file, String site) {
validateFile(file);
if (!StringUtils.hasText(site)) {
throw new RuntimeException("当前登录用户没有Site");
}
List<ParsedRow> parsedRows = parseExcel(file);
// 供应商整批预加载:一次文件只按名称去重查询,避免逐行查库。
List<String> nameKeys = new ArrayList<>();
for (ParsedRow row : parsedRows) {
String key = upperKey(row.vendorName);
if (key != null && !nameKeys.contains(key)) {
nameKeys.add(key);
}
}
Map<String, String> supplierMap = resolveSupplierMap(site, nameKeys);
List<SrmSavingsReportRowVo> result = new ArrayList<>();
for (ParsedRow row : parsedRows) {
String key = upperKey(row.vendorName);
if (StringUtils.hasText(row.vendorName)
&& (key == null || !supplierMap.containsKey(key))) {
row.errors.add("第" + row.excelRowNo + "行供应商不存在");
}
String supplierNo = key == null ? null : supplierMap.get(key);
result.add(toRowVo(row, supplierNo));
}
return result;
}
@Override
public Integer countByYearMonth(Integer year, Integer month) {
validateYearMonth(year, month);
Integer count = this.baseMapper.countByYearMonth(year, month);
return count == null ? 0 : count;
}
/**
* 保存导入数据:单事务,失败整体回滚。
* 服务端逐行重新解析校验(不信任前端 valid),Received_Date 为空的行跳过不落库;
* overwrite 先删除该年月全部数据再插入,append 直接追加。
*/
@Override
@Transactional(rollbackFor = Exception.class, timeout = 300)
public Map<String, Object> save(SrmSavingsReportSaveVo data) {
if (data == null) {
throw new RuntimeException("导入数据不能为空");
}
validateYearMonth(data.getYear(), data.getMonth());
String site = trimToNull(data.getSite());
if (!StringUtils.hasText(site)) {
throw new RuntimeException("当前登录用户没有Site");
}
if (!IMPORT_MODE_OVERWRITE.equals(data.getMode()) && !IMPORT_MODE_APPEND.equals(data.getMode())) {
throw new RuntimeException("导入模式不正确");
}
List<SrmSavingsReportRowVo> rows = data.getRows();
if (rows == null || rows.isEmpty()) {
throw new RuntimeException("没有可导入的数据,请先选择文件预览");
}
if (rows.size() > MAX_IMPORT_ROWS) {
throw new RuntimeException("单次导入上限是" + MAX_IMPORT_ROWS + "行,请分批导入");
}
// 供应商整批重新解析,保存不信任前端传回的 supplierNo。
List<String> nameKeys = new ArrayList<>();
for (SrmSavingsReportRowVo row : rows) {
String key = upperKey(row.getVendorName());
if (key != null && !nameKeys.contains(key)) {
nameKeys.add(key);
}
}
Map<String, String> supplierMap = resolveSupplierMap(site, nameKeys);
List<String> errors = new ArrayList<>();
List<SrmSavingsReport> entities = new ArrayList<>();
int skippedCount = 0;
String operator = ShiroUtils.getUserEntity() == null ? null : ShiroUtils.getUserEntity().getUsername();
Date now = new Date();
for (int index = 0; index < rows.size(); index++) {
SrmSavingsReportRowVo row = rows.get(index);
if (row == null) {
errors.add("第" + (index + 1) + "条数据为空");
continue;
}
int excelRowNo = row.getExcelRowNo() == null ? index + 2 : row.getExcelRowNo();
List<String> rowErrors = new ArrayList<>();
String poNumber = trimToNull(row.getPoNumber());
if (poNumber == null) {
rowErrors.add("第" + excelRowNo + "行PONumber不能为空");
}
String vendorName = trimToNull(row.getVendorName());
String supplierNo = null;
if (vendorName == null) {
rowErrors.add("第" + excelRowNo + "行VendorName不能为空");
} else {
supplierNo = supplierMap.get(upperKey(vendorName));
if (supplierNo == null) {
rowErrors.add("第" + excelRowNo + "行供应商不存在");
}
}
Date issuedDate = parseTextDate(row.getIssuedDate(), excelRowNo, "Issued_Date", rowErrors);
Date receivedDate = parseTextDate(row.getReceivedDate(), excelRowNo, "Received_Date", rowErrors);
Date needByDate = parseTextDate(row.getNeedByDate(), excelRowNo, "need_by_date", rowErrors);
BigDecimal unitPrice = parseTextDecimal(row.getUnitPrice(), excelRowNo, "UnitPrice", rowErrors);
BigDecimal qty = parseTextDecimal(row.getQty(), excelRowNo, "Qty", rowErrors);
BigDecimal oldPrice = parseTextDecimal(row.getOldPrice(), excelRowNo, "OldPrice", rowErrors);
BigDecimal variance = parseTextDecimal(row.getVariance(), excelRowNo, "Variance", rowErrors);
BigDecimal extAmount = parseTextDecimal(row.getExtAmount(), excelRowNo, "ExtAmount", rowErrors);
String itemCode = trimToNull(row.getItemCode());
if (!rowErrors.isEmpty()) {
errors.addAll(rowErrors);
continue;
}
// 与预览一致:Received_Date 为空的行属于未收货,跳过不落库。
if (receivedDate == null) {
skippedCount++;
continue;
}
SrmSavingsReport entity = new SrmSavingsReport();
entity.setYear(data.getYear());
entity.setMonth(data.getMonth());
entity.setPoNumber(poNumber);
entity.setVendorName(vendorName);
entity.setSupplierNo(supplierNo);
entity.setIssuedDate(issuedDate);
entity.setItemCode(itemCode);
entity.setUnitPrice(unitPrice);
entity.setReceivedDate(receivedDate);
entity.setNeedByDate(needByDate);
entity.setQty(qty);
entity.setOldPrice(oldPrice);
entity.setVariance(variance);
entity.setExtAmount(extAmount);
entity.setCreateBy(operator);
entity.setCreateDate(now);
entities.add(entity);
}
if (!errors.isEmpty()) {
String detail = errors.size() > 20
? String.join(";", errors.subList(0, 20)) + ";等共" + errors.size() + "个错误"
: String.join(";", errors);
throw new RuntimeException("导入校验失败:" + detail);
}
if (entities.isEmpty()) {
throw new RuntimeException("没有可导入的数据(全部行未收货)");
}
if (IMPORT_MODE_OVERWRITE.equals(data.getMode())) {
this.baseMapper.deleteByYearMonth(data.getYear(), data.getMonth());
}
// SQL Server JDBC 驱动在 BATCH 模式(executeBatch)下不支持 getGeneratedKeys 回填自增主键,
// 会报「必须执行该语句才能获得结果」;IdType.AUTO 下改逐条 insert,单条执行回填主键是驱动的合法路径。
for (SrmSavingsReport entity : entities) {
this.baseMapper.insert(entity);
}
Map<String, Object> result = new HashMap<>();
result.put("savedCount", entities.size());
result.put("skippedCount", skippedCount);
log.info("Savings报表导入完成 - site={}, year={}, month={}, mode={}, saved={}, skipped={}",
site, data.getYear(), data.getMonth(), data.getMode(), entities.size(), skippedCount);
return result;
}
// ==================== Excel 解析 ====================
/** 预览行的中间解析结果:业务值为强类型,解析失败信息累积在 errors。 */
private static class ParsedRow {
private int excelRowNo;
private String poNumber;
private String vendorName;
private String itemCode;
private Date issuedDate;
private Date receivedDate;
private Date needByDate;
private BigDecimal unitPrice;
private BigDecimal qty;
private BigDecimal oldPrice;
private BigDecimal variance;
private BigDecimal extAmount;
private final List<String> errors = new ArrayList<>();
}
private void validateFile(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new RuntimeException("请选择导入文件");
}
String name = file.getOriginalFilename();
if (name == null || !(name.toLowerCase(Locale.ENGLISH).endsWith(".xls")
|| name.toLowerCase(Locale.ENGLISH).endsWith(".xlsx"))) {
throw new RuntimeException("仅支持 .xls / .xlsx 格式的Excel文件");
}
}
private List<ParsedRow> parseExcel(MultipartFile file) {
try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
if (workbook.getNumberOfSheets() == 0) {
throw new RuntimeException("Excel中没有工作表");
}
Sheet sheet = workbook.getSheetAt(0);
validateHeader(sheet.getRow(0));
List<ParsedRow> rows = new ArrayList<>();
int emptyStreak = 0;
for (Row row : sheet) {
if (row.getRowNum() == 0) {
continue;
}
if (isEmptyRow(row)) {
emptyStreak++;
if (emptyStreak >= MAX_CONSECUTIVE_EMPTY_ROWS) {
break;
}
continue;
}
emptyStreak = 0;
if (rows.size() >= MAX_IMPORT_ROWS) {
throw new RuntimeException("单次导入上限是" + MAX_IMPORT_ROWS + "行,请分批导入");
}
rows.add(parseDataRow(row));
}
if (rows.isEmpty()) {
throw new RuntimeException("Excel中没有可导入的数据");
}
return rows;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException("读取Excel失败,请检查文件格式", ex);
}
}
/** 表头必须严格为固定 11 列且顺序一致,多列少列都直接终止,避免列错位静默导错。 */
private void validateHeader(Row headerRow) {
if (headerRow == null) {
throw new RuntimeException("Excel缺少表头行(第1行)");
}
List<String> actual = new ArrayList<>();
for (int i = 0; i < headerRow.getLastCellNum(); i++) {
String text = readCellText(headerRow, i);
if (!text.isEmpty()) {
actual.add(text);
}
}
if (actual.size() != COLUMN_COUNT) {
throw new RuntimeException("Excel表头必须为11列:" + String.join(", ", HEADER_LABELS)
+ ";实际识别到" + actual.size() + "列,请核对模板后重新导入");
}
for (int i = 0; i < COLUMN_COUNT; i++) {
if (!HEADER_LABELS.get(i).equalsIgnoreCase(actual.get(i))) {
throw new RuntimeException("Excel第" + (i + 1) + "列表头应为" + HEADER_LABELS.get(i)
+ ",实际为" + actual.get(i));
}
}
}
private boolean isEmptyRow(Row row) {
for (int i = 0; i < COLUMN_COUNT; i++) {
if (!readCellText(row, i).isEmpty()) {
return false;
}
}
return true;
}
private ParsedRow parseDataRow(Row row) {
ParsedRow parsed = new ParsedRow();
parsed.excelRowNo = row.getRowNum() + 1;
parsed.poNumber = trimToNull(readCellText(row, COL_PO_NUMBER));
parsed.vendorName = trimToNull(readCellText(row, COL_VENDOR_NAME));
parsed.itemCode = trimToNull(readCellText(row, COL_ITEM_CODE));
if (parsed.poNumber == null) {
parsed.errors.add("第" + parsed.excelRowNo + "行PONumber不能为空");
}
if (parsed.vendorName == null) {
parsed.errors.add("第" + parsed.excelRowNo + "行VendorName不能为空");
}
parsed.issuedDate = readCellDate(row, COL_ISSUED_DATE, "Issued_Date", parsed.errors);
parsed.receivedDate = readCellDate(row, COL_RECEIVED_DATE, "Received_Date", parsed.errors);
parsed.needByDate = readCellDate(row, COL_NEED_BY_DATE, "need_by_date", parsed.errors);
parsed.unitPrice = readCellDecimal(row, COL_UNIT_PRICE, "UnitPrice", parsed.errors);
parsed.qty = readCellDecimal(row, COL_QTY, "Qty", parsed.errors);
parsed.oldPrice = readCellDecimal(row, COL_OLD_PRICE, "OldPrice", parsed.errors);
parsed.variance = readCellDecimal(row, COL_VARIANCE, "Variance", parsed.errors);
parsed.extAmount = readCellDecimal(row, COL_EXT_AMOUNT, "ExtAmount", parsed.errors);
return parsed;
}
/** 单元格文本;getCell 对未写入的单元格返回 null,必须判空。 */
private String readCellText(Row row, int index) {
Cell cell = row.getCell(index);
if (cell == null) {
return "";
}
return DATA_FORMATTER.formatCellValue(cell).trim();
}
/** 日期单元格:Excel 日期格式直接取值(保留时分秒),文本按多种格式解析,失败累积行错误。 */
private Date readCellDate(Row row, int index, String label, List<String> errors) {
Cell cell = row.getCell(index);
if (cell == null || cell.getCellType() == CellType.BLANK) {
return null;
}
if (isNumericLike(cell) && DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
}
String text = DATA_FORMATTER.formatCellValue(cell).trim();
if (isEmptyLike(text)) {
return null;
}
Date date = parseTextDate(text);
if (date == null) {
errors.add("第" + (row.getRowNum() + 1) + "行" + label + "日期格式无法识别:" + text);
}
return date;
}
/** 数字单元格:数值格用原始存储值避免显示格式截断精度,文本格按数字解析,失败累积行错误。 */
private BigDecimal readCellDecimal(Row row, int index, String label, List<String> errors) {
Cell cell = row.getCell(index);
if (cell == null || cell.getCellType() == CellType.BLANK) {
return null;
}
if (isNumericLike(cell)) {
if (DateUtil.isCellDateFormatted(cell)) {
errors.add("第" + (row.getRowNum() + 1) + "行" + label + "不是数字:"
+ DATA_FORMATTER.formatCellValue(cell).trim());
return null;
}
// Excel 数值格底层就是 double,valueOf(double) 取的是单元格真实存储值,不受显示格式截断。
return BigDecimal.valueOf(cell.getNumericCellValue());
}
String text = DATA_FORMATTER.formatCellValue(cell).trim().replace(",", "");
if (isEmptyLike(text)) {
return null;
}
try {
return new BigDecimal(text);
} catch (Exception ex) {
errors.add("第" + (row.getRowNum() + 1) + "行" + label + "数字格式无法识别:" + text);
return null;
}
}
/** 数值格(含公式缓存为数值的情况)。文本格一律走 DataFormatter,不使用 getRawValue 防止读到共享字符串索引。 */
private boolean isNumericLike(Cell cell) {
if (cell == null) {
return false;
}
if (cell.getCellType() == CellType.NUMERIC) {
return true;
}
return cell.getCellType() == CellType.FORMULA
&& cell.getCachedFormulaResultType() == CellType.NUMERIC;
}
private SrmSavingsReportRowVo toRowVo(ParsedRow row, String supplierNo) {
SrmSavingsReportRowVo vo = new SrmSavingsReportRowVo();
vo.setExcelRowNo(row.excelRowNo);
vo.setPoNumber(row.poNumber);
vo.setVendorName(row.vendorName);
vo.setSupplierNo(supplierNo);
vo.setIssuedDate(formatDate(row.issuedDate));
vo.setReceivedDate(formatDate(row.receivedDate));
vo.setNeedByDate(formatDate(row.needByDate));
vo.setItemCode(row.itemCode);
vo.setUnitPrice(formatDecimal(row.unitPrice));
vo.setQty(formatDecimal(row.qty));
vo.setOldPrice(formatDecimal(row.oldPrice));
vo.setVariance(formatDecimal(row.variance));
vo.setExtAmount(formatDecimal(row.extAmount));
vo.setSkipped(row.errors.isEmpty() && row.receivedDate == null);
vo.setValid(row.errors.isEmpty());
if (!row.errors.isEmpty()) {
vo.setValidationMessage(String.join(";", row.errors));
} else if (row.receivedDate == null) {
vo.setValidationMessage(SKIPPED_MESSAGE);
} else {
vo.setValidationMessage("");
}
return vo;
}
// ==================== 通用工具 ====================
/** 批量解析供应商名称 → 编码;IN 条件分批,避免超长 SQL。 */
private Map<String, String> resolveSupplierMap(String site, List<String> nameKeys) {
Map<String, String> supplierMap = new HashMap<>();
if (nameKeys == null || nameKeys.isEmpty()) {
return supplierMap;
}
for (int start = 0; start < nameKeys.size(); start += SUPPLIER_IN_BATCH) {
List<String> batch = nameKeys.subList(start, Math.min(start + SUPPLIER_IN_BATCH, nameKeys.size()));
List<Map<String, Object>> found = this.baseMapper.listSupplierByNameKeys(site, batch);
if (found != null) {
for (Map<String, Object> item : found) {
Object key = item.get("nameKey");
Object no = item.get("supplierNo");
if (key != null && no != null) {
supplierMap.put(String.valueOf(key), String.valueOf(no));
}
}
}
}
return supplierMap;
}
private void validateYearMonth(Integer year, Integer month) {
if (year == null || year < 1970 || year > 9999) {
throw new RuntimeException("年份不正确");
}
if (month == null || month < 1 || month > 12) {
throw new RuntimeException("月份不正确");
}
}
/** 保存入参日期解析:只接受预览输出的 yyyy-MM-dd[ HH:mm[:ss]] 及常见分隔符写法。 */
private Date parseTextDate(String text, int excelRowNo, String label, List<String> errors) {
String value = trimToNull(text);
if (value == null || isNullLiteral(value)) {
return null;
}
Date date = parseTextDate(value);
if (date == null) {
errors.add("第" + excelRowNo + "行" + label + "日期格式无法识别:" + value);
}
return date;
}
private Date parseTextDate(String text) {
for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) {
try {
return Date.from(LocalDateTime.parse(text, formatter)
.atZone(ZoneId.systemDefault()).toInstant());
} catch (Exception ignore) {
// 尝试下一个格式
}
}
for (DateTimeFormatter formatter : DATE_FORMATTERS) {
try {
return Date.from(LocalDate.parse(text, formatter).atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (Exception ignore) {
// 尝试下一个格式
}
}
return null;
}
private BigDecimal parseTextDecimal(String text, int excelRowNo, String label, List<String> errors) {
String value = trimToNull(text);
if (value == null || isNullLiteral(value)) {
return null;
}
try {
return new BigDecimal(value.replace(",", ""));
} catch (Exception ex) {
errors.add("第" + excelRowNo + "行" + label + "数字格式无法识别:" + value);
return null;
}
}
private String formatDate(Date date) {
if (date == null) {
return null;
}
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).format(OUTPUT_FORMATTER);
}
private String formatDecimal(BigDecimal value) {
return value == null ? null : value.toPlainString();
}
private String upperKey(String name) {
String value = trimToNull(name);
return value == null ? null : value.toUpperCase(Locale.ENGLISH);
}
private String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
/** CNREPORT 样表用文本 NULL 表示空值(如未收货的 Received_Date),解析时一律按空处理。 */
private boolean isNullLiteral(String text) {
return "NULL".equalsIgnoreCase(text);
}
/** 空串或 NULL 文本都视为无值。 */
private boolean isEmptyLike(String text) {
return text == null || text.isEmpty() || isNullLiteral(text);
}
}

48
src/main/java/com/xujie/modules/order/vo/SrmSavingsReportRowVo.java

@ -0,0 +1,48 @@
package com.xujie.modules.order.vo;
import lombok.Data;
/**
* Savings 报表导入预览行:所有业务值以规范化字符串传输(日期 yyyy-MM-dd HH:mm:ss、数字 toPlainString),
* 解析失败的单元格保留原文并由 validationMessage 说明错误;保存时后端按同一规则重新解析校验。
*/
@Data
public class SrmSavingsReportRowVo {
/** 真实 Excel 行号(从 1 开始,表头为第 1 行) */
private Integer excelRowNo;
private String poNumber;
private String vendorName;
private String issuedDate;
private String itemCode;
private String unitPrice;
private String receivedDate;
private String needByDate;
private String qty;
private String oldPrice;
private String variance;
private String extAmount;
/** 预览阶段解析出的供应商编码(仅展示参考,保存时重新解析) */
private String supplierNo;
/** 校验是否通过;false 时前端黄标并阻断保存 */
private Boolean valid;
/** 行级错误/提示信息,多个错误用分号拼接 */
private String validationMessage;
/** Received_Date 为空时为 true:未收货,跳过不导入 */
private Boolean skipped;
}

27
src/main/java/com/xujie/modules/order/vo/SrmSavingsReportSaveVo.java

@ -0,0 +1,27 @@
package com.xujie.modules.order.vo;
import lombok.Data;
import java.util.List;
/**
* Savings 报表导入保存入参。
*/
@Data
public class SrmSavingsReportSaveVo {
/** 导入年份 */
private Integer year;
/** 导入月份(1-12) */
private Integer month;
/** 导入模式:overwrite=覆盖(先删该年月数据再插入),append=新增(追加) */
private String mode;
/** 当前登录 Site,用于供应商名称匹配 */
private String site;
/** 预览行数据;服务端不信任前端 valid,保存时逐行重新校验 */
private List<SrmSavingsReportRowVo> rows;
}

30
src/main/resources/mapper/order/SrmSavingsReportMapper.xml

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xujie.modules.order.dao.SrmSavingsReportMapper">
<!-- 供应商名称匹配口径与期初导入一致:UPPER(LTRIM(RTRIM(supplier_name))),按当前 site 过滤 -->
<select id="listSupplierByNameKeys" resultType="java.util.Map">
select UPPER(LTRIM(RTRIM(supplier_name))) as nameKey,
MIN(supplier_no) as supplierNo
from srm_supplier
where site = #{site}
and UPPER(LTRIM(RTRIM(supplier_name))) in
<foreach collection="nameKeys" item="nameKey" open="(" separator="," close=")">
#{nameKey}
</foreach>
group by UPPER(LTRIM(RTRIM(supplier_name)))
</select>
<select id="countByYearMonth" resultType="java.lang.Integer">
select count(1)
from srm_savings_report
where [year] = #{year}
and [month] = #{month}
</select>
<delete id="deleteByYearMonth">
delete from srm_savings_report
where [year] = #{year}
and [month] = #{month}
</delete>
</mapper>

8
src/test/java/com/xujie/service/DynamicDataSourceTestService.java

@ -1,4 +1,4 @@
package com.xujie.service;
@ -12,7 +12,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
* 测试多数据源
*
*
*
*/
@Service
//@DataSource("slave1")
@ -45,7 +45,9 @@ public class DynamicDataSourceTestService {
user.setMobile("13500000002");
sysUserDao.updateById(user);
//测试事物
int i = 1/0;
}
}
}
Loading…
Cancel
Save