Commit a6ae27b7 by chenxi

优加门店上架导入

1 parent 68d478d8
Showing 30 changed files with 1188 additions and 183 deletions
...@@ -32,7 +32,13 @@ public final class CommonConstants { ...@@ -32,7 +32,13 @@ public final class CommonConstants {
/** 超级管理员角色编码 */ /** 超级管理员角色编码 */
public static final String ROLE_SYS_ADMIN = "SYS_ADMIN"; public static final String ROLE_SYS_ADMIN = "SYS_ADMIN";
/** 优加财务经理角色编码 */ /** 优加商务经理角色编码(门店上架第 1 级审批) */
public static final String ROLE_YJ_BIZ_MGR = "YJ_BIZ_MGR";
/** 优加商务经理角色名称(提交时按名称查 sys_role 取 role_code) */
public static final String ROLE_NAME_YJ_BIZ_MGR = "优加商务经理";
/** 优加财务经理角色编码(门店上架第 2 级审批) */
public static final String ROLE_YJ_FINANCE_MGR = "YJ_FINANCE_MGR"; public static final String ROLE_YJ_FINANCE_MGR = "YJ_FINANCE_MGR";
/** 线上运营角色编码 */ /** 线上运营角色编码 */
......
...@@ -7,24 +7,77 @@ import java.util.Optional; ...@@ -7,24 +7,77 @@ import java.util.Optional;
/** /**
* 业务场景字典(门店上架唯一项之一)。 * 业务场景字典(门店上架唯一项之一)。
*
* <p>与 D+ 侧 {@code cn.com.glsx.dj.smartcarlife.enums.BaseSceneEnum} 一一对应:
* {@code label} = D+ 枚举的 {@code desc},{@code baseSceneCode} = D+ 的 {@code baseSceneCode}。
* 落库 {@code store_listing.business_scene} 存的是 <b>baseSceneCode</b>,
* 对外展示时用 {@link #ofCode(String)} 反查 {@link #getLabel()}。</p>
*
* <p>来源基线:{@code v5.8.7/rpc-smartcarlife/rpc-dj-smartcarlife-api/.../enums/BaseSceneEnum.java}</p>
*/ */
@Getter @Getter
public enum BusinessSceneEnum { public enum BusinessSceneEnum {
AFTER_SALE_MEMBER("售后会员权益升级"), /* biz_type = 1 */
PRE_SALE_EXTENDED_WARRANTY("售前延保"); QUALITY_UPGRADE("精品升级", "100101"),
NEW_CAR_DELIVERY("次新车升配", "100102"),
AFTER_SALE("售后众筹", "100103"),
/* biz_type = 2 */
PRE_MEMBER_UPGRADE("售前会员权益升级", "110101"),
POST_MEMBER_UPGRADE("售后会员权益升级", "110102"),
PRE_EXTEND_WARRANTY("售前延保", "110201"),
POST_EXTEND_WARRANTY("售后延保", "110202"),
/* biz_type = 6 */
USED_CAR_RECYCLE("二手车收车", "120101");
/** 业务场景文本(= D+ desc),模板 / 前端展示用 */
private final String label; private final String label;
BusinessSceneEnum(String label) { /** 业务场景编码(= D+ baseSceneCode),落库与对接 D+ 用 */
private final String baseSceneCode;
BusinessSceneEnum(String label, String baseSceneCode) {
this.label = label; this.label = label;
this.baseSceneCode = baseSceneCode;
} }
/** 按展示文本(Excel / 前端提交值)匹配 */
public static Optional<BusinessSceneEnum> ofLabel(String label) { public static Optional<BusinessSceneEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst(); if (label == null) {
return Optional.empty();
}
String text = label.trim();
return Arrays.stream(values()).filter(e -> e.label.equals(text)).findFirst();
} }
/** 按落库编码匹配 */
public static Optional<BusinessSceneEnum> ofCode(String baseSceneCode) {
if (baseSceneCode == null) {
return Optional.empty();
}
String code = baseSceneCode.trim();
return Arrays.stream(values()).filter(e -> e.baseSceneCode.equals(code)).findFirst();
}
/** 文本是否合法(导入校验用) */
public static boolean isValid(String label) { public static boolean isValid(String label) {
return ofLabel(label).isPresent(); return ofLabel(label).isPresent();
} }
/** 编码是否合法 */
public static boolean isValidCode(String baseSceneCode) {
return ofCode(baseSceneCode).isPresent();
}
/** 编码 → 文本;匹配不到时原样返回,保证展示不丢数据 */
public static String labelOfCode(String baseSceneCode) {
return ofCode(baseSceneCode).map(BusinessSceneEnum::getLabel).orElse(baseSceneCode);
}
/** 文本 → 编码;匹配不到时返回 null(由调用方决定报错文案) */
public static String codeOfLabel(String label) {
return ofLabel(label).map(BusinessSceneEnum::getBaseSceneCode).orElse(null);
}
} }
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 产品分类字典,多级分类以「-」连接。
*/
@Getter
public enum ProductCategoryEnum {
FILM_ORIGINAL("太阳膜-原厂"),
COATING_ORIGINAL("车衣-原厂"),
ACCESSORY_TRAY("精品-小桌板"),
ACCESSORY_FLOOR_MAT("精品-脚垫"),
PEDAL("踏板"),
COATING_AFTERMARKET("车衣-副厂");
private final String label;
ProductCategoryEnum(String label) {
this.label = label;
}
public static Optional<ProductCategoryEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst();
}
public static boolean isValid(String label) {
return ofLabel(label).isPresent();
}
}
...@@ -8,11 +8,15 @@ import java.util.Optional; ...@@ -8,11 +8,15 @@ import java.util.Optional;
/** /**
* 门店上架记录状态。 * 门店上架记录状态。
* *
* <p>仅 APPROVED(已生效)可对外展示;状态由系统自动流转,不提供人工改状态入口。</p> * <p>状态机:{@code DRAFT(导入产生)→ PENDING(提交后待审批)→ APPROVED(审批通过后生效)}。</p>
*
* <p>仅 APPROVED(已生效)可对外展示;DRAFT 是「操作态」,<b>不出现在任何列表查询中</b>;
* 状态由系统自动流转,不提供人工改状态入口。</p>
*/ */
@Getter @Getter
public enum StoreStatusEnum { public enum StoreStatusEnum {
DRAFT("DRAFT", "草稿", "info"),
PENDING("PENDING", "待审批", "warning"), PENDING("PENDING", "待审批", "warning"),
APPROVED("APPROVED", "已生效", "success"), APPROVED("APPROVED", "已生效", "success"),
REJECTED("REJECTED", "已打回", "danger"), REJECTED("REJECTED", "已打回", "danger"),
...@@ -47,4 +51,14 @@ public enum StoreStatusEnum { ...@@ -47,4 +51,14 @@ public enum StoreStatusEnum {
public boolean resubmittable() { public boolean resubmittable() {
return this == REJECTED || this == REVOKED; return this == REJECTED || this == REVOKED;
} }
/** 草稿:导入产生、尚未提交,列表查询需整体排除 */
public boolean draft() {
return this == DRAFT;
}
/** 未完结(草稿 / 待审批):同一「门店 + 场景」不允许多条同时存在 */
public boolean unfinished() {
return this == DRAFT || this == PENDING;
}
} }
...@@ -136,7 +136,7 @@ public class OssStsService { ...@@ -136,7 +136,7 @@ public class OssStsService {
* 生成最小权限策略:仅允许写入该 bucket 的该目录。 * 生成最小权限策略:仅允许写入该 bucket 的该目录。
*/ */
public String buildPolicy(String bucket, String dir) { public String buildPolicy(String bucket, String dir) {
String resource = "acs:oss:*:*:" String resources = "acs:oss:*:*:"
+ (StringUtils.hasText(dir) ? bucket + "/" + dir : bucket) + "/*"; + (StringUtils.hasText(dir) ? bucket + "/" + dir : bucket) + "/*";
return """ return """
{ {
...@@ -159,7 +159,7 @@ public class OssStsService { ...@@ -159,7 +159,7 @@ public class OssStsService {
} }
] ]
} }
""".formatted(resource).trim(); """.formatted(resources).trim();
} }
private OssCredentialsVO readCache(String cacheKey) { private OssCredentialsVO readCache(String cacheKey) {
......
package com.youjia.framework.rop;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youjia.common.core.ResultCode;
import com.youjia.common.exception.BusinessException;
import com.youjia.framework.util.RopHttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* D+(嘀加)ROP 网关出站客户端。
*
* <p>职责:按应用取地址与凭据 → 加签 → 调网关 → 解析响应 → 抛业务异常。</p>
*
* <p><b>无会话</b>:入站的三个方法({@code serviceMerchant.listWithPage}、
* {@code goodsCategoryConfiguration.queryAll}、{@code oaapproval.store.approve.pageQuery})
* 在 D+ 侧已声明 {@code needInSession=NO},因此这里<b>不登录、不传 sessionId</b>,
* 也<b>不依赖 Redis</b>。</p>
*
* <p><b>凭据按应用区分</b>:ROP 每个 {@code rop-*} 工程有各自的 appKey / appSecret,
* 由 {@link RopProperties#resolveAppKey(String)} / {@link RopProperties#resolveAppSecret(String)} 取用。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class RopClient {
/** 响应体中的候选载荷字段名 */
private static final String[] RESULT_KEYS = {"result", "data"};
/** 响应体中的候选错误信息字段名 */
private static final String[] MESSAGE_KEYS = {"message", "msg", "errorMessage", "errMsg"};
/** 响应体中的候选错误码字段名 */
private static final String[] ERROR_CODE_KEYS = {"errorCode", "errCode", "errId"};
private final RopProperties properties;
private final ObjectMapper objectMapper;
private volatile SimpleClientHttpRequestFactory requestFactory;
// ------------------------------------------------------------ 对外 API
/**
* 调用 ROP 方法并返回响应根节点。
*
* @param app 应用编码,见 {@link RopProperties#APP_SMARTCARLIFE} / {@link RopProperties#APP_OAAPPROVAL}
* @param method ROP 方法名
* @param params 业务参数(可为 null)
* @return 响应 JSON 根节点
*/
public JsonNode invoke(String app, String method, MultiValueMap<String, String> params) {
if (!properties.isEnabled()) {
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口未启用(请在 Nacos 配置 youjia.rop.enabled=true)");
}
if (!properties.wellConfigured(app)) {
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口未配置:" + properties.missingConfigHint(app));
}
String url = properties.resolveUrl(app);
// 兜底值可能为空,RopHttpUtil 对空参数会做剔除,这里不再额外校验
String appKey = properties.resolveAppKey(app);
String secret = properties.resolveAppSecret(app);
MultiValueMap<String, String> all = new LinkedMultiValueMap<>();
if (params != null) {
all.putAll(params);
}
String body;
try {
body = RopHttpUtil.get(url, all, method, appKey, secret,
properties.getVersion(), properties.getLocale(), getRequestFactory());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
log.error("[ROP] 调用失败 app={} method={} url={} msg={}", app, method, url, e.getMessage(), e);
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口调用失败(" + method + "):" + e.getMessage());
}
log.debug("[ROP] app={} method={} resp={}", app, method, body);
return parseAndCheck(app, method, body);
}
/**
* 调用 ROP 方法并把 {@code result} 反序列化为指定类型。
*
* @param app 应用编码
* @param method ROP 方法名
* @param params 业务参数
* @param resultType 结果类型(支持泛型)
* @return 业务结果;响应成功但无结果时返回 {@code null}
*/
public <T> T invokeForResult(String app, String method,
MultiValueMap<String, String> params, TypeReference<T> resultType) {
JsonNode resultNode = findResultNode(invoke(app, method, params));
if (resultNode == null || resultNode.isNull()) {
return null;
}
try {
return objectMapper.convertValue(resultNode, resultType);
} catch (IllegalArgumentException e) {
log.error("[ROP] 结果反序列化失败 app={} method={} msg={}", app, method, e.getMessage(), e);
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口返回结构解析失败:" + e.getMessage());
}
}
/**
* 调用 ROP 方法并返回 {@code result} 节点。
*/
public JsonNode invokeForResultNode(String app, String method, MultiValueMap<String, String> params) {
return findResultNode(invoke(app, method, params));
}
// ------------------------------------------------------------ 内部实现
private JsonNode parseAndCheck(String app, String method, String body) {
if (!StringUtils.hasText(body)) {
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口无响应内容(" + method + ")");
}
JsonNode root;
try {
root = objectMapper.readTree(body);
} catch (Exception e) {
log.error("[ROP] 响应非 JSON app={} method={} body={}", app, method, body);
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口返回格式异常(" + method + ")");
}
JsonNode codeNode = root.get("code");
String code = codeNode == null || codeNode.isNull() ? null : codeNode.asText();
boolean success = code == null
|| properties.getSuccessCodes() == null
|| properties.getSuccessCodes().isEmpty()
|| properties.getSuccessCodes().contains(code);
if (!success) {
String message = firstText(root, MESSAGE_KEYS);
String errorCode = firstText(root, ERROR_CODE_KEYS);
log.warn("[ROP] 业务失败 app={} method={} code={} errorCode={} message={}",
app, method, code, errorCode, message);
throw new BusinessException(ResultCode.REMOTE_CALL_FAILED,
"D+ 接口返回失败:" + (StringUtils.hasText(message) ? message : code));
}
return root;
}
private JsonNode findResultNode(JsonNode root) {
if (root == null) {
return null;
}
for (String key : RESULT_KEYS) {
JsonNode node = root.get(key);
if (node != null && !node.isNull()) {
return node;
}
}
return null;
}
private String firstText(JsonNode root, String[] keys) {
for (String key : keys) {
JsonNode node = root.get(key);
if (node != null && !node.isNull() && StringUtils.hasText(node.asText())) {
return node.asText();
}
}
return null;
}
private SimpleClientHttpRequestFactory getRequestFactory() {
SimpleClientHttpRequestFactory factory = requestFactory;
if (factory == null) {
synchronized (this) {
factory = requestFactory;
if (factory == null) {
factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(properties.getConnectTimeoutMs());
factory.setReadTimeout(properties.getReadTimeoutMs());
requestFactory = factory;
}
}
}
return factory;
}
}
package com.youjia.framework.rop;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* D+ ROP 客户端装配:启用 {@link RopProperties}(前缀 {@code youjia.rop})。
*/
@Configuration
@EnableConfigurationProperties(RopProperties.class)
public class RopConfiguration {
}
package com.youjia.framework.rop;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* D+(嘀加)ROP 网关配置(前缀 {@code youjia.rop})。
*
* <p>ROP 按应用(每个 {@code rop-*} 工程)独立部署:{@code server.servlet.context-path} 不同,
* <b>appKey / appSecret 也不同</b>。因此按「应用编码 → {url, appKey, appSecret}」配置,
* 调用时用应用编码同时取地址与凭据。</p>
*
* <pre>
* youjia:
* rop:
* enabled: true
* version: 1.0.0
* apps:
* smartcarlife:
* url: http://192.168.1.127:8392/rop-dj-smartcarlife/router
* app-key: xxx
* app-secret: xxx
* oaapproval:
* url: http://192.168.1.127:8392/rop-dj-oaapproval/router
* app-key: yyy
* app-secret: yyy
* </pre>
*
* <p>顶层的 {@link #appKey} / {@link #appSecret} 是<b>兜底值</b>:某应用未单独配置时回落到它,
* 方便只有一套凭据的场景(也可不配)。</p>
*
* <p>三个入站调用({@code serviceMerchant.listWithPage} / {@code goodsCategoryConfiguration.queryAll} /
* {@code oaapproval.store.approve.pageQuery})在 D+ 侧已改为 {@code needInSession=NO},
* <b>不需要会话(sessionId)</b>,因此本配置不含任何账号 / 会话字段。</p>
*
* <p>appKey / appSecret 属敏感信息,只允许通过环境变量 / Nacos 注入,禁止硬编码进代码库。</p>
*/
@Data
@ConfigurationProperties(prefix = "youjia.rop")
public class RopProperties {
/** 应用编码:车生活(serviceMerchant / goodsCategoryConfiguration) */
public static final String APP_SMARTCARLIFE = "smartcarlife";
/** 应用编码:门店上架审批(store.approve.*) */
public static final String APP_OAAPPROVAL = "oaapproval";
/** 总开关;关闭后所有 ROP 调用直接抛「D+ 接口未配置」 */
private boolean enabled = false;
/** 兜底应用标识(各应用未单独配置 app-key 时使用) */
private String appKey;
/** 兜底应用密钥(MD5 加签用) */
private String appSecret;
/** 接口版本号 */
private String version = "1.0.0";
/** 区域 */
private String locale = "zh_CN";
/** 连接超时(毫秒) */
private int connectTimeoutMs = 3000;
/** 读取超时(毫秒) */
private int readTimeoutMs = 10000;
/** 成功码:ROP 响应体 {@code code} 命中其中之一视为成功(实测成功码为 "0") */
private List<String> successCodes = new ArrayList<>(List.of("0"));
/** 应用端点:应用编码 → {url, appKey, appSecret} */
private Map<String, AppEndpoint> apps = new LinkedHashMap<>();
/**
* 单个 ROP 应用的连接信息。
*/
@Data
public static class AppEndpoint {
/** 该 ROP 应用的完整调用地址,形如 {host}/rop-dj-xxx/router */
private String url;
/** 该应用专属 appKey;留空回落到 {@link RopProperties#appKey} */
private String appKey;
/** 该应用专属 appSecret;留空回落到 {@link RopProperties#appSecret} */
private String appSecret;
}
/**
* 取指定应用的网关地址。
*
* @param app 应用编码,见 {@link #APP_SMARTCARLIFE} / {@link #APP_OAAPPROVAL}
* @return 网关地址;未配置返回 {@code null}
*/
public String resolveUrl(String app) {
AppEndpoint endpoint = endpoint(app);
return endpoint == null ? null : endpoint.getUrl();
}
/**
* 取指定应用的 appKey:应用级优先,其次顶层兜底。
*/
public String resolveAppKey(String app) {
AppEndpoint endpoint = endpoint(app);
if (endpoint != null && StringUtils.hasText(endpoint.getAppKey())) {
return endpoint.getAppKey();
}
return appKey;
}
/**
* 取指定应用的 appSecret:应用级优先,其次顶层兜底。
*/
public String resolveAppSecret(String app) {
AppEndpoint endpoint = endpoint(app);
if (endpoint != null && StringUtils.hasText(endpoint.getAppSecret())) {
return endpoint.getAppSecret();
}
return appSecret;
}
/**
* 指定应用的配置是否齐备(开关 + 地址 + 凭据)。
*
* @param app 应用编码
*/
public boolean wellConfigured(String app) {
return enabled
&& StringUtils.hasText(resolveUrl(app))
&& StringUtils.hasText(resolveAppKey(app))
&& StringUtils.hasText(resolveAppSecret(app));
}
/**
* 该应用缺失的配置项(用于给出可操作的错误提示);齐备时返回空串。
*/
public String missingConfigHint(String app) {
List<String> missing = new ArrayList<>();
if (!enabled) {
missing.add("youjia.rop.enabled");
}
if (!StringUtils.hasText(resolveUrl(app))) {
missing.add("youjia.rop.apps." + app + ".url");
}
if (!StringUtils.hasText(resolveAppKey(app))) {
missing.add("youjia.rop.apps." + app + ".app-key");
}
if (!StringUtils.hasText(resolveAppSecret(app))) {
missing.add("youjia.rop.apps." + app + ".app-secret");
}
return String.join(" / ", missing);
}
private AppEndpoint endpoint(String app) {
return apps == null || !StringUtils.hasText(app) ? null : apps.get(app);
}
}
...@@ -3,11 +3,9 @@ package com.youjia.store.controller; ...@@ -3,11 +3,9 @@ package com.youjia.store.controller;
import com.youjia.common.core.Result; import com.youjia.common.core.Result;
import com.youjia.framework.security.AuthIgnore; import com.youjia.framework.security.AuthIgnore;
import com.youjia.framework.security.RequirePermission; import com.youjia.framework.security.RequirePermission;
import com.youjia.store.dto.StoreImportFailExportDTO; import com.youjia.store.dto.StoreImportCommitDTO;
import com.youjia.store.dto.StoreImportSubmitDTO;
import com.youjia.store.service.StoreImportService; import com.youjia.store.service.StoreImportService;
import com.youjia.store.vo.StoreImportCheckVO; import com.youjia.store.vo.StoreImportCheckVO;
import com.youjia.store.vo.StoreImportSpecVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
...@@ -23,7 +21,9 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -23,7 +21,9 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
/** /**
* 导入门店信息(P03,四步向导)。全部接口仅使用 GET / POST 两种请求方式。 * 导入门店信息(P03)。全部接口仅使用 GET / POST 两种请求方式。
*
* <p>链路:下载模板 → 导入(校验 + 落库草稿)→ 提交(草稿 → 待审批)。</p>
* *
* <p>权限码:{@code store:import:view / store:import:template / store:import:upload / store:import:submit}</p> * <p>权限码:{@code store:import:view / store:import:template / store:import:upload / store:import:submit}</p>
*/ */
...@@ -35,42 +35,38 @@ public class StoreImportController { ...@@ -35,42 +35,38 @@ public class StoreImportController {
private final StoreImportService storeImportService; private final StoreImportService storeImportService;
/* 导入规范与字典接口已停用(实现保留,暂不对外暴露)
@RequirePermission("store:import:view") @RequirePermission("store:import:view")
@Operation(summary = "导入规范与字典(列分组、文件级限制、五级校验说明、枚举字典)") @Operation(summary = "导入规范与字典(列分组、文件级限制、校验说明、枚举字典)")
@GetMapping("/spec") @GetMapping("/spec")T
public Result<StoreImportSpecVO> spec() { public Result<StoreImportSpecVO> spec() {
return Result.success(storeImportService.spec()); return Result.success(storeImportService.spec());
} }
*/
/** /**
* 模板下载是浏览器直链(a 标签 / window.open),无法携带令牌与签名头,因此免鉴权。 * 模板下载是浏览器直链(a 标签 / window.open),无法携带令牌与签名头,因此免鉴权。
* 若后续需要收敛权限,请前端改为 ajax(blob) 下载并去掉 {@link AuthIgnore}。 * 若后续需要收敛权限,请前端改为 ajax(blob) 下载并去掉 {@link AuthIgnore}。
*/ */
@AuthIgnore @AuthIgnore
@Operation(summary = "下载导入模板(V1.0.1 / 21 列,含示例 12 行)") @Operation(summary = "下载导入模板(V1.0.1 / 21 列,直接输出模板文件)")
@GetMapping("/template") @GetMapping("/template")
public void template(HttpServletResponse response) { public void template(HttpServletResponse response) {
storeImportService.writeTemplate(response); storeImportService.writeTemplate(response);
} }
@RequirePermission("store:import:upload") @RequirePermission("store:import:upload")
@Operation(summary = "上传文件并执行五级校验") @Operation(summary = "导入:上传文件 → 校验 → 落库草稿(失败时返回失败明细文件 URL,不落库)")
@PostMapping(value = "/check", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/check", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result<StoreImportCheckVO> check(@RequestPart("file") MultipartFile file) { public Result<StoreImportCheckVO> check(@RequestPart("file") MultipartFile file,
return Result.success(storeImportService.check(file)); @RequestPart(value = "remark", required = false) String remark) {
} return Result.success(storeImportService.check(file, remark));
@RequirePermission("store:import:view")
@Operation(summary = "下载校验失败明细(xlsx)")
@PostMapping("/fail-export")
public void failExport(@Valid @RequestBody StoreImportFailExportDTO dto, HttpServletResponse response) {
storeImportService.writeFailDetail(dto, response);
} }
@RequirePermission("store:import:submit") @RequirePermission("store:import:submit")
@Operation(summary = "确认数据并提交审批(单次导入 1 家门店)") @Operation(summary = "提交:把草稿记录提交为待审批(不重新解析文件)")
@PostMapping("/submit") @PostMapping("/submit")
public Result<Long> submit(@Valid @RequestBody StoreImportSubmitDTO dto) { public Result<StoreImportCheckVO> submit(@Valid @RequestBody StoreImportCommitDTO dto) {
return Result.success("已提交审批", storeImportService.submit(dto)); return Result.success("已提交审批", storeImportService.commit(dto));
} }
} }
package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 提交入库的门店上架记录入参(草稿 → 待审批)。
*
* <p>一次导入「一家门店 × N 个业务场景」会产生 N 条 {@code store_listing}(草稿),
* 前端拿到导入返回的 {@code listingIds} 后原样回传即可。</p>
*/
@Getter
@Setter
@Schema(description = "提交门店上架记录入参")
public class StoreImportCommitDTO {
@Schema(description = "导入返回的上架记录 ID 列表(同一门店的多个业务场景)")
@NotEmpty(message = "上架记录 ID 不能为空")
private List<Long> listingIds;
}
package com.youjia.store.dto;
import com.youjia.store.vo.StoreImportFailVO;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 下载失败明细入参。
*
* <p>与 {@code /store/import/submit} 保持一致的无状态设计:由前端回传第 2 步校验结果中的失败明细,
* 服务端按标准模板结构生成 xlsx,不额外缓存解析结果。</p>
*/
@Getter
@Setter
@Schema(description = "下载失败明细入参")
public class StoreImportFailExportDTO {
@Schema(description = "门店名称(用于文件名与表头)")
private String storeName;
@Schema(description = "门店商户号")
private String merchantNo;
@Schema(description = "业务场景")
private String businessScene;
@Schema(description = "校验失败明细")
@NotEmpty(message = "失败明细不能为空")
private List<StoreImportFailVO> failures = new ArrayList<>();
}
...@@ -7,37 +7,107 @@ import lombok.Setter; ...@@ -7,37 +7,107 @@ import lombok.Setter;
import java.math.BigDecimal; import java.math.BigDecimal;
/** /**
* 校验通过并完成系统转译后的产品分类行(同时作为提交审批的入参)。 * 产品分类行(校验通过并完成系统转译后的行,含 Excel 模板全部 21 列的映射)。
*
* <p>列为门店维度的字段(门店名称 / 商户号 / 业务场景 / 运营成本三项)在每一行上冗余携带,
* 便于前端直接渲染预览表格;落库时按「门店 × 业务场景」聚合。</p>
*/ */
@Getter @Getter
@Setter @Setter
@Schema(description = "校验通过的产品分类行") @Schema(description = "导入行(产品分类明细)")
public class StoreImportRowDTO { public class StoreImportRowDTO {
@Schema(description = "产品分类(已转译为系统字典标准名)") /* ---------------- 门店信息(第 1 ~ 3 列) ---------------- */
@Schema(description = "门店名称(营业执照全称)")
private String storeName;
@Schema(description = "门店商户号")
private String merchantNo;
@Schema(description = "业务场景(落库为 baseSceneCode,展示用 label)")
private String businessScene;
@Schema(description = "业务场景编码(D+ baseSceneCode,如 110102)")
private String businessSceneCode;
/* ---------------- 产品分类(第 4 列) ---------------- */
@Schema(description = "产品分类(系统字典标准名,可多级以「-」分隔)")
private String productCategory; private String productCategory;
@Schema(description = "产品分类 ID(D+ dj_car_life_goods_category_configuration.category_type)")
private Integer productCategoryId;
@Schema(description = "产品分类层级(D+ dj_car_life_goods_category_configuration.level,1 起)")
private Integer productCategoryLevel;
/* ---------------- 管理层市场费(第 5 ~ 10 列) ---------------- */
@Schema(description = "管理层市场费1计算模式")
private String marketFee1CalcMode; private String marketFee1CalcMode;
@Schema(description = "管理层市场费1计算方式")
private String marketFee1CalcWay; private String marketFee1CalcWay;
@Schema(description = "管理层市场费1数值")
private BigDecimal marketFee1Value; private BigDecimal marketFee1Value;
@Schema(description = "管理层市场费1数值单位:RATIO-比例 AMOUNT-金额(由计算方式推导)")
private String marketFee1Unit; private String marketFee1Unit;
@Schema(description = "管理层市场费2计算模式")
private String marketFee2CalcMode; private String marketFee2CalcMode;
@Schema(description = "管理层市场费2计算方式")
private String marketFee2CalcWay; private String marketFee2CalcWay;
@Schema(description = "管理层市场费2数值")
private BigDecimal marketFee2Value; private BigDecimal marketFee2Value;
@Schema(description = "管理层市场费2数值单位:RATIO-比例 AMOUNT-金额(由计算方式推导)")
private String marketFee2Unit; private String marketFee2Unit;
/* ---------------- 一线阳光(第 11 ~ 18 列) ---------------- */
@Schema(description = "一线阳光是否开启线上积分:1-是 0-否") @Schema(description = "一线阳光是否开启线上积分:1-是 0-否")
private Integer sunshine1OnlinePoint; private Integer sunshine1OnlinePoint;
@Schema(description = "一线阳光计算模式")
private String sunshine1CalcMode; private String sunshine1CalcMode;
@Schema(description = "一线阳光计算方式")
private String sunshine1CalcWay; private String sunshine1CalcWay;
@Schema(description = "一线阳光激励费")
private BigDecimal sunshine1Value; private BigDecimal sunshine1Value;
@Schema(description = "一线阳光激励费单位:RATIO-比例 AMOUNT-金额(由计算方式推导)")
private String sunshine1Unit; private String sunshine1Unit;
@Schema(description = "一线阳光2是否开启线上积分:1-是 0-否") @Schema(description = "一线阳光2是否开启线上积分:1-是 0-否")
private Integer sunshine2OnlinePoint; private Integer sunshine2OnlinePoint;
@Schema(description = "一线阳光2计算模式")
private String sunshine2CalcMode; private String sunshine2CalcMode;
@Schema(description = "一线阳光2计算方式")
private String sunshine2CalcWay; private String sunshine2CalcWay;
@Schema(description = "一线阳光2激励费")
private BigDecimal sunshine2Value; private BigDecimal sunshine2Value;
@Schema(description = "一线阳光2激励费单位:RATIO-比例 AMOUNT-金额(由计算方式推导)")
private String sunshine2Unit; private String sunshine2Unit;
/* ---------------- 运营成本(第 19 ~ 21 列,门店维度) ---------------- */
@Schema(description = "装修、设备总投入")
private BigDecimal costDecoration;
@Schema(description = "当月产生(房租、水电、耗材等)")
private BigDecimal costMonthly;
@Schema(description = "人工成本")
private BigDecimal costLabor;
} }
package com.youjia.store.dto; package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.math.BigDecimal;
import java.util.List;
/** /**
* 提交审批入参。一次提交 = 一家门店的一个业务场景。 * 导入门店信息入参。
*
* <p>文件通过 {@code multipart/form-data} 的 {@code file} part 传入,
* 本对象只承载除文件外的附加参数(业务数据全部从 Excel 中解析,不再由前端回传)。</p>
*/ */
@Getter @Getter
@Setter @Setter
@Schema(description = "提交审批入参") @Schema(description = "导入门店信息入参")
public class StoreImportSubmitDTO { public class StoreImportSubmitDTO {
@Schema(description = "所属组织 ID,决定数据可见范围")
@NotNull(message = "所属组织不能为空")
private Long orgId;
@Schema(description = "门店名称")
@NotBlank(message = "门店名称不能为空")
@Size(max = 50, message = "门店名称长度不能超过 50")
private String storeName;
@Schema(description = "门店商户号")
@NotBlank(message = "门店商户号不能为空")
@Size(max = 32, message = "门店商户号长度不能超过 32")
private String merchantNo;
@Schema(description = "业务场景")
@NotBlank(message = "业务场景不能为空")
private String businessScene;
@Schema(description = "装修、设备总投入")
private BigDecimal costDecoration;
@Schema(description = "当月产生费用")
private BigDecimal costMonthly;
@Schema(description = "人工成本")
private BigDecimal costLabor;
@Schema(description = "备注") @Schema(description = "备注")
@Size(max = 200, message = "备注长度不能超过 200") @Size(max = 200, message = "备注长度不能超过 200")
private String remark; private String remark;
@Schema(description = "产品分类行(校验通过行)")
@NotEmpty(message = "至少需要一行产品分类数据")
@Valid
private List<StoreImportRowDTO> rows;
} }
...@@ -35,9 +35,12 @@ public class StoreListing extends BaseEntity { ...@@ -35,9 +35,12 @@ public class StoreListing extends BaseEntity {
@Schema(description = "门店商户号") @Schema(description = "门店商户号")
private String merchantNo; private String merchantNo;
@Schema(description = "业务场景:售后会员权益升级 / 售前延保") @Schema(description = "业务场景文本(= D+ BaseSceneEnum.desc,如「售后会员权益升级」)")
private String businessScene; private String businessScene;
@Schema(description = "业务场景编码(= D+ BaseSceneEnum.baseSceneCode,如 110102)")
private String businessSceneCode;
@Schema(description = "产品分类数") @Schema(description = "产品分类数")
private Integer categoryCount; private Integer categoryCount;
......
...@@ -32,6 +32,12 @@ public class StoreListingItem extends BaseEntity { ...@@ -32,6 +32,12 @@ public class StoreListingItem extends BaseEntity {
@Schema(description = "产品分类") @Schema(description = "产品分类")
private String productCategory; private String productCategory;
@Schema(description = "产品分类 ID(D+ dj_car_life_goods_category_configuration.category_type)")
private Integer productCategoryId;
@Schema(description = "产品分类层级(D+ dj_car_life_goods_category_configuration.level,1 起)")
private Integer productCategoryLevel;
/* ---------------- 管理层市场费 ---------------- */ /* ---------------- 管理层市场费 ---------------- */
@Schema(description = "管理层市场费1计算模式") @Schema(description = "管理层市场费1计算模式")
......
...@@ -5,6 +5,7 @@ import com.alibaba.excel.event.AnalysisEventListener; ...@@ -5,6 +5,7 @@ import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.data.ReadCellData;
import com.youjia.store.constant.StoreTemplateConstants; import com.youjia.store.constant.StoreTemplateConstants;
import lombok.Getter; import lombok.Getter;
import org.springframework.util.StringUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
...@@ -13,19 +14,45 @@ import java.util.Map; ...@@ -13,19 +14,45 @@ import java.util.Map;
/** /**
* 导入文件读取监听器:收集表头(L2 表头级校验)与数据行。 * 导入文件读取监听器:收集表头(L2 表头级校验)与数据行。
*
* <p>数据区裁剪规则(模板自带的示例行与填写说明行必须排除):</p>
* <ol>
* <li><b>说明行</b>:前 4 列任一开始于「请输入」→ 跳过(模板第 16 行的 4 段提示文案);</li>
* <li><b>首个全空行</b>:视为数据区结束,其后所有行忽略;</li>
* <li><b>示例行未替换</b>:门店名称为「营业执照全称」或商户号为「xxxxxx」→ 记录标记,
* 由校验器给出「请替换示例数据」的特殊提示(不静默通过)。</li>
* </ol>
*/ */
@Getter @Getter
public class StoreImportExcelListener extends AnalysisEventListener<StoreImportExcelRow> { public class StoreImportExcelListener extends AnalysisEventListener<StoreImportExcelRow> {
/** 说明行前缀 */
private static final String INSTRUCTION_PREFIX = "请输入";
/** 模板示例值:门店名称 */
private static final String SAMPLE_STORE_NAME = "营业执照全称";
/** 模板示例值:门店商户号 */
private static final String SAMPLE_MERCHANT_NO = "xxxxxx";
/** 表头行集合:列序号 -> 列名(分组表头行 + 字段名行) */ /** 表头行集合:列序号 -> 列名(分组表头行 + 字段名行) */
private final List<Map<Integer, String>> headRows = new ArrayList<>(); private final List<Map<Integer, String>> headRows = new ArrayList<>();
/** 数据行,按文件顺序 */ /** 数据行,按文件顺序(已剔除说明行与空行之后的尾部内容) */
private final List<StoreImportExcelRow> rows = new ArrayList<>(); private final List<StoreImportExcelRow> rows = new ArrayList<>();
/** 数据行在文件中的物理行号(含表头偏移,用于失败明细定位) */ /** 数据行在文件中的物理行号(1 基,用于失败明细定位) */
private final List<Integer> rowIndexes = new ArrayList<>(); private final List<Integer> rowIndexes = new ArrayList<>();
/** 跳过的说明行物理行号 */
private final List<Integer> instructionRowIndexes = new ArrayList<>();
/** 是否命中模板示例数据(门店名称 / 商户号未替换) */
private boolean sampleDataDetected = false;
/** 数据区是否已结束(遇到首个全空行) */
private boolean dataAreaEnded = false;
@Override @Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
this.headRows.add(new LinkedHashMap<>(headMap)); this.headRows.add(new LinkedHashMap<>(headMap));
...@@ -34,14 +61,31 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE ...@@ -34,14 +61,31 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE
@Override @Override
public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) { public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
Map<Integer, String> row = new LinkedHashMap<>(); Map<Integer, String> row = new LinkedHashMap<>();
headMap.forEach((index, cell) -> row.put(index, cell.getStringValue())); headMap.forEach((index, cell) -> row.put(index, cell == null ? null : cell.getStringValue()));
this.headRows.add(row); this.headRows.add(row);
} }
@Override @Override
public void invoke(StoreImportExcelRow data, AnalysisContext context) { public void invoke(StoreImportExcelRow data, AnalysisContext context) {
int physicalRowNo = context.readRowHolder().getRowIndex() + 1;
if (dataAreaEnded) {
return;
}
if (isInstructionRow(data)) {
instructionRowIndexes.add(physicalRowNo);
return;
}
if (isBlankRow(data)) {
// 首个全空行即数据区结束(模板第 15 行为空行)
dataAreaEnded = true;
return;
}
if (isSampleRow(data)) {
sampleDataDetected = true;
}
rows.add(data); rows.add(data);
rowIndexes.add(context.readRowHolder().getRowIndex() + 1); rowIndexes.add(physicalRowNo);
} }
@Override @Override
...@@ -57,7 +101,7 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE ...@@ -57,7 +101,7 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE
for (Map<Integer, String> row : headRows) { for (Map<Integer, String> row : headRows) {
boolean matched = true; boolean matched = true;
for (int i = 0; i < StoreTemplateConstants.COLUMNS.size(); i++) { for (int i = 0; i < StoreTemplateConstants.COLUMNS.size(); i++) {
if (!StoreTemplateConstants.COLUMNS.get(i).equals(row.get(i))) { if (!StoreTemplateConstants.COLUMNS.get(i).equals(trim(row.get(i)))) {
matched = false; matched = false;
break; break;
} }
...@@ -67,8 +111,58 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE ...@@ -67,8 +111,58 @@ public class StoreImportExcelListener extends AnalysisEventListener<StoreImportE
} }
} }
return headRows.stream() return headRows.stream()
.filter(row -> row.size() == StoreTemplateConstants.COLUMNS.size()) .filter(row -> row.size() >= StoreTemplateConstants.COLUMNS.size())
.findFirst() .findFirst()
.orElse(headRows.isEmpty() ? new LinkedHashMap<>() : headRows.get(headRows.size() - 1)); .orElse(headRows.isEmpty() ? new LinkedHashMap<>() : headRows.get(headRows.size() - 1));
} }
// ------------------------------------------------------------ 私有方法
/** 说明行:前 4 列任一以「请输入」开头 */
private boolean isInstructionRow(StoreImportExcelRow row) {
return startsWithInstruction(row.getStoreName())
|| startsWithInstruction(row.getMerchantNo())
|| startsWithInstruction(row.getBusinessScene())
|| startsWithInstruction(row.getProductCategory());
}
private boolean startsWithInstruction(String value) {
return StringUtils.hasText(value) && value.trim().startsWith(INSTRUCTION_PREFIX);
}
/** 全空行:21 列全部无文本 */
private boolean isBlankRow(StoreImportExcelRow row) {
return !StringUtils.hasText(row.getStoreName())
&& !StringUtils.hasText(row.getMerchantNo())
&& !StringUtils.hasText(row.getBusinessScene())
&& !StringUtils.hasText(row.getProductCategory())
&& !StringUtils.hasText(row.getMarketFee1CalcMode())
&& !StringUtils.hasText(row.getMarketFee1CalcWay())
&& !StringUtils.hasText(row.getMarketFee1Value())
&& !StringUtils.hasText(row.getMarketFee2CalcMode())
&& !StringUtils.hasText(row.getMarketFee2CalcWay())
&& !StringUtils.hasText(row.getMarketFee2Value())
&& !StringUtils.hasText(row.getSunshine1OnlinePoint())
&& !StringUtils.hasText(row.getSunshine1CalcMode())
&& !StringUtils.hasText(row.getSunshine1CalcWay())
&& !StringUtils.hasText(row.getSunshine1Value())
&& !StringUtils.hasText(row.getSunshine2OnlinePoint())
&& !StringUtils.hasText(row.getSunshine2CalcMode())
&& !StringUtils.hasText(row.getSunshine2CalcWay())
&& !StringUtils.hasText(row.getSunshine2Value())
&& !StringUtils.hasText(row.getCostDecoration())
&& !StringUtils.hasText(row.getCostMonthly())
&& !StringUtils.hasText(row.getCostLabor());
}
/** 示例行:门店名称 / 商户号仍是模板里的示例占位值 */
private boolean isSampleRow(StoreImportExcelRow row) {
String storeName = trim(row.getStoreName());
String merchantNo = trim(row.getMerchantNo());
return SAMPLE_STORE_NAME.equals(storeName) || SAMPLE_MERCHANT_NO.equals(merchantNo);
}
private String trim(String value) {
return value == null ? null : value.trim();
}
} }
package com.youjia.store.remote.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
/**
* D+ 产品分类配置({@code dj_car_life_goods_category_configuration})。
*
* <p>对应 ROP {@code dj.api.goodsCategoryConfiguration.queryAll} 的返回元素。</p>
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class GoodsCategoryDTO {
/** 主键 ID */
private Integer id;
/** 分类 ID(业务主键,落库到 store_listing_item.product_category_id) */
private Integer categoryType;
/** 分类名称(多级时父子各为单独一行) */
private String categoryName;
/** 场景类型 */
private Byte sceneType;
/** 场景名称 */
private String sceneName;
/** 层级,从 1 开始 */
private Byte level;
/** 父级 ID,一级为 null */
private Integer parentId;
}
package com.youjia.store.service; package com.youjia.store.service;
import com.youjia.store.dto.StoreImportFailExportDTO; import com.youjia.store.dto.StoreImportCommitDTO;
import com.youjia.store.dto.StoreImportSubmitDTO;
import com.youjia.store.vo.StoreImportCheckVO; import com.youjia.store.vo.StoreImportCheckVO;
import com.youjia.store.vo.StoreImportSpecVO; import com.youjia.store.vo.StoreImportSpecVO;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
/** /**
* 门店信息导入服务(导入向导第 1 ~ 4 步)。 * 门店信息导入服务。
*
* <p>链路:模板下载 → 导入(解析 + 校验 + 落库为草稿)→ 提交(草稿 → 待审批)。</p>
*/ */
public interface StoreImportService { public interface StoreImportService {
/** /**
* 导入规范与字典:模板结构、文件级限制、五级校验说明与全部枚举字典。 * 导入规范与字典:模板结构、文件级限制、校验说明与全部枚举字典。
*
* <p>供导入页「查看导入规范」以及审批 / 列表页的筛选下拉使用,前端不再硬编码枚举。</p>
*/ */
StoreImportSpecVO spec(); StoreImportSpecVO spec();
/** /**
* 下载《【优加】门店上架模版-V1.0.1.xlsx》:首行三组横向合并的分组表头, * 下载《【优加】门店上架模版-V1.0.1.xlsx》:直接输出项目内的模板文件,原样保留
* 第二行 21 列字段名,数据从第 3 行开始(示例 2 个业务场景 × 6 个产品分类,共 12 行)。 * 分组表头、合并单元格、示例行与填写说明行。
*/ */
void writeTemplate(HttpServletResponse response); void writeTemplate(HttpServletResponse response);
/** /**
* 上传文件并执行五级校验。 * 导入:解析 Excel → 校验(本地 + D+ 三项)→ 全部通过则落库为草稿。
*/ *
StoreImportCheckVO check(MultipartFile file); * <p>任一行失败时**不落库**,而是在原始 Excel 末尾追加「校验失败原因」列生成新文件、
* 上传 OSS 并回传 URL。</p>
/** *
* 下载校验失败明细(xlsx)。 * @param file 上传的 Excel
* @param remark 备注
* @return 导入结果(含失败文件 URL / 统计数 / 落库的记录 ID)
*/ */
void writeFailDetail(StoreImportFailExportDTO dto, HttpServletResponse response); StoreImportCheckVO check(MultipartFile file, String remark);
/** /**
* 提交审批:创建门店上架记录(门店 × 业务场景)+ 产品分类明细 + 审批留痕,状态置为「待审批」。 * 提交:把导入产生的草稿记录({@code DRAFT})更新为待审批({@code PENDING})。
*
* <p>不重新解析文件、不重新校验。</p>
* *
* @return 门店上架记录 ID * @param dto 上架记录 ID 列表(导入返回的 listingIds)
* @return 提交结果
*/ */
Long submit(StoreImportSubmitDTO dto); StoreImportCheckVO commit(StoreImportCommitDTO dto);
} }
...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; ...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youjia.common.core.PageResult; import com.youjia.common.core.PageResult;
import com.youjia.common.core.ResultCode; import com.youjia.common.core.ResultCode;
import com.youjia.common.enums.ApprovalActionEnum; import com.youjia.common.enums.ApprovalActionEnum;
import com.youjia.common.enums.BusinessSceneEnum;
import com.youjia.common.enums.StoreStatusEnum; import com.youjia.common.enums.StoreStatusEnum;
import com.youjia.common.exception.BusinessException; import com.youjia.common.exception.BusinessException;
import com.youjia.framework.security.CurrentUserHolder; import com.youjia.framework.security.CurrentUserHolder;
...@@ -250,9 +251,24 @@ public class StoreApprovalServiceImpl implements StoreApprovalService { ...@@ -250,9 +251,24 @@ public class StoreApprovalServiceImpl implements StoreApprovalService {
} }
private LambdaQueryWrapper<StoreListing> buildWrapper(StoreApprovalTaskQueryDTO query) { private LambdaQueryWrapper<StoreListing> buildWrapper(StoreApprovalTaskQueryDTO query) {
// 业务场景:business_scene 存文本、business_scene_code 存编码。
// 前端传文本或编码都支持(传编码时按 business_scene_code 命中)。
String sceneText = null;
String sceneCode = null;
if (StringUtils.hasText(query.getBusinessScene())) {
String param = query.getBusinessScene().trim();
if (BusinessSceneEnum.isValidCode(param)) {
sceneCode = param;
} else {
sceneText = param;
}
}
LambdaQueryWrapper<StoreListing> wrapper = new LambdaQueryWrapper<StoreListing>() LambdaQueryWrapper<StoreListing> wrapper = new LambdaQueryWrapper<StoreListing>()
.eq(StringUtils.hasText(query.getBusinessScene()), // 草稿是操作态,不出现在任何列表查询中
StoreListing::getBusinessScene, query.getBusinessScene()) .ne(StoreListing::getStatus, StoreStatusEnum.DRAFT.getCode())
.eq(sceneText != null, StoreListing::getBusinessScene, sceneText)
.eq(sceneCode != null, StoreListing::getBusinessSceneCode, sceneCode)
.eq(StringUtils.hasText(query.getSubmitUserName()), .eq(StringUtils.hasText(query.getSubmitUserName()),
StoreListing::getSubmitUserName, query.getSubmitUserName()) StoreListing::getSubmitUserName, query.getSubmitUserName())
.and(StringUtils.hasText(query.getKeyword()), w -> w .and(StringUtils.hasText(query.getKeyword()), w -> w
......
...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; ...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youjia.common.core.PageResult; import com.youjia.common.core.PageResult;
import com.youjia.common.core.ResultCode; import com.youjia.common.core.ResultCode;
import com.youjia.common.enums.BusinessSceneEnum;
import com.youjia.common.exception.BusinessException; import com.youjia.common.exception.BusinessException;
import com.youjia.framework.security.CurrentUserHolder; import com.youjia.framework.security.CurrentUserHolder;
import com.youjia.store.dto.StoreColumnConfigDTO; import com.youjia.store.dto.StoreColumnConfigDTO;
...@@ -141,11 +142,24 @@ public class StoreListingServiceImpl implements StoreListingService { ...@@ -141,11 +142,24 @@ public class StoreListingServiceImpl implements StoreListingService {
// ------------------------------------------------------------ 私有方法 // ------------------------------------------------------------ 私有方法
private LambdaQueryWrapper<StoreListing> buildWrapper(StoreListingQueryDTO query) { private LambdaQueryWrapper<StoreListing> buildWrapper(StoreListingQueryDTO query) {
// 业务场景:business_scene 存文本、business_scene_code 存编码。
// 前端传文本或编码都支持(传编码时按 business_scene_code 命中)。
String sceneText = null;
String sceneCode = null;
if (StringUtils.hasText(query.getBusinessScene())) {
String param = query.getBusinessScene().trim();
if (BusinessSceneEnum.isValidCode(param)) {
sceneCode = param;
} else {
sceneText = param;
}
}
LambdaQueryWrapper<StoreListing> wrapper = new LambdaQueryWrapper<StoreListing>() LambdaQueryWrapper<StoreListing> wrapper = new LambdaQueryWrapper<StoreListing>()
.eq(StoreListing::getIsEffective, 1) .eq(StoreListing::getIsEffective, 1)
.like(StringUtils.hasText(query.getStoreName()), StoreListing::getStoreName, query.getStoreName()) .like(StringUtils.hasText(query.getStoreName()), StoreListing::getStoreName, query.getStoreName())
.like(StringUtils.hasText(query.getMerchantNo()), StoreListing::getMerchantNo, query.getMerchantNo()) .like(StringUtils.hasText(query.getMerchantNo()), StoreListing::getMerchantNo, query.getMerchantNo())
.eq(StringUtils.hasText(query.getBusinessScene()), StoreListing::getBusinessScene, query.getBusinessScene()) .eq(sceneText != null, StoreListing::getBusinessScene, sceneText)
.eq(sceneCode != null, StoreListing::getBusinessSceneCode, sceneCode)
.ge(query.getStartDate() != null, StoreListing::getEffectiveTime, .ge(query.getStartDate() != null, StoreListing::getEffectiveTime,
query.getStartDate() == null ? null : query.getStartDate().atStartOfDay()) query.getStartDate() == null ? null : query.getStartDate().atStartOfDay())
.le(query.getEndDate() != null, StoreListing::getEffectiveTime, .le(query.getEndDate() != null, StoreListing::getEffectiveTime,
......
package com.youjia.store.support;
import com.youjia.store.dto.StoreImportRowDTO;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 导入校验的中间结果(服务内部使用,不对外暴露)。
*/
@Getter
@Setter
public class StoreImportCheckResult {
/** 共解析行数(剔除说明行 / 空行之后) */
private int totalRows;
/** 门店名称(取首行) */
private String storeName;
/** 门店商户号(取首行) */
private String merchantNo;
/** 业务场景(去重后以「/」分隔,展示用 label) */
private String businessSceneSummary;
/** 通过行数 */
private int passRows;
/** 通过行(已完成系统转译,可直接落库) */
private final List<StoreImportRowDTO> passRows_ = new ArrayList<>();
/** 去重后的产品分类数(按分类 id / 名称) */
private int distinctProductCategoryCount;
/** 去重后的业务场景数 */
private int distinctBusinessSceneCount;
/** 产品分类总行数 */
private int productCategoryRowCount;
/** 失败原因:key = Excel 物理行号(部分全局错误会挂在首行数据行号上) */
private final Map<Integer, String> reasonByRow = new LinkedHashMap<>();
/** 是否命中模板示例数据(门店名称 / 商户号未替换) */
private boolean sampleDataDetected;
/** 首个数据行的物理行号(全局错误挂载用) */
private Integer firstDataRowIndex;
/**
* 记录某行失败原因(同一行多条以「;」连接)。
*/
public void addFailure(Integer rowIndex, String reason) {
if (rowIndex == null) {
rowIndex = firstDataRowIndex;
}
if (rowIndex == null) {
return;
}
reasonByRow.merge(rowIndex, reason, (a, b) -> a + ";" + b);
}
/** 失败行数 */
public int getFailRows() {
return reasonByRow.size();
}
}
package com.youjia.store.support;
import com.youjia.common.core.ResultCode;
import com.youjia.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
/**
* 导入失败明细文件生成器。
*
* <p>在用户上传的原始 Excel 末尾**追加一列「校验失败原因」**,按行写入失败原因,
* 成功行留空。不重建文件,因此模板原始的分组表头、合并单元格、样式与示例行全部保留。</p>
*
* <p>列位置策略:模板 21 列(A~U,索引 0~20),失败原因列固定落在索引 21(V)。
* 若上传的本身就是系统上一次回吐的失败文件(V 列已是「校验失败原因」),则**复用该列覆盖写入**,
* 保证「下载 → 修正 → 再上传」可以反复进行而不会不断新增列。</p>
*/
@Slf4j
public final class StoreImportFailFileWriter {
/** 失败原因列标题 */
public static final String REASON_HEADER = "校验失败原因";
/** 模板列数(A~U) */
private static final int TEMPLATE_COLUMN_COUNT = 21;
/** 数据起始行索引(0 基;模板第 1 行分组表头、第 2 行字段名) */
private static final int FIRST_DATA_ROW_INDEX = 2;
/** 失败原因列宽(1/256 字符宽) */
private static final int REASON_COLUMN_WIDTH = 40 * 256;
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private StoreImportFailFileWriter() {
}
/**
* 生成失败明细文件。
*
* @param originalBytes 原始上传文件字节
* @param reasonByRow 失败原因,key = **Excel 物理行号(1 基)**,value = 原因(多行以「;」连接)
* @return 新文件字节
*/
public static byte[] write(byte[] originalBytes, Map<Integer, String> reasonByRow) {
if (originalBytes == null || originalBytes.length == 0) {
throw new BusinessException(ResultCode.FAIL, "原始文件内容为空,无法生成失败明细");
}
if (reasonByRow == null || reasonByRow.isEmpty()) {
throw new BusinessException(ResultCode.FAIL, "没有失败行,无需生成失败明细");
}
try (Workbook workbook = WorkbookFactory.create(new ByteArrayInputStream(originalBytes));
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Sheet sheet = workbook.getSheetAt(0);
if (sheet == null) {
throw new BusinessException(ResultCode.FAIL, "Excel 中没有工作表");
}
int reasonColumn = resolveReasonColumn(sheet);
writeHeader(sheet, reasonColumn);
writeReasons(sheet, reasonColumn, reasonByRow);
workbook.write(out);
return out.toByteArray();
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
log.error("[导入] 生成失败明细失败 msg={}", e.getMessage(), e);
throw new BusinessException(ResultCode.FAIL, "生成失败明细失败:" + e.getMessage());
}
}
/**
* 失败明细文件名。
*/
public static String fileName() {
return "门店上架导入失败明细_" + LocalDateTime.now().format(TS) + ".xlsx";
}
// ------------------------------------------------------------ 私有方法
/**
* 定位失败原因列:已存在则复用,否则取模板列数之后的第一列。
*/
private static int resolveReasonColumn(Sheet sheet) {
for (int r = 0; r <= 1; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
for (int c = TEMPLATE_COLUMN_COUNT; c <= TEMPLATE_COLUMN_COUNT + 3; c++) {
Cell cell = row.getCell(c);
if (cell != null && REASON_HEADER.equals(cellString(cell))) {
log.debug("[导入] 复用已存在的失败原因列,colIndex={}", c);
return c;
}
}
}
return TEMPLATE_COLUMN_COUNT;
}
/**
* 写表头:第 1 行写标题、第 2 行留空,并纵向合并为跨两行的单元格。
*/
private static void writeHeader(Sheet sheet, int columnIndex) {
Row firstRow = sheet.getRow(0);
if (firstRow == null) {
firstRow = sheet.createRow(0);
}
CellStyle headerStyle = copyStyle(sheet.getWorkbook(), firstRow.getCell(0));
Cell firstCell = firstRow.createCell(columnIndex);
firstCell.setCellValue(REASON_HEADER);
if (headerStyle != null) {
firstCell.setCellStyle(headerStyle);
}
Row secondRow = sheet.getRow(1);
if (secondRow == null) {
secondRow = sheet.createRow(1);
}
Cell secondCell = secondRow.createCell(columnIndex);
secondCell.setCellValue("");
if (headerStyle != null) {
secondCell.setCellStyle(headerStyle);
}
sheet.setColumnWidth(columnIndex, REASON_COLUMN_WIDTH);
mergeHeaderVertically(sheet, columnIndex);
}
private static void mergeHeaderVertically(Sheet sheet, int columnIndex) {
CellRangeAddress target = new CellRangeAddress(0, 1, columnIndex, columnIndex);
try {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
if (sheet.getMergedRegion(i).intersects(target)) {
log.debug("[导入] 失败原因列与已有合并区域重叠,跳过合并,colIndex={}", columnIndex);
return;
}
}
sheet.addMergedRegion(target);
} catch (Exception e) {
// 合并失败不影响整体流程
log.warn("[导入] 合并失败原因列表头失败:{}", e.getMessage());
}
}
/**
* 逐行写入失败原因;有内容的行都补一格(含空值),保证列样式齐整。
*/
private static void writeReasons(Sheet sheet, int columnIndex, Map<Integer, String> reasonByRow) {
int lastRowIndex = sheet.getLastRowNum();
for (int i = FIRST_DATA_ROW_INDEX; i <= lastRowIndex; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
int excelRowNo = i + 1;
String reason = reasonByRow.get(excelRowNo);
if (!StringUtils.hasText(reason) && !rowHasContent(row)) {
continue;
}
Cell cell = row.createCell(columnIndex);
cell.setCellValue(StringUtils.hasText(reason) ? reason : "");
CellStyle style = wrapStyle(sheet.getWorkbook(), row.getCell(0));
if (style != null) {
cell.setCellStyle(style);
}
}
}
/** 前 21 列是否有任一非空文本 */
private static boolean rowHasContent(Row row) {
for (int c = 0; c < TEMPLATE_COLUMN_COUNT; c++) {
Cell cell = row.getCell(c);
if (cell != null && StringUtils.hasText(cellString(cell))) {
return true;
}
}
return false;
}
private static String cellString(Cell cell) {
try {
return cell.getStringCellValue();
} catch (IllegalStateException e) {
// 数值 / 公式单元格
return String.valueOf(cell.getNumericCellValue());
}
}
/** 复制样式的深拷贝,避免多单元格共享同一 CellStyle 后被反复改写 */
private static CellStyle copyStyle(Workbook workbook, Cell source) {
if (source == null) {
return null;
}
CellStyle style = workbook.createCellStyle();
style.cloneStyleFrom(source.getCellStyle());
return style;
}
/** 复制样式并开启自动换行(失败原因较长) */
private static CellStyle wrapStyle(Workbook workbook, Cell source) {
CellStyle style = copyStyle(workbook, source);
if (style == null) {
style = workbook.createCellStyle();
}
style.setWrapText(true);
style.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
return style;
}
/**
* 判断工作簿是否为 xlsx(保留方法便于后续按需分流 xls)。
*/
static boolean isXlsx(Workbook workbook) {
return workbook instanceof XSSFWorkbook;
}
}
package com.youjia.store.support;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
/**
* 导入链路的接口级防重(防连点)。
*
* <p>用于挡住「用户手抖双击 / 前端重试」导致的并发重复处理:</p>
* <ul>
* <li>导入({@code check}):同一用户 + 同一文件内容短时间内只处理一次 ——
* 否则并发下会为同一「门店 × 场景」插入两条草稿;</li>
* <li>提交({@code commit}):同一用户 + 同一批上架记录短时间内只处理一次
* (并发安全另有乐观锁兜底)。</li>
* </ul>
*
* <p><b>降级策略</b>:Redis 不可用时不阻断业务(记 warn 后放行),
* 避免因为缓存故障把导入功能整体拖死。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class StoreImportIdempotentGuard {
/** key 前缀 */
private static final String KEY_PREFIX = "youjia:import:";
private final StringRedisTemplate stringRedisTemplate;
/**
* 生成防重 key。
*
* @param scene 场景,如 {@code check} / {@code commit}
* @param identity 业务标识(文件内容 MD5 或上架记录 ID 串)
* @param userId 当前用户,避免不同用户互相阻塞
*/
public String key(String scene, String identity, Long userId) {
String hash = DigestUtils.md5DigestAsHex(
identity.getBytes(StandardCharsets.UTF_8));
return KEY_PREFIX + scene + ":" + (userId == null ? 0L : userId) + ":" + hash;
}
/**
* 尝试加锁。
*
* @return {@code true} 表示获取成功(可以继续处理);{@code false} 表示已有相同请求在处理中
*/
public boolean tryLock(String key, Duration ttl) {
try {
Boolean ok = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", ttl);
return !Boolean.FALSE.equals(ok);
} catch (Exception e) {
log.warn("[导入] 防重锁获取失败(降级放行)key={} msg={}", key, e.getMessage());
return true;
}
}
/**
* 释放锁。仅释放在 finally 中调用,避免异常路径下长时间占锁。
*/
public void unlock(String key) {
try {
stringRedisTemplate.delete(key);
} catch (Exception e) {
log.warn("[导入] 防重锁释放失败 key={} msg={}", key, e.getMessage());
}
}
}
...@@ -10,29 +10,23 @@ import java.util.ArrayList; ...@@ -10,29 +10,23 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* 导入校验结果(第 2 步「数据校验」返回)。 * 门店上架导入结果(导入接口 / 提交接口共用)。
*/ */
@Getter @Getter
@Setter @Setter
@Schema(description = "导入校验结果") @Schema(description = "门店上架导入结果")
public class StoreImportCheckVO { public class StoreImportCheckVO {
@Schema(description = "模板版本") @Schema(description = "模板版本")
private String templateVersion; private String templateVersion;
@Schema(description = "表头是否通过 L2 校验") @Schema(description = "解析总行数")
private Boolean headerValid = Boolean.TRUE;
@Schema(description = "表头差异说明")
private String headerMessage;
@Schema(description = "共解析行数")
private Integer totalRows = 0; private Integer totalRows = 0;
@Schema(description = "通过行数") @Schema(description = "校验通过")
private Integer passRows = 0; private Integer passRows = 0;
@Schema(description = "失败行数") @Schema(description = "校验失败行数")
private Integer failRows = 0; private Integer failRows = 0;
@Schema(description = "门店名称") @Schema(description = "门店名称")
...@@ -41,9 +35,11 @@ public class StoreImportCheckVO { ...@@ -41,9 +35,11 @@ public class StoreImportCheckVO {
@Schema(description = "门店商户号") @Schema(description = "门店商户号")
private String merchantNo; private String merchantNo;
@Schema(description = "业务场景") @Schema(description = "业务场景(多个以「/」分隔)")
private String businessScene; private String businessScene;
/* 运营成本三项属于「业务场景」维度合并项,一次导入可能落多条记录、各场景取值不同,
因此不再随导入结果返回;成本明细请查落库记录详情(StoreListingDetailVO)。
@Schema(description = "装修、设备总投入") @Schema(description = "装修、设备总投入")
private BigDecimal costDecoration; private BigDecimal costDecoration;
...@@ -54,11 +50,35 @@ public class StoreImportCheckVO { ...@@ -54,11 +50,35 @@ public class StoreImportCheckVO {
private BigDecimal costLabor; private BigDecimal costLabor;
@Schema(description = "运营成本合计") @Schema(description = "运营成本合计")
private BigDecimal costTotal; private BigDecimal costTotal;*/
@Schema(description = "失败明细") @Schema(description = "失败明细")
private List<StoreImportFailVO> failures = new ArrayList<>(); private List<StoreImportFailVO> failures = new ArrayList<>();
@Schema(description = "通过行(系统转译后,可编辑后再提交)") @Schema(description = "通过行(系统转译后,可编辑后再提交)")
private List<StoreImportRowDTO> previewRows = new ArrayList<>(); private List<StoreImportRowDTO> previewRows = new ArrayList<>();
/* ---------------- 本轮改造新增 ---------------- */
@Schema(description = "导入失败明细文件下载地址(全部成功时为 null)")
private String failFileUrl;
@Schema(description = "下一个待审批角色名称,如「优加商务经理」")
private String nextRoleName;
@Schema(description = "去重后的产品分类数,例如 6(2 个业务场景 × 6 个分类 → 6)")
private Integer distinctProductCategoryCount = 0;
@Schema(description = "去重后的业务场景数,例如 2")
private Integer distinctBusinessSceneCount = 0;
@Schema(description = "产品分类总行数,例如 12")
private Integer productCategoryRowCount = 0;
@Schema(description = "本次落库 / 提交的上架记录 ID(按业务场景拆分,一条 = 一个场景)")
private List<Long> listingIds = new ArrayList<>();
@Schema(description = "是否已落库(导入成功为 true;仅校验失败为 false)")
private Boolean submitted = Boolean.FALSE;
} }
...@@ -22,7 +22,7 @@ public class YouJiaApplication { ...@@ -22,7 +22,7 @@ public class YouJiaApplication {
public static void main(String[] args) { public static void main(String[] args) {
Environment env = SpringApplication.run(YouJiaApplication.class, args).getEnvironment(); Environment env = SpringApplication.run(YouJiaApplication.class, args).getEnvironment();
String port = env.getProperty("server.port", "8080"); String port = env.getProperty("server.port", "8081");
String contextPath = env.getProperty("server.servlet.context-path", ""); String contextPath = env.getProperty("server.servlet.context-path", "");
try { try {
String host = InetAddress.getLocalHost().getHostAddress(); String host = InetAddress.getLocalHost().getHostAddress();
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!