mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
feat: 支持快递报价 Excel 导入与标准模板下载
This commit is contained in:
+44
-1
@@ -1,7 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
@@ -9,9 +13,14 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.freight.ExpressCarrierCodes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto.ExpressQuoteDtos;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto.ExpressQuoteImportDtos;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo.ExpressQuoteImportVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo.ExpressQuoteVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport.ExpressQuoteImportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.service.ExpressQuoteService;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -23,9 +32,12 @@ import java.util.Map;
|
||||
public class ExpressQuoteController {
|
||||
|
||||
private final ExpressQuoteService expressQuoteService;
|
||||
private final ExpressQuoteImportService expressQuoteImportService;
|
||||
|
||||
public ExpressQuoteController(ExpressQuoteService expressQuoteService) {
|
||||
public ExpressQuoteController(ExpressQuoteService expressQuoteService,
|
||||
ExpressQuoteImportService expressQuoteImportService) {
|
||||
this.expressQuoteService = expressQuoteService;
|
||||
this.expressQuoteImportService = expressQuoteImportService;
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
@@ -81,6 +93,37 @@ public class ExpressQuoteController {
|
||||
return ApiResponse.success("版本已删除");
|
||||
}
|
||||
|
||||
@GetMapping("/import/template")
|
||||
@RequirePermission(value = "ec:express-quote:read", description = "下载报价导入模板", allowSuper = true)
|
||||
public void downloadImportTemplate(HttpServletResponse response) {
|
||||
byte[] data = expressQuoteImportService.templateBytes();
|
||||
String filename = URLEncoder.encode("快递报价导入模板.xlsx", StandardCharsets.UTF_8).replace("+", "%20");
|
||||
try {
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"express-quote-template.xlsx\"; filename*=UTF-8''" + filename);
|
||||
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
|
||||
response.getOutputStream().write(data);
|
||||
response.getOutputStream().flush();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("下载模板失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping(value = "/import/preview", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@RequirePermission(value = "ec:express-quote:create", description = "预览报价导入", allowSuper = true)
|
||||
public ApiResponse<ExpressQuoteImportVO> importPreview(@RequestPart("file") MultipartFile file) {
|
||||
return ApiResponse.success("解析完成", expressQuoteImportService.preview(file));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/import/commit", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@RequirePermission(value = "ec:express-quote:create", description = "确认导入报价", allowSuper = true)
|
||||
public ApiResponse<ExpressQuoteVO> importCommit(
|
||||
@RequestPart("file") MultipartFile file,
|
||||
@Valid @RequestPart("params") ExpressQuoteImportDtos.Commit params) {
|
||||
return ApiResponse.success("导入成功", expressQuoteImportService.commit(file, params));
|
||||
}
|
||||
|
||||
@GetMapping("/meta/carriers")
|
||||
@RequirePermission(value = "ec:express-quote:read", description = "承运商字典", allowSuper = true)
|
||||
public ApiResponse<List<Map<String, String>>> carriers() {
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 报价导入提交参数(与文件一并 multipart)。 */
|
||||
public final class ExpressQuoteImportDtos {
|
||||
|
||||
private ExpressQuoteImportDtos() {
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Commit {
|
||||
/** CREATE / APPEND_VERSION */
|
||||
@NotBlank(message = "导入模式不能为空")
|
||||
private String mode;
|
||||
/** APPEND_VERSION 时必填 */
|
||||
private Long quoteId;
|
||||
private String carrierCode;
|
||||
private String code;
|
||||
private String name;
|
||||
private LocalDate effectiveFrom;
|
||||
private String weightRound;
|
||||
private Integer useVolumetric;
|
||||
private Integer volumeDivisor;
|
||||
private String remark;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** 快递报价导入预览。 */
|
||||
@Data
|
||||
public class ExpressQuoteImportVO {
|
||||
|
||||
/** STANDARD / CARRIER_MATRIX */
|
||||
private String format;
|
||||
private boolean success;
|
||||
private String carrierCode;
|
||||
private String code;
|
||||
private String name;
|
||||
private LocalDate effectiveFrom;
|
||||
private String weightRound;
|
||||
private Integer useVolumetric;
|
||||
private Integer volumeDivisor;
|
||||
private int regionCount;
|
||||
private int destinationCount;
|
||||
private int bandCount;
|
||||
private List<String> warnings = new ArrayList<>();
|
||||
private List<String> errors = new ArrayList<>();
|
||||
private List<RegionPreview> regions = new ArrayList<>();
|
||||
|
||||
@Data
|
||||
public static class RegionPreview {
|
||||
private String regionName;
|
||||
private String zoneLabel;
|
||||
private List<String> destinations;
|
||||
private int bandCount;
|
||||
private List<BandPreview> bands;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BandPreview {
|
||||
private Integer weightFromG;
|
||||
private Integer weightToG;
|
||||
private String priceMode;
|
||||
private BigDecimal flatAmount;
|
||||
private Integer firstWeightG;
|
||||
private BigDecimal firstAmount;
|
||||
private BigDecimal continuePerKg;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** 读取标准模板 Meta 页(key-value)。 */
|
||||
public final class ExpressQuoteImportMetaReader {
|
||||
|
||||
private ExpressQuoteImportMetaReader() {
|
||||
}
|
||||
|
||||
public static void apply(Workbook wb, ExpressQuoteImportModels.Draft draft) {
|
||||
Sheet meta = wb.getSheet("Meta");
|
||||
if (meta == null) {
|
||||
meta = wb.getSheet("meta");
|
||||
}
|
||||
if (meta == null) {
|
||||
return;
|
||||
}
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for (int r = 0; r <= meta.getLastRowNum(); r++) {
|
||||
Row row = meta.getRow(r);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
String k = ExpressQuoteMatrixSheetParser.cellText(row, 0);
|
||||
String v = ExpressQuoteMatrixSheetParser.cellText(row, 1);
|
||||
if (StringUtils.hasText(k) && StringUtils.hasText(v)) {
|
||||
map.put(k.trim().toLowerCase(Locale.ROOT), v.trim());
|
||||
}
|
||||
}
|
||||
draft.setFormat("STANDARD");
|
||||
if (map.containsKey("carriercode")) {
|
||||
draft.setCarrierCode(map.get("carriercode"));
|
||||
}
|
||||
if (map.containsKey("code")) {
|
||||
draft.setCode(map.get("code"));
|
||||
}
|
||||
if (map.containsKey("name")) {
|
||||
draft.setName(map.get("name"));
|
||||
}
|
||||
if (map.containsKey("effectivefrom")) {
|
||||
try {
|
||||
draft.setEffectiveFrom(LocalDate.parse(map.get("effectivefrom")));
|
||||
} catch (DateTimeParseException e) {
|
||||
draft.getErrors().add("Meta.effectiveFrom 日期格式应为 yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
if (map.containsKey("weightround")) {
|
||||
draft.setWeightRound(map.get("weightround").toUpperCase(Locale.ROOT));
|
||||
}
|
||||
if (map.containsKey("usevolumetric")) {
|
||||
draft.setUseVolumetric("1".equals(map.get("usevolumetric")) ? 1 : 0);
|
||||
}
|
||||
if (map.containsKey("volumedivisor")) {
|
||||
try {
|
||||
draft.setVolumeDivisor(Integer.parseInt(map.get("volumedivisor")));
|
||||
} catch (NumberFormatException e) {
|
||||
draft.getErrors().add("Meta.volumeDivisor 须为整数");
|
||||
}
|
||||
}
|
||||
if (map.containsKey("remark")) {
|
||||
draft.setRemark(map.get("remark"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** 报价表格导入中间模型(解析 → 合并 → 落库)。 */
|
||||
public final class ExpressQuoteImportModels {
|
||||
|
||||
private ExpressQuoteImportModels() {
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Draft {
|
||||
/** STANDARD / CARRIER_MATRIX */
|
||||
private String format;
|
||||
private String carrierCode;
|
||||
private String code;
|
||||
private String name;
|
||||
private LocalDate effectiveFrom;
|
||||
private String weightRound = "NONE";
|
||||
private Integer useVolumetric = 0;
|
||||
private Integer volumeDivisor = 6000;
|
||||
private String remark;
|
||||
private List<RegionDraft> regions = new ArrayList<>();
|
||||
private List<String> warnings = new ArrayList<>();
|
||||
private List<String> errors = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class RegionDraft {
|
||||
private String regionName;
|
||||
private String zoneLabel;
|
||||
private List<String> destinations = new ArrayList<>();
|
||||
private Integer isDefault = 0;
|
||||
private List<BandDraft> bands = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BandDraft {
|
||||
private Integer weightFromG;
|
||||
private Integer weightToG;
|
||||
private String priceMode;
|
||||
private BigDecimal flatAmount;
|
||||
private Integer firstWeightG;
|
||||
private BigDecimal firstAmount;
|
||||
private BigDecimal continuePerKg;
|
||||
}
|
||||
|
||||
/** 矩阵列定义。 */
|
||||
@Data
|
||||
public static class ColumnDef {
|
||||
private int colIndex;
|
||||
private int weightFromG;
|
||||
private Integer weightToG;
|
||||
/** FLAT_TICKET / FIRST_PLUS_KG;空则按单元格推断 */
|
||||
private String defaultPriceMode;
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.freight.ExpressCarrierCodes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto.ExpressQuoteDtos;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto.ExpressQuoteImportDtos;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuotePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo.ExpressQuoteImportVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo.ExpressQuoteVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.service.ExpressQuoteService;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 报价表格导入:解析(标准 Meta+矩阵 / 承运商多段矩阵)→ 合并 → 预览 / 落库。
|
||||
*/
|
||||
@Service
|
||||
public class ExpressQuoteImportService {
|
||||
|
||||
private final ExpressQuoteService expressQuoteService;
|
||||
|
||||
public ExpressQuoteImportService(ExpressQuoteService expressQuoteService) {
|
||||
this.expressQuoteService = expressQuoteService;
|
||||
}
|
||||
|
||||
public byte[] templateBytes() {
|
||||
return ExpressQuoteTemplateWriter.write();
|
||||
}
|
||||
|
||||
public ExpressQuoteImportVO preview(MultipartFile file) {
|
||||
ExpressQuoteImportModels.Draft draft = parseFile(file);
|
||||
return toPreview(draft);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ExpressQuoteVO commit(MultipartFile file, ExpressQuoteImportDtos.Commit params) {
|
||||
ExpressQuoteImportModels.Draft draft = parseFile(file);
|
||||
applyOverrides(draft, params);
|
||||
assertDraftReady(draft);
|
||||
String mode = params.getMode().trim().toUpperCase();
|
||||
if ("CREATE".equals(mode)) {
|
||||
return expressQuoteService.create(toCreateDto(draft));
|
||||
}
|
||||
if ("APPEND_VERSION".equals(mode)) {
|
||||
if (params.getQuoteId() == null) {
|
||||
throw new BusinessException("追加版本须指定 quoteId");
|
||||
}
|
||||
expressQuoteService.requireCompanyQuote(params.getQuoteId());
|
||||
expressQuoteService.upsertVersion(params.getQuoteId(), toVersionDto(draft));
|
||||
return expressQuoteService.detail(params.getQuoteId());
|
||||
}
|
||||
throw new BusinessException("不支持的导入模式: " + params.getMode());
|
||||
}
|
||||
|
||||
private ExpressQuoteImportModels.Draft parseFile(MultipartFile file) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new BusinessException("请上传 Excel 文件");
|
||||
}
|
||||
String name = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
|
||||
if (!name.toLowerCase().endsWith(".xlsx") && !name.toLowerCase().endsWith(".xls")) {
|
||||
throw new BusinessException("仅支持 .xlsx / .xls");
|
||||
}
|
||||
try (InputStream in = file.getInputStream(); Workbook wb = WorkbookFactory.create(in)) {
|
||||
ExpressQuoteImportModels.Draft draft = new ExpressQuoteImportModels.Draft();
|
||||
ExpressQuoteImportMetaReader.apply(wb, draft);
|
||||
Sheet quoteSheet = wb.getSheet("报价");
|
||||
if (quoteSheet == null) {
|
||||
quoteSheet = wb.getSheetAt(0);
|
||||
}
|
||||
if (!StringUtils.hasText(draft.getFormat())) {
|
||||
draft.setFormat("CARRIER_MATRIX");
|
||||
}
|
||||
List<ExpressQuoteImportModels.RegionDraft> raw =
|
||||
ExpressQuoteMatrixSheetParser.parse(quoteSheet, draft.getErrors());
|
||||
if (raw.isEmpty() && draft.getErrors().isEmpty()) {
|
||||
draft.getErrors().add("未解析到任何目的地报价行");
|
||||
}
|
||||
List<ExpressQuoteImportModels.RegionDraft> merged = ExpressQuoteRegionMerger.merge(raw);
|
||||
draft.setRegions(merged);
|
||||
int before = raw.size();
|
||||
int after = merged.size();
|
||||
if (before > after) {
|
||||
draft.getWarnings().add("已按价区+重量带合并分区:" + before + " 行 → " + after + " 个分区");
|
||||
}
|
||||
return draft;
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析 Excel 失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void applyOverrides(ExpressQuoteImportModels.Draft draft, ExpressQuoteImportDtos.Commit params) {
|
||||
if (params == null) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.hasText(params.getCarrierCode())) {
|
||||
draft.setCarrierCode(params.getCarrierCode());
|
||||
}
|
||||
if (StringUtils.hasText(params.getCode())) {
|
||||
draft.setCode(params.getCode());
|
||||
}
|
||||
if (StringUtils.hasText(params.getName())) {
|
||||
draft.setName(params.getName());
|
||||
}
|
||||
if (params.getEffectiveFrom() != null) {
|
||||
draft.setEffectiveFrom(params.getEffectiveFrom());
|
||||
}
|
||||
if (StringUtils.hasText(params.getWeightRound())) {
|
||||
draft.setWeightRound(params.getWeightRound());
|
||||
}
|
||||
if (params.getUseVolumetric() != null) {
|
||||
draft.setUseVolumetric(params.getUseVolumetric());
|
||||
}
|
||||
if (params.getVolumeDivisor() != null) {
|
||||
draft.setVolumeDivisor(params.getVolumeDivisor());
|
||||
}
|
||||
if (params.getRemark() != null) {
|
||||
draft.setRemark(params.getRemark());
|
||||
}
|
||||
}
|
||||
|
||||
private void assertDraftReady(ExpressQuoteImportModels.Draft draft) {
|
||||
if (draft.getErrors() != null && !draft.getErrors().isEmpty()) {
|
||||
throw new BusinessException("导入失败:\n" + String.join("\n", draft.getErrors()));
|
||||
}
|
||||
if (draft.getRegions() == null || draft.getRegions().isEmpty()) {
|
||||
throw new BusinessException("没有可导入的分区");
|
||||
}
|
||||
if (!StringUtils.hasText(draft.getCarrierCode())) {
|
||||
throw new BusinessException("请填写承运商 carrierCode");
|
||||
}
|
||||
if (!StringUtils.hasText(draft.getCode())) {
|
||||
throw new BusinessException("请填写报价编码 code");
|
||||
}
|
||||
if (!StringUtils.hasText(draft.getName())) {
|
||||
throw new BusinessException("请填写报价名称 name");
|
||||
}
|
||||
if (draft.getEffectiveFrom() == null) {
|
||||
draft.setEffectiveFrom(LocalDate.now());
|
||||
}
|
||||
}
|
||||
|
||||
private ExpressQuoteDtos.Create toCreateDto(ExpressQuoteImportModels.Draft draft) {
|
||||
ExpressQuoteDtos.Create create = new ExpressQuoteDtos.Create();
|
||||
create.setCode(draft.getCode().trim());
|
||||
create.setName(draft.getName().trim());
|
||||
create.setCarrierCode(ExpressCarrierCodes.normalizeCode(draft.getCarrierCode()));
|
||||
create.setBillingMode(ExpressQuotePO.MODE_REGION_WEIGHT);
|
||||
create.setStatus(1);
|
||||
create.setRemark(draft.getRemark());
|
||||
create.setInitialVersion(toVersionDto(draft));
|
||||
return create;
|
||||
}
|
||||
|
||||
private ExpressQuoteDtos.VersionUpsert toVersionDto(ExpressQuoteImportModels.Draft draft) {
|
||||
ExpressQuoteDtos.VersionUpsert v = new ExpressQuoteDtos.VersionUpsert();
|
||||
v.setEffectiveFrom(draft.getEffectiveFrom());
|
||||
v.setWeightRound(draft.getWeightRound());
|
||||
v.setUseVolumetric(draft.getUseVolumetric());
|
||||
v.setVolumeDivisor(draft.getVolumeDivisor());
|
||||
v.setRemark(draft.getRemark());
|
||||
v.setRegions(draft.getRegions().stream().map(r -> {
|
||||
ExpressQuoteDtos.RegionUpsert ru = new ExpressQuoteDtos.RegionUpsert();
|
||||
ru.setRegionName(r.getRegionName());
|
||||
ru.setZoneLabel(r.getZoneLabel());
|
||||
ru.setProvinces(r.getDestinations());
|
||||
ru.setIsDefault(r.getIsDefault());
|
||||
ru.setBands(r.getBands().stream().map(b -> {
|
||||
ExpressQuoteDtos.BandUpsert bu = new ExpressQuoteDtos.BandUpsert();
|
||||
BeanCopyUtils.copyProperties(b, bu);
|
||||
return bu;
|
||||
}).toList());
|
||||
return ru;
|
||||
}).toList());
|
||||
return v;
|
||||
}
|
||||
|
||||
private ExpressQuoteImportVO toPreview(ExpressQuoteImportModels.Draft draft) {
|
||||
ExpressQuoteImportVO vo = new ExpressQuoteImportVO();
|
||||
vo.setFormat(draft.getFormat());
|
||||
vo.setCarrierCode(draft.getCarrierCode());
|
||||
vo.setCode(draft.getCode());
|
||||
vo.setName(draft.getName());
|
||||
vo.setEffectiveFrom(draft.getEffectiveFrom());
|
||||
vo.setWeightRound(draft.getWeightRound());
|
||||
vo.setUseVolumetric(draft.getUseVolumetric());
|
||||
vo.setVolumeDivisor(draft.getVolumeDivisor());
|
||||
vo.setWarnings(draft.getWarnings());
|
||||
vo.setErrors(draft.getErrors());
|
||||
vo.setSuccess(draft.getErrors() == null || draft.getErrors().isEmpty());
|
||||
int dest = 0;
|
||||
int bands = 0;
|
||||
for (ExpressQuoteImportModels.RegionDraft r : draft.getRegions()) {
|
||||
ExpressQuoteImportVO.RegionPreview rp = new ExpressQuoteImportVO.RegionPreview();
|
||||
rp.setRegionName(r.getRegionName());
|
||||
rp.setZoneLabel(r.getZoneLabel());
|
||||
rp.setDestinations(r.getDestinations());
|
||||
rp.setBandCount(r.getBands().size());
|
||||
rp.setBands(r.getBands().stream().map(b -> {
|
||||
ExpressQuoteImportVO.BandPreview bp = new ExpressQuoteImportVO.BandPreview();
|
||||
BeanCopyUtils.copyProperties(b, bp);
|
||||
return bp;
|
||||
}).toList());
|
||||
vo.getRegions().add(rp);
|
||||
dest += r.getDestinations().size();
|
||||
bands += r.getBands().size();
|
||||
}
|
||||
vo.setRegionCount(draft.getRegions().size());
|
||||
vo.setDestinationCount(dest);
|
||||
vo.setBandCount(bands);
|
||||
if (vo.isSuccess() && draft.getRegions().isEmpty()) {
|
||||
vo.setSuccess(false);
|
||||
vo.getErrors().add("未解析到任何分区");
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.DataFormatter;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 解析承运商矩阵 / 标准模板「报价」页:支持同 Sheet 多段表头。
|
||||
* 空单元格=该重量带跳过;非空且不可解析=记入 errors(调用方整单失败)。
|
||||
*/
|
||||
public final class ExpressQuoteMatrixSheetParser {
|
||||
|
||||
private static final DataFormatter FMT = new DataFormatter();
|
||||
|
||||
private ExpressQuoteMatrixSheetParser() {
|
||||
}
|
||||
|
||||
public static List<ExpressQuoteImportModels.RegionDraft> parse(Sheet sheet, List<String> errors) {
|
||||
List<ExpressQuoteImportModels.RegionDraft> rows = new ArrayList<>();
|
||||
if (sheet == null) {
|
||||
errors.add("缺少报价工作表");
|
||||
return rows;
|
||||
}
|
||||
int last = sheet.getLastRowNum();
|
||||
List<ExpressQuoteImportModels.ColumnDef> columns = null;
|
||||
for (int r = 0; r <= last; r++) {
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
String c0 = cellText(row, 0);
|
||||
String c1 = cellText(row, 1);
|
||||
|
||||
// 偏远区域行:内嵌新重量表头
|
||||
if (isSectionMarker(c0) && hasWeightHeaders(row, 2)) {
|
||||
columns = readColumnsFromWeightRow(row, 2, null);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 标准表头行:目的省 | 重量/KG | ranges...
|
||||
if (isDestinationHeader(c0)) {
|
||||
if (hasWeightHeaders(row, 2)) {
|
||||
columns = readColumnsFromWeightRow(row, 2, null);
|
||||
// 下一行可能是模式行
|
||||
Row next = sheet.getRow(r + 1);
|
||||
if (next != null && isModeRow(next, columns)) {
|
||||
applyModes(next, columns);
|
||||
r++;
|
||||
}
|
||||
} else {
|
||||
// 目的省行仅有模式标签,重量在上一偏远行已设
|
||||
if (columns != null) {
|
||||
applyModes(row, columns);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 独立模式行(上一行已设列)
|
||||
if (columns != null && isModeRow(row, columns) && !looksLikeDestination(c0)) {
|
||||
applyModes(row, columns);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (columns == null || columns.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (!looksLikeDestination(c0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ExpressQuoteImportModels.RegionDraft region = parseDataRow(row, columns, errors, r + 1);
|
||||
if (region != null) {
|
||||
rows.add(region);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static ExpressQuoteImportModels.RegionDraft parseDataRow(
|
||||
Row row, List<ExpressQuoteImportModels.ColumnDef> columns, List<String> errors, int excelRow) {
|
||||
String destRaw = cellText(row, 0);
|
||||
if (!StringUtils.hasText(destRaw)) {
|
||||
return null;
|
||||
}
|
||||
String zone = cellText(row, 1);
|
||||
String dest = normalizeDestination(destRaw);
|
||||
ExpressQuoteImportModels.RegionDraft region = new ExpressQuoteImportModels.RegionDraft();
|
||||
region.setZoneLabel(StringUtils.hasText(zone) ? zone.trim() : null);
|
||||
region.setRegionName(StringUtils.hasText(zone) ? zone.trim() : dest);
|
||||
region.getDestinations().add(dest);
|
||||
|
||||
List<ExpressQuoteImportModels.BandDraft> bands = new ArrayList<>();
|
||||
for (ExpressQuoteImportModels.ColumnDef col : columns) {
|
||||
Object raw = cellValue(row, col.getColIndex());
|
||||
if (raw == null || (raw instanceof String s && !StringUtils.hasText(s))) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
Optional<ExpressQuoteImportModels.BandDraft> band = PriceCellParser.parse(
|
||||
raw, col.getDefaultPriceMode(), col.getWeightFromG(), col.getWeightToG());
|
||||
band.ifPresent(bands::add);
|
||||
} catch (PriceCellParser.UnparseablePriceException ex) {
|
||||
errors.add("第" + excelRow + "行「" + destRaw + "」列" + (col.getColIndex() + 1)
|
||||
+ "无法解析: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
if (bands.isEmpty() && errors.stream().noneMatch(e -> e.contains("第" + excelRow + "行"))) {
|
||||
errors.add("第" + excelRow + "行「" + destRaw + "」无任何有效重量带价格");
|
||||
return null;
|
||||
}
|
||||
region.setBands(bands);
|
||||
return bands.isEmpty() ? null : region;
|
||||
}
|
||||
|
||||
private static String normalizeDestination(String raw) {
|
||||
String t = raw.trim();
|
||||
String n = BiRegionNormalizer.normalize(t);
|
||||
return BiRegionNormalizer.isUnknown(n) ? t : n;
|
||||
}
|
||||
|
||||
private static List<ExpressQuoteImportModels.ColumnDef> readColumnsFromWeightRow(
|
||||
Row row, int startCol, List<String> modeHints) {
|
||||
List<ExpressQuoteImportModels.ColumnDef> cols = new ArrayList<>();
|
||||
short last = row.getLastCellNum();
|
||||
for (int c = startCol; c < last; c++) {
|
||||
String text = cellText(row, c);
|
||||
Optional<int[]> range = WeightBandHeaderParser.parseRangeGrams(text);
|
||||
if (range.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
ExpressQuoteImportModels.ColumnDef def = new ExpressQuoteImportModels.ColumnDef();
|
||||
def.setColIndex(c);
|
||||
def.setWeightFromG(range.get()[0]);
|
||||
int to = range.get()[1];
|
||||
def.setWeightToG(to < 0 ? null : to);
|
||||
if (modeHints != null && c < modeHints.size()) {
|
||||
def.setDefaultPriceMode(modeHints.get(c));
|
||||
}
|
||||
cols.add(def);
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
private static void applyModes(Row row, List<ExpressQuoteImportModels.ColumnDef> columns) {
|
||||
for (ExpressQuoteImportModels.ColumnDef col : columns) {
|
||||
String mode = PriceCellParser.detectModeLabel(cellText(row, col.getColIndex()));
|
||||
if (mode != null) {
|
||||
col.setDefaultPriceMode(mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasWeightHeaders(Row row, int startCol) {
|
||||
short last = row.getLastCellNum();
|
||||
for (int c = startCol; c < last; c++) {
|
||||
if (WeightBandHeaderParser.looksLikeWeightHeader(cellText(row, c))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isModeRow(Row row, List<ExpressQuoteImportModels.ColumnDef> columns) {
|
||||
int hit = 0;
|
||||
for (ExpressQuoteImportModels.ColumnDef col : columns) {
|
||||
if (PriceCellParser.detectModeLabel(cellText(row, col.getColIndex())) != null) {
|
||||
hit++;
|
||||
}
|
||||
}
|
||||
return hit >= Math.max(1, columns.size() / 3);
|
||||
}
|
||||
|
||||
private static boolean isDestinationHeader(String c0) {
|
||||
return StringUtils.hasText(c0) && (c0.contains("目的") || c0.contains("省份") || "目的省".equals(c0.trim()));
|
||||
}
|
||||
|
||||
private static boolean isSectionMarker(String c0) {
|
||||
return StringUtils.hasText(c0) && (c0.contains("偏远") || c0.contains("区域说明"));
|
||||
}
|
||||
|
||||
private static boolean looksLikeDestination(String c0) {
|
||||
if (!StringUtils.hasText(c0)) {
|
||||
return false;
|
||||
}
|
||||
String t = c0.trim();
|
||||
if (t.contains("快递报价") || isDestinationHeader(t) || isSectionMarker(t)) {
|
||||
return false;
|
||||
}
|
||||
if (WeightBandHeaderParser.looksLikeWeightHeader(t)) {
|
||||
return false;
|
||||
}
|
||||
if (PriceCellParser.detectModeLabel(t) != null) {
|
||||
return false;
|
||||
}
|
||||
return t.length() <= 40;
|
||||
}
|
||||
|
||||
static String cellText(Row row, int col) {
|
||||
Cell cell = row.getCell(col);
|
||||
if (cell == null) {
|
||||
return null;
|
||||
}
|
||||
return FMT.formatCellValue(cell).trim();
|
||||
}
|
||||
|
||||
static Object cellValue(Row row, int col) {
|
||||
Cell cell = row.getCell(col);
|
||||
if (cell == null) {
|
||||
return null;
|
||||
}
|
||||
CellType type = cell.getCellType();
|
||||
if (type == CellType.FORMULA) {
|
||||
type = cell.getCachedFormulaResultType();
|
||||
}
|
||||
return switch (type) {
|
||||
case NUMERIC -> BigDecimal.valueOf(cell.getNumericCellValue());
|
||||
case STRING -> {
|
||||
String s = cell.getStringCellValue();
|
||||
yield StringUtils.hasText(s) ? s.trim() : null;
|
||||
}
|
||||
case BOOLEAN -> cell.getBooleanCellValue();
|
||||
default -> {
|
||||
String t = FMT.formatCellValue(cell);
|
||||
yield StringUtils.hasText(t) ? t.trim() : null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** 相同价区标签且重量带完全一致 → 合并为一个分区(目的地并集)。 */
|
||||
public final class ExpressQuoteRegionMerger {
|
||||
|
||||
private ExpressQuoteRegionMerger() {
|
||||
}
|
||||
|
||||
public static List<ExpressQuoteImportModels.RegionDraft> merge(
|
||||
List<ExpressQuoteImportModels.RegionDraft> rows) {
|
||||
Map<String, ExpressQuoteImportModels.RegionDraft> merged = new LinkedHashMap<>();
|
||||
for (ExpressQuoteImportModels.RegionDraft row : rows) {
|
||||
String key = fingerprint(row);
|
||||
ExpressQuoteImportModels.RegionDraft exist = merged.get(key);
|
||||
if (exist == null) {
|
||||
ExpressQuoteImportModels.RegionDraft copy = copyRegion(row);
|
||||
merged.put(key, copy);
|
||||
} else {
|
||||
Set<String> dest = new LinkedHashSet<>(exist.getDestinations());
|
||||
dest.addAll(row.getDestinations());
|
||||
exist.setDestinations(new ArrayList<>(dest));
|
||||
if (!StringUtils.hasText(exist.getZoneLabel()) && StringUtils.hasText(row.getZoneLabel())) {
|
||||
exist.setZoneLabel(row.getZoneLabel());
|
||||
}
|
||||
}
|
||||
}
|
||||
List<ExpressQuoteImportModels.RegionDraft> result = new ArrayList<>(merged.values());
|
||||
int i = 1;
|
||||
for (ExpressQuoteImportModels.RegionDraft r : result) {
|
||||
if (!StringUtils.hasText(r.getRegionName())) {
|
||||
r.setRegionName(StringUtils.hasText(r.getZoneLabel())
|
||||
? r.getZoneLabel()
|
||||
: "分区" + i);
|
||||
}
|
||||
// 合并后名称:价区优先,否则取首个目的地概括
|
||||
if (StringUtils.hasText(r.getZoneLabel())) {
|
||||
r.setRegionName(r.getZoneLabel());
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String fingerprint(ExpressQuoteImportModels.RegionDraft r) {
|
||||
String zone = r.getZoneLabel() != null ? r.getZoneLabel().trim() : "";
|
||||
String bands = r.getBands().stream()
|
||||
.sorted(Comparator
|
||||
.comparing((ExpressQuoteImportModels.BandDraft b) -> b.getWeightFromG() != null ? b.getWeightFromG() : 0)
|
||||
.thenComparing(b -> b.getWeightToG() != null ? b.getWeightToG() : Integer.MAX_VALUE))
|
||||
.map(ExpressQuoteRegionMerger::bandKey)
|
||||
.collect(Collectors.joining("|"));
|
||||
return zone + "#" + bands;
|
||||
}
|
||||
|
||||
private static String bandKey(ExpressQuoteImportModels.BandDraft b) {
|
||||
return b.getWeightFromG() + "-" + b.getWeightToG() + ":" + b.getPriceMode()
|
||||
+ ":" + dec(b.getFlatAmount())
|
||||
+ ":" + b.getFirstWeightG()
|
||||
+ ":" + dec(b.getFirstAmount())
|
||||
+ ":" + dec(b.getContinuePerKg());
|
||||
}
|
||||
|
||||
private static String dec(BigDecimal v) {
|
||||
return v == null ? "" : v.stripTrailingZeros().toPlainString();
|
||||
}
|
||||
|
||||
private static ExpressQuoteImportModels.RegionDraft copyRegion(ExpressQuoteImportModels.RegionDraft src) {
|
||||
ExpressQuoteImportModels.RegionDraft r = new ExpressQuoteImportModels.RegionDraft();
|
||||
r.setRegionName(src.getRegionName());
|
||||
r.setZoneLabel(src.getZoneLabel());
|
||||
r.setIsDefault(src.getIsDefault());
|
||||
r.setDestinations(new ArrayList<>(src.getDestinations()));
|
||||
List<ExpressQuoteImportModels.BandDraft> bands = new ArrayList<>();
|
||||
for (ExpressQuoteImportModels.BandDraft b : src.getBands()) {
|
||||
ExpressQuoteImportModels.BandDraft c = new ExpressQuoteImportModels.BandDraft();
|
||||
c.setWeightFromG(b.getWeightFromG());
|
||||
c.setWeightToG(b.getWeightToG());
|
||||
c.setPriceMode(b.getPriceMode());
|
||||
c.setFlatAmount(b.getFlatAmount());
|
||||
c.setFirstWeightG(b.getFirstWeightG());
|
||||
c.setFirstAmount(b.getFirstAmount());
|
||||
c.setContinuePerKg(b.getContinuePerKg());
|
||||
bands.add(c);
|
||||
}
|
||||
r.setBands(bands);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 生成标准报价导入模板(Meta + 报价矩阵,单段表头,可直接填数)。
|
||||
*/
|
||||
public final class ExpressQuoteTemplateWriter {
|
||||
|
||||
private ExpressQuoteTemplateWriter() {
|
||||
}
|
||||
|
||||
public static byte[] write() {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
writeMeta(wb.createSheet("Meta"));
|
||||
writeQuote(wb.createSheet("报价"));
|
||||
writeReadme(wb.createSheet("说明"));
|
||||
wb.write(out);
|
||||
return out.toByteArray();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("生成报价模板失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeMeta(Sheet sheet) {
|
||||
kv(sheet, 0, "carrierCode", "ZTO");
|
||||
kv(sheet, 1, "code", "ZTO-DEMO");
|
||||
kv(sheet, 2, "name", "中通示范报价");
|
||||
kv(sheet, 3, "effectiveFrom", LocalDate.now().toString());
|
||||
kv(sheet, 4, "weightRound", "NONE");
|
||||
kv(sheet, 5, "useVolumetric", "0");
|
||||
kv(sheet, 6, "volumeDivisor", "6000");
|
||||
kv(sheet, 7, "remark", "");
|
||||
sheet.setColumnWidth(0, 4000);
|
||||
sheet.setColumnWidth(1, 6000);
|
||||
}
|
||||
|
||||
private static void kv(Sheet sheet, int row, String k, String v) {
|
||||
Row r = sheet.createRow(row);
|
||||
r.createCell(0).setCellValue(k);
|
||||
r.createCell(1).setCellValue(v);
|
||||
}
|
||||
|
||||
private static void writeQuote(Sheet sheet) {
|
||||
Row title = sheet.createRow(0);
|
||||
title.createCell(0).setCellValue("快递报价表(标准模板)");
|
||||
|
||||
String[] weights = {
|
||||
"0-0.5kg", "0.51-1KG", "1.01-2KG", "2.01-3KG",
|
||||
"3.01-5.5KG", "5.51-9KG", "9.01-10KG", "18.01-20KG"
|
||||
};
|
||||
Row header = sheet.createRow(1);
|
||||
header.createCell(0).setCellValue("目的省");
|
||||
header.createCell(1).setCellValue("重量/KG");
|
||||
for (int i = 0; i < weights.length; i++) {
|
||||
header.createCell(2 + i).setCellValue(weights[i]);
|
||||
}
|
||||
|
||||
Row mode = sheet.createRow(2);
|
||||
mode.createCell(0).setCellValue("");
|
||||
mode.createCell(1).setCellValue("");
|
||||
for (int i = 0; i < weights.length - 1; i++) {
|
||||
mode.createCell(2 + i).setCellValue("元/票");
|
||||
}
|
||||
mode.createCell(2 + weights.length - 1).setCellValue("首重0kg+续重/kg");
|
||||
|
||||
Object[][] samples = {
|
||||
{"浙江省", "二类", 1.4, 1.6, 1.9, 2.3, 3.6, 5.5, 6, "2+0.7元/kg"},
|
||||
{"北京市", "一类", 2.4, 2.6, 2.7, 3, 4.6, 6.5, 7, "3+0.7元/kg"},
|
||||
{"深圳市", "一类", 2.4, 2.6, 2.7, 3, 4.6, 6.5, 7, "3+0.7元/kg"},
|
||||
};
|
||||
for (int i = 0; i < samples.length; i++) {
|
||||
Row row = sheet.createRow(3 + i);
|
||||
Object[] s = samples[i];
|
||||
row.createCell(0).setCellValue(String.valueOf(s[0]));
|
||||
row.createCell(1).setCellValue(String.valueOf(s[1]));
|
||||
for (int c = 2; c < s.length; c++) {
|
||||
Object v = s[c];
|
||||
if (v instanceof Number n) {
|
||||
row.createCell(c).setCellValue(n.doubleValue());
|
||||
} else {
|
||||
row.createCell(c).setCellValue(String.valueOf(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < 10; i++) {
|
||||
sheet.setColumnWidth(i, 3500);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeReadme(Sheet sheet) {
|
||||
String[] lines = {
|
||||
"1. 填写 Meta 页:carrierCode/code/name/effectiveFrom 必填。",
|
||||
"2. 报价页为矩阵:目的省 + 价区 + 各重量列;同价区且价格相同会自动合并。",
|
||||
"3. 重量表头按字面转克,如 0.51-1KG → 510–1000g。",
|
||||
"4. 单元格支持数字(元/票)或「2+0.7元/kg」(首重+续重);空单元格表示该带无报价。",
|
||||
"5. 含「发/转单」等业务分支文案无法解析,将导致整单失败。",
|
||||
"6. 也可直接上传承运商多段矩阵表(无 Meta 时在提交时补全编码/名称/承运商/生效日)。",
|
||||
};
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
sheet.createRow(i).createCell(0).setCellValue(lines[i]);
|
||||
}
|
||||
sheet.setColumnWidth(0, 20000);
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteBandPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 解析价格单元格:数值 /「4.5元/票」/「2+0.7元/kg」。
|
||||
* 含业务分支文案(发极兔、转单等)视为不可解析。
|
||||
*/
|
||||
public final class PriceCellParser {
|
||||
|
||||
private static final Pattern FLAT = Pattern.compile(
|
||||
"^\\s*(\\d+(?:\\.\\d+)?)\\s*(?:元)?\\s*/?\\s*票?\\s*$");
|
||||
private static final Pattern FIRST_PLUS = Pattern.compile(
|
||||
"^\\s*(\\d+(?:\\.\\d+)?)\\s*\\+\\s*(\\d+(?:\\.\\d+)?)\\s*(?:元)?\\s*/?\\s*kg\\s*$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern REJECT = Pattern.compile("发|转单|其他快递|极兔|备注");
|
||||
|
||||
private PriceCellParser() {
|
||||
}
|
||||
|
||||
public static Optional<ExpressQuoteImportModels.BandDraft> parse(
|
||||
Object cellValue, String defaultMode, int weightFromG, Integer weightToG) {
|
||||
if (cellValue == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (cellValue instanceof Number n) {
|
||||
return Optional.of(buildNumeric(n, defaultMode, weightFromG, weightToG));
|
||||
}
|
||||
String text = String.valueOf(cellValue).trim();
|
||||
if (!StringUtils.hasText(text) || "-".equals(text) || "—".equals(text)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (REJECT.matcher(text).find()) {
|
||||
throw new UnparseablePriceException(text);
|
||||
}
|
||||
Matcher fp = FIRST_PLUS.matcher(text.replace(" ", ""));
|
||||
if (fp.matches()) {
|
||||
ExpressQuoteImportModels.BandDraft b = base(weightFromG, weightToG);
|
||||
b.setPriceMode(ExpressQuoteBandPO.MODE_FIRST_PLUS_KG);
|
||||
b.setFirstWeightG(0);
|
||||
b.setFirstAmount(new BigDecimal(fp.group(1)));
|
||||
b.setContinuePerKg(new BigDecimal(fp.group(2)));
|
||||
return Optional.of(b);
|
||||
}
|
||||
Matcher flat = FLAT.matcher(text.replace("元/票", "").replace("元", "").trim());
|
||||
// 再试:完整「4.5元/票」
|
||||
Matcher flat2 = Pattern.compile("^\\s*(\\d+(?:\\.\\d+)?)\\s*元\\s*/\\s*票\\s*$").matcher(text);
|
||||
if (flat2.matches()) {
|
||||
ExpressQuoteImportModels.BandDraft b = base(weightFromG, weightToG);
|
||||
b.setPriceMode(ExpressQuoteBandPO.MODE_FLAT_TICKET);
|
||||
b.setFlatAmount(new BigDecimal(flat2.group(1)));
|
||||
return Optional.of(b);
|
||||
}
|
||||
if (flat.matches() && !text.contains("+")) {
|
||||
ExpressQuoteImportModels.BandDraft b = base(weightFromG, weightToG);
|
||||
String mode = StringUtils.hasText(defaultMode) ? defaultMode : ExpressQuoteBandPO.MODE_FLAT_TICKET;
|
||||
if (ExpressQuoteBandPO.MODE_FIRST_PLUS_KG.equals(mode)) {
|
||||
// 列声明为首重续重但单元格只有数字 → 不可靠,报错
|
||||
throw new UnparseablePriceException(text + "(列为首重+续重,但单元格非 a+b 格式)");
|
||||
}
|
||||
b.setPriceMode(ExpressQuoteBandPO.MODE_FLAT_TICKET);
|
||||
b.setFlatAmount(new BigDecimal(flat.group(1)));
|
||||
return Optional.of(b);
|
||||
}
|
||||
// 纯数字字符串
|
||||
try {
|
||||
BigDecimal n = new BigDecimal(text);
|
||||
return Optional.of(buildNumeric(n, defaultMode, weightFromG, weightToG));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new UnparseablePriceException(text);
|
||||
}
|
||||
}
|
||||
|
||||
private static ExpressQuoteImportModels.BandDraft buildNumeric(
|
||||
Number n, String defaultMode, int weightFromG, Integer weightToG) {
|
||||
ExpressQuoteImportModels.BandDraft b = base(weightFromG, weightToG);
|
||||
BigDecimal amount = n instanceof BigDecimal bd ? bd : BigDecimal.valueOf(n.doubleValue());
|
||||
String mode = StringUtils.hasText(defaultMode) ? defaultMode : ExpressQuoteBandPO.MODE_FLAT_TICKET;
|
||||
if (ExpressQuoteBandPO.MODE_FIRST_PLUS_KG.equals(mode)) {
|
||||
throw new UnparseablePriceException(amount + "(列为首重+续重,需 a+b元/kg)");
|
||||
}
|
||||
b.setPriceMode(ExpressQuoteBandPO.MODE_FLAT_TICKET);
|
||||
b.setFlatAmount(amount);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static ExpressQuoteImportModels.BandDraft base(int from, Integer to) {
|
||||
ExpressQuoteImportModels.BandDraft b = new ExpressQuoteImportModels.BandDraft();
|
||||
b.setWeightFromG(from);
|
||||
b.setWeightToG(to);
|
||||
return b;
|
||||
}
|
||||
|
||||
public static String detectModeLabel(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return null;
|
||||
}
|
||||
String s = raw.trim();
|
||||
if (s.contains("续重") || s.contains("首重") || s.toLowerCase().contains("/kg")) {
|
||||
return ExpressQuoteBandPO.MODE_FIRST_PLUS_KG;
|
||||
}
|
||||
if (s.contains("元/票") || s.contains("票")) {
|
||||
return ExpressQuoteBandPO.MODE_FLAT_TICKET;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 不可解析价格。 */
|
||||
public static class UnparseablePriceException extends RuntimeException {
|
||||
public UnparseablePriceException(String cell) {
|
||||
super(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 解析表头重量区间:按字面 kg→克(0.51-1KG → 510–1000g)。
|
||||
*/
|
||||
public final class WeightBandHeaderParser {
|
||||
|
||||
private static final Pattern RANGE = Pattern.compile(
|
||||
"^\\s*(\\d+(?:\\.\\d+)?)\\s*[-~~到至]\\s*(\\d+(?:\\.\\d+)?)\\s*(?:kg|KG|Kg)?\\s*$");
|
||||
private static final Pattern OPEN = Pattern.compile(
|
||||
"^\\s*(\\d+(?:\\.\\d+)?)\\s*\\+\\s*(?:kg|KG|Kg)?\\s*$");
|
||||
|
||||
private WeightBandHeaderParser() {
|
||||
}
|
||||
|
||||
public static Optional<int[]> parseRangeGrams(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String s = raw.trim()
|
||||
.replace("重量", "")
|
||||
.replace("/KG", "")
|
||||
.replace("/kg", "")
|
||||
.trim();
|
||||
Matcher m = RANGE.matcher(s);
|
||||
if (m.matches()) {
|
||||
int from = kgToGrams(m.group(1));
|
||||
int to = kgToGrams(m.group(2));
|
||||
if (from < 0 || to < from) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new int[]{from, to});
|
||||
}
|
||||
Matcher open = OPEN.matcher(s);
|
||||
if (open.matches()) {
|
||||
int from = kgToGrams(open.group(1));
|
||||
return Optional.of(new int[]{from, -1}); // -1 = 无上限
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** kg 字面转克:0.51 → 510。 */
|
||||
public static int kgToGrams(String kgText) {
|
||||
BigDecimal kg = new BigDecimal(kgText.trim());
|
||||
return kg.multiply(BigDecimal.valueOf(1000)).setScale(0, RoundingMode.HALF_UP).intValueExact();
|
||||
}
|
||||
|
||||
public static boolean looksLikeWeightHeader(String raw) {
|
||||
return parseRangeGrams(raw).isPresent();
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.warehouse.quoteimport;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** 承运商样表解析冒烟(本地 temp 文件存在时才跑)。 */
|
||||
class ExpressQuoteMatrixSheetParserTest {
|
||||
|
||||
@Test
|
||||
void parseSampleCarrierMatrix() throws Exception {
|
||||
Path path = Path.of("temp/json/快递报价单.xlsx");
|
||||
if (!Files.exists(path)) {
|
||||
return;
|
||||
}
|
||||
try (InputStream in = Files.newInputStream(path); Workbook wb = WorkbookFactory.create(in)) {
|
||||
Sheet sheet = wb.getSheetAt(0);
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<ExpressQuoteImportModels.RegionDraft> raw =
|
||||
ExpressQuoteMatrixSheetParser.parse(sheet, errors);
|
||||
List<ExpressQuoteImportModels.RegionDraft> merged = ExpressQuoteRegionMerger.merge(raw);
|
||||
assertFalse(merged.isEmpty(), "应解析到分区");
|
||||
// 样表含「发极兔/转单」等文案 → 应有错误
|
||||
assertTrue(errors.stream().anyMatch(e -> e.contains("无法解析") || e.contains("发")),
|
||||
"应对不可解析单元格报错: " + errors);
|
||||
// 0.51-1KG → 510
|
||||
boolean has510 = merged.stream()
|
||||
.flatMap(r -> r.getBands().stream())
|
||||
.anyMatch(b -> Integer.valueOf(510).equals(b.getWeightFromG()));
|
||||
assertTrue(has510, "重量带应从 0.51kg 得到 510g");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateRoundTripHasRegions() {
|
||||
byte[] bytes = ExpressQuoteTemplateWriter.write();
|
||||
assertTrue(bytes.length > 1000);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user