mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
Compare commits
3
Commits
31cd151b12
...
3f8f066a7c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f8f066a7c | ||
|
|
49bbaa7362 | ||
|
|
36884890af |
@@ -1,14 +1,16 @@
|
||||
-- ========================================
|
||||
-- 电商-仓库发货与快递报价(无进销存)
|
||||
-- ec_warehouse / ec_express_quote(+version/region/tier)
|
||||
-- ec_warehouse / ec_express_quote(+version/region/band)
|
||||
-- ec_warehouse_express_bind / ec_express_carrier_alias
|
||||
-- SKU 默认仓、体积尺寸见 ec_product_design.sql(warehouse_id / length_mm…)
|
||||
-- REGION_WEIGHT:目的分区 × 多重量带(元/票 或 首重+续重/kg),对齐承运商矩阵报价单
|
||||
-- ========================================
|
||||
|
||||
-- ----------------------------
|
||||
-- 仓库主数据(无库存)
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `ec_warehouse_express_bind`;
|
||||
DROP TABLE IF EXISTS `ec_express_quote_band`;
|
||||
DROP TABLE IF EXISTS `ec_express_quote_tier`;
|
||||
DROP TABLE IF EXISTS `ec_express_quote_region`;
|
||||
DROP TABLE IF EXISTS `ec_express_quote_version`;
|
||||
@@ -78,8 +80,9 @@ CREATE TABLE `ec_express_quote_version` (
|
||||
`unit_scope` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'FLAT:ORDER|PIECE',
|
||||
`price_per_kg` decimal(10, 4) NULL DEFAULT NULL COMMENT 'PER_KG 单价',
|
||||
`min_amount` decimal(10, 2) NULL DEFAULT NULL COMMENT 'PER_KG 最低消费',
|
||||
`volume_divisor` int UNSIGNED NULL DEFAULT 6000 COMMENT '体积重除数(长*宽*高mm / divisor = g 量级需再换算;约定:mm³/divisor→kg*1000=g)',
|
||||
`volume_divisor` int UNSIGNED NULL DEFAULT 6000 COMMENT '计泡除数(cm 公式):体积重克=ceil(长*宽*高mm / divisor),如 6000/8000',
|
||||
`use_volumetric` tinyint NOT NULL DEFAULT 0 COMMENT '是否启用体积重:0否 1是(计费重=max实重,体积重)',
|
||||
`weight_round` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'NONE' COMMENT '计费重取整:NONE/CEIL_KG',
|
||||
`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 '更新时间',
|
||||
@@ -98,9 +101,10 @@ CREATE TABLE `ec_express_quote_region` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '分区ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`version_id` bigint UNSIGNED NOT NULL COMMENT '报价版本ID',
|
||||
`region_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '分区名(如江浙沪)',
|
||||
`provinces_json` json NOT NULL COMMENT '省份全称列表 JSON,与 BiRegionNormalizer 对齐',
|
||||
`is_default` tinyint NOT NULL DEFAULT 0 COMMENT '是否默认分区(未命中省时回落)',
|
||||
`region_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '分区名(如二类/江浙沪)',
|
||||
`zone_label` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '价区标签:一类/二类…(展示用)',
|
||||
`provinces_json` json NOT NULL COMMENT '目的地列表 JSON(省全称或市名,如深圳市)',
|
||||
`is_default` tinyint NOT NULL DEFAULT 0 COMMENT '是否默认分区(未命中时回落)',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
@@ -108,26 +112,31 @@ CREATE TABLE `ec_express_quote_region` (
|
||||
INDEX `idx_ec_express_quote_region_version`(`version_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_express_quote_region_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_region_version` FOREIGN KEY (`version_id`) REFERENCES `ec_express_quote_version` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-快递报价分区';
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-快递报价目的分区';
|
||||
|
||||
CREATE TABLE `ec_express_quote_tier` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '阶梯ID',
|
||||
-- 重量带:一分区多行;FLAT_TICKET=元/票;FIRST_PLUS_KG=首重价+续重元/kg(续重按 kg 向上取整段)
|
||||
CREATE TABLE `ec_express_quote_band` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '重量带ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`version_id` bigint UNSIGNED NOT NULL COMMENT '报价版本ID',
|
||||
`region_id` bigint UNSIGNED NOT NULL COMMENT '分区ID',
|
||||
`first_weight_g` int UNSIGNED NOT NULL DEFAULT 1000 COMMENT '首重(克)',
|
||||
`first_amount` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '首重价格',
|
||||
`additional_weight_g` int UNSIGNED NOT NULL DEFAULT 1000 COMMENT '续重步进(克)',
|
||||
`additional_amount` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '续重价格',
|
||||
`weight_from_g` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '计费重下限(克,含)',
|
||||
`weight_to_g` int UNSIGNED NULL DEFAULT NULL COMMENT '计费重上限(克,含);NULL=无上限',
|
||||
`price_mode` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'FLAT_TICKET/FIRST_PLUS_KG',
|
||||
`flat_amount` decimal(10, 2) NULL DEFAULT NULL COMMENT 'FLAT_TICKET 元/票',
|
||||
`first_weight_g` int UNSIGNED NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 首重克数(可为0)',
|
||||
`first_amount` decimal(10, 2) NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 首重价',
|
||||
`continue_per_kg` decimal(10, 4) NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 续重元/kg',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '同区分带排序',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_express_quote_tier_region`(`region_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_express_quote_tier_version`(`version_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_express_quote_tier_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_tier_version` FOREIGN KEY (`version_id`) REFERENCES `ec_express_quote_version` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_tier_region` FOREIGN KEY (`region_id`) REFERENCES `ec_express_quote_region` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-快递报价首重续重';
|
||||
INDEX `idx_ec_express_quote_band_region`(`region_id` ASC, `weight_from_g` ASC) USING BTREE,
|
||||
INDEX `idx_ec_express_quote_band_version`(`version_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_version` FOREIGN KEY (`version_id`) REFERENCES `ec_express_quote_version` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_region` FOREIGN KEY (`region_id`) REFERENCES `ec_express_quote_region` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-快递报价重量带';
|
||||
|
||||
-- ----------------------------
|
||||
-- 仓 ↔ 报价多对多绑定
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
-- 报价:单区单条首重续重 → 目的分区 × 多重量带(对齐承运商矩阵报价单)
|
||||
|
||||
-- 1) version 增加计费重取整
|
||||
ALTER TABLE `ec_express_quote_version`
|
||||
ADD COLUMN `weight_round` varchar(16) NOT NULL DEFAULT 'NONE' COMMENT '计费重取整:NONE/CEIL_KG'
|
||||
AFTER `use_volumetric`;
|
||||
|
||||
-- 2) region 增加价区标签
|
||||
ALTER TABLE `ec_express_quote_region`
|
||||
ADD COLUMN `zone_label` varchar(32) NULL DEFAULT NULL COMMENT '价区标签:一类/二类…'
|
||||
AFTER `region_name`;
|
||||
|
||||
ALTER TABLE `ec_express_quote_region`
|
||||
MODIFY COLUMN `provinces_json` json NOT NULL COMMENT '目的地列表 JSON(省全称或市名)';
|
||||
|
||||
-- 3) 新建重量带表
|
||||
CREATE TABLE IF NOT EXISTS `ec_express_quote_band` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '重量带ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`version_id` bigint UNSIGNED NOT NULL COMMENT '报价版本ID',
|
||||
`region_id` bigint UNSIGNED NOT NULL COMMENT '分区ID',
|
||||
`weight_from_g` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '计费重下限(克,含)',
|
||||
`weight_to_g` int UNSIGNED NULL DEFAULT NULL COMMENT '计费重上限(克,含);NULL=无上限',
|
||||
`price_mode` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'FLAT_TICKET/FIRST_PLUS_KG',
|
||||
`flat_amount` decimal(10, 2) NULL DEFAULT NULL COMMENT 'FLAT_TICKET 元/票',
|
||||
`first_weight_g` int UNSIGNED NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 首重克数',
|
||||
`first_amount` decimal(10, 2) NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 首重价',
|
||||
`continue_per_kg` decimal(10, 4) NULL DEFAULT NULL COMMENT 'FIRST_PLUS_KG 续重元/kg',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '同区分带排序',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `idx_ec_express_quote_band_region`(`region_id` ASC, `weight_from_g` ASC) USING BTREE,
|
||||
INDEX `idx_ec_express_quote_band_version`(`version_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_version` FOREIGN KEY (`version_id`) REFERENCES `ec_express_quote_version` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_express_quote_band_region` FOREIGN KEY (`region_id`) REFERENCES `ec_express_quote_region` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-快递报价重量带';
|
||||
|
||||
-- 4) 迁移旧 tier → 一条开区间 FIRST_PLUS_KG band
|
||||
INSERT INTO `ec_express_quote_band` (
|
||||
`company_id`, `version_id`, `region_id`,
|
||||
`weight_from_g`, `weight_to_g`, `price_mode`,
|
||||
`first_weight_g`, `first_amount`, `continue_per_kg`, `sort_order`
|
||||
)
|
||||
SELECT
|
||||
t.`company_id`, t.`version_id`, t.`region_id`,
|
||||
0, NULL, 'FIRST_PLUS_KG',
|
||||
IFNULL(t.`first_weight_g`, 1000),
|
||||
IFNULL(t.`first_amount`, 0),
|
||||
CASE
|
||||
WHEN IFNULL(t.`additional_weight_g`, 0) > 0
|
||||
THEN ROUND(IFNULL(t.`additional_amount`, 0) * 1000 / t.`additional_weight_g`, 4)
|
||||
ELSE IFNULL(t.`additional_amount`, 0)
|
||||
END,
|
||||
0
|
||||
FROM `ec_express_quote_tier` t
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `ec_express_quote_band` b WHERE b.`region_id` = t.`region_id`
|
||||
);
|
||||
|
||||
-- 5) 删除旧 tier
|
||||
DROP TABLE IF EXISTS `ec_express_quote_tier`;
|
||||
+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() {
|
||||
|
||||
+2
-1
@@ -119,7 +119,8 @@ public class FreightCostCalculator {
|
||||
}
|
||||
int chargeG = FreightQuoteResolver.chargeableWeightG(actualG, volumetricG, useVolumetric);
|
||||
Optional<BigDecimal> packageFreight = quoteResolver.resolveAmount(
|
||||
warehouseId, onDate, order.getProvince(), chargeG, pieceCount, preferredCarrier);
|
||||
warehouseId, onDate, order.getProvince(), order.getCity(),
|
||||
chargeG, pieceCount, preferredCarrier);
|
||||
|
||||
if (packageFreight.isPresent() && chargeG > 0) {
|
||||
allocateByWeight(result, group, lineWeight, packageFreight.get(), costMap, onDate);
|
||||
|
||||
+110
-47
@@ -6,14 +6,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteBandMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteRegionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteTierMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteVersionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.WarehouseExpressBindMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteBandPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuotePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteRegionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteTierPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteVersionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.WarehouseExpressBindPO;
|
||||
|
||||
@@ -27,8 +27,9 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 按仓 + 日期 + 省 + 计费重 + 可选承运商选价。
|
||||
* 按仓 + 日期 + 目的地 + 计费重 + 可选承运商选价。
|
||||
* 策略:PRIORITY;有 carrier 时将该 carrier 的 bind 提到最前。
|
||||
* REGION_WEIGHT:目的地优先市名精确匹配,再省全称,再默认分区;命中后按重量带计价。
|
||||
*/
|
||||
@Component
|
||||
public class FreightQuoteResolver {
|
||||
@@ -37,20 +38,20 @@ public class FreightQuoteResolver {
|
||||
private final ExpressQuoteMapper quoteMapper;
|
||||
private final ExpressQuoteVersionMapper versionMapper;
|
||||
private final ExpressQuoteRegionMapper regionMapper;
|
||||
private final ExpressQuoteTierMapper tierMapper;
|
||||
private final ExpressQuoteBandMapper bandMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public FreightQuoteResolver(WarehouseExpressBindMapper bindMapper,
|
||||
ExpressQuoteMapper quoteMapper,
|
||||
ExpressQuoteVersionMapper versionMapper,
|
||||
ExpressQuoteRegionMapper regionMapper,
|
||||
ExpressQuoteTierMapper tierMapper,
|
||||
ExpressQuoteBandMapper bandMapper,
|
||||
ObjectMapper objectMapper) {
|
||||
this.bindMapper = bindMapper;
|
||||
this.quoteMapper = quoteMapper;
|
||||
this.versionMapper = versionMapper;
|
||||
this.regionMapper = regionMapper;
|
||||
this.tierMapper = tierMapper;
|
||||
this.bandMapper = bandMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@@ -59,8 +60,10 @@ public class FreightQuoteResolver {
|
||||
* @param pieceCount 件数(FLAT/PIECE 用)
|
||||
* @return 运费金额;无法计价返回 empty
|
||||
*/
|
||||
public Optional<BigDecimal> resolveAmount(Long warehouseId, LocalDate onDate, String province,
|
||||
int chargeableWeightG, int pieceCount, String preferredCarrier) {
|
||||
public Optional<BigDecimal> resolveAmount(Long warehouseId, LocalDate onDate,
|
||||
String province, String city,
|
||||
int chargeableWeightG, int pieceCount,
|
||||
String preferredCarrier) {
|
||||
if (warehouseId == null || onDate == null || chargeableWeightG <= 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -94,6 +97,7 @@ public class FreightQuoteResolver {
|
||||
}
|
||||
|
||||
String provinceFull = BiRegionNormalizer.normalize(province);
|
||||
String cityRaw = StringUtils.hasText(city) ? city.trim() : null;
|
||||
for (WarehouseExpressBindPO bind : ordered) {
|
||||
ExpressQuotePO quote = quoteMapper.selectById(bind.getQuoteId());
|
||||
if (quote == null || quote.getStatus() == null || quote.getStatus() != 1) {
|
||||
@@ -107,7 +111,8 @@ public class FreightQuoteResolver {
|
||||
if (version == null) {
|
||||
continue;
|
||||
}
|
||||
Optional<BigDecimal> amount = price(quote, version, provinceFull, chargeableWeightG, pieceCount);
|
||||
int weightG = applyWeightRound(chargeableWeightG, version.getWeightRound());
|
||||
Optional<BigDecimal> amount = price(quote, version, provinceFull, cityRaw, weightG, pieceCount);
|
||||
if (amount.isPresent()) {
|
||||
return amount;
|
||||
}
|
||||
@@ -116,7 +121,7 @@ public class FreightQuoteResolver {
|
||||
}
|
||||
|
||||
private Optional<BigDecimal> price(ExpressQuotePO quote, ExpressQuoteVersionPO version,
|
||||
String provinceFull, int weightG, int pieceCount) {
|
||||
String provinceFull, String cityRaw, int weightG, int pieceCount) {
|
||||
String mode = quote.getBillingMode();
|
||||
if (ExpressQuotePO.MODE_FLAT.equals(mode)) {
|
||||
if (version.getFlatAmount() == null) {
|
||||
@@ -143,62 +148,120 @@ public class FreightQuoteResolver {
|
||||
return Optional.of(amount);
|
||||
}
|
||||
if (ExpressQuotePO.MODE_REGION_WEIGHT.equals(mode)) {
|
||||
return priceRegionWeight(version, provinceFull, weightG);
|
||||
return priceRegionWeight(version, provinceFull, cityRaw, weightG);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<BigDecimal> priceRegionWeight(ExpressQuoteVersionPO version, String provinceFull, int weightG) {
|
||||
private Optional<BigDecimal> priceRegionWeight(ExpressQuoteVersionPO version,
|
||||
String provinceFull, String cityRaw, int weightG) {
|
||||
List<ExpressQuoteRegionPO> regions = regionMapper.selectList(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, version.getId())
|
||||
.orderByAsc(ExpressQuoteRegionPO::getSortOrder));
|
||||
ExpressQuoteRegionPO hit = null;
|
||||
ExpressQuoteRegionPO hit = matchRegion(regions, provinceFull, cityRaw);
|
||||
if (hit == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<ExpressQuoteBandPO> bands = bandMapper.selectList(new LambdaQueryWrapper<ExpressQuoteBandPO>()
|
||||
.eq(ExpressQuoteBandPO::getRegionId, hit.getId())
|
||||
.orderByAsc(ExpressQuoteBandPO::getSortOrder)
|
||||
.orderByAsc(ExpressQuoteBandPO::getWeightFromG));
|
||||
ExpressQuoteBandPO band = matchBand(bands, weightG);
|
||||
if (band == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return priceBand(band, weightG);
|
||||
}
|
||||
|
||||
/** 市名精确优先,再省全称,再默认分区。 */
|
||||
private ExpressQuoteRegionPO matchRegion(List<ExpressQuoteRegionPO> regions,
|
||||
String provinceFull, String cityRaw) {
|
||||
ExpressQuoteRegionPO defaultRegion = null;
|
||||
ExpressQuoteRegionPO provinceHit = null;
|
||||
for (ExpressQuoteRegionPO r : regions) {
|
||||
if (r.getIsDefault() != null && r.getIsDefault() == 1) {
|
||||
defaultRegion = r;
|
||||
}
|
||||
if (provinceContains(r.getProvincesJson(), provinceFull)) {
|
||||
hit = r;
|
||||
break;
|
||||
List<String> dests = parseDestinations(r.getProvincesJson());
|
||||
if (cityRaw != null && dests.stream().anyMatch(d -> destinationEquals(d, cityRaw))) {
|
||||
return r;
|
||||
}
|
||||
if (provinceHit == null && !BiRegionNormalizer.isUnknown(provinceFull)
|
||||
&& dests.stream().anyMatch(d -> destinationEquals(d, provinceFull))) {
|
||||
provinceHit = r;
|
||||
}
|
||||
}
|
||||
if (hit == null) {
|
||||
hit = defaultRegion;
|
||||
}
|
||||
if (hit == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ExpressQuoteTierPO tier = tierMapper.selectOne(new LambdaQueryWrapper<ExpressQuoteTierPO>()
|
||||
.eq(ExpressQuoteTierPO::getRegionId, hit.getId())
|
||||
.last("LIMIT 1"));
|
||||
if (tier == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
int firstG = tier.getFirstWeightG() != null && tier.getFirstWeightG() > 0 ? tier.getFirstWeightG() : 1000;
|
||||
int addG = tier.getAdditionalWeightG() != null && tier.getAdditionalWeightG() > 0
|
||||
? tier.getAdditionalWeightG() : 1000;
|
||||
BigDecimal firstAmt = nz(tier.getFirstAmount());
|
||||
BigDecimal addAmt = nz(tier.getAdditionalAmount());
|
||||
if (weightG <= firstG) {
|
||||
return Optional.of(firstAmt);
|
||||
}
|
||||
int remain = weightG - firstG;
|
||||
int steps = (remain + addG - 1) / addG;
|
||||
return Optional.of(firstAmt.add(addAmt.multiply(BigDecimal.valueOf(steps))).setScale(2, RoundingMode.HALF_UP));
|
||||
return provinceHit != null ? provinceHit : defaultRegion;
|
||||
}
|
||||
|
||||
private boolean provinceContains(String provincesJson, String provinceFull) {
|
||||
if (!StringUtils.hasText(provincesJson) || BiRegionNormalizer.isUnknown(provinceFull)) {
|
||||
return false;
|
||||
private static ExpressQuoteBandPO matchBand(List<ExpressQuoteBandPO> bands, int weightG) {
|
||||
for (ExpressQuoteBandPO b : bands) {
|
||||
int from = b.getWeightFromG() != null ? b.getWeightFromG() : 0;
|
||||
Integer to = b.getWeightToG();
|
||||
if (weightG >= from && (to == null || weightG <= to)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Optional<BigDecimal> priceBand(ExpressQuoteBandPO band, int weightG) {
|
||||
if (ExpressQuoteBandPO.MODE_FLAT_TICKET.equals(band.getPriceMode())) {
|
||||
if (band.getFlatAmount() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(band.getFlatAmount().setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
if (ExpressQuoteBandPO.MODE_FIRST_PLUS_KG.equals(band.getPriceMode())) {
|
||||
int firstG = band.getFirstWeightG() != null ? Math.max(band.getFirstWeightG(), 0) : 0;
|
||||
BigDecimal firstAmt = nz(band.getFirstAmount());
|
||||
BigDecimal continuePerKg = nz(band.getContinuePerKg());
|
||||
if (weightG <= firstG) {
|
||||
return Optional.of(firstAmt.setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
int remainG = weightG - firstG;
|
||||
int continueKg = (remainG + 999) / 1000;
|
||||
return Optional.of(firstAmt.add(continuePerKg.multiply(BigDecimal.valueOf(continueKg)))
|
||||
.setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** 计费重取整:CEIL_KG 向上取整到整千克(克)。 */
|
||||
static int applyWeightRound(int weightG, String round) {
|
||||
if (weightG <= 0) {
|
||||
return weightG;
|
||||
}
|
||||
if ("CEIL_KG".equalsIgnoreCase(round)) {
|
||||
return ((weightG + 999) / 1000) * 1000;
|
||||
}
|
||||
return weightG;
|
||||
}
|
||||
|
||||
private List<String> parseDestinations(String provincesJson) {
|
||||
if (!StringUtils.hasText(provincesJson)) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
List<String> list = objectMapper.readValue(provincesJson, new TypeReference<>() {
|
||||
return objectMapper.readValue(provincesJson, new TypeReference<>() {
|
||||
});
|
||||
return list.stream().anyMatch(p -> Objects.equals(p, provinceFull));
|
||||
} catch (Exception e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean destinationEquals(String configured, String actual) {
|
||||
if (!StringUtils.hasText(configured) || !StringUtils.hasText(actual)) {
|
||||
return false;
|
||||
}
|
||||
String a = configured.trim();
|
||||
String b = actual.trim();
|
||||
if (Objects.equals(a, b)) {
|
||||
return true;
|
||||
}
|
||||
String na = BiRegionNormalizer.normalize(a);
|
||||
String nb = BiRegionNormalizer.normalize(b);
|
||||
return !BiRegionNormalizer.isUnknown(na) && Objects.equals(na, nb);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
@@ -206,7 +269,8 @@ public class FreightQuoteResolver {
|
||||
}
|
||||
|
||||
/**
|
||||
* 体积重(克):长宽高 mm,divisor 默认 6000 → kg = L*W*H/divisor,再 ×1000。
|
||||
* 体积重(克):长宽高 mm,divisor 默认 6000(cm 公式)。
|
||||
* 克 = ceil(Lmm * Wmm * Hmm / divisor)。
|
||||
*/
|
||||
public static int volumetricWeightG(Integer lengthMm, Integer widthMm, Integer heightMm, Integer divisor) {
|
||||
if (lengthMm == null || widthMm == null || heightMm == null
|
||||
@@ -215,8 +279,7 @@ public class FreightQuoteResolver {
|
||||
}
|
||||
int d = divisor != null && divisor > 0 ? divisor : 6000;
|
||||
long volume = (long) lengthMm * widthMm * heightMm;
|
||||
// kg = volume / d;g = kg * 1000 = volume * 1000 / d
|
||||
return (int) Math.ceil(volume * 1000.0 / d);
|
||||
return (int) Math.ceil(volume * 1.0 / d);
|
||||
}
|
||||
|
||||
public static int chargeableWeightG(int actualG, int volumetricG, boolean useVolumetric) {
|
||||
|
||||
+3
-3
@@ -2,9 +2,9 @@ package top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteTierPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteBandPO;
|
||||
|
||||
/** ExpressQuoteTier Mapper */
|
||||
/** 快递报价重量带 Mapper */
|
||||
@Mapper
|
||||
public interface ExpressQuoteTierMapper extends BaseMapper<ExpressQuoteTierPO> {
|
||||
public interface ExpressQuoteBandMapper extends BaseMapper<ExpressQuoteBandPO> {
|
||||
}
|
||||
+22
-4
@@ -27,7 +27,6 @@ public final class ExpressQuoteDtos {
|
||||
private String billingMode;
|
||||
private Integer status;
|
||||
private String remark;
|
||||
/** 创建时可顺带写入首个版本 */
|
||||
@Valid
|
||||
private VersionUpsert initialVersion;
|
||||
}
|
||||
@@ -60,6 +59,8 @@ public final class ExpressQuoteDtos {
|
||||
private BigDecimal minAmount;
|
||||
private Integer volumeDivisor;
|
||||
private Integer useVolumetric;
|
||||
/** NONE / CEIL_KG */
|
||||
private String weightRound;
|
||||
private String remark;
|
||||
@Valid
|
||||
private List<RegionUpsert> regions;
|
||||
@@ -69,13 +70,30 @@ public final class ExpressQuoteDtos {
|
||||
public static class RegionUpsert {
|
||||
@NotBlank(message = "分区名不能为空")
|
||||
private String regionName;
|
||||
/** 省份全称列表 */
|
||||
/** 一类/二类… */
|
||||
private String zoneLabel;
|
||||
/** 目的地:省全称或市名 */
|
||||
private List<String> provinces;
|
||||
private Integer isDefault;
|
||||
private Integer sortOrder;
|
||||
/** 重量带(REGION_WEIGHT 必填) */
|
||||
@Valid
|
||||
private List<BandUpsert> bands;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BandUpsert {
|
||||
/** 下限克(含),默认 0 */
|
||||
private Integer weightFromG;
|
||||
/** 上限克(含);空=无上限 */
|
||||
private Integer weightToG;
|
||||
/** FLAT_TICKET / FIRST_PLUS_KG */
|
||||
@NotBlank(message = "计价方式不能为空")
|
||||
private String priceMode;
|
||||
private BigDecimal flatAmount;
|
||||
private Integer firstWeightG;
|
||||
private BigDecimal firstAmount;
|
||||
private Integer additionalWeightG;
|
||||
private BigDecimal additionalAmount;
|
||||
private BigDecimal continuePerKg;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+23
-7
@@ -6,10 +6,13 @@ import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 分区首重/续重。 */
|
||||
/** 报价重量带(一分区多行)。 */
|
||||
@Data
|
||||
@TableName("ec_express_quote_tier")
|
||||
public class ExpressQuoteTierPO {
|
||||
@TableName("ec_express_quote_band")
|
||||
public class ExpressQuoteBandPO {
|
||||
|
||||
public static final String MODE_FLAT_TICKET = "FLAT_TICKET";
|
||||
public static final String MODE_FIRST_PLUS_KG = "FIRST_PLUS_KG";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
@@ -23,17 +26,30 @@ public class ExpressQuoteTierPO {
|
||||
@TableField("region_id")
|
||||
private Long regionId;
|
||||
|
||||
@TableField("weight_from_g")
|
||||
private Integer weightFromG;
|
||||
|
||||
/** NULL=无上限 */
|
||||
@TableField("weight_to_g")
|
||||
private Integer weightToG;
|
||||
|
||||
@TableField("price_mode")
|
||||
private String priceMode;
|
||||
|
||||
@TableField("flat_amount")
|
||||
private BigDecimal flatAmount;
|
||||
|
||||
@TableField("first_weight_g")
|
||||
private Integer firstWeightG;
|
||||
|
||||
@TableField("first_amount")
|
||||
private BigDecimal firstAmount;
|
||||
|
||||
@TableField("additional_weight_g")
|
||||
private Integer additionalWeightG;
|
||||
@TableField("continue_per_kg")
|
||||
private BigDecimal continuePerKg;
|
||||
|
||||
@TableField("additional_amount")
|
||||
private BigDecimal additionalAmount;
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
+5
-1
@@ -22,7 +22,11 @@ public class ExpressQuoteRegionPO {
|
||||
@TableField("region_name")
|
||||
private String regionName;
|
||||
|
||||
/** JSON 数组字符串 */
|
||||
/** 一类/二类等展示标签 */
|
||||
@TableField("zone_label")
|
||||
private String zoneLabel;
|
||||
|
||||
/** 目的地 JSON(省全称或市名) */
|
||||
@TableField("provinces_json")
|
||||
private String provincesJson;
|
||||
|
||||
|
||||
+4
@@ -46,6 +46,10 @@ public class ExpressQuoteVersionPO {
|
||||
@TableField("use_volumetric")
|
||||
private Integer useVolumetric;
|
||||
|
||||
/** NONE / CEIL_KG */
|
||||
@TableField("weight_round")
|
||||
private String weightRound;
|
||||
|
||||
@TableField("remark")
|
||||
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;
|
||||
}
|
||||
}
|
||||
+14
-3
@@ -21,7 +21,6 @@ public class ExpressQuoteVO {
|
||||
private String remark;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime updateTime;
|
||||
/** 当前生效版本(最大 effective_from)摘要 */
|
||||
private VersionVO currentVersion;
|
||||
private List<VersionVO> versions;
|
||||
|
||||
@@ -36,6 +35,7 @@ public class ExpressQuoteVO {
|
||||
private BigDecimal minAmount;
|
||||
private Integer volumeDivisor;
|
||||
private Integer useVolumetric;
|
||||
private String weightRound;
|
||||
private String remark;
|
||||
private LocalDateTime createTime;
|
||||
private List<RegionVO> regions;
|
||||
@@ -45,12 +45,23 @@ public class ExpressQuoteVO {
|
||||
public static class RegionVO {
|
||||
private Long id;
|
||||
private String regionName;
|
||||
private String zoneLabel;
|
||||
private List<String> provinces;
|
||||
private Integer isDefault;
|
||||
private Integer sortOrder;
|
||||
private List<BandVO> bands;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BandVO {
|
||||
private Long id;
|
||||
private Integer weightFromG;
|
||||
private Integer weightToG;
|
||||
private String priceMode;
|
||||
private BigDecimal flatAmount;
|
||||
private Integer firstWeightG;
|
||||
private BigDecimal firstAmount;
|
||||
private Integer additionalWeightG;
|
||||
private BigDecimal additionalAmount;
|
||||
private BigDecimal continuePerKg;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
|
||||
+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(), draft.getWarnings());
|
||||
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;
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
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 多段表头。
|
||||
* 空单元格 / 不可解析单元格 / 无有效带的行 → warning 并跳过,不拖垮整单。
|
||||
*/
|
||||
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<String> warnings) {
|
||||
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);
|
||||
|
||||
// 偏远区域行:内嵌新重量表头
|
||||
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, warnings, r + 1);
|
||||
if (region != null) {
|
||||
rows.add(region);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static ExpressQuoteImportModels.RegionDraft parseDataRow(
|
||||
Row row, List<ExpressQuoteImportModels.ColumnDef> columns,
|
||||
List<String> warnings, 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) {
|
||||
warnings.add("第" + excelRow + "行「" + destRaw + "」列" + (col.getColIndex() + 1)
|
||||
+ "已跳过(无法解析): " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
if (bands.isEmpty()) {
|
||||
warnings.add("第" + excelRow + "行「" + destRaw + "」无有效重量带,已跳过该目的地");
|
||||
return null;
|
||||
}
|
||||
region.setBands(bands);
|
||||
return 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();
|
||||
}
|
||||
}
|
||||
+91
-48
@@ -17,15 +17,15 @@ import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.freight.ExpressCarrierCodes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteBandMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteRegionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteTierMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.ExpressQuoteVersionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.mapper.WarehouseExpressBindMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.dto.ExpressQuoteDtos;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteBandPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuotePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteRegionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteTierPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.ExpressQuoteVersionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.po.WarehouseExpressBindPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.warehouse.model.vo.ExpressQuoteVO;
|
||||
@@ -48,7 +48,7 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ExpressQuoteVersionMapper versionMapper;
|
||||
private final ExpressQuoteRegionMapper regionMapper;
|
||||
private final ExpressQuoteTierMapper tierMapper;
|
||||
private final ExpressQuoteBandMapper bandMapper;
|
||||
private final WarehouseExpressBindMapper bindMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final BiOrderStatDirtyDayService dirtyDayService;
|
||||
@@ -57,7 +57,7 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
public ExpressQuoteServiceImpl(CurrentUserContext currentUserContext,
|
||||
ExpressQuoteVersionMapper versionMapper,
|
||||
ExpressQuoteRegionMapper regionMapper,
|
||||
ExpressQuoteTierMapper tierMapper,
|
||||
ExpressQuoteBandMapper bandMapper,
|
||||
WarehouseExpressBindMapper bindMapper,
|
||||
ProductSkuMapper productSkuMapper,
|
||||
BiOrderStatDirtyDayService dirtyDayService,
|
||||
@@ -65,7 +65,7 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.versionMapper = versionMapper;
|
||||
this.regionMapper = regionMapper;
|
||||
this.tierMapper = tierMapper;
|
||||
this.bandMapper = bandMapper;
|
||||
this.bindMapper = bindMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.dirtyDayService = dirtyDayService;
|
||||
@@ -235,15 +235,7 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
applyVersionFields(version, dto);
|
||||
version.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
versionMapper.updateById(version);
|
||||
// 重建分区
|
||||
List<ExpressQuoteRegionPO> oldRegions = regionMapper.selectList(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, version.getId()));
|
||||
for (ExpressQuoteRegionPO r : oldRegions) {
|
||||
tierMapper.delete(new LambdaQueryWrapper<ExpressQuoteTierPO>()
|
||||
.eq(ExpressQuoteTierPO::getRegionId, r.getId()));
|
||||
}
|
||||
regionMapper.delete(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, version.getId()));
|
||||
clearRegionsAndBands(version.getId());
|
||||
} else {
|
||||
version = new ExpressQuoteVersionPO();
|
||||
version.setCompanyId(quote.getCompanyId());
|
||||
@@ -266,6 +258,11 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
version.setMinAmount(dto.getMinAmount());
|
||||
version.setVolumeDivisor(dto.getVolumeDivisor() != null ? dto.getVolumeDivisor() : 6000);
|
||||
version.setUseVolumetric(dto.getUseVolumetric() != null ? dto.getUseVolumetric() : 0);
|
||||
String round = dto.getWeightRound() != null ? dto.getWeightRound().trim().toUpperCase() : "NONE";
|
||||
if (!"CEIL_KG".equals(round)) {
|
||||
round = "NONE";
|
||||
}
|
||||
version.setWeightRound(round);
|
||||
version.setRemark(dto.getRemark());
|
||||
}
|
||||
|
||||
@@ -275,44 +272,78 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
}
|
||||
int i = 0;
|
||||
for (ExpressQuoteDtos.RegionUpsert r : regions) {
|
||||
if (r.getBands() == null || r.getBands().isEmpty()) {
|
||||
throw new BusinessException("分区「" + r.getRegionName() + "」至少配置一条重量带");
|
||||
}
|
||||
ExpressQuoteRegionPO region = new ExpressQuoteRegionPO();
|
||||
region.setCompanyId(companyId);
|
||||
region.setVersionId(versionId);
|
||||
region.setRegionName(r.getRegionName().trim());
|
||||
region.setProvincesJson(toProvincesJson(r.getProvinces()));
|
||||
region.setZoneLabel(StringUtils.hasText(r.getZoneLabel()) ? r.getZoneLabel().trim() : null);
|
||||
region.setProvincesJson(toDestinationsJson(r.getProvinces()));
|
||||
region.setIsDefault(r.getIsDefault() != null ? r.getIsDefault() : 0);
|
||||
region.setSortOrder(r.getSortOrder() != null ? r.getSortOrder() : i++);
|
||||
regionMapper.insert(region);
|
||||
|
||||
ExpressQuoteTierPO tier = new ExpressQuoteTierPO();
|
||||
tier.setCompanyId(companyId);
|
||||
tier.setVersionId(versionId);
|
||||
tier.setRegionId(region.getId());
|
||||
tier.setFirstWeightG(r.getFirstWeightG() != null ? r.getFirstWeightG() : 1000);
|
||||
tier.setFirstAmount(r.getFirstAmount() != null ? r.getFirstAmount() : java.math.BigDecimal.ZERO);
|
||||
tier.setAdditionalWeightG(r.getAdditionalWeightG() != null ? r.getAdditionalWeightG() : 1000);
|
||||
tier.setAdditionalAmount(r.getAdditionalAmount() != null ? r.getAdditionalAmount() : java.math.BigDecimal.ZERO);
|
||||
tierMapper.insert(tier);
|
||||
int bi = 0;
|
||||
for (ExpressQuoteDtos.BandUpsert b : r.getBands()) {
|
||||
saveBand(companyId, versionId, region.getId(), b, bi++);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String toProvincesJson(List<String> provinces) {
|
||||
private void saveBand(Long companyId, Long versionId, Long regionId,
|
||||
ExpressQuoteDtos.BandUpsert b, int defaultOrder) {
|
||||
String mode = b.getPriceMode().trim().toUpperCase();
|
||||
if (!ExpressQuoteBandPO.MODE_FLAT_TICKET.equals(mode)
|
||||
&& !ExpressQuoteBandPO.MODE_FIRST_PLUS_KG.equals(mode)) {
|
||||
throw new BusinessException("不支持的重量带计价方式: " + b.getPriceMode());
|
||||
}
|
||||
int from = b.getWeightFromG() != null ? b.getWeightFromG() : 0;
|
||||
Integer to = b.getWeightToG();
|
||||
if (from < 0 || (to != null && to < from)) {
|
||||
throw new BusinessException("重量带区间无效");
|
||||
}
|
||||
ExpressQuoteBandPO band = new ExpressQuoteBandPO();
|
||||
band.setCompanyId(companyId);
|
||||
band.setVersionId(versionId);
|
||||
band.setRegionId(regionId);
|
||||
band.setWeightFromG(from);
|
||||
band.setWeightToG(to);
|
||||
band.setPriceMode(mode);
|
||||
band.setSortOrder(b.getSortOrder() != null ? b.getSortOrder() : defaultOrder);
|
||||
if (ExpressQuoteBandPO.MODE_FLAT_TICKET.equals(mode)) {
|
||||
if (b.getFlatAmount() == null) {
|
||||
throw new BusinessException("元/票金额不能为空");
|
||||
}
|
||||
band.setFlatAmount(b.getFlatAmount());
|
||||
} else {
|
||||
if (b.getFirstAmount() == null || b.getContinuePerKg() == null) {
|
||||
throw new BusinessException("首重价与续重元/kg 不能为空");
|
||||
}
|
||||
band.setFirstWeightG(b.getFirstWeightG() != null ? b.getFirstWeightG() : 0);
|
||||
band.setFirstAmount(b.getFirstAmount());
|
||||
band.setContinuePerKg(b.getContinuePerKg());
|
||||
}
|
||||
bandMapper.insert(band);
|
||||
}
|
||||
|
||||
/** 目的地:能归一为省全称则用全称,否则保留原名(如深圳市)。 */
|
||||
private String toDestinationsJson(List<String> destinations) {
|
||||
try {
|
||||
Set<String> normalized = new HashSet<>();
|
||||
if (provinces != null) {
|
||||
for (String p : provinces) {
|
||||
if (destinations != null) {
|
||||
for (String p : destinations) {
|
||||
if (!StringUtils.hasText(p)) {
|
||||
continue;
|
||||
}
|
||||
String n = BiRegionNormalizer.normalize(p);
|
||||
if (!BiRegionNormalizer.isUnknown(n)) {
|
||||
normalized.add(n);
|
||||
}
|
||||
String raw = p.trim();
|
||||
String n = BiRegionNormalizer.normalize(raw);
|
||||
normalized.add(BiRegionNormalizer.isUnknown(n) ? raw : n);
|
||||
}
|
||||
}
|
||||
return objectMapper.writeValueAsString(normalized.stream().sorted().toList());
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("省份列表序列化失败");
|
||||
throw new BusinessException("目的地列表序列化失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,20 +387,29 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
}
|
||||
} else if (ExpressQuotePO.MODE_REGION_WEIGHT.equals(billingMode)) {
|
||||
if (dto.getRegions() == null || dto.getRegions().isEmpty()) {
|
||||
throw new BusinessException("请配置分区与首重续重");
|
||||
throw new BusinessException("请配置目的分区与重量带");
|
||||
}
|
||||
for (ExpressQuoteDtos.RegionUpsert r : dto.getRegions()) {
|
||||
if (r.getBands() == null || r.getBands().isEmpty()) {
|
||||
throw new BusinessException("分区「" + r.getRegionName() + "」至少一条重量带");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteVersionCascade(Long versionId) {
|
||||
List<ExpressQuoteRegionPO> regions = regionMapper.selectList(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
private void clearRegionsAndBands(Long versionId) {
|
||||
List<ExpressQuoteRegionPO> oldRegions = regionMapper.selectList(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, versionId));
|
||||
for (ExpressQuoteRegionPO r : regions) {
|
||||
tierMapper.delete(new LambdaQueryWrapper<ExpressQuoteTierPO>()
|
||||
.eq(ExpressQuoteTierPO::getRegionId, r.getId()));
|
||||
for (ExpressQuoteRegionPO r : oldRegions) {
|
||||
bandMapper.delete(new LambdaQueryWrapper<ExpressQuoteBandPO>()
|
||||
.eq(ExpressQuoteBandPO::getRegionId, r.getId()));
|
||||
}
|
||||
regionMapper.delete(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, versionId));
|
||||
}
|
||||
|
||||
private void deleteVersionCascade(Long versionId) {
|
||||
clearRegionsAndBands(versionId);
|
||||
versionMapper.deleteById(versionId);
|
||||
}
|
||||
|
||||
@@ -427,24 +467,27 @@ public class ExpressQuoteServiceImpl extends ServiceImpl<ExpressQuoteMapper, Exp
|
||||
List<ExpressQuoteRegionPO> regions = regionMapper.selectList(new LambdaQueryWrapper<ExpressQuoteRegionPO>()
|
||||
.eq(ExpressQuoteRegionPO::getVersionId, v.getId())
|
||||
.orderByAsc(ExpressQuoteRegionPO::getSortOrder));
|
||||
List<ExpressQuoteTierPO> tiers = tierMapper.selectList(new LambdaQueryWrapper<ExpressQuoteTierPO>()
|
||||
.eq(ExpressQuoteTierPO::getVersionId, v.getId()));
|
||||
var tierByRegion = tiers.stream().collect(Collectors.toMap(ExpressQuoteTierPO::getRegionId, t -> t, (a, b) -> a));
|
||||
List<ExpressQuoteBandPO> bands = bandMapper.selectList(new LambdaQueryWrapper<ExpressQuoteBandPO>()
|
||||
.eq(ExpressQuoteBandPO::getVersionId, v.getId())
|
||||
.orderByAsc(ExpressQuoteBandPO::getSortOrder)
|
||||
.orderByAsc(ExpressQuoteBandPO::getWeightFromG));
|
||||
var bandsByRegion = bands.stream().collect(Collectors.groupingBy(ExpressQuoteBandPO::getRegionId));
|
||||
List<ExpressQuoteVO.RegionVO> regionVos = new ArrayList<>();
|
||||
for (ExpressQuoteRegionPO r : regions) {
|
||||
ExpressQuoteVO.RegionVO rv = new ExpressQuoteVO.RegionVO();
|
||||
rv.setId(r.getId());
|
||||
rv.setRegionName(r.getRegionName());
|
||||
rv.setZoneLabel(r.getZoneLabel());
|
||||
rv.setProvinces(parseProvinces(r.getProvincesJson()));
|
||||
rv.setIsDefault(r.getIsDefault());
|
||||
rv.setSortOrder(r.getSortOrder());
|
||||
ExpressQuoteTierPO tier = tierByRegion.get(r.getId());
|
||||
if (tier != null) {
|
||||
rv.setFirstWeightG(tier.getFirstWeightG());
|
||||
rv.setFirstAmount(tier.getFirstAmount());
|
||||
rv.setAdditionalWeightG(tier.getAdditionalWeightG());
|
||||
rv.setAdditionalAmount(tier.getAdditionalAmount());
|
||||
List<ExpressQuoteVO.BandVO> bandVos = new ArrayList<>();
|
||||
for (ExpressQuoteBandPO b : bandsByRegion.getOrDefault(r.getId(), List.of())) {
|
||||
ExpressQuoteVO.BandVO bv = new ExpressQuoteVO.BandVO();
|
||||
BeanCopyUtils.copyProperties(b, bv);
|
||||
bandVos.add(bv);
|
||||
}
|
||||
rv.setBands(bandVos);
|
||||
regionVos.add(rv);
|
||||
}
|
||||
regionVos.sort(Comparator.comparing(r -> r.getSortOrder() != null ? r.getSortOrder() : 0));
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
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<String> warnings = new ArrayList<>();
|
||||
List<ExpressQuoteImportModels.RegionDraft> raw =
|
||||
ExpressQuoteMatrixSheetParser.parse(sheet, errors, warnings);
|
||||
List<ExpressQuoteImportModels.RegionDraft> merged = ExpressQuoteRegionMerger.merge(raw);
|
||||
assertFalse(merged.isEmpty(), "应解析到分区");
|
||||
assertTrue(errors.isEmpty(), "跳过策略下不应产生硬错误: " + errors);
|
||||
assertTrue(warnings.stream().anyMatch(w -> w.contains("跳过")),
|
||||
"应对发极兔/空行给出跳过警告: " + warnings);
|
||||
boolean hasNeimeng = merged.stream()
|
||||
.flatMap(r -> r.getDestinations().stream())
|
||||
.anyMatch(d -> d.contains("内蒙古"));
|
||||
assertTrue(hasNeimeng, "内蒙古应保留可解析重量带");
|
||||
boolean hasXizang = merged.stream()
|
||||
.flatMap(r -> r.getDestinations().stream())
|
||||
.anyMatch(d -> d.contains("西藏"));
|
||||
assertFalse(hasXizang, "西藏无价格应整行跳过");
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
import type { ExpressQuoteDTO, ExpressQuoteVO } from './types';
|
||||
import type {
|
||||
ExpressQuoteDTO,
|
||||
ExpressQuoteImportDTO,
|
||||
ExpressQuoteImportVO,
|
||||
ExpressQuoteVO,
|
||||
} from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
import { exportByGet } from '#/utils/export';
|
||||
|
||||
export async function getExpressQuotePageApi(
|
||||
params: PageQueryDTO<ExpressQuoteDTO.Filters>,
|
||||
@@ -69,3 +75,41 @@ export async function getExpressProvincesApi() {
|
||||
'/ec/express-quote/meta/provinces',
|
||||
);
|
||||
}
|
||||
|
||||
export async function downloadExpressQuoteTemplateApi() {
|
||||
return exportByGet(
|
||||
'/ec/express-quote/import/template',
|
||||
'快递报价导入模板.xlsx',
|
||||
);
|
||||
}
|
||||
|
||||
export async function previewExpressQuoteImportApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<ExpressQuoteImportVO.Preview>(
|
||||
'/ec/express-quote/import/preview',
|
||||
formData,
|
||||
{
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function commitExpressQuoteImportApi(
|
||||
file: File,
|
||||
params: ExpressQuoteImportDTO.Commit,
|
||||
) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append(
|
||||
'params',
|
||||
new Blob([JSON.stringify(params)], { type: 'application/json' }),
|
||||
);
|
||||
return requestClient.post<ExpressQuoteVO.Info>(
|
||||
'/ec/express-quote/import/commit',
|
||||
formData,
|
||||
{
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './types.dto';
|
||||
export * from './types.import';
|
||||
export * from './types.vo';
|
||||
|
||||
@@ -31,18 +31,31 @@ export namespace ExpressQuoteDTO {
|
||||
minAmount?: number;
|
||||
volumeDivisor?: number;
|
||||
useVolumetric?: number;
|
||||
/** NONE / CEIL_KG */
|
||||
weightRound?: string;
|
||||
remark?: string;
|
||||
regions?: RegionUpsert[];
|
||||
}
|
||||
|
||||
export interface RegionUpsert {
|
||||
regionName: string;
|
||||
zoneLabel?: string;
|
||||
/** 目的地:省全称或市名 */
|
||||
provinces?: string[];
|
||||
isDefault?: number;
|
||||
sortOrder?: number;
|
||||
bands?: BandUpsert[];
|
||||
}
|
||||
|
||||
export interface BandUpsert {
|
||||
weightFromG?: number;
|
||||
weightToG?: number | null;
|
||||
/** FLAT_TICKET / FIRST_PLUS_KG */
|
||||
priceMode: string;
|
||||
flatAmount?: number;
|
||||
firstWeightG?: number;
|
||||
firstAmount?: number;
|
||||
additionalWeightG?: number;
|
||||
additionalAmount?: number;
|
||||
continuePerKg?: number;
|
||||
sortOrder?: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
export namespace ExpressQuoteImportVO {
|
||||
export interface Preview {
|
||||
format?: string;
|
||||
success: boolean;
|
||||
carrierCode?: string;
|
||||
code?: string;
|
||||
name?: string;
|
||||
effectiveFrom?: string;
|
||||
weightRound?: string;
|
||||
useVolumetric?: number;
|
||||
volumeDivisor?: number;
|
||||
regionCount: number;
|
||||
destinationCount: number;
|
||||
bandCount: number;
|
||||
warnings?: string[];
|
||||
errors?: string[];
|
||||
regions?: RegionPreview[];
|
||||
}
|
||||
|
||||
export interface RegionPreview {
|
||||
regionName: string;
|
||||
zoneLabel?: string;
|
||||
destinations?: string[];
|
||||
bandCount: number;
|
||||
bands?: BandPreview[];
|
||||
}
|
||||
|
||||
export interface BandPreview {
|
||||
weightFromG: number;
|
||||
weightToG?: number | null;
|
||||
priceMode: string;
|
||||
flatAmount?: number;
|
||||
firstWeightG?: number;
|
||||
firstAmount?: number;
|
||||
continuePerKg?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ExpressQuoteImportDTO {
|
||||
export interface Commit {
|
||||
mode: 'CREATE' | 'APPEND_VERSION';
|
||||
quoteId?: number;
|
||||
carrierCode?: string;
|
||||
code?: string;
|
||||
name?: string;
|
||||
effectiveFrom?: string;
|
||||
weightRound?: string;
|
||||
useVolumetric?: number;
|
||||
volumeDivisor?: number;
|
||||
remark?: string;
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ export namespace ExpressQuoteVO {
|
||||
minAmount?: number;
|
||||
volumeDivisor?: number;
|
||||
useVolumetric?: number;
|
||||
/** NONE / CEIL_KG */
|
||||
weightRound?: string;
|
||||
remark?: string;
|
||||
regions?: Region[];
|
||||
}
|
||||
@@ -30,13 +32,24 @@ export namespace ExpressQuoteVO {
|
||||
export interface Region {
|
||||
id?: number;
|
||||
regionName: string;
|
||||
zoneLabel?: string;
|
||||
provinces?: string[];
|
||||
isDefault?: number;
|
||||
sortOrder?: number;
|
||||
bands?: Band[];
|
||||
}
|
||||
|
||||
export interface Band {
|
||||
id?: number;
|
||||
weightFromG: number;
|
||||
weightToG?: number | null;
|
||||
/** FLAT_TICKET / FIRST_PLUS_KG */
|
||||
priceMode: string;
|
||||
flatAmount?: number;
|
||||
firstWeightG?: number;
|
||||
firstAmount?: number;
|
||||
additionalWeightG?: number;
|
||||
additionalAmount?: number;
|
||||
continuePerKg?: number;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export interface CarrierOption {
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
<script lang="ts" setup>
|
||||
import type { ExpressQuoteVO } from '#/api/ec/express-quote';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import {
|
||||
Collapse,
|
||||
CollapsePanel,
|
||||
Descriptions,
|
||||
DescriptionsItem,
|
||||
Drawer,
|
||||
Empty,
|
||||
Spin,
|
||||
Table,
|
||||
Tag,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import { getExpressQuoteDetailApi } from '#/api/ec/express-quote';
|
||||
|
||||
defineOptions({ name: 'ExpressQuoteDetailDrawer' });
|
||||
|
||||
const MODE_LABEL: Record<string, string> = {
|
||||
FLAT: '一口价',
|
||||
PER_KG: '按千克',
|
||||
REGION_WEIGHT: '分区×重量带',
|
||||
};
|
||||
|
||||
const openFlag = ref(false);
|
||||
const loading = ref(false);
|
||||
const detail = ref<ExpressQuoteVO.Info | null>(null);
|
||||
|
||||
const versions = computed(() => detail.value?.versions ?? []);
|
||||
|
||||
const bandColumns = [
|
||||
{
|
||||
title: '重量(克)',
|
||||
key: 'weight',
|
||||
customRender: ({ record }: { record: ExpressQuoteVO.Band }) =>
|
||||
formatWeightRange(record.weightFromG, record.weightToG),
|
||||
},
|
||||
{
|
||||
title: '方式',
|
||||
key: 'priceMode',
|
||||
customRender: ({ record }: { record: ExpressQuoteVO.Band }) =>
|
||||
record.priceMode === 'FIRST_PLUS_KG' ? '首重+续重/kg' : '元/票',
|
||||
},
|
||||
{
|
||||
title: '价格',
|
||||
key: 'price',
|
||||
customRender: ({ record }: { record: ExpressQuoteVO.Band }) =>
|
||||
formatBandPrice(record),
|
||||
},
|
||||
];
|
||||
|
||||
function formatWeightRange(from?: number, to?: number | null) {
|
||||
const f = from ?? 0;
|
||||
if (to == null) return `${f}g+`;
|
||||
return `${f}–${to}g`;
|
||||
}
|
||||
|
||||
function formatBandPrice(b: ExpressQuoteVO.Band) {
|
||||
if (b.priceMode === 'FIRST_PLUS_KG') {
|
||||
return `${b.firstAmount ?? 0} + ${b.continuePerKg ?? 0}元/kg(首重${b.firstWeightG ?? 0}g)`;
|
||||
}
|
||||
return `${b.flatAmount ?? 0} 元/票`;
|
||||
}
|
||||
|
||||
function money(v?: number | null) {
|
||||
if (v == null || Number.isNaN(Number(v))) return '—';
|
||||
return `¥${Number(v).toFixed(2)}`;
|
||||
}
|
||||
|
||||
async function open(id: number) {
|
||||
openFlag.value = true;
|
||||
loading.value = true;
|
||||
detail.value = null;
|
||||
try {
|
||||
detail.value = await getExpressQuoteDetailApi(id);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
message.error('加载报价详情失败');
|
||||
openFlag.value = false;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
openFlag.value = false;
|
||||
}
|
||||
|
||||
defineExpose({ open, close });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Drawer
|
||||
v-model:open="openFlag"
|
||||
:title="detail ? `报价详情 · ${detail.name}` : '报价详情'"
|
||||
width="820"
|
||||
destroy-on-close
|
||||
>
|
||||
<Spin :spinning="loading">
|
||||
<template v-if="detail">
|
||||
<Descriptions bordered :column="2" size="small" class="mb-4">
|
||||
<DescriptionsItem label="编码">{{ detail.code }}</DescriptionsItem>
|
||||
<DescriptionsItem label="承运商">
|
||||
{{ detail.carrierCode }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="计费模式">
|
||||
{{ MODE_LABEL[detail.billingMode] || detail.billingMode }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="状态">
|
||||
<Tag :color="detail.status === 1 ? 'green' : 'red'">
|
||||
{{ detail.status === 1 ? '启用' : '停用' }}
|
||||
</Tag>
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="创建时间">
|
||||
{{ detail.createTime || '—' }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="备注" :span="2">
|
||||
{{ detail.remark || '—' }}
|
||||
</DescriptionsItem>
|
||||
</Descriptions>
|
||||
|
||||
<div class="mb-2 text-sm font-medium">版本历史(按生效日)</div>
|
||||
<Empty v-if="!versions.length" description="暂无版本" />
|
||||
<Collapse v-else accordion :default-active-key="[String(versions[0]?.id)]">
|
||||
<CollapsePanel
|
||||
v-for="v in versions"
|
||||
:key="String(v.id)"
|
||||
:header="`生效 ${v.effectiveFrom}${v.id === detail.currentVersion?.id ? '(当前)' : ''}`"
|
||||
>
|
||||
<Descriptions bordered :column="2" size="small" class="mb-3">
|
||||
<DescriptionsItem
|
||||
v-if="detail.billingMode === 'FLAT'"
|
||||
label="一口价"
|
||||
>
|
||||
{{ money(v.flatAmount) }}
|
||||
({{ v.unitScope === 'PIECE' ? '每件' : '每单' }})
|
||||
</DescriptionsItem>
|
||||
<template v-else-if="detail.billingMode === 'PER_KG'">
|
||||
<DescriptionsItem label="元/kg">
|
||||
{{ v.pricePerKg ?? '—' }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="最低消费">
|
||||
{{ money(v.minAmount) }}
|
||||
</DescriptionsItem>
|
||||
</template>
|
||||
<DescriptionsItem label="体积重">
|
||||
{{ v.useVolumetric === 1 ? '启用' : '关闭' }}
|
||||
(除数 {{ v.volumeDivisor ?? 6000 }})
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="计费重取整">
|
||||
{{ v.weightRound === 'CEIL_KG' ? '向上整千克' : '不取整' }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem v-if="v.remark" label="版本备注" :span="2">
|
||||
{{ v.remark }}
|
||||
</DescriptionsItem>
|
||||
</Descriptions>
|
||||
|
||||
<template v-if="detail.billingMode === 'REGION_WEIGHT'">
|
||||
<div
|
||||
v-for="(region, ri) in v.regions || []"
|
||||
:key="region.id ?? ri"
|
||||
class="mb-3 rounded border border-border p-3"
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2 text-sm">
|
||||
<span class="font-medium">{{ region.regionName }}</span>
|
||||
<Tag v-if="region.zoneLabel" color="blue">
|
||||
{{ region.zoneLabel }}
|
||||
</Tag>
|
||||
<Tag v-if="region.isDefault === 1">默认分区</Tag>
|
||||
</div>
|
||||
<div class="mb-2 text-xs text-muted-foreground">
|
||||
目的地:{{ (region.provinces || []).join('、') || '—' }}
|
||||
</div>
|
||||
<Table
|
||||
size="small"
|
||||
:pagination="false"
|
||||
:columns="bandColumns"
|
||||
:data-source="region.bands || []"
|
||||
:row-key="
|
||||
(r: ExpressQuoteVO.Band, i: number) => String(r.id ?? i)
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<Empty
|
||||
v-if="!(v.regions && v.regions.length)"
|
||||
description="该版本无分区"
|
||||
/>
|
||||
</template>
|
||||
</CollapsePanel>
|
||||
</Collapse>
|
||||
</template>
|
||||
</Spin>
|
||||
</Drawer>
|
||||
</template>
|
||||
+248
-65
@@ -6,6 +6,7 @@ import { computed, reactive, ref } from 'vue';
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
@@ -14,23 +15,62 @@ import {
|
||||
Select,
|
||||
Switch,
|
||||
} from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import {
|
||||
createExpressQuoteApi,
|
||||
getExpressCarriersApi,
|
||||
getExpressProvincesApi,
|
||||
getExpressQuoteDetailApi,
|
||||
updateExpressQuoteApi,
|
||||
upsertExpressQuoteVersionApi,
|
||||
} from '#/api/ec/express-quote';
|
||||
|
||||
const emit = defineEmits<{ success: [] }>();
|
||||
|
||||
interface BandRow {
|
||||
weightFromG: number;
|
||||
weightToG: number | null;
|
||||
priceMode: string;
|
||||
flatAmount: number;
|
||||
firstWeightG: number;
|
||||
firstAmount: number;
|
||||
continuePerKg: number;
|
||||
}
|
||||
|
||||
interface RegionRow {
|
||||
regionName: string;
|
||||
zoneLabel: string;
|
||||
provinces: string[];
|
||||
isDefault: boolean;
|
||||
bands: BandRow[];
|
||||
}
|
||||
|
||||
function emptyBand(fromG = 0): BandRow {
|
||||
return {
|
||||
weightFromG: fromG,
|
||||
weightToG: null,
|
||||
priceMode: 'FLAT_TICKET',
|
||||
flatAmount: 0,
|
||||
firstWeightG: 0,
|
||||
firstAmount: 0,
|
||||
continuePerKg: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function emptyRegion(): RegionRow {
|
||||
return {
|
||||
regionName: '默认区',
|
||||
zoneLabel: '',
|
||||
provinces: [],
|
||||
isDefault: true,
|
||||
bands: [emptyBand(0)],
|
||||
};
|
||||
}
|
||||
|
||||
const isEdit = ref(false);
|
||||
const editingId = ref<number>();
|
||||
const carriers = ref<ExpressQuoteVO.CarrierOption[]>([]);
|
||||
const provinces = ref<ExpressQuoteVO.ProvinceOption[]>([]);
|
||||
const mode = ref('FLAT');
|
||||
|
||||
const form = reactive({
|
||||
code: '',
|
||||
@@ -39,25 +79,25 @@ const form = reactive({
|
||||
billingMode: 'FLAT',
|
||||
status: 1,
|
||||
remark: '',
|
||||
effectiveFrom: dayjs().format('YYYY-MM-DD'),
|
||||
effectiveFrom: new Date().toISOString().slice(0, 10),
|
||||
flatAmount: 0,
|
||||
unitScope: 'ORDER',
|
||||
pricePerKg: 0,
|
||||
minAmount: undefined as number | undefined,
|
||||
volumeDivisor: 6000,
|
||||
useVolumetric: false,
|
||||
regionName: '默认区',
|
||||
regionProvinces: [] as string[],
|
||||
firstWeightG: 1000,
|
||||
firstAmount: 0,
|
||||
additionalWeightG: 1000,
|
||||
additionalAmount: 0,
|
||||
weightRound: 'NONE',
|
||||
regions: [emptyRegion()] as RegionRow[],
|
||||
});
|
||||
|
||||
const isRegion = computed(() => form.billingMode === 'REGION_WEIGHT');
|
||||
const isFlat = computed(() => form.billingMode === 'FLAT');
|
||||
const isPerKg = computed(() => form.billingMode === 'PER_KG');
|
||||
|
||||
const provinceOptions = computed(() =>
|
||||
provinces.value.map((p) => ({ value: p.code, label: p.name })),
|
||||
);
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
onConfirm: handleSubmit,
|
||||
onOpenChange: (open) => {
|
||||
@@ -73,20 +113,16 @@ function reset() {
|
||||
billingMode: 'FLAT',
|
||||
status: 1,
|
||||
remark: '',
|
||||
effectiveFrom: dayjs().format('YYYY-MM-DD'),
|
||||
effectiveFrom: new Date().toISOString().slice(0, 10),
|
||||
flatAmount: 0,
|
||||
unitScope: 'ORDER',
|
||||
pricePerKg: 0,
|
||||
minAmount: undefined,
|
||||
volumeDivisor: 6000,
|
||||
useVolumetric: false,
|
||||
regionName: '默认区',
|
||||
regionProvinces: [],
|
||||
firstWeightG: 1000,
|
||||
firstAmount: 0,
|
||||
additionalWeightG: 1000,
|
||||
additionalAmount: 0,
|
||||
weightRound: 'NONE',
|
||||
});
|
||||
form.regions = [emptyRegion()];
|
||||
isEdit.value = false;
|
||||
editingId.value = undefined;
|
||||
}
|
||||
@@ -100,33 +136,100 @@ async function ensureMeta() {
|
||||
}
|
||||
}
|
||||
|
||||
function fillFromVersion(v?: ExpressQuoteVO.Version) {
|
||||
if (!v) return;
|
||||
form.effectiveFrom = v.effectiveFrom;
|
||||
form.flatAmount = v.flatAmount ?? 0;
|
||||
form.unitScope = v.unitScope || 'ORDER';
|
||||
form.pricePerKg = v.pricePerKg ?? 0;
|
||||
form.minAmount = v.minAmount;
|
||||
form.volumeDivisor = v.volumeDivisor ?? 6000;
|
||||
form.useVolumetric = v.useVolumetric === 1;
|
||||
form.weightRound = v.weightRound || 'NONE';
|
||||
if (v.regions?.length) {
|
||||
form.regions = v.regions.map((r) => ({
|
||||
regionName: r.regionName,
|
||||
zoneLabel: r.zoneLabel || '',
|
||||
provinces: r.provinces ? [...r.provinces] : [],
|
||||
isDefault: r.isDefault === 1,
|
||||
bands:
|
||||
r.bands?.length ?
|
||||
r.bands.map((b) => ({
|
||||
weightFromG: b.weightFromG ?? 0,
|
||||
weightToG: b.weightToG ?? null,
|
||||
priceMode: b.priceMode || 'FLAT_TICKET',
|
||||
flatAmount: b.flatAmount ?? 0,
|
||||
firstWeightG: b.firstWeightG ?? 0,
|
||||
firstAmount: b.firstAmount ?? 0,
|
||||
continuePerKg: b.continuePerKg ?? 0,
|
||||
}))
|
||||
: [emptyBand(0)],
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
async function open(edit: boolean, row?: ExpressQuoteVO.Info) {
|
||||
await ensureMeta();
|
||||
isEdit.value = edit;
|
||||
if (edit && row) {
|
||||
editingId.value = row.id;
|
||||
form.code = row.code;
|
||||
form.name = row.name;
|
||||
form.carrierCode = row.carrierCode;
|
||||
form.billingMode = row.billingMode;
|
||||
form.status = row.status;
|
||||
form.remark = row.remark || '';
|
||||
mode.value = row.billingMode;
|
||||
const detail = await getExpressQuoteDetailApi(row.id);
|
||||
form.code = detail.code;
|
||||
form.name = detail.name;
|
||||
form.carrierCode = detail.carrierCode;
|
||||
form.billingMode = detail.billingMode;
|
||||
form.status = detail.status;
|
||||
form.remark = detail.remark || '';
|
||||
fillFromVersion(detail.currentVersion);
|
||||
} else {
|
||||
reset();
|
||||
}
|
||||
modalApi.setState({
|
||||
title: edit ? '编辑报价单' : '新建报价单',
|
||||
class: 'w-[640px]',
|
||||
class: form.billingMode === 'REGION_WEIGHT' ? 'w-[920px]' : 'w-[640px]',
|
||||
});
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
function addRegion() {
|
||||
form.regions.push({
|
||||
regionName: `分区${form.regions.length + 1}`,
|
||||
zoneLabel: '',
|
||||
provinces: [],
|
||||
isDefault: false,
|
||||
bands: [emptyBand(0)],
|
||||
});
|
||||
}
|
||||
|
||||
function removeRegion(idx: number) {
|
||||
if (form.regions.length <= 1) {
|
||||
message.warning('至少保留一个分区');
|
||||
return;
|
||||
}
|
||||
form.regions.splice(idx, 1);
|
||||
}
|
||||
|
||||
function addBand(region: RegionRow) {
|
||||
const last = region.bands[region.bands.length - 1];
|
||||
const nextFrom =
|
||||
last?.weightToG != null ? last.weightToG + 1 : (last?.weightFromG ?? 0) + 1000;
|
||||
region.bands.push(emptyBand(nextFrom));
|
||||
}
|
||||
|
||||
function removeBand(region: RegionRow, idx: number) {
|
||||
if (region.bands.length <= 1) {
|
||||
message.warning('每分区至少一条重量带');
|
||||
return;
|
||||
}
|
||||
region.bands.splice(idx, 1);
|
||||
}
|
||||
|
||||
function buildVersion(): ExpressQuoteDTO.VersionUpsert {
|
||||
const version: ExpressQuoteDTO.VersionUpsert = {
|
||||
effectiveFrom: form.effectiveFrom,
|
||||
volumeDivisor: form.volumeDivisor,
|
||||
useVolumetric: form.useVolumetric ? 1 : 0,
|
||||
weightRound: form.weightRound,
|
||||
};
|
||||
if (form.billingMode === 'FLAT') {
|
||||
version.flatAmount = form.flatAmount;
|
||||
@@ -135,17 +238,23 @@ function buildVersion(): ExpressQuoteDTO.VersionUpsert {
|
||||
version.pricePerKg = form.pricePerKg;
|
||||
version.minAmount = form.minAmount;
|
||||
} else {
|
||||
version.regions = [
|
||||
{
|
||||
regionName: form.regionName || '默认区',
|
||||
provinces: form.regionProvinces,
|
||||
isDefault: 1,
|
||||
firstWeightG: form.firstWeightG,
|
||||
firstAmount: form.firstAmount,
|
||||
additionalWeightG: form.additionalWeightG,
|
||||
additionalAmount: form.additionalAmount,
|
||||
},
|
||||
];
|
||||
version.regions = form.regions.map((r, i) => ({
|
||||
regionName: r.regionName.trim() || `分区${i + 1}`,
|
||||
zoneLabel: r.zoneLabel.trim() || undefined,
|
||||
provinces: r.provinces,
|
||||
isDefault: r.isDefault ? 1 : 0,
|
||||
sortOrder: i,
|
||||
bands: r.bands.map((b, bi) => ({
|
||||
weightFromG: b.weightFromG ?? 0,
|
||||
weightToG: b.weightToG,
|
||||
priceMode: b.priceMode,
|
||||
flatAmount: b.priceMode === 'FLAT_TICKET' ? b.flatAmount : undefined,
|
||||
firstWeightG: b.priceMode === 'FIRST_PLUS_KG' ? b.firstWeightG : undefined,
|
||||
firstAmount: b.priceMode === 'FIRST_PLUS_KG' ? b.firstAmount : undefined,
|
||||
continuePerKg: b.priceMode === 'FIRST_PLUS_KG' ? b.continuePerKg : undefined,
|
||||
sortOrder: bi,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
return version;
|
||||
}
|
||||
@@ -155,6 +264,14 @@ async function handleSubmit() {
|
||||
message.warning('请填写编码与名称');
|
||||
return;
|
||||
}
|
||||
if (isRegion.value) {
|
||||
for (const r of form.regions) {
|
||||
if (!r.bands.length) {
|
||||
message.warning(`分区「${r.regionName}」至少一条重量带`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
modalApi.setState({ confirming: true });
|
||||
try {
|
||||
if (isEdit.value && editingId.value) {
|
||||
@@ -164,7 +281,6 @@ async function handleSubmit() {
|
||||
status: form.status,
|
||||
remark: form.remark || undefined,
|
||||
});
|
||||
// 编辑时可追加版本
|
||||
if (form.effectiveFrom) {
|
||||
await upsertExpressQuoteVersionApi(editingId.value, buildVersion());
|
||||
}
|
||||
@@ -193,7 +309,7 @@ defineExpose({ open });
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<Form layout="vertical" class="max-h-[70vh] overflow-y-auto px-1">
|
||||
<Form layout="vertical" class="max-h-[75vh] overflow-y-auto px-1">
|
||||
<FormItem v-if="!isEdit" label="报价编码" required>
|
||||
<Input v-model:value="form.code" />
|
||||
</FormItem>
|
||||
@@ -214,7 +330,7 @@ defineExpose({ open });
|
||||
:options="[
|
||||
{ value: 'FLAT', label: '一口价 FLAT' },
|
||||
{ value: 'PER_KG', label: '按千克 PER_KG' },
|
||||
{ value: 'REGION_WEIGHT', label: '分区首重续重' },
|
||||
{ value: 'REGION_WEIGHT', label: '分区×重量带' },
|
||||
]"
|
||||
/>
|
||||
</FormItem>
|
||||
@@ -258,42 +374,109 @@ defineExpose({ open });
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="isRegion">
|
||||
<FormItem label="分区名">
|
||||
<Input v-model:value="form.regionName" />
|
||||
</FormItem>
|
||||
<FormItem label="覆盖省份">
|
||||
<Select
|
||||
v-model:value="form.regionProvinces"
|
||||
mode="multiple"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:options="provinces.map((p) => ({ value: p.code, label: p.name }))"
|
||||
placeholder="可多选;设为默认分区"
|
||||
/>
|
||||
</FormItem>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<FormItem label="首重(克)">
|
||||
<InputNumber v-model:value="form.firstWeightG" :min="1" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="首重价">
|
||||
<InputNumber v-model:value="form.firstAmount" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="续重步进(克)">
|
||||
<InputNumber v-model:value="form.additionalWeightG" :min="1" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="续重价">
|
||||
<InputNumber v-model:value="form.additionalAmount" :min="0" class="w-full" />
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<span class="text-sm text-muted-foreground">目的分区 × 重量带(对齐承运商报价矩阵)</span>
|
||||
<Button size="small" type="dashed" @click="addRegion">添加分区</Button>
|
||||
</div>
|
||||
<div
|
||||
v-for="(region, ri) in form.regions"
|
||||
:key="ri"
|
||||
class="mb-3 rounded border border-border p-3"
|
||||
>
|
||||
<div class="mb-2 flex items-start justify-between gap-2">
|
||||
<div class="grid flex-1 grid-cols-3 gap-2">
|
||||
<FormItem label="分区名" class="mb-0">
|
||||
<Input v-model:value="region.regionName" />
|
||||
</FormItem>
|
||||
<FormItem label="价区标签" class="mb-0">
|
||||
<Input v-model:value="region.zoneLabel" placeholder="一类/二类…" />
|
||||
</FormItem>
|
||||
<FormItem label="默认分区" class="mb-0">
|
||||
<Switch v-model:checked="region.isDefault" />
|
||||
</FormItem>
|
||||
</div>
|
||||
<Button size="small" danger type="link" @click="removeRegion(ri)">删除</Button>
|
||||
</div>
|
||||
<FormItem label="目的地(省或市)" class="mb-2">
|
||||
<Select
|
||||
v-model:value="region.provinces"
|
||||
mode="tags"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:options="provinceOptions"
|
||||
placeholder="选省或输入市名如深圳市"
|
||||
/>
|
||||
</FormItem>
|
||||
<div class="mb-1 flex items-center justify-between">
|
||||
<span class="text-xs text-muted-foreground">重量带</span>
|
||||
<Button size="small" type="link" @click="addBand(region)">加带</Button>
|
||||
</div>
|
||||
<div
|
||||
v-for="(band, bi) in region.bands"
|
||||
:key="bi"
|
||||
class="mb-2 grid grid-cols-12 items-end gap-2 rounded bg-muted/40 p-2"
|
||||
>
|
||||
<FormItem label="从(克)" class="col-span-2 mb-0">
|
||||
<InputNumber v-model:value="band.weightFromG" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="到(克)" class="col-span-2 mb-0">
|
||||
<InputNumber
|
||||
v-model:value="band.weightToG"
|
||||
:min="0"
|
||||
class="w-full"
|
||||
placeholder="空=无上限"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="方式" class="col-span-3 mb-0">
|
||||
<Select
|
||||
v-model:value="band.priceMode"
|
||||
:options="[
|
||||
{ value: 'FLAT_TICKET', label: '元/票' },
|
||||
{ value: 'FIRST_PLUS_KG', label: '首重+续重/kg' },
|
||||
]"
|
||||
/>
|
||||
</FormItem>
|
||||
<template v-if="band.priceMode === 'FLAT_TICKET'">
|
||||
<FormItem label="元/票" class="col-span-3 mb-0">
|
||||
<InputNumber v-model:value="band.flatAmount" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
</template>
|
||||
<template v-else>
|
||||
<FormItem label="首重克" class="col-span-1 mb-0">
|
||||
<InputNumber v-model:value="band.firstWeightG" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="首重价" class="col-span-2 mb-0">
|
||||
<InputNumber v-model:value="band.firstAmount" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="续重元/kg" class="col-span-2 mb-0">
|
||||
<InputNumber v-model:value="band.continuePerKg" :min="0" class="w-full" />
|
||||
</FormItem>
|
||||
</template>
|
||||
<div class="col-span-2 flex justify-end pb-1">
|
||||
<Button size="small" type="link" danger @click="removeBand(region, bi)">
|
||||
删带
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<FormItem label="启用体积重">
|
||||
<Switch v-model:checked="form.useVolumetric" />
|
||||
</FormItem>
|
||||
<FormItem label="体积重除数">
|
||||
<InputNumber v-model:value="form.volumeDivisor" :min="1" class="w-full" />
|
||||
</FormItem>
|
||||
<FormItem label="计费重取整">
|
||||
<Select
|
||||
v-model:value="form.weightRound"
|
||||
:options="[
|
||||
{ value: 'NONE', label: '不取整' },
|
||||
{ value: 'CEIL_KG', label: '向上整千克' },
|
||||
]"
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
<FormItem label="备注">
|
||||
<Input.TextArea v-model:value="form.remark" :rows="2" />
|
||||
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
<script lang="ts" setup>
|
||||
import type {
|
||||
ExpressQuoteImportDTO,
|
||||
ExpressQuoteImportVO,
|
||||
ExpressQuoteVO,
|
||||
} from '#/api/ec/express-quote';
|
||||
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import type { UploadFile } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
Select,
|
||||
Upload,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
commitExpressQuoteImportApi,
|
||||
getEnabledExpressQuotesApi,
|
||||
getExpressCarriersApi,
|
||||
previewExpressQuoteImportApi,
|
||||
} from '#/api/ec/express-quote';
|
||||
|
||||
const emit = defineEmits<{ success: [] }>();
|
||||
|
||||
const carriers = ref<ExpressQuoteVO.CarrierOption[]>([]);
|
||||
const quotes = ref<ExpressQuoteVO.Info[]>([]);
|
||||
const fileList = ref<UploadFile[]>([]);
|
||||
const selectedFile = ref<File | null>(null);
|
||||
const preview = ref<ExpressQuoteImportVO.Preview | null>(null);
|
||||
const submitting = ref(false);
|
||||
|
||||
const form = reactive({
|
||||
mode: 'CREATE' as ExpressQuoteImportDTO.Commit['mode'],
|
||||
quoteId: undefined as number | undefined,
|
||||
carrierCode: '',
|
||||
code: '',
|
||||
name: '',
|
||||
effectiveFrom: new Date().toISOString().slice(0, 10),
|
||||
});
|
||||
|
||||
const canCommit = computed(
|
||||
() =>
|
||||
!!selectedFile.value &&
|
||||
!!preview.value?.success &&
|
||||
(form.mode === 'CREATE'
|
||||
? !!form.code.trim() && !!form.name.trim() && !!form.carrierCode
|
||||
: !!form.quoteId),
|
||||
);
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
onConfirm: handleCommit,
|
||||
onOpenChange: (open) => {
|
||||
if (!open) reset();
|
||||
},
|
||||
});
|
||||
|
||||
function reset() {
|
||||
fileList.value = [];
|
||||
selectedFile.value = null;
|
||||
preview.value = null;
|
||||
form.mode = 'CREATE';
|
||||
form.quoteId = undefined;
|
||||
form.carrierCode = '';
|
||||
form.code = '';
|
||||
form.name = '';
|
||||
form.effectiveFrom = new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
async function open() {
|
||||
if (!carriers.value.length) {
|
||||
carriers.value = await getExpressCarriersApi();
|
||||
}
|
||||
if (!quotes.value.length) {
|
||||
quotes.value = await getEnabledExpressQuotesApi();
|
||||
}
|
||||
reset();
|
||||
modalApi.setState({ title: '导入报价单', class: 'w-[720px]' });
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
async function onFileChange(info: { fileList: UploadFile[] }) {
|
||||
fileList.value = info.fileList.slice(-1);
|
||||
const raw = fileList.value[0]?.originFileObj;
|
||||
selectedFile.value = raw ?? null;
|
||||
preview.value = null;
|
||||
if (!raw) return;
|
||||
try {
|
||||
modalApi.setState({ confirming: true });
|
||||
const result = await previewExpressQuoteImportApi(raw);
|
||||
preview.value = result;
|
||||
if (result.carrierCode) form.carrierCode = result.carrierCode;
|
||||
if (result.code) form.code = result.code;
|
||||
if (result.name) form.name = result.name;
|
||||
if (result.effectiveFrom) form.effectiveFrom = result.effectiveFrom;
|
||||
if (!result.success) {
|
||||
message.warning('解析存在错误,请修正表格后重试');
|
||||
} else {
|
||||
message.success(
|
||||
`解析成功:${result.regionCount} 分区 / ${result.destinationCount} 目的地`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
preview.value = null;
|
||||
} finally {
|
||||
modalApi.setState({ confirming: false });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCommit() {
|
||||
if (!selectedFile.value || !canCommit.value) {
|
||||
message.warning('请先上传可解析的文件并补全必填项');
|
||||
return;
|
||||
}
|
||||
submitting.value = true;
|
||||
modalApi.setState({ confirming: true });
|
||||
try {
|
||||
const params: ExpressQuoteImportDTO.Commit = {
|
||||
mode: form.mode,
|
||||
effectiveFrom: form.effectiveFrom,
|
||||
};
|
||||
if (form.mode === 'CREATE') {
|
||||
params.carrierCode = form.carrierCode;
|
||||
params.code = form.code.trim();
|
||||
params.name = form.name.trim();
|
||||
} else {
|
||||
params.quoteId = form.quoteId;
|
||||
if (form.carrierCode) params.carrierCode = form.carrierCode;
|
||||
if (form.name.trim()) params.name = form.name.trim();
|
||||
}
|
||||
await commitExpressQuoteImportApi(selectedFile.value, params);
|
||||
message.success('导入成功');
|
||||
modalApi.close();
|
||||
emit('success');
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
modalApi.setState({ confirming: false });
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :confirm-disabled="!canCommit || submitting">
|
||||
<Form layout="vertical" class="max-h-[75vh] overflow-y-auto px-1">
|
||||
<FormItem label="Excel 文件" required>
|
||||
<Upload
|
||||
:file-list="fileList"
|
||||
:before-upload="() => false"
|
||||
accept=".xlsx,.xls"
|
||||
:max-count="1"
|
||||
@change="onFileChange"
|
||||
>
|
||||
<Button>选择文件</Button>
|
||||
</Upload>
|
||||
<div class="mt-1 text-xs text-muted-foreground">
|
||||
支持标准模板或承运商矩阵;「发/转单」文案与无价格行会跳过并警告
|
||||
</div>
|
||||
</FormItem>
|
||||
|
||||
<Alert
|
||||
v-if="preview && !preview.success"
|
||||
type="error"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
message="解析失败"
|
||||
:description="(preview.errors || []).join('\n')"
|
||||
/>
|
||||
<Alert
|
||||
v-if="preview?.success"
|
||||
type="success"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
:message="`可导入:${preview.regionCount} 分区,${preview.destinationCount} 目的地,共 ${preview.bandCount} 条重量带`"
|
||||
/>
|
||||
<Alert
|
||||
v-if="preview?.warnings?.length"
|
||||
type="warning"
|
||||
show-icon
|
||||
class="mb-3 whitespace-pre-wrap"
|
||||
:message="`已跳过 ${preview.warnings.length} 处,请核对`"
|
||||
:description="preview.warnings.join('\n')"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="preview?.regions?.length"
|
||||
class="mb-3 max-h-40 overflow-y-auto rounded border border-border p-2 text-xs"
|
||||
>
|
||||
<div v-for="(r, i) in preview.regions" :key="i" class="mb-1">
|
||||
<span class="font-medium">{{ r.regionName }}</span>
|
||||
<span v-if="r.zoneLabel" class="text-muted-foreground">
|
||||
({{ r.zoneLabel }})
|
||||
</span>
|
||||
:{{ (r.destinations || []).join('、') }} · {{ r.bandCount }} 带
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormItem label="导入方式" required>
|
||||
<Select
|
||||
v-model:value="form.mode"
|
||||
:options="[
|
||||
{ value: 'CREATE', label: '新建报价单' },
|
||||
{ value: 'APPEND_VERSION', label: '追加到已有报价(同日覆盖版本)' },
|
||||
]"
|
||||
/>
|
||||
</FormItem>
|
||||
|
||||
<FormItem v-if="form.mode === 'APPEND_VERSION'" label="目标报价" required>
|
||||
<Select
|
||||
v-model:value="form.quoteId"
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:options="
|
||||
quotes.map((q) => ({
|
||||
value: q.id,
|
||||
label: `${q.code} · ${q.name}`,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</FormItem>
|
||||
|
||||
<template v-if="form.mode === 'CREATE'">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<FormItem label="承运商" required>
|
||||
<Select
|
||||
v-model:value="form.carrierCode"
|
||||
:options="carriers.map((c) => ({ value: c.code, label: c.name }))"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="生效日" required>
|
||||
<Input v-model:value="form.effectiveFrom" placeholder="yyyy-MM-dd" />
|
||||
</FormItem>
|
||||
</div>
|
||||
<FormItem label="报价编码" required>
|
||||
<Input v-model:value="form.code" />
|
||||
</FormItem>
|
||||
<FormItem label="报价名称" required>
|
||||
<Input v-model:value="form.name" />
|
||||
</FormItem>
|
||||
</template>
|
||||
<FormItem v-else label="生效日" required>
|
||||
<Input v-model:value="form.effectiveFrom" placeholder="yyyy-MM-dd" />
|
||||
</FormItem>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -13,6 +13,7 @@ import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteExpressQuoteApi,
|
||||
downloadExpressQuoteTemplateApi,
|
||||
getExpressQuotePageApi,
|
||||
} from '#/api/ec/express-quote';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
@@ -21,7 +22,9 @@ import {
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
|
||||
import ExpressQuoteDetailDrawer from './components/ExpressQuoteDetailDrawer.vue';
|
||||
import ExpressQuoteFormModal from './components/ExpressQuoteFormModal.vue';
|
||||
import ExpressQuoteImportModal from './components/ExpressQuoteImportModal.vue';
|
||||
|
||||
defineOptions({ name: 'ExpressQuoteManagement' });
|
||||
|
||||
@@ -30,6 +33,12 @@ const loading = ref(false);
|
||||
const formModalRef = ref<InstanceType<typeof ExpressQuoteFormModal> | null>(
|
||||
null,
|
||||
);
|
||||
const importModalRef = ref<InstanceType<typeof ExpressQuoteImportModal> | null>(
|
||||
null,
|
||||
);
|
||||
const detailDrawerRef = ref<InstanceType<
|
||||
typeof ExpressQuoteDetailDrawer
|
||||
> | null>(null);
|
||||
const searchForm = ref({
|
||||
keywords: '',
|
||||
billingMode: undefined as string | undefined,
|
||||
@@ -38,6 +47,7 @@ const searchForm = ref({
|
||||
const gridReloadRef = ref<(() => void) | null>(null);
|
||||
|
||||
const actionCodes = [
|
||||
'ec:express-quote:read',
|
||||
'ec:express-quote:create',
|
||||
'ec:express-quote:update',
|
||||
'ec:express-quote:delete',
|
||||
@@ -62,7 +72,7 @@ const actionColumn: NonNullable<
|
||||
VxeGridProps<ExpressQuoteVO.Info>['columns']
|
||||
>[number] = {
|
||||
title: '操作',
|
||||
minWidth: 160,
|
||||
minWidth: 220,
|
||||
fixed: 'right' as const,
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
@@ -169,17 +179,27 @@ async function handleDelete(row: ExpressQuoteVO.Info) {
|
||||
<Page title="快递报价" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
公司级报价单(可多仓共用);支持一口价 / 按 kg / 分区首重续重;版本按生效日 as-of
|
||||
公司级报价单(可多仓共用);支持一口价 / 按 kg / 分区×重量带;版本按生效日 as-of
|
||||
</div>
|
||||
</template>
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<PermissionGate code="ec:express-quote:create">
|
||||
<Button type="primary" @click="formModalRef?.open(false)">
|
||||
<PlusIcon />
|
||||
新建报价
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
<Space>
|
||||
<PermissionGate code="ec:express-quote:read">
|
||||
<Button @click="downloadExpressQuoteTemplateApi()">
|
||||
下载模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="ec:express-quote:create">
|
||||
<Button @click="importModalRef?.open()">导入</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="ec:express-quote:create">
|
||||
<Button type="primary" @click="formModalRef?.open(false)">
|
||||
<PlusIcon />
|
||||
新建报价
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
<template #effective="{ row }: { row: ExpressQuoteVO.Info }">
|
||||
{{ row.currentVersion?.effectiveFrom || '—' }}
|
||||
@@ -194,6 +214,11 @@ async function handleDelete(row: ExpressQuoteVO.Info) {
|
||||
#action="{ row }: { row: ExpressQuoteVO.Info }"
|
||||
>
|
||||
<Space>
|
||||
<PermissionGate code="ec:express-quote:read">
|
||||
<Button size="small" @click="detailDrawerRef?.open(row.id)">
|
||||
详情
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="ec:express-quote:update">
|
||||
<Button size="small" @click="formModalRef?.open(true, row)">
|
||||
编辑/调价
|
||||
@@ -208,5 +233,10 @@ async function handleDelete(row: ExpressQuoteVO.Info) {
|
||||
</template>
|
||||
</Grid>
|
||||
<ExpressQuoteFormModal ref="formModalRef" @success="gridApi.reload()" />
|
||||
<ExpressQuoteImportModal
|
||||
ref="importModalRef"
|
||||
@success="gridApi.reload()"
|
||||
/>
|
||||
<ExpressQuoteDetailDrawer ref="detailDrawerRef" />
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user