Compare commits
218 Commits
import
...
50f6b49da9
| Author | SHA1 | Date | |
|---|---|---|---|
| 50f6b49da9 | |||
| 7c1af7c207 | |||
| b827052956 | |||
| 2a05686b75 | |||
| 233af57bad | |||
| 039508412b | |||
| 26920cbbe3 | |||
| 93dbc22603 | |||
| 43a98cf7cd | |||
| b1cd1cff7e | |||
| d69481f4c3 | |||
| b9fd76f855 | |||
| 12877c7b8e | |||
| a4dbe758e3 | |||
| f016acda91 | |||
| 808ac75253 | |||
| 521de8509b | |||
| 5fd87bbb1c | |||
| cd0433c86b | |||
| 22c1f42394 | |||
| f7334021e0 | |||
| 1c1c341bb9 | |||
| 4dae378c9a | |||
| a8af20bcde | |||
| 2044bdc87a | |||
| 1c78fdbef4 | |||
| 3cadaab214 | |||
| ecbe4fbaea | |||
| af5a0d352e | |||
| 5cc9219801 | |||
| 5f6a8ab089 | |||
| 102a45ef3a | |||
| 9b18851aaf | |||
| f25e2c3707 | |||
| ca02e9e5a3 | |||
| 409a078e2d | |||
| 34554cbaac | |||
| fe893c71f6 | |||
| bb45d4b96e | |||
| e7ba0626cd | |||
| 87f38be98a | |||
| 6e04ca07bb | |||
| 0fb8c01140 | |||
| 429f3e1e8e | |||
| ae24a9a99e | |||
| a5f18859dc | |||
| 8bafc724a4 | |||
| 9590227004 | |||
| be58a5cada | |||
| eaea99a1e9 | |||
| fbc3756ba7 | |||
| d177555ef9 | |||
| 546027e7a4 | |||
| 82fe1ac24b | |||
| 2973844559 | |||
| c5a942b4fc | |||
| bd3202830c | |||
| 0610f2c894 | |||
| 95109bc031 | |||
| 4fbd55cd41 | |||
| e1ef21f140 | |||
| 1177730464 | |||
| 0fc914f47a | |||
| dd023bd2ca | |||
| ad5a5abb31 | |||
| 4481850809 | |||
| 011c9e458a | |||
| 4c8e67fe64 | |||
| 32db399cb5 | |||
| d778036daf | |||
| c1efeef8c7 | |||
| 76aec53bae | |||
| 33f9f07037 | |||
| e8ce2d162f | |||
| aa4a6d9725 | |||
| f7a96724c6 | |||
| 3d8169c55a | |||
| 3b4f8a29d8 | |||
| efe7904755 | |||
| 01cd94e8b0 | |||
| 15744e668b | |||
| 7841fa0bba | |||
| 051abb9d7a | |||
| 05a94b29b5 | |||
| 3e2b48ace4 | |||
| 45878b9005 | |||
| c0c1232768 | |||
| 54e2654033 | |||
| 28f113a6c9 | |||
| d50e85fc52 | |||
| 9b31b3ce57 | |||
| 78a3f8ce4c | |||
| fc8d49a768 | |||
| a20d1dd465 | |||
| 46de27611d | |||
| 1d63c5cdc8 | |||
| 922e7def9d | |||
| 7191c93b4c | |||
| f8d134a330 | |||
| 6b401b8286 | |||
| e7133f65c9 | |||
| 79612be1c6 | |||
| 1b2d09049a | |||
| a941e4a9ab | |||
| bdc0acc097 | |||
| 83cb7208a8 | |||
| d68a53e3d0 | |||
| fe15c7120f | |||
| 6285429753 | |||
| 46b5ce3971 | |||
| 4832929a11 | |||
| 1536f1780b | |||
| 804a5a7bef | |||
| 60279fca4c | |||
| 2c076e2b0f | |||
| 48cd2e1f7b | |||
| 88afd149c3 | |||
| 9672be2252 | |||
| 1107b9144f | |||
| acc543b50a | |||
| b9c70bb4a3 | |||
| ee9ea88ce9 | |||
| 093826435e | |||
| 85a8d17194 | |||
| bbd41da1d3 | |||
| e4e10d46cc | |||
| 195e90df5e | |||
| c5da6f371b | |||
| 51d3a029cc | |||
| 30c7e72a80 | |||
| 36bf931274 | |||
| 58c755b715 | |||
| 937e707890 | |||
| 9a79aff47d | |||
| d393de816f | |||
| 27baa6ecf7 | |||
| d7a6b7cc94 | |||
| 24133ef8a8 | |||
| 35c155a1da | |||
| fc00728729 | |||
| 0a466153f7 | |||
| f364d180ea | |||
| 7f7b7527a0 | |||
| 940e96f59d | |||
| 5fe3801a4d | |||
| 40aecd7c22 | |||
| 49998c71e4 | |||
| f9c693533c | |||
| dff8b8f645 | |||
| 175708716c | |||
| ede52b6309 | |||
| 7c0df4fd08 | |||
| ae2eac39a0 | |||
| 5753163c0e | |||
| 0cd1cb26f1 | |||
| 2059c90047 | |||
| 4da2a84421 | |||
| 5ac0eef8a6 | |||
| 79b2d584dc | |||
| 0af3b6467d | |||
| e2f3b444ae | |||
| 20a24a46c4 | |||
| 6be4421ed9 | |||
| 4c290ea4fe | |||
| 89177db718 | |||
| d93dd04211 | |||
| a3e812a9c4 | |||
| 5e804bbf9a | |||
| ad2562c06e | |||
| 5a95375cda | |||
| 9e5c5ceab3 | |||
| fa53fd399f | |||
| cbc9a1c861 | |||
| 3814711ec4 | |||
| e4d4a19020 | |||
| 3b63172012 | |||
| 803ac3301e | |||
| 375a65be6a | |||
| 918190148b | |||
| d15cc03e48 | |||
| 0035d3cd7d | |||
| 08ab8da7d9 | |||
| 06c20b8418 | |||
| 16e5e31f33 | |||
| afa5dd8ab2 | |||
| 4ffc62fef1 | |||
| 757291f256 | |||
| f40010433d | |||
| a6aba2c49b | |||
| 492928667a | |||
| 416027ffe8 | |||
| 30924cb7c3 | |||
| 0104eccd34 | |||
| 7ba034ab1e | |||
| 15fc17e54b | |||
| 7487236ac6 | |||
| 1898d3ac9b | |||
| 8e5271ae38 | |||
| b1b106c397 | |||
| ceaaf287b0 | |||
| e36524de3a | |||
| e647a5d066 | |||
| fc0dc99ccc | |||
| 850c18d639 | |||
| c902bbd214 | |||
| 84e6222c4d | |||
| ba683bd578 | |||
| 12fc77b35c | |||
| 071c44679a | |||
| f2f7595674 | |||
| f799c2d7ea | |||
| 18f2903f35 | |||
| d7c15cb22f | |||
| 3582a3076e | |||
| e4a3ea9c7f | |||
| e62b900bb1 | |||
| 4794a9af3e | |||
| 07ea48795b |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -42,3 +42,4 @@ ehthumbs.db
|
|||||||
Thumbs.db
|
Thumbs.db
|
||||||
/file/
|
/file/
|
||||||
/websoft-modules.log
|
/websoft-modules.log
|
||||||
|
/tmp/
|
||||||
|
|||||||
@@ -284,3 +284,5 @@ docker run -d -p 9200:9200 websoft-api
|
|||||||
---
|
---
|
||||||
|
|
||||||
⭐ 如果这个项目对您有帮助,请给我们一个星标!
|
⭐ 如果这个项目对您有帮助,请给我们一个星标!
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
86
com/wechat/pay/java/core/exception/ServiceException.java
Normal file
86
com/wechat/pay/java/core/exception/ServiceException.java
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
package com.wechat.pay.java.core.exception;
|
||||||
|
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.wechat.pay.java.core.http.HttpRequest;
|
||||||
|
import com.wechat.pay.java.core.util.GsonUtil;
|
||||||
|
|
||||||
|
/** 发送HTTP请求成功,返回异常时抛出。例如返回状态码小于200或大于等于300、返回体参数不完整。 */
|
||||||
|
public class ServiceException extends WechatPayException {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -7174975090366956652L;
|
||||||
|
|
||||||
|
private final HttpRequest httpRequest;
|
||||||
|
private final int httpStatusCode;
|
||||||
|
private final String responseBody;
|
||||||
|
private String errorCode;
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回状态码小于200或大于300调用
|
||||||
|
*
|
||||||
|
* @param httpRequest http请求
|
||||||
|
* @param httpStatusCode http状态码
|
||||||
|
* @param responseBody http返回体
|
||||||
|
*/
|
||||||
|
public ServiceException(HttpRequest httpRequest, int httpStatusCode, String responseBody) {
|
||||||
|
super(
|
||||||
|
String.format(
|
||||||
|
"Wrong HttpStatusCode[%d]%nhttpResponseBody[%.1024s]\tHttpRequest[%s]",
|
||||||
|
httpStatusCode, responseBody, httpRequest));
|
||||||
|
this.httpRequest = httpRequest;
|
||||||
|
this.httpStatusCode = httpStatusCode;
|
||||||
|
this.responseBody = responseBody;
|
||||||
|
if (responseBody != null && !responseBody.isEmpty()) {
|
||||||
|
JsonObject jsonObject = GsonUtil.getGson().fromJson(responseBody, JsonObject.class);
|
||||||
|
JsonElement code = jsonObject.get("code");
|
||||||
|
JsonElement message = jsonObject.get("message");
|
||||||
|
this.errorCode = code == null ? null : code.getAsString();
|
||||||
|
this.errorMessage = message == null ? null : message.getAsString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取序列化版本UID
|
||||||
|
*
|
||||||
|
* @return UID
|
||||||
|
*/
|
||||||
|
public static long getSerialVersionUID() {
|
||||||
|
return serialVersionUID;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取HTTP请求
|
||||||
|
*
|
||||||
|
* @return HTTP请求
|
||||||
|
*/
|
||||||
|
public HttpRequest getHttpRequest() {
|
||||||
|
return httpRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取HTTP返回体
|
||||||
|
*
|
||||||
|
* @return HTTP返回体
|
||||||
|
*/
|
||||||
|
public String getResponseBody() {
|
||||||
|
return responseBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取HTTP状态码
|
||||||
|
*
|
||||||
|
* @return HTTP状态码
|
||||||
|
*/
|
||||||
|
public int getHttpStatusCode() {
|
||||||
|
return httpStatusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getErrorCode() {
|
||||||
|
return errorCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getErrorMessage() {
|
||||||
|
return errorMessage;
|
||||||
|
}
|
||||||
|
}
|
||||||
151
com/wechat/pay/java/core/http/AbstractHttpClient.java
Normal file
151
com/wechat/pay/java/core/http/AbstractHttpClient.java
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
package com.wechat.pay.java.core.http;
|
||||||
|
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.ACCEPT;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.AUTHORIZATION;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.OS;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.REQUEST_ID;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.USER_AGENT;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.USER_AGENT_FORMAT;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.VERSION;
|
||||||
|
import static com.wechat.pay.java.core.http.Constant.WECHAT_PAY_SERIAL;
|
||||||
|
import static java.net.HttpURLConnection.HTTP_MULT_CHOICE;
|
||||||
|
import static java.net.HttpURLConnection.HTTP_OK;
|
||||||
|
import static java.util.Objects.requireNonNull;
|
||||||
|
|
||||||
|
import com.wechat.pay.java.core.auth.Credential;
|
||||||
|
import com.wechat.pay.java.core.auth.Validator;
|
||||||
|
import com.wechat.pay.java.core.exception.MalformedMessageException;
|
||||||
|
import com.wechat.pay.java.core.exception.ServiceException;
|
||||||
|
import com.wechat.pay.java.core.exception.ValidationException;
|
||||||
|
import com.wechat.pay.java.core.http.HttpRequest.Builder;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
/** 请求客户端抽象基类 */
|
||||||
|
public abstract class AbstractHttpClient implements HttpClient {
|
||||||
|
|
||||||
|
protected final Credential credential;
|
||||||
|
protected final Validator validator;
|
||||||
|
|
||||||
|
public AbstractHttpClient(Credential credential, Validator validator) {
|
||||||
|
this.credential = requireNonNull(credential);
|
||||||
|
this.validator = requireNonNull(validator);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> HttpResponse<T> execute(HttpRequest httpRequest, Class<T> responseClass) {
|
||||||
|
HttpRequest innerRequest =
|
||||||
|
new Builder()
|
||||||
|
.url(httpRequest.getUrl())
|
||||||
|
.httpMethod(httpRequest.getHttpMethod())
|
||||||
|
.headers(httpRequest.getHeaders())
|
||||||
|
.addHeader(AUTHORIZATION, getAuthorization(httpRequest))
|
||||||
|
.addHeader(USER_AGENT, getUserAgent())
|
||||||
|
.addHeader(WECHAT_PAY_SERIAL, getWechatPaySerial())
|
||||||
|
.body(httpRequest.getBody())
|
||||||
|
.build();
|
||||||
|
OriginalResponse originalResponse = innerExecute(innerRequest);
|
||||||
|
validateResponse(originalResponse);
|
||||||
|
return assembleHttpResponse(originalResponse, responseClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public InputStream download(String url) {
|
||||||
|
HttpRequest originRequest =
|
||||||
|
new HttpRequest.Builder().httpMethod(HttpMethod.GET).url(url).build();
|
||||||
|
HttpRequest httpRequest =
|
||||||
|
new HttpRequest.Builder()
|
||||||
|
.url(url)
|
||||||
|
.httpMethod(HttpMethod.GET)
|
||||||
|
.addHeader(AUTHORIZATION, getAuthorization(originRequest))
|
||||||
|
.addHeader(ACCEPT, "*/*")
|
||||||
|
.addHeader(USER_AGENT, getUserAgent())
|
||||||
|
.addHeader(WECHAT_PAY_SERIAL, getWechatPaySerial())
|
||||||
|
.build();
|
||||||
|
return innerDownload(httpRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract InputStream innerDownload(HttpRequest httpRequest);
|
||||||
|
|
||||||
|
protected abstract OriginalResponse innerExecute(HttpRequest httpRequest);
|
||||||
|
|
||||||
|
private void validateResponse(OriginalResponse originalResponse) {
|
||||||
|
|
||||||
|
if (isInvalidHttpCode(originalResponse.getStatusCode())) {
|
||||||
|
throw new ServiceException(
|
||||||
|
originalResponse.getRequest(),
|
||||||
|
originalResponse.getStatusCode(),
|
||||||
|
originalResponse.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (originalResponse.getBody() != null
|
||||||
|
&& !originalResponse.getBody().isEmpty()
|
||||||
|
&& !MediaType.APPLICATION_JSON.equalsWith(originalResponse.getContentType())) {
|
||||||
|
throw new MalformedMessageException(
|
||||||
|
String.format(
|
||||||
|
"Unsupported content-type[%s]%nhttpRequest[%s]",
|
||||||
|
originalResponse.getContentType(), originalResponse.getRequest()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validator.validate(originalResponse.getHeaders(), originalResponse.getBody())) {
|
||||||
|
String requestId = originalResponse.getHeaders().getHeader(REQUEST_ID);
|
||||||
|
throw new ValidationException(
|
||||||
|
String.format(
|
||||||
|
"Validate response failed,the WechatPay signature is incorrect.%n"
|
||||||
|
+ "Request-ID[%s]\tresponseHeader[%s]\tresponseBody[%.1024s]",
|
||||||
|
requestId, originalResponse.getHeaders(), originalResponse.getBody()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean isInvalidHttpCode(int httpCode) {
|
||||||
|
return httpCode < HTTP_OK || httpCode >= HTTP_MULT_CHOICE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> HttpResponse<T> assembleHttpResponse(
|
||||||
|
OriginalResponse originalResponse, Class<T> responseClass) {
|
||||||
|
return new HttpResponse.Builder<T>()
|
||||||
|
.originalResponse(originalResponse)
|
||||||
|
.serviceResponseType(responseClass)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getSignBody(RequestBody requestBody) {
|
||||||
|
if (requestBody == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (requestBody instanceof JsonRequestBody) {
|
||||||
|
return ((JsonRequestBody) requestBody).getBody();
|
||||||
|
}
|
||||||
|
if (requestBody instanceof FileRequestBody) {
|
||||||
|
return ((FileRequestBody) requestBody).getMeta();
|
||||||
|
}
|
||||||
|
throw new UnsupportedOperationException(
|
||||||
|
String.format("Unsupported RequestBody Type[%s]", requestBody.getClass().getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getUserAgent() {
|
||||||
|
return String.format(
|
||||||
|
USER_AGENT_FORMAT,
|
||||||
|
getClass().getPackage().getImplementationVersion(),
|
||||||
|
OS,
|
||||||
|
VERSION == null ? "Unknown" : VERSION,
|
||||||
|
credential.getClass().getSimpleName(),
|
||||||
|
validator.getClass().getSimpleName(),
|
||||||
|
getHttpClientInfo());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getWechatPaySerial() {
|
||||||
|
return this.validator.getSerialNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取http客户端信息,用于User-Agent。 格式:客户端名称/版本 示例:okhttp3/4.9.3
|
||||||
|
*
|
||||||
|
* @return 客户端信息
|
||||||
|
*/
|
||||||
|
protected abstract String getHttpClientInfo();
|
||||||
|
|
||||||
|
private String getAuthorization(HttpRequest request) {
|
||||||
|
return credential.getAuthorization(
|
||||||
|
request.getUri(), request.getHttpMethod().name(), getSignBody(request.getBody()));
|
||||||
|
}
|
||||||
|
}
|
||||||
26
docs/SHOP_DEALER_REFEREE_BINDING.md
Normal file
26
docs/SHOP_DEALER_REFEREE_BINDING.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# ShopDealerReferee 绑定接口规则与索引建议
|
||||||
|
|
||||||
|
接口:`POST /api/shop/shop-dealer-referee`
|
||||||
|
|
||||||
|
## 业务规则(后端)
|
||||||
|
|
||||||
|
- 邀请人(dealerId)必须存在且有效:以 `shop_dealer_user` 记录存在且 `is_delete=0` 为准
|
||||||
|
- 当前用户(userId)仅从 token 获取;若 body.userId 存在且与 token 不一致则拒绝
|
||||||
|
- 禁止自己绑定自己:`dealerId == userId`
|
||||||
|
- 仅首次绑定生效:若已存在(同一 tenant、同一 user、`level=1`)则直接返回成功(幂等,不改绑)
|
||||||
|
- 记录溯源字段:`source`、`scene`
|
||||||
|
|
||||||
|
## 并发幂等(数据库建议)
|
||||||
|
|
||||||
|
建议在 `shop_dealer_referee` 增加溯源字段,并加唯一索引保证并发下不重复写入:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE shop_dealer_referee
|
||||||
|
ADD COLUMN source VARCHAR(32) NULL COMMENT '来源(如 goods_share)',
|
||||||
|
ADD COLUMN scene VARCHAR(255) NULL COMMENT '场景参数(溯源统计)';
|
||||||
|
|
||||||
|
-- 约束:同一 tenant 下,一个用户每个 level 只能有一条推荐关系
|
||||||
|
ALTER TABLE shop_dealer_referee
|
||||||
|
ADD UNIQUE KEY uk_shop_dealer_referee_tenant_user_level (tenant_id, user_id, level);
|
||||||
|
```
|
||||||
|
|
||||||
31
docs/TICKET_PACKAGE_FEATURE_PLAN.md
Normal file
31
docs/TICKET_PACKAGE_FEATURE_PLAN.md
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# 套票(冻结/可用、分期释放)功能开发计划
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
- 为“买N送M(例如买1送4)、起售(例如20桶起售)、按月释放(例如每月释放10桶)、可用未用完叠加”的套票/权益,提供后端可配置、可发放、可释放、可消费的能力。
|
||||||
|
|
||||||
|
## 核心概念
|
||||||
|
- 套票模板:按商品(goodsId)配置买赠规则、起售/起送、释放规则(每期释放数或释放期数)、首期释放时机。
|
||||||
|
- 用户套票账户:记录总量、可用量、冻结量、已用量、已释放量;绑定订单(用于幂等与追溯)。
|
||||||
|
- 释放计划:每期一条,到期后把冻结转可用(可用未用完自然叠加)。
|
||||||
|
- 变更流水:发放/释放/消费等都记录流水,便于对账与排查。
|
||||||
|
|
||||||
|
## 关键默认规则(可在模板里改)
|
||||||
|
- 仅赠送量进入套票账户(默认不包含“购买量”本身);如需“买20送80=总100”,可在模板设置 `includeBuyQty=true`。
|
||||||
|
- 首期释放:默认“支付成功当日/当刻”释放(`firstReleaseMode=0`);如需“下个月同日释放”,设 `firstReleaseMode=1`。
|
||||||
|
- 每期释放:默认按 `monthlyReleaseQty`;如配置了 `releasePeriods`,则平均分摊并处理余数。
|
||||||
|
|
||||||
|
## 开发步骤(建议按顺序)
|
||||||
|
1. 需求确认与接入点确认(订单哪个节点发放、桶票如何消费/核销、退款是否回滚、释放日期规则)。
|
||||||
|
2. 数据表设计与SQL输出(模板/账户/释放计划/流水)。
|
||||||
|
3. 实现套票模板后台CRUD接口。
|
||||||
|
4. 支付成功接入:在订单支付成功后发放套票账户+生成释放计划(幂等)。
|
||||||
|
5. 定时任务释放:扫描到期释放计划,执行“冻结->可用”转账(幂等)。
|
||||||
|
6. 消费扣减:对用户可用量做扣减(支持跨多套票账户FIFO扣减),并落流水。
|
||||||
|
7. 测试与验收:至少覆盖(买赠计算、分期拆分、叠加逻辑、幂等、并发扣减)。
|
||||||
|
|
||||||
|
## 待确认点(不确认也可先按默认实现)
|
||||||
|
- 套票数量=赠送量?还是(购买量+赠送量)?
|
||||||
|
- “释放日期”是按支付时间的“日”还是固定每月某一天?(31号跨月如何处理?)
|
||||||
|
- 退款/取消:是否回滚未使用的可用/冻结?已释放但未用如何处理?
|
||||||
|
- 消费场景:在哪个业务点扣减(下单抵扣/提货核销/线下核销)?
|
||||||
|
|
||||||
121
docs/TICKET_PACKAGE_TABLES.sql
Normal file
121
docs/TICKET_PACKAGE_TABLES.sql
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
-- 套票(冻结/可用、分期释放)相关表
|
||||||
|
-- 说明:项目使用了 MyBatis-Plus 的 tenant 拦截;表内显式保留 tenant_id 字段并建议建立联合唯一索引。
|
||||||
|
|
||||||
|
-- 1) 套票模板(按商品配置)
|
||||||
|
CREATE TABLE IF NOT EXISTS shop_ticket_template (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
goods_id INT NOT NULL,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||||
|
unit_name VARCHAR(20) NOT NULL DEFAULT '桶',
|
||||||
|
|
||||||
|
-- 起售/起送
|
||||||
|
min_buy_qty INT NOT NULL DEFAULT 1,
|
||||||
|
start_send_qty INT NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
-- 买赠:买1送4 => gift_multiplier=4
|
||||||
|
gift_multiplier INT NOT NULL DEFAULT 0,
|
||||||
|
-- 是否把购买量也计入套票总量(默认仅计入赠送量)
|
||||||
|
include_buy_qty TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
-- 释放规则:二选一
|
||||||
|
-- A) 每期释放数量(默认每月释放10)
|
||||||
|
monthly_release_qty INT NOT NULL DEFAULT 10,
|
||||||
|
-- B) 总共释放多少期(若配置>0,则按期数平均分摊)
|
||||||
|
release_periods INT NULL,
|
||||||
|
|
||||||
|
-- 首期释放时机:0=支付成功当刻;1=下个月同日
|
||||||
|
first_release_mode INT NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
comments VARCHAR(255) NULL,
|
||||||
|
sort_number INT NOT NULL DEFAULT 0,
|
||||||
|
user_id INT NULL,
|
||||||
|
|
||||||
|
deleted INT NOT NULL DEFAULT 0,
|
||||||
|
tenant_id INT NOT NULL,
|
||||||
|
create_time DATETIME NULL,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
|
||||||
|
UNIQUE KEY uk_ticket_template_tenant_goods (tenant_id, goods_id),
|
||||||
|
KEY idx_ticket_template_tenant (tenant_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- 2) 用户套票账户(一次购买通常生成一条)
|
||||||
|
CREATE TABLE IF NOT EXISTS shop_user_ticket (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
template_id INT NOT NULL,
|
||||||
|
goods_id INT NOT NULL,
|
||||||
|
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
order_id INT NULL,
|
||||||
|
order_no VARCHAR(64) NULL,
|
||||||
|
order_goods_id INT NULL,
|
||||||
|
|
||||||
|
total_qty INT NOT NULL DEFAULT 0,
|
||||||
|
available_qty INT NOT NULL DEFAULT 0,
|
||||||
|
frozen_qty INT NOT NULL DEFAULT 0,
|
||||||
|
used_qty INT NOT NULL DEFAULT 0,
|
||||||
|
released_qty INT NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
status INT NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
deleted INT NOT NULL DEFAULT 0,
|
||||||
|
tenant_id INT NOT NULL,
|
||||||
|
create_time DATETIME NULL,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
|
||||||
|
KEY idx_user_ticket_user (tenant_id, user_id),
|
||||||
|
KEY idx_user_ticket_order (tenant_id, order_no),
|
||||||
|
UNIQUE KEY uk_user_ticket_order_goods (tenant_id, template_id, order_no, order_goods_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- 3) 释放计划/释放记录(每期一条,幂等执行)
|
||||||
|
CREATE TABLE IF NOT EXISTS shop_user_ticket_release (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_ticket_id BIGINT NOT NULL,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
period_no INT NOT NULL,
|
||||||
|
|
||||||
|
release_qty INT NOT NULL,
|
||||||
|
release_time DATETIME NOT NULL,
|
||||||
|
|
||||||
|
status INT NOT NULL DEFAULT 0, -- 0待释放 1已释放 2作废
|
||||||
|
released_time DATETIME NULL,
|
||||||
|
|
||||||
|
tenant_id INT NOT NULL,
|
||||||
|
create_time DATETIME NULL,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
|
||||||
|
UNIQUE KEY uk_ticket_release_period (tenant_id, user_ticket_id, period_no),
|
||||||
|
KEY idx_ticket_release_due (status, release_time),
|
||||||
|
KEY idx_ticket_release_user (tenant_id, user_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- 4) 套票变更流水(发放/释放/消费/回滚等)
|
||||||
|
CREATE TABLE IF NOT EXISTS shop_user_ticket_log (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_ticket_id BIGINT NOT NULL,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
|
||||||
|
change_type INT NOT NULL, -- 10发放 20释放 30消费 40回滚/退款
|
||||||
|
change_available INT NOT NULL DEFAULT 0,
|
||||||
|
change_frozen INT NOT NULL DEFAULT 0,
|
||||||
|
change_used INT NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
available_after INT NOT NULL DEFAULT 0,
|
||||||
|
frozen_after INT NOT NULL DEFAULT 0,
|
||||||
|
used_after INT NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
order_id INT NULL,
|
||||||
|
order_no VARCHAR(64) NULL,
|
||||||
|
remark VARCHAR(255) NULL,
|
||||||
|
|
||||||
|
tenant_id INT NOT NULL,
|
||||||
|
create_time DATETIME NULL,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
|
||||||
|
KEY idx_ticket_log_user (tenant_id, user_id),
|
||||||
|
KEY idx_ticket_log_ticket (tenant_id, user_ticket_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
61
docs/ai/README.md
Normal file
61
docs/ai/README.md
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
# AI 模块(Ollama + RAG + 订单分析)
|
||||||
|
|
||||||
|
## 1. 配置
|
||||||
|
|
||||||
|
见 `src/main/resources/application.yml`:
|
||||||
|
|
||||||
|
- `ai.ollama.base-url`:主地址(例如 `https://ai-api.websoft.top`)
|
||||||
|
- `ai.ollama.fallback-url`:备用地址(例如 `http://47.119.165.234:11434`)
|
||||||
|
- `ai.ollama.chat-model`:对话模型(`qwen3.5:cloud`)
|
||||||
|
- `ai.ollama.embed-model`:向量模型(`qwen3-embedding:4b`)
|
||||||
|
|
||||||
|
## 2. 建表(知识库)
|
||||||
|
|
||||||
|
执行:`docs/ai/ai_kb_tables.sql`
|
||||||
|
|
||||||
|
## 3. API
|
||||||
|
|
||||||
|
说明:所有接口默认需要登录(`@PreAuthorize("isAuthenticated()")`),并且要求能够拿到 `tenantId`(header 或登录用户)。
|
||||||
|
|
||||||
|
### 3.1 对话
|
||||||
|
|
||||||
|
- `GET /api/ai/models`:获取 Ollama 模型列表
|
||||||
|
- `POST /api/ai/chat`:非流式对话
|
||||||
|
- `POST /api/ai/chat/stream`:流式对话(SSE)
|
||||||
|
- `GET /api/ai/chat/stream?prompt=...`:流式对话(SSE,适配 EventSource)
|
||||||
|
|
||||||
|
请求示例(非流式):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"prompt": "帮我写一个退款流程说明"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 知识库(RAG)
|
||||||
|
|
||||||
|
- `POST /api/ai/kb/upload`:上传文档入库(建议 txt/md/html)
|
||||||
|
- `POST /api/ai/kb/sync/cms`:同步 CMS 已发布文章到知识库(当前租户)
|
||||||
|
- `POST /api/ai/kb/query`:仅检索 topK
|
||||||
|
- `POST /api/ai/kb/ask`:检索 + 生成答案(答案要求引用 chunk_id)
|
||||||
|
|
||||||
|
请求示例(ask):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "怎么开具发票?",
|
||||||
|
"topK": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 商城订单分析(按租户/按天)
|
||||||
|
|
||||||
|
- `POST /api/ai/analytics/query`:返回按天指标数据
|
||||||
|
- `POST /api/ai/analytics/ask`:基于指标数据生成分析结论
|
||||||
|
|
||||||
|
请求示例(ask):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "最近30天支付率有没有明显下滑?请给出原因排查建议。",
|
||||||
|
"startDate": "2026-02-01",
|
||||||
|
"endDate": "2026-02-27"
|
||||||
|
}
|
||||||
|
```
|
||||||
39
docs/ai/ai_kb_tables.sql
Normal file
39
docs/ai/ai_kb_tables.sql
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
-- AI 知识库(RAG)建表脚本(MySQL)
|
||||||
|
-- 说明:本项目使用 MyBatis-Plus 默认命名规则(AiKbDocument -> ai_kb_document)。
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `ai_kb_document` (
|
||||||
|
`document_id` INT NOT NULL AUTO_INCREMENT COMMENT '文档ID',
|
||||||
|
`title` VARCHAR(255) NULL COMMENT '标题',
|
||||||
|
`source_type` VARCHAR(32) NULL COMMENT '来源类型:upload/cms',
|
||||||
|
`source_id` INT NULL COMMENT '来源ID(如 cms.article_id)',
|
||||||
|
`source_ref` VARCHAR(255) NULL COMMENT '来源引用(如文件名、文章 code)',
|
||||||
|
`content_hash` CHAR(64) NULL COMMENT '内容hash(SHA-256),用于增量同步',
|
||||||
|
`status` TINYINT NULL DEFAULT 0 COMMENT '状态',
|
||||||
|
`deleted` TINYINT NULL DEFAULT 0 COMMENT '逻辑删除:0否1是',
|
||||||
|
`tenant_id` INT NOT NULL COMMENT '租户ID',
|
||||||
|
`update_time` DATETIME NULL COMMENT '更新时间',
|
||||||
|
`create_time` DATETIME NULL COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`document_id`),
|
||||||
|
KEY `idx_ai_kb_document_tenant` (`tenant_id`),
|
||||||
|
KEY `idx_ai_kb_document_source` (`tenant_id`, `source_type`, `source_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI 知识库文档';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `ai_kb_chunk` (
|
||||||
|
`id` INT NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||||
|
`document_id` INT NOT NULL COMMENT '文档ID',
|
||||||
|
`chunk_id` VARCHAR(64) NOT NULL COMMENT 'chunk 唯一ID(用于引用)',
|
||||||
|
`chunk_index` INT NULL COMMENT 'chunk 序号',
|
||||||
|
`title` VARCHAR(255) NULL COMMENT '标题(冗余,便于展示)',
|
||||||
|
`content` LONGTEXT NULL COMMENT 'chunk 文本',
|
||||||
|
`content_hash` CHAR(64) NULL COMMENT 'chunk 内容hash',
|
||||||
|
`embedding` LONGTEXT NULL COMMENT 'embedding(JSON数组)',
|
||||||
|
`embedding_norm` DOUBLE NULL COMMENT 'embedding L2 范数',
|
||||||
|
`deleted` TINYINT NULL DEFAULT 0 COMMENT '逻辑删除:0否1是',
|
||||||
|
`tenant_id` INT NOT NULL COMMENT '租户ID',
|
||||||
|
`create_time` DATETIME NULL COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_ai_kb_chunk_chunk_id` (`chunk_id`),
|
||||||
|
KEY `idx_ai_kb_chunk_tenant` (`tenant_id`),
|
||||||
|
KEY `idx_ai_kb_chunk_document` (`document_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI 知识库 chunk';
|
||||||
|
|
||||||
14
docs/sql/2026-02-06_glt_ticket_order_delivery_fields.sql
Normal file
14
docs/sql/2026-02-06_glt_ticket_order_delivery_fields.sql
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
-- 水票配送订单:配送流程字段(需在数据库执行)
|
||||||
|
-- 表:glt_ticket_order
|
||||||
|
|
||||||
|
ALTER TABLE glt_ticket_order2
|
||||||
|
ADD COLUMN delivery_status INT NULL DEFAULT 10 COMMENT '配送状态:10待配送、20配送中、30待客户确认、40已完成',
|
||||||
|
ADD COLUMN send_start_time DATETIME NULL COMMENT '开始配送时间',
|
||||||
|
ADD COLUMN send_end_time DATETIME NULL COMMENT '确认送达时间',
|
||||||
|
ADD COLUMN send_end_img VARCHAR(512) NULL COMMENT '送达拍照留档图片URL',
|
||||||
|
ADD COLUMN receive_confirm_time DATETIME NULL COMMENT '客户确认收货时间',
|
||||||
|
ADD COLUMN receive_confirm_type INT NULL COMMENT '确认方式:10手动、20照片、30超时';
|
||||||
|
|
||||||
|
CREATE INDEX idx_glt_ticket_order_rider_status ON glt_ticket_order (tenant_id, rider_id, delivery_status, deleted);
|
||||||
|
CREATE INDEX idx_glt_ticket_order_user_status ON glt_ticket_order (tenant_id, user_id, delivery_status, deleted);
|
||||||
|
|
||||||
98
docs/水票配送订单-后端提示词.md
Normal file
98
docs/水票配送订单-后端提示词.md
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
# 水票配送订单:后端提示词(可直接发给后端)
|
||||||
|
|
||||||
|
> 目标:把“水票下单后 -> 配送员接单/配送 -> 用户确认 -> 自动确认”的闭环放到后端,用明确的字段 + 状态机校验保证不越权、不乱跳状态、并发不重复接单。
|
||||||
|
>
|
||||||
|
> 接口前缀:当前后端控制器为 `@RequestMapping("/api/glt/glt-ticket-order")`,下文默认都带 `/api` 前缀(如需兼容旧路径,可做网关转发或保留旧路由)。
|
||||||
|
|
||||||
|
## 0) 角色与权限边界(务必在后端兜底)
|
||||||
|
- 用户端(小程序用户):只能看/操作自己的订单(`userId` = token userId)。
|
||||||
|
- 配送员端:只能看/操作分配给自己的订单(`riderId` = token userId / rider userId)。
|
||||||
|
- 管理端:按后台权限控制(可查询/派单/改状态,但仍需 tenantId 隔离)。
|
||||||
|
|
||||||
|
建议:对“配送员端接口”忽略前端传入的 `riderId/userId/tenantId`,统一从登录态注入,避免越权。
|
||||||
|
|
||||||
|
## 1) 订单查询(配送员端)
|
||||||
|
建议提供配送员专用分页接口:`GET /api/glt/glt-ticket-order/rider/page`(避免与后台管理分页混用)。
|
||||||
|
请支持以下筛选,并保证权限隔离:
|
||||||
|
- `deliveryStatus`:10待配送、20配送中、30待客户确认、40已完成(配送员端必要;不传默认=10)
|
||||||
|
- `keywords`:支持按地址/备注等模糊搜索(可选)
|
||||||
|
- 排序:建议默认 `sendTime asc, createTime desc`(或沿用后端默认排序,但请告知前端)
|
||||||
|
|
||||||
|
权限隔离要求(配送员端):
|
||||||
|
- 只返回当前登录配送员的订单:后端强制 `param.riderId = loginUserId`(前端传不传都一样)。
|
||||||
|
- `tenantId/deleted` 等同样后端兜底(只查当前租户、只查未删除)。
|
||||||
|
|
||||||
|
返回字段建议(配送员端用得上):
|
||||||
|
- 门店/仓库/用户/配送员的展示字段:`storeName/storeAddress/storePhone`、`warehouseName/warehouseAddress`、`nickname/phone/avatar`、`riderName/riderPhone`(现有 `pageRel/listRel` 已在做关联返回)。
|
||||||
|
- 导航相关(详见第 5 节):收货地址 `lat/lng`、门店/仓库 `lngAndLat`(可关联返回或做快照字段)。
|
||||||
|
|
||||||
|
## 2) 配送流程字段(建议后端落库并回传)
|
||||||
|
订单表建议确保有以下字段(当前前端已按这些字段做流程判断/展示):
|
||||||
|
- `riderId/riderName/riderPhone`:配送员信息
|
||||||
|
- `deliveryStatus`:10/20/30/40
|
||||||
|
- `sendStartTime`:配送员点击“开始配送”的时间(建议 datetime)
|
||||||
|
- `sendEndTime`:配送员点击“确认送达”的时间(建议 datetime)
|
||||||
|
- `sendEndImg`:送达拍照留档图片 URL(可选/必填由后端策略决定;建议 varchar(512))
|
||||||
|
- `receiveConfirmTime`:客户确认收货时间(建议 datetime)
|
||||||
|
- `receiveConfirmType`:10客户手动确认、20配送照片自动确认、30超时自动确认
|
||||||
|
|
||||||
|
数据库变更(示例SQL见:`docs/sql/2026-02-06_glt_ticket_order_delivery_fields.sql`)。
|
||||||
|
|
||||||
|
强烈建议把“配送状态”与“业务状态(status=0/1、deleted=0/1)”分开,避免混用:
|
||||||
|
- `status/deleted`:系统通用字段(现有逻辑)
|
||||||
|
- `deliveryStatus`:配送流程状态(本需求新增)
|
||||||
|
|
||||||
|
## 3) 状态流转与校验(强烈建议在后端做)
|
||||||
|
请在更新订单时做状态机校验,避免前端绕过流程:
|
||||||
|
- `10 -> 20`:仅允许订单属于当前配送员,且未开始/未送达
|
||||||
|
- `20 -> 30`:配送员确认送达(可带 `sendEndImg`)
|
||||||
|
- `20/30 -> 40`:完成;来源可能是
|
||||||
|
- 客户手动确认(写 `receiveConfirmTime` + `receiveConfirmType=10`)
|
||||||
|
- 配送照片直接完成(写 `receiveConfirmTime` + `receiveConfirmType=20`,并要求 `sendEndImg`)
|
||||||
|
- 超时自动确认(写 `receiveConfirmTime` + `receiveConfirmType=30`,建议由定时任务执行)
|
||||||
|
|
||||||
|
并发/幂等建议(避免重复点击/重复请求带来的脏数据):
|
||||||
|
- 所有“状态变更接口”用条件更新实现原子校验:`UPDATE ... SET ... WHERE id=? AND rider_id=? AND delivery_status=? AND deleted=0`
|
||||||
|
- 对重复调用做幂等:
|
||||||
|
- `start`:如果已是 20 则直接返回成功;如果已到 30/40 返回“状态不允许”
|
||||||
|
- `delivered`:如果已是 30/40 则返回成功(或提示已送达);避免重复写 `sendEndTime`
|
||||||
|
- `confirm-receive`:如果已是 40 则返回成功(或提示已完成)
|
||||||
|
|
||||||
|
## 4) 建议新增/明确的接口能力
|
||||||
|
为了避免并发抢单/越权更新,建议新增更语义化的接口(或在 update 内做等价校验):
|
||||||
|
- 接单(抢单/派单):`POST /api/glt/glt-ticket-order/{id}/accept`
|
||||||
|
- 配送员端:后端原子校验:仅当 `rider_id IS NULL`(或为 0)时才能写入当前 rider 信息
|
||||||
|
- 管理端派单:允许传 `riderId`,但需校验骑手归属门店/租户(如有该约束)
|
||||||
|
- 开始配送:`POST /api/glt/glt-ticket-order/{id}/start`
|
||||||
|
- 写:`sendStartTime=now`、`deliveryStatus=20`
|
||||||
|
- 校验:必须 `riderId=当前登录配送员` 且当前 `deliveryStatus=10`
|
||||||
|
- 确认送达:`POST /api/glt/glt-ticket-order/{id}/delivered`
|
||||||
|
- 入参:`sendEndImg`(可选/必填,按策略)
|
||||||
|
- 写:`sendEndTime=now`、`deliveryStatus=30`、`sendEndImg`
|
||||||
|
- 可选策略 A(推荐可配置):若 `sendEndImg` 必填且存在,则可直接 `deliveryStatus=40` 并写 `receiveConfirmTime/Type=20`
|
||||||
|
- 客户确认收货:`POST /api/glt/glt-ticket-order/{id}/confirm-receive`
|
||||||
|
- 校验:只能本人 `userId` 操作,且必须 `deliveryStatus=30`
|
||||||
|
- 写:`deliveryStatus=40`、`receiveConfirmTime=now`、`receiveConfirmType=10`
|
||||||
|
|
||||||
|
接口返回建议:
|
||||||
|
- 成功统一返回 `ApiResult.success(...)`
|
||||||
|
- 失败请返回明确 msg(例如:`无权限`、`订单不存在`、`订单状态不允许`、`订单已被其他配送员接单`)
|
||||||
|
|
||||||
|
## 5) 为了“导航到收货地址/取货点”的字段补充(建议)
|
||||||
|
当前仅有 `address` 字符串,无法在小程序内 `openLocation` 精准导航;建议补充:
|
||||||
|
- 收货地址(推荐至少返回):`receiverName`、`receiverPhone`、`province/city/region/address/fullAddress`、`lat/lng`
|
||||||
|
- 取货点(门店/仓库,推荐至少返回):`store.lngAndLat`、`warehouse.lngAndLat`
|
||||||
|
|
||||||
|
实现方式二选一:
|
||||||
|
- 方式 A(更快):查询时关联 `shop_user_address`、`shop_store`、`shop_warehouse`,把经纬度字段透出给前端。
|
||||||
|
- 方式 B(更稳):下单时把收货地址的 `name/phone/lat/lng/fullAddress` 以及门店/仓库 `lngAndLat` 做快照写入订单,避免后续数据变更影响历史订单导航。
|
||||||
|
|
||||||
|
## 6)(可选但很有用)超时自动确认规则
|
||||||
|
- 建议后端提供可配置项:`autoConfirmHours`(例如 24h/48h)
|
||||||
|
- 定时任务扫描:`deliveryStatus=30` 且 `sendEndTime < now - autoConfirmHours` 的订单
|
||||||
|
- 原子更新:只更新仍处于 30 的订单,写入 `deliveryStatus=40`、`receiveConfirmTime=now`、`receiveConfirmType=30`
|
||||||
|
|
||||||
|
## 7)(可选)字段/枚举建议(便于前后端对齐)
|
||||||
|
- `deliveryStatus`:10待配送、20配送中、30待客户确认、40已完成
|
||||||
|
- `receiveConfirmType`:10客户手动确认、20配送照片自动确认、30超时自动确认
|
||||||
|
- 时间字段统一返回格式:`yyyy-MM-dd HH:mm:ss`(与项目现有 `@JsonFormat` 风格一致)
|
||||||
5
pom.xml
5
pom.xml
@@ -38,6 +38,11 @@
|
|||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- spring-boot-web -->
|
<!-- spring-boot-web -->
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
###############################################################################
|
|
||||||
# 捐款证书中文乱码修复脚本
|
|
||||||
# 用途:在运行中的Docker容器内安装中文字体
|
|
||||||
# 适用于:无法重新构建镜像的紧急情况
|
|
||||||
###############################################################################
|
|
||||||
|
|
||||||
set -e # 遇到错误立即退出
|
|
||||||
|
|
||||||
# 颜色输出
|
|
||||||
RED='\033[0;31m'
|
|
||||||
GREEN='\033[0;32m'
|
|
||||||
YELLOW='\033[1;33m'
|
|
||||||
NC='\033[0m' # No Color
|
|
||||||
|
|
||||||
# 容器名称(可根据实际情况修改)
|
|
||||||
CONTAINER_NAME="websoft-api-container"
|
|
||||||
|
|
||||||
echo -e "${GREEN}================================${NC}"
|
|
||||||
echo -e "${GREEN}中文字体修复脚本${NC}"
|
|
||||||
echo -e "${GREEN}================================${NC}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 检查容器是否存在
|
|
||||||
echo -e "${YELLOW}步骤 1/6: 检查容器状态...${NC}"
|
|
||||||
if ! docker ps | grep -q "$CONTAINER_NAME"; then
|
|
||||||
echo -e "${RED}错误:容器 $CONTAINER_NAME 未运行!${NC}"
|
|
||||||
echo "当前运行的容器:"
|
|
||||||
docker ps --format "table {{.Names}}\t{{.Status}}"
|
|
||||||
echo ""
|
|
||||||
read -p "请输入正确的容器名称: " CONTAINER_NAME
|
|
||||||
if [ -z "$CONTAINER_NAME" ]; then
|
|
||||||
echo -e "${RED}容器名称不能为空,退出。${NC}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
echo -e "${GREEN}✓ 容器正在运行${NC}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 检查是否已安装字体
|
|
||||||
echo -e "${YELLOW}步骤 2/6: 检查是否已安装中文字体...${NC}"
|
|
||||||
if docker exec "$CONTAINER_NAME" fc-list :lang=zh 2>/dev/null | grep -q "WenQuanYi"; then
|
|
||||||
echo -e "${GREEN}✓ 中文字体已安装${NC}"
|
|
||||||
docker exec "$CONTAINER_NAME" fc-list :lang=zh
|
|
||||||
echo ""
|
|
||||||
read -p "是否重新安装?(y/N): " REINSTALL
|
|
||||||
if [[ ! "$REINSTALL" =~ ^[Yy]$ ]]; then
|
|
||||||
echo "跳过安装,退出。"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo -e "${YELLOW}未检测到中文字体,开始安装...${NC}"
|
|
||||||
fi
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 安装字体工具
|
|
||||||
echo -e "${YELLOW}步骤 3/6: 安装字体工具...${NC}"
|
|
||||||
docker exec -u root "$CONTAINER_NAME" sh -c "apk add --no-cache fontconfig ttf-dejavu wget" || {
|
|
||||||
echo -e "${RED}✗ 字体工具安装失败${NC}"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
echo -e "${GREEN}✓ 字体工具安装成功${NC}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 下载中文字体
|
|
||||||
echo -e "${YELLOW}步骤 4/6: 下载文泉驿微米黑字体...${NC}"
|
|
||||||
echo "正在从GitHub下载(约10MB),请稍候..."
|
|
||||||
docker exec -u root "$CONTAINER_NAME" sh -c "
|
|
||||||
wget -O /tmp/wqy-microhei.ttc https://github.com/anthonyfok/fonts-wqy-microhei/raw/master/wqy-microhei.ttc 2>&1 | grep -E 'Connecting|Length|saved' || true
|
|
||||||
" || {
|
|
||||||
echo -e "${YELLOW}GitHub下载失败,尝试使用代理...${NC}"
|
|
||||||
docker exec -u root "$CONTAINER_NAME" sh -c "
|
|
||||||
wget -O /tmp/wqy-microhei.ttc https://ghproxy.com/https://github.com/anthonyfok/fonts-wqy-microhei/raw/master/wqy-microhei.ttc
|
|
||||||
" || {
|
|
||||||
echo -e "${RED}✗ 字体下载失败${NC}"
|
|
||||||
echo "请检查网络连接或手动下载字体文件。"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
echo -e "${GREEN}✓ 字体下载成功${NC}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 安装字体
|
|
||||||
echo -e "${YELLOW}步骤 5/6: 安装字体文件...${NC}"
|
|
||||||
docker exec -u root "$CONTAINER_NAME" sh -c "
|
|
||||||
mkdir -p /usr/share/fonts/truetype/wqy && \
|
|
||||||
mv /tmp/wqy-microhei.ttc /usr/share/fonts/truetype/wqy/ && \
|
|
||||||
fc-cache -fv
|
|
||||||
" || {
|
|
||||||
echo -e "${RED}✗ 字体安装失败${NC}"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
echo -e "${GREEN}✓ 字体安装成功${NC}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 验证安装
|
|
||||||
echo -e "${YELLOW}步骤 6/6: 验证字体安装...${NC}"
|
|
||||||
FONT_COUNT=$(docker exec "$CONTAINER_NAME" fc-list :lang=zh | wc -l)
|
|
||||||
if [ "$FONT_COUNT" -gt 0 ]; then
|
|
||||||
echo -e "${GREEN}✓ 中文字体验证成功!${NC}"
|
|
||||||
echo "已安装的中文字体:"
|
|
||||||
docker exec "$CONTAINER_NAME" fc-list :lang=zh
|
|
||||||
else
|
|
||||||
echo -e "${RED}✗ 字体验证失败${NC}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# 完成提示
|
|
||||||
echo -e "${GREEN}================================${NC}"
|
|
||||||
echo -e "${GREEN}修复完成!${NC}"
|
|
||||||
echo -e "${GREEN}================================${NC}"
|
|
||||||
echo ""
|
|
||||||
echo "后续步骤:"
|
|
||||||
echo "1. 不需要重启容器,字体已生效"
|
|
||||||
echo "2. 重新生成捐款证书即可看到效果"
|
|
||||||
echo "3. 如果仍有问题,请查看容器日志:"
|
|
||||||
echo " docker logs -f $CONTAINER_NAME"
|
|
||||||
echo ""
|
|
||||||
echo -e "${YELLOW}注意:${NC}"
|
|
||||||
echo "- 此修复方法在容器重启后会失效"
|
|
||||||
echo "- 建议后续使用更新后的Dockerfile重新构建镜像"
|
|
||||||
echo "- 详细文档请参考:docs/chinese-font-fix-guide.md"
|
|
||||||
echo ""
|
|
||||||
194
src/main/java/com/gxwebsoft/ai/client/OllamaClient.java
Normal file
194
src/main/java/com/gxwebsoft/ai/client/OllamaClient.java
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
package com.gxwebsoft.ai.client;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.gxwebsoft.ai.client.dto.*;
|
||||||
|
import com.gxwebsoft.ai.config.AiOllamaProperties;
|
||||||
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
|
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||||
|
import okhttp3.*;
|
||||||
|
import okio.BufferedSource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量 Ollama HTTP Client(兼容 /api/chat、/api/embeddings、/api/tags)。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class OllamaClient {
|
||||||
|
@Resource
|
||||||
|
private AiOllamaProperties props;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private volatile OkHttpClient http;
|
||||||
|
|
||||||
|
private OkHttpClient http() {
|
||||||
|
OkHttpClient c = http;
|
||||||
|
if (c != null) {
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
synchronized (this) {
|
||||||
|
if (http == null) {
|
||||||
|
http = new OkHttpClient.Builder()
|
||||||
|
.connectTimeout(Duration.ofMillis(props.getConnectTimeoutMs()))
|
||||||
|
.readTimeout(Duration.ofMillis(props.getReadTimeoutMs()))
|
||||||
|
.writeTimeout(Duration.ofMillis(props.getWriteTimeoutMs()))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
return http;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public OllamaTagsResponse tags() {
|
||||||
|
return getJson("/api/tags", OllamaTagsResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public OllamaChatResponse chat(OllamaChatRequest req) {
|
||||||
|
if (req.getStream() == null) {
|
||||||
|
req.setStream(false);
|
||||||
|
}
|
||||||
|
return postJson("/api/chat", req, OllamaChatResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流式对话:Ollama 会返回按行分隔的 JSON。
|
||||||
|
*/
|
||||||
|
public void chatStream(OllamaChatRequest req, Consumer<OllamaChatResponse> onEvent) {
|
||||||
|
Objects.requireNonNull(onEvent, "onEvent");
|
||||||
|
if (req.getStream() == null) {
|
||||||
|
req.setStream(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Request request = buildPost(baseUrl(), "/api/chat", JSONUtil.toJSONString(req));
|
||||||
|
try (Response resp = http().newCall(request).execute()) {
|
||||||
|
if (!resp.isSuccessful()) {
|
||||||
|
throw new BusinessException("Ollama chat stream failed: HTTP " + resp.code());
|
||||||
|
}
|
||||||
|
ResponseBody body = resp.body();
|
||||||
|
if (body == null) {
|
||||||
|
throw new BusinessException("Ollama chat stream failed: empty body");
|
||||||
|
}
|
||||||
|
|
||||||
|
BufferedSource source = body.source();
|
||||||
|
String line;
|
||||||
|
while ((line = source.readUtf8Line()) != null) {
|
||||||
|
line = line.trim();
|
||||||
|
if (line.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
OllamaChatResponse event = objectMapper.readValue(line, OllamaChatResponse.class);
|
||||||
|
onEvent.accept(event);
|
||||||
|
if (Boolean.TRUE.equals(event.getDone())) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("Ollama chat stream IO error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public OllamaEmbeddingResponse embedding(String prompt) {
|
||||||
|
OllamaEmbeddingRequest req = new OllamaEmbeddingRequest();
|
||||||
|
req.setModel(props.getEmbedModel());
|
||||||
|
req.setPrompt(prompt);
|
||||||
|
return postJson("/api/embeddings", req, OllamaEmbeddingResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String baseUrl() {
|
||||||
|
if (props.getBaseUrl() == null || props.getBaseUrl().trim().isEmpty()) {
|
||||||
|
throw new BusinessException("ai.ollama.base-url 未配置");
|
||||||
|
}
|
||||||
|
return props.getBaseUrl().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String fallbackUrl() {
|
||||||
|
if (props.getFallbackUrl() == null || props.getFallbackUrl().trim().isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return props.getFallbackUrl().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T getJson(String path, Class<T> clazz) {
|
||||||
|
try {
|
||||||
|
return getJsonOnce(baseUrl(), path, clazz);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String fb = fallbackUrl();
|
||||||
|
if (fb == null) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
return getJsonOnce(fb, path, clazz);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T getJsonOnce(String base, String path, Class<T> clazz) {
|
||||||
|
Request req = new Request.Builder()
|
||||||
|
.url(join(base, path))
|
||||||
|
.get()
|
||||||
|
.build();
|
||||||
|
try (Response resp = http().newCall(req).execute()) {
|
||||||
|
if (!resp.isSuccessful()) {
|
||||||
|
throw new BusinessException("Ollama GET failed: HTTP " + resp.code());
|
||||||
|
}
|
||||||
|
ResponseBody body = resp.body();
|
||||||
|
if (body == null) {
|
||||||
|
throw new BusinessException("Ollama GET failed: empty body");
|
||||||
|
}
|
||||||
|
return objectMapper.readValue(body.string(), clazz);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("Ollama GET IO error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T postJson(String path, Object payload, Class<T> clazz) {
|
||||||
|
String json = JSONUtil.toJSONString(payload);
|
||||||
|
try {
|
||||||
|
return postJsonOnce(baseUrl(), path, json, clazz);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String fb = fallbackUrl();
|
||||||
|
if (fb == null) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
return postJsonOnce(fb, path, json, clazz);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T postJsonOnce(String base, String path, String json, Class<T> clazz) {
|
||||||
|
Request req = buildPost(base, path, json);
|
||||||
|
try (Response resp = http().newCall(req).execute()) {
|
||||||
|
if (!resp.isSuccessful()) {
|
||||||
|
throw new BusinessException("Ollama POST failed: HTTP " + resp.code());
|
||||||
|
}
|
||||||
|
ResponseBody body = resp.body();
|
||||||
|
if (body == null) {
|
||||||
|
throw new BusinessException("Ollama POST failed: empty body");
|
||||||
|
}
|
||||||
|
return objectMapper.readValue(body.string(), clazz);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("Ollama POST IO error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Request buildPost(String base, String path, String json) {
|
||||||
|
RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
|
||||||
|
return new Request.Builder()
|
||||||
|
.url(join(base, path))
|
||||||
|
.post(body)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String join(String base, String path) {
|
||||||
|
String b = base;
|
||||||
|
if (b.endsWith("/")) {
|
||||||
|
b = b.substring(0, b.length() - 1);
|
||||||
|
}
|
||||||
|
String p = path.startsWith("/") ? path : ("/" + path);
|
||||||
|
return b + p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OllamaChatRequest {
|
||||||
|
private String model;
|
||||||
|
private List<OllamaMessage> messages;
|
||||||
|
private Boolean stream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ollama options,例如:temperature、top_k、top_p、num_predict...
|
||||||
|
*/
|
||||||
|
private Map<String, Object> options;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class OllamaChatResponse {
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private String createdAt;
|
||||||
|
|
||||||
|
private OllamaMessage message;
|
||||||
|
|
||||||
|
private Boolean done;
|
||||||
|
|
||||||
|
@JsonProperty("total_duration")
|
||||||
|
private Long totalDuration;
|
||||||
|
|
||||||
|
@JsonProperty("prompt_eval_count")
|
||||||
|
private Integer promptEvalCount;
|
||||||
|
|
||||||
|
@JsonProperty("eval_count")
|
||||||
|
private Integer evalCount;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OllamaEmbeddingRequest {
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ollama embeddings 目前常用字段为 prompt。
|
||||||
|
*/
|
||||||
|
private String prompt;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class OllamaEmbeddingResponse {
|
||||||
|
private List<Double> embedding;
|
||||||
|
}
|
||||||
|
|
||||||
14
src/main/java/com/gxwebsoft/ai/client/dto/OllamaMessage.java
Normal file
14
src/main/java/com/gxwebsoft/ai/client/dto/OllamaMessage.java
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class OllamaMessage {
|
||||||
|
private String role;
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.gxwebsoft.ai.client.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class OllamaTagsResponse {
|
||||||
|
private List<Model> models;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public static class Model {
|
||||||
|
private String name;
|
||||||
|
private Long size;
|
||||||
|
private String digest;
|
||||||
|
private String modified_at;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.gxwebsoft.ai.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ollama API 配置。
|
||||||
|
*
|
||||||
|
* 说明:本项目通过自建 Ollama 网关提供服务,因此这里用 baseUrl + fallbackUrl。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "ai.ollama")
|
||||||
|
public class AiOllamaProperties {
|
||||||
|
/**
|
||||||
|
* 主地址,例如:https://ai-api.websoft.top
|
||||||
|
*/
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 备用地址,例如:http://47.119.165.234:11434
|
||||||
|
*/
|
||||||
|
private String fallbackUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对话模型,例如:qwen3.5:cloud
|
||||||
|
*/
|
||||||
|
private String chatModel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向量模型,例如:qwen3-embedding:4b
|
||||||
|
*/
|
||||||
|
private String embedModel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 超时(毫秒)。
|
||||||
|
*/
|
||||||
|
private long connectTimeoutMs = 10_000;
|
||||||
|
private long readTimeoutMs = 300_000;
|
||||||
|
private long writeTimeoutMs = 60_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 并发上限(用于 embedding/入库等批处理场景)。
|
||||||
|
*/
|
||||||
|
private int maxConcurrency = 4;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RAG:检索候选 chunk 最大数量(避免一次性拉取过多数据导致内存/耗时过高)。
|
||||||
|
*/
|
||||||
|
private int ragMaxCandidates = 2000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RAG:检索返回 topK。
|
||||||
|
*/
|
||||||
|
private int ragTopK = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RAG:单个 chunk 最大字符数(用于入库切分)。
|
||||||
|
*/
|
||||||
|
private int ragChunkSize = 800;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RAG:chunk 重叠字符数(用于减少语义断裂)。
|
||||||
|
*/
|
||||||
|
private int ragChunkOverlap = 120;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.gxwebsoft.ai.controller;
|
||||||
|
|
||||||
|
import com.gxwebsoft.ai.dto.*;
|
||||||
|
import com.gxwebsoft.ai.service.AiAnalyticsService;
|
||||||
|
import com.gxwebsoft.common.core.web.ApiResult;
|
||||||
|
import com.gxwebsoft.common.core.web.BaseController;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
@Tag(name = "AI - 订单数据分析")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ai/analytics")
|
||||||
|
public class AiAnalyticsController extends BaseController {
|
||||||
|
@Resource
|
||||||
|
private AiAnalyticsService analyticsService;
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "查询商城订单按天指标(当前租户)")
|
||||||
|
@PostMapping("/query")
|
||||||
|
public ApiResult<AiShopMetricsQueryResult> query(@RequestBody AiShopMetricsQueryRequest request) {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(analyticsService.queryShopMetrics(tenantId, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "AI 解析并输出订单分析结论(当前租户)")
|
||||||
|
@PostMapping("/ask")
|
||||||
|
public ApiResult<AiAnalyticsAskResult> ask(@RequestBody AiAnalyticsAskRequest request) {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(analyticsService.askShopAnalytics(tenantId, request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package com.gxwebsoft.ai.controller;
|
||||||
|
|
||||||
|
import com.gxwebsoft.ai.client.OllamaClient;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaChatResponse;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaTagsResponse;
|
||||||
|
import com.gxwebsoft.ai.dto.AiChatRequest;
|
||||||
|
import com.gxwebsoft.ai.dto.AiChatResult;
|
||||||
|
import com.gxwebsoft.ai.dto.AiMessage;
|
||||||
|
import com.gxwebsoft.ai.service.AiChatService;
|
||||||
|
import com.gxwebsoft.common.core.web.ApiResult;
|
||||||
|
import com.gxwebsoft.common.core.web.BaseController;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
@Tag(name = "AI - 对话")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ai")
|
||||||
|
public class AiChatController extends BaseController {
|
||||||
|
@Resource
|
||||||
|
private OllamaClient ollamaClient;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AiChatService aiChatService;
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "获取 Ollama 模型列表")
|
||||||
|
@GetMapping("/models")
|
||||||
|
public ApiResult<OllamaTagsResponse> models() {
|
||||||
|
return success(ollamaClient.tags());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "非流式对话")
|
||||||
|
@PostMapping("/chat")
|
||||||
|
public ApiResult<AiChatResult> chat(@RequestBody AiChatRequest request) {
|
||||||
|
return success(aiChatService.chat(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "流式对话(SSE)")
|
||||||
|
@PostMapping("/chat/stream")
|
||||||
|
public SseEmitter chatStream(@RequestBody AiChatRequest request) {
|
||||||
|
// 10 分钟超时(可根据前端需要调整)
|
||||||
|
SseEmitter emitter = new SseEmitter(10 * 60 * 1000L);
|
||||||
|
|
||||||
|
CompletableFuture.runAsync(() -> {
|
||||||
|
try {
|
||||||
|
aiChatService.chatStream(request,
|
||||||
|
delta -> {
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event().name("delta").data(delta));
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 客户端断开会触发 send 异常,这里直接结束即可
|
||||||
|
emitter.complete();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(OllamaChatResponse done) -> {
|
||||||
|
try {
|
||||||
|
Map<String, Object> meta = new LinkedHashMap<>();
|
||||||
|
meta.put("model", done.getModel());
|
||||||
|
meta.put("prompt_eval_count", done.getPromptEvalCount());
|
||||||
|
meta.put("eval_count", done.getEvalCount());
|
||||||
|
meta.put("total_duration", done.getTotalDuration());
|
||||||
|
emitter.send(SseEmitter.event().name("done").data(meta));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
} finally {
|
||||||
|
emitter.complete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "流式对话(SSE, GET 版本,便于 EventSource)")
|
||||||
|
@GetMapping("/chat/stream")
|
||||||
|
public SseEmitter chatStreamGet(@RequestParam("prompt") String prompt) {
|
||||||
|
AiChatRequest req = new AiChatRequest();
|
||||||
|
req.setMessages(Collections.singletonList(new AiMessage("user", prompt)));
|
||||||
|
return chatStream(req);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.gxwebsoft.ai.controller;
|
||||||
|
|
||||||
|
import com.gxwebsoft.ai.dto.*;
|
||||||
|
import com.gxwebsoft.ai.service.AiKbRagService;
|
||||||
|
import com.gxwebsoft.common.core.web.ApiResult;
|
||||||
|
import com.gxwebsoft.common.core.web.BaseController;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
@Tag(name = "AI - 知识库(RAG)")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ai/kb")
|
||||||
|
public class AiKbController extends BaseController {
|
||||||
|
@Resource
|
||||||
|
private AiKbRagService ragService;
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "上传文档入库(txt/md/html 优先)")
|
||||||
|
@PostMapping("/upload")
|
||||||
|
public ApiResult<AiKbIngestResult> upload(@RequestParam("file") MultipartFile file) {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(ragService.ingestUpload(tenantId, file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "同步 CMS 文章到知识库(当前租户)")
|
||||||
|
@PostMapping("/sync/cms")
|
||||||
|
public ApiResult<AiKbIngestResult> syncCms() {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(ragService.syncCms(tenantId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "仅检索(返回 topK 命中)")
|
||||||
|
@PostMapping("/query")
|
||||||
|
public ApiResult<AiKbQueryResult> query(@RequestBody AiKbQueryRequest request) {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(ragService.query(tenantId, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
@Operation(summary = "知识库问答(RAG 生成 + 返回检索结果)")
|
||||||
|
@PostMapping("/ask")
|
||||||
|
public ApiResult<AiKbAskResult> ask(@RequestBody AiKbAskRequest request) {
|
||||||
|
Integer tenantId = getTenantId();
|
||||||
|
return success(ragService.ask(tenantId, request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiAnalyticsAskRequest", description = "AI 数据分析提问")
|
||||||
|
public class AiAnalyticsAskRequest {
|
||||||
|
private String question;
|
||||||
|
private String startDate;
|
||||||
|
private String endDate;
|
||||||
|
}
|
||||||
|
|
||||||
12
src/main/java/com/gxwebsoft/ai/dto/AiAnalyticsAskResult.java
Normal file
12
src/main/java/com/gxwebsoft/ai/dto/AiAnalyticsAskResult.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiAnalyticsAskResult", description = "AI 数据分析结果")
|
||||||
|
public class AiAnalyticsAskResult {
|
||||||
|
private String analysis;
|
||||||
|
private AiShopMetricsQueryResult data;
|
||||||
|
}
|
||||||
|
|
||||||
35
src/main/java/com/gxwebsoft/ai/dto/AiChatRequest.java
Normal file
35
src/main/java/com/gxwebsoft/ai/dto/AiChatRequest.java
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiChatRequest", description = "AI 对话请求")
|
||||||
|
public class AiChatRequest {
|
||||||
|
@Schema(description = "可选:直接传一句话。若 messages 为空则使用该字段构造 user message")
|
||||||
|
private String prompt;
|
||||||
|
|
||||||
|
@Schema(description = "可选:OpenAI 风格 messages(role: system/user/assistant)")
|
||||||
|
private List<AiMessage> messages;
|
||||||
|
|
||||||
|
@Schema(description = "可选:覆盖默认模型")
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
@Schema(description = "是否流式输出(/chat/stream 端点通常忽略此字段)")
|
||||||
|
private Boolean stream;
|
||||||
|
|
||||||
|
@Schema(description = "temperature")
|
||||||
|
private Double temperature;
|
||||||
|
|
||||||
|
@Schema(description = "top_k")
|
||||||
|
private Integer topK;
|
||||||
|
|
||||||
|
@Schema(description = "top_p")
|
||||||
|
private Double topP;
|
||||||
|
|
||||||
|
@Schema(description = "num_predict(类似 max_tokens)")
|
||||||
|
private Integer numPredict;
|
||||||
|
}
|
||||||
|
|
||||||
15
src/main/java/com/gxwebsoft/ai/dto/AiChatResult.java
Normal file
15
src/main/java/com/gxwebsoft/ai/dto/AiChatResult.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(name = "AiChatResult", description = "AI 对话结果")
|
||||||
|
public class AiChatResult {
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
|
|
||||||
12
src/main/java/com/gxwebsoft/ai/dto/AiKbAskRequest.java
Normal file
12
src/main/java/com/gxwebsoft/ai/dto/AiKbAskRequest.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbAskRequest", description = "知识库问答请求")
|
||||||
|
public class AiKbAskRequest {
|
||||||
|
private String question;
|
||||||
|
private Integer topK;
|
||||||
|
}
|
||||||
|
|
||||||
12
src/main/java/com/gxwebsoft/ai/dto/AiKbAskResult.java
Normal file
12
src/main/java/com/gxwebsoft/ai/dto/AiKbAskResult.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbAskResult", description = "知识库问答结果")
|
||||||
|
public class AiKbAskResult {
|
||||||
|
private String answer;
|
||||||
|
private AiKbQueryResult retrieval;
|
||||||
|
}
|
||||||
|
|
||||||
15
src/main/java/com/gxwebsoft/ai/dto/AiKbHit.java
Normal file
15
src/main/java/com/gxwebsoft/ai/dto/AiKbHit.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbHit", description = "知识库命中")
|
||||||
|
public class AiKbHit {
|
||||||
|
private String chunkId;
|
||||||
|
private Integer documentId;
|
||||||
|
private String title;
|
||||||
|
private Double score;
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
|
|
||||||
15
src/main/java/com/gxwebsoft/ai/dto/AiKbIngestResult.java
Normal file
15
src/main/java/com/gxwebsoft/ai/dto/AiKbIngestResult.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbIngestResult", description = "知识库入库结果")
|
||||||
|
public class AiKbIngestResult {
|
||||||
|
private Integer documentId;
|
||||||
|
private String title;
|
||||||
|
private Integer chunks;
|
||||||
|
private Integer updatedDocuments;
|
||||||
|
private Integer skippedDocuments;
|
||||||
|
}
|
||||||
|
|
||||||
12
src/main/java/com/gxwebsoft/ai/dto/AiKbQueryRequest.java
Normal file
12
src/main/java/com/gxwebsoft/ai/dto/AiKbQueryRequest.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbQueryRequest", description = "知识库检索请求")
|
||||||
|
public class AiKbQueryRequest {
|
||||||
|
private String query;
|
||||||
|
private Integer topK;
|
||||||
|
}
|
||||||
|
|
||||||
13
src/main/java/com/gxwebsoft/ai/dto/AiKbQueryResult.java
Normal file
13
src/main/java/com/gxwebsoft/ai/dto/AiKbQueryResult.java
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbQueryResult", description = "知识库检索结果")
|
||||||
|
public class AiKbQueryResult {
|
||||||
|
private List<AiKbHit> hits;
|
||||||
|
}
|
||||||
|
|
||||||
14
src/main/java/com/gxwebsoft/ai/dto/AiMessage.java
Normal file
14
src/main/java/com/gxwebsoft/ai/dto/AiMessage.java
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class AiMessage {
|
||||||
|
private String role;
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiShopMetricsQueryRequest", description = "商城订单指标查询请求")
|
||||||
|
public class AiShopMetricsQueryRequest {
|
||||||
|
@Schema(description = "开始日期(YYYY-MM-DD)")
|
||||||
|
private String startDate;
|
||||||
|
|
||||||
|
@Schema(description = "结束日期(YYYY-MM-DD),包含该天")
|
||||||
|
private String endDate;
|
||||||
|
|
||||||
|
@Schema(description = "是否按天分组,默认 true")
|
||||||
|
private Boolean groupByDay;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiShopMetricsQueryResult", description = "商城订单指标查询结果")
|
||||||
|
public class AiShopMetricsQueryResult {
|
||||||
|
private Integer tenantId;
|
||||||
|
private String startDate;
|
||||||
|
private String endDate;
|
||||||
|
private List<AiShopMetricsRow> rows;
|
||||||
|
}
|
||||||
|
|
||||||
23
src/main/java/com/gxwebsoft/ai/dto/AiShopMetricsRow.java
Normal file
23
src/main/java/com/gxwebsoft/ai/dto/AiShopMetricsRow.java
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package com.gxwebsoft.ai.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiShopMetricsRow", description = "商城订单指标行(按 tenant/day)")
|
||||||
|
public class AiShopMetricsRow {
|
||||||
|
private Integer tenantId;
|
||||||
|
private String day;
|
||||||
|
|
||||||
|
private Long orderCnt;
|
||||||
|
private Long paidOrderCnt;
|
||||||
|
private BigDecimal gmv;
|
||||||
|
private BigDecimal refundAmt;
|
||||||
|
private Long payUserCnt;
|
||||||
|
|
||||||
|
private BigDecimal aov;
|
||||||
|
private BigDecimal payRate;
|
||||||
|
}
|
||||||
|
|
||||||
57
src/main/java/com/gxwebsoft/ai/entity/AiKbChunk.java
Normal file
57
src/main/java/com/gxwebsoft/ai/entity/AiKbChunk.java
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package com.gxwebsoft.ai.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 知识库分段(chunk)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbChunk", description = "AI 知识库分段")
|
||||||
|
public class AiKbChunk implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
private Integer documentId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部引用用的唯一 ID(便于在答案里引用)。
|
||||||
|
*/
|
||||||
|
private String chunkId;
|
||||||
|
|
||||||
|
private Integer chunkIndex;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
private String contentHash;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* embedding JSON(数组),存成文本便于快速落库。
|
||||||
|
*/
|
||||||
|
private String embedding;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* embedding 的 L2 范数,用于余弦相似度。
|
||||||
|
*/
|
||||||
|
private Double embeddingNorm;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
|
||||||
|
private Integer tenantId;
|
||||||
|
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
|
|
||||||
59
src/main/java/com/gxwebsoft/ai/entity/AiKbDocument.java
Normal file
59
src/main/java/com/gxwebsoft/ai/entity/AiKbDocument.java
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package com.gxwebsoft.ai.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 知识库文档(来源:上传、CMS 等)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(name = "AiKbDocument", description = "AI 知识库文档")
|
||||||
|
public class AiKbDocument implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@TableId(value = "document_id", type = IdType.AUTO)
|
||||||
|
private Integer documentId;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* upload / cms
|
||||||
|
*/
|
||||||
|
private String sourceType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 例如 CMS article_id
|
||||||
|
*/
|
||||||
|
private Integer sourceId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 例如文件名、路径等
|
||||||
|
*/
|
||||||
|
private String sourceRef;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文档文本内容哈希(用于增量同步/去重)。
|
||||||
|
*/
|
||||||
|
private String contentHash;
|
||||||
|
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
|
||||||
|
private Integer tenantId;
|
||||||
|
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
|
|
||||||
10
src/main/java/com/gxwebsoft/ai/mapper/AiKbChunkMapper.java
Normal file
10
src/main/java/com/gxwebsoft/ai/mapper/AiKbChunkMapper.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package com.gxwebsoft.ai.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbChunk;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface AiKbChunkMapper extends BaseMapper<AiKbChunk> {
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.gxwebsoft.ai.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbDocument;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface AiKbDocumentMapper extends BaseMapper<AiKbDocument> {
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.gxwebsoft.ai.mapper;
|
||||||
|
|
||||||
|
import com.gxwebsoft.ai.dto.AiShopMetricsRow;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface AiShopAnalyticsMapper {
|
||||||
|
List<AiShopMetricsRow> queryMetrics(@Param("tenantId") Integer tenantId,
|
||||||
|
@Param("start") LocalDateTime start,
|
||||||
|
@Param("end") LocalDateTime end);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.gxwebsoft.ai.mapper.AiShopAnalyticsMapper">
|
||||||
|
|
||||||
|
<select id="queryMetrics" resultType="com.gxwebsoft.ai.dto.AiShopMetricsRow">
|
||||||
|
SELECT
|
||||||
|
tenant_id,
|
||||||
|
DATE_FORMAT(create_time, '%Y-%m-%d') AS day,
|
||||||
|
COUNT(1) AS order_cnt,
|
||||||
|
SUM(CASE WHEN pay_status = 1 THEN 1 ELSE 0 END) AS paid_order_cnt,
|
||||||
|
SUM(CASE WHEN pay_status = 1 THEN COALESCE(pay_price, 0) ELSE 0 END) AS gmv,
|
||||||
|
SUM(CASE WHEN COALESCE(refund_money, 0) > 0 THEN COALESCE(refund_money, 0) ELSE 0 END) AS refund_amt,
|
||||||
|
COUNT(DISTINCT IF(pay_status = 1, user_id, NULL)) AS pay_user_cnt
|
||||||
|
FROM shop_order
|
||||||
|
WHERE deleted = 0
|
||||||
|
AND tenant_id = #{tenantId}
|
||||||
|
AND create_time >= #{start}
|
||||||
|
AND create_time < #{end}
|
||||||
|
GROUP BY tenant_id, DATE_FORMAT(create_time, '%Y-%m-%d')
|
||||||
|
ORDER BY day ASC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
|
|
||||||
24
src/main/java/com/gxwebsoft/ai/prompt/AiPrompts.java
Normal file
24
src/main/java/com/gxwebsoft/ai/prompt/AiPrompts.java
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package com.gxwebsoft.ai.prompt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一提示词模板(尽量简短、可控)。
|
||||||
|
*/
|
||||||
|
public class AiPrompts {
|
||||||
|
private AiPrompts() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final String SYSTEM_SUPPORT =
|
||||||
|
"你是 WebSoft 客服AI。规则:\n" +
|
||||||
|
"- 只使用给定的“上下文资料”回答,禁止编造。\n" +
|
||||||
|
"- 如果资料不足,直接说“资料不足”,并列出需要补充的信息。\n" +
|
||||||
|
"- 答案末尾必须给引用,格式:[source:chunk_id]。\n" +
|
||||||
|
"- 输出中文,简洁可执行。\n";
|
||||||
|
|
||||||
|
public static final String SYSTEM_ANALYTICS =
|
||||||
|
"你是商城订单数据分析助手。你将基于提供的按天指标数据给出结论。\n" +
|
||||||
|
"要求:\n" +
|
||||||
|
"- 只基于数据陈述,不要编造不存在的数字。\n" +
|
||||||
|
"- 输出包含:结论、关键指标变化、异常点、建议的下一步核查。\n" +
|
||||||
|
"- 输出中文,简洁。\n";
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.gxwebsoft.ai.dto.*;
|
||||||
|
import com.gxwebsoft.ai.prompt.AiPrompts;
|
||||||
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
|
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiAnalyticsService {
|
||||||
|
@Resource
|
||||||
|
private AiShopAnalyticsService shopAnalyticsService;
|
||||||
|
@Resource
|
||||||
|
private AiChatService aiChatService;
|
||||||
|
|
||||||
|
public AiShopMetricsQueryResult queryShopMetrics(Integer tenantId, AiShopMetricsQueryRequest request) {
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw new BusinessException("tenantId 不能为空");
|
||||||
|
}
|
||||||
|
if (request == null) {
|
||||||
|
throw new BusinessException("请求不能为空");
|
||||||
|
}
|
||||||
|
LocalDate start = parseDate(request.getStartDate(), "startDate");
|
||||||
|
LocalDate end = parseDate(request.getEndDate(), "endDate");
|
||||||
|
if (end.isBefore(start)) {
|
||||||
|
throw new BusinessException("endDate 不能早于 startDate");
|
||||||
|
}
|
||||||
|
|
||||||
|
AiShopMetricsQueryResult r = new AiShopMetricsQueryResult();
|
||||||
|
r.setTenantId(tenantId);
|
||||||
|
r.setStartDate(start.toString());
|
||||||
|
r.setEndDate(end.toString());
|
||||||
|
r.setRows(shopAnalyticsService.queryTenantDaily(tenantId, start, end));
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiAnalyticsAskResult askShopAnalytics(Integer tenantId, AiAnalyticsAskRequest request) {
|
||||||
|
if (request == null || StrUtil.isBlank(request.getQuestion())) {
|
||||||
|
throw new BusinessException("question 不能为空");
|
||||||
|
}
|
||||||
|
AiShopMetricsQueryRequest q = new AiShopMetricsQueryRequest();
|
||||||
|
q.setStartDate(request.getStartDate());
|
||||||
|
q.setEndDate(request.getEndDate());
|
||||||
|
q.setGroupByDay(true);
|
||||||
|
AiShopMetricsQueryResult data = queryShopMetrics(tenantId, q);
|
||||||
|
|
||||||
|
String userPrompt =
|
||||||
|
"用户问题:\n" + request.getQuestion() + "\n\n" +
|
||||||
|
"数据(JSON,字段含义:order_cnt=订单数,paid_order_cnt=已支付订单数,gmv=已支付金额,refund_amt=退款金额,pay_user_cnt=支付用户数,aov=客单价,pay_rate=支付率):\n" +
|
||||||
|
JSONUtil.toJSONString(data, true);
|
||||||
|
|
||||||
|
AiChatRequest chat = new AiChatRequest();
|
||||||
|
chat.setMessages(Arrays.asList(
|
||||||
|
new AiMessage("system", AiPrompts.SYSTEM_ANALYTICS),
|
||||||
|
new AiMessage("user", userPrompt)
|
||||||
|
));
|
||||||
|
|
||||||
|
AiChatResult resp = aiChatService.chat(chat);
|
||||||
|
AiAnalyticsAskResult r = new AiAnalyticsAskResult();
|
||||||
|
r.setAnalysis(resp.getContent());
|
||||||
|
r.setData(data);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LocalDate parseDate(String s, String field) {
|
||||||
|
if (StrUtil.isBlank(s)) {
|
||||||
|
throw new BusinessException(field + " 不能为空,格式 YYYY-MM-DD");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return LocalDate.parse(s.trim());
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
throw new BusinessException(field + " 格式错误,需 YYYY-MM-DD");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
94
src/main/java/com/gxwebsoft/ai/service/AiChatService.java
Normal file
94
src/main/java/com/gxwebsoft/ai/service/AiChatService.java
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.gxwebsoft.ai.client.OllamaClient;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaChatRequest;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaChatResponse;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaMessage;
|
||||||
|
import com.gxwebsoft.ai.config.AiOllamaProperties;
|
||||||
|
import com.gxwebsoft.ai.dto.AiChatRequest;
|
||||||
|
import com.gxwebsoft.ai.dto.AiChatResult;
|
||||||
|
import com.gxwebsoft.ai.dto.AiMessage;
|
||||||
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiChatService {
|
||||||
|
@Resource
|
||||||
|
private AiOllamaProperties props;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private OllamaClient ollamaClient;
|
||||||
|
|
||||||
|
public AiChatResult chat(AiChatRequest request) {
|
||||||
|
OllamaChatRequest req = buildChatRequest(request, false);
|
||||||
|
OllamaChatResponse resp = ollamaClient.chat(req);
|
||||||
|
String content = resp != null && resp.getMessage() != null ? resp.getMessage().getContent() : null;
|
||||||
|
return new AiChatResult(content == null ? "" : content);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void chatStream(AiChatRequest request, Consumer<String> onDelta, Consumer<OllamaChatResponse> onFinal) {
|
||||||
|
Objects.requireNonNull(onDelta, "onDelta");
|
||||||
|
OllamaChatRequest req = buildChatRequest(request, true);
|
||||||
|
ollamaClient.chatStream(req, event -> {
|
||||||
|
String delta = event != null && event.getMessage() != null ? event.getMessage().getContent() : null;
|
||||||
|
if (StrUtil.isNotBlank(delta)) {
|
||||||
|
onDelta.accept(delta);
|
||||||
|
}
|
||||||
|
if (Boolean.TRUE.equals(event.getDone()) && onFinal != null) {
|
||||||
|
onFinal.accept(event);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private OllamaChatRequest buildChatRequest(AiChatRequest request, boolean stream) {
|
||||||
|
if (request == null) {
|
||||||
|
throw new BusinessException("请求不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AiMessage> messages = request.getMessages();
|
||||||
|
if ((messages == null || messages.isEmpty()) && StrUtil.isBlank(request.getPrompt())) {
|
||||||
|
throw new BusinessException("prompt 或 messages 不能为空");
|
||||||
|
}
|
||||||
|
if (messages == null || messages.isEmpty()) {
|
||||||
|
messages = Collections.singletonList(new AiMessage("user", request.getPrompt()));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<OllamaMessage> ollamaMessages = new ArrayList<>();
|
||||||
|
for (AiMessage m : messages) {
|
||||||
|
if (m == null || StrUtil.isBlank(m.getRole()) || m.getContent() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ollamaMessages.add(new OllamaMessage(m.getRole(), m.getContent()));
|
||||||
|
}
|
||||||
|
if (ollamaMessages.isEmpty()) {
|
||||||
|
throw new BusinessException("messages 为空或无有效内容");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> options = new HashMap<>();
|
||||||
|
if (request.getTemperature() != null) {
|
||||||
|
options.put("temperature", request.getTemperature());
|
||||||
|
}
|
||||||
|
if (request.getTopK() != null) {
|
||||||
|
options.put("top_k", request.getTopK());
|
||||||
|
}
|
||||||
|
if (request.getTopP() != null) {
|
||||||
|
options.put("top_p", request.getTopP());
|
||||||
|
}
|
||||||
|
if (request.getNumPredict() != null) {
|
||||||
|
options.put("num_predict", request.getNumPredict());
|
||||||
|
}
|
||||||
|
|
||||||
|
OllamaChatRequest req = new OllamaChatRequest();
|
||||||
|
req.setModel(StrUtil.blankToDefault(request.getModel(), props.getChatModel()));
|
||||||
|
req.setMessages(ollamaMessages);
|
||||||
|
req.setStream(stream);
|
||||||
|
req.setOptions(options.isEmpty() ? null : options);
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbChunk;
|
||||||
|
|
||||||
|
public interface AiKbChunkService extends IService<AiKbChunk> {
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbDocument;
|
||||||
|
|
||||||
|
public interface AiKbDocumentService extends IService<AiKbDocument> {
|
||||||
|
}
|
||||||
|
|
||||||
426
src/main/java/com/gxwebsoft/ai/service/AiKbRagService.java
Normal file
426
src/main/java/com/gxwebsoft/ai/service/AiKbRagService.java
Normal file
@@ -0,0 +1,426 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.gxwebsoft.ai.client.OllamaClient;
|
||||||
|
import com.gxwebsoft.ai.client.dto.OllamaEmbeddingResponse;
|
||||||
|
import com.gxwebsoft.ai.config.AiOllamaProperties;
|
||||||
|
import com.gxwebsoft.ai.dto.*;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbChunk;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbDocument;
|
||||||
|
import com.gxwebsoft.ai.prompt.AiPrompts;
|
||||||
|
import com.gxwebsoft.ai.util.AiTextUtil;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsArticle;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsArticleContent;
|
||||||
|
import com.gxwebsoft.cms.service.CmsArticleContentService;
|
||||||
|
import com.gxwebsoft.cms.service.CmsArticleService;
|
||||||
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
|
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.apache.tika.Tika;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiKbRagService {
|
||||||
|
@Resource
|
||||||
|
private AiOllamaProperties props;
|
||||||
|
@Resource
|
||||||
|
private OllamaClient ollamaClient;
|
||||||
|
@Resource
|
||||||
|
private AiKbDocumentService documentService;
|
||||||
|
@Resource
|
||||||
|
private AiKbChunkService chunkService;
|
||||||
|
@Resource
|
||||||
|
private CmsArticleService cmsArticleService;
|
||||||
|
@Resource
|
||||||
|
private CmsArticleContentService cmsArticleContentService;
|
||||||
|
@Resource
|
||||||
|
private AiChatService aiChatService;
|
||||||
|
@Resource
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private final Tika tika = new Tika();
|
||||||
|
private volatile ExecutorService embedPool;
|
||||||
|
|
||||||
|
private ExecutorService pool() {
|
||||||
|
ExecutorService p = embedPool;
|
||||||
|
if (p != null) {
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
synchronized (this) {
|
||||||
|
if (embedPool == null) {
|
||||||
|
embedPool = Executors.newFixedThreadPool(Math.max(1, props.getMaxConcurrency()));
|
||||||
|
}
|
||||||
|
return embedPool;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiKbIngestResult ingestUpload(Integer tenantId, MultipartFile file) {
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw new BusinessException("tenantId 不能为空");
|
||||||
|
}
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
throw new BusinessException("文件不能为空");
|
||||||
|
}
|
||||||
|
String title = StrUtil.blankToDefault(file.getOriginalFilename(), "upload");
|
||||||
|
String text = extractText(file);
|
||||||
|
if (StrUtil.isBlank(text)) {
|
||||||
|
throw new BusinessException("无法解析文件内容,请上传 txt/md/html 等可解析文本");
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentHash = AiTextUtil.sha256(text);
|
||||||
|
AiKbDocument doc = new AiKbDocument();
|
||||||
|
doc.setTitle(title);
|
||||||
|
doc.setSourceType("upload");
|
||||||
|
doc.setSourceRef(title);
|
||||||
|
doc.setContentHash(contentHash);
|
||||||
|
doc.setStatus(0);
|
||||||
|
doc.setTenantId(tenantId);
|
||||||
|
doc.setCreateTime(LocalDateTime.now());
|
||||||
|
doc.setUpdateTime(LocalDateTime.now());
|
||||||
|
documentService.save(doc);
|
||||||
|
|
||||||
|
int chunks = ingestChunks(doc, text);
|
||||||
|
|
||||||
|
AiKbIngestResult r = new AiKbIngestResult();
|
||||||
|
r.setDocumentId(doc.getDocumentId());
|
||||||
|
r.setTitle(doc.getTitle());
|
||||||
|
r.setChunks(chunks);
|
||||||
|
r.setUpdatedDocuments(1);
|
||||||
|
r.setSkippedDocuments(0);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步 CMS(仅当前 tenant)。
|
||||||
|
*/
|
||||||
|
public AiKbIngestResult syncCms(Integer tenantId) {
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw new BusinessException("tenantId 不能为空");
|
||||||
|
}
|
||||||
|
// 仅同步“已发布且未删除”的文章
|
||||||
|
List<CmsArticle> articles = cmsArticleService.list(new LambdaQueryWrapper<CmsArticle>()
|
||||||
|
.eq(CmsArticle::getTenantId, tenantId)
|
||||||
|
.eq(CmsArticle::getDeleted, 0)
|
||||||
|
.eq(CmsArticle::getStatus, 0));
|
||||||
|
if (articles == null || articles.isEmpty()) {
|
||||||
|
AiKbIngestResult r = new AiKbIngestResult();
|
||||||
|
r.setUpdatedDocuments(0);
|
||||||
|
r.setSkippedDocuments(0);
|
||||||
|
r.setChunks(0);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<Integer> articleIds = articles.stream().map(CmsArticle::getArticleId).collect(Collectors.toSet());
|
||||||
|
List<CmsArticleContent> contents = cmsArticleContentService.list(new LambdaQueryWrapper<CmsArticleContent>()
|
||||||
|
.in(CmsArticleContent::getArticleId, articleIds));
|
||||||
|
|
||||||
|
Map<Integer, CmsArticleContent> contentByArticle = contents.stream()
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
CmsArticleContent::getArticleId,
|
||||||
|
c -> c,
|
||||||
|
(a, b) -> (a.getCreateTime() != null && b.getCreateTime() != null && a.getCreateTime().isAfter(b.getCreateTime())) ? a : b
|
||||||
|
));
|
||||||
|
|
||||||
|
int updatedDocs = 0;
|
||||||
|
int skippedDocs = 0;
|
||||||
|
int totalChunks = 0;
|
||||||
|
|
||||||
|
for (CmsArticle a : articles) {
|
||||||
|
CmsArticleContent c = contentByArticle.get(a.getArticleId());
|
||||||
|
String raw = "";
|
||||||
|
if (a.getOverview() != null) {
|
||||||
|
raw += a.getOverview() + "\n";
|
||||||
|
}
|
||||||
|
if (c != null && c.getContent() != null) {
|
||||||
|
raw += c.getContent();
|
||||||
|
}
|
||||||
|
String text = a.getTitle() + "\n" + AiTextUtil.stripHtml(raw);
|
||||||
|
text = AiTextUtil.normalizeWhitespace(text);
|
||||||
|
if (StrUtil.isBlank(text)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String hash = AiTextUtil.sha256(text);
|
||||||
|
|
||||||
|
AiKbDocument existing = documentService.getOne(new LambdaQueryWrapper<AiKbDocument>()
|
||||||
|
.eq(AiKbDocument::getTenantId, tenantId)
|
||||||
|
.eq(AiKbDocument::getSourceType, "cms")
|
||||||
|
.eq(AiKbDocument::getSourceId, a.getArticleId())
|
||||||
|
.last("limit 1"));
|
||||||
|
|
||||||
|
if (existing != null && StrUtil.equals(existing.getContentHash(), hash)) {
|
||||||
|
skippedDocs++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
AiKbDocument doc;
|
||||||
|
if (existing == null) {
|
||||||
|
doc = new AiKbDocument();
|
||||||
|
doc.setTitle(a.getTitle());
|
||||||
|
doc.setSourceType("cms");
|
||||||
|
doc.setSourceId(a.getArticleId());
|
||||||
|
doc.setSourceRef(a.getCode());
|
||||||
|
doc.setContentHash(hash);
|
||||||
|
doc.setStatus(0);
|
||||||
|
doc.setTenantId(tenantId);
|
||||||
|
doc.setCreateTime(LocalDateTime.now());
|
||||||
|
doc.setUpdateTime(LocalDateTime.now());
|
||||||
|
documentService.save(doc);
|
||||||
|
} else {
|
||||||
|
doc = existing;
|
||||||
|
doc.setTitle(a.getTitle());
|
||||||
|
doc.setSourceRef(a.getCode());
|
||||||
|
doc.setContentHash(hash);
|
||||||
|
doc.setUpdateTime(LocalDateTime.now());
|
||||||
|
documentService.updateById(doc);
|
||||||
|
// 重新入库:先删除旧 chunk
|
||||||
|
chunkService.remove(new LambdaQueryWrapper<AiKbChunk>().eq(AiKbChunk::getDocumentId, doc.getDocumentId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
int chunks = ingestChunks(doc, text);
|
||||||
|
totalChunks += chunks;
|
||||||
|
updatedDocs++;
|
||||||
|
}
|
||||||
|
|
||||||
|
AiKbIngestResult r = new AiKbIngestResult();
|
||||||
|
r.setUpdatedDocuments(updatedDocs);
|
||||||
|
r.setSkippedDocuments(skippedDocs);
|
||||||
|
r.setChunks(totalChunks);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiKbQueryResult query(Integer tenantId, AiKbQueryRequest request) {
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw new BusinessException("tenantId 不能为空");
|
||||||
|
}
|
||||||
|
if (request == null || StrUtil.isBlank(request.getQuery())) {
|
||||||
|
throw new BusinessException("query 不能为空");
|
||||||
|
}
|
||||||
|
int topK = request.getTopK() != null ? request.getTopK() : props.getRagTopK();
|
||||||
|
topK = Math.max(1, Math.min(20, topK));
|
||||||
|
|
||||||
|
float[] qEmb = embedding(request.getQuery());
|
||||||
|
float qNorm = l2(qEmb);
|
||||||
|
if (qNorm == 0f) {
|
||||||
|
throw new BusinessException("query embedding 为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// MVP:按 tenant 拉取最新 N 条候选 chunk,再做余弦相似度排序
|
||||||
|
List<AiKbChunk> candidates = chunkService.list(new LambdaQueryWrapper<AiKbChunk>()
|
||||||
|
.eq(AiKbChunk::getTenantId, tenantId)
|
||||||
|
.orderByDesc(AiKbChunk::getId)
|
||||||
|
.last("limit " + props.getRagMaxCandidates()));
|
||||||
|
|
||||||
|
PriorityQueue<AiKbHit> pq = new PriorityQueue<>(Comparator.comparingDouble(h -> h.getScore() == null ? -1d : h.getScore()));
|
||||||
|
for (AiKbChunk c : candidates) {
|
||||||
|
if (StrUtil.isBlank(c.getEmbedding())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
float[] cEmb = parseEmbedding(c.getEmbedding());
|
||||||
|
if (cEmb == null || cEmb.length == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Double cNormD = c.getEmbeddingNorm();
|
||||||
|
float cNorm = cNormD == null ? l2(cEmb) : cNormD.floatValue();
|
||||||
|
if (cNorm == 0f) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
double score = dot(qEmb, cEmb) / (qNorm * cNorm);
|
||||||
|
AiKbHit hit = new AiKbHit();
|
||||||
|
hit.setChunkId(c.getChunkId());
|
||||||
|
hit.setDocumentId(c.getDocumentId());
|
||||||
|
hit.setTitle(StrUtil.blankToDefault(c.getTitle(), ""));
|
||||||
|
hit.setScore(score);
|
||||||
|
// 返回给前端时避免过长
|
||||||
|
hit.setContent(clip(c.getContent(), 900));
|
||||||
|
|
||||||
|
if (pq.size() < topK) {
|
||||||
|
pq.add(hit);
|
||||||
|
} else if (hit.getScore() != null && hit.getScore() > pq.peek().getScore()) {
|
||||||
|
pq.poll();
|
||||||
|
pq.add(hit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AiKbHit> hits = new ArrayList<>(pq);
|
||||||
|
hits.sort((a, b) -> Double.compare(b.getScore(), a.getScore()));
|
||||||
|
AiKbQueryResult r = new AiKbQueryResult();
|
||||||
|
r.setHits(hits);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiKbAskResult ask(Integer tenantId, AiKbAskRequest request) {
|
||||||
|
if (request == null || StrUtil.isBlank(request.getQuestion())) {
|
||||||
|
throw new BusinessException("question 不能为空");
|
||||||
|
}
|
||||||
|
AiKbQueryRequest q = new AiKbQueryRequest();
|
||||||
|
q.setQuery(request.getQuestion());
|
||||||
|
q.setTopK(request.getTopK());
|
||||||
|
AiKbQueryResult retrieval = query(tenantId, q);
|
||||||
|
|
||||||
|
String context = buildContext(retrieval);
|
||||||
|
String userPrompt = "上下文资料:\n" + context + "\n\n用户问题:\n" + request.getQuestion();
|
||||||
|
|
||||||
|
AiChatRequest chatReq = new AiChatRequest();
|
||||||
|
chatReq.setMessages(Arrays.asList(
|
||||||
|
new AiMessage("system", AiPrompts.SYSTEM_SUPPORT),
|
||||||
|
new AiMessage("user", userPrompt)
|
||||||
|
));
|
||||||
|
AiChatResult chat = aiChatService.chat(chatReq);
|
||||||
|
|
||||||
|
AiKbAskResult r = new AiKbAskResult();
|
||||||
|
r.setAnswer(chat.getContent());
|
||||||
|
r.setRetrieval(retrieval);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int ingestChunks(AiKbDocument doc, String text) {
|
||||||
|
List<String> chunks = AiTextUtil.chunkText(text, props.getRagChunkSize(), props.getRagChunkOverlap());
|
||||||
|
if (chunks.isEmpty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
List<CompletableFuture<AiKbChunk>> futures = new ArrayList<>(chunks.size());
|
||||||
|
for (int i = 0; i < chunks.size(); i++) {
|
||||||
|
final int idx = i;
|
||||||
|
final String chunkText = chunks.get(i);
|
||||||
|
futures.add(CompletableFuture.supplyAsync(() -> {
|
||||||
|
OllamaEmbeddingResponse emb = ollamaClient.embedding(chunkText);
|
||||||
|
if (emb == null || emb.getEmbedding() == null || emb.getEmbedding().isEmpty()) {
|
||||||
|
throw new BusinessException("embedding 生成失败");
|
||||||
|
}
|
||||||
|
float[] v = toFloat(emb.getEmbedding());
|
||||||
|
float norm = l2(v);
|
||||||
|
AiKbChunk c = new AiKbChunk();
|
||||||
|
c.setDocumentId(doc.getDocumentId());
|
||||||
|
c.setChunkId(UUID.randomUUID().toString().replace("-", ""));
|
||||||
|
c.setChunkIndex(idx);
|
||||||
|
c.setTitle(doc.getTitle());
|
||||||
|
c.setContent(chunkText);
|
||||||
|
c.setContentHash(AiTextUtil.sha256(chunkText));
|
||||||
|
c.setEmbedding(JSONUtil.toJSONString(emb.getEmbedding()));
|
||||||
|
c.setEmbeddingNorm((double) norm);
|
||||||
|
c.setTenantId(doc.getTenantId());
|
||||||
|
c.setCreateTime(now);
|
||||||
|
c.setDeleted(0);
|
||||||
|
return c;
|
||||||
|
}, pool()));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AiKbChunk> entities = futures.stream().map(f -> {
|
||||||
|
try {
|
||||||
|
return f.get(10, TimeUnit.MINUTES);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new BusinessException("embedding 批处理失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
|
||||||
|
chunkService.saveBatch(entities);
|
||||||
|
return entities.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractText(MultipartFile file) {
|
||||||
|
try {
|
||||||
|
String contentType = file.getContentType();
|
||||||
|
String filename = file.getOriginalFilename();
|
||||||
|
|
||||||
|
// 优先:对纯文本直接读 UTF-8
|
||||||
|
if ((contentType != null && contentType.startsWith("text/"))
|
||||||
|
|| (filename != null && (filename.endsWith(".txt") || filename.endsWith(".md") || filename.endsWith(".html") || filename.endsWith(".htm")))) {
|
||||||
|
return AiTextUtil.normalizeWhitespace(new String(file.getBytes(), StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试用 tika 解析(注意:当前依赖为 tika-core,解析能力有限)
|
||||||
|
String parsed = tika.parseToString(file.getInputStream());
|
||||||
|
return AiTextUtil.normalizeWhitespace(parsed);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private float[] embedding(String text) {
|
||||||
|
OllamaEmbeddingResponse emb = ollamaClient.embedding(text);
|
||||||
|
if (emb == null || emb.getEmbedding() == null || emb.getEmbedding().isEmpty()) {
|
||||||
|
throw new BusinessException("embedding 生成失败");
|
||||||
|
}
|
||||||
|
return toFloat(emb.getEmbedding());
|
||||||
|
}
|
||||||
|
|
||||||
|
private float[] parseEmbedding(String json) {
|
||||||
|
try {
|
||||||
|
// embedding 是一维数组,存储为 JSON 文本
|
||||||
|
double[] d = ObjectUtil.isEmpty(json) ? null : objectMapper.readValue(json, double[].class);
|
||||||
|
if (d == null || d.length == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
float[] f = new float[d.length];
|
||||||
|
for (int i = 0; i < d.length; i++) {
|
||||||
|
f[i] = (float) d[i];
|
||||||
|
}
|
||||||
|
return f;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float[] toFloat(List<Double> v) {
|
||||||
|
float[] out = new float[v.size()];
|
||||||
|
for (int i = 0; i < v.size(); i++) {
|
||||||
|
Double d = v.get(i);
|
||||||
|
out[i] = d == null ? 0f : d.floatValue();
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float dot(float[] a, float[] b) {
|
||||||
|
int n = Math.min(a.length, b.length);
|
||||||
|
double s = 0d;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
s += (double) a[i] * (double) b[i];
|
||||||
|
}
|
||||||
|
return (float) s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float l2(float[] a) {
|
||||||
|
double s = 0d;
|
||||||
|
for (float v : a) {
|
||||||
|
s += (double) v * (double) v;
|
||||||
|
}
|
||||||
|
return (float) Math.sqrt(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clip(String s, int max) {
|
||||||
|
if (s == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (s.length() <= max) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
return s.substring(0, max) + "...";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String buildContext(AiKbQueryResult retrieval) {
|
||||||
|
if (retrieval == null || retrieval.getHits() == null || retrieval.getHits().isEmpty()) {
|
||||||
|
return "(无)";
|
||||||
|
}
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (AiKbHit h : retrieval.getHits()) {
|
||||||
|
sb.append("[source:").append(h.getChunkId()).append("] ");
|
||||||
|
if (StrUtil.isNotBlank(h.getTitle())) {
|
||||||
|
sb.append(h.getTitle()).append("\n");
|
||||||
|
}
|
||||||
|
sb.append(h.getContent()).append("\n\n");
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.gxwebsoft.ai.service;
|
||||||
|
|
||||||
|
import com.gxwebsoft.ai.dto.AiShopMetricsRow;
|
||||||
|
import com.gxwebsoft.ai.mapper.AiShopAnalyticsMapper;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiShopAnalyticsService {
|
||||||
|
@Resource
|
||||||
|
private AiShopAnalyticsMapper mapper;
|
||||||
|
|
||||||
|
public List<AiShopMetricsRow> queryTenantDaily(Integer tenantId, LocalDate startDate, LocalDate endDateInclusive) {
|
||||||
|
LocalDateTime start = startDate.atStartOfDay();
|
||||||
|
LocalDateTime endExclusive = endDateInclusive.plusDays(1).atStartOfDay();
|
||||||
|
List<AiShopMetricsRow> rows = mapper.queryMetrics(tenantId, start, endExclusive);
|
||||||
|
if (rows == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (AiShopMetricsRow r : rows) {
|
||||||
|
long orderCnt = r.getOrderCnt() == null ? 0L : r.getOrderCnt();
|
||||||
|
long paidCnt = r.getPaidOrderCnt() == null ? 0L : r.getPaidOrderCnt();
|
||||||
|
BigDecimal gmv = r.getGmv() == null ? BigDecimal.ZERO : r.getGmv();
|
||||||
|
|
||||||
|
if (paidCnt > 0) {
|
||||||
|
r.setAov(gmv.divide(BigDecimal.valueOf(paidCnt), 4, RoundingMode.HALF_UP));
|
||||||
|
} else {
|
||||||
|
r.setAov(BigDecimal.ZERO);
|
||||||
|
}
|
||||||
|
if (orderCnt > 0) {
|
||||||
|
r.setPayRate(BigDecimal.valueOf(paidCnt)
|
||||||
|
.divide(BigDecimal.valueOf(orderCnt), 4, RoundingMode.HALF_UP));
|
||||||
|
} else {
|
||||||
|
r.setPayRate(BigDecimal.ZERO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbChunk;
|
||||||
|
import com.gxwebsoft.ai.mapper.AiKbChunkMapper;
|
||||||
|
import com.gxwebsoft.ai.service.AiKbChunkService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiKbChunkServiceImpl extends ServiceImpl<AiKbChunkMapper, AiKbChunk> implements AiKbChunkService {
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.gxwebsoft.ai.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.gxwebsoft.ai.entity.AiKbDocument;
|
||||||
|
import com.gxwebsoft.ai.mapper.AiKbDocumentMapper;
|
||||||
|
import com.gxwebsoft.ai.service.AiKbDocumentService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AiKbDocumentServiceImpl extends ServiceImpl<AiKbDocumentMapper, AiKbDocument> implements AiKbDocumentService {
|
||||||
|
}
|
||||||
|
|
||||||
100
src/main/java/com/gxwebsoft/ai/util/AiTextUtil.java
Normal file
100
src/main/java/com/gxwebsoft/ai/util/AiTextUtil.java
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
package com.gxwebsoft.ai.util;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class AiTextUtil {
|
||||||
|
private AiTextUtil() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sha256(String s) {
|
||||||
|
if (s == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
byte[] dig = md.digest(s.getBytes(StandardCharsets.UTF_8));
|
||||||
|
StringBuilder sb = new StringBuilder(dig.length * 2);
|
||||||
|
for (byte b : dig) {
|
||||||
|
sb.append(String.format("%02x", b));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 很轻量的 HTML 转纯文本(不追求完美,只用于知识库入库前清洗)。
|
||||||
|
*/
|
||||||
|
public static String stripHtml(String html) {
|
||||||
|
if (StrUtil.isBlank(html)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String s = html;
|
||||||
|
s = s.replaceAll("(?is)<script[^>]*>.*?</script>", " ");
|
||||||
|
s = s.replaceAll("(?is)<style[^>]*>.*?</style>", " ");
|
||||||
|
s = s.replaceAll("(?is)<br\\s*/?>", "\n");
|
||||||
|
s = s.replaceAll("(?is)</p\\s*>", "\n");
|
||||||
|
s = s.replaceAll("(?is)<[^>]+>", " ");
|
||||||
|
// 常见 HTML 实体最小处理
|
||||||
|
s = s.replace(" ", " ");
|
||||||
|
s = s.replace("<", "<").replace(">", ">").replace("&", "&").replace(""", "\"");
|
||||||
|
return normalizeWhitespace(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalizeWhitespace(String s) {
|
||||||
|
if (s == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
// 合并空白,保留换行用于 chunking
|
||||||
|
String x = s.replace("\r", "\n");
|
||||||
|
x = x.replaceAll("[\\t\\f\\u000B]+", " ");
|
||||||
|
x = x.replaceAll("[ ]{2,}", " ");
|
||||||
|
x = x.replaceAll("\\n{3,}", "\n\n");
|
||||||
|
return x.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按字符数切分,并做固定 overlap。
|
||||||
|
*/
|
||||||
|
public static List<String> chunkText(String text, int chunkSize, int overlap) {
|
||||||
|
String s = normalizeWhitespace(text);
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
if (StrUtil.isBlank(s)) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (chunkSize <= 0) {
|
||||||
|
chunkSize = 800;
|
||||||
|
}
|
||||||
|
if (overlap < 0) {
|
||||||
|
overlap = 0;
|
||||||
|
}
|
||||||
|
if (overlap >= chunkSize) {
|
||||||
|
overlap = Math.max(0, chunkSize / 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
int n = s.length();
|
||||||
|
int start = 0;
|
||||||
|
while (start < n) {
|
||||||
|
int end = Math.min(n, start + chunkSize);
|
||||||
|
String chunk = s.substring(start, end).trim();
|
||||||
|
if (!chunk.isEmpty()) {
|
||||||
|
out.add(chunk);
|
||||||
|
}
|
||||||
|
if (end >= n) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
start = end - overlap;
|
||||||
|
if (start < 0) {
|
||||||
|
start = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
package com.gxwebsoft.cms.controller;
|
package com.gxwebsoft.cms.controller;
|
||||||
|
|
||||||
|
import cn.afterturn.easypoi.excel.ExcelImportUtil;
|
||||||
|
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
import com.gxwebsoft.cms.entity.CmsDesign;
|
import com.gxwebsoft.cms.entity.CmsDesign;
|
||||||
import com.gxwebsoft.cms.entity.CmsModel;
|
import com.gxwebsoft.cms.entity.CmsModel;
|
||||||
|
import com.gxwebsoft.cms.param.CmsNavigationImportParam;
|
||||||
import com.gxwebsoft.cms.service.CmsDesignService;
|
import com.gxwebsoft.cms.service.CmsDesignService;
|
||||||
import com.gxwebsoft.cms.service.CmsModelService;
|
import com.gxwebsoft.cms.service.CmsModelService;
|
||||||
|
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||||
import com.gxwebsoft.common.core.web.BaseController;
|
import com.gxwebsoft.common.core.web.BaseController;
|
||||||
@@ -21,11 +25,18 @@ import com.gxwebsoft.common.system.entity.User;
|
|||||||
import com.gxwebsoft.common.system.service.UserService;
|
import com.gxwebsoft.common.system.service.UserService;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 网站导航记录表控制器
|
* 网站导航记录表控制器
|
||||||
@@ -79,6 +90,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return success(cmsNavigationService.getByIdRelByCodeRel(code));
|
return success(cmsNavigationService.getByIdRelByCodeRel(code));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:save')")
|
||||||
@Operation(summary = "添加网站导航记录表")
|
@Operation(summary = "添加网站导航记录表")
|
||||||
@PostMapping()
|
@PostMapping()
|
||||||
public ApiResult<?> save(@RequestBody CmsNavigation cmsNavigation) {
|
public ApiResult<?> save(@RequestBody CmsNavigation cmsNavigation) {
|
||||||
@@ -99,6 +111,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("添加失败");
|
return fail("添加失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:update')")
|
||||||
@Operation(summary = "修改网站导航记录表")
|
@Operation(summary = "修改网站导航记录表")
|
||||||
@PutMapping()
|
@PutMapping()
|
||||||
public ApiResult<?> update(@RequestBody CmsNavigation cmsNavigation) {
|
public ApiResult<?> update(@RequestBody CmsNavigation cmsNavigation) {
|
||||||
@@ -111,6 +124,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("修改失败");
|
return fail("修改失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:remove')")
|
||||||
@Operation(summary = "删除网站导航记录表")
|
@Operation(summary = "删除网站导航记录表")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
@@ -121,6 +135,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:save')")
|
||||||
@Operation(summary = "批量添加网站导航记录表")
|
@Operation(summary = "批量添加网站导航记录表")
|
||||||
@PostMapping("/batch")
|
@PostMapping("/batch")
|
||||||
public ApiResult<?> saveBatch(@RequestBody List<CmsNavigation> list) {
|
public ApiResult<?> saveBatch(@RequestBody List<CmsNavigation> list) {
|
||||||
@@ -131,6 +146,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("添加失败");
|
return fail("添加失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:update')")
|
||||||
@Operation(summary = "批量修改网站导航记录表")
|
@Operation(summary = "批量修改网站导航记录表")
|
||||||
@PutMapping("/batch")
|
@PutMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsNavigation> batchParam) {
|
public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsNavigation> batchParam) {
|
||||||
@@ -141,6 +157,7 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("修改失败");
|
return fail("修改失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:remove')")
|
||||||
@Operation(summary = "批量删除网站导航记录表")
|
@Operation(summary = "批量删除网站导航记录表")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
@@ -151,6 +168,173 @@ public class CmsNavigationController extends BaseController {
|
|||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* excel批量导入网站导航
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsNavigation:save')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "批量导入网站导航")
|
||||||
|
@Transactional(rollbackFor = {Exception.class})
|
||||||
|
@PostMapping("/import")
|
||||||
|
public ApiResult<?> importBatch(@RequestParam("file") MultipartFile file) {
|
||||||
|
ImportParams importParams = new ImportParams();
|
||||||
|
try {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
if (loginUser == null) {
|
||||||
|
return fail("请先登录");
|
||||||
|
}
|
||||||
|
Integer currentUserId = loginUser.getUserId();
|
||||||
|
Integer currentTenantId = loginUser.getTenantId();
|
||||||
|
|
||||||
|
// 1) 清理当前租户的历史数据:先清理 deleted=1,再把 deleted=0 标记为 deleted=1
|
||||||
|
List<CmsNavigation> undeleted = cmsNavigationService.list(new LambdaQueryWrapper<CmsNavigation>()
|
||||||
|
.eq(CmsNavigation::getTenantId, currentTenantId)
|
||||||
|
.eq(CmsNavigation::getDeleted, 0));
|
||||||
|
cmsNavigationService.remove(new LambdaQueryWrapper<CmsNavigation>()
|
||||||
|
.eq(CmsNavigation::getTenantId, currentTenantId)
|
||||||
|
.eq(CmsNavigation::getDeleted, 1));
|
||||||
|
if (!CollectionUtils.isEmpty(undeleted)) {
|
||||||
|
LambdaUpdateWrapper<CmsNavigation> updateWrapper = new LambdaUpdateWrapper<>();
|
||||||
|
updateWrapper.eq(CmsNavigation::getTenantId, currentTenantId);
|
||||||
|
updateWrapper.eq(CmsNavigation::getDeleted, 0);
|
||||||
|
updateWrapper.set(CmsNavigation::getDeleted, 1);
|
||||||
|
cmsNavigationService.update(updateWrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 读取Excel
|
||||||
|
List<CmsNavigationImportParam> list = ExcelImportUtil.importExcel(
|
||||||
|
file.getInputStream(), CmsNavigationImportParam.class, importParams);
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) 先全部落库(先按根节点保存),再尝试按“导入文件的 parentId -> 导入文件的 navigationId”映射回填层级。
|
||||||
|
// 这样即使 parentId 无法匹配(导入文件缺少导航ID/父节点缺失),也能把数据全部导入,无法还原层级的作为根节点处理。
|
||||||
|
Map<Integer, Integer> newIdByOldId = new HashMap<>();
|
||||||
|
List<Integer> newIds = new ArrayList<>(list.size());
|
||||||
|
List<Integer> oldIds = new ArrayList<>(list.size());
|
||||||
|
List<Integer> oldParentIds = new ArrayList<>(list.size());
|
||||||
|
|
||||||
|
for (CmsNavigationImportParam param : list) {
|
||||||
|
CmsNavigation nav = convertToNavigation(param, currentUserId, currentTenantId);
|
||||||
|
nav.setParentId(0);
|
||||||
|
cmsNavigationService.save(nav);
|
||||||
|
cmsNavigationService.saveAsync(nav);
|
||||||
|
|
||||||
|
Integer oldId = param.getNavigationId();
|
||||||
|
if (oldId != null) {
|
||||||
|
newIdByOldId.put(oldId, nav.getNavigationId());
|
||||||
|
}
|
||||||
|
newIds.add(nav.getNavigationId());
|
||||||
|
oldIds.add(oldId);
|
||||||
|
oldParentIds.add(param.getParentId() != null ? param.getParentId() : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
int orphanCount = 0;
|
||||||
|
int restoredCount = 0;
|
||||||
|
for (int i = 0; i < newIds.size(); i++) {
|
||||||
|
Integer oldParentId = oldParentIds.get(i);
|
||||||
|
if (oldParentId == null || oldParentId == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Integer oldId = oldIds.get(i);
|
||||||
|
Integer newId = newIds.get(i);
|
||||||
|
Integer newParentId = newIdByOldId.get(oldParentId);
|
||||||
|
// 无法匹配父节点(或出现自引用)就当作孤儿节点,保持根节点
|
||||||
|
if (newParentId == null || (oldId != null && oldParentId.equals(oldId)) || (newId != null && newParentId.equals(newId))) {
|
||||||
|
orphanCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cmsNavigationService.update(new LambdaUpdateWrapper<CmsNavigation>()
|
||||||
|
.eq(CmsNavigation::getNavigationId, newId)
|
||||||
|
.set(CmsNavigation::getParentId, newParentId));
|
||||||
|
restoredCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
redisUtil.delete(SITE_INFO_KEY_PREFIX.concat(currentTenantId.toString()));
|
||||||
|
return success("成功导入" + list.size() + "条,恢复层级" + restoredCount + "条,无法还原层级的孤儿节点" + orphanCount + "条(已作为根节点导入)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归创建子级导航
|
||||||
|
*/
|
||||||
|
private void createChildNavigations(Map<Integer, List<CmsNavigationImportParam>> navGroups,
|
||||||
|
Map<Integer, CmsNavigation> tempIdMapping,
|
||||||
|
Integer originalParentId,
|
||||||
|
Integer defaultUserId,
|
||||||
|
Integer defaultTenantId) {
|
||||||
|
if (originalParentId == null || originalParentId == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<CmsNavigationImportParam> children = navGroups.get(originalParentId);
|
||||||
|
if (CollectionUtils.isEmpty(children)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CmsNavigation parent = tempIdMapping.get(originalParentId);
|
||||||
|
if (parent == null || parent.getNavigationId() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Integer newParentId = parent.getNavigationId();
|
||||||
|
for (CmsNavigationImportParam param : children) {
|
||||||
|
CmsNavigation nav = convertToNavigation(param, defaultUserId, defaultTenantId);
|
||||||
|
nav.setParentId(newParentId);
|
||||||
|
cmsNavigationService.save(nav);
|
||||||
|
cmsNavigationService.saveAsync(nav);
|
||||||
|
if (param.getNavigationId() != null) {
|
||||||
|
tempIdMapping.put(param.getNavigationId(), nav);
|
||||||
|
}
|
||||||
|
createChildNavigations(navGroups, tempIdMapping, param.getNavigationId(), defaultUserId, defaultTenantId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private CmsNavigation convertToNavigation(CmsNavigationImportParam param, Integer defaultUserId, Integer defaultTenantId) {
|
||||||
|
CmsNavigation nav = new CmsNavigation();
|
||||||
|
nav.setType(param.getType());
|
||||||
|
nav.setTitle(StrUtil.trimStart(param.getTitle()));
|
||||||
|
nav.setParentId(param.getParentId() != null ? param.getParentId() : 0);
|
||||||
|
// saveAsync 依赖 model 生成路由/页面;缺省按 page 处理
|
||||||
|
nav.setModel(StrUtil.isBlank(param.getModel()) ? "page" : param.getModel());
|
||||||
|
nav.setCode(param.getCode());
|
||||||
|
nav.setPath(param.getPath());
|
||||||
|
nav.setComponent(param.getComponent());
|
||||||
|
nav.setTarget(param.getTarget());
|
||||||
|
nav.setIcon(param.getIcon());
|
||||||
|
nav.setColor(param.getColor());
|
||||||
|
nav.setHide(param.getHide());
|
||||||
|
nav.setPermission(param.getPermission());
|
||||||
|
nav.setPassword(param.getPassword());
|
||||||
|
nav.setPosition(param.getPosition());
|
||||||
|
nav.setTop(param.getTop());
|
||||||
|
nav.setBottom(param.getBottom());
|
||||||
|
nav.setActive(param.getActive());
|
||||||
|
nav.setMeta(param.getMeta());
|
||||||
|
nav.setStyle(param.getStyle());
|
||||||
|
nav.setModelName(param.getModelName());
|
||||||
|
nav.setPageId(param.getPageId());
|
||||||
|
nav.setItemId(param.getItemId());
|
||||||
|
nav.setIsMpWeixin(param.getIsMpWeixin());
|
||||||
|
nav.setGutter(param.getGutter());
|
||||||
|
nav.setSpan(param.getSpan());
|
||||||
|
nav.setReadNum(param.getReadNum());
|
||||||
|
nav.setMerchantId(param.getMerchantId());
|
||||||
|
nav.setLang(param.getLang());
|
||||||
|
nav.setHome(param.getHome());
|
||||||
|
nav.setRecommend(param.getRecommend());
|
||||||
|
nav.setSortNumber(param.getSortNumber() != null ? param.getSortNumber() : 0);
|
||||||
|
nav.setComments(param.getComments());
|
||||||
|
nav.setStatus(param.getStatus() != null ? param.getStatus() : 0);
|
||||||
|
|
||||||
|
// 导入时强制落到当前登录用户/租户,避免“导出其他租户 -> 导入”写回原租户导致当前租户数据不全。
|
||||||
|
nav.setUserId(defaultUserId);
|
||||||
|
nav.setTenantId(defaultTenantId);
|
||||||
|
nav.setDeleted(0);
|
||||||
|
return nav;
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取树形结构的网站导航数据")
|
@Operation(summary = "获取树形结构的网站导航数据")
|
||||||
@GetMapping("/tree")
|
@GetMapping("/tree")
|
||||||
public ApiResult<List<CmsNavigation>> tree(CmsNavigationParam param) {
|
public ApiResult<List<CmsNavigation>> tree(CmsNavigationParam param) {
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package com.gxwebsoft.cms.controller;
|
||||||
|
|
||||||
|
import com.gxwebsoft.common.core.web.BaseController;
|
||||||
|
import com.gxwebsoft.cms.service.CmsOrderService;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsOrder;
|
||||||
|
import com.gxwebsoft.cms.param.CmsOrderParam;
|
||||||
|
import com.gxwebsoft.common.core.web.ApiResult;
|
||||||
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
|
import com.gxwebsoft.common.core.web.PageParam;
|
||||||
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
|
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单控制器
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:25
|
||||||
|
*/
|
||||||
|
@Tag(name = "网站订单管理")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/cms/cms-order")
|
||||||
|
public class CmsOrderController extends BaseController {
|
||||||
|
@Resource
|
||||||
|
private CmsOrderService cmsOrderService;
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:list')")
|
||||||
|
@Operation(summary = "分页查询网站订单")
|
||||||
|
@GetMapping("/page")
|
||||||
|
public ApiResult<PageResult<CmsOrder>> page(CmsOrderParam param) {
|
||||||
|
// 使用关联查询
|
||||||
|
return success(cmsOrderService.pageRel(param));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:list')")
|
||||||
|
@Operation(summary = "查询全部网站订单")
|
||||||
|
@GetMapping()
|
||||||
|
public ApiResult<List<CmsOrder>> list(CmsOrderParam param) {
|
||||||
|
// 使用关联查询
|
||||||
|
return success(cmsOrderService.listRel(param));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:list')")
|
||||||
|
@Operation(summary = "根据id查询网站订单")
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ApiResult<CmsOrder> get(@PathVariable("id") Integer id) {
|
||||||
|
// 使用关联查询
|
||||||
|
return success(cmsOrderService.getByIdRel(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "添加网站订单")
|
||||||
|
@PostMapping()
|
||||||
|
public ApiResult<?> save(@RequestBody CmsOrder cmsOrder) {
|
||||||
|
|
||||||
|
if (cmsOrderService.save(cmsOrder)) {
|
||||||
|
return success("添加成功");
|
||||||
|
}
|
||||||
|
return fail("添加失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "修改网站订单")
|
||||||
|
@PutMapping()
|
||||||
|
public ApiResult<?> update(@RequestBody CmsOrder cmsOrder) {
|
||||||
|
if (cmsOrderService.updateById(cmsOrder)) {
|
||||||
|
return success("修改成功");
|
||||||
|
}
|
||||||
|
return fail("修改失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:remove')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "删除网站订单")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
|
if (cmsOrderService.removeById(id)) {
|
||||||
|
return success("删除成功");
|
||||||
|
}
|
||||||
|
return fail("删除失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:save')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "批量添加网站订单")
|
||||||
|
@PostMapping("/batch")
|
||||||
|
public ApiResult<?> saveBatch(@RequestBody List<CmsOrder> list) {
|
||||||
|
if (cmsOrderService.saveBatch(list)) {
|
||||||
|
return success("添加成功");
|
||||||
|
}
|
||||||
|
return fail("添加失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "批量修改网站订单")
|
||||||
|
@PutMapping("/batch")
|
||||||
|
public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsOrder> batchParam) {
|
||||||
|
if (batchParam.update(cmsOrderService, "id")) {
|
||||||
|
return success("修改成功");
|
||||||
|
}
|
||||||
|
return fail("修改失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("hasAuthority('cms:cmsOrder:remove')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "批量删除网站订单")
|
||||||
|
@DeleteMapping("/batch")
|
||||||
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
|
if (cmsOrderService.removeByIds(ids)) {
|
||||||
|
return success("删除成功");
|
||||||
|
}
|
||||||
|
return fail("删除失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -43,6 +43,10 @@ public class CmsNavigation implements Serializable {
|
|||||||
@Schema(description = "模型")
|
@Schema(description = "模型")
|
||||||
private String model;
|
private String model;
|
||||||
|
|
||||||
|
@Schema(description = "模型名称")
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String modelName;
|
||||||
|
|
||||||
@Schema(description = "标识")
|
@Schema(description = "标识")
|
||||||
private String code;
|
private String code;
|
||||||
|
|
||||||
@@ -114,9 +118,6 @@ public class CmsNavigation implements Serializable {
|
|||||||
@TableField(exist = false)
|
@TableField(exist = false)
|
||||||
private Integer parentPosition;
|
private Integer parentPosition;
|
||||||
|
|
||||||
@Schema(description = "模型名称")
|
|
||||||
private String modelName;
|
|
||||||
|
|
||||||
@Schema(description = "绑定的页面(已废弃)")
|
@Schema(description = "绑定的页面(已废弃)")
|
||||||
private Integer pageId;
|
private Integer pageId;
|
||||||
|
|
||||||
|
|||||||
266
src/main/java/com/gxwebsoft/cms/entity/CmsOrder.java
Normal file
266
src/main/java/com/gxwebsoft/cms/entity/CmsOrder.java
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
package com.gxwebsoft.cms.entity;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:24
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@Schema(name = "CmsOrder对象", description = "网站订单")
|
||||||
|
public class CmsOrder implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Schema(description = "id")
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Schema(description = "订单类型,0售前咨询 1售后服务 2意见反馈")
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
@Schema(description = "订单标题")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Schema(description = "公司/团队名称")
|
||||||
|
private String company;
|
||||||
|
|
||||||
|
@Schema(description = "订单内容")
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
@Schema(description = "订单编号")
|
||||||
|
private String orderNo;
|
||||||
|
|
||||||
|
@Schema(description = "快递/自提")
|
||||||
|
private Integer deliveryType;
|
||||||
|
|
||||||
|
@Schema(description = "下单渠道,0网站 1微信小程序 2其他")
|
||||||
|
private Integer channel;
|
||||||
|
|
||||||
|
@Schema(description = "微信支付交易号号")
|
||||||
|
private String transactionId;
|
||||||
|
|
||||||
|
@Schema(description = "微信退款订单号")
|
||||||
|
private String refundOrder;
|
||||||
|
|
||||||
|
@Schema(description = "商户ID")
|
||||||
|
private Integer merchantId;
|
||||||
|
|
||||||
|
@Schema(description = "商户名称")
|
||||||
|
private String merchantName;
|
||||||
|
|
||||||
|
@Schema(description = "商户编号")
|
||||||
|
private String merchantCode;
|
||||||
|
|
||||||
|
@Schema(description = "使用的优惠券id")
|
||||||
|
private Integer couponId;
|
||||||
|
|
||||||
|
@Schema(description = "使用的会员卡id")
|
||||||
|
private String cardId;
|
||||||
|
|
||||||
|
@Schema(description = "关联管理员id")
|
||||||
|
private Integer adminId;
|
||||||
|
|
||||||
|
@Schema(description = "核销管理员id")
|
||||||
|
private Integer confirmId;
|
||||||
|
|
||||||
|
@Schema(description = "IC卡号")
|
||||||
|
private String icCard;
|
||||||
|
|
||||||
|
@Schema(description = "真实姓名")
|
||||||
|
private String realName;
|
||||||
|
|
||||||
|
@Schema(description = "关联收货地址")
|
||||||
|
private Integer addressId;
|
||||||
|
|
||||||
|
@Schema(description = "收货地址")
|
||||||
|
private String address;
|
||||||
|
|
||||||
|
private String addressLat;
|
||||||
|
|
||||||
|
private String addressLng;
|
||||||
|
|
||||||
|
@Schema(description = "自提店铺id")
|
||||||
|
private Integer selfTakeMerchantId;
|
||||||
|
|
||||||
|
@Schema(description = "自提店铺")
|
||||||
|
private String selfTakeMerchantName;
|
||||||
|
|
||||||
|
@Schema(description = "配送开始时间")
|
||||||
|
private String sendStartTime;
|
||||||
|
|
||||||
|
@Schema(description = "配送结束时间")
|
||||||
|
private String sendEndTime;
|
||||||
|
|
||||||
|
@Schema(description = "发货店铺id")
|
||||||
|
private Integer expressMerchantId;
|
||||||
|
|
||||||
|
@Schema(description = "发货店铺")
|
||||||
|
private String expressMerchantName;
|
||||||
|
|
||||||
|
@Schema(description = "订单总额")
|
||||||
|
private BigDecimal totalPrice;
|
||||||
|
|
||||||
|
@Schema(description = "减少的金额,使用VIP会员折扣、优惠券抵扣、优惠券折扣后减去的价格")
|
||||||
|
private BigDecimal reducePrice;
|
||||||
|
|
||||||
|
@Schema(description = "实际付款")
|
||||||
|
private BigDecimal payPrice;
|
||||||
|
|
||||||
|
@Schema(description = "用于统计")
|
||||||
|
private BigDecimal price;
|
||||||
|
|
||||||
|
@Schema(description = "价钱,用于积分赠送")
|
||||||
|
private BigDecimal money;
|
||||||
|
|
||||||
|
@Schema(description = "取消时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime cancelTime;
|
||||||
|
|
||||||
|
@Schema(description = "取消原因")
|
||||||
|
private String cancelReason;
|
||||||
|
|
||||||
|
@Schema(description = "退款金额")
|
||||||
|
private BigDecimal refundMoney;
|
||||||
|
|
||||||
|
@Schema(description = "教练价格")
|
||||||
|
private BigDecimal coachPrice;
|
||||||
|
|
||||||
|
@Schema(description = "购买数量")
|
||||||
|
private Integer totalNum;
|
||||||
|
|
||||||
|
@Schema(description = "教练id")
|
||||||
|
private Integer coachId;
|
||||||
|
|
||||||
|
@Schema(description = "商品ID")
|
||||||
|
private Integer formId;
|
||||||
|
|
||||||
|
@Schema(description = "支付的用户id")
|
||||||
|
private Integer payUserId;
|
||||||
|
|
||||||
|
@Schema(description = "0余额支付,1微信支付,2支付宝支付,3银联支付,4现金支付,5POS机支付,6免费,7积分支付")
|
||||||
|
private Integer payType;
|
||||||
|
|
||||||
|
@Schema(description = "微信支付子类型:JSAPI小程序支付,NATIVE扫码支付")
|
||||||
|
private String wechatPayType;
|
||||||
|
|
||||||
|
@Schema(description = "0余额支付,1微信支付,2支付宝支付,3银联支付,4现金支付,5POS机支付,6免费,7积分支付")
|
||||||
|
private Integer friendPayType;
|
||||||
|
|
||||||
|
@Schema(description = "0未付款,1已付款")
|
||||||
|
private Integer payStatus;
|
||||||
|
|
||||||
|
@Schema(description = "0未使用,1已完成,2已取消,3取消中,4退款申请中,5退款被拒绝,6退款成功,7客户端申请退款")
|
||||||
|
private Integer orderStatus;
|
||||||
|
|
||||||
|
@Schema(description = "发货状态(10未发货 20已发货 30部分发货)")
|
||||||
|
private Integer deliveryStatus;
|
||||||
|
|
||||||
|
@Schema(description = "无需发货备注")
|
||||||
|
private String deliveryNote;
|
||||||
|
|
||||||
|
@Schema(description = "发货时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime deliveryTime;
|
||||||
|
|
||||||
|
@Schema(description = "评价状态(0未评价 1已评价)")
|
||||||
|
private Integer evaluateStatus;
|
||||||
|
|
||||||
|
@Schema(description = "评价时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime evaluateTime;
|
||||||
|
|
||||||
|
@Schema(description = "优惠类型:0无、1抵扣优惠券、2折扣优惠券、3、VIP月卡、4VIP年卡,5VIP次卡、6VIP会员卡、7IC月卡、8IC年卡、9IC次卡、10IC会员卡、11免费订单、12VIP充值卡、13IC充值卡、14VIP季卡、15IC季卡")
|
||||||
|
private Integer couponType;
|
||||||
|
|
||||||
|
@Schema(description = "优惠说明")
|
||||||
|
private String couponDesc;
|
||||||
|
|
||||||
|
@Schema(description = "二维码地址,保存订单号,支付成功后才生成")
|
||||||
|
private String qrcode;
|
||||||
|
|
||||||
|
@Schema(description = "vip月卡年卡、ic月卡年卡回退次数")
|
||||||
|
private Integer returnNum;
|
||||||
|
|
||||||
|
@Schema(description = "vip充值回退金额")
|
||||||
|
private BigDecimal returnMoney;
|
||||||
|
|
||||||
|
@Schema(description = "预约详情开始时间数组")
|
||||||
|
private String startTime;
|
||||||
|
|
||||||
|
@Schema(description = "是否已开具发票:0未开发票,1已开发票,2不能开具发票")
|
||||||
|
private Integer isInvoice;
|
||||||
|
|
||||||
|
@Schema(description = "发票流水号")
|
||||||
|
private String invoiceNo;
|
||||||
|
|
||||||
|
@Schema(description = "商家留言")
|
||||||
|
private String merchantRemarks;
|
||||||
|
|
||||||
|
@Schema(description = "支付时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime payTime;
|
||||||
|
|
||||||
|
@Schema(description = "退款时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime refundTime;
|
||||||
|
|
||||||
|
@Schema(description = "申请退款时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime refundApplyTime;
|
||||||
|
|
||||||
|
@Schema(description = "过期时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime expirationTime;
|
||||||
|
|
||||||
|
@Schema(description = "自提码")
|
||||||
|
private String selfTakeCode;
|
||||||
|
|
||||||
|
@Schema(description = "是否已收到赠品")
|
||||||
|
private Boolean hasTakeGift;
|
||||||
|
|
||||||
|
@Schema(description = "对账情况:0=未对账;1=已对账;3=已对账,金额对不上;4=未查询到该订单")
|
||||||
|
private Integer checkBill;
|
||||||
|
|
||||||
|
@Schema(description = "订单是否已结算(0未结算 1已结算)")
|
||||||
|
private Integer isSettled;
|
||||||
|
|
||||||
|
@Schema(description = "系统版本号 0当前版本 value=其他版本")
|
||||||
|
private Integer version;
|
||||||
|
|
||||||
|
@Schema(description = "用户id")
|
||||||
|
private Integer userId;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String comments;
|
||||||
|
|
||||||
|
@Schema(description = "排序号")
|
||||||
|
private Integer sortNumber;
|
||||||
|
|
||||||
|
@Schema(description = "是否删除, 0否, 1是")
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
|
||||||
|
@Schema(description = "租户id")
|
||||||
|
private Integer tenantId;
|
||||||
|
|
||||||
|
@Schema(description = "修改时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
}
|
||||||
37
src/main/java/com/gxwebsoft/cms/mapper/CmsOrderMapper.java
Normal file
37
src/main/java/com/gxwebsoft/cms/mapper/CmsOrderMapper.java
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package com.gxwebsoft.cms.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsOrder;
|
||||||
|
import com.gxwebsoft.cms.param.CmsOrderParam;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单Mapper
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:24
|
||||||
|
*/
|
||||||
|
public interface CmsOrderMapper extends BaseMapper<CmsOrder> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询
|
||||||
|
*
|
||||||
|
* @param page 分页对象
|
||||||
|
* @param param 查询参数
|
||||||
|
* @return List<CmsOrder>
|
||||||
|
*/
|
||||||
|
List<CmsOrder> selectPageRel(@Param("page") IPage<CmsOrder> page,
|
||||||
|
@Param("param") CmsOrderParam param);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询全部
|
||||||
|
*
|
||||||
|
* @param param 查询参数
|
||||||
|
* @return List<User>
|
||||||
|
*/
|
||||||
|
List<CmsOrder> selectListRel(@Param("param") CmsOrderParam param);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -4,9 +4,11 @@
|
|||||||
|
|
||||||
<!-- 关联查询sql -->
|
<!-- 关联查询sql -->
|
||||||
<sql id="selectSql">
|
<sql id="selectSql">
|
||||||
SELECT a.*, b.title as parentName, b.position as parentPosition
|
SELECT a.*, b.title as parentName, b.position as parentPosition, c.name as modelName
|
||||||
FROM cms_navigation a
|
FROM cms_navigation a
|
||||||
LEFT JOIN cms_navigation b ON a.parent_id = b.navigation_id
|
LEFT JOIN cms_navigation b ON a.parent_id = b.navigation_id AND b.deleted = 0 AND b.tenant_id = a.tenant_id
|
||||||
|
<!-- c.model = 0 会触发 MySQL 字符串转数字比较,导致几乎所有模型都匹配,从而把导航行成倍放大 -->
|
||||||
|
LEFT JOIN cms_model c ON a.model = c.model AND c.deleted = 0 AND c.tenant_id = a.tenant_id
|
||||||
<where>
|
<where>
|
||||||
<if test="param.navigationId != null">
|
<if test="param.navigationId != null">
|
||||||
AND a.navigation_id = #{param.navigationId}
|
AND a.navigation_id = #{param.navigationId}
|
||||||
|
|||||||
258
src/main/java/com/gxwebsoft/cms/mapper/xml/CmsOrderMapper.xml
Normal file
258
src/main/java/com/gxwebsoft/cms/mapper/xml/CmsOrderMapper.xml
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.gxwebsoft.cms.mapper.CmsOrderMapper">
|
||||||
|
|
||||||
|
<!-- 关联查询sql -->
|
||||||
|
<sql id="selectSql">
|
||||||
|
SELECT a.*
|
||||||
|
FROM cms_order a
|
||||||
|
<where>
|
||||||
|
<if test="param.id != null">
|
||||||
|
AND a.id = #{param.id}
|
||||||
|
</if>
|
||||||
|
<if test="param.type != null">
|
||||||
|
AND a.type = #{param.type}
|
||||||
|
</if>
|
||||||
|
<if test="param.title != null">
|
||||||
|
AND a.title LIKE CONCAT('%', #{param.title}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.company != null">
|
||||||
|
AND a.company LIKE CONCAT('%', #{param.company}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.content != null">
|
||||||
|
AND a.content LIKE CONCAT('%', #{param.content}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.orderNo != null">
|
||||||
|
AND a.order_no LIKE CONCAT('%', #{param.orderNo}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.deliveryType != null">
|
||||||
|
AND a.delivery_type = #{param.deliveryType}
|
||||||
|
</if>
|
||||||
|
<if test="param.channel != null">
|
||||||
|
AND a.channel = #{param.channel}
|
||||||
|
</if>
|
||||||
|
<if test="param.transactionId != null">
|
||||||
|
AND a.transaction_id LIKE CONCAT('%', #{param.transactionId}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.refundOrder != null">
|
||||||
|
AND a.refund_order LIKE CONCAT('%', #{param.refundOrder}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.merchantId != null">
|
||||||
|
AND a.merchant_id = #{param.merchantId}
|
||||||
|
</if>
|
||||||
|
<if test="param.merchantName != null">
|
||||||
|
AND a.merchant_name LIKE CONCAT('%', #{param.merchantName}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.merchantCode != null">
|
||||||
|
AND a.merchant_code LIKE CONCAT('%', #{param.merchantCode}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.couponId != null">
|
||||||
|
AND a.coupon_id = #{param.couponId}
|
||||||
|
</if>
|
||||||
|
<if test="param.cardId != null">
|
||||||
|
AND a.card_id LIKE CONCAT('%', #{param.cardId}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.adminId != null">
|
||||||
|
AND a.admin_id = #{param.adminId}
|
||||||
|
</if>
|
||||||
|
<if test="param.confirmId != null">
|
||||||
|
AND a.confirm_id = #{param.confirmId}
|
||||||
|
</if>
|
||||||
|
<if test="param.icCard != null">
|
||||||
|
AND a.ic_card LIKE CONCAT('%', #{param.icCard}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.realName != null">
|
||||||
|
AND a.real_name LIKE CONCAT('%', #{param.realName}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.addressId != null">
|
||||||
|
AND a.address_id = #{param.addressId}
|
||||||
|
</if>
|
||||||
|
<if test="param.address != null">
|
||||||
|
AND a.address LIKE CONCAT('%', #{param.address}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.addressLat != null">
|
||||||
|
AND a.address_lat LIKE CONCAT('%', #{param.addressLat}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.addressLng != null">
|
||||||
|
AND a.address_lng LIKE CONCAT('%', #{param.addressLng}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.selfTakeMerchantId != null">
|
||||||
|
AND a.self_take_merchant_id = #{param.selfTakeMerchantId}
|
||||||
|
</if>
|
||||||
|
<if test="param.selfTakeMerchantName != null">
|
||||||
|
AND a.self_take_merchant_name LIKE CONCAT('%', #{param.selfTakeMerchantName}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.sendStartTime != null">
|
||||||
|
AND a.send_start_time LIKE CONCAT('%', #{param.sendStartTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.sendEndTime != null">
|
||||||
|
AND a.send_end_time LIKE CONCAT('%', #{param.sendEndTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.expressMerchantId != null">
|
||||||
|
AND a.express_merchant_id = #{param.expressMerchantId}
|
||||||
|
</if>
|
||||||
|
<if test="param.expressMerchantName != null">
|
||||||
|
AND a.express_merchant_name LIKE CONCAT('%', #{param.expressMerchantName}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.totalPrice != null">
|
||||||
|
AND a.total_price = #{param.totalPrice}
|
||||||
|
</if>
|
||||||
|
<if test="param.reducePrice != null">
|
||||||
|
AND a.reduce_price = #{param.reducePrice}
|
||||||
|
</if>
|
||||||
|
<if test="param.payPrice != null">
|
||||||
|
AND a.pay_price = #{param.payPrice}
|
||||||
|
</if>
|
||||||
|
<if test="param.price != null">
|
||||||
|
AND a.price = #{param.price}
|
||||||
|
</if>
|
||||||
|
<if test="param.money != null">
|
||||||
|
AND a.money = #{param.money}
|
||||||
|
</if>
|
||||||
|
<if test="param.cancelTime != null">
|
||||||
|
AND a.cancel_time LIKE CONCAT('%', #{param.cancelTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.cancelReason != null">
|
||||||
|
AND a.cancel_reason LIKE CONCAT('%', #{param.cancelReason}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.refundMoney != null">
|
||||||
|
AND a.refund_money = #{param.refundMoney}
|
||||||
|
</if>
|
||||||
|
<if test="param.coachPrice != null">
|
||||||
|
AND a.coach_price = #{param.coachPrice}
|
||||||
|
</if>
|
||||||
|
<if test="param.totalNum != null">
|
||||||
|
AND a.total_num = #{param.totalNum}
|
||||||
|
</if>
|
||||||
|
<if test="param.coachId != null">
|
||||||
|
AND a.coach_id = #{param.coachId}
|
||||||
|
</if>
|
||||||
|
<if test="param.formId != null">
|
||||||
|
AND a.form_id = #{param.formId}
|
||||||
|
</if>
|
||||||
|
<if test="param.payUserId != null">
|
||||||
|
AND a.pay_user_id = #{param.payUserId}
|
||||||
|
</if>
|
||||||
|
<if test="param.payType != null">
|
||||||
|
AND a.pay_type = #{param.payType}
|
||||||
|
</if>
|
||||||
|
<if test="param.wechatPayType != null">
|
||||||
|
AND a.wechat_pay_type LIKE CONCAT('%', #{param.wechatPayType}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.friendPayType != null">
|
||||||
|
AND a.friend_pay_type = #{param.friendPayType}
|
||||||
|
</if>
|
||||||
|
<if test="param.payStatus != null">
|
||||||
|
AND a.pay_status = #{param.payStatus}
|
||||||
|
</if>
|
||||||
|
<if test="param.orderStatus != null">
|
||||||
|
AND a.order_status = #{param.orderStatus}
|
||||||
|
</if>
|
||||||
|
<if test="param.deliveryStatus != null">
|
||||||
|
AND a.delivery_status = #{param.deliveryStatus}
|
||||||
|
</if>
|
||||||
|
<if test="param.deliveryNote != null">
|
||||||
|
AND a.delivery_note LIKE CONCAT('%', #{param.deliveryNote}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.deliveryTime != null">
|
||||||
|
AND a.delivery_time LIKE CONCAT('%', #{param.deliveryTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.evaluateStatus != null">
|
||||||
|
AND a.evaluate_status = #{param.evaluateStatus}
|
||||||
|
</if>
|
||||||
|
<if test="param.evaluateTime != null">
|
||||||
|
AND a.evaluate_time LIKE CONCAT('%', #{param.evaluateTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.couponType != null">
|
||||||
|
AND a.coupon_type = #{param.couponType}
|
||||||
|
</if>
|
||||||
|
<if test="param.couponDesc != null">
|
||||||
|
AND a.coupon_desc LIKE CONCAT('%', #{param.couponDesc}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.qrcode != null">
|
||||||
|
AND a.qrcode LIKE CONCAT('%', #{param.qrcode}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.returnNum != null">
|
||||||
|
AND a.return_num = #{param.returnNum}
|
||||||
|
</if>
|
||||||
|
<if test="param.returnMoney != null">
|
||||||
|
AND a.return_money = #{param.returnMoney}
|
||||||
|
</if>
|
||||||
|
<if test="param.startTime != null">
|
||||||
|
AND a.start_time LIKE CONCAT('%', #{param.startTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.isInvoice != null">
|
||||||
|
AND a.is_invoice = #{param.isInvoice}
|
||||||
|
</if>
|
||||||
|
<if test="param.invoiceNo != null">
|
||||||
|
AND a.invoice_no LIKE CONCAT('%', #{param.invoiceNo}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.merchantRemarks != null">
|
||||||
|
AND a.merchant_remarks LIKE CONCAT('%', #{param.merchantRemarks}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.payTime != null">
|
||||||
|
AND a.pay_time LIKE CONCAT('%', #{param.payTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.refundTime != null">
|
||||||
|
AND a.refund_time LIKE CONCAT('%', #{param.refundTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.refundApplyTime != null">
|
||||||
|
AND a.refund_apply_time LIKE CONCAT('%', #{param.refundApplyTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.expirationTime != null">
|
||||||
|
AND a.expiration_time LIKE CONCAT('%', #{param.expirationTime}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.selfTakeCode != null">
|
||||||
|
AND a.self_take_code LIKE CONCAT('%', #{param.selfTakeCode}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.hasTakeGift != null">
|
||||||
|
AND a.has_take_gift = #{param.hasTakeGift}
|
||||||
|
</if>
|
||||||
|
<if test="param.checkBill != null">
|
||||||
|
AND a.check_bill = #{param.checkBill}
|
||||||
|
</if>
|
||||||
|
<if test="param.isSettled != null">
|
||||||
|
AND a.is_settled = #{param.isSettled}
|
||||||
|
</if>
|
||||||
|
<if test="param.version != null">
|
||||||
|
AND a.version = #{param.version}
|
||||||
|
</if>
|
||||||
|
<if test="param.userId != null">
|
||||||
|
AND a.user_id = #{param.userId}
|
||||||
|
</if>
|
||||||
|
<if test="param.comments != null">
|
||||||
|
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="param.sortNumber != null">
|
||||||
|
AND a.sort_number = #{param.sortNumber}
|
||||||
|
</if>
|
||||||
|
<if test="param.deleted != null">
|
||||||
|
AND a.deleted = #{param.deleted}
|
||||||
|
</if>
|
||||||
|
<if test="param.deleted == null">
|
||||||
|
AND a.deleted = 0
|
||||||
|
</if>
|
||||||
|
<if test="param.createTimeStart != null">
|
||||||
|
AND a.create_time >= #{param.createTimeStart}
|
||||||
|
</if>
|
||||||
|
<if test="param.createTimeEnd != null">
|
||||||
|
AND a.create_time <= #{param.createTimeEnd}
|
||||||
|
</if>
|
||||||
|
<if test="param.keywords != null">
|
||||||
|
AND (a.comments LIKE CONCAT('%', #{param.keywords}, '%')
|
||||||
|
)
|
||||||
|
</if>
|
||||||
|
</where>
|
||||||
|
</sql>
|
||||||
|
|
||||||
|
<!-- 分页查询 -->
|
||||||
|
<select id="selectPageRel" resultType="com.gxwebsoft.cms.entity.CmsOrder">
|
||||||
|
<include refid="selectSql"></include>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 查询全部 -->
|
||||||
|
<select id="selectListRel" resultType="com.gxwebsoft.cms.entity.CmsOrder">
|
||||||
|
<include refid="selectSql"></include>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package com.gxwebsoft.cms.param;
|
||||||
|
|
||||||
|
import cn.afterturn.easypoi.excel.annotation.Excel;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站导航导入参数(Excel 批量导入)
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CmsNavigationImportParam implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Excel(name = "导航ID")
|
||||||
|
private Integer navigationId;
|
||||||
|
|
||||||
|
@Excel(name = "类型")
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
@Excel(name = "菜单名称")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Excel(name = "上级id")
|
||||||
|
private Integer parentId;
|
||||||
|
|
||||||
|
@Excel(name = "模型")
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
@Excel(name = "标识")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
@Excel(name = "菜单路由地址")
|
||||||
|
private String path;
|
||||||
|
|
||||||
|
@Excel(name = "菜单组件地址")
|
||||||
|
private String component;
|
||||||
|
|
||||||
|
@Excel(name = "打开位置")
|
||||||
|
private String target;
|
||||||
|
|
||||||
|
@Excel(name = "菜单图标")
|
||||||
|
private String icon;
|
||||||
|
|
||||||
|
@Excel(name = "图标颜色")
|
||||||
|
private String color;
|
||||||
|
|
||||||
|
@Excel(name = "是否隐藏")
|
||||||
|
private Integer hide;
|
||||||
|
|
||||||
|
@Excel(name = "可见类型")
|
||||||
|
private Integer permission;
|
||||||
|
|
||||||
|
@Excel(name = "访问密码")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@Excel(name = "位置")
|
||||||
|
private Integer position;
|
||||||
|
|
||||||
|
@Excel(name = "仅在顶部显示")
|
||||||
|
private Integer top;
|
||||||
|
|
||||||
|
@Excel(name = "仅在底部显示")
|
||||||
|
private Integer bottom;
|
||||||
|
|
||||||
|
@Excel(name = "选中path")
|
||||||
|
private String active;
|
||||||
|
|
||||||
|
@Excel(name = "其它路由元信息")
|
||||||
|
private String meta;
|
||||||
|
|
||||||
|
@Excel(name = "css样式")
|
||||||
|
private String style;
|
||||||
|
|
||||||
|
@Excel(name = "模型名称")
|
||||||
|
private String modelName;
|
||||||
|
|
||||||
|
@Excel(name = "页面ID")
|
||||||
|
private Integer pageId;
|
||||||
|
|
||||||
|
@Excel(name = "详情页ID")
|
||||||
|
private Integer itemId;
|
||||||
|
|
||||||
|
@Excel(name = "是否微信小程序菜单")
|
||||||
|
private Boolean isMpWeixin;
|
||||||
|
|
||||||
|
@Excel(name = "菜单间距")
|
||||||
|
private Integer gutter;
|
||||||
|
|
||||||
|
@Excel(name = "菜单宽度")
|
||||||
|
private Integer span;
|
||||||
|
|
||||||
|
@Excel(name = "阅读量")
|
||||||
|
private Integer readNum;
|
||||||
|
|
||||||
|
@Excel(name = "商户ID")
|
||||||
|
private Long merchantId;
|
||||||
|
|
||||||
|
@Excel(name = "国际化语言")
|
||||||
|
private String lang;
|
||||||
|
|
||||||
|
@Excel(name = "设为首页")
|
||||||
|
private Integer home;
|
||||||
|
|
||||||
|
@Excel(name = "是否推荐")
|
||||||
|
private Boolean recommend;
|
||||||
|
|
||||||
|
@Excel(name = "排序")
|
||||||
|
private Integer sortNumber;
|
||||||
|
|
||||||
|
@Excel(name = "备注")
|
||||||
|
private String comments;
|
||||||
|
|
||||||
|
@Excel(name = "状态")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Excel(name = "用户ID")
|
||||||
|
private Integer userId;
|
||||||
|
|
||||||
|
@Excel(name = "租户ID")
|
||||||
|
private Integer tenantId;
|
||||||
|
}
|
||||||
|
|
||||||
284
src/main/java/com/gxwebsoft/cms/param/CmsOrderParam.java
Normal file
284
src/main/java/com/gxwebsoft/cms/param/CmsOrderParam.java
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
package com.gxwebsoft.cms.param;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||||
|
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||||
|
import com.gxwebsoft.common.core.web.BaseParam;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单查询参数
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:24
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
@Schema(name = "CmsOrderParam对象", description = "网站订单查询参数")
|
||||||
|
public class CmsOrderParam extends BaseParam {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Schema(description = "id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Schema(description = "订单类型,0售前咨询 1售后服务 2意见反馈")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
@Schema(description = "订单标题")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Schema(description = "公司/团队名称")
|
||||||
|
private String company;
|
||||||
|
|
||||||
|
@Schema(description = "订单内容")
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
@Schema(description = "订单编号")
|
||||||
|
private String orderNo;
|
||||||
|
|
||||||
|
@Schema(description = "快递/自提")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer deliveryType;
|
||||||
|
|
||||||
|
@Schema(description = "下单渠道,0网站 1微信小程序 2其他")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer channel;
|
||||||
|
|
||||||
|
@Schema(description = "微信支付交易号号")
|
||||||
|
private String transactionId;
|
||||||
|
|
||||||
|
@Schema(description = "微信退款订单号")
|
||||||
|
private String refundOrder;
|
||||||
|
|
||||||
|
@Schema(description = "商户ID")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Long merchantId;
|
||||||
|
|
||||||
|
@Schema(description = "商户名称")
|
||||||
|
private String merchantName;
|
||||||
|
|
||||||
|
@Schema(description = "商户编号")
|
||||||
|
private String merchantCode;
|
||||||
|
|
||||||
|
@Schema(description = "使用的优惠券id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer couponId;
|
||||||
|
|
||||||
|
@Schema(description = "使用的会员卡id")
|
||||||
|
private String cardId;
|
||||||
|
|
||||||
|
@Schema(description = "关联管理员id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer adminId;
|
||||||
|
|
||||||
|
@Schema(description = "核销管理员id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer confirmId;
|
||||||
|
|
||||||
|
@Schema(description = "IC卡号")
|
||||||
|
private String icCard;
|
||||||
|
|
||||||
|
@Schema(description = "真实姓名")
|
||||||
|
private String realName;
|
||||||
|
|
||||||
|
@Schema(description = "关联收货地址")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer addressId;
|
||||||
|
|
||||||
|
@Schema(description = "收货地址")
|
||||||
|
private String address;
|
||||||
|
|
||||||
|
private String addressLat;
|
||||||
|
|
||||||
|
private String addressLng;
|
||||||
|
|
||||||
|
@Schema(description = "自提店铺id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer selfTakeMerchantId;
|
||||||
|
|
||||||
|
@Schema(description = "自提店铺")
|
||||||
|
private String selfTakeMerchantName;
|
||||||
|
|
||||||
|
@Schema(description = "配送开始时间")
|
||||||
|
private String sendStartTime;
|
||||||
|
|
||||||
|
@Schema(description = "配送结束时间")
|
||||||
|
private String sendEndTime;
|
||||||
|
|
||||||
|
@Schema(description = "发货店铺id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer expressMerchantId;
|
||||||
|
|
||||||
|
@Schema(description = "发货店铺")
|
||||||
|
private String expressMerchantName;
|
||||||
|
|
||||||
|
@Schema(description = "订单总额")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal totalPrice;
|
||||||
|
|
||||||
|
@Schema(description = "减少的金额,使用VIP会员折扣、优惠券抵扣、优惠券折扣后减去的价格")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal reducePrice;
|
||||||
|
|
||||||
|
@Schema(description = "实际付款")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal payPrice;
|
||||||
|
|
||||||
|
@Schema(description = "用于统计")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal price;
|
||||||
|
|
||||||
|
@Schema(description = "价钱,用于积分赠送")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal money;
|
||||||
|
|
||||||
|
@Schema(description = "取消时间")
|
||||||
|
private String cancelTime;
|
||||||
|
|
||||||
|
@Schema(description = "取消原因")
|
||||||
|
private String cancelReason;
|
||||||
|
|
||||||
|
@Schema(description = "退款金额")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal refundMoney;
|
||||||
|
|
||||||
|
@Schema(description = "教练价格")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal coachPrice;
|
||||||
|
|
||||||
|
@Schema(description = "购买数量")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer totalNum;
|
||||||
|
|
||||||
|
@Schema(description = "教练id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer coachId;
|
||||||
|
|
||||||
|
@Schema(description = "商品ID")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer formId;
|
||||||
|
|
||||||
|
@Schema(description = "支付的用户id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer payUserId;
|
||||||
|
|
||||||
|
@Schema(description = "0余额支付,1微信支付,2支付宝支付,3银联支付,4现金支付,5POS机支付,6免费,7积分支付")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer payType;
|
||||||
|
|
||||||
|
@Schema(description = "微信支付子类型:JSAPI小程序支付,NATIVE扫码支付")
|
||||||
|
private String wechatPayType;
|
||||||
|
|
||||||
|
@Schema(description = "0余额支付,1微信支付,2支付宝支付,3银联支付,4现金支付,5POS机支付,6免费,7积分支付")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer friendPayType;
|
||||||
|
|
||||||
|
@Schema(description = "0未付款,1已付款")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer payStatus;
|
||||||
|
|
||||||
|
@Schema(description = "0未使用,1已完成,2已取消,3取消中,4退款申请中,5退款被拒绝,6退款成功,7客户端申请退款")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer orderStatus;
|
||||||
|
|
||||||
|
@Schema(description = "发货状态(10未发货 20已发货 30部分发货)")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer deliveryStatus;
|
||||||
|
|
||||||
|
@Schema(description = "无需发货备注")
|
||||||
|
private String deliveryNote;
|
||||||
|
|
||||||
|
@Schema(description = "发货时间")
|
||||||
|
private String deliveryTime;
|
||||||
|
|
||||||
|
@Schema(description = "评价状态(0未评价 1已评价)")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer evaluateStatus;
|
||||||
|
|
||||||
|
@Schema(description = "评价时间")
|
||||||
|
private String evaluateTime;
|
||||||
|
|
||||||
|
@Schema(description = "优惠类型:0无、1抵扣优惠券、2折扣优惠券、3、VIP月卡、4VIP年卡,5VIP次卡、6VIP会员卡、7IC月卡、8IC年卡、9IC次卡、10IC会员卡、11免费订单、12VIP充值卡、13IC充值卡、14VIP季卡、15IC季卡")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer couponType;
|
||||||
|
|
||||||
|
@Schema(description = "优惠说明")
|
||||||
|
private String couponDesc;
|
||||||
|
|
||||||
|
@Schema(description = "二维码地址,保存订单号,支付成功后才生成")
|
||||||
|
private String qrcode;
|
||||||
|
|
||||||
|
@Schema(description = "vip月卡年卡、ic月卡年卡回退次数")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer returnNum;
|
||||||
|
|
||||||
|
@Schema(description = "vip充值回退金额")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private BigDecimal returnMoney;
|
||||||
|
|
||||||
|
@Schema(description = "预约详情开始时间数组")
|
||||||
|
private String startTime;
|
||||||
|
|
||||||
|
@Schema(description = "是否已开具发票:0未开发票,1已开发票,2不能开具发票")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer isInvoice;
|
||||||
|
|
||||||
|
@Schema(description = "发票流水号")
|
||||||
|
private String invoiceNo;
|
||||||
|
|
||||||
|
@Schema(description = "商家留言")
|
||||||
|
private String merchantRemarks;
|
||||||
|
|
||||||
|
@Schema(description = "支付时间")
|
||||||
|
private String payTime;
|
||||||
|
|
||||||
|
@Schema(description = "退款时间")
|
||||||
|
private String refundTime;
|
||||||
|
|
||||||
|
@Schema(description = "申请退款时间")
|
||||||
|
private String refundApplyTime;
|
||||||
|
|
||||||
|
@Schema(description = "过期时间")
|
||||||
|
private String expirationTime;
|
||||||
|
|
||||||
|
@Schema(description = "自提码")
|
||||||
|
private String selfTakeCode;
|
||||||
|
|
||||||
|
@Schema(description = "是否已收到赠品")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Boolean hasTakeGift;
|
||||||
|
|
||||||
|
@Schema(description = "对账情况:0=未对账;1=已对账;3=已对账,金额对不上;4=未查询到该订单")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer checkBill;
|
||||||
|
|
||||||
|
@Schema(description = "订单是否已结算(0未结算 1已结算)")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer isSettled;
|
||||||
|
|
||||||
|
@Schema(description = "系统版本号 0当前版本 value=其他版本")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer version;
|
||||||
|
|
||||||
|
@Schema(description = "用户id")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer userId;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String comments;
|
||||||
|
|
||||||
|
@Schema(description = "排序号")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer sortNumber;
|
||||||
|
|
||||||
|
@Schema(description = "是否删除, 0否, 1是")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer deleted;
|
||||||
|
|
||||||
|
}
|
||||||
42
src/main/java/com/gxwebsoft/cms/service/CmsOrderService.java
Normal file
42
src/main/java/com/gxwebsoft/cms/service/CmsOrderService.java
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package com.gxwebsoft.cms.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsOrder;
|
||||||
|
import com.gxwebsoft.cms.param.CmsOrderParam;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单Service
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:24
|
||||||
|
*/
|
||||||
|
public interface CmsOrderService extends IService<CmsOrder> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页关联查询
|
||||||
|
*
|
||||||
|
* @param param 查询参数
|
||||||
|
* @return PageResult<CmsOrder>
|
||||||
|
*/
|
||||||
|
PageResult<CmsOrder> pageRel(CmsOrderParam param);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关联查询全部
|
||||||
|
*
|
||||||
|
* @param param 查询参数
|
||||||
|
* @return List<CmsOrder>
|
||||||
|
*/
|
||||||
|
List<CmsOrder> listRel(CmsOrderParam param);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据id查询
|
||||||
|
*
|
||||||
|
* @param id id
|
||||||
|
* @return CmsOrder
|
||||||
|
*/
|
||||||
|
CmsOrder getByIdRel(Integer id);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.gxwebsoft.cms.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.gxwebsoft.cms.mapper.CmsOrderMapper;
|
||||||
|
import com.gxwebsoft.cms.service.CmsOrderService;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsOrder;
|
||||||
|
import com.gxwebsoft.cms.param.CmsOrderParam;
|
||||||
|
import com.gxwebsoft.common.core.web.PageParam;
|
||||||
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网站订单Service实现
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2026-01-27 13:03:24
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class CmsOrderServiceImpl extends ServiceImpl<CmsOrderMapper, CmsOrder> implements CmsOrderService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<CmsOrder> pageRel(CmsOrderParam param) {
|
||||||
|
PageParam<CmsOrder, CmsOrderParam> page = new PageParam<>(param);
|
||||||
|
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||||
|
List<CmsOrder> list = baseMapper.selectPageRel(page, param);
|
||||||
|
return new PageResult<>(list, page.getTotal());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<CmsOrder> listRel(CmsOrderParam param) {
|
||||||
|
List<CmsOrder> list = baseMapper.selectListRel(param);
|
||||||
|
// 排序
|
||||||
|
PageParam<CmsOrder, CmsOrderParam> page = new PageParam<>();
|
||||||
|
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||||
|
return page.sortRecords(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CmsOrder getByIdRel(Integer id) {
|
||||||
|
CmsOrderParam param = new CmsOrderParam();
|
||||||
|
param.setId(id);
|
||||||
|
return param.getOne(baseMapper.selectListRel(param));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -337,9 +337,16 @@ public class CmsWebsiteServiceImpl extends ServiceImpl<CmsWebsiteMapper, CmsWebs
|
|||||||
if (StrUtil.isNotBlank(siteInfo)) {
|
if (StrUtil.isNotBlank(siteInfo)) {
|
||||||
log.info("从缓存获取网站信息,租户ID: {}", tenantId);
|
log.info("从缓存获取网站信息,租户ID: {}", tenantId);
|
||||||
try {
|
try {
|
||||||
return JSONUtil.parseObject(siteInfo, ShopVo.class);
|
// 兼容历史缓存:JSON "null" 会被解析为 null;此时应视为未命中并回源数据库。
|
||||||
|
ShopVo cacheVo = JSONUtil.parseObject(siteInfo, ShopVo.class);
|
||||||
|
if (cacheVo != null) {
|
||||||
|
return cacheVo;
|
||||||
|
}
|
||||||
|
log.warn("网站信息缓存命中但内容为空(null),清理缓存后回源数据库,租户ID: {}", tenantId);
|
||||||
|
redisUtil.delete(cacheKey);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("缓存解析失败,从数据库重新获取: {}", e.getMessage());
|
log.warn("缓存解析失败,清理缓存后从数据库重新获取: {}", e.getMessage());
|
||||||
|
redisUtil.delete(cacheKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,11 @@ public class ConfigProperties {
|
|||||||
*/
|
*/
|
||||||
private String serverUrl;
|
private String serverUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API网关地址
|
||||||
|
*/
|
||||||
|
private String apiUrl;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 阿里云存储 OSS
|
* 阿里云存储 OSS
|
||||||
* Endpoint
|
* Endpoint
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
|
||||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package com.gxwebsoft.common.core.config;
|
package com.gxwebsoft.common.core.config;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonParser;
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,14 +19,43 @@ import java.time.format.DateTimeFormatter;
|
|||||||
*/
|
*/
|
||||||
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
|
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
|
||||||
|
|
||||||
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
private final DateTimeFormatter formatter;
|
||||||
|
|
||||||
|
public LocalDateTimeDeserializer() {
|
||||||
|
this(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTimeDeserializer(DateTimeFormatter formatter) {
|
||||||
|
this.formatter = formatter;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||||
String value = p.getValueAsString();
|
JsonToken t = p.currentToken();
|
||||||
if (value != null && !value.isEmpty()) {
|
ZoneId zoneId = ctxt.getTimeZone() != null ? ctxt.getTimeZone().toZoneId() : ZoneId.systemDefault();
|
||||||
return LocalDateTime.parse(value, FORMATTER);
|
|
||||||
|
// Accept epoch timestamps (seconds or millis) for compatibility with frontends that send numbers.
|
||||||
|
if (t == JsonToken.VALUE_NUMBER_INT) {
|
||||||
|
long ts = p.getLongValue();
|
||||||
|
// Heuristic: 10+ digits is seconds; 13+ digits is millis (most common in JS).
|
||||||
|
Instant instant = (String.valueOf(Math.abs(ts)).length() >= 13)
|
||||||
|
? Instant.ofEpochMilli(ts)
|
||||||
|
: Instant.ofEpochSecond(ts);
|
||||||
|
return LocalDateTime.ofInstant(instant, zoneId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String value = p.getValueAsString();
|
||||||
|
if (value == null || value.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle numeric timestamps passed as strings, e.g. "1769618486000"
|
||||||
|
if (value.chars().allMatch(Character::isDigit)) {
|
||||||
|
long ts = Long.parseLong(value);
|
||||||
|
Instant instant = (value.length() >= 13) ? Instant.ofEpochMilli(ts) : Instant.ofEpochSecond(ts);
|
||||||
|
return LocalDateTime.ofInstant(instant, zoneId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return LocalDateTime.parse(value, formatter);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,7 +80,8 @@ public class SwaggerConfig {
|
|||||||
public GroupedOpenApi shopApi() {
|
public GroupedOpenApi shopApi() {
|
||||||
return GroupedOpenApi.builder()
|
return GroupedOpenApi.builder()
|
||||||
.group("shop")
|
.group("shop")
|
||||||
.pathsToMatch("/api/shop/**")
|
// 订单等用户侧接口在 shop 包内,但路径使用 /api/user/**(前端统一 user 侧 API 前缀)
|
||||||
|
.pathsToMatch("/api/shop/**", "/api/user/**")
|
||||||
.packagesToScan("com.gxwebsoft.shop")
|
.packagesToScan("com.gxwebsoft.shop")
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ public class SecurityConfig {
|
|||||||
"/api/shop/wx-login/**",
|
"/api/shop/wx-login/**",
|
||||||
"/api/shop/wx-native-pay/**",
|
"/api/shop/wx-native-pay/**",
|
||||||
"/api/shop/wx-pay/**",
|
"/api/shop/wx-pay/**",
|
||||||
|
"/api/system/wx-pay/**",
|
||||||
"/api/bszx/bszx-pay/notify/**",
|
"/api/bszx/bszx-pay/notify/**",
|
||||||
"/api/wxWorkQrConnect",
|
"/api/wxWorkQrConnect",
|
||||||
"/WW_verify_QMv7HoblYU6z63bb.txt",
|
"/WW_verify_QMv7HoblYU6z63bb.txt",
|
||||||
|
|||||||
@@ -50,15 +50,26 @@ public class EnvironmentAwarePaymentService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 根据环境调整回调地址
|
// 开发/测试环境允许强制覆盖,方便本地联调。
|
||||||
|
if (isDevelopmentEnvironment()) {
|
||||||
Payment envPayment = clonePayment(payment);
|
Payment envPayment = clonePayment(payment);
|
||||||
String notifyUrl = getEnvironmentNotifyUrl();
|
String notifyUrl = getEnvironmentNotifyUrl();
|
||||||
|
log.info("环境感知支付配置(开发/测试) - 环境: {}, 原始回调: {}, 覆盖后回调: {}",
|
||||||
log.info("环境感知支付配置 - 环境: {}, 原始回调: {}, 调整后回调: {}",
|
|
||||||
activeProfile, payment.getNotifyUrl(), notifyUrl);
|
activeProfile, payment.getNotifyUrl(), notifyUrl);
|
||||||
|
|
||||||
envPayment.setNotifyUrl(notifyUrl);
|
envPayment.setNotifyUrl(notifyUrl);
|
||||||
|
return envPayment;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生产/其它环境:优先使用数据库中的 notifyUrl(多租户域名可能不同)。
|
||||||
|
if (payment.getNotifyUrl() != null && !payment.getNotifyUrl().trim().isEmpty()) {
|
||||||
|
return payment;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据库未配置时才兜底使用环境配置。
|
||||||
|
Payment envPayment = clonePayment(payment);
|
||||||
|
String notifyUrl = getEnvironmentNotifyUrl();
|
||||||
|
log.info("环境感知支付配置(兜底) - 环境: {}, 原始回调为空,兜底回调: {}", activeProfile, notifyUrl);
|
||||||
|
envPayment.setNotifyUrl(notifyUrl);
|
||||||
return envPayment;
|
return envPayment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
package com.gxwebsoft.common.core.utils;
|
package com.gxwebsoft.common.core.utils;
|
||||||
|
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||||
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||||
|
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON解析工具类
|
* JSON解析工具类
|
||||||
@@ -11,8 +16,21 @@ import com.fasterxml.jackson.databind.ObjectWriter;
|
|||||||
* @since 2017-06-10 10:10:39
|
* @since 2017-06-10 10:10:39
|
||||||
*/
|
*/
|
||||||
public class JSONUtil {
|
public class JSONUtil {
|
||||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
/**
|
||||||
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
|
* 注意:不要直接 new ObjectMapper() 否则不支持 Java8 时间类型(LocalDateTime 等)。
|
||||||
|
* 这里做最小可用配置,避免在 Redis/日志/签名等场景序列化失败。
|
||||||
|
*/
|
||||||
|
private static final ObjectMapper objectMapper;
|
||||||
|
private static final ObjectWriter objectWriter;
|
||||||
|
|
||||||
|
static {
|
||||||
|
objectMapper = new ObjectMapper();
|
||||||
|
objectMapper.registerModule(new JavaTimeModule());
|
||||||
|
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
|
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
|
||||||
|
objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对象转json字符串
|
* 对象转json字符串
|
||||||
|
|||||||
119
src/main/java/com/gxwebsoft/common/core/web/ImportParams.java
Normal file
119
src/main/java/com/gxwebsoft/common/core/web/ImportParams.java
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
/**
|
||||||
|
* Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com)
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package com.gxwebsoft.common.core.web;
|
||||||
|
|
||||||
|
import cn.afterturn.easypoi.excel.entity.ExcelBaseParams;
|
||||||
|
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导入参数设置
|
||||||
|
*
|
||||||
|
* @author JueYue
|
||||||
|
* 2013-9-24
|
||||||
|
* @version 1.0
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ImportParams extends ExcelBaseParams {
|
||||||
|
|
||||||
|
public static final String SAVE_URL = "/excel/upload/excelUpload";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 表格标题行数,默认0
|
||||||
|
*/
|
||||||
|
private int titleRows = 0;
|
||||||
|
/**
|
||||||
|
* 表头行数,默认1
|
||||||
|
*/
|
||||||
|
private int headRows = 1;
|
||||||
|
/**
|
||||||
|
* 字段真正值和列标题之间的距离 默认0
|
||||||
|
*/
|
||||||
|
private int startRows = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主键设置,如何这个cell没有值,就跳过 或者认为这个是list的下面的值
|
||||||
|
* 大家不理解,去掉这个
|
||||||
|
*/
|
||||||
|
|
||||||
|
private Integer keyIndex = null;
|
||||||
|
/**
|
||||||
|
* 开始读取的sheet位置,默认为0
|
||||||
|
*/
|
||||||
|
private int startSheetIndex = 0;
|
||||||
|
/**
|
||||||
|
* 上传表格需要读取的sheet 数量,默认为1
|
||||||
|
*/
|
||||||
|
private int sheetNum = 1;
|
||||||
|
/**
|
||||||
|
* 是否需要保存上传的Excel,默认为false
|
||||||
|
*/
|
||||||
|
private boolean needSave = false;
|
||||||
|
/**
|
||||||
|
* 校验组
|
||||||
|
*/
|
||||||
|
private Class[] verifyGroup = null;
|
||||||
|
/**
|
||||||
|
* 是否需要校验上传的Excel,默认为false
|
||||||
|
*/
|
||||||
|
private boolean needVerify = false;
|
||||||
|
/**
|
||||||
|
* 返回文件是否分割,默认是分割
|
||||||
|
*/
|
||||||
|
private boolean verifyFileSplit = true;
|
||||||
|
/**
|
||||||
|
* 校验处理接口
|
||||||
|
*/
|
||||||
|
private IExcelVerifyHandler verifyHandler;
|
||||||
|
/**
|
||||||
|
* 保存上传的Excel目录,默认是 如 TestEntity这个类保存路径就是
|
||||||
|
* upload/excelUpload/Test/yyyyMMddHHmss_***** 保存名称上传时间_五位随机数
|
||||||
|
*/
|
||||||
|
private String saveUrl = SAVE_URL;
|
||||||
|
/**
|
||||||
|
* 最后的无效行数
|
||||||
|
*/
|
||||||
|
private int lastOfInvalidRow = 0;
|
||||||
|
/**
|
||||||
|
* 手动控制读取的行数
|
||||||
|
*/
|
||||||
|
private int readRows = 0;
|
||||||
|
/**
|
||||||
|
* 导入时校验数据模板,是不是正确的Excel
|
||||||
|
*/
|
||||||
|
private String[] importFields;
|
||||||
|
/**
|
||||||
|
* 导入时校验excel的标题列顺序。依赖于importFields的配置顺序
|
||||||
|
*/
|
||||||
|
private boolean needCheckOrder = false;
|
||||||
|
/**
|
||||||
|
* Key-Value 读取标记,以这个为Key,后面一个Cell 为Value,多个改为ArrayList
|
||||||
|
*/
|
||||||
|
private String keyMark = ":";
|
||||||
|
/**
|
||||||
|
* 按照Key-Value 规则读取全局扫描Excel,但是跳过List读取范围提升性能
|
||||||
|
* 仅仅支持titleRows + headRows + startRows 以及 lastOfInvalidRow
|
||||||
|
*/
|
||||||
|
private boolean readSingleCell = false;
|
||||||
|
/**
|
||||||
|
* 是否并行计算
|
||||||
|
*/
|
||||||
|
private boolean concurrentTask = false;
|
||||||
|
/**
|
||||||
|
* 最小截取大小
|
||||||
|
*/
|
||||||
|
private Integer critical = 1000;
|
||||||
|
}
|
||||||
@@ -1,20 +1,29 @@
|
|||||||
package com.gxwebsoft.common.system.controller;
|
package com.gxwebsoft.common.system.controller;
|
||||||
|
|
||||||
|
import cn.afterturn.easypoi.excel.ExcelImportUtil;
|
||||||
|
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
||||||
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||||
import com.gxwebsoft.common.core.web.*;
|
import com.gxwebsoft.common.core.web.*;
|
||||||
import com.gxwebsoft.common.system.entity.Menu;
|
import com.gxwebsoft.common.system.entity.*;
|
||||||
import com.gxwebsoft.common.system.entity.Plug;
|
import com.gxwebsoft.common.system.param.MenuImportParam;
|
||||||
import com.gxwebsoft.common.system.param.MenuParam;
|
import com.gxwebsoft.common.system.param.MenuParam;
|
||||||
import com.gxwebsoft.common.system.service.MenuService;
|
import com.gxwebsoft.common.system.param.VersionParam;
|
||||||
import com.gxwebsoft.common.system.service.PlugService;
|
import com.gxwebsoft.common.system.service.*;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import java.util.List;
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 菜单控制器
|
* 菜单控制器
|
||||||
@@ -22,21 +31,27 @@ import java.util.List;
|
|||||||
* @author WebSoft
|
* @author WebSoft
|
||||||
* @since 2018-12-24 16:10:23
|
* @since 2018-12-24 16:10:23
|
||||||
*/
|
*/
|
||||||
@Tag(name = "菜单管理")
|
@Tag(name = "菜单")
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/system/menu")
|
@RequestMapping("/api/system/menu")
|
||||||
public class MenuController extends BaseController {
|
public class MenuController extends BaseController {
|
||||||
@Resource
|
@Resource
|
||||||
private MenuService menuService;
|
private MenuService menuService;
|
||||||
@Resource
|
@Resource
|
||||||
private PlugService plugService;
|
private CompanyService companyService;
|
||||||
|
@Resource
|
||||||
|
private UserService userService;
|
||||||
|
@Resource
|
||||||
|
private RoleService roleService;
|
||||||
|
@Resource
|
||||||
|
private RoleMenuService roleMenuService;
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:list')")
|
@PreAuthorize("hasAuthority('sys:menu:list')")
|
||||||
@Operation(summary = "分页查询菜单")
|
@Operation(summary = "分页查询菜单")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<Menu>> page(MenuParam param) {
|
public ApiResult<PageResult<Menu>> page(MenuParam param) {
|
||||||
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
||||||
page.setDefaultOrder("sort_number");
|
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||||
return success(menuService.page(page, page.getWrapper()));
|
return success(menuService.page(page, page.getWrapper()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +60,7 @@ public class MenuController extends BaseController {
|
|||||||
@GetMapping()
|
@GetMapping()
|
||||||
public ApiResult<List<Menu>> list(MenuParam param) {
|
public ApiResult<List<Menu>> list(MenuParam param) {
|
||||||
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
||||||
page.setDefaultOrder("sort_number");
|
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||||
return success(menuService.list(page.getOrderWrapper()));
|
return success(menuService.list(page.getOrderWrapper()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,12 +72,18 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:save')")
|
@PreAuthorize("hasAuthority('sys:menu:save')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "添加菜单")
|
@Operation(summary = "添加菜单")
|
||||||
@PostMapping()
|
@PostMapping()
|
||||||
public ApiResult<?> add(@RequestBody Menu menu) {
|
public ApiResult<?> add(@RequestBody Menu menu) {
|
||||||
if (menu.getParentId() == null) {
|
if (menu.getParentId() == null) {
|
||||||
menu.setParentId(0);
|
menu.setParentId(0);
|
||||||
}
|
}
|
||||||
|
// 去除字符串前面的空格
|
||||||
|
menu.setTitle(StrUtil.trimStart(menu.getTitle()));
|
||||||
|
menu.setPath(StrUtil.trimStart(menu.getPath()));
|
||||||
|
menu.setComponent(StrUtil.trimStart(menu.getComponent()));
|
||||||
|
menu.setAuthority(StrUtil.trimStart(menu.getAuthority()));
|
||||||
if (menuService.save(menu)) {
|
if (menuService.save(menu)) {
|
||||||
return success("添加成功");
|
return success("添加成功");
|
||||||
}
|
}
|
||||||
@@ -70,9 +91,15 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "修改菜单")
|
@Operation(summary = "修改菜单")
|
||||||
@PutMapping()
|
@PutMapping()
|
||||||
public ApiResult<?> update(@RequestBody Menu menu) {
|
public ApiResult<?> update(@RequestBody Menu menu) {
|
||||||
|
// 去除字符串前面的空格
|
||||||
|
menu.setTitle(StrUtil.trimStart(menu.getTitle()));
|
||||||
|
menu.setPath(StrUtil.trimStart(menu.getPath()));
|
||||||
|
menu.setComponent(StrUtil.trimStart(menu.getComponent()));
|
||||||
|
menu.setAuthority(StrUtil.trimStart(menu.getAuthority()));
|
||||||
if (menuService.updateById(menu)) {
|
if (menuService.updateById(menu)) {
|
||||||
return success("修改成功");
|
return success("修改成功");
|
||||||
}
|
}
|
||||||
@@ -80,6 +107,7 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "删除菜单")
|
@Operation(summary = "删除菜单")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
@@ -90,6 +118,7 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:save')")
|
@PreAuthorize("hasAuthority('sys:menu:save')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "批量添加菜单")
|
@Operation(summary = "批量添加菜单")
|
||||||
@PostMapping("/batch")
|
@PostMapping("/batch")
|
||||||
public ApiResult<?> saveBatch(@RequestBody List<Menu> menus) {
|
public ApiResult<?> saveBatch(@RequestBody List<Menu> menus) {
|
||||||
@@ -100,6 +129,7 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "批量修改菜单")
|
@Operation(summary = "批量修改菜单")
|
||||||
@PutMapping("/batch")
|
@PutMapping("/batch")
|
||||||
public ApiResult<?> updateBatch(@RequestBody BatchParam<Menu> batchParam) {
|
public ApiResult<?> updateBatch(@RequestBody BatchParam<Menu> batchParam) {
|
||||||
@@ -110,6 +140,7 @@ public class MenuController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
||||||
|
@OperationLog
|
||||||
@Operation(summary = "批量删除菜单")
|
@Operation(summary = "批量删除菜单")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
@@ -119,14 +150,35 @@ public class MenuController extends BaseController {
|
|||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
||||||
@Operation(summary = "菜单克隆")
|
@Operation(summary = "删除父级以下菜单")
|
||||||
@PostMapping("/clone")
|
@DeleteMapping("/deleteParentMenu/{id}")
|
||||||
public ApiResult<?> onClone(@RequestBody MenuParam param){
|
public ApiResult<?> deleteParentMenu(@PathVariable("id") Integer id) {
|
||||||
if(menuService.cloneMenu(param)){
|
final List<Menu> list = menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, id));
|
||||||
return success("克隆成功,请刷新");
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
menuService.removeById(id);
|
||||||
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("克隆失败");
|
final Set<Integer> ids = list.stream().map(Menu::getMenuId).collect(Collectors.toSet());
|
||||||
|
final List<Menu> list2 = menuService.list(new LambdaUpdateWrapper<Menu>().in(Menu::getParentId, ids));
|
||||||
|
final Set<Integer> collect = list2.stream().map(Menu::getMenuId).collect(Collectors.toSet());
|
||||||
|
if (!CollectionUtils.isEmpty(list2)) {
|
||||||
|
ids.addAll(collect);
|
||||||
|
final List<Menu> list3 = menuService.list(new LambdaUpdateWrapper<Menu>().in(Menu::getParentId, ids));
|
||||||
|
final Set<Integer> collect1 = list3.stream().map(Menu::getMenuId).collect(Collectors.toSet());
|
||||||
|
if (!CollectionUtils.isEmpty(collect1)) {
|
||||||
|
ids.addAll(collect1);
|
||||||
|
}
|
||||||
|
ids.add(id);
|
||||||
|
if (menuService.removeByIds(ids)) {
|
||||||
|
return success("删除成功");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ids.add(id);
|
||||||
|
if (menuService.removeByIds(ids)) {
|
||||||
|
return success("删除成功");
|
||||||
|
}
|
||||||
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||||
@@ -135,11 +187,271 @@ public class MenuController extends BaseController {
|
|||||||
public ApiResult<?> install(@PathVariable("id") Integer id){
|
public ApiResult<?> install(@PathVariable("id") Integer id){
|
||||||
if(menuService.install(id)){
|
if(menuService.install(id)){
|
||||||
// 更新安装次数
|
// 更新安装次数
|
||||||
final Plug plug = plugService.getOne(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, id));
|
// final Plug plug = plugService.getOne(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, id));
|
||||||
plug.setInstalls(plug.getInstalls() + 1);
|
// plug.setInstalls(plug.getInstalls() + 1);
|
||||||
plugService.updateById(plug);
|
// plugService.updateById(plug);
|
||||||
return success("安装成功");
|
return success("安装成功");
|
||||||
}
|
}
|
||||||
return fail("安装失败",id);
|
return fail("安装失败",id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* excel批量导入菜单
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('sys:menu:save')")
|
||||||
|
@Operation(summary = "批量导入菜单")
|
||||||
|
@Transactional(rollbackFor = {Exception.class})
|
||||||
|
@PostMapping("/import")
|
||||||
|
public ApiResult<?> importBatch(MultipartFile file) {
|
||||||
|
ImportParams importParams = new ImportParams();
|
||||||
|
try {
|
||||||
|
System.out.println("=== 开始菜单导入流程 ===");
|
||||||
|
|
||||||
|
// 检查导入前的菜单数据
|
||||||
|
long beforeCount = menuService.count();
|
||||||
|
System.out.println("导入前菜单总数: " + beforeCount);
|
||||||
|
|
||||||
|
// 检查当前未删除的菜单
|
||||||
|
List<Menu> undeletedMenus = menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getDeleted, 0));
|
||||||
|
System.out.println("当前未删除的菜单数: " + undeletedMenus.size());
|
||||||
|
if (!undeletedMenus.isEmpty()) {
|
||||||
|
System.out.println("未删除菜单列表:");
|
||||||
|
for (Menu menu : undeletedMenus) {
|
||||||
|
System.out.println(" ID: " + menu.getMenuId() + ", 名称: " + menu.getTitle() +
|
||||||
|
", 父级ID: " + menu.getParentId() + ", deleted: " + menu.getDeleted());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 第一步:永久删除已标记为 deleted=1 的记录
|
||||||
|
boolean deleteResult = menuService.remove(new LambdaQueryWrapper<Menu>().eq(Menu::getDeleted, 1));
|
||||||
|
System.out.println("已永久删除标记为deleted=1的菜单记录,结果: " + deleteResult);
|
||||||
|
|
||||||
|
// 第二步:将现有未删除的记录(deleted=0)标记为 deleted=1
|
||||||
|
if (!undeletedMenus.isEmpty()) {
|
||||||
|
LambdaUpdateWrapper<Menu> updateWrapper = new LambdaUpdateWrapper<>();
|
||||||
|
updateWrapper.eq(Menu::getDeleted, 0);
|
||||||
|
updateWrapper.set(Menu::getDeleted, 1);
|
||||||
|
boolean updateResult = menuService.update(updateWrapper);
|
||||||
|
System.out.println("更新未删除菜单记录的结果: " + updateResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查更新后的菜单数据
|
||||||
|
long afterCleanupCount = menuService.count(new LambdaQueryWrapper<Menu>().eq(Menu::getDeleted, 0));
|
||||||
|
System.out.println("清理后未标记删除的菜单数: " + afterCleanupCount);
|
||||||
|
|
||||||
|
// 第三步:导入XLS文件的内容
|
||||||
|
List<MenuImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), MenuImportParam.class, importParams);
|
||||||
|
System.out.println("从Excel文件中读取到" + list.size() + "条菜单记录");
|
||||||
|
|
||||||
|
// 存储原始parentId到菜单列表的映射关系
|
||||||
|
Map<Integer, List<MenuImportParam>> menuGroups = new HashMap<>();
|
||||||
|
// 存储原始ID到新菜单对象的映射关系(用于后续设置正确的parentId)
|
||||||
|
Map<Integer, Menu> tempIdMapping = new HashMap<>();
|
||||||
|
|
||||||
|
// 按parentId分组(处理null值)
|
||||||
|
for (MenuImportParam param : list) {
|
||||||
|
Integer parentId = param.getParentId() != null ? param.getParentId() : 0;
|
||||||
|
menuGroups.computeIfAbsent(parentId, k -> new ArrayList<>()).add(param);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("菜单分组情况:");
|
||||||
|
for (Map.Entry<Integer, List<MenuImportParam>> entry : menuGroups.entrySet()) {
|
||||||
|
System.out.println(" parentId=" + entry.getKey() + " 的菜单数: " + entry.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先创建所有父级菜单(parentId为0的菜单)
|
||||||
|
List<MenuImportParam> rootMenus = menuGroups.getOrDefault(0, new ArrayList<>());
|
||||||
|
List<Menu> createdRootMenus = new ArrayList<>();
|
||||||
|
|
||||||
|
System.out.println("开始创建" + rootMenus.size() + "个根菜单");
|
||||||
|
for (MenuImportParam param : rootMenus) {
|
||||||
|
Menu menu = convertToMenu(param);
|
||||||
|
menu.setParentId(0); // 根菜单的parentId为0
|
||||||
|
menuService.save(menu);
|
||||||
|
createdRootMenus.add(menu);
|
||||||
|
System.out.println("创建根菜单: " + menu.getTitle() + ", ID: " + menu.getMenuId() + ", 原始ID: " + param.getMenuId());
|
||||||
|
|
||||||
|
// 记录原始ID到新菜单的映射关系
|
||||||
|
if (param.getMenuId() != null) {
|
||||||
|
tempIdMapping.put(param.getMenuId(), menu);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 递归创建子级菜单(注意:这里不再处理parentId=0的菜单,因为已经在上面处理过了)
|
||||||
|
System.out.println("开始创建子级菜单(跳过根菜单)");
|
||||||
|
// 只处理非根菜单的子级菜单
|
||||||
|
for (Map.Entry<Integer, List<MenuImportParam>> entry : menuGroups.entrySet()) {
|
||||||
|
Integer parentId = entry.getKey();
|
||||||
|
if (parentId != 0) { // 跳过根菜单(parentId=0)
|
||||||
|
System.out.println("处理parentId=" + parentId + "的子菜单");
|
||||||
|
createChildMenus(menuGroups, tempIdMapping, parentId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取所有导入的菜单ID
|
||||||
|
List<Integer> allImportedMenuIds = new ArrayList<>();
|
||||||
|
for (Menu menu : tempIdMapping.values()) {
|
||||||
|
allImportedMenuIds.add(menu.getMenuId());
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("总共导入了" + allImportedMenuIds.size() + "个菜单");
|
||||||
|
|
||||||
|
// 显示导入的菜单详情
|
||||||
|
if (!allImportedMenuIds.isEmpty()) {
|
||||||
|
List<Menu> allImportedMenus = menuService.list(new LambdaQueryWrapper<Menu>()
|
||||||
|
.in(Menu::getMenuId, allImportedMenuIds)
|
||||||
|
.orderByAsc(Menu::getParentId, Menu::getSortNumber));
|
||||||
|
System.out.println("导入的菜单详情:");
|
||||||
|
for (Menu menu : allImportedMenus) {
|
||||||
|
System.out.println(" ID: " + menu.getMenuId() + ", 名称: " + menu.getTitle() +
|
||||||
|
", 父级ID: " + menu.getParentId() + ", 类型: " + menu.getMenuType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 为超级管理员配置菜单权限
|
||||||
|
if (!allImportedMenuIds.isEmpty()) {
|
||||||
|
List<Menu> allImportedMenus = menuService.list(new LambdaQueryWrapper<Menu>()
|
||||||
|
.in(Menu::getMenuId, allImportedMenuIds));
|
||||||
|
System.out.println("为" + allImportedMenus.size() + "个菜单配置超级管理员权限");
|
||||||
|
configureSuperAdminPermissionsForImportedMenus(allImportedMenus);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 最终检查
|
||||||
|
long finalCount = menuService.count();
|
||||||
|
System.out.println("导入后菜单总数: " + finalCount);
|
||||||
|
System.out.println("=== 菜单导入流程结束 ===");
|
||||||
|
|
||||||
|
return success("成功导入" + list.size() + "条");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归创建子级菜单
|
||||||
|
* @param menuGroups 菜单分组
|
||||||
|
* @param tempIdMapping 临时ID映射关系
|
||||||
|
* @param originalParentId 原始父级ID
|
||||||
|
*/
|
||||||
|
private void createChildMenus(Map<Integer, List<MenuImportParam>> menuGroups,
|
||||||
|
Map<Integer, Menu> tempIdMapping,
|
||||||
|
Integer originalParentId) {
|
||||||
|
System.out.println(">>> 进入createChildMenus方法,处理originalParentId=" + originalParentId);
|
||||||
|
|
||||||
|
// 特殊处理:originalParentId=0的情况已经在主方法中处理过了,这里不应该再处理
|
||||||
|
if (originalParentId == 0) {
|
||||||
|
System.out.println(" 跳过originalParentId=0的处理(已在主方法中处理)");
|
||||||
|
System.out.println("<<< 退出createChildMenus方法,处理originalParentId=" + originalParentId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<MenuImportParam> childMenus = menuGroups.get(originalParentId);
|
||||||
|
if (childMenus == null || childMenus.isEmpty()) {
|
||||||
|
System.out.println(" 没有找到originalParentId=" + originalParentId + "的子菜单");
|
||||||
|
System.out.println("<<< 退出createChildMenus方法,处理originalParentId=" + originalParentId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取新的父级菜单对象
|
||||||
|
Menu parentMenu = tempIdMapping.get(originalParentId);
|
||||||
|
if (parentMenu == null) {
|
||||||
|
System.out.println(" 未找到原始ID为" + originalParentId + "的父级菜单,跳过处理");
|
||||||
|
System.out.println("<<< 退出createChildMenus方法,处理originalParentId=" + originalParentId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer newParentId = parentMenu.getMenuId();
|
||||||
|
|
||||||
|
System.out.println(" 创建父级ID为" + originalParentId + "(新ID:" + newParentId + ")的子菜单,共" + childMenus.size() + "个");
|
||||||
|
|
||||||
|
// 创建所有子菜单
|
||||||
|
for (int i = 0; i < childMenus.size(); i++) {
|
||||||
|
MenuImportParam param = childMenus.get(i);
|
||||||
|
System.out.println(" 处理第" + (i+1) + "个子菜单,原始ID: " + param.getMenuId() + ", 原始ParentId: " + param.getParentId());
|
||||||
|
|
||||||
|
Menu menu = convertToMenu(param);
|
||||||
|
menu.setParentId(newParentId);
|
||||||
|
menuService.save(menu);
|
||||||
|
|
||||||
|
System.out.println(" 创建子菜单: " + menu.getTitle() + ", ID: " + menu.getMenuId() +
|
||||||
|
", 父级ID: " + menu.getParentId() + ", 原始ID: " + param.getMenuId());
|
||||||
|
|
||||||
|
// 记录原始ID到新菜单的映射关系
|
||||||
|
if (param.getMenuId() != null) {
|
||||||
|
tempIdMapping.put(param.getMenuId(), menu);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 递归创建当前菜单的子级菜单(使用原始ID作为下一个递归的父级ID)
|
||||||
|
System.out.println(" 递归调用createChildMenus,处理原始ID=" + param.getMenuId() + "的子菜单");
|
||||||
|
createChildMenus(menuGroups, tempIdMapping, param.getMenuId());
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("<<< 退出createChildMenus方法,处理originalParentId=" + originalParentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将MenuImportParam转换为Menu实体
|
||||||
|
* @param param MenuImportParam对象
|
||||||
|
* @return Menu实体
|
||||||
|
*/
|
||||||
|
private Menu convertToMenu(MenuImportParam param) {
|
||||||
|
Menu menu = new Menu();
|
||||||
|
menu.setParentId(param.getParentId());
|
||||||
|
menu.setTitle(param.getTitle());
|
||||||
|
menu.setPath(param.getPath());
|
||||||
|
menu.setComponent(param.getComponent());
|
||||||
|
menu.setModules(param.getModules());
|
||||||
|
menu.setModulesUrl(param.getModulesUrl());
|
||||||
|
menu.setMenuType(param.getMenuType());
|
||||||
|
menu.setSortNumber(param.getSortNumber() != null ? param.getSortNumber() : 0);
|
||||||
|
menu.setAuthority(param.getAuthority());
|
||||||
|
menu.setIcon(param.getIcon());
|
||||||
|
menu.setHide(param.getHide());
|
||||||
|
menu.setAppId(param.getAppId());
|
||||||
|
menu.setTenantId(param.getTenantId());
|
||||||
|
menu.setDeleted(0); // 新导入的数据deleted设为0
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为超级管理员配置导入菜单的权限
|
||||||
|
* @param importedMenus 导入的菜单列表
|
||||||
|
*/
|
||||||
|
private void configureSuperAdminPermissionsForImportedMenus(List<Menu> importedMenus) {
|
||||||
|
try {
|
||||||
|
// 1.查找当前租户的超管权限的roleId
|
||||||
|
final Role superAdmin = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, "superAdmin"));
|
||||||
|
if (superAdmin == null) {
|
||||||
|
System.out.println("未找到superAdmin角色");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final Integer roleId = superAdmin.getRoleId();
|
||||||
|
final Integer tenantId = superAdmin.getTenantId();
|
||||||
|
|
||||||
|
// 为所有导入的菜单配置权限
|
||||||
|
for (Menu menu : importedMenus) {
|
||||||
|
RoleMenu roleMenu = new RoleMenu();
|
||||||
|
roleMenu.setRoleId(roleId);
|
||||||
|
roleMenu.setMenuId(menu.getMenuId());
|
||||||
|
roleMenu.setTenantId(tenantId);
|
||||||
|
roleMenuService.save(roleMenu);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调整根菜单的排序(如果有根菜单的话)
|
||||||
|
for (Menu menu : importedMenus) {
|
||||||
|
if (menu.getParentId() == 0) {
|
||||||
|
menu.setSortNumber(0);
|
||||||
|
menuService.updateById(menu);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("为超级管理员配置菜单权限成功,共配置了" + importedMenus.size() + "个菜单");
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("为超级管理员配置菜单权限失败: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import com.alibaba.fastjson.JSONObject;
|
|||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.gxwebsoft.cms.entity.CmsWebsite;
|
||||||
|
import com.gxwebsoft.cms.service.CmsWebsiteService;
|
||||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||||
@@ -52,7 +54,7 @@ import static com.gxwebsoft.common.core.constants.RedisConstants.MP_WX_KEY;
|
|||||||
public class WxLoginController extends BaseController {
|
public class WxLoginController extends BaseController {
|
||||||
private final StringRedisTemplate redisTemplate;
|
private final StringRedisTemplate redisTemplate;
|
||||||
private final OkHttpClient http = new OkHttpClient();
|
private final OkHttpClient http = new OkHttpClient();
|
||||||
private final ObjectMapper om = new ObjectMapper();
|
private final ObjectMapper om;
|
||||||
private volatile long tokenExpireEpoch = 0L; // 过期的 epoch 秒
|
private volatile long tokenExpireEpoch = 0L; // 过期的 epoch 秒
|
||||||
@Resource
|
@Resource
|
||||||
private SettingService settingService;
|
private SettingService settingService;
|
||||||
@@ -74,10 +76,13 @@ public class WxLoginController extends BaseController {
|
|||||||
private ConfigProperties config;
|
private ConfigProperties config;
|
||||||
@Resource
|
@Resource
|
||||||
private UserRefereeService userRefereeService;
|
private UserRefereeService userRefereeService;
|
||||||
|
@Resource
|
||||||
|
private CmsWebsiteService cmsWebsiteService;
|
||||||
|
|
||||||
|
|
||||||
public WxLoginController(StringRedisTemplate redisTemplate) {
|
public WxLoginController(StringRedisTemplate redisTemplate, ObjectMapper objectMapper) {
|
||||||
this.redisTemplate = redisTemplate;
|
this.redisTemplate = redisTemplate;
|
||||||
|
this.om = objectMapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取微信AccessToken")
|
@Operation(summary = "获取微信AccessToken")
|
||||||
@@ -442,6 +447,13 @@ public class WxLoginController extends BaseController {
|
|||||||
map.put("page", "pages/index/index");
|
map.put("page", "pages/index/index");
|
||||||
map.put("env_version", "release");
|
map.put("env_version", "release");
|
||||||
|
|
||||||
|
// 判断应用运行状态
|
||||||
|
final CmsWebsite website = cmsWebsiteService.getByTenantId(tenantId);
|
||||||
|
if(website.getRunning().equals(2)){
|
||||||
|
map.put("check_path",false);
|
||||||
|
map.put("env_version","trial");
|
||||||
|
}
|
||||||
|
|
||||||
String jsonBody = JSON.toJSONString(map);
|
String jsonBody = JSON.toJSONString(map);
|
||||||
System.out.println("请求的 JSON body = " + jsonBody);
|
System.out.println("请求的 JSON body = " + jsonBody);
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
package com.gxwebsoft.common.system.entity;
|
package com.gxwebsoft.common.system.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.util.Date;
|
||||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +18,7 @@ import java.util.List;
|
|||||||
@Data
|
@Data
|
||||||
@Schema(description = "菜单")
|
@Schema(description = "菜单")
|
||||||
@TableName("sys_menu")
|
@TableName("sys_menu")
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
public class Menu implements GrantedAuthority {
|
public class Menu implements GrantedAuthority {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
public static final int TYPE_MENU = 0; // 菜单类型
|
public static final int TYPE_MENU = 0; // 菜单类型
|
||||||
@@ -40,9 +40,19 @@ public class Menu implements GrantedAuthority {
|
|||||||
@Schema(description = "菜单组件地址")
|
@Schema(description = "菜单组件地址")
|
||||||
private String component;
|
private String component;
|
||||||
|
|
||||||
|
@Schema(description = "模块ID")
|
||||||
|
private String modules;
|
||||||
|
|
||||||
|
@Schema(description = "模块API")
|
||||||
|
private String modulesUrl;
|
||||||
|
|
||||||
@Schema(description = "菜单类型, 0菜单, 1按钮")
|
@Schema(description = "菜单类型, 0菜单, 1按钮")
|
||||||
private Integer menuType;
|
private Integer menuType;
|
||||||
|
|
||||||
|
@Schema(description = "打开方式, 0当前页, 1新窗口")
|
||||||
|
@TableField(exist = false)
|
||||||
|
private Integer openType;
|
||||||
|
|
||||||
@Schema(description = "排序号")
|
@Schema(description = "排序号")
|
||||||
private Integer sortNumber;
|
private Integer sortNumber;
|
||||||
|
|
||||||
@@ -69,12 +79,10 @@ public class Menu implements GrantedAuthority {
|
|||||||
private Integer tenantId;
|
private Integer tenantId;
|
||||||
|
|
||||||
@Schema(description = "创建时间")
|
@Schema(description = "创建时间")
|
||||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
private Date createTime;
|
||||||
private LocalDateTime createTime;
|
|
||||||
|
|
||||||
@Schema(description = "修改时间")
|
@Schema(description = "修改时间")
|
||||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
private Date updateTime;
|
||||||
private LocalDateTime updateTime;
|
|
||||||
|
|
||||||
@Schema(description = "子菜单")
|
@Schema(description = "子菜单")
|
||||||
@TableField(exist = false)
|
@TableField(exist = false)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.gxwebsoft.common.system.mapper.UserRoleMapper">
|
<mapper namespace="com.gxwebsoft.common.system.mapper.UserRoleMapper">
|
||||||
|
|
||||||
<insert id="insertBatch">
|
<insert id="insertBatch">
|
||||||
INSERT INTO sys_user_role(user_id, role_id) VALUES
|
INSERT INTO gxwebsoft_core.sys_user_role(user_id, role_id) VALUES
|
||||||
<foreach collection="roleIds" item="roleId" separator=",">
|
<foreach collection="roleIds" item="roleId" separator=",">
|
||||||
(#{userId}, #{roleId})
|
(#{userId}, #{roleId})
|
||||||
</foreach>
|
</foreach>
|
||||||
@@ -11,10 +11,10 @@
|
|||||||
|
|
||||||
<select id="selectByUserId" resultType="com.gxwebsoft.common.system.entity.Role">
|
<select id="selectByUserId" resultType="com.gxwebsoft.common.system.entity.Role">
|
||||||
SELECT *
|
SELECT *
|
||||||
FROM sys_role
|
FROM gxwebsoft_core.sys_role
|
||||||
WHERE role_id IN (
|
WHERE role_id IN (
|
||||||
SELECT role_id
|
SELECT role_id
|
||||||
FROM sys_user_role
|
FROM gxwebsoft_core.sys_user_role
|
||||||
WHERE user_id = #{userId}
|
WHERE user_id = #{userId}
|
||||||
)
|
)
|
||||||
AND deleted = 0
|
AND deleted = 0
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<select id="selectByUserIds" resultType="com.gxwebsoft.common.system.entity.Role">
|
<select id="selectByUserIds" resultType="com.gxwebsoft.common.system.entity.Role">
|
||||||
SELECT a.user_id, b.*
|
SELECT a.user_id, b.*
|
||||||
FROM sys_user_role a
|
FROM gxwebsoft_core.sys_user_role a
|
||||||
LEFT JOIN gxwebsoft_core.sys_role b ON a.role_id = b.role_id
|
LEFT JOIN gxwebsoft_core.sys_role b ON a.role_id = b.role_id
|
||||||
WHERE a.user_id IN
|
WHERE a.user_id IN
|
||||||
<foreach collection="userIds" open="(" close=")" separator="," item="userId">
|
<foreach collection="userIds" open="(" close=")" separator="," item="userId">
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.gxwebsoft.common.system.param;
|
||||||
|
|
||||||
|
import cn.afterturn.easypoi.excel.annotation.Excel;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 菜单导入参数
|
||||||
|
*
|
||||||
|
* @author WebSoft
|
||||||
|
* @since 2025-09-30
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class MenuImportParam implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Excel(name = "菜单ID")
|
||||||
|
private Integer menuId;
|
||||||
|
|
||||||
|
@Excel(name = "父级ID")
|
||||||
|
private Integer parentId;
|
||||||
|
|
||||||
|
@Excel(name = "菜单名称")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Excel(name = "路由地址")
|
||||||
|
private String path;
|
||||||
|
|
||||||
|
@Excel(name = "组件路径")
|
||||||
|
private String component;
|
||||||
|
|
||||||
|
@Excel(name = "模块ID")
|
||||||
|
private String modules;
|
||||||
|
|
||||||
|
@Excel(name = "模块API")
|
||||||
|
private String modulesUrl;
|
||||||
|
|
||||||
|
@Excel(name = "菜单类型")
|
||||||
|
private Integer menuType;
|
||||||
|
|
||||||
|
@Excel(name = "排序号")
|
||||||
|
private Integer sortNumber;
|
||||||
|
|
||||||
|
@Excel(name = "权限标识")
|
||||||
|
private String authority;
|
||||||
|
|
||||||
|
@Excel(name = "图标")
|
||||||
|
private String icon;
|
||||||
|
|
||||||
|
@Excel(name = "是否隐藏")
|
||||||
|
private Integer hide;
|
||||||
|
|
||||||
|
@Excel(name = "关联应用")
|
||||||
|
private Integer appId;
|
||||||
|
|
||||||
|
@Excel(name = "租户id")
|
||||||
|
private Integer tenantId;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
package com.gxwebsoft.common.system.param;
|
package com.gxwebsoft.common.system.param;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||||
import com.gxwebsoft.common.core.web.BaseParam;
|
import com.gxwebsoft.common.core.web.BaseParam;
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
@@ -40,10 +40,17 @@ public class MenuParam extends BaseParam {
|
|||||||
@Schema(description = "菜单组件地址")
|
@Schema(description = "菜单组件地址")
|
||||||
private String component;
|
private String component;
|
||||||
|
|
||||||
|
@Schema(description = "模块ID")
|
||||||
|
private String modules;
|
||||||
|
|
||||||
@Schema(description = "菜单类型, 0菜单, 1按钮")
|
@Schema(description = "菜单类型, 0菜单, 1按钮")
|
||||||
@QueryField(type = QueryType.EQ)
|
@QueryField(type = QueryType.EQ)
|
||||||
private Integer menuType;
|
private Integer menuType;
|
||||||
|
|
||||||
|
@Schema(description = "打开方式, 0当前页, 1新窗口")
|
||||||
|
@TableField(exist = false)
|
||||||
|
private Integer openType;
|
||||||
|
|
||||||
@Schema(description = "权限标识")
|
@Schema(description = "权限标识")
|
||||||
private String authority;
|
private String authority;
|
||||||
|
|
||||||
@@ -65,4 +72,12 @@ public class MenuParam extends BaseParam {
|
|||||||
@QueryField(type = QueryType.EQ)
|
@QueryField(type = QueryType.EQ)
|
||||||
private Integer tenantId;
|
private Integer tenantId;
|
||||||
|
|
||||||
|
@Schema(description = "企业ID")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer companyId;
|
||||||
|
|
||||||
|
@Schema(description = "租户名称")
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String tenantName;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.gxwebsoft.common.system.param;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||||
|
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||||
|
import com.gxwebsoft.common.core.web.BaseParam;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本更新查询参数
|
||||||
|
*
|
||||||
|
* @author 科技小王子
|
||||||
|
* @since 2024-01-15 18:52:24
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
@Schema(name = "VersionParam对象", description = "版本更新查询参数")
|
||||||
|
public class VersionParam extends BaseParam {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Schema(description = "ID")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Schema(description = "版本名")
|
||||||
|
private String versionName;
|
||||||
|
|
||||||
|
@Schema(description = "版本号")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer versionCode;
|
||||||
|
|
||||||
|
@Schema(description = "下载链接")
|
||||||
|
private String androidDownloadUrl;
|
||||||
|
|
||||||
|
@Schema(description = "下载链接")
|
||||||
|
private String iosDownloadUrl;
|
||||||
|
|
||||||
|
@Schema(description = "更新日志")
|
||||||
|
private String updateInfo;
|
||||||
|
|
||||||
|
@Schema(description = "强制更新")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer isHard;
|
||||||
|
|
||||||
|
@Schema(description = "热更")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer isHot;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String comments;
|
||||||
|
|
||||||
|
@Schema(description = "文章排序(数字越小越靠前)")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer sortNumber;
|
||||||
|
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer userId;
|
||||||
|
|
||||||
|
@Schema(description = "状态, 0正常, 1冻结")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Schema(description = "是否删除, 0否, 1是")
|
||||||
|
@QueryField(type = QueryType.EQ)
|
||||||
|
private Integer deleted;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.gxwebsoft.common.system.service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信小程序 access_token 获取服务(按租户)。
|
||||||
|
*
|
||||||
|
* <p>用于调用微信小程序开放接口(例如:上传发货信息)。</p>
|
||||||
|
*/
|
||||||
|
public interface WxMiniappAccessTokenService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取指定租户的小程序 access_token(内部带缓存)。
|
||||||
|
*
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return access_token
|
||||||
|
*/
|
||||||
|
String getAccessToken(Integer tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package com.gxwebsoft.common.system.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import cn.hutool.http.HttpUtil;
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||||
|
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||||
|
import com.gxwebsoft.common.system.service.WxMiniappAccessTokenService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static com.gxwebsoft.common.core.constants.RedisConstants.ACCESS_TOKEN_KEY;
|
||||||
|
import static com.gxwebsoft.common.core.constants.RedisConstants.MP_WX_KEY;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信小程序 access_token 获取实现(按租户)。
|
||||||
|
*
|
||||||
|
* <p>复用现有缓存结构:
|
||||||
|
* <ul>
|
||||||
|
* <li>小程序配置:Redis key = {@code mp-weixin:{tenantId}},value 为 JSON,包含 appId/appSecret</li>
|
||||||
|
* <li>access_token:Redis key = {@code access-token:{tenantId}},value 为微信返回的 JSON 字符串</li>
|
||||||
|
* </ul>
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class WxMiniappAccessTokenServiceImpl implements WxMiniappAccessTokenService {
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private RedisUtil redisUtil;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAccessToken(Integer tenantId) {
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw new BusinessException("tenantId 不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
final String tokenCacheKey = ACCESS_TOKEN_KEY + ":" + tenantId;
|
||||||
|
|
||||||
|
// 1) 优先从缓存取(兼容 JSON 或纯字符串 token 的历史格式)
|
||||||
|
String cachedValue = redisUtil.get(tokenCacheKey);
|
||||||
|
if (StrUtil.isNotBlank(cachedValue)) {
|
||||||
|
try {
|
||||||
|
JSONObject cachedJson = JSON.parseObject(cachedValue);
|
||||||
|
String accessToken = cachedJson.getString("access_token");
|
||||||
|
if (StrUtil.isNotBlank(accessToken)) {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
} catch (Exception ignore) {
|
||||||
|
// 旧格式:直接存 token
|
||||||
|
return cachedValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 缓存没有则从租户配置获取 appId/appSecret
|
||||||
|
final String wxConfigKey = MP_WX_KEY + tenantId;
|
||||||
|
final String wxConfigValue = redisUtil.get(wxConfigKey);
|
||||||
|
if (StrUtil.isBlank(wxConfigValue)) {
|
||||||
|
throw new BusinessException("未找到微信小程序配置,请检查缓存key: " + wxConfigKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
JSONObject wxConfig;
|
||||||
|
try {
|
||||||
|
wxConfig = JSON.parseObject(wxConfigValue);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new BusinessException("微信小程序配置格式错误: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
final String appId = wxConfig.getString("appId");
|
||||||
|
final String appSecret = wxConfig.getString("appSecret");
|
||||||
|
if (StrUtil.isBlank(appId) || StrUtil.isBlank(appSecret)) {
|
||||||
|
throw new BusinessException("微信小程序配置不完整(appId/appSecret)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) 调用微信接口获取 token
|
||||||
|
final String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
|
||||||
|
+ "&appid=" + appId + "&secret=" + appSecret;
|
||||||
|
String result = HttpUtil.get(apiUrl);
|
||||||
|
|
||||||
|
JSONObject json = JSON.parseObject(result);
|
||||||
|
if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
|
||||||
|
Integer errcode = json.getInteger("errcode");
|
||||||
|
String errmsg = json.getString("errmsg");
|
||||||
|
throw new BusinessException("获取小程序access_token失败: " + errmsg + " (errcode: " + errcode + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
String accessToken = json.getString("access_token");
|
||||||
|
Integer expiresIn = json.getInteger("expires_in");
|
||||||
|
if (StrUtil.isBlank(accessToken)) {
|
||||||
|
throw new BusinessException("获取小程序access_token失败: access_token为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) 缓存微信原始 JSON(与现有实现保持一致),提前5分钟过期
|
||||||
|
long ttlSeconds = 7000L;
|
||||||
|
if (expiresIn != null && expiresIn > 300) {
|
||||||
|
ttlSeconds = expiresIn - 300L;
|
||||||
|
}
|
||||||
|
redisUtil.set(tokenCacheKey, result, ttlSeconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
log.info("获取小程序access_token成功 - tenantId={}, ttlSeconds={}", tenantId, ttlSeconds);
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditAdministrativeLicense;
|
import com.gxwebsoft.credit.entity.CreditAdministrativeLicense;
|
||||||
import com.gxwebsoft.credit.param.CreditAdministrativeLicenseImportParam;
|
import com.gxwebsoft.credit.param.CreditAdministrativeLicenseImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditAdministrativeLicenseParam;
|
import com.gxwebsoft.credit.param.CreditAdministrativeLicenseParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditAdministrativeLicenseService;
|
import com.gxwebsoft.credit.service.CreditAdministrativeLicenseService;
|
||||||
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;
|
||||||
@@ -22,8 +25,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 行政许可控制器
|
* 行政许可控制器
|
||||||
@@ -41,6 +46,12 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询行政许可")
|
@Operation(summary = "分页查询行政许可")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditAdministrativeLicense>> page(CreditAdministrativeLicenseParam param) {
|
public ApiResult<PageResult<CreditAdministrativeLicense>> page(CreditAdministrativeLicenseParam param) {
|
||||||
@@ -94,7 +105,7 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
@Operation(summary = "删除行政许可")
|
@Operation(summary = "删除行政许可")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditAdministrativeLicenseService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditAdministrativeLicense.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -127,12 +138,52 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
@Operation(summary = "批量删除行政许可")
|
@Operation(summary = "批量删除行政许可")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditAdministrativeLicenseService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditAdministrativeLicense.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditAdministrativeLicense:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditAdministrativeLicenseService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditAdministrativeLicense::getId,
|
||||||
|
CreditAdministrativeLicense::setId,
|
||||||
|
CreditAdministrativeLicense::getName,
|
||||||
|
CreditAdministrativeLicense::getCompanyId,
|
||||||
|
CreditAdministrativeLicense::setCompanyId,
|
||||||
|
CreditAdministrativeLicense::setCompanyName,
|
||||||
|
CreditAdministrativeLicense::getHasData,
|
||||||
|
CreditAdministrativeLicense::setHasData,
|
||||||
|
CreditAdministrativeLicense::getTenantId,
|
||||||
|
CreditAdministrativeLicense::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入行政许可
|
* 批量导入行政许可
|
||||||
*/
|
*/
|
||||||
@@ -143,6 +194,7 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditAdministrativeLicenseImportParam> importResult = ExcelImportSupport.readAnySheet(
|
ExcelImportSupport.ImportResult<CreditAdministrativeLicenseImportParam> importResult = ExcelImportSupport.readAnySheet(
|
||||||
@@ -161,6 +213,11 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
Map<String, String> urlByCode = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可编号");
|
Map<String, String> urlByCode = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可编号");
|
||||||
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可证名称");
|
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可证名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -184,6 +241,12 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -207,51 +270,20 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertByCodeOrName(
|
|
||||||
creditAdministrativeLicenseService,
|
creditAdministrativeLicenseService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditAdministrativeLicense::getId,
|
chunkRowNumbers,
|
||||||
CreditAdministrativeLicense::setId,
|
mpBatchSize,
|
||||||
CreditAdministrativeLicense::getCode,
|
|
||||||
CreditAdministrativeLicense::getCode,
|
|
||||||
CreditAdministrativeLicense::getName,
|
CreditAdministrativeLicense::getName,
|
||||||
CreditAdministrativeLicense::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditAdministrativeLicenseService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditAdministrativeLicense existing = null;
|
|
||||||
if (!ImportHelper.isBlank(rowItem.getCode())) {
|
|
||||||
existing = creditAdministrativeLicenseService.lambdaQuery()
|
|
||||||
.eq(CreditAdministrativeLicense::getCode, rowItem.getCode())
|
|
||||||
.one();
|
|
||||||
}
|
|
||||||
if (existing == null) {
|
|
||||||
existing = creditAdministrativeLicenseService.lambdaQuery()
|
|
||||||
.eq(CreditAdministrativeLicense::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
}
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditAdministrativeLicenseService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -265,52 +297,19 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertByCodeOrName(
|
|
||||||
creditAdministrativeLicenseService,
|
creditAdministrativeLicenseService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditAdministrativeLicense::getId,
|
chunkRowNumbers,
|
||||||
CreditAdministrativeLicense::setId,
|
mpBatchSize,
|
||||||
CreditAdministrativeLicense::getCode,
|
|
||||||
CreditAdministrativeLicense::getCode,
|
|
||||||
CreditAdministrativeLicense::getName,
|
CreditAdministrativeLicense::getName,
|
||||||
CreditAdministrativeLicense::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditAdministrativeLicenseService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditAdministrativeLicense existing = null;
|
|
||||||
if (!ImportHelper.isBlank(rowItem.getCode())) {
|
|
||||||
existing = creditAdministrativeLicenseService.lambdaQuery()
|
|
||||||
.eq(CreditAdministrativeLicense::getCode, rowItem.getCode())
|
|
||||||
.one();
|
|
||||||
}
|
|
||||||
if (existing == null) {
|
|
||||||
existing = creditAdministrativeLicenseService.lambdaQuery()
|
|
||||||
.eq(CreditAdministrativeLicense::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
}
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditAdministrativeLicenseService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.ADMINISTRATIVE_LICENSE, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -322,6 +321,153 @@ public class CreditAdministrativeLicenseController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史行政许可(仅解析“历史行政许可”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditAdministrativeLicense:save')")
|
||||||
|
@Operation(summary = "批量导入历史行政许可")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史行政许可");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史行政许可”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditAdministrativeLicenseImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditAdministrativeLicenseImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditAdministrativeLicenseImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCode = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可编号");
|
||||||
|
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "决定文书/许可证名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditAdministrativeLicense> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditAdministrativeLicenseImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditAdministrativeLicense item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCode() != null) {
|
||||||
|
item.setCode(item.getCode().trim());
|
||||||
|
}
|
||||||
|
if (item.getName() != null) {
|
||||||
|
item.setName(item.getName().trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ImportHelper.isBlank(item.getName())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:决定文书/许可证名称不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = null;
|
||||||
|
if (!ImportHelper.isBlank(item.getCode())) {
|
||||||
|
link = urlByCode.get(item.getCode());
|
||||||
|
}
|
||||||
|
if ((link == null || link.isEmpty()) && !ImportHelper.isBlank(item.getName())) {
|
||||||
|
link = urlByName.get(item.getName());
|
||||||
|
}
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditAdministrativeLicenseService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditAdministrativeLicense::getName,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditAdministrativeLicenseService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditAdministrativeLicense::getName,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.ADMINISTRATIVE_LICENSE, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载行政许可导入模板
|
* 下载行政许可导入模板
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import com.gxwebsoft.common.system.entity.User;
|
|||||||
import com.gxwebsoft.credit.entity.CreditBankruptcy;
|
import com.gxwebsoft.credit.entity.CreditBankruptcy;
|
||||||
import com.gxwebsoft.credit.param.CreditBankruptcyImportParam;
|
import com.gxwebsoft.credit.param.CreditBankruptcyImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditBankruptcyParam;
|
import com.gxwebsoft.credit.param.CreditBankruptcyParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditBankruptcyService;
|
import com.gxwebsoft.credit.service.CreditBankruptcyService;
|
||||||
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;
|
||||||
@@ -22,8 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 破产重整控制器
|
* 破产重整控制器
|
||||||
@@ -41,6 +45,12 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询破产重整")
|
@Operation(summary = "分页查询破产重整")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditBankruptcy>> page(CreditBankruptcyParam param) {
|
public ApiResult<PageResult<CreditBankruptcy>> page(CreditBankruptcyParam param) {
|
||||||
@@ -94,7 +104,7 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
@Operation(summary = "删除破产重整")
|
@Operation(summary = "删除破产重整")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditBankruptcyService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditBankruptcy.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -127,12 +137,51 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
@Operation(summary = "批量删除破产重整")
|
@Operation(summary = "批量删除破产重整")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditBankruptcyService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditBankruptcy.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditBankruptcy:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditBankruptcyService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditBankruptcy::getId,
|
||||||
|
CreditBankruptcy::setId,
|
||||||
|
CreditBankruptcy::getParty,
|
||||||
|
CreditBankruptcy::getCompanyId,
|
||||||
|
CreditBankruptcy::setCompanyId,
|
||||||
|
CreditBankruptcy::getHasData,
|
||||||
|
CreditBankruptcy::setHasData,
|
||||||
|
CreditBankruptcy::getTenantId,
|
||||||
|
CreditBankruptcy::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入破产重整
|
* 批量导入破产重整
|
||||||
*/
|
*/
|
||||||
@@ -143,10 +192,19 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditBankruptcyImportParam> importResult = ExcelImportSupport.readAnySheet(
|
// Prefer importing from the explicit tab name "破产重整" when present.
|
||||||
file, CreditBankruptcyImportParam.class, this::isEmptyImportRow);
|
// This avoids accidentally importing from other sheets (e.g. "历史破产重整") in multi-sheet workbooks.
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "破产重整");
|
||||||
|
ExcelImportSupport.ImportResult<CreditBankruptcyImportParam> importResult;
|
||||||
|
if (sheetIndex >= 0) {
|
||||||
|
importResult = ExcelImportSupport.read(file, CreditBankruptcyImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
} else {
|
||||||
|
// Backward compatible: try any sheet for older templates without the expected tab name.
|
||||||
|
importResult = ExcelImportSupport.readAnySheet(file, CreditBankruptcyImportParam.class, this::isEmptyImportRow);
|
||||||
|
}
|
||||||
List<CreditBankruptcyImportParam> list = importResult.getData();
|
List<CreditBankruptcyImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
@@ -180,6 +238,9 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -202,41 +263,20 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBankruptcyService,
|
creditBankruptcyService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBankruptcy::getId,
|
chunkRowNumbers,
|
||||||
CreditBankruptcy::setId,
|
mpBatchSize,
|
||||||
CreditBankruptcy::getCode,
|
CreditBankruptcy::getCode,
|
||||||
CreditBankruptcy::getCode,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBankruptcyService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBankruptcy existing = creditBankruptcyService.lambdaQuery()
|
|
||||||
.eq(CreditBankruptcy::getCode, rowItem.getCode())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBankruptcyService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -250,42 +290,19 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBankruptcyService,
|
creditBankruptcyService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBankruptcy::getId,
|
chunkRowNumbers,
|
||||||
CreditBankruptcy::setId,
|
mpBatchSize,
|
||||||
CreditBankruptcy::getCode,
|
CreditBankruptcy::getCode,
|
||||||
CreditBankruptcy::getCode,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBankruptcyService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBankruptcy existing = creditBankruptcyService.lambdaQuery()
|
|
||||||
.eq(CreditBankruptcy::getCode, rowItem.getCode())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBankruptcyService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.BANKRUPTCY, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -297,6 +314,132 @@ public class CreditBankruptcyController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史破产重整(仅解析“历史破产重整”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditBankruptcy:save')")
|
||||||
|
@Operation(summary = "批量导入历史破产重整")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史破产重整");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史破产重整”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditBankruptcyImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditBankruptcyImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditBankruptcyImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCode = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditBankruptcy> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditBankruptcyImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditBankruptcy item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCode() != null) {
|
||||||
|
item.setCode(item.getCode().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCode())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCode.get(item.getCode());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditBankruptcyService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditBankruptcy::getCode,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditBankruptcyService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditBankruptcy::getCode,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.BANKRUPTCY, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载破产重整导入模板
|
* 下载破产重整导入模板
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditBranch;
|
import com.gxwebsoft.credit.entity.CreditBranch;
|
||||||
import com.gxwebsoft.credit.param.CreditBranchImportParam;
|
import com.gxwebsoft.credit.param.CreditBranchImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditBranchParam;
|
import com.gxwebsoft.credit.param.CreditBranchParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditBranchService;
|
import com.gxwebsoft.credit.service.CreditBranchService;
|
||||||
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;
|
||||||
@@ -22,8 +25,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 分支机构控制器
|
* 分支机构控制器
|
||||||
@@ -41,6 +46,12 @@ public class CreditBranchController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询分支机构")
|
@Operation(summary = "分页查询分支机构")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditBranch>> page(CreditBranchParam param) {
|
public ApiResult<PageResult<CreditBranch>> page(CreditBranchParam param) {
|
||||||
@@ -94,7 +105,7 @@ public class CreditBranchController extends BaseController {
|
|||||||
@Operation(summary = "删除分支机构")
|
@Operation(summary = "删除分支机构")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditBranchService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditBranch.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -127,12 +138,52 @@ public class CreditBranchController extends BaseController {
|
|||||||
@Operation(summary = "批量删除分支机构")
|
@Operation(summary = "批量删除分支机构")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditBranchService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditBranch.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditBranch:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditBranchService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditBranch::getId,
|
||||||
|
CreditBranch::setId,
|
||||||
|
CreditBranch::getName,
|
||||||
|
CreditBranch::getCompanyId,
|
||||||
|
CreditBranch::setCompanyId,
|
||||||
|
CreditBranch::setCompanyName,
|
||||||
|
CreditBranch::getHasData,
|
||||||
|
CreditBranch::setHasData,
|
||||||
|
CreditBranch::getTenantId,
|
||||||
|
CreditBranch::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入分支机构
|
* 批量导入分支机构
|
||||||
*/
|
*/
|
||||||
@@ -143,6 +194,7 @@ public class CreditBranchController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditBranchImportParam> importResult = ExcelImportSupport.readAnySheet(
|
ExcelImportSupport.ImportResult<CreditBranchImportParam> importResult = ExcelImportSupport.readAnySheet(
|
||||||
@@ -160,6 +212,11 @@ public class CreditBranchController extends BaseController {
|
|||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "分支机构名称");
|
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "分支机构名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -179,6 +236,9 @@ public class CreditBranchController extends BaseController {
|
|||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -202,41 +262,20 @@ public class CreditBranchController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBranchService,
|
creditBranchService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBranch::getId,
|
chunkRowNumbers,
|
||||||
CreditBranch::setId,
|
mpBatchSize,
|
||||||
CreditBranch::getName,
|
CreditBranch::getName,
|
||||||
CreditBranch::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBranchService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBranch existing = creditBranchService.lambdaQuery()
|
|
||||||
.eq(CreditBranch::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBranchService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -250,42 +289,19 @@ public class CreditBranchController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBranchService,
|
creditBranchService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBranch::getId,
|
chunkRowNumbers,
|
||||||
CreditBranch::setId,
|
mpBatchSize,
|
||||||
CreditBranch::getName,
|
CreditBranch::getName,
|
||||||
CreditBranch::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBranchService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBranch existing = creditBranchService.lambdaQuery()
|
|
||||||
.eq(CreditBranch::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBranchService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.BRANCH, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditBreachOfTrust;
|
import com.gxwebsoft.credit.entity.CreditBreachOfTrust;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.param.CreditBreachOfTrustImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditBreachOfTrustParam;
|
import com.gxwebsoft.credit.param.CreditBreachOfTrustParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditBreachOfTrustService;
|
import com.gxwebsoft.credit.service.CreditBreachOfTrustService;
|
||||||
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;
|
||||||
@@ -21,9 +23,11 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 失信被执行人控制器
|
* 失信被执行人控制器
|
||||||
@@ -41,6 +45,12 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询失信被执行人")
|
@Operation(summary = "分页查询失信被执行人")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditBreachOfTrust>> page(CreditBreachOfTrustParam param) {
|
public ApiResult<PageResult<CreditBreachOfTrust>> page(CreditBreachOfTrustParam param) {
|
||||||
@@ -89,7 +99,7 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
@Operation(summary = "删除失信被执行人")
|
@Operation(summary = "删除失信被执行人")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditBreachOfTrustService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditBreachOfTrust.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -122,12 +132,55 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
@Operation(summary = "批量删除失信被执行人")
|
@Operation(summary = "批量删除失信被执行人")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditBreachOfTrustService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditBreachOfTrust.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditBreachOfTrust:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditBreachOfTrustService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditBreachOfTrust::getId,
|
||||||
|
CreditBreachOfTrust::setId,
|
||||||
|
CreditBreachOfTrust::getCompanyId,
|
||||||
|
CreditBreachOfTrust::setCompanyId,
|
||||||
|
CreditBreachOfTrust::getHasData,
|
||||||
|
CreditBreachOfTrust::setHasData,
|
||||||
|
CreditBreachOfTrust::getTenantId,
|
||||||
|
CreditBreachOfTrust::new,
|
||||||
|
CreditBreachOfTrust::getPlaintiffAppellant,
|
||||||
|
CreditBreachOfTrust::getAppellee,
|
||||||
|
CreditBreachOfTrust::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入失信被执行人
|
* 批量导入失信被执行人
|
||||||
*/
|
*/
|
||||||
@@ -138,14 +191,16 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "失信被执行人", 0);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "失信被执行人", 0);
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
ExcelImportSupport.ImportResult<CreditBreachOfTrustImportParam> importResult = ExcelImportSupport.read(
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow, sheetIndex);
|
file, CreditBreachOfTrustImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
List<CreditBreachOfTrustImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -154,6 +209,7 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -161,13 +217,22 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditBreachOfTrustImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditBreachOfTrust item = convertImportParamToEntity(param);
|
CreditBreachOfTrust item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -190,41 +255,20 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBreachOfTrustService,
|
creditBreachOfTrustService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBreachOfTrust::getId,
|
chunkRowNumbers,
|
||||||
CreditBreachOfTrust::setId,
|
mpBatchSize,
|
||||||
CreditBreachOfTrust::getCaseNumber,
|
CreditBreachOfTrust::getCaseNumber,
|
||||||
CreditBreachOfTrust::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBreachOfTrustService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBreachOfTrust existing = creditBreachOfTrustService.lambdaQuery()
|
|
||||||
.eq(CreditBreachOfTrust::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBreachOfTrustService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -238,42 +282,19 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditBreachOfTrustService,
|
creditBreachOfTrustService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditBreachOfTrust::getId,
|
chunkRowNumbers,
|
||||||
CreditBreachOfTrust::setId,
|
mpBatchSize,
|
||||||
CreditBreachOfTrust::getCaseNumber,
|
CreditBreachOfTrust::getCaseNumber,
|
||||||
CreditBreachOfTrust::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditBreachOfTrustService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditBreachOfTrust existing = creditBreachOfTrustService.lambdaQuery()
|
|
||||||
.eq(CreditBreachOfTrust::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditBreachOfTrustService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.BREACH_OF_TRUST, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -285,29 +306,157 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史失信被执行人(仅解析“历史失信被执行人”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditBreachOfTrust:save')")
|
||||||
|
@Operation(summary = "批量导入历史失信被执行人")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史失信被执行人");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史失信被执行人”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditBreachOfTrustImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditBreachOfTrustImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditBreachOfTrustImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
// 同案号多条:以导入文件中“最后一条”为准(视为最新)
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditBreachOfTrust> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditBreachOfTrustImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditBreachOfTrust item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditBreachOfTrustService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditBreachOfTrust::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditBreachOfTrustService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditBreachOfTrust::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.BREACH_OF_TRUST, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载失信被执行人导入模板
|
* 下载失信被执行人导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载失信被执行人导入模板")
|
@Operation(summary = "下载失信被执行人导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditBreachOfTrustImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditBreachOfTrustImportParam example = new CreditBreachOfTrustImportParam();
|
||||||
example.setDataType("失信被执行人");
|
example.setDataType("失信被执行人");
|
||||||
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
example.setOtherPartiesThirdParty("第三人示例");
|
||||||
|
example.setInvolvedAmount("20,293.91");
|
||||||
|
example.setDataStatus("正常");
|
||||||
example.setOccurrenceTime("2024-01-01");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
example.setCaseNumber("(2024)示例案号");
|
|
||||||
example.setCauseOfAction("案由示例");
|
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setReleaseDate("2024-01-01");
|
||||||
example.setComments("备注信息");
|
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("失信被执行人导入模板", "失信被执行人", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("失信被执行人导入模板", "失信被执行人", CreditBreachOfTrustImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_breach_of_trust_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_breach_of_trust_import_template.xlsx");
|
||||||
@@ -316,29 +465,46 @@ public class CreditBreachOfTrustController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditBreachOfTrustImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
||||||
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant2())
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
&& ImportHelper.isBlank(param.getAppellee())
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
&& ImportHelper.isBlank(param.getAppellee2());
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditBreachOfTrust convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditBreachOfTrust convertImportParamToEntity(CreditBreachOfTrustImportParam param) {
|
||||||
CreditBreachOfTrust entity = new CreditBreachOfTrust();
|
CreditBreachOfTrust entity = new CreditBreachOfTrust();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
entity.setDataType(param.getDataType());
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
|
||||||
entity.setAppellee(param.getAppellee());
|
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
String plaintiffAppellant = !ImportHelper.isBlank(param.getPlaintiffAppellant2())
|
||||||
entity.setCourtName(param.getCourtName());
|
? param.getPlaintiffAppellant2()
|
||||||
|
: param.getPlaintiffAppellant();
|
||||||
|
entity.setPlaintiffAppellant(plaintiffAppellant);
|
||||||
|
|
||||||
|
String appellee = !ImportHelper.isBlank(param.getAppellee2())
|
||||||
|
? param.getAppellee2()
|
||||||
|
: param.getAppellee();
|
||||||
|
entity.setAppellee(appellee);
|
||||||
|
|
||||||
|
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
|
|
||||||
|
entity.setInvolvedAmount(!ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount());
|
||||||
|
entity.setOccurrenceTime(!ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime());
|
||||||
|
entity.setCourtName(!ImportHelper.isBlank(param.getCourtName2())
|
||||||
|
? param.getCourtName2()
|
||||||
|
: param.getCourtName());
|
||||||
|
entity.setReleaseDate(param.getReleaseDate());
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditCaseFiling;
|
import com.gxwebsoft.credit.entity.CreditCaseFiling;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.param.CreditCaseFilingImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCaseFilingParam;
|
import com.gxwebsoft.credit.param.CreditCaseFilingParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditCaseFilingService;
|
import com.gxwebsoft.credit.service.CreditCaseFilingService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 司法大数据控制器
|
* 司法大数据控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询司法大数据")
|
@Operation(summary = "分页查询司法大数据")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCaseFiling>> page(CreditCaseFilingParam param) {
|
public ApiResult<PageResult<CreditCaseFiling>> page(CreditCaseFilingParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
@Operation(summary = "删除司法大数据")
|
@Operation(summary = "删除司法大数据")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCaseFilingService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCaseFiling.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,29 +137,75 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
@Operation(summary = "批量删除司法大数据")
|
@Operation(summary = "批量删除司法大数据")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCaseFilingService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCaseFiling.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入司法大数据
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCaseFiling:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Special: party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditCaseFilingService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditCaseFiling::getId,
|
||||||
|
CreditCaseFiling::setId,
|
||||||
|
CreditCaseFiling::getCompanyId,
|
||||||
|
CreditCaseFiling::setCompanyId,
|
||||||
|
CreditCaseFiling::getHasData,
|
||||||
|
CreditCaseFiling::setHasData,
|
||||||
|
CreditCaseFiling::getTenantId,
|
||||||
|
CreditCaseFiling::new,
|
||||||
|
CreditCaseFiling::getPlaintiffAppellant,
|
||||||
|
CreditCaseFiling::getAppellee,
|
||||||
|
CreditCaseFiling::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入立案信息
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("hasAuthority('credit:creditCaseFiling:save')")
|
@PreAuthorize("hasAuthority('credit:creditCaseFiling:save')")
|
||||||
@Operation(summary = "批量导入司法大数据")
|
@Operation(summary = "批量导入立案信息")
|
||||||
@PostMapping("/import")
|
@PostMapping("/import")
|
||||||
public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
|
public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
|
||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "立案信息", 0);
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
ExcelImportSupport.ImportResult<CreditCaseFilingImportParam> importResult = ExcelImportSupport.read(
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
file, CreditCaseFilingImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCaseFilingImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +214,8 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
// easypoi 默认不会读取单元格超链接地址;url 通常挂在“案号”列的超链接中,需要额外读取回填。
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,9 +223,15 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditCaseFilingImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditCaseFiling item = convertImportParamToEntity(param);
|
CreditCaseFiling item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (link != null && !link.isEmpty()) {
|
||||||
|
item.setUrl(link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
@@ -193,41 +258,20 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCaseFilingService,
|
creditCaseFilingService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCaseFiling::getId,
|
chunkRowNumbers,
|
||||||
CreditCaseFiling::setId,
|
mpBatchSize,
|
||||||
CreditCaseFiling::getCaseNumber,
|
CreditCaseFiling::getCaseNumber,
|
||||||
CreditCaseFiling::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCaseFilingService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCaseFiling existing = creditCaseFilingService.lambdaQuery()
|
|
||||||
.eq(CreditCaseFiling::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCaseFilingService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +285,19 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCaseFilingService,
|
creditCaseFilingService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCaseFiling::getId,
|
chunkRowNumbers,
|
||||||
CreditCaseFiling::setId,
|
mpBatchSize,
|
||||||
CreditCaseFiling::getCaseNumber,
|
CreditCaseFiling::getCaseNumber,
|
||||||
CreditCaseFiling::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCaseFilingService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCaseFiling existing = creditCaseFilingService.lambdaQuery()
|
|
||||||
.eq(CreditCaseFiling::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCaseFilingService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.CASE_FILING, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -289,28 +310,156 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载司法大数据导入模板
|
* 批量导入历史立案信息(仅解析“历史立案信息”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载司法大数据导入模板")
|
@PreAuthorize("hasAuthority('credit:creditCaseFiling:save')")
|
||||||
|
@Operation(summary = "批量导入历史立案信息")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史立案信息");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史立案信息”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditCaseFilingImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditCaseFilingImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCaseFilingImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditCaseFiling> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditCaseFilingImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditCaseFiling item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCaseFilingService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCaseFiling::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCaseFilingService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCaseFiling::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.CASE_FILING, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下载立案信息导入模板
|
||||||
|
*/
|
||||||
|
@Operation(summary = "下载立案信息导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditCaseFilingImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditCaseFilingImportParam example = new CreditCaseFilingImportParam();
|
||||||
example.setDataType("司法大数据");
|
example.setDataType("立案信息");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
example.setOtherPartiesThirdParty2("第三人示例");
|
||||||
example.setOccurrenceTime("2024-01-01");
|
example.setInvolvedAmount("100000");
|
||||||
|
example.setDataStatus("正常");
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setCauseOfAction("案由示例");
|
example.setCauseOfAction("案由示例");
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("司法大数据导入模板", "司法大数据", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("立案信息导入模板", "立案信息", CreditCaseFilingImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_case_filing_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_case_filing_import_template.xlsx");
|
||||||
@@ -319,29 +468,55 @@ public class CreditCaseFilingController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditCaseFilingImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
&& ImportHelper.isBlank(param.getAppellee())
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
&& ImportHelper.isBlank(param.getCauseOfAction())
|
||||||
|
&& ImportHelper.isBlank(param.getOtherPartiesThirdParty())
|
||||||
|
&& ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
|
&& ImportHelper.isBlank(param.getCourtName())
|
||||||
|
&& ImportHelper.isBlank(param.getCourtName2())
|
||||||
|
&& ImportHelper.isBlank(param.getOccurrenceTime())
|
||||||
|
&& ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
&& ImportHelper.isBlank(param.getInvolvedAmount())
|
||||||
|
&& ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
&& ImportHelper.isBlank(param.getDataStatus())
|
||||||
|
&& ImportHelper.isBlank(param.getDataType())
|
||||||
|
&& ImportHelper.isBlank(param.getComments());
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditCaseFiling convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditCaseFiling convertImportParamToEntity(CreditCaseFilingImportParam param) {
|
||||||
CreditCaseFiling entity = new CreditCaseFiling();
|
CreditCaseFiling entity = new CreditCaseFiling();
|
||||||
|
|
||||||
|
// Template compatibility: prefer new columns when present.
|
||||||
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime();
|
||||||
|
String otherPartiesThirdParty = !ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
|
? param.getOtherPartiesThirdParty2()
|
||||||
|
: param.getOtherPartiesThirdParty();
|
||||||
|
String courtName = !ImportHelper.isBlank(param.getCourtName2())
|
||||||
|
? param.getCourtName2()
|
||||||
|
: param.getCourtName();
|
||||||
|
String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
entity.setDataType(param.getDataType());
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
||||||
entity.setAppellee(param.getAppellee());
|
entity.setAppellee(param.getAppellee());
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
entity.setCauseOfAction(param.getCauseOfAction());
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
entity.setOtherPartiesThirdParty(otherPartiesThirdParty);
|
||||||
entity.setCourtName(param.getCourtName());
|
entity.setCourtName(courtName);
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
|
entity.setInvolvedAmount(involvedAmount);
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import com.gxwebsoft.credit.entity.CreditCompany;
|
|||||||
import com.gxwebsoft.credit.param.CreditCompanyImportParam;
|
import com.gxwebsoft.credit.param.CreditCompanyImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCompanyParam;
|
import com.gxwebsoft.credit.param.CreditCompanyParam;
|
||||||
import com.gxwebsoft.credit.service.CreditCompanyService;
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
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 org.apache.poi.ss.usermodel.Workbook;
|
import org.apache.poi.ss.usermodel.Workbook;
|
||||||
@@ -26,8 +27,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 企业控制器
|
* 企业控制器
|
||||||
@@ -45,6 +48,9 @@ public class CreditCompanyController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询企业")
|
@Operation(summary = "分页查询企业")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCompany>> page(CreditCompanyParam param) {
|
public ApiResult<PageResult<CreditCompany>> page(CreditCompanyParam param) {
|
||||||
@@ -93,7 +99,7 @@ public class CreditCompanyController extends BaseController {
|
|||||||
@Operation(summary = "删除企业")
|
@Operation(summary = "删除企业")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCompanyService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCompany.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,7 +132,7 @@ public class CreditCompanyController extends BaseController {
|
|||||||
@Operation(summary = "批量删除企业")
|
@Operation(summary = "批量删除企业")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCompanyService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCompany.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -141,7 +147,9 @@ public class CreditCompanyController extends BaseController {
|
|||||||
public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
|
public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
|
||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int insertedCount = 0;
|
||||||
|
Set<String> touchedMatchNames = new HashSet<>();
|
||||||
|
String refreshWarning = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
List<CreditCompanyImportParam> list = null;
|
List<CreditCompanyImportParam> list = null;
|
||||||
@@ -214,13 +222,17 @@ public class CreditCompanyController extends BaseController {
|
|||||||
// continue;
|
// continue;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
touchedMatchNames.add(item.getMatchName().trim());
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
insertedCount += batchImportSupport.persistChunkWithFallbackCount(
|
||||||
chunkItems,
|
chunkItems,
|
||||||
chunkRowNumbers,
|
chunkRowNumbers,
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
() -> {
|
||||||
|
int delta = countInsertedByMatchName(chunkItems);
|
||||||
|
batchImportSupport.upsertBySingleKey(
|
||||||
creditCompanyService,
|
creditCompanyService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCompany::getId,
|
CreditCompany::getId,
|
||||||
@@ -229,22 +241,22 @@ public class CreditCompanyController extends BaseController {
|
|||||||
CreditCompany::getMatchName,
|
CreditCompany::getMatchName,
|
||||||
null,
|
null,
|
||||||
mpBatchSize
|
mpBatchSize
|
||||||
),
|
);
|
||||||
|
return delta;
|
||||||
|
},
|
||||||
(rowItem, rowNumber) -> {
|
(rowItem, rowNumber) -> {
|
||||||
boolean saved = creditCompanyService.save(rowItem);
|
boolean saved = creditCompanyService.save(rowItem);
|
||||||
if (!saved) {
|
if (saved) {
|
||||||
|
return 1; // insert 入库
|
||||||
|
}
|
||||||
CreditCompany existing = creditCompanyService.getByMatchName(rowItem.getMatchName());
|
CreditCompany existing = creditCompanyService.getByMatchName(rowItem.getMatchName());
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
rowItem.setId(existing.getId());
|
rowItem.setId(existing.getId());
|
||||||
if (creditCompanyService.updateById(rowItem)) {
|
if (creditCompanyService.updateById(rowItem)) {
|
||||||
return true;
|
return 0; // update 不计入“入库”条数
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
throw new RuntimeException("保存失败");
|
||||||
return true;
|
|
||||||
}
|
|
||||||
errorMessages.add("第" + rowNumber + "行:保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
},
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
@@ -259,10 +271,12 @@ public class CreditCompanyController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
insertedCount += batchImportSupport.persistChunkWithFallbackCount(
|
||||||
chunkItems,
|
chunkItems,
|
||||||
chunkRowNumbers,
|
chunkRowNumbers,
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
() -> {
|
||||||
|
int delta = countInsertedByMatchName(chunkItems);
|
||||||
|
batchImportSupport.upsertBySingleKey(
|
||||||
creditCompanyService,
|
creditCompanyService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCompany::getId,
|
CreditCompany::getId,
|
||||||
@@ -271,31 +285,71 @@ public class CreditCompanyController extends BaseController {
|
|||||||
CreditCompany::getMatchName,
|
CreditCompany::getMatchName,
|
||||||
null,
|
null,
|
||||||
mpBatchSize
|
mpBatchSize
|
||||||
),
|
);
|
||||||
|
return delta;
|
||||||
|
},
|
||||||
(rowItem, rowNumber) -> {
|
(rowItem, rowNumber) -> {
|
||||||
boolean saved = creditCompanyService.save(rowItem);
|
boolean saved = creditCompanyService.save(rowItem);
|
||||||
if (!saved) {
|
if (saved) {
|
||||||
|
return 1; // insert 入库
|
||||||
|
}
|
||||||
CreditCompany existing = creditCompanyService.getByMatchName(rowItem.getMatchName());
|
CreditCompany existing = creditCompanyService.getByMatchName(rowItem.getMatchName());
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
rowItem.setId(existing.getId());
|
rowItem.setId(existing.getId());
|
||||||
if (creditCompanyService.updateById(rowItem)) {
|
if (creditCompanyService.updateById(rowItem)) {
|
||||||
return true;
|
return 0; // update 不计入“入库”条数
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
throw new RuntimeException("保存失败");
|
||||||
return true;
|
|
||||||
}
|
|
||||||
errorMessages.add("第" + rowNumber + "行:保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
},
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 导入完成后,按 matchName 定位本次涉及的企业并回填“关联记录数”字段(避免 companyId/自增 id 在导入对象里拿不到)。
|
||||||
|
if (!touchedMatchNames.isEmpty()) {
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
List<String> allMatchNames = new ArrayList<>(touchedMatchNames);
|
||||||
|
final int inChunkSize = 800;
|
||||||
|
for (int i = 0; i < allMatchNames.size(); i += inChunkSize) {
|
||||||
|
List<String> chunk = allMatchNames.subList(i, Math.min(allMatchNames.size(), i + inChunkSize));
|
||||||
|
List<CreditCompany> dbRows = creditCompanyService.lambdaQuery()
|
||||||
|
.select(CreditCompany::getId)
|
||||||
|
.in(CreditCompany::getMatchName, chunk)
|
||||||
|
.list();
|
||||||
|
if (!CollectionUtils.isEmpty(dbRows)) {
|
||||||
|
for (CreditCompany row : dbRows) {
|
||||||
|
if (row != null && row.getId() != null) {
|
||||||
|
touchedCompanyIds.add(row.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
creditCompanyRecordCountService.refreshAll(touchedCompanyIds);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
// 导入本身已经成功写入,回填计数字段失败不应导致整个导入失败(可后续单独重试刷新)。
|
||||||
|
String msg = ex.getMessage();
|
||||||
|
if (msg != null && msg.length() > 300) {
|
||||||
|
msg = msg.substring(0, 300) + "...";
|
||||||
|
}
|
||||||
|
refreshWarning = "关联记录数回填失败:" + (msg != null ? msg : ex.getClass().getSimpleName());
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
String msg = "成功入库" + insertedCount + "条数据";
|
||||||
|
if (refreshWarning != null) {
|
||||||
|
msg = msg + ";" + refreshWarning;
|
||||||
|
}
|
||||||
|
return success(msg, null);
|
||||||
} else {
|
} else {
|
||||||
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
String msg = "导入完成,入库" + insertedCount + "条,失败" + errorMessages.size() + "条";
|
||||||
|
if (refreshWarning != null) {
|
||||||
|
msg = msg + ";" + refreshWarning;
|
||||||
|
}
|
||||||
|
return success(msg, errorMessages);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -405,6 +459,53 @@ public class CreditCompanyController extends BaseController {
|
|||||||
return value == null || value.trim().isEmpty();
|
return value == null || value.trim().isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入库条数以 insert 为准:matchName 在数据库中不存在时计 1,否则计 0。
|
||||||
|
*
|
||||||
|
* <p>统计口径需与批量 upsert 的匹配字段保持一致(matchName)。</p>
|
||||||
|
*/
|
||||||
|
private int countInsertedByMatchName(List<CreditCompany> items) {
|
||||||
|
if (CollectionUtils.isEmpty(items)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
List<String> matchNames = new ArrayList<>(items.size());
|
||||||
|
for (CreditCompany item : items) {
|
||||||
|
if (item == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String key = item.getMatchName();
|
||||||
|
if (!isBlank(key)) {
|
||||||
|
matchNames.add(key.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (matchNames.isEmpty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> existing = new HashSet<>();
|
||||||
|
List<CreditCompany> dbRows = creditCompanyService.lambdaQuery()
|
||||||
|
.select(CreditCompany::getMatchName)
|
||||||
|
.in(CreditCompany::getMatchName, matchNames)
|
||||||
|
.list();
|
||||||
|
if (!CollectionUtils.isEmpty(dbRows)) {
|
||||||
|
for (CreditCompany row : dbRows) {
|
||||||
|
String v = row != null ? row.getMatchName() : null;
|
||||||
|
if (!isBlank(v)) {
|
||||||
|
existing.add(v.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
for (CreditCompany item : items) {
|
||||||
|
String key = item != null ? item.getMatchName() : null;
|
||||||
|
if (!isBlank(key) && !existing.contains(key.trim())) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将CreditCompanyImportParam转换为CreditCompany实体
|
* 将CreditCompanyImportParam转换为CreditCompany实体
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditCompetitor;
|
import com.gxwebsoft.credit.entity.CreditCompetitor;
|
||||||
import com.gxwebsoft.credit.param.CreditCompetitorImportParam;
|
import com.gxwebsoft.credit.param.CreditCompetitorImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCompetitorParam;
|
import com.gxwebsoft.credit.param.CreditCompetitorParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditCompetitorService;
|
import com.gxwebsoft.credit.service.CreditCompetitorService;
|
||||||
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;
|
||||||
@@ -22,7 +25,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 竞争对手控制器
|
* 竞争对手控制器
|
||||||
@@ -40,6 +46,12 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询竞争对手")
|
@Operation(summary = "分页查询竞争对手")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCompetitor>> page(CreditCompetitorParam param) {
|
public ApiResult<PageResult<CreditCompetitor>> page(CreditCompetitorParam param) {
|
||||||
@@ -93,7 +105,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
@Operation(summary = "删除竞争对手")
|
@Operation(summary = "删除竞争对手")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCompetitorService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCompetitor.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +138,52 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
@Operation(summary = "批量删除竞争对手")
|
@Operation(summary = "批量删除竞争对手")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCompetitorService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCompetitor.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCompetitor:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditCompetitorService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditCompetitor::getId,
|
||||||
|
CreditCompetitor::setId,
|
||||||
|
CreditCompetitor::getName,
|
||||||
|
CreditCompetitor::getCompanyId,
|
||||||
|
CreditCompetitor::setCompanyId,
|
||||||
|
CreditCompetitor::setCompanyName,
|
||||||
|
CreditCompetitor::getHasData,
|
||||||
|
CreditCompetitor::setHasData,
|
||||||
|
CreditCompetitor::getTenantId,
|
||||||
|
CreditCompetitor::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入竞争对手
|
* 批量导入竞争对手
|
||||||
*/
|
*/
|
||||||
@@ -142,6 +194,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "竞争对手", 2);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "竞争对手", 2);
|
||||||
@@ -150,6 +203,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
List<CreditCompetitorImportParam> list = importResult.getData();
|
List<CreditCompetitorImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -158,6 +212,13 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByName = ExcelImportSupport.readUrlByKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "企业名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -168,9 +229,19 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
CreditCompetitorImportParam param = list.get(i);
|
CreditCompetitorImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditCompetitor item = convertImportParamToEntity(param);
|
CreditCompetitor item = convertImportParamToEntity(param);
|
||||||
|
// name 为竞争对手企业名称;companyName 为主体企业名称。
|
||||||
|
if (!ImportHelper.isBlank(item.getName())) {
|
||||||
|
String link = urlByName.get(item.getName().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -189,46 +260,25 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
if (ImportHelper.isBlank(item.getCompanyName())) {
|
if (ImportHelper.isBlank(item.getName())) {
|
||||||
errorMessages.add("第" + excelRowNumber + "行:企业名称不能为空");
|
errorMessages.add("第" + excelRowNumber + "行:企业名称不能为空");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCompetitorService,
|
creditCompetitorService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCompetitor::getId,
|
chunkRowNumbers,
|
||||||
CreditCompetitor::setId,
|
mpBatchSize,
|
||||||
CreditCompetitor::getCompanyName,
|
CreditCompetitor::getName,
|
||||||
CreditCompetitor::getCompanyName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCompetitorService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCompetitor existing = creditCompetitorService.lambdaQuery()
|
|
||||||
.eq(CreditCompetitor::getCompanyName, rowItem.getCompanyName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCompetitorService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -242,42 +292,19 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCompetitorService,
|
creditCompetitorService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCompetitor::getId,
|
chunkRowNumbers,
|
||||||
CreditCompetitor::setId,
|
mpBatchSize,
|
||||||
CreditCompetitor::getCompanyName,
|
CreditCompetitor::getName,
|
||||||
CreditCompetitor::getCompanyName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCompetitorService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCompetitor existing = creditCompetitorService.lambdaQuery()
|
|
||||||
.eq(CreditCompetitor::getCompanyName, rowItem.getCompanyName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCompetitorService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.COMPETITOR, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -298,7 +325,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
List<CreditCompetitorImportParam> templateList = new ArrayList<>();
|
List<CreditCompetitorImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditCompetitorImportParam example = new CreditCompetitorImportParam();
|
CreditCompetitorImportParam example = new CreditCompetitorImportParam();
|
||||||
example.setCompanyName("示例科技有限公司");
|
example.setName("示例科技有限公司");
|
||||||
example.setLegalRepresentative("张三");
|
example.setLegalRepresentative("张三");
|
||||||
example.setRegisteredCapital("5000");
|
example.setRegisteredCapital("5000");
|
||||||
example.setEstablishmentDate("2015-01-01");
|
example.setEstablishmentDate("2015-01-01");
|
||||||
@@ -321,7 +348,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCompanyName())
|
return ImportHelper.isBlank(param.getName())
|
||||||
&& ImportHelper.isBlank(param.getLegalRepresentative())
|
&& ImportHelper.isBlank(param.getLegalRepresentative())
|
||||||
&& ImportHelper.isBlank(param.getRegisteredCapital())
|
&& ImportHelper.isBlank(param.getRegisteredCapital())
|
||||||
&& ImportHelper.isBlank(param.getEstablishmentDate());
|
&& ImportHelper.isBlank(param.getEstablishmentDate());
|
||||||
@@ -330,7 +357,7 @@ public class CreditCompetitorController extends BaseController {
|
|||||||
private CreditCompetitor convertImportParamToEntity(CreditCompetitorImportParam param) {
|
private CreditCompetitor convertImportParamToEntity(CreditCompetitorImportParam param) {
|
||||||
CreditCompetitor entity = new CreditCompetitor();
|
CreditCompetitor entity = new CreditCompetitor();
|
||||||
|
|
||||||
entity.setCompanyName(param.getCompanyName());
|
entity.setName(param.getName());
|
||||||
entity.setLegalRepresentative(param.getLegalRepresentative());
|
entity.setLegalRepresentative(param.getLegalRepresentative());
|
||||||
entity.setRegisteredCapital(param.getRegisteredCapital());
|
entity.setRegisteredCapital(param.getRegisteredCapital());
|
||||||
entity.setEstablishmentDate(param.getEstablishmentDate());
|
entity.setEstablishmentDate(param.getEstablishmentDate());
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditCourtAnnouncement;
|
import com.gxwebsoft.credit.entity.CreditCourtAnnouncement;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.param.CreditCourtAnnouncementImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCourtAnnouncementParam;
|
import com.gxwebsoft.credit.param.CreditCourtAnnouncementParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditCourtAnnouncementService;
|
import com.gxwebsoft.credit.service.CreditCourtAnnouncementService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 法院公告司法大数据控制器
|
* 法院公告司法大数据控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询法院公告司法大数据")
|
@Operation(summary = "分页查询法院公告司法大数据")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCourtAnnouncement>> page(CreditCourtAnnouncementParam param) {
|
public ApiResult<PageResult<CreditCourtAnnouncement>> page(CreditCourtAnnouncementParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
@Operation(summary = "删除法院公告司法大数据")
|
@Operation(summary = "删除法院公告司法大数据")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCourtAnnouncementService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCourtAnnouncement.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +137,55 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
@Operation(summary = "批量删除法院公告司法大数据")
|
@Operation(summary = "批量删除法院公告司法大数据")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCourtAnnouncementService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCourtAnnouncement.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCourtAnnouncement:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditCourtAnnouncementService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditCourtAnnouncement::getId,
|
||||||
|
CreditCourtAnnouncement::setId,
|
||||||
|
CreditCourtAnnouncement::getCompanyId,
|
||||||
|
CreditCourtAnnouncement::setCompanyId,
|
||||||
|
CreditCourtAnnouncement::getHasData,
|
||||||
|
CreditCourtAnnouncement::setHasData,
|
||||||
|
CreditCourtAnnouncement::getTenantId,
|
||||||
|
CreditCourtAnnouncement::new,
|
||||||
|
CreditCourtAnnouncement::getPlaintiffAppellant,
|
||||||
|
CreditCourtAnnouncement::getAppellee,
|
||||||
|
CreditCourtAnnouncement::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入法院公告司法大数据
|
* 批量导入法院公告司法大数据
|
||||||
*/
|
*/
|
||||||
@@ -142,13 +196,17 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
// 兼容多 sheet 文件:优先定位“法院公告”sheet,否则默认第 0 个。
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "法院公告", 0);
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
ExcelImportSupport.ImportResult<CreditCourtAnnouncementImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditCourtAnnouncementImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCourtAnnouncementImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +215,7 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,9 +223,15 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditCourtAnnouncementImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditCourtAnnouncement item = convertImportParamToEntity(param);
|
CreditCourtAnnouncement item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
@@ -193,41 +258,20 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCourtAnnouncementService,
|
creditCourtAnnouncementService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCourtAnnouncement::getId,
|
chunkRowNumbers,
|
||||||
CreditCourtAnnouncement::setId,
|
mpBatchSize,
|
||||||
CreditCourtAnnouncement::getCaseNumber,
|
CreditCourtAnnouncement::getCaseNumber,
|
||||||
CreditCourtAnnouncement::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCourtAnnouncementService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCourtAnnouncement existing = creditCourtAnnouncementService.lambdaQuery()
|
|
||||||
.eq(CreditCourtAnnouncement::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCourtAnnouncementService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +285,19 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCourtAnnouncementService,
|
creditCourtAnnouncementService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCourtAnnouncement::getId,
|
chunkRowNumbers,
|
||||||
CreditCourtAnnouncement::setId,
|
mpBatchSize,
|
||||||
CreditCourtAnnouncement::getCaseNumber,
|
CreditCourtAnnouncement::getCaseNumber,
|
||||||
CreditCourtAnnouncement::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCourtAnnouncementService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCourtAnnouncement existing = creditCourtAnnouncementService.lambdaQuery()
|
|
||||||
.eq(CreditCourtAnnouncement::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCourtAnnouncementService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.COURT_ANNOUNCEMENT, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -288,15 +309,146 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史法院公告(仅解析“历史法院公告”选项卡;兼容“历史法庭公告”)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCourtAnnouncement:save')")
|
||||||
|
@Operation(summary = "批量导入历史法院公告司法大数据")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史法院公告");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
// 兼容旧命名
|
||||||
|
sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史法庭公告");
|
||||||
|
}
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史法院公告”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditCourtAnnouncementImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditCourtAnnouncementImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCourtAnnouncementImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditCourtAnnouncement> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditCourtAnnouncementImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditCourtAnnouncement item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCourtAnnouncementService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCourtAnnouncement::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCourtAnnouncementService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCourtAnnouncement::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.COURT_ANNOUNCEMENT, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载法院公告司法大数据导入模板
|
* 下载法院公告司法大数据导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载法院公告司法大数据导入模板")
|
@Operation(summary = "下载法院公告司法大数据导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditCourtAnnouncementImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditCourtAnnouncementImportParam example = new CreditCourtAnnouncementImportParam();
|
||||||
example.setDataType("法院公告");
|
example.setDataType("法院公告");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
@@ -304,13 +456,13 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
example.setOccurrenceTime("2024-01-01");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setCauseOfAction("案由示例");
|
example.setCauseOfAction("案由示例");
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setInvolvedAmount("100000");
|
||||||
|
example.setDataStatus("正常");
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("法院公告导入模板", "法院公告", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("法院公告导入模板", "法院公告", CreditCourtAnnouncementImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_court_announcement_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_court_announcement_import_template.xlsx");
|
||||||
@@ -319,28 +471,43 @@ public class CreditCourtAnnouncementController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditCourtAnnouncementImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
&& ImportHelper.isBlank(param.getCauseOfAction());
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditCourtAnnouncement convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditCourtAnnouncement convertImportParamToEntity(CreditCourtAnnouncementImportParam param) {
|
||||||
CreditCourtAnnouncement entity = new CreditCourtAnnouncement();
|
CreditCourtAnnouncement entity = new CreditCourtAnnouncement();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
String dataType = !ImportHelper.isBlank(param.getDataType2())
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
? param.getDataType2()
|
||||||
|
: param.getDataType();
|
||||||
|
String plaintiffAppellant = !ImportHelper.isBlank(param.getPlaintiffAppellant2())
|
||||||
|
? param.getPlaintiffAppellant2()
|
||||||
|
: param.getPlaintiffAppellant();
|
||||||
|
String otherPartiesThirdParty = !ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
|
? param.getOtherPartiesThirdParty2()
|
||||||
|
: param.getOtherPartiesThirdParty();
|
||||||
|
String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
|
||||||
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime();
|
||||||
|
|
||||||
|
entity.setDataType(dataType);
|
||||||
|
entity.setPlaintiffAppellant(plaintiffAppellant);
|
||||||
entity.setAppellee(param.getAppellee());
|
entity.setAppellee(param.getAppellee());
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
entity.setOtherPartiesThirdParty(otherPartiesThirdParty);
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
entity.setCauseOfAction(param.getCauseOfAction());
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
|
||||||
entity.setCourtName(param.getCourtName());
|
entity.setCourtName(param.getCourtName());
|
||||||
|
entity.setInvolvedAmount(involvedAmount);
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditCourtSession;
|
import com.gxwebsoft.credit.entity.CreditCourtSession;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.param.CreditCourtSessionImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCourtSessionParam;
|
import com.gxwebsoft.credit.param.CreditCourtSessionParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditCourtSessionService;
|
import com.gxwebsoft.credit.service.CreditCourtSessionService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 开庭公告司法大数据控制器
|
* 开庭公告司法大数据控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询开庭公告司法大数据")
|
@Operation(summary = "分页查询开庭公告司法大数据")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCourtSession>> page(CreditCourtSessionParam param) {
|
public ApiResult<PageResult<CreditCourtSession>> page(CreditCourtSessionParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
@Operation(summary = "删除开庭公告司法大数据")
|
@Operation(summary = "删除开庭公告司法大数据")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCourtSessionService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCourtSession.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +137,55 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
@Operation(summary = "批量删除开庭公告司法大数据")
|
@Operation(summary = "批量删除开庭公告司法大数据")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCourtSessionService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCourtSession.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCourtSession:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditCourtSessionService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditCourtSession::getId,
|
||||||
|
CreditCourtSession::setId,
|
||||||
|
CreditCourtSession::getCompanyId,
|
||||||
|
CreditCourtSession::setCompanyId,
|
||||||
|
CreditCourtSession::getHasData,
|
||||||
|
CreditCourtSession::setHasData,
|
||||||
|
CreditCourtSession::getTenantId,
|
||||||
|
CreditCourtSession::new,
|
||||||
|
CreditCourtSession::getPlaintiffAppellant,
|
||||||
|
CreditCourtSession::getAppellee,
|
||||||
|
CreditCourtSession::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入开庭公告司法大数据
|
* 批量导入开庭公告司法大数据
|
||||||
*/
|
*/
|
||||||
@@ -142,13 +196,17 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
// 兼容多 sheet 文件:优先定位“开庭公告”sheet,否则默认第 0 个。
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "开庭公告", 0);
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
ExcelImportSupport.ImportResult<CreditCourtSessionImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditCourtSessionImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCourtSessionImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +215,7 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,13 +223,22 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditCourtSessionImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditCourtSession item = convertImportParamToEntity(param);
|
CreditCourtSession item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -193,41 +261,20 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCourtSessionService,
|
creditCourtSessionService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCourtSession::getId,
|
chunkRowNumbers,
|
||||||
CreditCourtSession::setId,
|
mpBatchSize,
|
||||||
CreditCourtSession::getCaseNumber,
|
CreditCourtSession::getCaseNumber,
|
||||||
CreditCourtSession::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCourtSessionService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCourtSession existing = creditCourtSessionService.lambdaQuery()
|
|
||||||
.eq(CreditCourtSession::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCourtSessionService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +288,19 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditCourtSessionService,
|
creditCourtSessionService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditCourtSession::getId,
|
chunkRowNumbers,
|
||||||
CreditCourtSession::setId,
|
mpBatchSize,
|
||||||
CreditCourtSession::getCaseNumber,
|
CreditCourtSession::getCaseNumber,
|
||||||
CreditCourtSession::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditCourtSessionService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditCourtSession existing = creditCourtSessionService.lambdaQuery()
|
|
||||||
.eq(CreditCourtSession::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditCourtSessionService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.COURT_SESSION, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -288,29 +312,157 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史开庭公告(仅解析“历史开庭公告”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCourtSession:save')")
|
||||||
|
@Operation(summary = "批量导入历史开庭公告司法大数据")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史开庭公告");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史开庭公告”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditCourtSessionImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditCourtSessionImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditCourtSessionImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditCourtSession> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditCourtSessionImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditCourtSession item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCourtSessionService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCourtSession::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditCourtSessionService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditCourtSession::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.COURT_SESSION, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载开庭公告司法大数据导入模板
|
* 下载开庭公告司法大数据导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载开庭公告司法大数据导入模板")
|
@Operation(summary = "下载开庭公告司法大数据导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditCourtSessionImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditCourtSessionImportParam example = new CreditCourtSessionImportParam();
|
||||||
example.setDataType("开庭公告");
|
example.setDataType("开庭公告");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
example.setOtherPartiesThirdParty2("第三人示例");
|
||||||
example.setOccurrenceTime("2024-01-01");
|
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setCauseOfAction("案由示例");
|
example.setCauseOfAction("案由示例");
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
|
example.setInvolvedAmount("100000");
|
||||||
|
example.setDataStatus("正常");
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("开庭公告导入模板", "开庭公告", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("开庭公告导入模板", "开庭公告", CreditCourtSessionImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_court_session_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_court_session_import_template.xlsx");
|
||||||
@@ -319,29 +471,39 @@ public class CreditCourtSessionController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditCourtSessionImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
&& ImportHelper.isBlank(param.getCauseOfAction());
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditCourtSession convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditCourtSession convertImportParamToEntity(CreditCourtSessionImportParam param) {
|
||||||
CreditCourtSession entity = new CreditCourtSession();
|
CreditCourtSession entity = new CreditCourtSession();
|
||||||
|
|
||||||
|
// Template compatibility: prefer new columns ("发生时间"/"其他当事人/第三人") when present.
|
||||||
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime();
|
||||||
|
String otherPartiesThirdParty = !ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
|
? param.getOtherPartiesThirdParty2()
|
||||||
|
: param.getOtherPartiesThirdParty();
|
||||||
|
String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
entity.setDataType(param.getDataType());
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
||||||
entity.setAppellee(param.getAppellee());
|
entity.setAppellee(param.getAppellee());
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
entity.setInvolvedAmount(involvedAmount);
|
||||||
|
|
||||||
|
entity.setOtherPartiesThirdParty(otherPartiesThirdParty);
|
||||||
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
entity.setCauseOfAction(param.getCauseOfAction());
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
|
||||||
entity.setCourtName(param.getCourtName());
|
entity.setCourtName(param.getCourtName());
|
||||||
entity.setDataStatus(param.getDataStatus());
|
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditCustomer;
|
import com.gxwebsoft.credit.entity.CreditCustomer;
|
||||||
import com.gxwebsoft.credit.param.CreditCustomerImportParam;
|
import com.gxwebsoft.credit.param.CreditCustomerImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditCustomerParam;
|
import com.gxwebsoft.credit.param.CreditCustomerParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditCustomerService;
|
import com.gxwebsoft.credit.service.CreditCustomerService;
|
||||||
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;
|
||||||
@@ -22,8 +25,12 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 客户控制器
|
* 客户控制器
|
||||||
@@ -41,6 +48,12 @@ public class CreditCustomerController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询客户")
|
@Operation(summary = "分页查询客户")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditCustomer>> page(CreditCustomerParam param) {
|
public ApiResult<PageResult<CreditCustomer>> page(CreditCustomerParam param) {
|
||||||
@@ -89,7 +102,7 @@ public class CreditCustomerController extends BaseController {
|
|||||||
@Operation(summary = "删除客户")
|
@Operation(summary = "删除客户")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditCustomerService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditCustomer.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -122,12 +135,52 @@ public class CreditCustomerController extends BaseController {
|
|||||||
@Operation(summary = "批量删除客户")
|
@Operation(summary = "批量删除客户")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditCustomerService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditCustomer.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditCustomer:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditCustomerService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditCustomer::getId,
|
||||||
|
CreditCustomer::setId,
|
||||||
|
CreditCustomer::getName,
|
||||||
|
CreditCustomer::getCompanyId,
|
||||||
|
CreditCustomer::setCompanyId,
|
||||||
|
CreditCustomer::setCompanyName,
|
||||||
|
CreditCustomer::getHasData,
|
||||||
|
CreditCustomer::setHasData,
|
||||||
|
CreditCustomer::getTenantId,
|
||||||
|
CreditCustomer::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入客户
|
* 批量导入客户
|
||||||
*/
|
*/
|
||||||
@@ -138,6 +191,7 @@ public class CreditCustomerController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "客户", 4);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "客户", 4);
|
||||||
@@ -146,6 +200,7 @@ public class CreditCustomerController extends BaseController {
|
|||||||
List<CreditCustomerImportParam> list = importResult.getData();
|
List<CreditCustomerImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -154,6 +209,12 @@ public class CreditCustomerController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByName = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "客户");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -165,9 +226,19 @@ public class CreditCustomerController extends BaseController {
|
|||||||
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
try {
|
try {
|
||||||
CreditCustomer item = convertImportParamToEntity(param);
|
CreditCustomer item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getName())) {
|
||||||
|
item.setName(item.getName().trim());
|
||||||
|
String link = urlByName.get(item.getName());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -190,119 +261,14 @@ public class CreditCustomerController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += persistImportChunk(chunkItems, chunkRowNumbers, mpBatchSize, errorMessages);
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> {
|
|
||||||
// 批内一次查库,避免逐行查/写导致数据库压力过大
|
|
||||||
List<String> names = new ArrayList<>(chunkItems.size());
|
|
||||||
for (CreditCustomer it : chunkItems) {
|
|
||||||
if (it != null && !ImportHelper.isBlank(it.getName())) {
|
|
||||||
names.add(it.getName().trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<CreditCustomer> existingList = names.isEmpty()
|
|
||||||
? new ArrayList<>()
|
|
||||||
: creditCustomerService.lambdaQuery()
|
|
||||||
.in(CreditCustomer::getName, names)
|
|
||||||
.list();
|
|
||||||
java.util.Map<String, CreditCustomer> existingByName = new java.util.HashMap<>();
|
|
||||||
for (CreditCustomer existing : existingList) {
|
|
||||||
if (existing != null && !ImportHelper.isBlank(existing.getName())) {
|
|
||||||
existingByName.putIfAbsent(existing.getName().trim(), existing);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
java.util.Map<String, CreditCustomer> latestByName = new java.util.HashMap<>();
|
|
||||||
int acceptedRows = 0;
|
|
||||||
for (int idx = 0; idx < chunkItems.size(); idx++) {
|
|
||||||
CreditCustomer it = chunkItems.get(idx);
|
|
||||||
int rowNo = (idx < chunkRowNumbers.size()) ? chunkRowNumbers.get(idx) : -1;
|
|
||||||
if (it == null || ImportHelper.isBlank(it.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String name = it.getName().trim();
|
|
||||||
CreditCustomer existing = existingByName.get(name);
|
|
||||||
if (existing != null) {
|
|
||||||
Integer existingTenantId = existing.getTenantId();
|
|
||||||
if (it.getTenantId() != null
|
|
||||||
&& existingTenantId != null
|
|
||||||
&& !it.getTenantId().equals(existingTenantId)) {
|
|
||||||
errorMessages.add("第" + rowNo + "行:客户名称已存在且归属其他租户,无法导入");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
it.setId(existing.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
it.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 同名多行:保留最后一行的值(等价于“先插入/更新,再被后续行更新”)
|
|
||||||
latestByName.put(name, it);
|
|
||||||
acceptedRows++;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<CreditCustomer> updates = new ArrayList<>();
|
|
||||||
List<CreditCustomer> inserts = new ArrayList<>();
|
|
||||||
for (CreditCustomer it : latestByName.values()) {
|
|
||||||
if (it.getId() != null) {
|
|
||||||
updates.add(it);
|
|
||||||
} else {
|
|
||||||
inserts.add(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!updates.isEmpty()) {
|
|
||||||
creditCustomerService.updateBatchById(updates, mpBatchSize);
|
|
||||||
}
|
|
||||||
if (!inserts.isEmpty()) {
|
|
||||||
creditCustomerService.saveBatch(inserts, mpBatchSize);
|
|
||||||
}
|
|
||||||
return acceptedRows;
|
|
||||||
},
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
CreditCustomer existing = creditCustomerService.lambdaQuery()
|
|
||||||
.eq(CreditCustomer::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
Integer existingTenantId = existing.getTenantId();
|
|
||||||
if (rowItem.getTenantId() != null
|
|
||||||
&& existingTenantId != null
|
|
||||||
&& !rowItem.getTenantId().equals(existingTenantId)) {
|
|
||||||
errorMessages.add("第" + rowNumber + "行:客户名称已存在且归属其他租户,无法导入");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
rowItem.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
return creditCustomerService.updateById(rowItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return creditCustomerService.save(rowItem);
|
|
||||||
} catch (DataIntegrityViolationException e) {
|
|
||||||
if (!isDuplicateCustomerName(e)) {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
CreditCustomer dbExisting = creditCustomerService.lambdaQuery()
|
|
||||||
.eq(CreditCustomer::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (dbExisting != null) {
|
|
||||||
Integer existingTenantId = dbExisting.getTenantId();
|
|
||||||
rowItem.setId(dbExisting.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
rowItem.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
return creditCustomerService.updateById(rowItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
errorMessages.add("第" + rowNumber + "行:保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
|
||||||
);
|
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
chunkRowNumbers.clear();
|
chunkRowNumbers.clear();
|
||||||
}
|
}
|
||||||
@@ -313,115 +279,10 @@ public class CreditCustomerController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += persistImportChunk(chunkItems, chunkRowNumbers, mpBatchSize, errorMessages);
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> {
|
|
||||||
List<String> names = new ArrayList<>(chunkItems.size());
|
|
||||||
for (CreditCustomer it : chunkItems) {
|
|
||||||
if (it != null && !ImportHelper.isBlank(it.getName())) {
|
|
||||||
names.add(it.getName().trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<CreditCustomer> existingList = names.isEmpty()
|
|
||||||
? new ArrayList<>()
|
|
||||||
: creditCustomerService.lambdaQuery()
|
|
||||||
.in(CreditCustomer::getName, names)
|
|
||||||
.list();
|
|
||||||
java.util.Map<String, CreditCustomer> existingByName = new java.util.HashMap<>();
|
|
||||||
for (CreditCustomer existing : existingList) {
|
|
||||||
if (existing != null && !ImportHelper.isBlank(existing.getName())) {
|
|
||||||
existingByName.putIfAbsent(existing.getName().trim(), existing);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
java.util.Map<String, CreditCustomer> latestByName = new java.util.HashMap<>();
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.CUSTOMER, touchedCompanyIds);
|
||||||
int acceptedRows = 0;
|
|
||||||
for (int idx = 0; idx < chunkItems.size(); idx++) {
|
|
||||||
CreditCustomer it = chunkItems.get(idx);
|
|
||||||
int rowNo = (idx < chunkRowNumbers.size()) ? chunkRowNumbers.get(idx) : -1;
|
|
||||||
if (it == null || ImportHelper.isBlank(it.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String name = it.getName().trim();
|
|
||||||
CreditCustomer existing = existingByName.get(name);
|
|
||||||
if (existing != null) {
|
|
||||||
Integer existingTenantId = existing.getTenantId();
|
|
||||||
if (it.getTenantId() != null
|
|
||||||
&& existingTenantId != null
|
|
||||||
&& !it.getTenantId().equals(existingTenantId)) {
|
|
||||||
errorMessages.add("第" + rowNo + "行:客户名称已存在且归属其他租户,无法导入");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
it.setId(existing.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
it.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
latestByName.put(name, it);
|
|
||||||
acceptedRows++;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<CreditCustomer> updates = new ArrayList<>();
|
|
||||||
List<CreditCustomer> inserts = new ArrayList<>();
|
|
||||||
for (CreditCustomer it : latestByName.values()) {
|
|
||||||
if (it.getId() != null) {
|
|
||||||
updates.add(it);
|
|
||||||
} else {
|
|
||||||
inserts.add(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!updates.isEmpty()) {
|
|
||||||
creditCustomerService.updateBatchById(updates, mpBatchSize);
|
|
||||||
}
|
|
||||||
if (!inserts.isEmpty()) {
|
|
||||||
creditCustomerService.saveBatch(inserts, mpBatchSize);
|
|
||||||
}
|
|
||||||
return acceptedRows;
|
|
||||||
},
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
CreditCustomer existing = creditCustomerService.lambdaQuery()
|
|
||||||
.eq(CreditCustomer::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
Integer existingTenantId = existing.getTenantId();
|
|
||||||
if (rowItem.getTenantId() != null
|
|
||||||
&& existingTenantId != null
|
|
||||||
&& !rowItem.getTenantId().equals(existingTenantId)) {
|
|
||||||
errorMessages.add("第" + rowNumber + "行:客户名称已存在且归属其他租户,无法导入");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
rowItem.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
return creditCustomerService.updateById(rowItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return creditCustomerService.save(rowItem);
|
|
||||||
} catch (DataIntegrityViolationException e) {
|
|
||||||
if (!isDuplicateCustomerName(e)) {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
CreditCustomer dbExisting = creditCustomerService.lambdaQuery()
|
|
||||||
.eq(CreditCustomer::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (dbExisting != null) {
|
|
||||||
Integer existingTenantId = dbExisting.getTenantId();
|
|
||||||
rowItem.setId(dbExisting.getId());
|
|
||||||
if (existingTenantId != null) {
|
|
||||||
rowItem.setTenantId(existingTenantId);
|
|
||||||
}
|
|
||||||
return creditCustomerService.updateById(rowItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
errorMessages.add("第" + rowNumber + "行:保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
@@ -489,19 +350,71 @@ public class CreditCustomerController extends BaseController {
|
|||||||
return value.trim();
|
return value.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isDuplicateCustomerName(DataIntegrityViolationException e) {
|
private int persistImportChunk(List<CreditCustomer> items,
|
||||||
|
List<Integer> excelRowNumbers,
|
||||||
|
int mpBatchSize,
|
||||||
|
List<String> errorMessages) {
|
||||||
|
return batchImportSupport.persistChunkWithFallback(
|
||||||
|
items,
|
||||||
|
excelRowNumbers,
|
||||||
|
() -> {
|
||||||
|
boolean ok = creditCustomerService.saveBatch(items, mpBatchSize);
|
||||||
|
if (!ok) {
|
||||||
|
throw new RuntimeException("批量保存失败");
|
||||||
|
}
|
||||||
|
return items.size();
|
||||||
|
},
|
||||||
|
(rowItem, rowNumber) -> {
|
||||||
|
try {
|
||||||
|
boolean saved = creditCustomerService.save(rowItem);
|
||||||
|
if (saved) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (rowNumber != null && rowNumber > 0) {
|
||||||
|
errorMessages.add("第" + rowNumber + "行:保存失败");
|
||||||
|
} else {
|
||||||
|
errorMessages.add("保存失败");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch (DataIntegrityViolationException e) {
|
||||||
|
if (isDuplicateKey(e)) {
|
||||||
|
String name = rowItem != null ? rowItem.getName() : null;
|
||||||
|
String label = ImportHelper.isBlank(name) ? "数据" : ("客户【" + name.trim() + "】");
|
||||||
|
if (rowNumber != null && rowNumber > 0) {
|
||||||
|
errorMessages.add("第" + rowNumber + "行:" + label + "重复(唯一索引冲突)");
|
||||||
|
} else {
|
||||||
|
errorMessages.add(label + "重复(唯一索引冲突)");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isDuplicateKey(DataIntegrityViolationException e) {
|
||||||
|
// Prefer structured detection (SQLState / vendor error code), fall back to message contains.
|
||||||
|
for (Throwable t = e; t != null; t = t.getCause()) {
|
||||||
|
if (t instanceof SQLException) {
|
||||||
|
SQLException se = (SQLException) t;
|
||||||
|
// MySQL: 1062 Duplicate entry; PostgreSQL/H2: SQLState 23505 unique_violation
|
||||||
|
if (se.getErrorCode() == 1062) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if ("23505".equals(se.getSQLState())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Throwable mostSpecificCause = e.getMostSpecificCause();
|
Throwable mostSpecificCause = e.getMostSpecificCause();
|
||||||
String message = mostSpecificCause != null ? mostSpecificCause.getMessage() : e.getMessage();
|
String message = mostSpecificCause != null ? mostSpecificCause.getMessage() : e.getMessage();
|
||||||
if (message == null) {
|
if (message == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
String lower = message.toLowerCase();
|
String lower = message.toLowerCase();
|
||||||
if (!lower.contains("duplicate")) {
|
return lower.contains("duplicate") && lower.contains("key");
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return lower.contains("credit_customer.name")
|
|
||||||
|| lower.contains("for key 'name'")
|
|
||||||
|| lower.contains("for key `name`");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditDeliveryNotice;
|
import com.gxwebsoft.credit.entity.CreditDeliveryNotice;
|
||||||
|
import com.gxwebsoft.credit.param.CreditDeliveryNoticeImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditDeliveryNoticeParam;
|
import com.gxwebsoft.credit.param.CreditDeliveryNoticeParam;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditDeliveryNoticeService;
|
import com.gxwebsoft.credit.service.CreditDeliveryNoticeService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 送达公告司法大数据控制器
|
* 送达公告司法大数据控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询送达公告司法大数据")
|
@Operation(summary = "分页查询送达公告司法大数据")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditDeliveryNotice>> page(CreditDeliveryNoticeParam param) {
|
public ApiResult<PageResult<CreditDeliveryNotice>> page(CreditDeliveryNoticeParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
@Operation(summary = "删除送达公告司法大数据")
|
@Operation(summary = "删除送达公告司法大数据")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditDeliveryNoticeService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditDeliveryNotice.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +137,55 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
@Operation(summary = "批量删除送达公告司法大数据")
|
@Operation(summary = "批量删除送达公告司法大数据")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditDeliveryNoticeService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditDeliveryNotice.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditDeliveryNotice:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditDeliveryNoticeService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditDeliveryNotice::getId,
|
||||||
|
CreditDeliveryNotice::setId,
|
||||||
|
CreditDeliveryNotice::getCompanyId,
|
||||||
|
CreditDeliveryNotice::setCompanyId,
|
||||||
|
CreditDeliveryNotice::getHasData,
|
||||||
|
CreditDeliveryNotice::setHasData,
|
||||||
|
CreditDeliveryNotice::getTenantId,
|
||||||
|
CreditDeliveryNotice::new,
|
||||||
|
CreditDeliveryNotice::getPlaintiffAppellant,
|
||||||
|
CreditDeliveryNotice::getAppellee,
|
||||||
|
CreditDeliveryNotice::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入送达公告司法大数据
|
* 批量导入送达公告司法大数据
|
||||||
*/
|
*/
|
||||||
@@ -142,13 +196,16 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "送达公告", 0);
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
ExcelImportSupport.ImportResult<CreditDeliveryNoticeImportParam> importResult = ExcelImportSupport.read(
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
file, CreditDeliveryNoticeImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditDeliveryNoticeImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +214,9 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
// URL 通常以超链接形式存在于“案号”列里
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,9 +224,15 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditDeliveryNoticeImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditDeliveryNotice item = convertImportParamToEntity(param);
|
CreditDeliveryNotice item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (link != null && !link.isEmpty()) {
|
||||||
|
item.setUrl(link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
@@ -193,41 +259,20 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditDeliveryNoticeService,
|
creditDeliveryNoticeService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditDeliveryNotice::getId,
|
chunkRowNumbers,
|
||||||
CreditDeliveryNotice::setId,
|
mpBatchSize,
|
||||||
CreditDeliveryNotice::getCaseNumber,
|
CreditDeliveryNotice::getCaseNumber,
|
||||||
CreditDeliveryNotice::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditDeliveryNoticeService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditDeliveryNotice existing = creditDeliveryNoticeService.lambdaQuery()
|
|
||||||
.eq(CreditDeliveryNotice::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditDeliveryNoticeService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +286,19 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditDeliveryNoticeService,
|
creditDeliveryNoticeService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditDeliveryNotice::getId,
|
chunkRowNumbers,
|
||||||
CreditDeliveryNotice::setId,
|
mpBatchSize,
|
||||||
CreditDeliveryNotice::getCaseNumber,
|
CreditDeliveryNotice::getCaseNumber,
|
||||||
CreditDeliveryNotice::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditDeliveryNoticeService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditDeliveryNotice existing = creditDeliveryNoticeService.lambdaQuery()
|
|
||||||
.eq(CreditDeliveryNotice::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditDeliveryNoticeService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.DELIVERY_NOTICE, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -288,29 +310,157 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史送达公告(仅解析“历史送达公告”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditDeliveryNotice:save')")
|
||||||
|
@Operation(summary = "批量导入历史送达公告司法大数据")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史送达公告");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史送达公告”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditDeliveryNoticeImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditDeliveryNoticeImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditDeliveryNoticeImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditDeliveryNotice> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditDeliveryNoticeImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditDeliveryNotice item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditDeliveryNoticeService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditDeliveryNotice::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditDeliveryNoticeService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditDeliveryNotice::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.DELIVERY_NOTICE, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载送达公告导入模板
|
* 下载送达公告导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载送达公告导入模板")
|
@Operation(summary = "下载送达公告导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditDeliveryNoticeImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditDeliveryNoticeImportParam example = new CreditDeliveryNoticeImportParam();
|
||||||
example.setDataType("送达公告");
|
example.setDataType("送达公告");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
example.setOtherPartiesThirdParty2("第三人示例");
|
||||||
|
example.setInvolvedAmount("100000");
|
||||||
|
example.setDataStatus("正常");
|
||||||
example.setOccurrenceTime("2024-01-01");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setCauseOfAction("案由示例");
|
example.setCauseOfAction("案由示例");
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("送达公告导入模板", "送达公告", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("送达公告导入模板", "送达公告", CreditDeliveryNoticeImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_delivery_notice_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_delivery_notice_import_template.xlsx");
|
||||||
@@ -319,29 +469,45 @@ public class CreditDeliveryNoticeController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditDeliveryNoticeImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
|
&& ImportHelper.isBlank(param.getCauseOfAction())
|
||||||
|
&& ImportHelper.isBlank(param.getOtherPartiesThirdParty())
|
||||||
|
&& ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
&& ImportHelper.isBlank(param.getAppellee());
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditDeliveryNotice convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditDeliveryNotice convertImportParamToEntity(CreditDeliveryNoticeImportParam param) {
|
||||||
CreditDeliveryNotice entity = new CreditDeliveryNotice();
|
CreditDeliveryNotice entity = new CreditDeliveryNotice();
|
||||||
|
|
||||||
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime();
|
||||||
|
String otherPartiesThirdParty = !ImportHelper.isBlank(param.getOtherPartiesThirdParty2())
|
||||||
|
? param.getOtherPartiesThirdParty2()
|
||||||
|
: param.getOtherPartiesThirdParty();
|
||||||
|
String courtName = !ImportHelper.isBlank(param.getCourtName2())
|
||||||
|
? param.getCourtName2()
|
||||||
|
: param.getCourtName();
|
||||||
|
String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
entity.setDataType(param.getDataType());
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
||||||
entity.setAppellee(param.getAppellee());
|
entity.setAppellee(param.getAppellee());
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
entity.setInvolvedAmount(involvedAmount);
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
|
|
||||||
|
entity.setOtherPartiesThirdParty(otherPartiesThirdParty);
|
||||||
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
entity.setCauseOfAction(param.getCauseOfAction());
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
entity.setCourtName(courtName);
|
||||||
entity.setCourtName(param.getCourtName());
|
|
||||||
entity.setDataStatus(param.getDataStatus());
|
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditExternal;
|
import com.gxwebsoft.credit.entity.CreditExternal;
|
||||||
import com.gxwebsoft.credit.param.CreditExternalImportParam;
|
import com.gxwebsoft.credit.param.CreditExternalImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditExternalParam;
|
import com.gxwebsoft.credit.param.CreditExternalParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditExternalService;
|
import com.gxwebsoft.credit.service.CreditExternalService;
|
||||||
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;
|
||||||
@@ -22,7 +25,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对外投资控制器
|
* 对外投资控制器
|
||||||
@@ -40,6 +46,12 @@ public class CreditExternalController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询对外投资")
|
@Operation(summary = "分页查询对外投资")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditExternal>> page(CreditExternalParam param) {
|
public ApiResult<PageResult<CreditExternal>> page(CreditExternalParam param) {
|
||||||
@@ -93,7 +105,7 @@ public class CreditExternalController extends BaseController {
|
|||||||
@Operation(summary = "删除对外投资")
|
@Operation(summary = "删除对外投资")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditExternalService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditExternal.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +138,52 @@ public class CreditExternalController extends BaseController {
|
|||||||
@Operation(summary = "批量删除对外投资")
|
@Operation(summary = "批量删除对外投资")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditExternalService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditExternal.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditExternal:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditExternalService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditExternal::getId,
|
||||||
|
CreditExternal::setId,
|
||||||
|
CreditExternal::getName,
|
||||||
|
CreditExternal::getCompanyId,
|
||||||
|
CreditExternal::setCompanyId,
|
||||||
|
CreditExternal::setCompanyName,
|
||||||
|
CreditExternal::getHasData,
|
||||||
|
CreditExternal::setHasData,
|
||||||
|
CreditExternal::getTenantId,
|
||||||
|
CreditExternal::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入对外投资
|
* 批量导入对外投资
|
||||||
*/
|
*/
|
||||||
@@ -142,6 +194,7 @@ public class CreditExternalController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "对外投资", 0);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "对外投资", 0);
|
||||||
@@ -150,6 +203,7 @@ public class CreditExternalController extends BaseController {
|
|||||||
List<CreditExternalImportParam> list = importResult.getData();
|
List<CreditExternalImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -158,6 +212,12 @@ public class CreditExternalController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByName = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "被投资企业名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -168,9 +228,18 @@ public class CreditExternalController extends BaseController {
|
|||||||
CreditExternalImportParam param = list.get(i);
|
CreditExternalImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditExternal item = convertImportParamToEntity(param);
|
CreditExternal item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getName())) {
|
||||||
|
String link = urlByName.get(item.getName().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -194,41 +263,20 @@ public class CreditExternalController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditExternalService,
|
creditExternalService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditExternal::getId,
|
chunkRowNumbers,
|
||||||
CreditExternal::setId,
|
mpBatchSize,
|
||||||
CreditExternal::getName,
|
CreditExternal::getName,
|
||||||
CreditExternal::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditExternalService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditExternal existing = creditExternalService.lambdaQuery()
|
|
||||||
.eq(CreditExternal::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditExternalService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -242,42 +290,19 @@ public class CreditExternalController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditExternalService,
|
creditExternalService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditExternal::getId,
|
chunkRowNumbers,
|
||||||
CreditExternal::setId,
|
mpBatchSize,
|
||||||
CreditExternal::getName,
|
CreditExternal::getName,
|
||||||
CreditExternal::getName,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditExternalService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditExternal existing = creditExternalService.lambdaQuery()
|
|
||||||
.eq(CreditExternal::getName, rowItem.getName())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditExternalService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.EXTERNAL, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditFinalVersion;
|
import com.gxwebsoft.credit.entity.CreditFinalVersion;
|
||||||
|
import com.gxwebsoft.credit.param.CreditFinalVersionImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditFinalVersionParam;
|
import com.gxwebsoft.credit.param.CreditFinalVersionParam;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditFinalVersionService;
|
import com.gxwebsoft.credit.service.CreditFinalVersionService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 终本案件控制器
|
* 终本案件控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询终本案件")
|
@Operation(summary = "分页查询终本案件")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditFinalVersion>> page(CreditFinalVersionParam param) {
|
public ApiResult<PageResult<CreditFinalVersion>> page(CreditFinalVersionParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
@Operation(summary = "删除终本案件")
|
@Operation(summary = "删除终本案件")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditFinalVersionService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditFinalVersion.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +137,55 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
@Operation(summary = "批量删除终本案件")
|
@Operation(summary = "批量删除终本案件")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditFinalVersionService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditFinalVersion.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditFinalVersion:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Party columns may contain multiple roles/names; match if any company name is contained in the text.
|
||||||
|
// Priority: 原告/上诉人 > 被告/被上诉人 > 其他当事人/第三人
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditFinalVersionService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditFinalVersion::getId,
|
||||||
|
CreditFinalVersion::setId,
|
||||||
|
CreditFinalVersion::getCompanyId,
|
||||||
|
CreditFinalVersion::setCompanyId,
|
||||||
|
CreditFinalVersion::getHasData,
|
||||||
|
CreditFinalVersion::setHasData,
|
||||||
|
CreditFinalVersion::getTenantId,
|
||||||
|
CreditFinalVersion::new,
|
||||||
|
CreditFinalVersion::getPlaintiffAppellant,
|
||||||
|
CreditFinalVersion::getAppellee,
|
||||||
|
CreditFinalVersion::getOtherPartiesThirdParty
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入终本案件
|
* 批量导入终本案件
|
||||||
*/
|
*/
|
||||||
@@ -142,13 +196,17 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
// 按选项卡名称读取(客户提供的文件可能不是把目标 sheet 放在第一个)
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "终本案件", 0);
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
ExcelImportSupport.ImportResult<CreditFinalVersionImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditFinalVersionImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditFinalVersionImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +215,7 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,13 +223,22 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditFinalVersionImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditFinalVersion item = convertImportParamToEntity(param);
|
CreditFinalVersion item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber().trim());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -193,41 +261,20 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditFinalVersionService,
|
creditFinalVersionService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditFinalVersion::getId,
|
chunkRowNumbers,
|
||||||
CreditFinalVersion::setId,
|
mpBatchSize,
|
||||||
CreditFinalVersion::getCaseNumber,
|
CreditFinalVersion::getCaseNumber,
|
||||||
CreditFinalVersion::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditFinalVersionService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditFinalVersion existing = creditFinalVersionService.lambdaQuery()
|
|
||||||
.eq(CreditFinalVersion::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditFinalVersionService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +288,19 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditFinalVersionService,
|
creditFinalVersionService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditFinalVersion::getId,
|
chunkRowNumbers,
|
||||||
CreditFinalVersion::setId,
|
mpBatchSize,
|
||||||
CreditFinalVersion::getCaseNumber,
|
CreditFinalVersion::getCaseNumber,
|
||||||
CreditFinalVersion::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditFinalVersionService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditFinalVersion existing = creditFinalVersionService.lambdaQuery()
|
|
||||||
.eq(CreditFinalVersion::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditFinalVersionService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.FINAL_VERSION, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -288,29 +312,156 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史终本案件(仅解析“历史终本案件”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditFinalVersion:save')")
|
||||||
|
@Operation(summary = "批量导入历史终本案件")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史终本案件");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史终本案件”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditFinalVersionImportParam> importResult = ExcelImportSupport.read(
|
||||||
|
file, CreditFinalVersionImportParam.class, this::isEmptyImportRow, sheetIndex);
|
||||||
|
List<CreditFinalVersionImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditFinalVersion> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditFinalVersionImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditFinalVersion item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditFinalVersionService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditFinalVersion::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditFinalVersionService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditFinalVersion::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.FINAL_VERSION, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载终本案件导入模板
|
* 下载终本案件导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载终本案件导入模板")
|
@Operation(summary = "下载终本案件导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditFinalVersionImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditFinalVersionImportParam example = new CreditFinalVersionImportParam();
|
||||||
example.setDataType("终本案件");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
example.setOtherPartiesThirdParty("第三人示例");
|
||||||
example.setOccurrenceTime("2024-01-01");
|
example.setInvolvedAmount("20,293.91");
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setDataStatus("正常");
|
||||||
example.setCauseOfAction("案由示例");
|
|
||||||
example.setInvolvedAmount("100000");
|
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setOccurrenceTime("2024-01-01");
|
||||||
|
example.setFinalDate("2024-01-01");
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("终本案件导入模板", "终本案件", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("终本案件导入模板", "终本案件", CreditFinalVersionImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_final_version_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_final_version_import_template.xlsx");
|
||||||
@@ -319,29 +470,45 @@ public class CreditFinalVersionController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditFinalVersionImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber());
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditFinalVersion convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditFinalVersion convertImportParamToEntity(CreditFinalVersionImportParam param) {
|
||||||
CreditFinalVersion entity = new CreditFinalVersion();
|
CreditFinalVersion entity = new CreditFinalVersion();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
String plaintiffAppellant = !ImportHelper.isBlank(param.getPlaintiffAppellant2())
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
? param.getPlaintiffAppellant2()
|
||||||
entity.setAppellee(param.getAppellee());
|
: param.getPlaintiffAppellant();
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
String appellee = !ImportHelper.isBlank(param.getAppellee2())
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
? param.getAppellee2()
|
||||||
|
: param.getAppellee();
|
||||||
|
String otherPartiesThirdParty = !ImportHelper.isBlank(param.getOtherPartiesThirdParty())
|
||||||
|
? param.getOtherPartiesThirdParty()
|
||||||
|
: param.getOtherPartiesThirdParty2();
|
||||||
|
String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
|
||||||
|
? param.getInvolvedAmount2()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
String courtName = !ImportHelper.isBlank(param.getCourtName2())
|
||||||
|
? param.getCourtName2()
|
||||||
|
: param.getCourtName();
|
||||||
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
|
? param.getOccurrenceTime2()
|
||||||
|
: param.getOccurrenceTime();
|
||||||
|
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
entity.setPlaintiffAppellant(plaintiffAppellant);
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
entity.setAppellee(appellee);
|
||||||
entity.setCourtName(param.getCourtName());
|
entity.setUnfulfilledAmount(param.getUnfulfilledAmount());
|
||||||
|
entity.setInvolvedAmount(involvedAmount);
|
||||||
|
entity.setOtherPartiesThirdParty(otherPartiesThirdParty);
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
|
entity.setCourtName(courtName);
|
||||||
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
|
entity.setFinalDate(param.getFinalDate());
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import com.gxwebsoft.common.core.web.BatchParam;
|
|||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
import com.gxwebsoft.credit.entity.CreditGqdj;
|
import com.gxwebsoft.credit.entity.CreditGqdj;
|
||||||
|
import com.gxwebsoft.credit.param.CreditGqdjImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditGqdjParam;
|
import com.gxwebsoft.credit.param.CreditGqdjParam;
|
||||||
import com.gxwebsoft.credit.param.CreditJudicialImportParam;
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditGqdjService;
|
import com.gxwebsoft.credit.service.CreditGqdjService;
|
||||||
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;
|
||||||
@@ -22,7 +24,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 股权冻结控制器
|
* 股权冻结控制器
|
||||||
@@ -40,6 +45,12 @@ public class CreditGqdjController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询股权冻结")
|
@Operation(summary = "分页查询股权冻结")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditGqdj>> page(CreditGqdjParam param) {
|
public ApiResult<PageResult<CreditGqdj>> page(CreditGqdjParam param) {
|
||||||
@@ -93,7 +104,7 @@ public class CreditGqdjController extends BaseController {
|
|||||||
@Operation(summary = "删除股权冻结")
|
@Operation(summary = "删除股权冻结")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditGqdjService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditGqdj.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -126,12 +137,53 @@ public class CreditGqdjController extends BaseController {
|
|||||||
@Operation(summary = "批量删除股权冻结")
|
@Operation(summary = "批量删除股权冻结")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditGqdjService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditGqdj.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据当事人/企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId 为空/0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditGqdj:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Match companyId by any party/company-name column (e.g. plaintiff/appellant, defendant/appellee).
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNames(
|
||||||
|
creditGqdjService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditGqdj::getId,
|
||||||
|
CreditGqdj::setId,
|
||||||
|
CreditGqdj::getCompanyId,
|
||||||
|
CreditGqdj::setCompanyId,
|
||||||
|
CreditGqdj::getHasData,
|
||||||
|
CreditGqdj::setHasData,
|
||||||
|
CreditGqdj::getTenantId,
|
||||||
|
CreditGqdj::new,
|
||||||
|
CreditGqdj::getPlaintiffAppellant,
|
||||||
|
CreditGqdj::getAppellee
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入股权冻结司法大数据
|
* 批量导入股权冻结司法大数据
|
||||||
*/
|
*/
|
||||||
@@ -142,13 +194,42 @@ public class CreditGqdjController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditJudicialImportParam> importResult = ExcelImportSupport.read(
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "股权冻结", 0);
|
||||||
file, CreditJudicialImportParam.class, this::isEmptyImportRow);
|
// Prefer the "best" header configuration; many upstream files have extra title rows or multi-row headers.
|
||||||
List<CreditJudicialImportParam> list = importResult.getData();
|
ExcelImportSupport.ImportResult<CreditGqdjImportParam> importResult = ExcelImportSupport.readBest(
|
||||||
|
file,
|
||||||
|
CreditGqdjImportParam.class,
|
||||||
|
this::isEmptyImportRow,
|
||||||
|
// Score rows that look like real data (at least has a case number in either column).
|
||||||
|
p -> p != null
|
||||||
|
&& (!ImportHelper.isBlank(p.getCaseNumber())
|
||||||
|
|| !ImportHelper.isBlank(p.getCaseNumber2())
|
||||||
|
),
|
||||||
|
sheetIndex
|
||||||
|
);
|
||||||
|
List<CreditGqdjImportParam> list = importResult.getData();
|
||||||
int usedTitleRows = importResult.getTitleRows();
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
int usedHeadRows = importResult.getHeadRows();
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
// Fallback: try other sheets if the named/default sheet doesn't match.
|
||||||
|
importResult = ExcelImportSupport.readAnySheetBest(
|
||||||
|
file,
|
||||||
|
CreditGqdjImportParam.class,
|
||||||
|
this::isEmptyImportRow,
|
||||||
|
p -> p != null
|
||||||
|
&& (!ImportHelper.isBlank(p.getCaseNumber())
|
||||||
|
|| !ImportHelper.isBlank(p.getCaseNumber2()))
|
||||||
|
);
|
||||||
|
list = importResult.getData();
|
||||||
|
usedTitleRows = importResult.getTitleRows();
|
||||||
|
usedHeadRows = importResult.getHeadRows();
|
||||||
|
usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
}
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
@@ -157,6 +238,67 @@ public class CreditGqdjController extends BaseController {
|
|||||||
User loginUser = getLoginUser();
|
User loginUser = getLoginUser();
|
||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
// easypoi 默认不会读取单元格超链接地址;url 通常挂在“案号/执行通知文书号”列的超链接中,需要额外读取回填。
|
||||||
|
String caseNumberHeader = "执行通知文书号";
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader);
|
||||||
|
// Some upstream sources use "案号" as the case number header.
|
||||||
|
Map<String, String> urlByCaseNumberFromAh = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
urlByCaseNumberFromAh.forEach(urlByCaseNumber::putIfAbsent);
|
||||||
|
// Some upstream sources use "暗号" as the case number header.
|
||||||
|
Map<String, String> urlByCaseNumberFromAh2 = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号");
|
||||||
|
urlByCaseNumberFromAh2.forEach(urlByCaseNumber::putIfAbsent);
|
||||||
|
// 有些源文件会单独提供“url/网址/链接”等列(可能是纯文本也可能是超链接)
|
||||||
|
Map<String, String> urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "链接");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
// Try again with "案号" as the key column name.
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "链接");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
// Try again with "暗号" as the key column name.
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "链接");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -164,13 +306,26 @@ public class CreditGqdjController extends BaseController {
|
|||||||
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
for (int i = 0; i < list.size(); i++) {
|
for (int i = 0; i < list.size(); i++) {
|
||||||
CreditJudicialImportParam param = list.get(i);
|
CreditGqdjImportParam param = list.get(i);
|
||||||
try {
|
try {
|
||||||
CreditGqdj item = convertImportParamToEntity(param);
|
CreditGqdj item = convertImportParamToEntity(param);
|
||||||
|
if (!ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
String key = item.getCaseNumber().trim();
|
||||||
|
String link = urlByCaseNumber.get(key);
|
||||||
|
if (ImportHelper.isBlank(link)) {
|
||||||
|
link = urlByCaseNumberFromUrlCol.get(key);
|
||||||
|
}
|
||||||
|
if (link != null && !link.isEmpty()) {
|
||||||
|
item.setUrl(link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -193,41 +348,20 @@ public class CreditGqdjController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditGqdjService,
|
creditGqdjService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditGqdj::getId,
|
chunkRowNumbers,
|
||||||
CreditGqdj::setId,
|
mpBatchSize,
|
||||||
CreditGqdj::getCaseNumber,
|
CreditGqdj::getCaseNumber,
|
||||||
CreditGqdj::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditGqdjService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditGqdj existing = creditGqdjService.lambdaQuery()
|
|
||||||
.eq(CreditGqdj::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditGqdjService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -241,42 +375,19 @@ public class CreditGqdjController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
chunkItems,
|
|
||||||
chunkRowNumbers,
|
|
||||||
() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditGqdjService,
|
creditGqdjService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
CreditGqdj::getId,
|
chunkRowNumbers,
|
||||||
CreditGqdj::setId,
|
mpBatchSize,
|
||||||
CreditGqdj::getCaseNumber,
|
CreditGqdj::getCaseNumber,
|
||||||
CreditGqdj::getCaseNumber,
|
"",
|
||||||
null,
|
|
||||||
mpBatchSize
|
|
||||||
),
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditGqdjService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditGqdj existing = creditGqdjService.lambdaQuery()
|
|
||||||
.eq(CreditGqdj::getCaseNumber, rowItem.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditGqdjService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.GQDJ, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
@@ -288,29 +399,219 @@ public class CreditGqdjController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史股权冻结(仅解析“历史股权冻结”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditGqdj:save')")
|
||||||
|
@Operation(summary = "批量导入历史股权冻结司法大数据")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史股权冻结");
|
||||||
|
if (sheetIndex < 0) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史股权冻结”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditGqdjImportParam> importResult = ExcelImportSupport.readBest(
|
||||||
|
file,
|
||||||
|
CreditGqdjImportParam.class,
|
||||||
|
this::isEmptyImportRow,
|
||||||
|
p -> p != null
|
||||||
|
&& (!ImportHelper.isBlank(p.getCaseNumber())
|
||||||
|
|| !ImportHelper.isBlank(p.getCaseNumber2())),
|
||||||
|
sheetIndex
|
||||||
|
);
|
||||||
|
List<CreditGqdjImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
String caseNumberHeader = "执行通知文书号";
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader);
|
||||||
|
Map<String, String> urlByCaseNumberFromAh = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
urlByCaseNumberFromAh.forEach(urlByCaseNumber::putIfAbsent);
|
||||||
|
Map<String, String> urlByCaseNumberFromAh2 = ExcelImportSupport.readHyperlinksByHeaderKey(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号");
|
||||||
|
urlByCaseNumberFromAh2.forEach(urlByCaseNumber::putIfAbsent);
|
||||||
|
Map<String, String> urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, caseNumberHeader, "链接");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号", "链接");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "url");
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "URL");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "网址");
|
||||||
|
}
|
||||||
|
if (urlByCaseNumberFromUrlCol.isEmpty()) {
|
||||||
|
urlByCaseNumberFromUrlCol = ExcelImportSupport.readKeyValueByHeaders(
|
||||||
|
file, usedSheetIndex, usedTitleRows, usedHeadRows, "暗号", "链接");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditGqdj> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditGqdjImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditGqdj item = convertImportParamToEntity(param);
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String key = item.getCaseNumber();
|
||||||
|
String link = urlByCaseNumber.get(key);
|
||||||
|
if (ImportHelper.isBlank(link)) {
|
||||||
|
link = urlByCaseNumberFromUrlCol.get(key);
|
||||||
|
}
|
||||||
|
if (!ImportHelper.isBlank(link)) {
|
||||||
|
item.setUrl(link.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataType("失效");
|
||||||
|
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditGqdjService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditGqdj::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditGqdjService,
|
||||||
|
chunkItems,
|
||||||
|
chunkRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditGqdj::getCaseNumber,
|
||||||
|
"",
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.GQDJ, touchedCompanyIds);
|
||||||
|
|
||||||
|
if (errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "条", errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载股权冻结导入模板
|
* 下载股权冻结导入模板
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载股权冻结导入模板")
|
@Operation(summary = "下载股权冻结导入模板")
|
||||||
@GetMapping("/import/template")
|
@GetMapping("/import/template")
|
||||||
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
List<CreditJudicialImportParam> templateList = new ArrayList<>();
|
List<CreditGqdjImportParam> templateList = new ArrayList<>();
|
||||||
|
|
||||||
CreditJudicialImportParam example = new CreditJudicialImportParam();
|
CreditGqdjImportParam example = new CreditGqdjImportParam();
|
||||||
example.setDataType("股权冻结");
|
example.setDataType("股权冻结");
|
||||||
example.setPlaintiffAppellant("原告示例");
|
example.setPlaintiffAppellant("原告示例");
|
||||||
example.setAppellee("被告示例");
|
example.setAppellee("被告示例");
|
||||||
example.setOtherPartiesThirdParty("第三人示例");
|
|
||||||
example.setOccurrenceTime("2024-01-01");
|
|
||||||
example.setCaseNumber("(2024)示例案号");
|
example.setCaseNumber("(2024)示例案号");
|
||||||
example.setCauseOfAction("案由示例");
|
|
||||||
example.setInvolvedAmount("100000");
|
example.setInvolvedAmount("100000");
|
||||||
example.setCourtName("示例法院");
|
example.setCourtName("示例法院");
|
||||||
example.setDataStatus("已公开");
|
example.setDataStatus("已公开");
|
||||||
example.setComments("备注信息");
|
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
|
|
||||||
Workbook workbook = ExcelImportSupport.buildTemplate("股权冻结导入模板", "股权冻结", CreditJudicialImportParam.class, templateList);
|
Workbook workbook = ExcelImportSupport.buildTemplate("股权冻结导入模板", "股权冻结", CreditGqdjImportParam.class, templateList);
|
||||||
|
|
||||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
response.setHeader("Content-Disposition", "attachment; filename=credit_gqdj_import_template.xlsx");
|
response.setHeader("Content-Disposition", "attachment; filename=credit_gqdj_import_template.xlsx");
|
||||||
@@ -319,30 +620,65 @@ public class CreditGqdjController extends BaseController {
|
|||||||
workbook.close();
|
workbook.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isEmptyImportRow(CreditJudicialImportParam param) {
|
private boolean isEmptyImportRow(CreditGqdjImportParam param) {
|
||||||
if (param == null) {
|
if (param == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// Don't over-filter here: if some columns are mapped but case number header differs,
|
||||||
|
// we still want to read the row and report "案号不能为空" instead of "未读取到数据".
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber())
|
||||||
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
&& ImportHelper.isBlank(param.getCaseNumber2())
|
||||||
&& ImportHelper.isBlank(param.getAppellee())
|
&& ImportHelper.isBlank(param.getAppellee())
|
||||||
&& ImportHelper.isBlank(param.getCauseOfAction());
|
&& ImportHelper.isBlank(param.getAppellee2())
|
||||||
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant())
|
||||||
|
&& ImportHelper.isBlank(param.getPlaintiffAppellant2())
|
||||||
|
&& ImportHelper.isBlank(param.getInvolvedAmount())
|
||||||
|
&& ImportHelper.isBlank(param.getCourtName())
|
||||||
|
&& ImportHelper.isBlank(param.getDataType())
|
||||||
|
&& ImportHelper.isBlank(param.getDataStatus())
|
||||||
|
&& ImportHelper.isBlank(param.getDataStatus2())
|
||||||
|
&& ImportHelper.isBlank(param.getFreezeDateStart())
|
||||||
|
&& ImportHelper.isBlank(param.getFreezeDateEnd())
|
||||||
|
&& ImportHelper.isBlank(param.getFreezeDateStart2())
|
||||||
|
&& ImportHelper.isBlank(param.getFreezeDateEnd2())
|
||||||
|
&& ImportHelper.isBlank(param.getPublicDate());
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreditGqdj convertImportParamToEntity(CreditJudicialImportParam param) {
|
private CreditGqdj convertImportParamToEntity(CreditGqdjImportParam param) {
|
||||||
CreditGqdj entity = new CreditGqdj();
|
CreditGqdj entity = new CreditGqdj();
|
||||||
|
|
||||||
entity.setDataType(param.getDataType());
|
// Template compatibility: some sources use alternate headers for the same columns.
|
||||||
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
String appellee = !ImportHelper.isBlank(param.getAppellee()) ? param.getAppellee() : param.getAppellee2();
|
||||||
entity.setAppellee(param.getAppellee());
|
String plaintiffAppellant = !ImportHelper.isBlank(param.getPlaintiffAppellant())
|
||||||
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
? param.getPlaintiffAppellant()
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
: param.getPlaintiffAppellant2();
|
||||||
|
|
||||||
|
if (!ImportHelper.isBlank(param.getCaseNumber2())) {
|
||||||
|
entity.setCaseNumber(param.getCaseNumber2());
|
||||||
|
} else {
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setCauseOfAction(param.getCauseOfAction());
|
}
|
||||||
|
entity.setAppellee(appellee);
|
||||||
|
entity.setPlaintiffAppellant(plaintiffAppellant);
|
||||||
entity.setInvolvedAmount(param.getInvolvedAmount());
|
entity.setInvolvedAmount(param.getInvolvedAmount());
|
||||||
entity.setCourtName(param.getCourtName());
|
entity.setCourtName(param.getCourtName());
|
||||||
|
if (!ImportHelper.isBlank(param.getDataStatus2())) {
|
||||||
|
entity.setDataStatus(param.getDataStatus2());
|
||||||
|
} else {
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
entity.setComments(param.getComments());
|
}
|
||||||
|
entity.setDataType(param.getDataType());
|
||||||
|
entity.setPublicDate(param.getPublicDate());
|
||||||
|
if (!ImportHelper.isBlank(param.getFreezeDateStart2())) {
|
||||||
|
entity.setFreezeDateStart(param.getFreezeDateStart2());
|
||||||
|
} else {
|
||||||
|
entity.setFreezeDateStart(param.getFreezeDateStart());
|
||||||
|
}
|
||||||
|
if (!ImportHelper.isBlank(param.getFreezeDateEnd2())) {
|
||||||
|
entity.setFreezeDateEnd(param.getFreezeDateEnd2());
|
||||||
|
} else {
|
||||||
|
entity.setFreezeDateEnd(param.getFreezeDateEnd());
|
||||||
|
}
|
||||||
|
|
||||||
return entity;
|
return entity;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import com.gxwebsoft.common.core.web.BaseController;
|
|||||||
import com.gxwebsoft.common.core.web.BatchParam;
|
import com.gxwebsoft.common.core.web.BatchParam;
|
||||||
import com.gxwebsoft.common.core.web.PageResult;
|
import com.gxwebsoft.common.core.web.PageResult;
|
||||||
import com.gxwebsoft.common.system.entity.User;
|
import com.gxwebsoft.common.system.entity.User;
|
||||||
|
import com.gxwebsoft.credit.entity.CreditCompany;
|
||||||
import com.gxwebsoft.credit.entity.CreditHistoricalLegalPerson;
|
import com.gxwebsoft.credit.entity.CreditHistoricalLegalPerson;
|
||||||
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonImportParam;
|
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonParam;
|
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditHistoricalLegalPersonService;
|
import com.gxwebsoft.credit.service.CreditHistoricalLegalPersonService;
|
||||||
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;
|
||||||
@@ -22,8 +25,10 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 历史法定代表人控制器
|
* 历史法定代表人控制器
|
||||||
@@ -41,6 +46,12 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询历史法定代表人")
|
@Operation(summary = "分页查询历史法定代表人")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditHistoricalLegalPerson>> page(CreditHistoricalLegalPersonParam param) {
|
public ApiResult<PageResult<CreditHistoricalLegalPerson>> page(CreditHistoricalLegalPersonParam param) {
|
||||||
@@ -94,7 +105,7 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
@Operation(summary = "删除历史法定代表人")
|
@Operation(summary = "删除历史法定代表人")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditHistoricalLegalPersonService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditHistoricalLegalPerson.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -127,12 +138,52 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
@Operation(summary = "批量删除历史法定代表人")
|
@Operation(summary = "批量删除历史法定代表人")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditHistoricalLegalPersonService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditHistoricalLegalPerson.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
|
||||||
|
creditHistoricalLegalPersonService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditHistoricalLegalPerson::getId,
|
||||||
|
CreditHistoricalLegalPerson::setId,
|
||||||
|
CreditHistoricalLegalPerson::getName,
|
||||||
|
CreditHistoricalLegalPerson::getCompanyId,
|
||||||
|
CreditHistoricalLegalPerson::setCompanyId,
|
||||||
|
CreditHistoricalLegalPerson::setCompanyName,
|
||||||
|
CreditHistoricalLegalPerson::getHasData,
|
||||||
|
CreditHistoricalLegalPerson::setHasData,
|
||||||
|
CreditHistoricalLegalPerson::getTenantId,
|
||||||
|
CreditHistoricalLegalPerson::new
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入历史法定代表人
|
* 批量导入历史法定代表人
|
||||||
*/
|
*/
|
||||||
@@ -143,6 +194,7 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ExcelImportSupport.ImportResult<CreditHistoricalLegalPersonImportParam> importResult = ExcelImportSupport.readAnySheet(
|
ExcelImportSupport.ImportResult<CreditHistoricalLegalPersonImportParam> importResult = ExcelImportSupport.readAnySheet(
|
||||||
@@ -160,6 +212,11 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "名称");
|
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "名称");
|
||||||
|
String fixedCompanyName = null;
|
||||||
|
if (companyId != null && companyId > 0) {
|
||||||
|
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
|
||||||
|
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
|
||||||
|
}
|
||||||
|
|
||||||
final int chunkSize = 500;
|
final int chunkSize = 500;
|
||||||
final int mpBatchSize = 500;
|
final int mpBatchSize = 500;
|
||||||
@@ -179,6 +236,9 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
|
|
||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
|
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
|
||||||
|
item.setCompanyName(fixedCompanyName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
@@ -202,89 +262,20 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditHistoricalLegalPersonService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
chunkRowNumbers,
|
chunkRowNumbers,
|
||||||
() -> {
|
mpBatchSize,
|
||||||
// 批内一次查库:按 name in (...) 拉取,再按 registerDate 做内存匹配
|
CreditHistoricalLegalPerson::getName,
|
||||||
List<String> names = new ArrayList<>(chunkItems.size());
|
"",
|
||||||
for (CreditHistoricalLegalPerson it : chunkItems) {
|
|
||||||
if (it != null && !ImportHelper.isBlank(it.getName())) {
|
|
||||||
names.add(it.getName().trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<CreditHistoricalLegalPerson> existingList = names.isEmpty()
|
|
||||||
? new ArrayList<>()
|
|
||||||
: creditHistoricalLegalPersonService.lambdaQuery()
|
|
||||||
.in(CreditHistoricalLegalPerson::getName, names)
|
|
||||||
.list();
|
|
||||||
|
|
||||||
java.util.Map<String, CreditHistoricalLegalPerson> byName = new java.util.HashMap<>();
|
|
||||||
java.util.Map<String, CreditHistoricalLegalPerson> byNameDate = new java.util.HashMap<>();
|
|
||||||
for (CreditHistoricalLegalPerson existing : existingList) {
|
|
||||||
if (existing == null || ImportHelper.isBlank(existing.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String n = existing.getName().trim();
|
|
||||||
byName.putIfAbsent(n, existing);
|
|
||||||
String d = ImportHelper.isBlank(existing.getRegisterDate()) ? null : existing.getRegisterDate().trim();
|
|
||||||
if (d != null) {
|
|
||||||
byNameDate.putIfAbsent(n + "|" + d, existing);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<CreditHistoricalLegalPerson> updates = new ArrayList<>();
|
|
||||||
List<CreditHistoricalLegalPerson> inserts = new ArrayList<>();
|
|
||||||
for (CreditHistoricalLegalPerson it : chunkItems) {
|
|
||||||
if (it == null || ImportHelper.isBlank(it.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String n = it.getName().trim();
|
|
||||||
CreditHistoricalLegalPerson existing;
|
|
||||||
if (!ImportHelper.isBlank(it.getRegisterDate())) {
|
|
||||||
String d = it.getRegisterDate().trim();
|
|
||||||
existing = byNameDate.get(n + "|" + d);
|
|
||||||
} else {
|
|
||||||
existing = byName.get(n);
|
|
||||||
}
|
|
||||||
if (existing != null) {
|
|
||||||
it.setId(existing.getId());
|
|
||||||
updates.add(it);
|
|
||||||
} else {
|
|
||||||
inserts.add(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!updates.isEmpty()) {
|
|
||||||
creditHistoricalLegalPersonService.updateBatchById(updates, mpBatchSize);
|
|
||||||
}
|
|
||||||
if (!inserts.isEmpty()) {
|
|
||||||
creditHistoricalLegalPersonService.saveBatch(inserts, mpBatchSize);
|
|
||||||
}
|
|
||||||
return updates.size() + inserts.size();
|
|
||||||
},
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditHistoricalLegalPersonService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditHistoricalLegalPerson existing = creditHistoricalLegalPersonService.lambdaQuery()
|
|
||||||
.eq(CreditHistoricalLegalPerson::getName, rowItem.getName())
|
|
||||||
.eq(!ImportHelper.isBlank(rowItem.getRegisterDate()), CreditHistoricalLegalPerson::getRegisterDate, rowItem.getRegisterDate())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditHistoricalLegalPersonService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
chunkItems.clear();
|
chunkItems.clear();
|
||||||
@@ -298,89 +289,19 @@ public class CreditHistoricalLegalPersonController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += batchImportSupport.persistChunkWithFallback(
|
successCount += batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditHistoricalLegalPersonService,
|
||||||
chunkItems,
|
chunkItems,
|
||||||
chunkRowNumbers,
|
chunkRowNumbers,
|
||||||
() -> {
|
mpBatchSize,
|
||||||
List<String> names = new ArrayList<>(chunkItems.size());
|
CreditHistoricalLegalPerson::getName,
|
||||||
for (CreditHistoricalLegalPerson it : chunkItems) {
|
"",
|
||||||
if (it != null && !ImportHelper.isBlank(it.getName())) {
|
|
||||||
names.add(it.getName().trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<CreditHistoricalLegalPerson> existingList = names.isEmpty()
|
|
||||||
? new ArrayList<>()
|
|
||||||
: creditHistoricalLegalPersonService.lambdaQuery()
|
|
||||||
.in(CreditHistoricalLegalPerson::getName, names)
|
|
||||||
.list();
|
|
||||||
|
|
||||||
java.util.Map<String, CreditHistoricalLegalPerson> byName = new java.util.HashMap<>();
|
|
||||||
java.util.Map<String, CreditHistoricalLegalPerson> byNameDate = new java.util.HashMap<>();
|
|
||||||
for (CreditHistoricalLegalPerson existing : existingList) {
|
|
||||||
if (existing == null || ImportHelper.isBlank(existing.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String n = existing.getName().trim();
|
|
||||||
byName.putIfAbsent(n, existing);
|
|
||||||
String d = ImportHelper.isBlank(existing.getRegisterDate()) ? null : existing.getRegisterDate().trim();
|
|
||||||
if (d != null) {
|
|
||||||
byNameDate.putIfAbsent(n + "|" + d, existing);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<CreditHistoricalLegalPerson> updates = new ArrayList<>();
|
|
||||||
List<CreditHistoricalLegalPerson> inserts = new ArrayList<>();
|
|
||||||
for (CreditHistoricalLegalPerson it : chunkItems) {
|
|
||||||
if (it == null || ImportHelper.isBlank(it.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String n = it.getName().trim();
|
|
||||||
CreditHistoricalLegalPerson existing;
|
|
||||||
if (!ImportHelper.isBlank(it.getRegisterDate())) {
|
|
||||||
String d = it.getRegisterDate().trim();
|
|
||||||
existing = byNameDate.get(n + "|" + d);
|
|
||||||
} else {
|
|
||||||
existing = byName.get(n);
|
|
||||||
}
|
|
||||||
if (existing != null) {
|
|
||||||
it.setId(existing.getId());
|
|
||||||
updates.add(it);
|
|
||||||
} else {
|
|
||||||
inserts.add(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!updates.isEmpty()) {
|
|
||||||
creditHistoricalLegalPersonService.updateBatchById(updates, mpBatchSize);
|
|
||||||
}
|
|
||||||
if (!inserts.isEmpty()) {
|
|
||||||
creditHistoricalLegalPersonService.saveBatch(inserts, mpBatchSize);
|
|
||||||
}
|
|
||||||
return updates.size() + inserts.size();
|
|
||||||
},
|
|
||||||
(rowItem, rowNumber) -> {
|
|
||||||
boolean saved = creditHistoricalLegalPersonService.save(rowItem);
|
|
||||||
if (!saved) {
|
|
||||||
CreditHistoricalLegalPerson existing = creditHistoricalLegalPersonService.lambdaQuery()
|
|
||||||
.eq(CreditHistoricalLegalPerson::getName, rowItem.getName())
|
|
||||||
.eq(!ImportHelper.isBlank(rowItem.getRegisterDate()), CreditHistoricalLegalPerson::getRegisterDate, rowItem.getRegisterDate())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
rowItem.setId(existing.getId());
|
|
||||||
if (creditHistoricalLegalPersonService.updateById(rowItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String prefix = rowNumber > 0 ? ("第" + rowNumber + "行:") : "";
|
|
||||||
errorMessages.add(prefix + "保存失败");
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
errorMessages
|
errorMessages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.HISTORICAL_LEGAL_PERSON, touchedCompanyIds);
|
||||||
|
|
||||||
if (errorMessages.isEmpty()) {
|
if (errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + successCount + "条数据", null);
|
return success("成功导入" + successCount + "条数据", null);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import com.gxwebsoft.common.system.entity.User;
|
|||||||
import com.gxwebsoft.credit.entity.CreditJudgmentDebtor;
|
import com.gxwebsoft.credit.entity.CreditJudgmentDebtor;
|
||||||
import com.gxwebsoft.credit.param.CreditJudgmentDebtorImportParam;
|
import com.gxwebsoft.credit.param.CreditJudgmentDebtorImportParam;
|
||||||
import com.gxwebsoft.credit.param.CreditJudgmentDebtorParam;
|
import com.gxwebsoft.credit.param.CreditJudgmentDebtorParam;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyService;
|
||||||
|
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
|
||||||
import com.gxwebsoft.credit.service.CreditJudgmentDebtorService;
|
import com.gxwebsoft.credit.service.CreditJudgmentDebtorService;
|
||||||
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;
|
||||||
@@ -29,8 +31,10 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
@@ -50,6 +54,12 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
@Resource
|
@Resource
|
||||||
private BatchImportSupport batchImportSupport;
|
private BatchImportSupport batchImportSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyService creditCompanyService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CreditCompanyRecordCountService creditCompanyRecordCountService;
|
||||||
|
|
||||||
@Operation(summary = "分页查询被执行人")
|
@Operation(summary = "分页查询被执行人")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public ApiResult<PageResult<CreditJudgmentDebtor>> page(CreditJudgmentDebtorParam param) {
|
public ApiResult<PageResult<CreditJudgmentDebtor>> page(CreditJudgmentDebtorParam param) {
|
||||||
@@ -103,7 +113,7 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
@Operation(summary = "删除被执行人")
|
@Operation(summary = "删除被执行人")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||||
if (creditJudgmentDebtorService.removeById(id)) {
|
if (batchImportSupport.hardRemoveById(CreditJudgmentDebtor.class, id)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
@@ -136,12 +146,62 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
@Operation(summary = "批量删除被执行人")
|
@Operation(summary = "批量删除被执行人")
|
||||||
@DeleteMapping("/batch")
|
@DeleteMapping("/batch")
|
||||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||||
if (creditJudgmentDebtorService.removeByIds(ids)) {
|
if (batchImportSupport.hardRemoveByIds(CreditJudgmentDebtor.class, ids)) {
|
||||||
return success("删除成功");
|
return success("删除成功");
|
||||||
}
|
}
|
||||||
return fail("删除失败");
|
return fail("删除失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据企业名称匹配企业并更新 companyId(匹配 CreditCompany.name / CreditCompany.matchName)
|
||||||
|
*
|
||||||
|
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditJudgmentDebtor:update')")
|
||||||
|
@OperationLog
|
||||||
|
@Operation(summary = "根据企业名称匹配并更新companyId")
|
||||||
|
@PostMapping("/company-id/refresh")
|
||||||
|
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
|
||||||
|
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit,
|
||||||
|
@RequestParam(value = "topLevelOnly", required = false, defaultValue = "true") Boolean topLevelOnly
|
||||||
|
) {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
// Match only on "name" column: debtor.name contains a (top-level) CreditCompany name/matchName.
|
||||||
|
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyNameContainedInText(
|
||||||
|
creditJudgmentDebtorService,
|
||||||
|
creditCompanyService,
|
||||||
|
currentTenantId,
|
||||||
|
onlyNull,
|
||||||
|
limit,
|
||||||
|
CreditJudgmentDebtor::getId,
|
||||||
|
CreditJudgmentDebtor::setId,
|
||||||
|
CreditJudgmentDebtor::getCompanyId,
|
||||||
|
CreditJudgmentDebtor::setCompanyId,
|
||||||
|
CreditJudgmentDebtor::getHasData,
|
||||||
|
CreditJudgmentDebtor::setHasData,
|
||||||
|
CreditJudgmentDebtor::getTenantId,
|
||||||
|
CreditJudgmentDebtor::new,
|
||||||
|
q -> {
|
||||||
|
if (!Boolean.TRUE.equals(topLevelOnly)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// "一级企业":parentId=0(部分历史数据可能为 NULL,兼容处理)
|
||||||
|
q.and(w -> w.eq(com.gxwebsoft.credit.entity.CreditCompany::getParentId, 0)
|
||||||
|
.or()
|
||||||
|
.isNull(com.gxwebsoft.credit.entity.CreditCompany::getParentId));
|
||||||
|
},
|
||||||
|
CreditJudgmentDebtor::getName
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!stats.anyDataRead) {
|
||||||
|
return success("无可更新数据", stats.toMap());
|
||||||
|
}
|
||||||
|
return success("更新完成,更新" + stats.updated + "条", stats.toMap());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量导入被执行人
|
* 批量导入被执行人
|
||||||
*/
|
*/
|
||||||
@@ -165,6 +225,46 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
if (!outcome.anyDataRead) {
|
if (!outcome.anyDataRead) {
|
||||||
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.JUDGMENT_DEBTOR, outcome.touchedCompanyIds);
|
||||||
|
|
||||||
|
if (outcome.errorMessages.isEmpty()) {
|
||||||
|
return success("成功导入" + outcome.successCount + "条数据", null);
|
||||||
|
}
|
||||||
|
return success("导入完成,成功" + outcome.successCount + "条,失败" + outcome.errorMessages.size() + "条", outcome.errorMessages);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return fail("导入失败:" + e.getMessage(), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量导入历史被执行人(写入被执行人表 credit_judgment_debtor,仅解析“历史被执行人”选项卡)
|
||||||
|
* 规则:使用数据库唯一索引约束,重复数据不导入。
|
||||||
|
*/
|
||||||
|
@PreAuthorize("hasAuthority('credit:creditJudgmentDebtor:save')")
|
||||||
|
@Operation(summary = "批量导入历史被执行人")
|
||||||
|
@PostMapping("/import/history")
|
||||||
|
public ApiResult<List<String>> importHistoryBatch(@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "companyId", required = false) Integer companyId) {
|
||||||
|
try {
|
||||||
|
User loginUser = getLoginUser();
|
||||||
|
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
|
||||||
|
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
|
||||||
|
|
||||||
|
ImportOutcome outcome;
|
||||||
|
if (isZip(file)) {
|
||||||
|
outcome = importHistoryFromZip(file, currentUserId, currentTenantId, companyId);
|
||||||
|
} else {
|
||||||
|
outcome = importHistoryFromExcel(file, safeFileLabel(file.getOriginalFilename()), currentUserId, currentTenantId, companyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!outcome.anyDataRead) {
|
||||||
|
return fail("未读取到数据,请确认文件中存在“历史被执行人”选项卡且表头与示例格式一致", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.JUDGMENT_DEBTOR, outcome.touchedCompanyIds);
|
||||||
|
|
||||||
if (outcome.errorMessages.isEmpty()) {
|
if (outcome.errorMessages.isEmpty()) {
|
||||||
return success("成功导入" + outcome.successCount + "条数据", null);
|
return success("成功导入" + outcome.successCount + "条数据", null);
|
||||||
}
|
}
|
||||||
@@ -188,7 +288,6 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
example.setName("某某公司");
|
example.setName("某某公司");
|
||||||
example.setCode("1234567890");
|
example.setCode("1234567890");
|
||||||
example.setOccurrenceTime("2024-01-10");
|
example.setOccurrenceTime("2024-01-10");
|
||||||
example.setAmount("100000");
|
|
||||||
example.setDataStatus("已公开");
|
example.setDataStatus("已公开");
|
||||||
example.setComments("备注信息");
|
example.setComments("备注信息");
|
||||||
templateList.add(example);
|
templateList.add(example);
|
||||||
@@ -209,10 +308,7 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
if (isImportHeaderRow(param)) {
|
if (isImportHeaderRow(param)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ImportHelper.isBlank(param.getCaseNumber())
|
return ImportHelper.isBlank(param.getCaseNumber());
|
||||||
&& ImportHelper.isBlank(param.getName())
|
|
||||||
&& ImportHelper.isBlank(param.getName1())
|
|
||||||
&& ImportHelper.isBlank(param.getCode());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isImportHeaderRow(CreditJudgmentDebtorImportParam param) {
|
private boolean isImportHeaderRow(CreditJudgmentDebtorImportParam param) {
|
||||||
@@ -224,7 +320,9 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
|| isHeaderValue(param.getCode(), "证件号/组织机构代码")
|
|| isHeaderValue(param.getCode(), "证件号/组织机构代码")
|
||||||
|| isHeaderValue(param.getOccurrenceTime(), "立案日期")
|
|| isHeaderValue(param.getOccurrenceTime(), "立案日期")
|
||||||
|| isHeaderValue(param.getCourtName(), "法院")
|
|| isHeaderValue(param.getCourtName(), "法院")
|
||||||
|| isHeaderValue(param.getAmount(), "执行标的(元)")
|
|| isHeaderValue(param.getCourtNameQcc(), "执行法院")
|
||||||
|
|| isHeaderValue(param.getInvolvedAmount(), "涉案金额")
|
||||||
|
|| isHeaderValue(param.getInvolvedAmountQcc(), "执行标的(元)")
|
||||||
|| isHeaderValue(param.getDataStatus(), "数据状态");
|
|| isHeaderValue(param.getDataStatus(), "数据状态");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,17 +333,56 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
return headerText.equals(value.trim());
|
return headerText.equals(value.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean hasMeaningfulPartyValue(String value) {
|
||||||
|
if (ImportHelper.isBlank(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return !"-".equals(value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
private CreditJudgmentDebtor convertImportParamToEntity(CreditJudgmentDebtorImportParam param) {
|
private CreditJudgmentDebtor convertImportParamToEntity(CreditJudgmentDebtorImportParam param) {
|
||||||
CreditJudgmentDebtor entity = new CreditJudgmentDebtor();
|
CreditJudgmentDebtor entity = new CreditJudgmentDebtor();
|
||||||
|
|
||||||
entity.setCaseNumber(param.getCaseNumber());
|
entity.setCaseNumber(param.getCaseNumber());
|
||||||
entity.setName1(param.getName1());
|
entity.setName1(param.getName1());
|
||||||
String debtorName = ImportHelper.isBlank(param.getName()) ? param.getName1() : param.getName();
|
String debtorName = ImportHelper.isBlank(param.getName()) ? param.getName1() : param.getName();
|
||||||
|
if (debtorName != null) {
|
||||||
|
debtorName = debtorName.trim();
|
||||||
|
}
|
||||||
|
entity.setPlaintiffAppellant(param.getPlaintiffAppellant());
|
||||||
|
entity.setAppellee(param.getAppellee());
|
||||||
|
entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
|
||||||
|
// Some upstream XLS templates store party/company name in "原告/上诉人/被告/第三人" columns.
|
||||||
|
// When present, use them to populate the debtor "name" for compatibility.
|
||||||
|
if (hasMeaningfulPartyValue(param.getPlaintiffAppellant())) {
|
||||||
|
debtorName = param.getPlaintiffAppellant().trim();
|
||||||
|
} else if (hasMeaningfulPartyValue(param.getAppellee())) {
|
||||||
|
debtorName = param.getAppellee().trim();
|
||||||
|
} else if (hasMeaningfulPartyValue(param.getOtherPartiesThirdParty())) {
|
||||||
|
debtorName = param.getOtherPartiesThirdParty().trim();
|
||||||
|
}
|
||||||
entity.setName(debtorName);
|
entity.setName(debtorName);
|
||||||
entity.setCode(param.getCode());
|
entity.setCode(param.getCode());
|
||||||
entity.setOccurrenceTime(param.getOccurrenceTime());
|
String occurrenceTime = !ImportHelper.isBlank(param.getOccurrenceTime2())
|
||||||
entity.setAmount(param.getAmount());
|
? param.getOccurrenceTime2().trim()
|
||||||
entity.setCourtName(param.getCourtName());
|
: (param.getOccurrenceTime() != null ? param.getOccurrenceTime().trim() : null);
|
||||||
|
entity.setOccurrenceTime(occurrenceTime);
|
||||||
|
// 兼容企查查历史被执行人:执行标的(元) / 执行法院
|
||||||
|
String amount = !ImportHelper.isBlank(param.getInvolvedAmountQcc())
|
||||||
|
? param.getInvolvedAmountQcc()
|
||||||
|
: param.getInvolvedAmount();
|
||||||
|
if (amount != null) {
|
||||||
|
amount = amount.trim();
|
||||||
|
}
|
||||||
|
entity.setAmount(amount);
|
||||||
|
|
||||||
|
String courtName = !ImportHelper.isBlank(param.getCourtName())
|
||||||
|
? param.getCourtName()
|
||||||
|
: param.getCourtNameQcc();
|
||||||
|
if (courtName != null) {
|
||||||
|
courtName = courtName.trim();
|
||||||
|
}
|
||||||
|
entity.setCourtName(courtName);
|
||||||
entity.setDataStatus(param.getDataStatus());
|
entity.setDataStatus(param.getDataStatus());
|
||||||
entity.setComments(param.getComments());
|
entity.setComments(param.getComments());
|
||||||
|
|
||||||
@@ -256,17 +393,20 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
private final boolean anyDataRead;
|
private final boolean anyDataRead;
|
||||||
private final int successCount;
|
private final int successCount;
|
||||||
private final List<String> errorMessages;
|
private final List<String> errorMessages;
|
||||||
|
private final Set<Integer> touchedCompanyIds;
|
||||||
|
|
||||||
private ImportOutcome(boolean anyDataRead, int successCount, List<String> errorMessages) {
|
private ImportOutcome(boolean anyDataRead, int successCount, List<String> errorMessages, Set<Integer> touchedCompanyIds) {
|
||||||
this.anyDataRead = anyDataRead;
|
this.anyDataRead = anyDataRead;
|
||||||
this.successCount = successCount;
|
this.successCount = successCount;
|
||||||
this.errorMessages = errorMessages;
|
this.errorMessages = errorMessages;
|
||||||
|
this.touchedCompanyIds = touchedCompanyIds != null ? touchedCompanyIds : new HashSet<>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ImportOutcome importFromExcel(MultipartFile excelFile, String fileLabel, Integer currentUserId, Integer currentTenantId, Integer companyId, boolean strictDebtorSheet) throws Exception {
|
private ImportOutcome importFromExcel(MultipartFile excelFile, String fileLabel, Integer currentUserId, Integer currentTenantId, Integer companyId, boolean strictDebtorSheet) throws Exception {
|
||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
ExcelImportSupport.ImportResult<CreditJudgmentDebtorImportParam> importResult = readDebtorImport(excelFile, strictDebtorSheet);
|
ExcelImportSupport.ImportResult<CreditJudgmentDebtorImportParam> importResult = readDebtorImport(excelFile, strictDebtorSheet);
|
||||||
List<CreditJudgmentDebtorImportParam> list = importResult.getData();
|
List<CreditJudgmentDebtorImportParam> list = importResult.getData();
|
||||||
@@ -275,7 +415,7 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
int usedSheetIndex = importResult.getSheetIndex();
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
if (CollectionUtils.isEmpty(list)) {
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
return new ImportOutcome(false, 0, errorMessages);
|
return new ImportOutcome(false, 0, errorMessages, touchedCompanyIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(excelFile, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(excelFile, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
@@ -308,6 +448,9 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
if (item.getCompanyId() == null && companyId != null) {
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
item.setCompanyId(companyId);
|
item.setCompanyId(companyId);
|
||||||
}
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
if (item.getUserId() == null && currentUserId != null) {
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
item.setUserId(currentUserId);
|
item.setUserId(currentUserId);
|
||||||
}
|
}
|
||||||
@@ -329,6 +472,10 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
|
||||||
chunkItems.add(item);
|
chunkItems.add(item);
|
||||||
chunkRowNumbers.add(excelRowNumber);
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
if (chunkItems.size() >= chunkSize) {
|
if (chunkItems.size() >= chunkSize) {
|
||||||
@@ -345,7 +492,129 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
if (!chunkItems.isEmpty()) {
|
if (!chunkItems.isEmpty()) {
|
||||||
successCount += persistImportChunk(chunkItems, chunkRowNumbers, prefix, mpBatchSize, errorMessages);
|
successCount += persistImportChunk(chunkItems, chunkRowNumbers, prefix, mpBatchSize, errorMessages);
|
||||||
}
|
}
|
||||||
return new ImportOutcome(true, successCount, errorMessages);
|
return new ImportOutcome(true, successCount, errorMessages, touchedCompanyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ImportOutcome importHistoryFromExcel(MultipartFile excelFile, String fileLabel, Integer currentUserId, Integer currentTenantId, Integer companyId) throws Exception {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
int historySheetIndex = ExcelImportSupport.findSheetIndex(excelFile, "历史被执行人");
|
||||||
|
if (historySheetIndex < 0) {
|
||||||
|
return new ImportOutcome(false, 0, errorMessages, touchedCompanyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExcelImportSupport.ImportResult<CreditJudgmentDebtorImportParam> importResult = ExcelImportSupport.readBest(
|
||||||
|
excelFile,
|
||||||
|
CreditJudgmentDebtorImportParam.class,
|
||||||
|
this::isEmptyImportRow,
|
||||||
|
this::isScoreImportRow,
|
||||||
|
historySheetIndex
|
||||||
|
);
|
||||||
|
|
||||||
|
List<CreditJudgmentDebtorImportParam> list = importResult.getData();
|
||||||
|
int usedTitleRows = importResult.getTitleRows();
|
||||||
|
int usedHeadRows = importResult.getHeadRows();
|
||||||
|
int usedSheetIndex = importResult.getSheetIndex();
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(list)) {
|
||||||
|
return new ImportOutcome(false, 0, errorMessages, touchedCompanyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> urlByCaseNumber = ExcelImportSupport.readHyperlinksByHeaderKey(excelFile, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
|
||||||
|
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(excelFile, usedSheetIndex, usedTitleRows, usedHeadRows, "被执行人名称");
|
||||||
|
Map<String, String> urlByName1 = ExcelImportSupport.readHyperlinksByHeaderKey(excelFile, usedSheetIndex, usedTitleRows, usedHeadRows, "被执行人");
|
||||||
|
|
||||||
|
String prefix = ImportHelper.isBlank(fileLabel) ? "" : "【" + fileLabel + "】";
|
||||||
|
final int chunkSize = 500;
|
||||||
|
final int mpBatchSize = 500;
|
||||||
|
List<CreditJudgmentDebtor> chunkItems = new ArrayList<>(chunkSize);
|
||||||
|
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
CreditJudgmentDebtorImportParam param = list.get(i);
|
||||||
|
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
|
||||||
|
try {
|
||||||
|
CreditJudgmentDebtor item = convertImportParamToEntity(param);
|
||||||
|
|
||||||
|
if (item.getCaseNumber() != null) {
|
||||||
|
item.setCaseNumber(item.getCaseNumber().trim());
|
||||||
|
}
|
||||||
|
if (ImportHelper.isBlank(item.getCaseNumber())) {
|
||||||
|
errorMessages.add(prefix + "第" + excelRowNumber + "行:案号不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String link = urlByCaseNumber.get(item.getCaseNumber());
|
||||||
|
if ((link == null || link.isEmpty()) && !ImportHelper.isBlank(item.getName())) {
|
||||||
|
link = urlByName.get(item.getName().trim());
|
||||||
|
}
|
||||||
|
if ((link == null || link.isEmpty()) && !ImportHelper.isBlank(item.getName1())) {
|
||||||
|
link = urlByName1.get(item.getName1().trim());
|
||||||
|
}
|
||||||
|
if (link != null && !link.isEmpty()) {
|
||||||
|
item.setUrl(link);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.getCompanyId() == null && companyId != null) {
|
||||||
|
item.setCompanyId(companyId);
|
||||||
|
}
|
||||||
|
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
|
||||||
|
touchedCompanyIds.add(item.getCompanyId());
|
||||||
|
}
|
||||||
|
if (item.getUserId() == null && currentUserId != null) {
|
||||||
|
item.setUserId(currentUserId);
|
||||||
|
}
|
||||||
|
if (item.getTenantId() == null && currentTenantId != null) {
|
||||||
|
item.setTenantId(currentTenantId);
|
||||||
|
}
|
||||||
|
if (item.getStatus() == null) {
|
||||||
|
item.setStatus(0);
|
||||||
|
}
|
||||||
|
if (item.getRecommend() == null) {
|
||||||
|
item.setRecommend(0);
|
||||||
|
}
|
||||||
|
if (item.getDeleted() == null) {
|
||||||
|
item.setDeleted(0);
|
||||||
|
}
|
||||||
|
// 历史导入的数据统一标记为“失效”
|
||||||
|
item.setDataStatus("失效");
|
||||||
|
|
||||||
|
chunkItems.add(item);
|
||||||
|
chunkRowNumbers.add(excelRowNumber);
|
||||||
|
if (chunkItems.size() >= chunkSize) {
|
||||||
|
successCount += persistHistoryImportChunk(chunkItems, chunkRowNumbers, prefix, mpBatchSize, errorMessages);
|
||||||
|
chunkItems.clear();
|
||||||
|
chunkRowNumbers.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add(prefix + "第" + excelRowNumber + "行:" + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chunkItems.isEmpty()) {
|
||||||
|
successCount += persistHistoryImportChunk(chunkItems, chunkRowNumbers, prefix, mpBatchSize, errorMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ImportOutcome(true, successCount, errorMessages, touchedCompanyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int persistHistoryImportChunk(List<CreditJudgmentDebtor> items,
|
||||||
|
List<Integer> excelRowNumbers,
|
||||||
|
String prefix,
|
||||||
|
int mpBatchSize,
|
||||||
|
List<String> errorMessages) {
|
||||||
|
return batchImportSupport.persistInsertOnlyChunk(
|
||||||
|
creditJudgmentDebtorService,
|
||||||
|
items,
|
||||||
|
excelRowNumbers,
|
||||||
|
mpBatchSize,
|
||||||
|
CreditJudgmentDebtor::getCaseNumber,
|
||||||
|
prefix,
|
||||||
|
errorMessages
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int persistImportChunk(List<CreditJudgmentDebtor> items,
|
private int persistImportChunk(List<CreditJudgmentDebtor> items,
|
||||||
@@ -353,54 +622,15 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
String prefix,
|
String prefix,
|
||||||
int mpBatchSize,
|
int mpBatchSize,
|
||||||
List<String> errorMessages) {
|
List<String> errorMessages) {
|
||||||
if (CollectionUtils.isEmpty(items)) {
|
return batchImportSupport.persistInsertOnlyChunk(
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return batchImportSupport.runInNewTx(() -> batchImportSupport.upsertBySingleKey(
|
|
||||||
creditJudgmentDebtorService,
|
creditJudgmentDebtorService,
|
||||||
items,
|
items,
|
||||||
CreditJudgmentDebtor::getId,
|
excelRowNumbers,
|
||||||
CreditJudgmentDebtor::setId,
|
mpBatchSize,
|
||||||
CreditJudgmentDebtor::getCaseNumber,
|
CreditJudgmentDebtor::getCaseNumber,
|
||||||
CreditJudgmentDebtor::getCaseNumber,
|
prefix,
|
||||||
null,
|
errorMessages
|
||||||
mpBatchSize
|
);
|
||||||
));
|
|
||||||
} catch (Exception batchException) {
|
|
||||||
int successCount = 0;
|
|
||||||
for (int i = 0; i < items.size(); i++) {
|
|
||||||
CreditJudgmentDebtor item = items.get(i);
|
|
||||||
int excelRowNumber = (excelRowNumbers != null && i < excelRowNumbers.size()) ? excelRowNumbers.get(i) : -1;
|
|
||||||
try {
|
|
||||||
int delta = batchImportSupport.runInNewTx(() -> {
|
|
||||||
boolean saved = creditJudgmentDebtorService.save(item);
|
|
||||||
if (!saved) {
|
|
||||||
CreditJudgmentDebtor existing = creditJudgmentDebtorService.lambdaQuery()
|
|
||||||
.eq(CreditJudgmentDebtor::getCaseNumber, item.getCaseNumber())
|
|
||||||
.one();
|
|
||||||
if (existing != null) {
|
|
||||||
item.setId(existing.getId());
|
|
||||||
if (creditJudgmentDebtorService.updateById(item)) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
});
|
|
||||||
if (delta > 0) {
|
|
||||||
successCount += delta;
|
|
||||||
} else {
|
|
||||||
errorMessages.add(prefix + "第" + excelRowNumber + "行:保存失败");
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
errorMessages.add(prefix + "第" + excelRowNumber + "行:" + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return successCount;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ImportOutcome importFromZip(MultipartFile zipFile, Integer currentUserId, Integer currentTenantId, Integer companyId) throws Exception {
|
private ImportOutcome importFromZip(MultipartFile zipFile, Integer currentUserId, Integer currentTenantId, Integer companyId) throws Exception {
|
||||||
@@ -415,6 +645,7 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
List<String> errorMessages = new ArrayList<>();
|
List<String> errorMessages = new ArrayList<>();
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
boolean anyDataRead = false;
|
boolean anyDataRead = false;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
try (InputStream is = zipFile.getInputStream(); ZipInputStream zis = new ZipInputStream(is, charset)) {
|
try (InputStream is = zipFile.getInputStream(); ZipInputStream zis = new ZipInputStream(is, charset)) {
|
||||||
ZipEntry entry;
|
ZipEntry entry;
|
||||||
@@ -437,13 +668,59 @@ public class CreditJudgmentDebtorController extends BaseController {
|
|||||||
anyDataRead = true;
|
anyDataRead = true;
|
||||||
successCount += outcome.successCount;
|
successCount += outcome.successCount;
|
||||||
errorMessages.addAll(outcome.errorMessages);
|
errorMessages.addAll(outcome.errorMessages);
|
||||||
|
touchedCompanyIds.addAll(outcome.touchedCompanyIds);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
errorMessages.add("【" + entryFileName + "】解析失败:" + e.getMessage());
|
errorMessages.add("【" + entryFileName + "】解析失败:" + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new ImportOutcome(anyDataRead, successCount, errorMessages);
|
return new ImportOutcome(anyDataRead, successCount, errorMessages, touchedCompanyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ImportOutcome importHistoryFromZip(MultipartFile zipFile, Integer currentUserId, Integer currentTenantId, Integer companyId) throws Exception {
|
||||||
|
try {
|
||||||
|
return importHistoryFromZip(zipFile, currentUserId, currentTenantId, companyId, StandardCharsets.UTF_8);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return importHistoryFromZip(zipFile, currentUserId, currentTenantId, companyId, Charset.forName("GBK"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ImportOutcome importHistoryFromZip(MultipartFile zipFile, Integer currentUserId, Integer currentTenantId, Integer companyId, Charset charset) throws Exception {
|
||||||
|
List<String> errorMessages = new ArrayList<>();
|
||||||
|
int successCount = 0;
|
||||||
|
boolean anyDataRead = false;
|
||||||
|
Set<Integer> touchedCompanyIds = new HashSet<>();
|
||||||
|
|
||||||
|
try (InputStream is = zipFile.getInputStream(); ZipInputStream zis = new ZipInputStream(is, charset)) {
|
||||||
|
ZipEntry entry;
|
||||||
|
while ((entry = zis.getNextEntry()) != null) {
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String entryName = entry.getName();
|
||||||
|
if (!isExcelFileName(entryName)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] bytes = readAllBytes(zis);
|
||||||
|
String entryFileName = safeFileLabel(entryName);
|
||||||
|
MultipartFile excelFile = new InMemoryMultipartFile(entryFileName, bytes);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ImportOutcome outcome = importHistoryFromExcel(excelFile, entryFileName, currentUserId, currentTenantId, companyId);
|
||||||
|
if (outcome.anyDataRead) {
|
||||||
|
anyDataRead = true;
|
||||||
|
successCount += outcome.successCount;
|
||||||
|
errorMessages.addAll(outcome.errorMessages);
|
||||||
|
touchedCompanyIds.addAll(outcome.touchedCompanyIds);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMessages.add("【" + entryFileName + "】解析失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ImportOutcome(anyDataRead, successCount, errorMessages, touchedCompanyIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isZip(MultipartFile file) {
|
private static boolean isZip(MultipartFile file) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user