refactor: 重构了项目结构,拆分出parent,common,legacy,sms,aicc模块

- parent: 管理公共依赖
- common: 可公用的代码
- legacy: 原气象预警和责任人管理
- sms: 给防汛专家发送生日和节日短信
- aicc: 联通智能外呼,代码拆分出了模块,但是功能未调试
refactor
李一帆 2025-10-30 15:22:38 +08:00
parent 7f2b3458c4
commit 6398fe6ea4
251 changed files with 19884 additions and 187 deletions

85
module-aicc/pom.xml Normal file
View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.whdc</groupId>
<artifactId>fxkh-txl-parent</artifactId>
<version>1.0</version>
<relativePath>../poms/dependency.xml</relativePath>
</parent>
<artifactId>fxkh-txl-aicc</artifactId>
<packaging>jar</packaging>
<description>防汛抗旱通讯录API - 自动外呼模块</description>
<dependencies>
<!-- Common Module -->
<dependency>
<groupId>com.whdc</groupId>
<artifactId>fxkh-txl-common</artifactId>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- Database -->
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmJdbcDriver18</artifactId>
</dependency>
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmDialect-for-hibernate4.0</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- HTTP Client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,77 @@
package com.whdc.aicc.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* @author lyf
* @since 2025-06-14
*/
@Data
@Accessors(chain = true)
@ApiModel(description = "自动拨号")
@TableName("FXKH_TXL.AUTOCALL")
@ToString
public class AutoCall {
/*
newresponderId,responderName,wcmId,createTm
query__
*/
@TableId(value = "ID", type = IdType.AUTO)
private Integer id;
@TableField(value = "responder_id")
@JsonProperty("addressBookOldId")
private Integer responderId;
@JsonProperty("addressBookOldName")
@TableField(value = "responder_name")
private String responderName;
@TableField(value = "status")
private String status;//接通,空号,停机,关机,未接,拒接,占线,呼叫失败,null(空代表未呼叫)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "_create_tm")
private Date createTm;
@TableField(value = "wcm_id")
private Integer wcmId;
@TableField(value = "level")
private Integer level;
@TableField(value = "__talk_times")
private Integer talkTimes;//通话时长,单位秒
@TableField(value = "__sip_term_cause")
private String sipTermCause; //例如”对方挂机“
@TableField(value = "__caller")
private String caller;
@TableField(value = "__number")
private String number;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__startring_at")
private Date startringAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__connected_at")
private Date connectedAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__started_at")
private Date startedAt;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__endring_at")
private Date endringAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__disconnected_at")
private Date disconnectedAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__stopped_at")
private Date stopedAt;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__last_modify")
private Date lastModify;
}

View File

@ -0,0 +1,15 @@
package com.whdc.aicc.model;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @author lyf
* @since 2025-06-19
*/
@Data
@TableName("FXKH_TXL.AUTOCALL_CONFIG")
public class AutoCallConfig {
private String key;
private String value;
}

View File

@ -0,0 +1,98 @@
package com.whdc.aicc.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @author lyf
* @since 2025-07-08
*/
@Data
@TableName("FXKH_TXL.AUTO_CALL_PERSON")
public class AutoCallPerson {
public static final int STATUS_DEFAULT = 0;
public static final int STATUS_UPLOADED = 1;
public static final int STATUS_CALLED = 2;
public static final int STATUS_PUT = 3;
public static final int STATUS_CANCELLED = 4;
public static final int STATUS_MANUAL_CLOSE = 6;
public static final int ERRCODE_ENCODE = 1;
public static final int ERRCODE_UPLOAD_FAIL = 2;
public static final String TAG_DONE = "已知晓";
@TableId(value = "ID", type = IdType.AUTO)
private Integer id;
@TableField(value = "task_id")
private Integer taskId;
@TableField(value = "status")
private Integer status; //0:未上传 default 0
@TableField(value = "level")
private Integer level;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "_create_tm")
private Date createTm;
@TableField(value = "error_code")
private Integer errorCode; //default 0
@TableField(value = "uploaded_times")
private Integer uploadedTimes; //default 0
@TableField(value = "sms_content")
private String smsContent; //短信内容
@TableField(value = "manual_close")
private Integer manualClose; //default 0
@TableField(value = "position")
private String position;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "manual_close_tm")
private Date manualCloseTm;
@TableField(value = "__request_id")
private String uploadRequestId; //任务名同时作为参数的taskName用custId
@TableField(value = "__cust_id")
private String uploadCustId; //联系人id用warningResponderId加时间戳毫秒
@TableField(value = "__cust_name")
private String uploadCustName; //联系人
@TableField(value = "__content")
private String uploadContent; //外呼内容
@TableField(value = "__number")
private String uploadNumber;
@TableField(value = "__upload_resp_msg")
private String uploadRespMsg; //上传结果
@TableField(value = "__remark")
private String detailRemark;//接通,空号,停机,关机,未接,拒接,占线,呼叫失败,null(空代表未呼叫)
@TableField(value = "__talk_times")
private Integer detailTalkTimes;//通话时长,单位秒
@TableField(value = "__sip_term_cause")
private String detailSipTermCause; //例如”对方挂机“
@TableField(value = "__tag")
private String tag; //话术识别:未识别,已知晓
@TableField("__is_complete")
private Integer isComplete; //default 0
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__startring_at")
private Date detailStartringAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__connected_at")
private Date detailConnectedAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__started_at")
private Date detailStartedAt;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__endring_at")
private Date detailEndringAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__disconnected_at")
private Date detailDisconnectedAt; //-3
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__stopped_at")
private Date detailStopedAt;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "__last_modify")
private Date detailLastModify;
}

View File

@ -0,0 +1,67 @@
package com.whdc.aicc.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @author lyf
* @since 2025-07-08
*/
@Data
@TableName("FXKH_TXL.AUTO_CALL_TASK")
public class AutoCallTask {
public static final int STATUS_DEFAULT = 0; // 不生成
public static final int STATUS_SHOULD_GENERATE = 1;
public static final int STATUS_GENERATED_AKA_READY_TO_UPLOAD = 2;
public static final int STATUS_ANY_SUCCESS = 3;
public static final int STATUS_ALL_FAIL = 4;
public static final int STATUS_CANCELLED = 5;
public static final int STATUS_MANUAL_CLOSE = 6; //人工处置
public static final int ERRCODE_NO_PERSON = 1;
public static final int ERRCODE_DB_ERROR = 2;
@TableId(value = "ID", type = IdType.AUTO)
private Integer id;
@TableField(value = "warn_id")
private Integer warnId; //not null
@TableField(value = "status")
private Integer status; //0:不拨打 default 0
@TableField(value = "error_code")
private Integer errorCode; //default 0
@TableField(value = "warn_name")
private String warnName;
@TableField(value = "warn_tm")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date warnTm;
@TableField(value = "warn_level")
private String warnLevel;
@TableField(value = "WARN_CTNM")
private String warnCtnm;
@TableField(value = "warn_cnnm")
private String warnCnnm;
@TableField(value = "warn_content")
private String warnContent;
@TableField(value = "__tag")
private String tag; //话术识别:未识别,已知晓
@TableField(value = "submit")
private Integer submit; //是否已提交线程池default 0
@TableField(value = "_create_tm")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTm;
@TableField(value = "_remark")
private String remark;
@TableField(exist = false)
private List<AutoCallPerson> callList;
@TableField(exist = false)
private AutoCallPerson successPerson;
}

View File

@ -0,0 +1,71 @@
package com.whdc.aicc.model.aicc;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.ToString;
import java.util.List;
/**
*
*
* @author lyf
* @since 2025-06-17
*/
@lombok.Data
@ToString
public class AICCCallRespDetail {
private Data data;
@lombok.Data
@ToString
public static class Data {
List<Record> records;
}
@lombok.Data
@ToString
public static class Record {
private String caller; //外呼号码
private Long dataTime;
private String processId; //机器人id
private String sessionDetailId; //联系人id等同返回值的custId
private Integer talkTimes;//通话时长,单位秒
private String remark; //中文状态,接通,空号,停机,关机,未接,拒接,占线,呼叫失败,""代表未呼叫
private String taskName; //任务名
private Integer status; //0进行中 2结束 4暂停
private Integer totalCount;
private Integer sendCount;
private boolean isCompleted;
private RawVarListMap rawVarListMap;
private List<Tag> tags;
}
@lombok.Data
@ToString
public static class RawVarListMap {
private String taskName; //任务名作为参数的taskName
private String dialTaskMainSn; //任务编号作为参数的requestId
private String custId; //联系人id
private String sipTermCause; //例如”对方挂机“
private String sipTermStatus; //接通是200
private String caller;
@JSONField(name = "@NUMBER")
private String number;
private String startringAt;
private String connectedAt;
private String startedAt;
private String endringAt;
private String disconnectedAt;
private String stopedAt;
private String lastModify;
}
@lombok.Data
@ToString
public static class Tag {
@JSONField(name = "tag_name")
private String tagName;
}
}

View File

@ -0,0 +1,38 @@
package com.whdc.aicc.model.aicc;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* uploadCallData
*
* @author lyf
* @since 2025-06-20
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class AICCCallRespTask extends AICCCallRespWrapper {
/*
{
"msg": "操作成功!",
"result": {
"msg": "任务名称重复" | "导入成功",
"count": "0",
"status": "-1"
},
"code": 0,
"redirected": false,
"success": true,
"errorType": 0,
"errorCode": "",
"timestamp": 1750383985979
}
*/
//code 0 success true
public static final String MSG_SUCCESS = "导入成功";
public static final String MSG_REPEAT = "任务名称重复";
private String msg;
private String count;
private String status;
}

View File

@ -0,0 +1,37 @@
package com.whdc.aicc.model.aicc;
import lombok.Data;
/**
* @author lyf
* @since 2025-06-20
*/
@Data
public class AICCCallRespWrapper<T> {
/*
{
"code": 406,
"errorCode": "",
"errorType": 0,
"msg": "Token失效请重新登录!",
"redirected": true,
"success": false,
"timestamp": 1750384243314
}
*/
//code 406 success false
private String msg;
private int code;
private boolean redirected;
private boolean success;
private int errorType;
private String errorCode;
private long timestamp;
//token失效没有result
private T result;
public boolean isTokenInvalid() {
return code == 406 && !success;
}
}

View File

@ -0,0 +1,19 @@
package com.whdc.aicc.model.aicc;
import lombok.Data;
/**
* @author lyf
* @since 2025-06-20
*/
@Data
public class AICCLogin {
/*
{"msg":"操作成功!","result":{"msg":"操作成功","tenantId":"963936517","status":"0","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkhCU0wwMSIsInRlbmFudElkIjoiOTYzOTM2NTE3IiwiZXhwIjoxNzUwNjg4NjE4fQ.INUcA-keg7T3HrZXH87K2ZqOT2trxLF38kmA9Wu301w"},"code":0,"redirected":false,"success":true,"errorType":0,"errorCode":"","timestamp":1750386218853}
*/
//code 0 success true
private String msg;
private String tenantId;
private String status;
private String token;
}

View File

@ -0,0 +1,120 @@
package com.whdc.aicc.model.aicc;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.experimental.Accessors;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author lyf
* @since 2025-06-20
*/
@Data
public class AICCUploadTask {
/*
JSONObject data = new JSONObject();
data.put("taskName", taskName);
data.put("processId", processId);
data.put("callerGroup", callerGroup);
data.put("requestId", requestId);
data.put("calleeType", 2);
data.put("repeatTimes", 2);
data.put("autoCall", "0");
data.put("spanSeconds", 60);
data.put("processType", "3");
data.put("mutiTimeRange", timeRange);
JSONArray params = new JSONArray();
JSONObject param = new JSONObject();
param.put("@common_user_name", custName);
param.put("@NUMBER", number);
if (bakNumbers != null && bakNumbers.length > 0) {
for (int i = 0; i < bakNumbers.length; i++) {
if (i == 3) break;
param.put("备用号码" + (i + 1), bakNumbers[i]);
}
}
param.put("custId", custId);
param.put("content", "我是省防办智能外呼系统," + content + "如需咨询请拨打02787221781");
params.add(param);
data.put("param", params);
*/
private String taskName;
private String processId;
private String callerGroup;
private String requestId;
private int calleeType = 0; //默认0 重乎1 顺乎2 默认为0
// private int repeatTimes = 1;//呼叫次数,CallType=0不传; CalleeType=1重乎必传; CalleeType=2顺乎并且autoCall为0必传
private String autoCall = "1";//顺乎未接通是否重乎,开启=0; 关闭=1; CalleeType=2顺乎必传
// private int spanSeconds = 3;//重乎间隔时间(秒),CallType=0不传; CalleeType=1重乎必传; CalleeType=2顺乎并且autoCall为0必传
private String processType = "3";
private String mutiTimeRange;
private List<Cust> param;
// private String smsSend = "1"; //1不发短信0发短信
// private String smsSendType = "0"; //挂机短信0,未接通短信1,smsSend为0必传
// private String templateId; //短信模板id,smsSend为0必传
@Data
public static class Cust {
@JSONField(name = "@common_user_name")
private String custName;
@JSONField(name = "@NUMBER")
private String number;
@JSONField(name = "备用号码1")
private String backNumber1;
@JSONField(name = "备用号码2")
private String backNumber2;
@JSONField(name = "备用号码3")
private String backNumber3;
private String custId;
private String content;
@JSONField(serialize = false, deserialize = false)
private List<String> _numbers;
public static CustBuilder builder() {
return new CustBuilder();
}
@Data
@Accessors(chain = true)
public static class CustBuilder {
private String custName;
private String custId;
private String content;
@JSONField(serialize = false, deserialize = false)
private List<String> _numbers;
public Cust build() {
Cust cust = new Cust();
cust.setCustName(custName);
cust.setCustId(custId);
cust.setContent(content);
for (int i = 0; i < _numbers.size(); i++) {
switch (i) {
case 0:
cust.setNumber(_numbers.get(i));
break;
case 1:
cust.setBackNumber1(_numbers.get(i));
break;
case 2:
cust.setBackNumber2(_numbers.get(i));
break;
case 3:
cust.setBackNumber3(_numbers.get(i));
break;
}
}
return cust;
}
}
}
public void genMutiTimeRange() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.mutiTimeRange = sdf.format(new Date()) + "_" + sdf.format(new Date(System.currentTimeMillis() + 1000 * 60 * 60));
}
}

View File

@ -0,0 +1,282 @@
package com.whdc.aicc.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.whdc.aicc.model.aicc.*;
import com.whdc.common.utils.AESpkcs7paddingUtil;
import com.whdc.common.utils.HttpHelper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author lyf
* @since 2025-06-19
*/
@Component
@Slf4j
public class AICCHelper {
@Setter
@Value("${autocall.processId}")
private String processId;
@Setter
@Value("${autocall.callerGroup}")
private String callerGroup;
@Setter
@Value("${autocall.secret}")
private String secret;
@Setter
@Value("${autocall.sysUserId}")
private String sysUserId;
@Autowired
private HttpHelper httpHelper = new HttpHelper();
private static final AtomicBoolean isAcquiringToken = new AtomicBoolean(false);
private static volatile CountDownLatch latch = new CountDownLatch(0);
private static final AtomicReference<String> globalToken = new AtomicReference<>();
public String getToken() {
if (globalToken.get() == null) {
initToken();
}
return globalToken.get();
}
public void initToken() throws RuntimeException {
if (isAcquiringToken.compareAndSet(false, true)) {
latch = new CountDownLatch(1);
globalToken.set(null);
try {
String data = "{\"sysUserId\":\"" + sysUserId + "\",\"expire\":1000000}";
String encrypt;
try {
encrypt = AESpkcs7paddingUtil.encrypt(data, secret);
} catch (Exception e) {
throw new RuntimeException(e);
}
JSONObject request = new JSONObject();
request.put("request", encrypt);
Map<String, String> headers = new HashMap<>();
// headers.put("X-Access-Token", getToken());
String resp = httpHelper.postJsonString("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/login", request.toJSONString(), headers);
TypeReference<AICCCallRespWrapper<AICCLogin>> type = new TypeReference<AICCCallRespWrapper<AICCLogin>>() {
};
AICCCallRespWrapper<AICCLogin> AICCCallRespWrapper = JSON.parseObject(resp, type);
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess() || AICCCallRespWrapper.getResult() == null) {
log.warn("获取外呼系统token失败");
return;
}
AICCLogin result = AICCCallRespWrapper.getResult();
String token = result.getToken();
// if (token != null && !token.isEmpty()) {
globalToken.set(token);
// }
} finally {
isAcquiringToken.set(false);
latch.countDown();
}
} else {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public AICCCallRespWrapper<AICCCallRespTask> apiUploadCallData(AICCUploadTask data) throws GeneralSecurityException, UnsupportedEncodingException {
return apiUploadCallData(data, getToken());
}
public AICCCallRespWrapper<AICCCallRespTask> apiUploadCallData(AICCUploadTask data, String token) throws GeneralSecurityException, UnsupportedEncodingException {
String e;
try {
e = AESpkcs7paddingUtil.encrypt(JSON.toJSONString(data), secret);
} catch (GeneralSecurityException | UnsupportedEncodingException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JSONObject request = new JSONObject();
request.put("request", e);
Map<String, String> headers = new HashMap<>();
headers.put("X-Access-Token", token);
String resp = httpHelper.postJsonString("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/uploadCallData", request.toJSONString(), headers);
log.info("apiUploadCallData: {}", resp);
TypeReference<AICCCallRespWrapper<AICCCallRespTask>> type = new TypeReference<AICCCallRespWrapper<AICCCallRespTask>>() {
};
AICCCallRespWrapper<AICCCallRespTask> AICCCallRespWrapper = null;
if (!resp.contains("请求失败") && !resp.contains("网络异常")) {
try {
AICCCallRespWrapper = JSON.parseObject(resp, type);
} catch (Exception ex) {
log.warn("apiUploadCallData first time: {}", resp);
log.warn("error: ", ex);
}
} else {
log.info("apiUploadCallData first time: {}", resp);
}
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
initToken();
headers.put("X-Access-Token", getToken());
resp = httpHelper.postJsonString("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/uploadCallData", request.toJSONString(), headers);
if (!resp.contains("请求失败") && !resp.contains("网络异常")) {
try {
AICCCallRespWrapper = JSON.parseObject(resp, type);
} catch (Exception ex) {
log.warn("apiUploadCallData second time: {}", resp);
log.warn("error: ", ex);
}
} else {
log.info("apiUploadCallData second time: {}", resp);
}
}
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
return null;
}
return AICCCallRespWrapper;
}
public AICCCallRespWrapper<AICCCallRespDetail> apiGetTaskCallDetail(String requestId, String custId) {
return apiGetTaskCallDetail(requestId, custId, getToken());
}
public AICCCallRespWrapper<AICCCallRespDetail> apiGetTaskCallDetail(String requestId, String custId, String token) {
JSONObject request = new JSONObject();
request.put("requestId", requestId);
request.put("custId", custId);
Map<String, String> headers = new HashMap<>();
headers.put("X-Access-Token", token);
String resp = httpHelper.postJsonString("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/getTaskCallDetail", request.toJSONString(), headers);
TypeReference<AICCCallRespWrapper<AICCCallRespDetail>> type = new TypeReference<AICCCallRespWrapper<AICCCallRespDetail>>() {
};
AICCCallRespWrapper<AICCCallRespDetail> aICCCallRespWrapper = null;
try {
aICCCallRespWrapper = JSON.parseObject(resp, type);
} catch (Exception e) {
log.warn("apiGetTaskCallDetail first time: {}", resp);
log.warn("error: ", e);
}
if (aICCCallRespWrapper == null || !aICCCallRespWrapper.isSuccess()) {
initToken();
headers.put("X-Access-Token", getToken());
resp = httpHelper.postJsonString("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/getTaskCallDetail", request.toJSONString(), headers);
try {
aICCCallRespWrapper = JSON.parseObject(resp, type);
} catch (Exception e) {
log.warn("apiGetTaskCallDetail second time: {}", resp);
log.warn("error: ", e);
}
}
if (aICCCallRespWrapper == null || !aICCCallRespWrapper.isSuccess()) {
log.info("获取任务详情失败:{}", resp);
return null;
}
return aICCCallRespWrapper;
}
public AICCUploadTask newTask(String requestId, String custId, String custName, String content, List<String> numbers) {
AICCUploadTask task = new AICCUploadTask();
task.setTaskName(requestId);
task.setProcessId(processId);
task.setCallerGroup(callerGroup);
task.setRequestId(requestId);
task.genMutiTimeRange();
AICCUploadTask.Cust param = AICCUploadTask.Cust.builder()
.setCustName(custName)
.setCustId(custId)
.setContent(content)
.set_numbers(numbers)
.build();
task.setParam(Collections.singletonList(param));
return task;
}
// private String sendPost(String url, JSONObject jsonData) {
// String resp = sendPost(url, jsonData.toJSONString());
// if (resp == null) {
// resp = sendPost(url, jsonData.toJSONString());
// }
// return resp;
// }
//
// private String sendPost(String url, JSONObject jsonData, String token) {
// String resp = sendPost(url, jsonData.toJSONString(), token);
// if (resp == null) {
// resp = sendPost(url, jsonData.toJSONString(), token);
// }
// return resp;
// }
//
// private String sendPost(String url, String jsonData) {
// return sendPost(url, jsonData, getToken());
// }
//
// private String sendPost(String url, String jsonData, String token) {
// CloseableHttpResponse response = null;
// CloseableHttpClient httpClient = null;
// String responseContent = null;
// try {
// httpClient = HttpClients.createDefault();
// HttpPost httpPost = new HttpPost(url);
// httpPost.addHeader("Content-Type", "application/json");
// httpPost.addHeader("X-Access-Token", token);
//
// if (StringUtils.isNotBlank(jsonData)) {
// httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
// }
//
// log.info("请求地址: " + url);
// log.info("token: " + getToken());
// log.info("请求参数: " + jsonData);
//
// response = httpClient.execute(httpPost);
// HttpEntity entity = response.getEntity();
// responseContent = EntityUtils.toString(entity, "UTF-8");
// responseContent = jsonFormat(responseContent);
// if (responseContent.length() < 200) {
// log.info("响应参数: " + responseContent);
// }
// } catch (Exception e) {
// log.error("发送请求异常", e);
// return null;
// } finally {
// try {
// if (null != response) {
// response.close();
// }
// httpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return responseContent;
// }
private static String jsonFormat(String str) {
if (JSON.isValidObject(str)) {
str = JSON.parseObject(str).toJSONString();
}
return str;
}
}

View File

@ -0,0 +1,236 @@
package com.whdc.aicc.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.whdc.aicc.model.aicc.*;
import com.whdc.common.utils.AESpkcs7paddingUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author lyf
* @since 2025-06-19
*/
@Component
@Slf4j
public class AutoCallHelper {
@Setter
@Value("${autocall.processId}")
private String processId;
@Setter
@Value("${autocall.callerGroup}")
private String callerGroup;
@Setter
@Value("${autocall.secret}")
private String secret;
@Setter
@Value("${autocall.sysUserId}")
private String sysUserId;
private static final AtomicBoolean isAcquiringToken = new AtomicBoolean(false);
private static volatile CountDownLatch latch = new CountDownLatch(0);
private static final AtomicReference<String> globalToken = new AtomicReference<>();
public String getToken() {
if (globalToken.get() == null) {
initToken();
}
return globalToken.get();
}
public void initToken() throws RuntimeException {
if (isAcquiringToken.compareAndSet(false, true)) {
globalToken.set(null);
try {
String data = "{\"sysUserId\":\"" + sysUserId + "\",\"expire\":1000000}";
String encrypt;
try {
encrypt = AESpkcs7paddingUtil.encrypt(data, secret);
} catch (Exception e) {
throw new RuntimeException(e);
}
JSONObject request = new JSONObject();
request.put("request", encrypt);
String resp = sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/login", request);
TypeReference<AICCCallRespWrapper<AICCLogin>> type = new TypeReference<AICCCallRespWrapper<AICCLogin>>() {
};
AICCCallRespWrapper<AICCLogin> AICCCallRespWrapper = JSON.parseObject(resp, type);
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess() || AICCCallRespWrapper.getResult() == null) {
log.warn("获取外呼系统token失败");
return;
}
AICCLogin result = AICCCallRespWrapper.getResult();
String token = result.getToken();
if (token != null && !token.isEmpty()) {
globalToken.set(token);
}
} finally {
isAcquiringToken.set(false);
}
} else {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public AICCCallRespWrapper<AICCCallRespTask> apiUploadCallData(AICCUploadTask data) {
return apiUploadCallData(data, getToken());
}
public AICCCallRespWrapper<AICCCallRespTask> apiUploadCallData(AICCUploadTask data, String token) {
String e;
try {
e = AESpkcs7paddingUtil.encrypt(JSON.toJSONString(data), secret);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JSONObject request = new JSONObject();
request.put("request", e);
String resp = sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/uploadCallData", request, token);
TypeReference<AICCCallRespWrapper<AICCCallRespTask>> type = new TypeReference<AICCCallRespWrapper<AICCCallRespTask>>() {
};
AICCCallRespWrapper<AICCCallRespTask> AICCCallRespWrapper = JSON.parseObject(resp, type);
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
initToken();
resp = sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/uploadCallData", request, token);
AICCCallRespWrapper = JSON.parseObject(resp, type);
}
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
return null;
}
return AICCCallRespWrapper;
}
public AICCCallRespWrapper<AICCCallRespDetail> apiGetTaskCallDetail(String requestId, String custId) {
JSONObject request = new JSONObject();
request.put("requestId", requestId);
request.put("custId", custId);
String resp = sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/getTaskCallDetail", request);
TypeReference<AICCCallRespWrapper<AICCCallRespDetail>> type = new TypeReference<AICCCallRespWrapper<AICCCallRespDetail>>() {
};
AICCCallRespWrapper<AICCCallRespDetail> AICCCallRespWrapper = JSON.parseObject(resp, type);
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
initToken();
resp = sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/getTaskCallDetail", request);
AICCCallRespWrapper = JSON.parseObject(resp, type);
}
if (AICCCallRespWrapper == null || !AICCCallRespWrapper.isSuccess()) {
return null;
}
return AICCCallRespWrapper;
}
public AICCUploadTask newTask(String requestId, String custId, String custName, String content, List<String> numbers) {
AICCUploadTask task = new AICCUploadTask();
task.setTaskName(requestId);
task.setProcessId(processId);
task.setCallerGroup(callerGroup);
task.setRequestId(requestId);
task.genMutiTimeRange();
AICCUploadTask.Cust param = AICCUploadTask.Cust.builder()
.setCustName(custName)
.setCustId(custId)
.setContent(content)
.set_numbers(numbers)
.build();
task.setParam(Collections.singletonList(param));
return task;
}
private String sendPost(String url, JSONObject jsonData) {
String resp = sendPost(url, jsonData.toJSONString());
if (resp == null) {
resp = sendPost(url, jsonData.toJSONString());
}
return resp;
}
private String sendPost(String url, JSONObject jsonData, String token) {
String resp = sendPost(url, jsonData.toJSONString(), token);
if (resp == null) {
resp = sendPost(url, jsonData.toJSONString(), token);
}
return resp;
}
private String sendPost(String url, String jsonData) {
return sendPost(url, jsonData, getToken());
}
private String sendPost(String url, String jsonData, String token) {
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("X-Access-Token", token);
if (StringUtils.isNotBlank(jsonData)) {
httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
}
log.info("请求地址: " + url);
log.info("token: " + getToken());
log.info("请求参数: " + jsonData);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
responseContent = jsonFormat(responseContent);
if (responseContent.length() < 200) {
log.info("响应参数: " + responseContent);
}
} catch (Exception e) {
log.error("发送请求异常", e);
return null;
} finally {
try {
if (null != response) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
private static String jsonFormat(String str) {
if (JSON.isValidObject(str)) {
str = JSON.parseObject(str).toJSONString();
}
return str;
}
}

View File

@ -0,0 +1,23 @@
<?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.whdc.mapper.AutoCallMapper">
<select id="getListByLevelAndStatus" resultType="com.whdc.legacy.model.autocall.AutoCall">
select * from AUTOCALL A
where 1=1
<if test="level != null">
and A.LEVEL = #{adnm}
</if>
<if test="status != null and called == null">
and A.STATUS = #{status}
</if>
<if test="called != null and called == true">
and A.STATUS is not null
</if>
<if test="called != null and called == false">
and A.STATUS is null
</if>
<if test="stm != null and etm != null">
AND A._create_tm BETWEEN #{stm} AND #{etm}
</if>
</select>
</mapper>

View File

@ -0,0 +1,14 @@
<?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.whdc.mapper.AutoCallPersonMapper">
<select id="selectListByTaskId" resultType="com.whdc.legacy.model.autocall.AutoCallPerson">
select T1.*,T2.POSITION as position from FXKH_TXL.AUTO_CALL_PERSON T1
LEFT JOIN FXKH_TXL.SH_ADDRESS_BOOK T2 ON T1.__NUMBER = T2.PHONE
where T1.TASK_ID = #{taskId}
</select>
</mapper>

View File

@ -0,0 +1,31 @@
<?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.whdc.mapper.AutoCallTaskMapper">
<select id="listWarnsThatNotGeneratedTask" resultType="com.whdc.legacy.model.entity.QXWarning">
SELECT
Q.*
FROM
FXKH_TXL.QXWARNING Q
WHERE
NOT EXISTS (
SELECT 1
FROM FXKH_TXL.AUTO_CALL_TASK TASK
WHERE TASK.WARN_ID = Q.WARNID
)
AND Q.PUBLISH_TIME > (
SELECT MAX(TASK_LATEST.warn_tm)
FROM FXKH_TXL.AUTO_CALL_TASK TASK_LATEST
)
ORDER BY Q.WARNID ASC;
</select>
<select id="getList" resultType="com.whdc.legacy.model.autocall.AutoCallTask">
SELECT
*
FROM
FXKH_TXL.AUTOCALL_TASK TASK
WHERE
TASK.AUTOCALL_ID IS NULL
AND TASK.SHOULD_GENERATE = 1
AND TASK.GENERATED = 0
</select>
</mapper>

View File

@ -0,0 +1,31 @@
<?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.whdc.legacy.mapper.WarnCallMapMapper">
<select id="listWarnsThatNotGeneratedWcm" resultType="com.whdc.legacy.model.entity.QXWarning">
SELECT
Q.*
FROM
FXKH_TXL.QXWARNING Q
WHERE
NOT EXISTS (
SELECT 1
FROM FXKH_TXL.WARN_CALL_MAP WCM
WHERE WCM.WARN_ID = Q.WARNID
)
AND Q.PUBLISH_TIME > (
SELECT MAX(WCM_LATEST.warn_tm)
FROM FXKH_TXL.WARN_CALL_MAP WCM_LATEST
)
ORDER BY Q.WARNID ASC;
</select>
<select id="getWCMList" resultType="com.whdc.legacy.model.autocall.AutoCall">
SELECT
*
FROM
FXKH_TXL.WARN_CALL_MAP WCM
WHERE
WCM.AUTOCALL_ID IS NULL
AND WCM.SHOULD_GENERATE = 1
AND WCM.GENERATED = 0
</select>
</mapper>

102
module-common/pom.xml Normal file
View File

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.whdc</groupId>
<artifactId>fxkh-txl-parent</artifactId>
<version>1.0</version>
<relativePath>../poms/dependency.xml</relativePath>
</parent>
<artifactId>fxkh-txl-common</artifactId>
<packaging>jar</packaging>
<description>防汛抗旱通讯录API - 公共模块</description>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Utilities -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- HTTP Client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,53 @@
package com.whdc.common.annotation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @author
* @date 2022-04-27 12:08
*/
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateTimeRangeValidator.class)
@Documented
public @interface DateTimeRange {
String message() default "{message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String datafmt() default "yyyy-MM-dd HH:mm:ss";
/**
*
*
* @return
*/
String startField();
/**
*
*
* @return
*/
String endField();
/**
*
*
* @return
*/
long interval();
/**
*
*
* @return
*/
TimeUnit timeUnit() default TimeUnit.HOURS;
}

View File

@ -0,0 +1,63 @@
package com.whdc.common.annotation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author
* @date 2022-04-27 11:55
*/
public class DateTimeRangeValidator implements ConstraintValidator<DateTimeRange, Object> {
private String datefmt;
private String startField;
private String endField;
private long interval;
private TimeUnit timeUnit;
@Override
public void initialize(DateTimeRange dateTimeRange) {
this.datefmt = dateTimeRange.datafmt();
this.startField = dateTimeRange.startField();
this.endField = dateTimeRange.endField();
this.interval = dateTimeRange.interval();
this.timeUnit = dateTimeRange.timeUnit();
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
try {
if (obj == null) {
return false;
}
if (StringUtils.isBlank(this.startField) || StringUtils.isBlank(this.endField)) {
return false;
}
String stmval = BeanUtils.getProperty(obj, this.startField);
String etmval = BeanUtils.getProperty(obj, this.endField);
if (StringUtils.isBlank(stmval) || StringUtils.isBlank(etmval)) {
return false;
}
DateFormat df = new SimpleDateFormat(this.datefmt);
Date stm = df.parse(stmval);
Date etm = df.parse(etmval);
long dateDiff = stm.getTime() - etm.getTime();
return Math.abs(dateDiff) < this.timeUnit.toMillis(this.interval);
} catch (Exception e) {
return false;
}
}
}

View File

@ -0,0 +1,86 @@
package com.whdc.common.aspect;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.whdc.common.utils.ReqUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* @author
* @date 2022-06-26 0:34
*/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
private void print(String fmt, Object... str) {
log.info(fmt, str);
}
@Pointcut("execution(public * com.whdc.controller.*Controller.*(..))")
public void controllerPointcut() {
}
@Before("controllerPointcut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Signature signature = joinPoint.getSignature();
String name = signature.getName();
print("------------- 开始 -------------");
print("请求: {} {}", name, request.getRequestURI(), request.getMethod());
print("方法: {} {}.{}", name, signature.getDeclaringTypeName(), name);
print("地址: {} {}", name, ReqUtils.getIpAddress(request));
Object[] args = joinPoint.getArgs();
Object[] arguments = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest
|| args[i] instanceof ServletResponse
|| args[i] instanceof MultipartFile) {
continue;
}
arguments[i] = args[i];
}
String[] excludeProperties = {"password", "file"};
PropertyPreFilters filters = new PropertyPreFilters();
PropertyPreFilters.MySimplePropertyPreFilter excludeFilter = filters.addFilter();
excludeFilter.addExcludes(excludeProperties);
print("参数: {} {}", name, JSONObject.toJSONString(arguments, excludeFilter));
}
@Around("controllerPointcut()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Signature signature = proceedingJoinPoint.getSignature();
String name = signature.getName();
Object result = proceedingJoinPoint.proceed();
String[] excludeProperties = {"password", "file"};
PropertyPreFilters filters = new PropertyPreFilters();
PropertyPreFilters.MySimplePropertyPreFilter excludeFilter = filters.addFilter();
excludeFilter.addExcludes(excludeProperties);
// print("返回结果: {}", JSONObject.toJSONString(result, excludeFilter));
print("------------- 耗时:{} {} ms -------------", name, System.currentTimeMillis() - startTime);
return result;
}
}

View File

@ -0,0 +1,20 @@
package com.whdc.common.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* SMS
* SMS
*
* @author lyf
* @since 2025-10-29
*/
@Configuration
@ComponentScan(basePackages = "com.whdc.common")
public class CommonModuleConfig {
// 在启动类上注解扫描com.whdc.common包下的所有组件
}

View File

@ -0,0 +1,46 @@
package com.whdc.common.config;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author
* @date 2022-06-26 1:09
*/
@EnableWebMvc
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
*
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名------------修改此行
.allowedOriginPatterns("*")
// 是否允许证书cookies
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(3600);
}
}

View File

@ -0,0 +1,66 @@
package com.whdc.common.config;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author
* @date 2022-04-06 9:49
*/
@EnableSwagger2
@Configuration
public class Knife4jConfiguration {
private final OpenApiExtensionResolver openApiExtensionResolver;
@Autowired
public Knife4jConfiguration(OpenApiExtensionResolver openApiExtensionResolver) {
this.openApiExtensionResolver = openApiExtensionResolver;
}
private ApiInfo getApiInfoBuilder() {
return new ApiInfoBuilder()
.title("防汛抗旱通讯录api")
.description("# 防汛抗旱通讯录api RESTful APIs")
.termsOfServiceUrl("http://219.138.108.99:19000/jszx")
.contact(new Contact("湖北纬皓端成", null, null))
.version("1.0")
.build();
}
@Bean(value = "base")
public Docket base() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(getApiInfoBuilder())
//分组名称
.groupName("v1.0")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.whdc.controller"))
.paths(PathSelectors.any())
.build()
.extensions(openApiExtensionResolver.buildExtensions("v1.0"));
}
@Bean(value = "md")
public Docket md() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(getApiInfoBuilder())
.select()
// ...
.build()
// 构建扩展插件-自定义文档 group
.extensions(openApiExtensionResolver.buildExtensions("doc-knife4j-1.0.0"))
.groupName("接口说明文档");
}
}

View File

@ -0,0 +1,34 @@
package com.whdc.common.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author
* @date 2022-04-08 0:33
*/
@Configuration
@MapperScan("com.whdc.mapper")
public class MyBatisPlusConfig {
/*
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}*/
/**
* ,mybatis, MybatisConfiguration#useDeprecatedExecutor = false
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM)); // 分页插件
return interceptor;
}
}

View File

@ -0,0 +1,85 @@
package com.whdc.common.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;
import static com.whdc.common.model.MyConstant.REC;
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
String sqlId = mappedStatement.getId();
log.debug("------sqlId------" + sqlId);
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
Object parameter = invocation.getArgs()[1];
log.debug("------sqlCommandType------" + sqlCommandType);
if (parameter == null) {
return invocation.proceed();
}
if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType) {
Field[] fields = parameter.getClass().getDeclaredFields();
// Field[] fields = oConvertUtils.getAllFields(parameter);
for (Field field : fields) {
if (Modifier.isFinal(field.getModifiers())) {
continue;
}
// if (field.getType().equals(String.class)) {
// field.setAccessible(true);
// Object o = field.get(parameter);
// field.setAccessible(false);
// String newVal = o == null ? "" : String.valueOf(o).trim();
// field.setAccessible(true);
// field.set(parameter, newVal);
// field.setAccessible(false);
// }
// 注入创建时间
if ("createtime".equals(field.getName()) || ("createTime".equals(field.getName()))) {
field.setAccessible(true);
Object local_createDate = field.get(parameter);
field.setAccessible(false);
if (local_createDate == null || "".equals(local_createDate)) {
field.setAccessible(true);
field.set(parameter, new Date());
field.setAccessible(false);
}
}
// 删除标识
if ("del".equals(field.getName())) {
field.setAccessible(true);
Object local_createDate = field.get(parameter);
field.setAccessible(false);
if (local_createDate == null || "".equals(local_createDate)) {
field.setAccessible(true);
field.set(parameter, REC);
field.setAccessible(false);
}
}
}
}
return invocation.proceed();
}
}

View File

@ -0,0 +1,111 @@
package com.whdc.common.config;
/**
* Description:
* Created by XuSan on 2024/6/3.
*
* @author XuSan
* @version 1.0
*/
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.io.Serializable;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
*/
@Configuration
@EnableCaching
public class RedisConfig implements Serializable {
/**
* aspectSpringpointcut
* 使
*/
/* @Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return RedisCacheManager.create(redisConnectionFactory);
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
// 创建一个模板类
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
// 将刚才的redis连接工厂设置到模板类中
template.setConnectionFactory(factory);
// 设置key的序列化器
template.setKeySerializer(new StringRedisSerializer());
// 设置value的序列化器
//使用Jackson 2将对象序列化为JSON
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//json转对象类不设置默认的会将json转成hashmap
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}*/
/**
* redis
*/
// @Bean
// public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
// .entryTtl(Duration.ofDays(1))
// .computePrefixWith(cacheName -> "caching:" + cacheName);
//
// return new CustomRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), defaultCacheConfig);
// }
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl( -1), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//自定义设置缓存时间
redisCacheConfigurationMap.put("fxkh:txl:warning", this.getRedisCacheConfigurationWithTtl(120));
return redisCacheConfigurationMap;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}

View File

@ -0,0 +1,60 @@
package com.whdc.common.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
/**
* @author
* @date 2022-04-22 14:13
*/
@Configuration
public class RestTemplateConfig {
@Order(1)
@Bean
public RestTemplate restTemplate(@Qualifier("simpleClientHttpRequestFactory") ClientHttpRequestFactory factory){
RestTemplate restTemplate = new RestTemplate(factory);
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_OCTET_STREAM,
MediaType.TEXT_HTML));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
return restTemplate;
}
@Order(2)
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000); // 单位毫秒
requestFactory.setReadTimeout(30000); // 单位毫秒
return new RestTemplate(requestFactory);
}
@Order(4)
@Bean("redisTemplate")
public RedisTemplate<String, String> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
// 设置键和值的序列化方式默认使用JDK的序列化方式
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}

View File

@ -0,0 +1,42 @@
package com.whdc.common.config;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author XuSan
* @date 2021/1/11 16:39
* @explain 线
*/
@Configuration
//@Slf4j
public class ThreadPools implements AsyncConfigurer {
// 全核心线程池
@Bean(value = "intensivePool", destroyMethod = "shutdown")
public ExecutorService intensive() {
return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder()
.setNameFormat("fixed -- %d").build());
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);//不配置默认是1
return taskScheduler;
}
// public static Void handleException(Throwable ex) {
// log.error("请求出现异常:" + ex.getMessage(), ex);
// return null;
// }
}

View File

@ -0,0 +1,56 @@
package com.whdc.common.config;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Description:
* Created by XuSan on 2024/6/3.
*
*
* @author XuSan
* @version 1.0
*/
@Data
@Configuration
@ConditionalOnClass(WxMaService.class)
@ConfigurationProperties(prefix = "wx.miniapp.configs")
public class WxMiniappConfiguration {
/**
* appId
*/
private String appId;
/**
* Secret
*/
private String secret;
@Bean
@ConditionalOnMissingBean(WxMaService.class)
public WxMaService wxMaService() {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(this.getAppId());
config.setSecret(this.getSecret());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}

View File

@ -0,0 +1,68 @@
package com.whdc.common.exception;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
/**
*
*
* @author
* @date 2022-04-09 15:38
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController extends BasicErrorController {
@Value("${server.error.path:${error.path:/error}}")
private String path;
public CustomErrorController(ServerProperties serverProperties) {
super(new DefaultErrorAttributes(), serverProperties.getError());
}
/**
* JSON
*/
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
Map<String, Object> map = new HashMap<String, Object>(16);
Map<String, Object> originalMsgMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
String path = (String) originalMsgMap.get("path");
String error = (String) originalMsgMap.get("error");
String message = (String) originalMsgMap.get("message");
StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add(path).add(error).add(message);
map.put("code", status.value());
map.put("msg", joiner.toString());
return new ResponseEntity<Map<String, Object>>(map, status);
}
/**
* HTML
*/
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
//请求的状态
HttpStatus status = getStatus(request);
response.setStatus(getStatus(request).value());
Map<String, Object> model = getErrorAttributes(request, ErrorAttributeOptions.defaults());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
//指定自定义的视图
return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
}
}

View File

@ -0,0 +1,25 @@
package com.whdc.common.exception;
/**
* @author
* @date 2022-06-26 10:58
*/
public class MyException extends RuntimeException {
private final String msg;
public String getMsg() {
return msg;
}
public MyException(String msg) {
super(msg);
this.msg = msg;
}
public MyException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
}

View File

@ -0,0 +1,199 @@
package com.whdc.common.exception;
import com.whdc.common.utils.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Set;
/**
* @author
* @date 2022-06-26 10:58
*/
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
@PostConstruct
public void init() {
}
/**
*
*
* @param e
*/
private void saveLogs(Exception e) {
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResultJson handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
log.error("缺少请求参数", e);
return ResultJson.error(ResultJson.PARAM_ERROR, "缺少请求参数");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResultJson handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("缺少请求参数", e);
return ResultJson.error(ResultJson.PARAM_ERROR, "参数格式错误。使用 json 格式字符串传递参数");
}
/**
* 400 - Bad Request---------------------
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultJson handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
try {
// log.error("参数验证失败 " + e.getMessage(), e);
BindingResult result = e.getBindingResult();
if (result.getErrorCount() > 0) {
StringBuffer strbuf = new StringBuffer();
for (ObjectError err : result.getAllErrors()) {
if (strbuf.length() > 0) {
strbuf.append(";");
}
strbuf.append(err.getDefaultMessage());
}
return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败:" + strbuf);
}
return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败");
} catch (Exception err) {
return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败," + err.getMessage());
}
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(BindException.class)
public ResultJson handleBindException(BindException e) {
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
log.error("参数绑定失败", message);
return ResultJson.error(ResultJson.PARAM_ERROR, "参数绑定失败," + message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ConstraintViolationException.class)
public ResultJson handleServiceException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
log.error("参数验证失败4 " + message, e);
return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败5," + message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ValidationException.class)
public ResultJson handleValidationException(ValidationException e) {
log.error("参数验证失败6 " + e.getMessage());
e.printStackTrace();
return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败7");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResultJson handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
log.error("不支持当前请求方法", e.getMessage());
return ResultJson.error(ResultJson.METHOD_NOT_ALLOWED, "不支持当前请求方法");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResultJson handleHttpMediaTypeNotSupportedException(Exception e) {
log.error("不支持当前媒体类型", e.getMessage());
return ResultJson.error(ResultJson.NSUPPORTED_MEDIA_TYPE, "不支持当前媒体类型");
}
/**
* :
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(DataIntegrityViolationException.class)
public ResultJson handleException(DataIntegrityViolationException e) {
log.error("操作数据库出现异常: ", e);
return ResultJson.error(ResultJson.FAIL, "操作数据库出现异常");
}
/**
*
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(Exception.class)
public ResultJson handleException(Exception e) {
log.error("通用异常:" + e.getMessage(), e);
if (e instanceof SQLIntegrityConstraintViolationException) {
return ResultJson.error(ResultJson.FAIL, "数据库主键冲突,请联系管理员");
} else if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
return ResultJson.error(ResultJson.FAIL, "找不到资源");
}
return ResultJson.error(ResultJson.SERVER_ERROR, "内部服务器错误");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(MyException.class)
public ResultJson handleServiceException(MyException e) {
log.error("业务逻辑异常", e);
//RetryableException 无法单独捕获处理,只能简单处理一下返回值
String msg = e.getMsg();
if (StringUtils.isNotBlank(e.getMsg()) && e.getMsg().startsWith("Connection refused: connect executing POST")) {
msg = "连接被拒绝";
}
return ResultJson.error(ResultJson.FAIL, msg);
}
}

View File

@ -0,0 +1,26 @@
package com.whdc.common.model;
/**
* @author xusan
* @date 2023/4/27 9:41
*/
public class MyConstant {
public static final String
// 删除
DEL = "0",
// 未删除
REC = "1",
// redis KEY
TOKEN_KEY = "SW_TOKEN_SJQX";
/**
* -
*/
public static final String ROLE_PUSH = "data_zh_om";
public static final String REDIS_KEY = "fxkh:txl:";
}

View File

@ -0,0 +1,8 @@
package com.whdc.common.model.group;
/**
* @author
* @date 2022-06-26 15:13
*/
public interface Delete {
}

View File

@ -0,0 +1,8 @@
package com.whdc.common.model.group;
/**
* @author
* @date 2022-06-27 22:27
*/
public interface Find {
}

View File

@ -0,0 +1,8 @@
package com.whdc.common.model.group;
/**
* @author
* @date 2022-06-26 15:12
*/
public interface Insert {
}

View File

@ -0,0 +1,8 @@
package com.whdc.common.model.group;
/**
* @author
* @date 2022-06-26 15:12
*/
public interface Update {
}

View File

@ -0,0 +1,29 @@
package com.whdc.common.strategy;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Context
*/
@Component
public class SaveContext {
private final Map<String, SyncSaveInterface> strategyMap = new ConcurrentHashMap<>();
@Autowired
public SaveContext(Map<String, SyncSaveInterface> strategyMap) {
this.strategyMap.putAll(strategyMap);
}
// 新增
public boolean syncSave(String channel, JSONObject jsonObject) {
return strategyMap.get(channel).syncSave(jsonObject);
}
}

View File

@ -0,0 +1,14 @@
package com.whdc.common.strategy;
import com.alibaba.fastjson.JSONObject;
/**
* @author xusan
* @date 2023/4/20 16:28
*/
public interface SyncSaveInterface {
boolean syncSave(JSONObject jsonObject);
}

View File

@ -0,0 +1,184 @@
package com.whdc.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Security;
public class AESpkcs7paddingUtil {
/**
*
*/
private static final String KEY_ALGORITHM = "AES";
/**
* / / /
* Java 6PKCS5Padding
* Bouncy CastlePKCS7Padding
*/
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
static {
//如果是PKCS7Padding填充方式则必须加上下面这行
Security.addProvider(new BouncyCastleProvider());
}
/**
*
*
* @return
* @throws Exception
*/
public static String generateKey() throws Exception {
//实例化密钥生成器
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
/**
* AES
* AES128192256javaAES128
* 192256oraclejdk"Additional Resources"
* "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files",[DOWNLOAD]
* local_policy.jarUS_export_policy.jarjdkjre/lib/security/
*/
kg.init(128);
//生成密钥
SecretKey secretKey = kg.generateKey();
//获得密钥的字符串形式
return Base64.encodeBase64String(secretKey.getEncoded());
}
/**
* AES
*
* @param source
* @param key
* @return
* @throws Exception
*/
public static String encrypt(String source, String key) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] sourceBytes = source.getBytes("UTF-8");
byte[] keyBytes = key.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM));
byte[] decrypted = cipher.doFinal(sourceBytes);
return Base64.encodeBase64String(decrypted);
}
/**
* AES
*
* @param encryptStr
* @param key
* @return
* @throws Exception
*/
public static String decrypt(String encryptStr, String key) {
try {
byte[] sourceBytes = Base64.decodeBase64(encryptStr);
final byte[] keyBytes = key.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM));
byte[] decoded = cipher.doFinal(sourceBytes);
return new String(decoded, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception {
String data = "{\"sysUserId\":\"HBSL01\",\"expire\":1000000}";
String encrypt = encrypt(data, "yxt@2024-1234567");
System.out.println(encrypt);
String request = "{\"request\":\"" + encrypt + "\"}";
String resp = HttpUtil.sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/login", request);
System.out.println(resp);
/*
*/
// genTask();
// genQueryTask();
// String request = "{\n" +
// " \"requestId\": \"hbsl1750130919921\",\n" +
// " \"custId\": \"hbsl-zj\"\n" +
// "}";
// JSONObject header = new JSONObject();
// header.put("X-Access-Token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ik5TQkRKSzIwMjUiLCJ0ZW5hbnRJZCI6IjE5MTY1NDI5IiwiZXhwIjoxNzUwNDI5OTAzfQ.RvsTL5L8jPl6GqiQq344jBP5i-v6vuQt-kARsvUvuyY");
// String resp = HttpUtil.sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/getTaskCallDetail", request, header);
// AICCCallRespDetail autoCallDetail = JSON.parseObject(resp, AICCCallRespDetail.class);
// autoCallDetail.getResult().getData().getRecords().forEach(System.out::println);
// AutoCallHelper helper = new AutoCallHelper();
// helper.initToken();
// String token = helper.getToken();
// genTask();
}
private static void genQueryTask() throws Exception {
String requestId = "hbsl1750130186416";
String custId = "detail2c9ab2f08709s438018722de2ebf001f";
String data = "{\"requestId\":\"" + requestId + "\",\"custId\":\"" + custId + "\"}";
System.out.println(data);
String e = encrypt(data, "yxt@2024-1234567");
System.out.println(e);
}
private static void genTask() throws Exception {
String taskName = "hbsl" + System.currentTimeMillis();
String processId = "1934801506242949122";
// String processId = "1934876091344777218";
String requestId = taskName;
String callerGroup = "02160980358";
// String callerGroup = "01080945234";
String content = "这里是湖北省防汛抗旱指挥部办公室咸宁市2025年06月15日02时26分58秒发布暴雨橙色预警信号过去6小时最大降水出现在青山镇(青山水库)为54.6毫米。预计今天夜间崇阳南部将出现暴雨到大暴雨累计降雨量将达100毫米以上并伴有雷暴大风山区山洪、地质灾害、城乡积涝、中小河流洪水风险高请加强防范。";
// String content = "咸宁市2025年06月15日02时26分58秒发布暴雨橙色预警信号";
JSONObject data = new JSONObject();
data.put("taskName", taskName);
data.put("processId", processId);
data.put("callerGroup", callerGroup);
data.put("requestId", requestId);
data.put("calleeType", 2);
data.put("repeatTimes", 2);
data.put("autoCall", "0");
data.put("spanSeconds", 60);
data.put("processType", "3");
data.put("mutiTimeRange", "2025-06-17 10:00:00_2025-06-17 21:00:00");
JSONArray params = new JSONArray();
JSONObject param = new JSONObject();
param.put("@common_user_name", "李");
// param.put("@NUMBER", "15671545233");
param.put("@NUMBER", "15671545233");
param.put("备用号码1", "18162570850");
// param.put("备用号码1", "13933930962");
// param.put("备用号码2", "15697168180");
param.put("custId", "abo70652-abo70653-abo70654");
// param.put("address", "{}");
param.put("content", content);
params.add(param);
data.put("param", params);
System.out.println(data);
String e = encrypt(data.toJSONString(), "yxt@2024-1234567");
JSONObject request = new JSONObject();
request.put("request", e);
JSONObject header = new JSONObject();
header.put("X-Access-Token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ik5TQkRKSzIwMjUiLCJ0ZW5hbnRJZCI6IjE5MTY1NDI5IiwiZXhwIjoxNzUwNDI5OTAzfQ.RvsTL5L8jPl6GqiQq344jBP5i-v6vuQt-kARsvUvuyY");
HttpUtil.sendPost("https://aicc.cuopen.net:9801/aicc-api/ssb/callout/thirdParty/task/uploadCallData", request.toJSONString(), header);
}
}

View File

@ -0,0 +1,247 @@
package com.whdc.common.utils;
import com.whdc.common.exception.MyException;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
/**
* Description:
* Created by XuSan on 2024/3/14.
*
* @author XuSan
* @version 1.0
*/
public class AdinfoUtils {
/**
*
*
* @param adcd
* @param adlevel
* @return
*/
public static String likeAdcd(String adcd, Integer adlevel) {
// // 判断行政区划和行政区划等级是否匹配
// validateAdcdAndAdlevel(adcd, adlevel);
if (adlevel > 5) {
adlevel = 5;
}
switch (adlevel) {
case 0:
if (adcd.length() < 2){
return adcd;
}
return adcd.substring(0, 2);
case 1:
if (adcd.length() < 4){
return adcd;
}
return adcd.substring(0, 4);
case 2:
if (adcd.length() < 6){
return adcd;
}
return adcd.substring(0, 6);
case 3:
if (adcd.length() < 9){
return adcd;
}
return adcd.substring(0, 9);
case 4:
if (adcd.length() < 12){
return adcd;
}
return adcd.substring(0, 12);
case 5:
return adcd;
default:
throw new MyException("不支持该行政区划等级");
}
}
/**
*
*
* @param adcd
* @param adlevel
* @return
*/
public static String getParentAdcd(String adcd, Integer adlevel) {
if (Objects.isNull(adlevel)){
adlevel = getAdlevel(adcd);
}
if (adlevel > 5) {
adlevel = 5;
}
switch (adlevel) {
case 0:
return adcd.substring(0, 2) + "0000000000000";
case 1:
return adcd.substring(0, 4) + "00000000000";
case 2:
return adcd.substring(0, 6) + "000000000";
case 3:
return adcd.substring(0, 9) + "000000";
case 4:
return adcd.substring(0, 12) + "000";
case 5:
return adcd;
default:
throw new MyException("不支持该行政区划等级");
}
}
/**
*
*
* @param adlevel
* @return
*/
public static String getAdcdRight( Integer adlevel) {
if (adlevel > 5) {
adlevel = 5;
}
switch (adlevel) {
case 0:
return "0000000000000";
case 1:
return "00000000000";
case 2:
return "000000000";
case 3:
return "000000";
case 4:
return "000";
case 5:
return "";
default:
throw new MyException("不支持该行政区划等级");
}
}
/**
*
*
* @param adcd
* @param adlevel
* @return
*/
public static void validateAdcdAndAdlevel(String adcd, Integer adlevel) {
// 避免重复代码,提取为私有方法
validateAdcd(adcd, adlevel, 2);
validateAdcd(adcd, adlevel, 4);
validateAdcd(adcd, adlevel, 6);
validateAdcd(adcd, adlevel, 9);
validateAdcd(adcd, adlevel, 12);
}
/**
*
*
* @param adcd
* @param adlevel
* @param startIndex
* @throws MyException
*/
private static void validateAdcd(String adcd, Integer adlevel, int startIndex) throws MyException {
if (StringUtils.isBlank(adcd) || adcd.length() < startIndex) {
throw new MyException("行政区划编码错误 " + adcd);
}
// String subAdcd = adcd.substring(startIndex);
int adlevelBySubAdcd = getAdlevelBySubAdcd(adcd,startIndex);
if (adlevel != adlevelBySubAdcd || adlevel+1 != adlevelBySubAdcd || adlevel-1 != adlevelBySubAdcd) {
throw new MyException("行政区划编码和行政区划等级不匹配");
}
}
/**
*
*
* @param adcd
* @return
*/
public static int getAdlevel(String adcd) {
if (StringUtils.isBlank(adcd) || adcd.length() != 15) {
throw new MyException("行政区划编码错误 " + adcd);
}
// 避免重复代码,提取为私有方法
int subAdcd = getAdlevelBySubAdcd(adcd, 2);
if (5 != subAdcd) {
return subAdcd;
}
subAdcd = getAdlevelBySubAdcd(adcd, 4);
if (5 != subAdcd) {
return subAdcd;
}
subAdcd = getAdlevelBySubAdcd(adcd, 6);
if (5 != subAdcd) {
return subAdcd;
}
subAdcd = getAdlevelBySubAdcd(adcd, 9);
if (5 != subAdcd) {
return subAdcd;
}
subAdcd = getAdlevelBySubAdcd(adcd, 12);
return subAdcd;
}
/**
*
*
* @param adcd
* @return
*/
public static int getAdlevelBySubAdcd(String adcd, int startIndex) {
String subAdcd = adcd.substring(startIndex);
// 根据行政区划分析出的行政区划等级
int expectedLevel = 0;
switch (subAdcd) {
case "0000000000000": // 省
break;
case "00000000000": // 市
expectedLevel = 1;
break;
case "000000000": // 县
expectedLevel = 2;
break;
case "000000": // 镇
expectedLevel = 3;
break;
case "000": // 村
expectedLevel = 4;
break;
default:
// 村
expectedLevel = 5;
}
return expectedLevel;
}
}

View File

@ -0,0 +1,129 @@
package com.whdc.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author
* @date 2022-07-22 8:46
*/
@Slf4j
public class DataUtils {
public static final BigDecimal MIN_VALUE = BigDecimal.valueOf(0.001);
private static Map<String, String> extension2Scheme = new HashMap<String, String>();
static {
extension2Scheme.put("jpg", "data:image/jpg;base64,");
extension2Scheme.put("jpeg", "data:image/jpeg;base64,");
extension2Scheme.put("png", "data:image/png;base64,");
extension2Scheme.put("gif", "data:image/gif;base64,");
extension2Scheme.put("icon", "data:image/x-icon;base64,");
}
/**
* σ=sqrt(s^2)
* scale
*
*
* @param value
* @param scale
* @return
*/
public static BigDecimal sqrt(BigDecimal value, int scale) {
BigDecimal num2 = BigDecimal.valueOf(2);
int precision = 100;
MathContext mc = new MathContext(precision, RoundingMode.HALF_UP);
BigDecimal deviation = value;
int cnt = 0;
while (cnt < precision) {
deviation = (deviation.add(value.divide(deviation, mc))).divide(num2, mc);
cnt++;
}
deviation = deviation.setScale(scale, BigDecimal.ROUND_HALF_UP);
return deviation;
}
public static String File2Base64(String filepath) {
if (StringUtils.isBlank(filepath)) {
return null;
}
File file1 = new File(filepath);
if (!file1.exists()) {
return null;
}
int lastPointIndex = filepath.lastIndexOf(".");
String type = filepath.substring(lastPointIndex + 1);
if (!extension2Scheme.containsKey(type.toLowerCase())) {
System.out.println("文件类型错误 " + type);
return null;
}
try (FileInputStream inputStream = new FileInputStream(file1)) {
byte[] buffer = new byte[inputStream.available()];
if (inputStream.read(buffer) == -1) {
inputStream.close();
}
return extension2Scheme.get(type.toLowerCase()) + Base64.getEncoder().encodeToString(buffer);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void DelFile(String filepath) {
File file1 = new File(filepath);
System.out.println("清理图片缓存:" + filepath + (file1.delete() ? "成功" : "失败"));
}
public static Void handleException(Throwable ex) {
log.error("请求出现异常:" + ex.getMessage(), ex);
return null;
}
public static String handleExceptionStr(Throwable ex) {
log.error("请求出现异常:" + ex.getMessage(), ex);
return null;
}
public static Integer handleExceptionInt(Throwable ex) {
log.error("请求出现异常:" + ex.getMessage(), ex);
return null;
}
/**
*
* @param elValue
* @return
*/
public static BigDecimal gcFormat(BigDecimal elValue){
if (Objects.isNull(elValue)){
return null;
}
if (BigDecimal.ZERO.equals(elValue)){
return MIN_VALUE;
}
return elValue;
}
}

View File

@ -0,0 +1,142 @@
package com.whdc.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @author
* @date 2022-06-26 1:01
*/
public class DateUtils {
/**
* (yyyy-MM-dd HH:mm:ss)
*/
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public final static String DATE_PATTERN = "yyyy年MM月dd日";
public final static String DATE_PATTERN1 = "yyyy-MM-dd";
public final static String DATE_PATTERN_HM = "HH:mm";
public static final ThreadLocal<SimpleDateFormat> sdfhmsS = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
}
};
public static final ThreadLocal<SimpleDateFormat> sdfYMDh = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm"));
public static final ThreadLocal<SimpleDateFormat> sdfhms = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(DATE_TIME_PATTERN);
}
};
public static final ThreadLocal<SimpleDateFormat> sdfymd = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(DATE_PATTERN);
}
};
public static final ThreadLocal<SimpleDateFormat> sdf_utc = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}
};
public static final ThreadLocal<SimpleDateFormat> sdf_utc_sss = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
}
};
public static final ThreadLocal<SimpleDateFormat> sdf_Str = ThreadLocal.withInitial(() -> new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"));
public static LocalDateTime strToLDT(String str,String format){
return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(format));
}
public static String dateToStr(Date date){
return sdfhms.get().format(date);
}
public static String dateToStr(LocalDateTime date){
return dateToStr(date,DATE_TIME_PATTERN);
}
public static String dateToStr(LocalDateTime date,String format){
return date.format(DateTimeFormatter.ofPattern(format));
}
public static Date dateToStr(String dateString){
try {
return sdf_Str.get().parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static Date dateToStrYMDHds(String dateString){
try {
return sdfhms.get().parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static String dateToStr(Date date, ThreadLocal<SimpleDateFormat> format){
if (Objects.isNull(date)){
return null;
}
return format.get().format(date);
}
/**
* mongo isodate
*
* @param dateStr
* @return
*/
public static Date dateToISODate(String dateStr) throws ParseException {
//T代表后面跟着时间Z代表UTC统一时间
Date date = formatD(dateStr);
SimpleDateFormat format = sdfhms.get();
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
String isoDate = format.format(date);
return format.parse(isoDate);
}
public static Date formatD(String dateStr) throws ParseException {
return formatD(dateStr, DATE_TIME_PATTERN);
}
public static Date formatD(String dateStr, String format) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.parse(dateStr);
}
public static Date standardize(Date date, boolean stm) {
Calendar c = Calendar.getInstance();
c.setTime(date);
if (stm) {
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
} else {
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
}
return c.getTime();
}
public static void main(String[] args) throws ParseException {
// System.out.println(dateToISODate("2021-11-05T13:00:00Z"));
System.out.println(dateToStr(LocalDateTime.now()));
}
}

View File

@ -0,0 +1,124 @@
package com.whdc.common.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
* Description:
* Created by XuSan on 2024/3/18.
*
* @author XuSan
* @version 1.0
*/
public class ExcelCommon {
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// "attachment;filename=" + URLEncoder.encode(fileName, "iso8859-1"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null) ;
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
return list;
}
public static <T> List<T> importExcel(String filePath, Integer startSheetIndex, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setStartSheetIndex(startSheetIndex);
List<T> list = null;
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer startSheetIndex, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setStartSheetIndex(startSheetIndex);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}

View File

@ -0,0 +1,235 @@
package com.whdc.common.utils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author lyf
* @since 2025-06-25
*/
@Slf4j
@Component
public class HttpHelper {
@Autowired
private OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// public @NotNull String get(@NotNull String url, @Nullable Map<String, String> params, @Nullable Map<String, String> headers) {
// if (url.isEmpty()) {
// return "url为空";
// }
//
// Request.Builder requestBuilder = new Request.Builder()
// .url(url)
// .get();
//
// //header
// if (headers != null) {
// for (Map.Entry<String, String> entry : headers.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// if (key != null && value != null) {
// requestBuilder.header(key, value);
// }
// }
// }
// //doGet
// Request request = requestBuilder.build();
//
// return doGet(request);
// }
//
// private @NotNull String doGet(Request request) {
// try (Response response = okHttpClient.newCall(request).execute()) {
// if (response.isSuccessful() && response.body() != null) {
// return response.body().string();
// } else {
// return "请求失败:" + response;
// }
// } catch (IOException e) {
// return "网络异常:" + e.getMessage();
// }
// }
public @NotNull String postJsonString(@NotNull String url, @Nullable String json, @Nullable Map<String, String> headers) {
return postJsonString(url, json, headers, StandardCharsets.UTF_8);
}
public @NotNull String postJsonString(@NotNull String url, @Nullable String json, @Nullable Map<String, String> headers, @NotNull Charset charset) {
if (url.isEmpty()) {
return "url为空";
}
if (json == null) {
json = "{}";
}
//mediatype
MediaType mediaType = MediaType.get("application/json");
//payload
RequestBody requestBody = RequestBody.create(json, mediaType);
//builder
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.header("Content-Type", mediaType + ";charset=" + charset.name())
.post(requestBody);
//header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
requestBuilder.header(key, value);
}
}
}
Request request = requestBuilder.build();
//post
String resp = doPost(request);
if (resp.contains("请求失败") || resp.contains("网络异常")) {
log.warn("请求失败request{}", request);
log.warn("请求失败request header{}", headers);
log.warn("请求失败request payload{}", json);
}
return resp;
}
public @NotNull String postFormData(@NotNull String url, @Nullable Map<String, Object> params, @Nullable Map<String, String> headers) {
return postFormData(url, params, headers, StandardCharsets.UTF_8);
}
public @NotNull String postFormData(@NotNull String url, @Nullable Map<String, Object> params, @Nullable Map<String, String> headers, @NotNull Charset charset) {
if (url.isEmpty()) {
return "url为空";
}
//mediatype
MediaType mediaType = MultipartBody.FORM;
//payload
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null || value == null) {
continue;
}
if (value instanceof String) {
bodyBuilder.addFormDataPart(key, (String) value);
} else if (value instanceof File) {
File file = (File) value;
RequestBody fileBody = RequestBody.create(file, MediaType.get("application/octet-stream"));
bodyBuilder.addFormDataPart(key, file.getName(), fileBody);
} else {
return "不支持的参数类型";
}
}
}
RequestBody requestBody = bodyBuilder.build();
//builder
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.header("Content-Type", mediaType + ";charset=" + charset.name())
.post(requestBody);
//header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
requestBuilder.header(key, value);
}
}
}
//post
Request request = requestBuilder.build();
String resp = doPost(request);
if (resp.contains("请求失败") || resp.contains("网络异常")) {
log.warn("请求失败request{}", request);
log.warn("请求失败request header{}", headers);
log.warn("请求失败request payload{}", params);
}
return resp;
}
public @NotNull String postFormUrlEncoded(@NotNull String url, @Nullable Map<String, Object> params, @Nullable Map<String, String> headers) {
return postFormUrlEncoded(url, params, headers, StandardCharsets.UTF_8);
}
public @NotNull String postFormUrlEncoded(@NotNull String url, @Nullable Map<String, Object> params, @Nullable Map<String, String> headers, @NotNull Charset charset) {
if (url.isEmpty()) {
return "url为空";
}
//mediatype
MediaType mediaType = MediaType.get("application/x-www-form-urlencoded");
//payload
FormBody.Builder bodyBuilder = new FormBody.Builder(charset);
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
try {
// Manually encode using GBK
String encodedValue = URLEncoder.encode(value.toString(), "GBK");
bodyBuilder.addEncoded(key, encodedValue);
} catch (Exception e) {
return "参数encode错误";
}
}
}
}
RequestBody formBody = bodyBuilder.build();
//builder
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.header("Content-Type", mediaType + ";charset=" + charset.name())
.post(formBody);
//header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
requestBuilder.header(key, value);
}
}
}
//post
Request request = requestBuilder.build();
String resp = doPost(request);
if (resp.contains("请求失败") || resp.contains("网络异常")) {
log.warn("请求失败request{}", request);
log.warn("请求失败request header{}", headers);
log.warn("请求失败request payload{}", params);
}
return resp;
}
private @NotNull String doPost(Request request) {
try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
return response.body().string();
} else {
log.warn("请求失败response{}", response);
return "请求失败:" + response;
}
} catch (IOException e) {
return "网络异常:" + e.getMessage();
}
}
}

View File

@ -0,0 +1,434 @@
package com.whdc.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whdc.common.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
@Slf4j
public class HttpUtil {
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
public static String doGetThrEx(String url, JSONObject json) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json");
if (Objects.nonNull(json)){
StringBuilder sb = new StringBuilder();
for (String key : json.keySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key).append("=").append(json.get(key));
}
url += "?" + sb;
String token = json.getString("token");
if (StringUtils.isNotBlank(token)){
httpHeaders.add("X-Access-Token", token);
}
}
org.springframework.http.HttpEntity<JSONObject> requestEntity = new org.springframework.http.HttpEntity<>(json, httpHeaders);
return REST_TEMPLATE.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody();
}
public static String doGet(String url, JSONObject json) {
try {
return doGetThrEx(url, json);
} catch (Exception e) {
throw new MyException("请求异常:" + e.getMessage(), e);
}
}
public static String get(String _url) {
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null;
String jstr = null;
try {
log.info("请求地址: " + _url);
URL url = new URL(_url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
// log.info("响应参数: " + jstr);
jstr = jsonFormat(jstr);
return jstr;
}
} else if (conn.getResponseCode() == 500) {
is = conn.getErrorStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
if (jstr.contains("Token失效请重新登录")) { // 第三方token失效处理
return "{\"code\": 301,\"extMessage\":\"Token失效请重新登录\"}";
}
}
}
} catch (Exception ignore) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignore) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
}
}
}
return null;
}
public static String getBySetCookie(String _url,String cookie) {
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null;
String jstr = null;
try {
log.info("请求地址: " + _url);
URL url = new URL(_url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (StringUtils.isNotBlank(cookie)){
// 设置cookie
conn.setRequestProperty("Cookie", cookie);
}
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
// log.info("响应参数: " + jstr);
jstr = jsonFormat(jstr);
return jstr;
}
} else if (conn.getResponseCode() == 500) {
is = conn.getErrorStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
if (jstr.contains("Token失效请重新登录")) { // 第三方token失效处理
return "{\"code\": 301,\"extMessage\":\"Token失效请重新登录\"}";
}
}
}
} catch (Exception ignore) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignore) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
}
}
}
return null;
}
public static String get(String _url, String authorization) {
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null;
String jstr = null;
try {
log.info("请求地址: " + _url);
URL url = new URL(_url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", authorization);
conn.setRequestMethod("GET");
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.connect();
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
// log.info("响应参数: " + jstr);
jstr = jsonFormat(jstr);
return jstr;
}
} else if (conn.getResponseCode() == 500) {
is = conn.getErrorStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
if (jstr.contains("Token失效请重新登录")) { // 第三方token失效处理
return "{\"code\": 301,\"extMessage\":\"Token失效请重新登录\"}";
}
}
}
} catch (Exception ignore) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignore) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
}
}
}
return null;
}
public static String get(String _url, String token, String forward) {
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null;
String jstr = null;
try {
log.info("请求地址: " + _url);
URL url = new URL(_url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("X-Access-Token", token);
conn.setRequestProperty("url", forward);
conn.setRequestMethod("GET");
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.connect();
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
// log.info("响应参数: " + jstr);
jstr = jsonFormat(jstr);
return jstr;
}
} else if (conn.getResponseCode() == 500) {
is = conn.getErrorStream();
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
jstr = sb.toString();
if (jstr.contains("Token失效请重新登录")) { // 第三方token失效处理
return "{\"code\": 301,\"extMessage\":\"Token失效请重新登录\"}";
}
}
}
} catch (Exception ignore) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignore) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
}
}
}
return null;
}
/**
* @param url
* @param jsonData
* @return
*/
public static String sendPost(String url, String jsonData) {
return sendPost(url, jsonData, null);
}
public static String sendPost(String url, String jsonData, JSONObject header) {
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
if (Objects.nonNull(header)) {
for (String key : header.keySet()) {
// httpPost.addHeader("X-Access-Token", token);
httpPost.addHeader(key, header.getString(key));
}
}
if (StringUtils.isNotBlank(jsonData)){
httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
}
log.info("请求地址: " + url);
log.info("请求header: " + header);
log.info("请求参数: " + jsonData);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
responseContent = jsonFormat(responseContent);
if (responseContent.length() < 200) {
log.info("响应参数: " + responseContent);
}
} catch (Exception e) {
log.error("发送请求异常", e);
throw new MyException("发送请求异常", e);
} finally {
try {
if (null != response) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
private static String jsonFormat(String str) {
if (JSON.isValidObject(str)) {
str = JSON.parseObject(str).toJSONString();
}
return str;
}
}

View File

@ -0,0 +1,31 @@
package com.whdc.common.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
/**
* @author xusan
* @date 2023/4/17 16:44
*/
public class JsonUtils {
public static boolean isJson(String str) {
if (StringUtils.isBlank(str)){
return false;
}
try {
JSONObject.parseObject(str);
return true;
} catch (Exception e) {
return false;
}
}
public static void updateJson(JSONObject jsonObject,String key){
String data = jsonObject.getString("DATA");
if (StringUtils.isNotBlank(data) && StringUtils.isBlank(jsonObject.getString(key))){
jsonObject.put(key,data);
}
}
}

View File

@ -0,0 +1,25 @@
package com.whdc.common.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
/**
* @author xusan
* @date 2023/4/11 15:03
*/
public class NumUtils {
public static Pattern isNumber = Pattern.compile("^-?\\d+(\\.\\d+)?$");
public static boolean isNumber(String number) {
// 非空校验
if (StringUtils.isEmpty(number)) {
return false;
}
// 数字校验(可以包含小数可以是1,9,-1,1.1,-1.1,不能是+1.1,+1)
// 这个支持+1.1,+1
// Pattern pattern = Pattern.compile("[+-]?[@-9]+(\\\\.[0-9]+)?");
return isNumber.matcher(number).matches();
}
}

View File

@ -0,0 +1,113 @@
package com.whdc.common.utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
/**
* @author xusan
* @date 2023/4/13 14:19
*/
public class RedisConfUtils {
public static StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
public static void setStringRedisSerializer(RedisTemplate<String, Object> redisTemplate) {
if (!Objects.isNull(redisTemplate)) {
if (!(redisTemplate.getKeySerializer() instanceof StringRedisSerializer)) {
redisTemplate.setKeySerializer(stringRedisSerializer);
}
}
}
public static void setDefaultRedisSerializer(RedisTemplate<String, Object> redisTemplate) {
if (!Objects.isNull(redisTemplate)) {
if (redisTemplate.getKeySerializer() instanceof StringRedisSerializer) {
redisTemplate.setKeySerializer(redisTemplate.getHashKeySerializer());
}
}
}
public static void setStringRedisSeria(RedisTemplate<String, String> redisTemplate) {
if (!Objects.isNull(redisTemplate)) {
if (!(redisTemplate.getKeySerializer() instanceof StringRedisSerializer)) {
redisTemplate.setKeySerializer(stringRedisSerializer);
}
}
}
public static void setDefaultRedisSeria(RedisTemplate<String, String> redisTemplate) {
if (!Objects.isNull(redisTemplate)) {
if (redisTemplate.getKeySerializer() instanceof StringRedisSerializer) {
redisTemplate.setKeySerializer(redisTemplate.getHashKeySerializer());
}
}
}
public static Object get(String key, RedisTemplate<String, Object> redisTemplate) {
try {
setStringRedisSerializer(redisTemplate);
return redisTemplate.opsForValue().get(key);
} finally {
setDefaultRedisSerializer(redisTemplate);
}
}
public static void set(String key, Object o, RedisTemplate<String, Object> redisTemplate) {
try {
setStringRedisSerializer(redisTemplate);
redisTemplate.opsForValue().set(key, o);
} finally {
setDefaultRedisSerializer(redisTemplate);
}
}
public static Set<String> getKeys(String key, RedisTemplate<String, Object> redisTemplate) {
try {
setStringRedisSerializer(redisTemplate);
return redisTemplate.keys(key + "*");
} finally {
setDefaultRedisSerializer(redisTemplate);
}
}
public static Boolean hasKey(String key, RedisTemplate<String, Object> redisTemplate) {
try {
setStringRedisSerializer(redisTemplate);
return redisTemplate.hasKey(key);
} finally {
setDefaultRedisSerializer(redisTemplate);
}
}
public static void delete(String key, RedisTemplate<String, String> redisTemplate) {
try {
setStringRedisSeria(redisTemplate);
redisTemplate.delete(key);
} finally {
setDefaultRedisSeria(redisTemplate);
}
}
public static void delete(Collection<String> keys, RedisTemplate<String, String> redisTemplate) {
try {
setStringRedisSeria(redisTemplate);
redisTemplate.delete(keys);
} finally {
setDefaultRedisSeria(redisTemplate);
}
}
}

View File

@ -0,0 +1,128 @@
package com.whdc.common.utils;
import javax.servlet.http.HttpServletRequest;
public class ReqUtils {
private static final String dbPath = null;
/**
* IP使request.getRemoteAddr();使IP,
* X-Forwarded-ForIPIP
* X-Forwarded-ForunknownIP
* X-Forwarded-For192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
* IP 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {// 获取客户端ip地址
String clientIp = request.getHeader("x-forwarded-for");
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getHeader("Proxy-Client-IP");
}
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getHeader("WL-Proxy-Client-IP");
}
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getRemoteAddr();
}
/*
* ipip.
*/
String sIP = null;
if (clientIp != null && !clientIp.contains("unknown") && clientIp.indexOf(",") > 0) {
String[] ipsz = clientIp.split(",");
for (String anIpsz : ipsz) {
if (!isInnerIP(anIpsz.trim())) {
sIP = anIpsz.trim();
break;
}
}
/*
* ipipip.
*/
if (null == sIP) {
sIP = ipsz[0].trim();
}
clientIp = sIP;
}
if (clientIp != null && clientIp.contains("unknown")) {
clientIp = clientIp.replaceAll("unknown,", "");
clientIp = clientIp.trim();
}
if ("".equals(clientIp) || null == clientIp) {
clientIp = "127.0.0.1";
}
return clientIp;
}
/**
* IP
*
* @param ipAddress ip
* @return
*/
public static boolean isInnerIP(String ipAddress) {
boolean isInnerIp;
long ipNum = getIpNum(ipAddress);
/**
IPA 10.0.0.0-10.255.255.255
B 172.16.0.0-172.31.255.255
C 192.168.0.0-192.168.255.255
127
**/
long aBegin = getIpNum("10.0.0.0");
long aEnd = getIpNum("10.255.255.255");
long bBegin = getIpNum("172.16.0.0");
long bEnd = getIpNum("172.31.255.255");
long cBegin = getIpNum("192.168.0.0");
long cEnd = getIpNum("192.168.255.255");
isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd)
|| ipAddress.equals("127.0.0.1");
return isInnerIp;
}
private static long getIpNum(String ipAddress) {
String[] ip = ipAddress.split("\\.");
long a = Integer.parseInt(ip[0]);
long b = Integer.parseInt(ip[1]);
long c = Integer.parseInt(ip[2]);
long d = Integer.parseInt(ip[3]);
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
}
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
public static String getRealIP(HttpServletRequest request) {
// 获取客户端ip地址
String clientIp = request.getHeader("x-forwarded-for");
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getRemoteAddr();
}
String[] clientIps = clientIp.split(",");
if (clientIps.length <= 1) return clientIp.trim();
// 判断是否来自CDN
if (isComefromCDN(request)) {
if (clientIps.length >= 2) return clientIps[clientIps.length - 2].trim();
}
return clientIps[clientIps.length - 1].trim();
}
private static boolean isComefromCDN(HttpServletRequest request) {
String host = request.getHeader("host");
return host.contains("www.189.cn") ||
host.contains("shouji.189.cn") ||
host.contains("image2.chinatelecom-ec.com") ||
host.contains("image1.chinatelecom-ec.com");
}
}

View File

@ -0,0 +1,171 @@
package com.whdc.common.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
@ApiModel(description = "数据传输对象")
@Component
@SuppressWarnings("all")
public class ResultJson<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
public static final Integer SUCCESS = 200;
private static final String SUCCESS_MSG = "success";
/**
*
*/
public static final Integer FAIL = 900;
private static final String FAIL_MSG = "fail";
public static final Integer PARAM_ERROR = 400; // 失败、参数错误等
public static final Integer UNAUTHORIZED = 401; // 用户验证失败,或者用户验证信息过期
public static final Integer PERMISSION_DENIED = 403; // 没有权限
public static final Integer NOT_FOUND = 404; // 未找到资源
public static final Integer METHOD_NOT_ALLOWED = 405; // 不支持的类型
public static final Integer NSUPPORTED_MEDIA_TYPE = 415; // 不支持的媒体
public static final Integer NOT_ALLOWED = 405; // 请求太频繁同一个用户token)、同一个url、同样的请求参数请求间隔小于0.5秒
public static final Integer SERVER_ERROR = 500; // 后台错误
public static final Integer SRC_TIMEOUT = 504; // 请求资源超时
@ApiModelProperty("数据消息")
private String msg;
@ApiModelProperty("传输状态码200=成功400=参数错误; 500=后端错误900=失败)")
private Integer code;
@ApiModelProperty("传输数据")
private T data;
@ApiModelProperty("接口响应时间戳")
private String restm; // 接口响应时间戳。如果有缓存,则该时间表示最后接口响应时间
public static ResultJson error() {
return error(FAIL, "未知异常,请联系管理员");
}
public static ResultJson error(String msg) {
return error(FAIL, msg);
}
public static ResultJson error(int code, String msg) {
ResultJson r = new ResultJson();
r.setCode(code);
r.setMsg(msg);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public static ResultJson error(int code, String msg, Object data) {
ResultJson r = new ResultJson();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public static ResultJson ok(Integer code, String msg) {
ResultJson r = new ResultJson();
r.setMsg(msg);
r.setCode(code);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public static ResultJson ok() {
ResultJson r = new ResultJson();
r.setCode(SUCCESS);
r.setMsg(SUCCESS_MSG);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public static ResultJson ok(Object data) {
ResultJson r = new ResultJson();
r.setCode(SUCCESS);
r.setMsg(SUCCESS_MSG);
r.setData(data);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public static ResultJson ok(Object data, String msg) {
ResultJson r = new ResultJson();
r.setData(data);
r.setCode(SUCCESS);
r.setMsg(msg);
r.setRestm(DateUtils.sdfhmsS.get().format(new Date()));
return r;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public static Integer getSUCCESS() {
return SUCCESS;
}
public static String getSuccessMsg() {
return SUCCESS_MSG;
}
public static Integer getFAIL() {
return FAIL;
}
public static String getFailMsg() {
return FAIL_MSG;
}
public String getRestm() {
return restm;
}
public void setRestm(String restm) {
this.restm = restm;
}
@Override
public String toString() {
return "ResultJson{" +
"msg='" + msg + "'" +
", code=" + code +
", data=" + data +
", restm=" + restm +
'}';
}
}

View File

@ -0,0 +1,55 @@
package com.whdc.common.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
/**
* Description:
* Created by XuSan on 2024/6/13.
*
* @author XuSan
* @version 1.0
*/
public class SymmetricEncryption {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
public static void main(String[] args) throws Exception {
String encryptedData = encrypt("82402321", "0492716ae0314f0496d62e0de215059a");
String decryptedData = decrypt("lJM1xLd93ghNeWVTNNjjJw==", "4e1f078b917d4c7ca3e7eec1f683d3c2");
System.out.println("Original Data: " + 82402321);
System.out.println("Encrypted Data: " + encryptedData);
System.out.println("Decrypted Data: " + decryptedData);
}
public static String encrypt(String data, String password) throws Exception {
SecretKey key = generateKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData, String password) throws Exception {
SecretKey key = generateKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData);
}
private static SecretKey generateKey(String password) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
keyGenerator.init(KEY_SIZE, secureRandom);
// keyGenerator.init(KEY_SIZE, new SecureRandom(password.getBytes()));
return new SecretKeySpec(keyGenerator.generateKey().getEncoded(), ALGORITHM);
}
}

127
module-legacy/pom.xml Normal file
View File

@ -0,0 +1,127 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.whdc</groupId>
<artifactId>fxkh-txl-parent</artifactId>
<version>1.0</version>
<relativePath>../poms/dependency.xml</relativePath>
</parent>
<artifactId>fxkh-txl-legacy</artifactId>
<packaging>jar</packaging>
<description>防汛抗旱通讯录API - 启动模块</description>
<dependencies>
<!-- Web Module -->
<dependency>
<groupId>com.whdc</groupId>
<artifactId>fxkh-txl-sms</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.jeffreyning</groupId>
<artifactId>mybatisplus-plus</artifactId>
</dependency>
<!-- Database -->
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmJdbcDriver18</artifactId>
</dependency>
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmDialect-for-hibernate4.0</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- PDF Generation -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>forms</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>svg</artifactId>
</dependency>
<!-- Sa-Token 权限认证, 在线文档http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
</dependency><!-- Sa-Token 整合 Redis (使用 jackson 序列化方式) -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
</dependency>
<!-- Dev Tools -->
</dependencies>
<build>
<plugins>
<!-- <plugin>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-maven-plugin</artifactId>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>repackage</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
</plugins>
</build>
</project>

View File

@ -0,0 +1,42 @@
package com.whdc.legacy;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.whdc.common.config.CommonModuleConfig;
import com.whdc.sms.config.SmsModuleConfig;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author
* @date 2022-06-26 0:17
*/
@Slf4j
@EnableWebMvc
@EnableKnife4j
@EnableCaching
@EnableScheduling
@SpringBootApplication
@MapperScan("com.whdc.**.mapper")
@EnableTransactionManagement
@Import({SmsModuleConfig.class, CommonModuleConfig.class})
public class FxkhTxlApiApplication {
public static void main(String[] args) {
try {
SpringApplication.run(FxkhTxlApiApplication.class, args);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>> 启动完成 <<<<<<<<<<<<<<<<<<<<<<<<<<<");
} catch (BeansException e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,212 @@
package com.whdc.legacy.component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whdc.legacy.model.dto.ApiDto;
import com.whdc.legacy.model.entity.QXWarning;
import com.whdc.legacy.model.entity.ShAddressBook;
import com.whdc.legacy.model.vo.QXWarningVO;
import com.whdc.legacy.model.vo.WarningData;
import com.whdc.legacy.service.IQXWarningService;
import com.whdc.legacy.service.ShAddressBookService;
import com.whdc.common.utils.DateUtils;
import com.whdc.common.utils.HttpUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.whdc.legacy.controller.QXWarnController.QX_TEMP_REDIS_KEY;
/**
* @author
* @date 2022-07-17 15:33
*/
@Component
@Slf4j
@ConditionalOnProperty(
name = "enableSchedules.qxwarning",
havingValue = "true"
)
public class MyPostConstruct {
@Autowired
private ShAddressBookService shAddressBookService;
@Value("${getGroupWarning}")
public String getGroupWarning;
@PostConstruct
public void initCache() {
log.debug("加载缓存");
// 预警初始化
QXWarningInit();
}
@Autowired
private IQXWarningService service;
@Autowired
private RedisTemplate<String, String> stringRedisTemplate;
@Async
@ApiOperation(value = "预警数据同步接口", notes = "预警数据同步接口")
@GetMapping("/syncData")
@Scheduled(cron ="*/20 * * * * ?")
public void syncData() {
LocalDateTime now = LocalDateTime.now();
sync(DateUtils.dateToStr(now.minusHours(1)),DateUtils.dateToStr(now.plusHours(1)));
// sync(null,null);
}
/**
*
*/
private void QXWarningInit(){
long count = service.count();
if (count > 0){
return;
}
LocalDateTime now = LocalDateTime.now();
sync(DateUtils.dateToStr(now.minusYears(1)),DateUtils.dateToStr(now));
}
public void sync(String stm,String etm) {
log.info("预警数据同步开始!!!");
ApiDto apiDto = new ApiDto();
if (StringUtils.isNotBlank(stm)){
log.info("开始时间 " + stm);
apiDto.setStartTime(stm);
}
if (StringUtils.isNotBlank(etm)){
log.info("结束时间 " + etm);
apiDto.setEndTime(etm);
}
apiDto.setFilter(Lists.newArrayList());
String str = HttpUtil.sendPost(getGroupWarning, JSON.toJSONString(apiDto));
// String str = HttpUtil.sendPost("http://127.0.0.1:20000/shzh/met/zyqxfw/api/warning/getGroupWarning", JSON.toJSONString(apiDto));
JSONObject json = JSON.parseObject(str);
if (json != null && json.getInteger("code") == HttpStatus.SC_OK) {
List<WarningData> data = json.getJSONArray("data").toJavaList(WarningData.class);
List<QXWarningVO> warningList = getList(data);
log.info("预警数据同步获取数据条数 " + warningList.size());
List<Integer> warnIds = warningList.stream().map(QXWarningVO::getWarnid).collect(Collectors.toList());
List<QXWarning> list = service.lambdaQuery().in(QXWarning::getWarnid, warnIds).list();
log.info("预警数据同步已存预警 " + list.size());
Set<Integer> dbWarnSet = list.stream().map(QXWarning::getWarnid).collect(Collectors.toSet());
List<QXWarning> adds = Lists.newArrayList();
for (QXWarningVO warningVO : warningList) {
if (!dbWarnSet.contains(warningVO.getWarnid())) {
QXWarning qxwarning = new QXWarning();
qxwarning.setCreateTime(DateUtils.dateToStrYMDHds(warningVO.getCreateTime()));
qxwarning.setPublishTime(DateUtils.dateToStrYMDHds(warningVO.getPublishTime()));
qxwarning.setStartTime(DateUtils.dateToStrYMDHds(warningVO.getStartTime()));
qxwarning.setEndTime(DateUtils.dateToStrYMDHds(warningVO.getEndTime()));
qxwarning.setWarnSignalType(warningVO.getWarnSignalType());
qxwarning.setWarnSignalLevel(warningVO.getWarnSignalLevel());
qxwarning.setPublishUnit(warningVO.getPublishUnit());
qxwarning.setContent(warningVO.getContent());
qxwarning.setWarnid(warningVO.getWarnid());
qxwarning.setCtnm(warningVO.getCtnm());
qxwarning.setCnnm(warningVO.getCnnm());
stringRedisTemplate.opsForValue().set(QX_TEMP_REDIS_KEY + qxwarning.getWarnid(),JSON.toJSONString(warningVO));
adds.add(qxwarning);
}
}
if (CollectionUtils.isNotEmpty(adds)) {
log.info("预警数据同步待添加预警 " + adds.size());
if (this.service.saveBatch(adds)) {
log.info("添加成功 " + adds.size());
}
}
}
log.info("预警数据同步执行完成!!!");
}
private List<QXWarningVO> getList(List<WarningData> data) {
List<QXWarningVO> respList = Lists.newArrayList();
for (WarningData datum : data) {//最外层的列表
String ctnm = datum.getEffectArea();//市级范围
for (WarningData.TypeList typeList : datum.getTypeList()) {//里面的
// 预警类型
String type = typeList.getType();
List<WarningData.Warning> warnList = typeList.getWarnList();
for (WarningData.Warning warning : warnList) {
String cnnm = warning.getEffectArea();
QXWarningVO vo = new QXWarningVO();
String publishUnit = warning.getPublishUnit();
// vo.setTitle(publishUnit + "发布" + type + "预警");
vo.setCtnm(ctnm);//市级名称
vo.setCnnm(cnnm);//县级名称
vo.setPublishUnit(publishUnit);//发布单位
vo.setPublishTime(warning.getPublishTime());//预警发布时间
vo.setWarnSignalType(warning.getWarnSignalType());//预警类型
vo.setWarnSignalLevel(warning.getWarnSignalLevel());//预警级别
vo.setContent(warning.getContent());//预警内容
vo.setWarnid(warning.getId());
vo.setCreateTime(warning.getCreateTime());
vo.setStartTime(warning.getStartTime());
vo.setEndTime(warning.getEndTime());
respList.add(vo);
}
}
}
respList = respList.stream().filter(o -> "暴雨".equals(o.getWarnSignalType()) || "雷雨大风".equals(o.getWarnSignalType())).collect(Collectors.toList());
respList = respList.stream().filter(o -> "红色".equals(o.getWarnSignalLevel()) || "橙色".equals(o.getWarnSignalLevel())).collect(Collectors.toList());
return respList.stream().sorted(Comparator.comparing(QXWarningVO::getPublishTime).reversed())
.collect(Collectors.toList());
}
@Async
@ApiOperation(value = "恢复山洪负责人抽查状态定时任务", notes = "预警数据同步接口")
@GetMapping("/recoveryShAddressBookSpotCheck")
@Scheduled(cron = "0 0 0 * * ?")
public void recoveryShAddressBookSpotCheck() {
boolean update = shAddressBookService.lambdaUpdate()
.set(ShAddressBook::getIsSpotCheck, 0)
.set(ShAddressBook::getCallStatus, 0)
.eq(ShAddressBook::getIsSpotCheck, 1)
.eq(ShAddressBook::getDel, 1)
.update();
log.info("恢复山洪负责人抽查状态定时任务执行结果: " + update);
}
}

View File

@ -0,0 +1,100 @@
package com.whdc.legacy.controller;
import com.whdc.legacy.model.entity.AbUdR;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.IAbUdRService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "用户单位字典关联表 - Controller")
@RestController
@RequestMapping("/abudr")
public class AbUdRController {
@Autowired
private IAbUdRService service;
@ApiOperation(value = "查询所有")
@PostMapping(value = "find")
public ResultJson<AbUdR> find(@RequestBody AbUdR dto) {
return ResultJson.ok(service.find(dto));
}
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<AbUdR> page(@RequestBody AbUdR dto) {
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) AbUdR model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AbUdR::getAdId,String.valueOf(model.getAdId()).trim())
.eq(AbUdR::getDictId,String.valueOf(model.getDictId() ).trim())
.list())
){
return ResultJson.error("重复新增");
}
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) AbUdR model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AbUdR::getAdId,String.valueOf(model.getAdId()).trim())
.eq(AbUdR::getDictId,String.valueOf(model.getDictId() ).trim())
.list())
){
return ResultJson.error("重复修改");
}
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,185 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whdc.legacy.mapper.AddressBookCityMapper;
import com.whdc.legacy.model.dto.AddressBookCityDto;
import com.whdc.legacy.model.entity.AddressBookCity;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.IAddressBookCityService;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import static com.whdc.legacy.model.MyConstant.DEL;
import static com.whdc.legacy.model.MyConstant.REC;
/**
* Description:
* Created by XuSan on 2024/8/21.
*
* @author XuSan
* @version 1.0
*/
@Slf4j
@Api(tags = "市级责任人通讯录 - Controller")
@RestController
@RequestMapping("/addressbookCity")
@Transactional
public class AddressBookCityController {
@Autowired
private AddressBookCityMapper thisMapper;
@Autowired
private IAddressBookCityService thisService;
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<AddressBookCity> page(@RequestBody AddressBookCityDto dto) {
LambdaQueryWrapper<AddressBookCity> query = new LambdaQueryWrapper<>();
if (!Objects.isNull(dto.getName())) {
query.like(AddressBookCity::getName, dto.getName());
}
if (!Objects.isNull(dto.getUnit())) {
query.like(AddressBookCity::getUnit, dto.getUnit());
}
if (!Objects.isNull(dto.getPhone())) {
query.like(AddressBookCity::getPhone, dto.getPhone());
}
query.eq(AddressBookCity::getDel, REC);
query.orderByAsc(AddressBookCity::getId);
return ResultJson.ok(thisMapper.selectPage(dto.getPage(), query));
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson<Boolean> insert(@RequestBody @Validated(Insert.class) AddressBookCity model) {
LambdaQueryWrapper<AddressBookCity> query = new LambdaQueryWrapper<>();
query.eq(AddressBookCity::getName, model.getName());
query.eq(AddressBookCity::getPhone, model.getPhone());
query.eq(AddressBookCity::getDel, REC);
if (thisMapper.selectCount(query) > 0) {
return ResultJson.error("当前名字,手机号已存在");
}
model.setId(null);
return ResultJson.ok(thisMapper.insert(model) == 1);
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson<Boolean> update(@RequestBody @Validated(Update.class) AddressBookCity model) {
AddressBookCity obj = thisMapper.selectById(model.getId());
if (Objects.isNull(obj)) {
return ResultJson.error("当前数据不存在");
}
LambdaQueryWrapper<AddressBookCity> query = new LambdaQueryWrapper<>();
query.eq(AddressBookCity::getName, model.getName());
query.eq(AddressBookCity::getPhone, model.getPhone());
query.eq(AddressBookCity::getDel, REC);
query.ne(AddressBookCity::getId, model.getId());
if (thisMapper.selectCount(query) > 0) {
return ResultJson.error("当前名字,手机号已存在");
}
return ResultJson.ok(thisMapper.updateById(model) == 1);
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson<Boolean> delete(@PathVariable("id") Integer id) {
if (Objects.isNull(thisMapper.selectById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(thisMapper.deleteById(id) == 1);
}
@ApiOperation(value = "导出")
@PostMapping(value = "download")
public void download(HttpServletResponse response,@RequestBody AddressBookCityDto dto) {
LambdaQueryWrapper<AddressBookCity> query = new LambdaQueryWrapper<>();
if (!Objects.isNull(dto.getName())) {
query.like(AddressBookCity::getName, dto.getName());
}
if (!Objects.isNull(dto.getUnit())) {
query.like(AddressBookCity::getUnit, dto.getUnit());
}
if (!Objects.isNull(dto.getPhone())) {
query.like(AddressBookCity::getPhone, dto.getPhone());
}
query.eq(AddressBookCity::getDel, REC);
query.orderByAsc(AddressBookCity::getId);
List<AddressBookCity> list = thisMapper.selectList(query);
AtomicInteger i = new AtomicInteger(1);
list.forEach(o -> o.setId(i.getAndIncrement()));
ExcelCommon.exportExcel(list,
null, "市级责任人通讯录", AddressBookCity.class, "市级责任人通讯录" + LocalDateTime.now() + ".xlsx",
response);
}
@ApiOperation(value = "导入")
@PostMapping(value = "Import")
public ResultJson<String> Import(MultipartFile file) {
List<AddressBookCity> appends = ExcelCommon.importExcel(file, 0, 1, AddressBookCity.class);
if (CollectionUtils.isNotEmpty(appends)) {
long count = appends.stream().filter(o -> StringUtils.isEmpty(o.getName()) || StringUtils.isEmpty(o.getPhone()))
.count();
if (count > 0) {
return ResultJson.error("姓名和手机号不能为空");
}
boolean update = thisService.lambdaUpdate().set(AddressBookCity::getDel, DEL)
.eq(AddressBookCity::getDel, REC)
.update();
if (!update) {
log.info("更新失败");
}
appends.forEach(o -> o.setId(null)
.setName(StringUtils.deleteWhitespace(o.getName()))
.setPhone(StringUtils.deleteWhitespace(o.getPhone()))
.setUnit(StringUtils.deleteWhitespace(o.getUnit()))
.setPosition(StringUtils.deleteWhitespace(o.getPosition()))
.setComments(StringUtils.deleteWhitespace(o.getComments()))
);
boolean data = thisService.saveBatch(appends);
if (data) {
return ResultJson.ok("上传成功");
}
}
return ResultJson.error("上传失败");
}
}

View File

@ -0,0 +1,829 @@
package com.whdc.legacy.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.AddressBookDto;
import com.whdc.legacy.model.entity.AbUdR;
import com.whdc.legacy.model.entity.AddressBook;
import com.whdc.legacy.model.entity.Organization;
import com.whdc.legacy.model.entity.User;
import com.whdc.legacy.model.enums.Role;
import com.whdc.legacy.model.enums.VersionsType;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.AdcdTree;
import com.whdc.legacy.model.vo.AddressBookVo;
import com.whdc.legacy.model.vo.ExcelABVo;
import com.whdc.legacy.model.vo.ExcelDataVo;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import com.whdc.legacy.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static com.whdc.legacy.model.MyConstant.REDIS_KEY;
import static com.whdc.legacy.service.impl.AdinfoServiceImpl.TREE_ALL;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "通讯录 - Controller")
@RestController
@RequestMapping("/addressbook")
@Transactional
public class AddressBookController {
public static final String ADDRESS_BOOK_REDIS_KEY = REDIS_KEY + "addressbook";
public static final String ADDRESS_BOOK_TEMP_REDIS_KEY = ADDRESS_BOOK_REDIS_KEY + "temp:";
@Autowired
private IAddressBookService service;
@Autowired
private IUserService userService;
@Autowired
private IAdinfoService adinfoService;
@Autowired
private IVersionsService versionsService;
@Autowired
private IOrganizationService organizationsService;
@Autowired
private IAbUdRService abUdRService;
@Autowired
private RedisTemplate<String,String> redisTemplate;
// @ApiOperation(value = "查询所有")
// @PostMapping(value = "find")
// public ResultJson<AddressBook> find(@RequestBody AddressBook dto) {
//
// return ResultJson.ok(service.find(dto));
//
// }
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<AddressBookVo> page(@RequestBody AddressBookDto dto) {
dto.setUserId(String.valueOf(StpUtil.getLoginId()));
IPage<AddressBookVo> page = service.page(dto);
// return ResultJson.ok(JSON.parseObject(JSON.toJSONString(page).replaceAll("null","")));
return ResultJson.ok(page);
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
@CacheEvict(value = ADDRESS_BOOK_REDIS_KEY, allEntries = true)
public ResultJson insert(@RequestBody @Validated(Insert.class) AddressBook model) {
User user = userService.getRole(Integer.valueOf(String.valueOf(StpUtil.getLoginId())));
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
return ResultJson.error("权限不足");
case R001:
case R099:
if (Integer.parseInt(model.getRole()) > Integer.parseInt(user.getRole())) {
return ResultJson.error("权限不足!");
}
break;
default:
return ResultJson.error("权限不足!!");
}
if (StringUtils.isNotBlank(model.getRole())) {
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
case R001:
case R099:
break;
default:
return ResultJson.error("权限不匹配");
}
if (Integer.parseInt(user.getRole()) < Integer.parseInt(model.getRole())) {
return ResultJson.error("权限不足!");
}
}
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AddressBook::getName, String.valueOf(model.getName()).trim())
.list())
) {
return ResultJson.error("该名称重复");
}
if (StringUtils.isNotBlank(model.getPhone()) && CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AddressBook::getPhone, model.getPhone().trim())
.list())
) {
return ResultJson.error("该手机号已存在");
}
model.setId(null);
boolean save = service.save(model);
// 添加日志
String adcd = model.getAdcd();
versionsService.saveInfo(model, VersionsType.ADD, adcd);
if (save) {
redisTemplate.delete(ADDRESS_BOOK_REDIS_KEY + "*");
// 没有手机号用名字注册
//"省防指".equals(organizationsService.getById(model.getOrganization()).getName())
// &&
if (StringUtils.isBlank(model.getPhone())) {
if (StringUtils.isNotBlank(model.getTel())) {
userService.register(model.getTel(), model.getId(), model.getRole());
} else {
userService.register(model.getName(), model.getId(), model.getRole());
}
} else {
userService.register(model.getPhone(), model.getId(), model.getRole());
}
if (StringUtils.isNotBlank(adcd)) {
List<AbUdR> list = abUdRService.lambdaQuery().eq(AbUdR::getDictId, model.getAdcd())
.select(AbUdR::getSort)
.orderByDesc(AbUdR::getSort)
.list();
Integer sort = 0;
if (CollectionUtils.isNotEmpty(list)) {
AbUdR abUdR = list.get(0);
sort = abUdR.getSort() + 1;
}
abUdRService.save(new AbUdR(model.getId(), adcd.replaceFirst("000000", ""), ++sort, model.getType()));
} else {
List<AbUdR> list = abUdRService.lambdaQuery().eq(AbUdR::getDictId, model.getOrganization())
.select(AbUdR::getSort)
.orderByDesc(AbUdR::getSort)
.list();
Integer sort = 0;
if (CollectionUtils.isNotEmpty(list)) {
AbUdR abUdR = list.get(0);
sort = abUdR.getSort() + 1;
}
// 添加关联关系`
abUdRService.save(new AbUdR(model.getId(), model.getOrganization(), sort, model.getType()));
}
}
return ResultJson.ok(save);
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
@CacheEvict(value = ADDRESS_BOOK_REDIS_KEY, allEntries = true)
public ResultJson update(@RequestBody @Validated(Update.class) AddressBook model) {
Integer loginId = Integer.valueOf(String.valueOf(StpUtil.getLoginId()));
User user = userService.getRole(loginId);
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000: {
// 不是修改自己
if (!model.getId().equals(user.getAbId())) {
return ResultJson.error("权限不足");
}
}
;
case R001:
case R099:
if (Integer.parseInt(model.getRole()) > Integer.parseInt(user.getRole())) {
return ResultJson.error("权限不足!");
}
break;
default:
return ResultJson.error("权限不足!!");
}
if (StringUtils.isNotBlank(model.getRole())) {
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
case R001:
case R099:
break;
default:
return ResultJson.error("权限不匹配");
}
if (Integer.parseInt(user.getRole()) < Integer.parseInt(model.getRole())) {
return ResultJson.error("权限不足!");
}
}
AddressBook byId = service.getById(model.getId());
if (Objects.isNull(byId)) {
return ResultJson.error("当前数据不存在");
}
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AddressBook::getName, String.valueOf(model.getName()).trim())
.ne(AddressBook::getId, model.getId())
.list())
) {
return ResultJson.error("该名称重复");
}
if (StringUtils.isNotBlank(model.getPhone()) && CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(AddressBook::getPhone, model.getPhone().trim())
.ne(AddressBook::getId, model.getId())
.list())
) {
return ResultJson.error("该手机号已存在");
}
// List<Versions> list = versionsService.lambdaQuery()
// .eq(Versions::getAbId, model.getId())
// .list();
// Integer version = 0;
// if (CollectionUtils.isNotEmpty(list)){
// version = list
// .stream().map(Versions::getVersion)
// .max(Comparator.comparing(Integer::intValue))
// .get();
// }else{
// log.info("当前数据在进行修改但无相关记录;" + model.getId());
// }
// // 添加日志
// versionsService.save(new Versions(null, JSON.toJSONString(model),model.getId(),++version,model.getCreateId(),new Date(), VersionsType.UPDATE.getName()));
String adcd = model.getAdcd();
if (StringUtils.isBlank(adcd)) {
adcd = byId.getAdcd();
}
model.setRole(user.getRole());
versionsService.saveInfo(model, VersionsType.UPDATE, adcd);
boolean data = service.updateById(model);
if (data) {
redisTemplate.delete(ADDRESS_BOOK_REDIS_KEY + "*");
String organization = model.getOrganization();
if (StringUtils.isNotBlank(model.getAdcd())) {
organization = model.getAdcd().replaceFirst("000000", "");
}
Integer sort = model.getSort();
if (0 != sort) {
boolean update = abUdRService.lambdaUpdate()
.set(AbUdR::getSort, sort)
.set(AbUdR::getDictId, organization)
.eq(AbUdR::getAdId, model.getId())
.update();
log.info("修改abUdR: " + update);
}
User one = userService.lambdaQuery().eq(User::getAbId, model.getId()).one();
if (Objects.nonNull(one)) {
// 没有就创建账号
if (StringUtils.isBlank(model.getPhone())) {
if (StringUtils.isNotBlank(model.getTel())) {
if (!one.getUsername().equals(model.getTel())) {
one.setUsername(model.getTel())
.updateById();
}
} else {
if (!one.getUsername().equals(model.getName())) {
one.setUsername(model.getName())
.updateById();
}
}
} else {
if (!one.getUsername().equals(model.getPhone())) {
one.setUsername(model.getPhone())
.updateById();
}
}
} else {
// 没有就创建账号
if (StringUtils.isBlank(model.getPhone())) {
if (StringUtils.isNotBlank(model.getTel())) {
userService.register(model.getTel(), model.getId(), model.getRole());
} else {
userService.register(model.getName(), model.getId(), model.getRole());
}
} else {
userService.register(model.getPhone(), model.getId(), model.getRole());
}
}
}
return ResultJson.ok(data);
}
@ApiOperation(value = "修改权限")
@PostMapping(value = "updateRole")
public ResultJson updateRole(@RequestBody @Validated(Update.class) AddressBook model) {
Integer loginId = Integer.valueOf(String.valueOf(StpUtil.getLoginId()));
User user = userService.getRole(loginId);
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
case R001:
case R099: {
if (Integer.parseInt(model.getRole()) > Integer.parseInt(user.getRole())) {
return ResultJson.error("权限不足");
}
break;
}
default:
return ResultJson.error("权限不足!!");
}
AddressBook byId = service.getById(model.getId());
if (Objects.isNull(byId)) {
return ResultJson.error("当前数据不存在");
}
// List<Versions> list = versionsService.lambdaQuery()
// .eq(Versions::getAbId, model.getId())
// .list();
// Integer version = 0;
// if (CollectionUtils.isNotEmpty(list)){
// version = list
// .stream().map(Versions::getVersion)
// .max(Comparator.comparing(Integer::intValue))
// .get();
// }else{
// log.info("当前数据在进行修改但无相关记录;" + model.getId());
// }
// // 添加日志
// versionsService.save(new Versions(null, JSON.toJSONString(model),model.getId(),++version,model.getCreateId(),new Date(), VersionsType.UPDATE_ROLE.getName()));
byId.setOname(model.getOname());
byId.setRole(model.getRole());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
versionsService.saveInfo(byId, VersionsType.UPDATE_ROLE, byId.getAdcd());
// 只修改角色
boolean update = userService.lambdaUpdate()
.set(User::getRole, model.getRole())
.eq(User::getAbId, model.getId())
.update();
return ResultJson.ok(update);
}
@ApiOperation(value = "设置白名单")
@PostMapping(value = "setWhitelists")
public ResultJson setWhitelists(@RequestBody @Validated(Update.class) AddressBook model) {
Integer loginId = Integer.valueOf(String.valueOf(StpUtil.getLoginId()));
User user = userService.getRole(loginId);
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
case R001:
return ResultJson.error("权限不足");
case R099: {
break;
}
default:
return ResultJson.error("权限不足!!");
}
AddressBook byId = service.getById(model.getId());
if (Objects.isNull(byId)) {
return ResultJson.error("当前数据不存在");
}
byId.setIsPass(model.getIsPass());
versionsService.saveInfo(model, VersionsType.WHITE, byId.getAdcd());
boolean update = service.lambdaUpdate()
.set(AddressBook::getIsPass, model.getIsPass())
.eq(AddressBook::getId, model.getId())
.update();
if (!update) {
throw new MyException("操作数据库失败");
}
return ResultJson.ok(update);
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
@CacheEvict(value = ADDRESS_BOOK_REDIS_KEY, allEntries = true)
public ResultJson delete(@PathVariable("id") Integer id) {
Integer loginId = Integer.valueOf(String.valueOf(StpUtil.getLoginId()));
User user = userService.getRole(loginId);
AddressBook model = service.getById(id);
if (Objects.isNull(model)) {
return ResultJson.error("当前数据不存在");
}
User delUser = userService.lambdaQuery()
.eq(User::getAbId, model.getId())
.one();
switch (Objects.requireNonNull(Role.getByName(user.getRole()))) {
case R000:
case R001:
case R099:
if (Integer.parseInt(delUser.getRole()) > Integer.parseInt(user.getRole())) {
return ResultJson.error("权限不足");
}
break;
default:
return ResultJson.error("权限不足!!");
}
// List<Versions> list = versionsService.lambdaQuery()
// .eq(Versions::getAbId, model.getId())
// .list();
// Integer version = 0;
// if (CollectionUtils.isNotEmpty(list)){
// version = list
// .stream().map(Versions::getVersion)
// .max(Comparator.comparing(Integer::intValue))
// .get();
// }else{
// log.info("当前数据在进行修改但无相关记录;" + model.getId());
// }
// // 添加日志
// versionsService.save(new Versions(null, JSON.toJSONString(model),model.getId(),++version,model.getCreateId(),new Date(), VersionsType.DEL.getName()));
versionsService.saveInfo(model, VersionsType.DEL, model.getAdcd());
return ResultJson.ok(service.removeById(id));
}
@ApiOperation(value = "查询详情")
@GetMapping(value = "get/{id}")
public ResultJson get(@PathVariable("id") Integer id) {
AddressBook byId = service.getById(id);
if (byId != null) {
if (StringUtils.isNotBlank(byId.getOrganization())) {
Organization byId2 = organizationsService.getById(byId.getOrganization());
if (byId2 != null) {
byId.setOname(byId2.getName());
}
}
}
return ResultJson.ok(byId);
}
@ApiOperation(value = "查询用户详情")
@GetMapping(value = "getByUser/{userId}")
public ResultJson getByUser(@PathVariable("userId") Integer userId) {
User byId = userService.getById(userId);
if (Objects.isNull(byId)) {
return ResultJson.error("该用户不存在");
}
// return ResultJson.ok(JSON.parseObject(JSON.toJSONString(service.getById(byId.getAbId())).replaceAll("null","")));
AddressBook byId1 = service.getById(byId.getAbId());
if (byId1 != null) {
if (StringUtils.isNotBlank(byId1.getOrganization())) {
Organization byId2 = organizationsService.getById(byId1.getOrganization());
if (byId2 != null) {
byId1.setOname(byId2.getName());
}
}
byId1.setRole(byId.getRole());
}
return ResultJson.ok(byId1);
}
@ApiOperation(value = "查询行政区划联系人")
@GetMapping(value = "getAdcdUser")
public ResultJson<List<ExcelABVo>> getAdcdUser() {
List<AdcdTree> tree = adinfoService.tree(TREE_ALL, TREE_ALL);
if (CollectionUtils.isEmpty(tree)) {
throw new MyException("当前行政区划不存在");
}
// List<AddressBook> addressBooks = service.lambdaQuery().isNotNull(AddressBook::getAdcd)
// .list();
List<AddressBook> addressBooks = service.lambdaQuery().likeLeft(AddressBook::getAdcd, "000000000")
.list();
if (CollectionUtils.isEmpty(addressBooks)) {
throw new MyException("行政区划责任人为空");
}
Map<String, List<AddressBook>> abMap = addressBooks.stream().collect(Collectors.groupingBy(AddressBook::getAdcd, Collectors.toList()));
// 行政区划责任人数据
List<ExcelABVo> data = Lists.newArrayList();
for (int i = 0; i < tree.size(); i++) {
AdcdTree t = tree.get(i);
// String adcd = t.getAdcd();
String cityAdnm = t.getAdnm();
// List<AddressBook> books = abMap.get(adcd);
// if (CollectionUtils.isEmpty(books)) {
// continue;
// }
// books.forEach(b -> {
// if (StringUtils.isNotBlank(finalAdnm)) {
// if (cityAdnm.equals(finalAdnm)) {
// data.add(new ExcelABVo(cityAdnm, cityAdnm, b.getName(), b.getPosition(), b.getPhone()));
// }
// } else {
// data.add(new ExcelABVo(cityAdnm, cityAdnm, b.getName(), b.getPosition(), b.getPhone()));
// }
// });
List<AdcdTree> children = t.getChildren();
if (CollectionUtils.isNotEmpty(children)) {
for (int i1 = 1; i1 < children.size(); i1++) {
AdcdTree tc = children.get(i1);
String tcAdcd = tc.getAdcd();
String tcCityAdnm = tc.getAdnm();
List<AddressBook> tcBooks = abMap.get(tcAdcd);
if (CollectionUtils.isEmpty(tcBooks)) {
continue;
}
tcBooks.forEach(b -> {
data.add(new ExcelABVo(cityAdnm, tcCityAdnm, b.getName(), b.getPosition(), b.getPhone()));
});
}
}
}
if (CollectionUtils.isEmpty(data)) {
throw new MyException("当前行政区划责任人为空");
}
return ResultJson.ok(data);
}
// @ApiOperation(value = "通过行政区划下载excel")
// @GetMapping(value = "getExcel/{adnm}")
public void getExcel(@PathVariable("adnm")
@ApiParam(value = "名称,all: 查询全部")
String adnm, HttpServletResponse response) {
// 查询全部标识
if ("all".equals(adnm)) {
adnm = "";
}
List<AdcdTree> tree = adinfoService.tree(TREE_ALL, TREE_ALL);
if (CollectionUtils.isEmpty(tree)) {
throw new MyException("当前行政区划不存在");
}
// List<AddressBook> addressBooks = service.lambdaQuery().isNotNull(AddressBook::getAdcd)
// .list();
List<AddressBook> addressBooks = service.lambdaQuery().likeLeft(AddressBook::getAdcd, "000000000")
.list();
if (CollectionUtils.isEmpty(addressBooks)) {
throw new MyException("行政区划责任人为空");
}
Map<String, List<AddressBook>> abMap = addressBooks.stream().collect(Collectors.groupingBy(AddressBook::getAdcd, Collectors.toList()));
// 行政区划责任人数据
List<ExcelABVo> data = Lists.newArrayList();
String finalAdnm = adnm;
for (int i = 0; i < tree.size(); i++) {
AdcdTree t = tree.get(i);
// String adcd = t.getAdcd();
String cityAdnm = t.getAdnm();
// List<AddressBook> books = abMap.get(adcd);
// if (CollectionUtils.isEmpty(books)) {
// continue;
// }
// books.forEach(b -> {
// if (StringUtils.isNotBlank(finalAdnm)) {
// if (cityAdnm.equals(finalAdnm)) {
// data.add(new ExcelABVo(cityAdnm, cityAdnm, b.getName(), b.getPosition(), b.getPhone()));
// }
// } else {
// data.add(new ExcelABVo(cityAdnm, cityAdnm, b.getName(), b.getPosition(), b.getPhone()));
// }
// });
List<AdcdTree> children = t.getChildren();
if (CollectionUtils.isNotEmpty(children)) {
for (int i1 = 1; i1 < children.size(); i1++) {
AdcdTree tc = children.get(i1);
String tcAdcd = tc.getAdcd();
String tcCityAdnm = tc.getAdnm();
List<AddressBook> tcBooks = abMap.get(tcAdcd);
if (CollectionUtils.isEmpty(tcBooks)) {
continue;
}
tcBooks.forEach(b -> {
if (StringUtils.isNotBlank(finalAdnm)) {
if (cityAdnm.equals(finalAdnm) || tcCityAdnm.equals(finalAdnm)) {
data.add(new ExcelABVo(cityAdnm, tcCityAdnm, b.getName(), b.getPosition(), b.getPhone()));
}
} else {
data.add(new ExcelABVo(cityAdnm, tcCityAdnm, b.getName(), b.getPosition(), b.getPhone()));
}
});
}
}
}
if (CollectionUtils.isEmpty(data)) {
throw new MyException("当前行政区划责任人为空");
}
ExcelCommon.exportExcel(data,
null, "防汛抗旱通讯录", ExcelABVo.class, "防汛抗旱通讯录_" + LocalDateTime.now() + ".xlsx",
response);
}
// @ApiOperation(value = "解析文件数据")
// @PostMapping(value = "getExcelData")
public ResultJson<ExcelDataVo> getExcelData(MultipartFile file) {
List<ExcelABVo> appends = ExcelCommon.importExcel(file, 0, 1, ExcelABVo.class);
ExcelDataVo excelDataVo = new ExcelDataVo();
excelDataVo.setList(appends);
if (CollectionUtils.isNotEmpty(appends)){
String key = UUID.randomUUID().toString().replaceAll("-", "");
redisTemplate.opsForValue().set(ADDRESS_BOOK_TEMP_REDIS_KEY + key, JSON.toJSONString(appends), 30, TimeUnit.MINUTES);
excelDataVo.setKey(key);
}
return ResultJson.ok(excelDataVo);
}
// @ApiOperation(value = "行政区划联系人导入")
// @PostMapping(value = "uploadExcel")
public ResultJson uploadExcel(@RequestBody ExcelDataVo data) {
// List<ExcelABVo> appends = ExcelCommon.importExcel(file, 0, 1, ExcelABVo.class);
String s = redisTemplate.opsForValue().get(ADDRESS_BOOK_TEMP_REDIS_KEY + data.getKey());
if (StringUtils.isBlank(s)){
throw new MyException("文件已过期");
}
List<ExcelABVo> appends = JSON.parseArray(s, ExcelABVo.class);
if (CollectionUtils.isEmpty(appends)) {
throw new MyException("文件为空");
}
Set<String> set = appends.stream().map(vo -> vo.getName() + "_" + vo.getPhone()).collect(Collectors.toSet());
if (set.size() != appends.size()){
throw new MyException("联系人重复");
}
List<AdcdTree> tree = adinfoService.tree(TREE_ALL, TREE_ALL);
List<AddressBook> abs = Lists.newArrayList();
appends.forEach(vo -> {
String phone = vo.getPhone();
String name = vo.getName();
String position = vo.getPosition();
String city = vo.getCity();
String county = vo.getCounty();
AddressBook e = new AddressBook();
e.setName(name)
.setPhone(phone)
.setAdcd(getAdcd(tree, city, county))
.setPosition(position);
abs.add(e);
});
// 原数据删除
removeAdcd();
if (!service.saveBatch(abs)) {
throw new MyException("表格数据新增失败");
}
List<User> users = Lists.newArrayList();
List<AbUdR> abUdRs = Lists.newArrayList();
AtomicReference<Integer> sort = new AtomicReference<>(0);
// 新增关联数据
abs.forEach(a -> {
String phone = a.getPhone();
if (StringUtils.isNotBlank(phone)){
User user = new User();
String salt = UUID.randomUUID().toString().replaceAll("-", "");
user
.setUsername(phone)
.setAbId(a.getId())
.setRole("1")
.setSalt(salt)
.setPassword(DigestUtils.md5DigestAsHex((salt + "Fxkh@123456").getBytes()));
users.add(user);
}
AbUdR au = new AbUdR();
Integer i = sort.get() + 1;
au.setType("1")
.setAdId(a.getId())
.setDictId(a.getAdcd().replaceFirst("000000", ""))
.setSort(i);
abUdRs.add(au);
sort.set(i);
});
if (!userService.saveBatch(users)) {
throw new MyException("用户数据新增失败");
}
if (!abUdRService.saveBatch(abUdRs)) {
throw new MyException("关联数据新增失败");
}
return ResultJson.ok("数据新增成功");
}
private String getAdcd(List<AdcdTree> tree, String city, String county) {
for (AdcdTree a : tree) {
if (a.getAdnm().equals(city)) {
List<AdcdTree> children = a.getChildren();
if (a.getAdnm().equals(county)) {
county = "市本级";
}
for (AdcdTree b : children) {
if (b.getAdnm().equals(county)) {
return b.getAdcd();
}
}
}
}
throw new MyException("当前市行政区划匹配失败");
}
private void removeAdcd() {
List<AddressBook> addressBooks = service.lambdaQuery().likeLeft(AddressBook::getAdcd, "000000000")
.list();
boolean r1 = service.removeBatchByIds(addressBooks);
if (!r1) {
throw new MyException("通讯录数据删除失败");
}
List<Integer> abIds = addressBooks.stream().map(AddressBook::getId).collect(Collectors.toList());
LambdaQueryWrapper<AbUdR> aurQueryWrapper = new LambdaQueryWrapper<>();
aurQueryWrapper.in(AbUdR::getAdId, abIds);
boolean remove1 = abUdRService.remove(aurQueryWrapper);
if (!remove1) {
throw new MyException("关联数据删除失败");
}
LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
userQueryWrapper.in(User::getAbId, abIds);
boolean remove2 = userService.remove(userQueryWrapper);
if (!remove2) {
throw new MyException("用户账号删除失败");
}
}
}

View File

@ -0,0 +1,163 @@
package com.whdc.legacy.controller;
import com.whdc.legacy.model.entity.Adinfo;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.AdcdTree;
import com.whdc.legacy.service.IAdinfoService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.whdc.legacy.service.impl.AdinfoServiceImpl.TREE_ALL;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "行政区划基础信息 - Controller")
@RestController
@RequestMapping("/adinfo")
public class AdinfoController {
@Autowired
private IAdinfoService service;
@ApiOperation(value = "查询所有")
@PostMapping(value = "find")
public ResultJson<Adinfo> find(@RequestBody Adinfo dto) {
return ResultJson.ok(service.find(dto));
}
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<Adinfo> page(@RequestBody Adinfo dto) {
return ResultJson.ok(service.page(dto));
}
@GetMapping("/tree/{adcdOradnm}")
@ApiOperation(value = "树型查询")
public ResultJson<List<AdcdTree>> tree(@PathVariable("adcdOradnm")
@ApiParam(value = "编码或名称,all: 查询全部")
String adcdOradnm) {
List<AdcdTree> list = service.tree(TREE_ALL, TREE_ALL);
// 查询全部标识
if ("all".equals(adcdOradnm)) {
return ResultJson.ok(list);
}else{
return ResultJson.ok(list.stream().filter(item -> item.getAdnm().equals(adcdOradnm)).collect(Collectors.toList()));
}
}
@GetMapping("/getCountys/{adnm}")
@ApiOperation(value = "通过市名获取县")
public ResultJson<List<Adinfo>> getCountys(@PathVariable("adnm")
@ApiParam(value = "名称")
String adnm) {
Adinfo one = service.lambdaQuery()
.like(Adinfo::getAdnm, adnm)
.one();
if (Objects.isNull(one)){
return ResultJson.error("当前行政区划不存在");
}
String adcd = one.getAdcd();
// 确保查的是县
List<Adinfo> list = service.lambdaQuery()
.likeRight(Adinfo::getAdcd, adcd.substring(0,4))
.ne(Adinfo::getAdcd,adcd.substring(0,4) + "00000000000")
.list();
if (CollectionUtils.isNotEmpty(list)){
return ResultJson.ok(list.stream().map(ad -> {
if ("市辖区".equals(ad.getAdnm())){
Adinfo adinfo = service.lambdaQuery().eq(Adinfo::getAdcd, ad.getAdcd().substring(0, 4) + "00000000000")
.one();
if (Objects.nonNull(adinfo)){
ad.setAdnm(adinfo.getAdnm());
}
}
return ad;
}).sorted(Comparator.comparing(Adinfo::getAdcd)).collect(Collectors.toList()));
}
return ResultJson.ok(list);
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) Adinfo model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Adinfo::getAdcd,String.valueOf(model.getAdcd()).trim())
.or()
.eq(Adinfo::getAdnm,String.valueOf(model.getAdnm()).trim())
.list())
){
return ResultJson.error("该名称或编码重复");
}
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) Adinfo model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Adinfo::getAdcd,String.valueOf(model.getAdcd()).trim())
.or()
.eq(Adinfo::getAdnm,String.valueOf(model.getAdnm()).trim())
.list())
){
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,110 @@
package com.whdc.legacy.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.whdc.legacy.model.dto.FcDto;
import com.whdc.legacy.model.entity.Fc;
import com.whdc.legacy.model.group.Find;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.FcVo;
import com.whdc.legacy.service.IFcService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "置顶和常用联系人 - Controller")
@RestController
@RequestMapping("/fc")
public class FcController {
@Autowired
private IFcService service;
// @ApiOperation(value = "查询所有")
// @PostMapping(value = "find")
public ResultJson<Fc> find(@RequestBody Fc dto) {
return ResultJson.ok(service.find(dto));
}
// @ApiOperation(value = "分页查询")
// @PostMapping(value = "page")
public ResultJson<FcVo> page(@RequestBody @Validated(Find.class) FcDto dto) {
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) Fc model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Fc::getUserId,String.valueOf(StpUtil.getLoginId()).trim())
.eq(Fc::getAbId,String.valueOf(model.getAbId()).trim())
.eq(Fc::getType,model.getType().trim())
.list())
){
return ResultJson.error("该数据已存在");
}
model.setUserId(Integer.valueOf(String.valueOf(StpUtil.getLoginId())));
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) Fc model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Fc::getUserId,String.valueOf(StpUtil.getLoginId()).trim())
.eq(Fc::getAbId,String.valueOf(model.getAbId()).trim())
.eq(Fc::getType,String.valueOf(model.getType()).trim())
.ne(Fc::getId, model.getId())
.list())
){
return ResultJson.error("该排序已添加");
}
model.setUserId(Integer.valueOf(String.valueOf(StpUtil.getLoginId())));
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,87 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.FindPageDto;
import com.whdc.legacy.model.dto.LoginInfoDto;
import com.whdc.legacy.model.entity.LoginInfo;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.ILoginInfoService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "登录日志 - Controller")
@RestController
@RequestMapping("/logininfo")
public class LoginInfoController {
@Autowired
private ILoginInfoService service;
@ApiOperation(value = "查询所有")
@PostMapping(value = "find")
public ResultJson<LoginInfo> find(@RequestBody LoginInfo dto) {
return ResultJson.ok(service.find(dto));
}
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<LoginInfo> page(@RequestBody LoginInfoDto dto) {
IPage<LoginInfo> page = service.page(dto);
return ResultJson.ok(page);
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) LoginInfo model) {
model.setCreateTime(new Date());
return ResultJson.ok(service.save(model));
}
// @ApiOperation(value = "修改")
// @PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) LoginInfo model) {
return ResultJson.ok(service.updateById(model));
}
// @ApiOperation(value = "删除")
// @GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,167 @@
package com.whdc.legacy.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.whdc.legacy.model.entity.Organization;
import com.whdc.legacy.model.entity.UnitDict;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.AdcdTree;
import com.whdc.legacy.model.vo.FcCommVo;
import com.whdc.legacy.service.IOrganizationService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "组织表 - Controller")
@RestController
@RequestMapping("/organization")
public class OrganizationController {
@Autowired
private IOrganizationService service;
@ApiOperation(value = "查询所有")
@PostMapping(value = "find")
public ResultJson<FcCommVo> find(HttpServletRequest request) {
List<Organization> organizations = service.findByUserId(String.valueOf(StpUtil.getLoginId()),request.getHeader("adcd"));
return ResultJson.ok(findFcCommVo(organizations));
}
private List<FcCommVo> findFcCommVo(List<Organization> organizations){
ArrayList<FcCommVo> list = new ArrayList<>();
if (CollectionUtils.isEmpty(organizations)){
return list;
}
for (Organization o : organizations) {
FcCommVo fcCommVo = new FcCommVo();
List<AdcdTree> adinfoList = o.getAdinfoList();
fcCommVo.setAdinfo(findAdcdTree(adinfoList));
List<UnitDict> unitDicts = o.getUnitDicts();
fcCommVo.setUds(findUds(unitDicts));
fcCommVo.setId(String.valueOf(o.getId()))
.setName(o.getName())
.setSort(o.getSort())
.setFsort(o.getFsort())
.setFcid(o.getFcid())
.setType("0");
list.add(fcCommVo);
}
return list;
}
private List<FcCommVo> findAdcdTree(List<AdcdTree> adinfoList){
ArrayList<FcCommVo> list = new ArrayList<>();
if (CollectionUtils.isEmpty(adinfoList)){
return list;
}
for (AdcdTree o : adinfoList) {
FcCommVo fcCommVo = new FcCommVo();
fcCommVo.setId(o.getAdcd())
.setName(o.getAdnm())
.setAdlevel(o.getAdlevel())
.setType("4");
fcCommVo.setAdinfo(findAdcdTree(o.getChildren()));
list.add(fcCommVo);
}
return list;
}
private List<FcCommVo> findUds(List<UnitDict> unitDicts){
ArrayList<FcCommVo> list = new ArrayList<>();
if (CollectionUtils.isEmpty(unitDicts)){
return list;
}
for (UnitDict o : unitDicts) {
FcCommVo fcCommVo = new FcCommVo();
fcCommVo.setId(String.valueOf(o.getId()))
.setName(o.getName())
.setSort(o.getSort())
.setFsort(o.getFsort())
.setFcid(o.getFcid())
.setType("1");
list.add(fcCommVo);
}
return list;
}
// @ApiOperation(value = "分页查询")
// @PostMapping(value = "page")
public ResultJson<Organization> page(@RequestBody Organization dto) {
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) Organization model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Organization::getName,String.valueOf(model.getName()).trim())
.list())
){
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) Organization model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(Organization::getName,String.valueOf(model.getName()).trim())
.ne(Organization::getId, model.getId())
.list())
){
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,326 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.ShAddressBookDto;
import com.whdc.legacy.model.entity.ShAddressBook;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.AdcdTree;
import com.whdc.legacy.model.vo.ShAddressBookVo;
import com.whdc.legacy.service.ShAddressBookService;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.whdc.legacy.model.MyConstant.DEL;
import static com.whdc.legacy.model.MyConstant.REC;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Api(tags = "山洪责任人通讯录")
@RestController
@RequestMapping(value = "/shAddressBook")
public class ShAddressBookController {
@Autowired
private ShAddressBookService service;
@ApiOperation(value = "修改")
@PostMapping("/update")
public ResultJson<ShAddressBook> update(@Validated(Update.class) @RequestBody ShAddressBook dto) {
ShAddressBook dbData = service.getById(dto.getId());
if (Objects.isNull(dbData)){
throw new MyException("当前数据不存在");
}
boolean result;
// 判断是新增还是修改 名字相同是修改
if (StringUtils.isNotBlank(dto.getName()) && StringUtils.isNotBlank(dbData.getName()) && !dto.getName().equals(dbData.getName())){
dbData
.setName(dto.getName())
.setPhone(dto.getPhone())
.setPosition(dto.getPosition());
result = service.updateById(dbData);
}else{
// 删除原数据
boolean update = service.lambdaUpdate().set(ShAddressBook::getDel, DEL)
.eq(ShAddressBook::getId, dto.getId())
.update();
if (!update){
throw new MyException("修改原数据失败");
}
// 新增
dbData.setId(null)
.setName(dto.getName())
.setPhone(dto.getPhone())
.setPosition(dto.getPosition());
result = service.save(dbData);
}
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "抽查")
@PostMapping("/setSpotCheck/{spotCheck}")
public ResultJson setSpotCheck(@RequestBody List<Integer> ids,
@PathVariable
@ApiParam("是否抽查0不抽查1抽查")
@Pattern(message = "仅支持 0 或者 1", regexp = "[01]")
Integer spotCheck
) {
if (CollectionUtils.isEmpty(ids)){
throw new MyException("当前选中数据为空");
}
if (service.lambdaQuery().in(ShAddressBook::getId, ids).count() != ids.size()){
throw new MyException("当前选中数据有误");
}
boolean update = service.lambdaUpdate()
.set(ShAddressBook::getIsSpotCheck, spotCheck)
.in(ShAddressBook::getId, ids)
.update();
return ResultJson.ok(update);
}
@ApiOperation(value = "分页 (行政责任人分页查询 type1:行政责任人,包保责任人分页查询 type1:包保责任人,今日抽查分页查询 isSpotCheck:1 )")
@PostMapping("/page")
public ResultJson<IPage<ShAddressBook>> page(@RequestBody ShAddressBookDto dto) {
//
// LambdaQueryChainWrapper<ShAddressBook> query = service.lambdaQuery();
//
// String type1 = dto.getType1();
// if (StringUtils.isNotBlank(type1)) {
// query.eq(ShAddressBook::getType1, type1);
// }
//
// String type2 = dto.getType2();
//
// if (StringUtils.isNotBlank(type2)) {
// query.eq(ShAddressBook::getType2, type2);
// }
//
// String isSpotCheck = dto.getIsSpotCheck();
//
// if (StringUtils.isNotBlank(isSpotCheck)) {
// query.eq(ShAddressBook::getIsSpotCheck, isSpotCheck);
// }
//
// String city = dto.getCity();
//
// if (StringUtils.isNotBlank(city)) {
// query.eq(ShAddressBook::getCity, city);
// }
//
// String county = dto.getCounty();
//
// if (StringUtils.isNotBlank(county)) {
// query.eq(ShAddressBook::getCounty, county);
// }
//
// String area = dto.getArea();
//
// if (StringUtils.isNotBlank(area)) {
// query.eq(ShAddressBook::getArea, area);
// }
//
// String village = dto.getVillage();
//
// if (StringUtils.isNotBlank(village)) {
// query.eq(ShAddressBook::getVillage, village);
// }
//
// String name = dto.getName();
//
// if (StringUtils.isNotBlank(name)) {
// query.like(ShAddressBook::getName, name);
// }
//
// String land = dto.getLand();
//
// if (StringUtils.isNotBlank(land)) {
// query.like(ShAddressBook::getLand, land);
// }
//
// String phone = dto.getPhone();
//
// if (StringUtils.isNotBlank(phone)) {
// query.like(ShAddressBook::getPhone, phone);
// }
//
// query.orderByAsc(ShAddressBook::getSort);
//
// return ResultJson.ok(service.page(dto.getPage(), query));
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "导出 (行政责任人分页查询 type1:行政责任人,包保责任人分页查询 type1:包保责任人,今日抽查分页查询 isSpotCheck:1 )")
@PostMapping("/export")
public void export(@RequestBody ShAddressBookDto dto,HttpServletResponse response) {
LambdaQueryWrapper<ShAddressBook> query = new LambdaQueryWrapper<>();
String type1 = dto.getType1();
if (StringUtils.isNotBlank(type1)) {
query.eq(ShAddressBook::getType1, type1);
}
String type2 = dto.getType2();
if (StringUtils.isNotBlank(type2)) {
query.eq(ShAddressBook::getType2, type2);
}
String isSpotCheck = dto.getIsSpotCheck();
if (StringUtils.isNotBlank(isSpotCheck)) {
query.eq(ShAddressBook::getIsSpotCheck, isSpotCheck);
}
String city = dto.getCity();
if (StringUtils.isNotBlank(city)) {
query.eq(ShAddressBook::getCity, city);
}
String county = dto.getCounty();
if (StringUtils.isNotBlank(county)) {
query.eq(ShAddressBook::getCounty, county);
}
String area = dto.getArea();
if (StringUtils.isNotBlank(area)) {
query.eq(ShAddressBook::getArea, area);
}
String village = dto.getVillage();
if (StringUtils.isNotBlank(village)) {
query.eq(ShAddressBook::getVillage, village);
}
String name = dto.getName();
if (StringUtils.isNotBlank(name)) {
query.like(ShAddressBook::getName, name);
}
String land = dto.getLand();
if (StringUtils.isNotBlank(land)) {
query.like(ShAddressBook::getLand, land);
}
String phone = dto.getPhone();
if (StringUtils.isNotBlank(phone)) {
query.like(ShAddressBook::getPhone, phone);
}
String callStatus = dto.getCallStatus();
if (StringUtils.isNotBlank(phone)) {
if ("1".equals(callStatus)){
query.eq(ShAddressBook::getCallStatus, callStatus);
}else{
query.ne(ShAddressBook::getCallStatus, 1);
}
}
query
.eq(ShAddressBook::getDel, REC)
.orderByAsc(ShAddressBook::getSort);
List<ShAddressBook> list = service.list(query);
AtomicInteger integer = new AtomicInteger(1);
list = list.stream().map(o->o.setSort(integer.getAndIncrement()))
.collect(Collectors.toList());
ExcelCommon.exportExcel(list,
null, "山洪责任人通讯录", ShAddressBook.class, "山洪责任人通讯录.xlsx",
response);
}
@ApiOperation(value = "下载模板")
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletResponse response) {
ExcelCommon.exportExcel(Lists.newArrayList(),
null, "山洪责任人通讯录", ShAddressBook.class, "山洪责任人通讯录模板.xlsx",
response);
}
@ApiOperation(value = "上传")
@PostMapping("/upload/{type1}")
public ResultJson upload(
@PathVariable("type1")
@ApiParam(name = "type1", value = "责任人类型, 0:行政责任人,1:包保责任人")
@Pattern(message = "仅支持 0 或者 1", regexp = "[01]")
String type1,
MultipartFile file) {
List<ShAddressBook> appends = ExcelCommon.importExcel(file, 0, 1, ShAddressBook.class);
service.updateAll(type1, appends);
return ResultJson.ok();
}
@GetMapping("/tree")
@ApiOperation(value = "树型查询")
public ResultJson<List<AdcdTree>> tree() {
List<AdcdTree> list = service.tree();
return ResultJson.ok(list);
}
@ApiOperation(value = "抽查责任人批量匹配")
@PostMapping("/importBatchMatch")
public ResultJson importBatchMatch(MultipartFile file) {
List<ShAddressBookVo> shAddressBooks = ExcelCommon.importExcel(file, 0, 1, ShAddressBookVo.class);
if (CollectionUtils.isEmpty(shAddressBooks)) {
throw new MyException("文件解析数据为空");
}
Map<String, Object> map = service.importBatchMatch(shAddressBooks);
return ResultJson.ok(map);
}
@ApiOperation(value = "下载批量匹配模板")
@GetMapping("/downloadMatchTemplate")
public void downloadMatchTemplate(HttpServletResponse response) {
ExcelCommon.exportExcel(Lists.newArrayList(), null, "责任人", ShAddressBookVo.class, "责任人批量匹配模板.xlsx", response);
}
}

View File

@ -0,0 +1,97 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.ShCallWordDto;
import com.whdc.legacy.model.entity.ShCallWord;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.ShCallWordService;
import com.whdc.legacy.service.ShPeriodService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Api(tags = "备注")
@RestController
@RequestMapping(value="/shCallWord")
public class ShCallWordController {
@Autowired
private ShCallWordService service;
@Autowired
private ShPeriodService shPeriodService;
@ApiOperation(value = "新增")
@PostMapping("/insert")
public ResultJson<ShCallWord> insert(@Validated(Insert.class) @RequestBody ShCallWord dto) {
if (Objects.nonNull(dto.getShPeriodId()) && Objects.isNull(shPeriodService.getById(dto.getShPeriodId()))){
throw new MyException("当前防汛周期不存在");
}
dto.setId(null);
dto.setCreateTime(new Date());
boolean result = service.save(dto);
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "修改")
@PostMapping("/update")
public ResultJson<ShCallWord> update(@Validated(Update.class) @RequestBody ShCallWord dto) {
if (Objects.isNull(service.getById(dto.getId()))){
throw new MyException("当前数据不存在");
}
if (Objects.nonNull(dto.getShPeriodId()) && Objects.isNull(shPeriodService.getById(dto.getShPeriodId()))){
throw new MyException("当前防汛周期不存在");
}
dto.setCreateTime(null);
boolean result = service.updateById(dto);
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "删除")
@GetMapping("/del/{id}")
public ResultJson<Boolean> del(@Schema(name = "id") @PathVariable("id") Serializable id) {
return ResultJson.ok(service.removeById(id));
}
@ApiOperation(value = "列表")
@PostMapping("/list")
public ResultJson<List<ShCallWord>> list(@RequestBody ShCallWordDto dto) {
return ResultJson.ok(service.list(dto));
}
@ApiOperation(value = "分页")
@PostMapping("/page")
public ResultJson<IPage<ShCallWord>> page(@RequestBody ShCallWordDto dto) {
// LambdaQueryChainWrapper<ShCallWord> query = service.lambdaQuery();
// if (Objects.nonNull(dto.getStm()) && Objects.nonNull(dto.getEtm())){
// query.between(ShCallWord::getCreateTime,dto.getStm(),dto.getEtm());
// }
//
// if (StringUtils.isNotBlank(dto.getShAbType1())){
// query.eq(ShCallWord::getShAbType1,dto.getShAbType1());
// }
//
// query.orderByDesc(ShCallWord::getCreateTime);
//
// return ResultJson.ok(service.page(dto.getPage(),query));
return ResultJson.ok(service.page(dto));
}
}

View File

@ -0,0 +1,223 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.ShCallsDto;
import com.whdc.legacy.model.entity.ShAddressBook;
import com.whdc.legacy.model.entity.ShCallWord;
import com.whdc.legacy.model.entity.ShCalls;
import com.whdc.legacy.model.enums.CallType;
import com.whdc.legacy.model.enums.CallingType;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.vo.ShCallsExcelVo;
import com.whdc.legacy.model.vo.ShCallsVo;
import com.whdc.legacy.service.ShAddressBookService;
import com.whdc.legacy.service.ShCallsService;
import com.whdc.common.utils.DateUtils;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Api(tags = "抽查日志")
@RestController
@RequestMapping(value="/shCalls")
public class ShCallsController {
@Autowired
private ShCallsService service;
@Autowired
private ShAddressBookService shAddressBookService;
@ApiOperation(value = "新增")
@PostMapping("/insert")
public ResultJson<ShCallWord> insert(@Validated(Insert.class) @RequestBody ShCalls dto) {
if (shAddressBookService.lambdaQuery().eq(ShAddressBook::getId, dto.getShAbId()).count() != 1){
throw new MyException("当前通讯录不存在");
}
if (StringUtils.isNotBlank(dto.getCallType()) && "0".equals(dto.getCallType())){
boolean update = shAddressBookService.lambdaUpdate()
.set(ShAddressBook::getCallStatus, 1)
.eq(ShAddressBook::getId, dto.getShAbId())
.update();
if (!update){
throw new MyException("更新通讯录状态失败");
}
dto.setStatus("1");
}else{
dto.setStatus("0");
}
dto.setId(null);
boolean result = service.save(dto);
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "列表")
@PostMapping("/list")
public ResultJson<List<ShCalls>> list(@RequestBody ShCallsDto dto) {
LambdaQueryChainWrapper<ShCalls> query = service.lambdaQuery();
if (Objects.nonNull(dto.getDate())){
query.between(ShCalls::getCallTime, dto.getDate() + " 00:00:00",dto.getDate() + " 23:59:59");
}else{
if (StringUtils.isNotBlank(dto.getCallTime())){
String dateStr = dto.getCallTime().split(" ")[0];
query.between(ShCalls::getCallTime, dateStr + " 00:00:00",dateStr + " 23:59:59");
}
}
if (Objects.nonNull(dto.getShAbId())){
query.eq(ShCalls::getShAbId, dto.getShAbId());
}else{
throw new MyException("山洪通讯录编号不能为空");
}
query.orderByDesc(ShCalls::getCallTime);
return ResultJson.ok(query.list());
}
@ApiOperation(value = "抽查日志分页")
@PostMapping("/page")
public ResultJson<IPage<ShCallsVo>> page(@RequestBody ShCallsDto dto) {
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "综述")
@PostMapping("/statistics")
public ResultJson<String> statistics(@RequestBody @Validated ShCallsDto dto) {
List<ShCallsVo> list = service.listVo(dto);
String dateStr = LocalDate.parse(dto.getDate(),DateTimeFormatter.ofPattern(DateUtils.DATE_PATTERN1))
.format(DateTimeFormatter.ofPattern(DateUtils.DATE_PATTERN));
List<String> citys = list.stream().map(ShCallsVo::getCity).distinct().filter(StringUtils::isNotBlank).collect(Collectors.toList());
List<String> countys = list.stream().map(ShCallsVo::getCounty).distinct().filter(StringUtils::isNotBlank).collect(Collectors.toList());
// return ResultJson.ok(String.format("%%抽查了%%个市(%%%%个县(%%)县乡村山洪灾害防御责任人和包保责任人共计%%人。",
return ResultJson.ok(String.format("%s抽查了%d个市%s%d个县%s县乡村山洪灾害防御责任人和包保责任人共计%d人。",
dateStr,
citys.size(),
StringUtils.join(citys, ","),
countys.size(),
StringUtils.join(countys, ","),
list.stream().map(ShCallsVo::getPhone).distinct().filter(StringUtils::isNotBlank).count()
));
}
@ApiOperation(value = "抽查日志导出")
@PostMapping("/export")
public void export(@RequestBody ShCallsDto dto, HttpServletResponse response) {
List<ShAddressBook> list = service.list(dto);
List<ShCallsExcelVo> excels = Lists.newArrayList();
AtomicInteger i = new AtomicInteger(1);
list.forEach(item -> {
List<ShCalls> calls = item.getList();
if (CollectionUtils.isNotEmpty(calls)){
Map<String, List<ShCalls>> dateCalls = calls.stream()
// .filter(o-> Objects.nonNull(o.getCallTime()))
.collect(Collectors.groupingBy(o -> DateUtils.dateToStr(o.getCallTime(), DateUtils.sdfymd), Collectors.toList()));
dateCalls.forEach((k,v) ->{
ShCallsExcelVo excel = new ShCallsExcelVo();
excel.setDateStr(k);
excel.setType2(item.getType2());
excel.setName(item.getName());
excel.setPhone(item.getPhone());
excel.setPosition(item.getPosition());
excel.setCity(item.getCity());
excel.setCounty(item.getCounty());
excel.setLand(item.getLand());
excel.setCallStatus(item.getCallStatus());
long count = v.stream().map(ShCalls::getKnow).filter("是"::equals)
.count();
if (count > 0){
excel.setKnow("是");
}else{
excel.setKnow("否");
}
long count1 = v.stream().filter(o -> Objects.nonNull(o.getStatus()) && "1".equals(o.getStatus())).count();
if (count1 > 0){
excel.setCallStatus("是");
}else {
excel.setCallStatus("否");
}
excel.setTimeStr(StringUtils.join(v.stream().map(o ->{
String type = o.getType();
if (StringUtils.isNotBlank(type)){
CallType callType = CallType.getByName(type);
if (Objects.nonNull(callType)){
type = callType.getValue();
}
}else{
type = "未填写";
}
String callType = o.getCallType();
if (StringUtils.isNotBlank(callType)){
CallingType callingType = CallingType.getByName(callType);
if (Objects.nonNull(callingType)){
callType = callingType.getValue();
}
}else{
callType = "未填写";
}
return DateUtils.dateToStr(o.getCallTime(),ThreadLocal.withInitial(() -> new SimpleDateFormat(DateUtils.DATE_PATTERN_HM))) + " " + type + " " + callType;
}).distinct().collect(Collectors.toList()), ","));
excel.setRemark(StringUtils.join(v.stream().map(ShCalls::getRemark).distinct().collect(Collectors.toList()), "/n"));
excels.add(excel);
});
}
});
List<ShCallsExcelVo> data = excels.stream().sorted(Comparator.comparing(ShCallsExcelVo::getDateStr).reversed()).collect(Collectors.toList());
data.forEach(o->o.setId(i.getAndIncrement()));
ExcelCommon.exportExcel(data,
null, "抽查日志", ShCallsExcelVo.class, "抽查日志.xlsx",
response);
}
@ApiOperation(value = "日志日期统计")
@PostMapping("/logDateStatistics")
public ResultJson<Map<String, Long>> logDateStatistics(@RequestBody @Validated ShCallsDto dto) {
if (StringUtils.isBlank(dto.getStiStartTime()) || StringUtils.isBlank(dto.getStiEndTime())) {
throw new MyException("开始时间和结束时间参数必填!");
}
Map<String, Long> retMap = service.logDateStatistics(dto);
return ResultJson.ok(retMap);
}
}

View File

@ -0,0 +1,92 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.ShPeriodDto;
import com.whdc.legacy.model.entity.ShPeriod;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.ShPeriodService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Api(tags = "防汛周期")
@RestController
@RequestMapping(value="/shPeriod")
public class ShPeriodController {
@Autowired
private ShPeriodService service;
@ApiOperation(value = "新增")
@PostMapping("/insert")
public ResultJson<ShPeriod> insert(@Validated(Insert.class) @RequestBody ShPeriod dto) {
if (service.lambdaQuery().eq(ShPeriod::getName, dto.getName()).count() > 0){
throw new MyException("名称重复");
}
dto.setId(null);
boolean result = service.save(dto);
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "修改")
@PostMapping("/update")
public ResultJson<ShPeriod> update(@Validated(Update.class) @RequestBody ShPeriod dto) {
if (service.lambdaQuery()
.eq(ShPeriod::getName, dto.getName())
.ne(ShPeriod::getId, dto.getId())
.count() > 0){
throw new MyException("名称重复");
}
dto.setCreateTime(null);
boolean result = service.updateById(dto);
return ResultJson.ok(result ? dto : null);
}
@ApiOperation(value = "删除")
@GetMapping("/del/{id}")
public ResultJson<Boolean> del(@Schema(name = "id") @PathVariable("id") Serializable id) {
return ResultJson.ok(service.removeById(id));
}
// @ApiOperation(value = "列表")
// @PostMapping("/list")
public ResultJson<List<ShPeriod>> list() {
return ResultJson.ok(service.lambdaQuery().list());
}
@ApiOperation(value = "分页")
@PostMapping("/page")
public ResultJson<IPage<ShPeriod>> page(@RequestBody ShPeriodDto dto) {
// LambdaQueryChainWrapper<ShPeriod> query = service.lambdaQuery();
// if (Objects.nonNull(dto.getStm()) && Objects.nonNull(dto.getEtm())){
// query.between(ShPeriod::getCreateTime,dto.getStm(),dto.getEtm());
// }
//
// if (StringUtils.isNotBlank(dto.getName())){
// query.eq(ShPeriod::getName,dto.getName());
// }
//
// query.orderByDesc(ShPeriod::getCreateTime);
//
// return ResultJson.ok(service.page(dto.getPage(),query));
return ResultJson.ok(service.page(dto));
}
}

View File

@ -0,0 +1,27 @@
package com.whdc.legacy.controller;
import com.whdc.common.utils.ResultJson;
import com.whdc.sms.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
/**
* @author lyf
* @since 2025-10-29
*/
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private ISmsService smsService;
@GetMapping("/sms")
public ResultJson<String> testSms() {
String result = smsService.send(Collections.singletonList("15671545233"), "测试短信");
return ResultJson.ok(result);
}
}

View File

@ -0,0 +1,130 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.whdc.legacy.model.entity.Organization;
import com.whdc.legacy.model.entity.UnitDict;
import com.whdc.legacy.model.group.Find;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.service.IOrganizationService;
import com.whdc.legacy.service.IUnitDictService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "单位字典表 - Controller")
@RestController
@RequestMapping("/unitdict")
public class UnitDictController {
@Autowired
private IUnitDictService service;
@Autowired
private IOrganizationService organizationService;
@ApiOperation(value = "查询所有")
@PostMapping(value = "find")
public ResultJson<UnitDict> find(@RequestBody @Validated(Find.class) UnitDict dto) {
if (Objects.isNull(organizationService.getById( dto.getOId()))) {
return ResultJson.error("组织类型Id不存在");
}
LambdaQueryChainWrapper<UnitDict> query = service.lambdaQuery();
String name = dto.getName();
if (StringUtils.isNotBlank(name)) {
query.like(UnitDict::getName, name);
}
query.eq(UnitDict::getOId, dto.getOId());
query.orderByAsc(UnitDict::getSort);
return ResultJson.ok(query.list());
}
// @ApiOperation(value = "分页查询")
// @PostMapping(value = "page")
public ResultJson<UnitDict> page(@RequestBody UnitDict dto) {
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) UnitDict model) {
if (Objects.isNull(organizationService.getById( model.getOId()))) {
return ResultJson.error("组织类型Id不存在");
}
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(UnitDict::getName, String.valueOf(model.getName()).trim())
.eq(UnitDict::getOId, String.valueOf(model.getOId()).trim())
.list())
) {
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) UnitDict model) {
if (Objects.isNull(organizationService.getById( model.getOId()))) {
return ResultJson.error("组织类型Id不存在");
}
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(UnitDict::getName, String.valueOf(model.getName()).trim())
.eq(UnitDict::getOId, String.valueOf(model.getOId()).trim())
.ne(UnitDict::getId, model.getId())
.list())
) {
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,240 @@
package com.whdc.legacy.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.whdc.legacy.model.dto.LoginDto;
import com.whdc.legacy.model.dto.UserDto;
import com.whdc.legacy.model.dto.VxLoginDto;
import com.whdc.legacy.model.entity.User;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.AuthToken;
import com.whdc.legacy.model.vo.LoginVo;
import com.whdc.legacy.service.IUserService;
import com.whdc.legacy.service.impl.UserServiceImpl;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import static com.whdc.legacy.service.impl.UserServiceImpl.getPassword;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "用户表 - Controller")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService service;
@ApiOperation(value = "登录", notes = "登录后,从 tokenInfo 中获取 token 相关信息。headers[tokenName] = tokenValue ")
@PostMapping("doLogin")
public ResultJson<LoginVo> doLogin(@RequestBody @Validated LoginDto obj) throws InvocationTargetException, IllegalAccessException {
LoginVo loginVo = service.login(obj);
if (loginVo == null || loginVo.getId() == null) {
return ResultJson.error("登录失败");
} else {
StpUtil.login(loginVo.getId()); // 使用 user id 登录
// 获取 Token 相关参数
loginVo.setTokenInfo(new AuthToken(StpUtil.getTokenInfo()));
// 更新最后登录时间
service.updateLastDate(loginVo.getId());
return ResultJson.ok(loginVo);
}
}
@ApiOperation(value = "wx登录", notes = "登录后,从 tokenInfo 中获取 token 相关信息。headers[tokenName] = tokenValue ")
@PostMapping("wxLogin")
public ResultJson<LoginVo> wxLogin(@RequestBody @Validated VxLoginDto obj) throws InvocationTargetException, IllegalAccessException {
LoginVo loginVo = service.wxLogin(obj);
if (loginVo == null || loginVo.getId() == null) {
return ResultJson.error("登录失败");
} else {
StpUtil.login(loginVo.getId()); // 使用 user id 登录
// 获取 Token 相关参数
loginVo.setTokenInfo(new AuthToken(StpUtil.getTokenInfo()));
// 更新最后登录时间
service.updateLastDate(loginVo.getId());
return ResultJson.ok(loginVo);
}
}
@ApiOperation(value = "wxOpenid登录", notes = "登录后,从 tokenInfo 中获取 token 相关信息。headers[tokenName] = tokenValue ")
@GetMapping("wxLogin/{openid}")
public ResultJson<LoginVo> getWxLogin(@PathVariable("openid") String openid) throws InvocationTargetException, IllegalAccessException {
LoginVo loginVo = service.wxLogin(openid);
if (loginVo == null || loginVo.getId() == null) {
return ResultJson.error("登录失败");
} else {
StpUtil.login(loginVo.getId()); // 使用 user id 登录
// 获取 Token 相关参数
loginVo.setTokenInfo(new AuthToken(StpUtil.getTokenInfo()));
// 更新最后登录时间
service.updateLastDate(loginVo.getId());
return ResultJson.ok(loginVo);
}
}
@ApiOperation(value = "查询登录状态")
@PostMapping("isLogin")
public ResultJson<AuthToken> isLogin() {
return ResultJson.ok(StpUtil.getTokenInfo());
}
@ApiOperation(value = "按id踢人下线")
@PostMapping("kickout/{id}")
public ResultJson kickout(@PathVariable String id) {
StpUtil.kickout(id);
return ResultJson.ok("将用户[" + id + "]踢下线");
}
@ApiOperation(value = "登出")
@PostMapping("logout")
public ResultJson logout() {
StpUtil.logout();
return ResultJson.ok();
}
// @ApiOperation(value = "查询所有")
// @PostMapping(value = "find")
public ResultJson<User> find(@RequestBody User dto) {
return ResultJson.ok(service.find(dto));
}
// @ApiOperation(value = "分页查询")
// @PostMapping(value = "page")
public ResultJson<User> page(@RequestBody User dto) {
return ResultJson.ok(service.page(dto));
}
// @ApiOperation(value = "注册")
// @PostMapping(value = "register")
public ResultJson insert(@RequestBody @Validated(Insert.class) User model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(User::getUsername,String.valueOf(model.getUsername()).trim())
.list())
){
return ResultJson.error("该名称重复");
}
return ResultJson.ok(service.register(model));
}
// @ApiOperation(value = "修改")
// @PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) User model) {
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(User::getUsername,String.valueOf(model.getUsername()).trim())
.ne(User::getId, model.getId())
.list())
){
return ResultJson.error("用户名重复");
}
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
@ApiOperation(value = "修改密码")
@PostMapping(value = "updatePw")
public ResultJson updatePwd(@RequestBody UserDto dto) {
return service.updatePwd(dto);
}
@ApiOperation(value = "忘记密码")
@GetMapping(value = "forgotPassword/{username}")
public ResultJson updatePwd(@PathVariable("username") String username) {
User one = service.lambdaQuery().eq(User::getUsername, username)
.one();
if (Objects.isNull(service.getById(one))) {
return ResultJson.error("当前数据不存在");
}
one.setPassword(getPassword(one.getSalt(), UserServiceImpl.DEFAULT_PASSWORD));
return ResultJson.ok(one.updateById() + " " + UserServiceImpl.DEFAULT_PASSWORD);
}
@ApiOperation(value = "发送验证码")
@GetMapping(value = "pushCode/{phone}")
public ResultJson pushCode(@PathVariable("phone") String phone) {
return ResultJson.ok(service.pushCode(phone));
}
@ApiOperation(value = "手机验证码登录")
@GetMapping(value = "loginByCode/{phone}/{code}")
public ResultJson loginByCode(@PathVariable("phone") String phone,@PathVariable("code") String code) throws InvocationTargetException, IllegalAccessException {
LoginVo loginVo = service.loginByCode(phone, code.toUpperCase());
StpUtil.login(loginVo.getId()); // 使用 user id 登录
// 获取 Token 相关参数
loginVo.setTokenInfo(new AuthToken(StpUtil.getTokenInfo()));
// 更新最后登录时间
service.updateLastDate(loginVo.getId());
return ResultJson.ok(loginVo);
}
}

View File

@ -0,0 +1,77 @@
package com.whdc.legacy.controller;
import com.whdc.legacy.model.dto.CommDto;
import com.whdc.legacy.model.entity.Versions;
import com.whdc.legacy.service.IVersionsService;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* @author xusan
* @date 2024-05-11
*/
@Slf4j
@Api(tags = "通讯录日志 - Controller")
@RestController
@RequestMapping("/versions")
public class VersionsController {
@Autowired
private IVersionsService service;
// @ApiOperation(value = "查询所有")
// @PostMapping(value = "find")
public ResultJson<Versions> find(@RequestBody Versions dto) {
return ResultJson.ok(service.find(dto));
}
@ApiOperation(value = "分页查询")
@PostMapping(value = "page")
public ResultJson<Versions> page(@RequestBody CommDto dto, HttpServletRequest request) {
if (StringUtils.isBlank(dto.getAdcd())){
dto.setAdcd(request.getHeader("adcd"));
}
return ResultJson.ok(service.page(dto));
}
@ApiOperation(value = "通过版本号查询")
@GetMapping(value = "getByV/{abId}/{version}")
public ResultJson<Versions> getByV(@PathVariable("abId") Integer abId, @PathVariable("version") Integer version) {
if (version < 0) {
return ResultJson.error("版本号不能小于0");
}
return ResultJson.ok(service.lambdaQuery()
.eq(Versions::getAbId, abId)
.eq(Versions::getVersion, version).one());
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
}

View File

@ -0,0 +1,135 @@
package com.whdc.legacy.controller;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.whdc.legacy.model.entity.WarningResponder;
import com.whdc.legacy.model.entity.QXWarning;
import com.whdc.legacy.model.entity.WarnMsgFB;
import com.whdc.legacy.model.vo.ExcelOldDataVo;
import com.whdc.legacy.service.IWarningResponderService;
import com.whdc.legacy.service.IQXWarningService;
import com.whdc.legacy.service.IWarnMsgFBService;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Api(tags = "预警叫应 - Controller")
@RestController
@RequestMapping("/warnmsgfb")
public class WarnMsgFBController {
@Autowired
private IWarnMsgFBService service;
@Autowired
private IQXWarningService qxService;
@Autowired
private IWarningResponderService oldService;
//增
@ApiOperation(value = "新增")
@PostMapping(value = "/add")
public ResultJson<String> insert(@RequestBody @Validated WarnMsgFB dto) {
//根据warnid和phone判断是否重复
if (CollectionUtils.isNotEmpty(
service.lambdaQuery()
.eq(WarnMsgFB::getWarnid,dto.getWarnid())
.eq(WarnMsgFB::getCalledPhone,String.valueOf(dto.getCalledPhone())).list()
)
){
return ResultJson.error("该名称或编码重复");
}
boolean save = service.save(dto);
return ResultJson.ok(save);
}
//删
//改
//查
@ApiOperation(value = "查询所有")
@PostMapping(value = "/find")
public ResultJson<WarnMsgFB> find(@RequestBody WarnMsgFB dto) {
return ResultJson.ok(service.find(dto));
}
@ApiOperation(value = "解析文件数据")
@PostMapping(value = "getExcelData")
public ResultJson<ExcelOldDataVo> getExcelData(MultipartFile file) {
List<WarnMsgFB> warnMsgs = ExcelCommon.importExcel(file,0, 1, WarnMsgFB.class);
List<QXWarning> qxWarns = ExcelCommon.importExcel(file,1, 0, 1, QXWarning.class);
Map<String, List<QXWarning>> qxByID = qxWarns.stream().collect(Collectors.groupingBy(QXWarning::getEffectId, Collectors.toList()));
List<WarningResponder> olds = oldService.list();
Map<String, List<WarningResponder>> txlByName = olds.stream().collect(Collectors.groupingBy(WarningResponder::getName, Collectors.toList()));
warnMsgs.forEach(o -> {
List<QXWarning> qxWarnings = qxByID.get(o.getEffectId());
if (CollectionUtils.isNotEmpty(qxWarnings)){
QXWarning qxWarning = qxWarnings.get(0);
o.setHandleTime(qxWarning.getHandleTime())
.setPublishTime(qxWarning.getPublishTime())
.setWarnid(qxWarning.getWarnid());
String name = o.getCalledPerson();
List<WarningResponder> txl = txlByName.get(name);
if (CollectionUtils.isNotEmpty(txl)){
o.setCalledPhone(txl.get(0).getPhone());
}else{
o.setCalledPhone(null);
}
}
});
List<Integer> warns = warnMsgs.stream().map(WarnMsgFB::getWarnid).collect(Collectors.toList());
List<WarnMsgFB> list = service.lambdaQuery().in(WarnMsgFB::getWarnid, warns).list();
Map<Integer, List<WarnMsgFB>> map = list.stream().collect(Collectors.groupingBy(WarnMsgFB::getWarnid, Collectors.toList()));
List<WarnMsgFB> warnDb = Lists.newArrayList();
for (WarnMsgFB warn : warnMsgs) {
Integer warnid = warn.getWarnid();
if (!map.containsKey(warnid)){
warnDb.add(warn);
}
}
if (CollectionUtils.isNotEmpty(warnDb)){
service.saveBatch(warnDb);
}
List<Integer> qxwarns = qxWarns.stream().map(QXWarning::getWarnid).collect(Collectors.toList());
List<QXWarning> qxlist = qxService.lambdaQuery().in(QXWarning::getWarnid, qxwarns).list();
Map<Integer, List<QXWarning>> qxmap = qxlist.stream().collect(Collectors.groupingBy(QXWarning::getWarnid, Collectors.toList()));
List<QXWarning> qxDb = Lists.newArrayList();
for (QXWarning qxWarn : qxWarns) {
Integer warnid = qxWarn.getWarnid();
if (!qxmap.containsKey(warnid)){
qxDb.add(qxWarn);
}
}
if (CollectionUtils.isNotEmpty(qxDb)){
qxService.saveBatch(qxDb);
}
return ResultJson.ok();
}
}

View File

@ -0,0 +1,486 @@
package com.whdc.legacy.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.ApiDto;
import com.whdc.legacy.model.dto.GroupWarningDto;
import com.whdc.legacy.model.vo.AdcdTree;
import com.whdc.legacy.model.vo.WarningData;
import com.whdc.legacy.model.vo.WarningHistoryListVo;
import com.whdc.legacy.model.vo.WarningListVo;
import com.whdc.legacy.service.IAddressBookService;
import com.whdc.legacy.service.IAdinfoService;
import com.whdc.common.utils.HttpUtil;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import java.util.stream.Collectors;
import static com.whdc.legacy.model.MyConstant.REDIS_KEY;
import static com.whdc.legacy.service.impl.AdinfoServiceImpl.TREE_ALL;
/**
* Description:
* Created by XuSan on 2024/5/23.
*
* @author XuSan
* @version 1.0
*/
@Slf4j
@Api(tags = "预警 - Controller")
@RestController
@RequestMapping("/warning")
public class WarningController {
public static final String THIS_REDIS_KEY = REDIS_KEY + "warning";
@Value("${getGroupWarning}")
public String getGroupWarning;
@Autowired
private IAddressBookService addressBookService;
@Autowired
private IAdinfoService adinfoService;
/**
*
*
* @param dto
* @return
*/
@ApiOperation(value = "气象预警")
@PostMapping("/getGroupWarning")
public ResultJson<List<WarningListVo>> getGroupWarning(
@RequestBody GroupWarningDto dto) {
ApiDto apiDto = new ApiDto();
apiDto.setStartTime(dto.getStartTime());
apiDto.setEndTime(dto.getEndTime());
apiDto.setPageNumber(dto.getPageNumber());
apiDto.setPageSize(dto.getPageSize());
ArrayList<ApiDto.Filter> filter = Lists.newArrayList();
String publishUnit = dto.getPublishUnit();
// if (StringUtils.isNotBlank(publishUnit)) {
// String[] split = publishUnit.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("publishUnit", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("publishUnit", "like", String.format("%s%s%s", "%", publishUnit, "%")));
// }
// }
String warnSignalLevel = dto.getWarnSignalLevel();
// if (StringUtils.isNotBlank(warnSignalLevel)) {
// String[] split = warnSignalLevel.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("warnSignalLevel", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("warnSignalLevel", "like", String.format("%s%s%s", "%", warnSignalLevel, "%")));
// }
// }
String warnSignalType = dto.getWarnSignalType();
// if (StringUtils.isNotBlank(warnSignalType)) {
// String[] split = warnSignalType.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("warnSignalType", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("warnSignalType", "like", String.format("%s%s%s", "%", warnSignalType, "%")));
// }
// }
apiDto.setFilter(filter);
// String str = HttpUtil.sendPost(getGroupWarning, JSON.toJSONString(apiDto));
String str = HttpUtil.sendPost("http://127.0.0.1:20000/shzh/met/zyqxfw/api/warning/getGroupWarning", JSON.toJSONString(apiDto));
JSONObject json = JSON.parseObject(str);
if (json != null && json.getInteger("code") == HttpStatus.SC_OK) {
List<WarningData> data = json.getJSONArray("data").toJavaList(WarningData.class);
return ResultJson.ok(getList(data, publishUnit, warnSignalLevel, warnSignalType));
}
return ResultJson.ok(json);
}
/**
*
*
* @param dto
* @return
*/
@ApiOperation(value = "历史气象预警统计")
@PostMapping("/getHistoryGroupWarning")
// @Cacheable(value = THIS_REDIS_KEY, key = "#root.method.name+':'+#dto.toString()")
public ResultJson<List<WarningHistoryListVo>> getHistoryGroupWarning(@RequestBody GroupWarningDto dto) {
ApiDto apiDto = new ApiDto();
apiDto.setStartTime(dto.getStartTime());
apiDto.setEndTime(dto.getEndTime());
apiDto.setPageNumber(dto.getPageNumber());
apiDto.setPageSize(dto.getPageSize());
ArrayList<ApiDto.Filter> filter = Lists.newArrayList();
String publishUnit = dto.getPublishUnit();
// if (StringUtils.isNotBlank(publishUnit)) {
// String[] split = publishUnit.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("publishUnit", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("publishUnit", "like", String.format("%s%s%s", "%", publishUnit, "%")));
// }
// }
String warnSignalLevel = dto.getWarnSignalLevel();
// if (StringUtils.isNotBlank(warnSignalLevel)) {
// String[] split = warnSignalLevel.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("warnSignalLevel", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("warnSignalLevel", "like", String.format("%s%s%s", "%", warnSignalLevel, "%")));
// }
// }
String warnSignalType = dto.getWarnSignalType();
// if (StringUtils.isNotBlank(warnSignalType)) {
// String[] split = warnSignalType.split(",");
// if (split.length > 1) {
// String str = "(";
// for (String s : split) {
// str += s + ",";
// }
// str = str.substring(0, str.length() - 1) + ")";
// filter.add(new ApiDto.Filter("warnSignalType", "in " + str, ""));
//
// } else {
// filter.add(new ApiDto.Filter("warnSignalType", "like", String.format("%s%s%s", "%", warnSignalType, "%")));
// }
// }
apiDto.setFilter(filter);
String str = HttpUtil.sendPost(getGroupWarning, JSON.toJSONString(apiDto));
// String str = HttpUtil.sendPost("http://127.0.0.1:20000/shzh/met/zyqxfw/api/warning/getGroupWarning", JSON.toJSONString(apiDto));
JSONObject json = JSON.parseObject(str);
if (json != null && json.getInteger("code") == HttpStatus.SC_OK) {
List<WarningData> data = json.getJSONArray("data").toJavaList(WarningData.class);
return ResultJson.ok(getCount(data, publishUnit, warnSignalLevel, warnSignalType));
}
return ResultJson.ok(json);
}
/**
*
*
* @param data
* @return
*/
private List<WarningListVo> getList(List<WarningData> data,
String reqPublishUnit,
String reqWarnSignalLevel,
String reqWarnSignalType) {
List<WarningListVo> respList = Lists.newArrayList();
for (WarningData datum : data) {
for (WarningData.TypeList typeList : datum.getTypeList()) {
// 预警类型
String type = typeList.getType();
List<WarningData.Warning> warnList = typeList.getWarnList();
warnList = warnListFilter(warnList, reqPublishUnit, reqWarnSignalLevel, reqWarnSignalType);
for (WarningData.Warning warning : warnList) {
WarningListVo vo = new WarningListVo();
String publishUnit = warning.getPublishUnit();
vo.setTitle(publishUnit + "发布" + type + "预警");
vo.setPublishTime(warning.getPublishTime());
vo.setContent(warning.getContent());
vo.setWarnSignalType(warning.getWarnSignalType());
vo.setWarnSignalLevel(warning.getWarnSignalLevel());
vo.setAdnm(publishUnit.replace("气象台", ""));
String adnm = publishUnit.replace("气象台", "");
if ("恩施州".equals(adnm)){
adnm = "恩施土家族苗族自治州";
}
if ("武汉经济技术开发区".equals(adnm)){
adnm = "经济技术开发区(汉南区)";
}
String adcd = adinfoService.getAdcdByAdnm(adnm);
if (StringUtils.isNotBlank(adcd)){
vo.setAddressBooks(addressBookService.getListByAdnm(adcd));
}else{
log.info("当前行政区划不存在: " + adnm);
}
respList.add(vo);
}
}
}
return respList.stream().sorted(Comparator.comparing(WarningListVo::getPublishTime).reversed())
.collect(Collectors.toList());
}
/**
*
*
* @return
*/
private List<WarningData.Warning> warnListFilter(List<WarningData.Warning> warnList,
String publishUnit,
String warnSignalLevel,
String warnSignalType
) {
if (StringUtils.isNotBlank(publishUnit)) {
HashSet<String> set = Sets.newHashSet(publishUnit.split(","));
if (CollectionUtils.isNotEmpty(set)) {
warnList = warnList.stream()
.filter(w ->
set.contains(w.getPublishUnit().split("气象")[0])
).collect(Collectors.toList());
}
}
if (StringUtils.isNotBlank(warnSignalLevel)) {
HashSet<String> set = Sets.newHashSet(warnSignalLevel.split(","));
if (CollectionUtils.isNotEmpty(set)) {
warnList = warnList.stream()
.filter(w ->
set.contains(w.getWarnSignalLevel())
).collect(Collectors.toList());
}
}
if (StringUtils.isNotBlank(warnSignalType)) {
HashSet<String> set = Sets.newHashSet(warnSignalType.split(","));
if (CollectionUtils.isNotEmpty(set)) {
warnList = warnList.stream()
.filter(w ->
set.contains(w.getWarnSignalType())
).collect(Collectors.toList());
}
}
return warnList;
}
private List<WarningHistoryListVo> getCount(List<WarningData> data,
String publishUnit,
String warnSignalLevel,
String reqWarnSignalType
) {
List<WarningData.Warning> warnList = Lists.newArrayList();
for (WarningData datum : data) {
for (WarningData.TypeList typeList : datum.getTypeList()) {
warnList.addAll(typeList.getWarnList());
}
}
warnList = warnListFilter(warnList, publishUnit, warnSignalLevel, reqWarnSignalType);
Map<String, List<WarningData.Warning>> warnMap = warnList.stream()
.collect(Collectors
.groupingBy(WarningData.Warning::getPublishUnit, Collectors.toList()));
List<WarningHistoryListVo> voList = Lists.newArrayList();
warnMap.forEach((k, v) -> {
WarningHistoryListVo vo = new WarningHistoryListVo();
vo.setEffectArea(k.split("气象")[0]);
vo.setWarnSignalType("暴雨");
// List<WarningHistoryListVo> typeList = Lists.newArrayList();
// 类型 只要暴雨
Map<String, List<WarningData.Warning>> types = v.stream()
// .filter(o -> "暴雨".equals(o.getWarnSignalType()))
.filter(o -> "橙色".equals(o.getWarnSignalLevel()) || "红色".equals(o.getWarnSignalLevel()))
.collect(Collectors
.groupingBy(WarningData.Warning::getWarnSignalType, Collectors.toList()));
// Set<String> warnSignalType = Sets.newHashSet("雷电", "暴雨", "大风", "冰雹", "雷雨大风");
types.forEach((kt, vt) -> {
// WarningHistoryListVo voType = new WarningHistoryListVo();
// voType.setWarnSignalType(kt);
// warnSignalType.remove(kt);
// 等级分组
Map<String, Long> levels = vt.stream()
.collect(Collectors.groupingBy(WarningData.Warning::getWarnSignalLevel, Collectors.counting()));
levels.forEach((k1, v1) -> {
switch (k1) {
case "红色":
// voType.setRedCount(v1.intValue());
vo.setRedCount(v1.intValue() + vo.getRedCount());
break;
case "橙色":
// voType.setOraCount(v1.intValue());
vo.setOraCount(v1.intValue() + vo.getOraCount());
break;
case "黄色":
// voType.setYelCount(v1.intValue());
vo.setYelCount(v1.intValue() + vo.getYelCount());
break;
case "蓝色":
// voType.setBluCount(v1.intValue());
vo.setBluCount(v1.intValue() + vo.getBluCount());
break;
default:
throw new MyException("当前预警等级不存在: " + k1);
}
});
// voType.setSumCount(vt.size());
// typeList.add(voType);
});
// 保证完整数据
// warnSignalType.forEach(kt -> {
// WarningHistoryListVo voType = new WarningHistoryListVo();
// voType.setWarnSignalType(kt);
// typeList.add(voType);
// });
// vo.setChild(typeList);
vo.setSumCount(vo.getRedCount() + vo.getOraCount() + vo .getYelCount() + vo.getBluCount());
voList.add(vo);
});
// 进行行政区划匹配
if (CollectionUtils.isNotEmpty(voList)) {
List<AdcdTree> tree = adinfoService.tree(TREE_ALL, TREE_ALL);
Map<String, List<WarningHistoryListVo>> areaMap = voList.stream()
.collect(Collectors
.groupingBy(WarningHistoryListVo::getEffectArea, Collectors.toList()));
return setAll(getAdcdByWhlVo(tree, areaMap));
}
return setAll(voList);
}
private List<WarningHistoryListVo> setAll(List<WarningHistoryListVo> vos) {
if (CollectionUtils.isNotEmpty(vos)) {
WarningHistoryListVo vo = new WarningHistoryListVo();
vo.setWarnSignalType("暴雨");
vo.setEffectArea("总计");
int oraSum = vos.stream().mapToInt(WarningHistoryListVo::getOraCount).sum();
vo.setOraCount(oraSum);
int redSum = vos.stream().mapToInt(WarningHistoryListVo::getRedCount).sum();
vo.setRedCount(redSum);
int bluSum = vos.stream().mapToInt(WarningHistoryListVo::getBluCount).sum();
vo.setBluCount(bluSum);
int yelSum = vos.stream().mapToInt(WarningHistoryListVo::getYelCount).sum();
vo.setYelCount(yelSum);
vo.setSumCount(oraSum + redSum + bluSum + yelSum);
vos.add(0, vo);
}
return vos;
}
private List<WarningHistoryListVo> getAdcdByWhlVo(List<AdcdTree> tree, Map<String, List<WarningHistoryListVo>> areaMap) {
List<WarningHistoryListVo> respList = Lists.newArrayList();
for (AdcdTree adcdTree : tree) {
String adnm = adcdTree.getAdnm();
if ("恩施土家族苗族自治州".equals(adnm)){
adnm = "恩施州";
adcdTree.setAdnm(adnm);
}
List<AdcdTree> children = adcdTree.getChildren();
List<WarningHistoryListVo> vos = areaMap.remove(adnm);
if (CollectionUtils.isNotEmpty(vos)) {
WarningHistoryListVo vo = vos.get(0);
List<WarningHistoryListVo> childList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(children)) {
// 第一个是市级单位
for (int i = 1; i < children.size(); i++) {
AdcdTree t = children.get(i);
String adnm1 = t.getAdnm();
if ("经济技术开发区(汉南区)".equals(adnm1)){
adnm1 = "武汉经济技术开发区";
}
List<WarningHistoryListVo> vos1 = areaMap.remove(adnm1);
if (CollectionUtils.isNotEmpty(vos1)) {
childList.addAll(vos1);
}
}
}
vo.setAreaChild(childList);
respList.add(vo);
}
}
areaMap.keySet().forEach(s -> System.out.println("未匹配行政区划: " + s));
return respList;
}
// public static void main(String[] args) {
// GroupWarningDto dto = new GroupWarningDto();
// dto.setStartTime("2024-01-01 00:00:00");
// dto.setEndTime("2024-06-20 23:00:00");
// System.out.println(new WarningController().getHistoryGroupWarning(dto));
// }
}

View File

@ -0,0 +1,260 @@
package com.whdc.legacy.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.whdc.common.exception.MyException;
import com.whdc.legacy.model.dto.WarningResponderDto;
import com.whdc.legacy.model.entity.WarningResponder;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import com.whdc.legacy.model.vo.ExcelDataVo;
import com.whdc.legacy.model.vo.ExcelOldDataVo;
import com.whdc.legacy.service.IWarningResponderService;
import com.whdc.common.utils.ExcelCommon;
import com.whdc.common.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.whdc.legacy.model.MyConstant.REDIS_KEY;
/**
* Description:
* Created by XuSan on 2024/6/11.
*
* @author XuSan
* @version 1.0
*/
@Slf4j
@Api(tags = "web通讯录 - Controller")
@RestController
@RequestMapping({"/addressbookOld", "/warningResponder"})
@Transactional
public class WarningResponderController {
@Autowired
private IWarningResponderService service;
public static final String ADDRESS_BOOK_REDIS_KEY = REDIS_KEY + "addressbookOld";
public static final String ADDRESS_BOOK_TEMP_REDIS_KEY = ADDRESS_BOOK_REDIS_KEY + "temp:";
@Autowired
private RedisTemplate<String,String> redisTemplate;
@ApiOperation(value = "查询所有联系人")
@PostMapping(value = "find")
// @Cacheable(value = ADDRESS_BOOK_REDIS_KEY, key = "#root.method.name+':'+#dto.toString()")
public ResultJson<List<WarningResponder>> find(@RequestBody WarningResponderDto dto) {
LambdaQueryChainWrapper<WarningResponder> query = service.lambdaQuery();
String name = dto.getName();
if (StringUtils.isNotBlank(name)){
query.like(WarningResponder::getName, name);
}
String phone = dto.getPhone();
if (StringUtils.isNotBlank(phone)){
query.like(WarningResponder::getPhone, phone);
}
// 添加默认排序
query.orderByAsc(WarningResponder::getCtnm).orderByAsc(WarningResponder::getCnnm).orderByAsc(WarningResponder::getName);
List<WarningResponder> data = query.list();
data = data.stream().map(vo -> vo.setLevelLabel(dictMappingReverse(vo.getLevel())).decryptPhone()).collect(Collectors.toList());
return ResultJson.ok(data);
}
@ApiOperation(value = "下载excel")
@GetMapping(value = "downloadExcel")
public void downloadExcel( HttpServletResponse response) {
List<WarningResponder> list = service.lambdaQuery()
.list();
for (WarningResponder o : list) {
o.decryptPhone();
}
list.stream().forEach(vo -> vo.setLevelLabel(dictMappingReverse(vo.getLevel())));
ExcelCommon.exportExcel(list,
null, "防汛抗旱通讯录", WarningResponder.class, "湖北省防汛抗旱通信录模版" + LocalDateTime.now() + ".xlsx",
response);
}
@ApiOperation(value = "解析文件数据")
@PostMapping(value = "getExcelData")
public ResultJson<ExcelOldDataVo> getExcelData(MultipartFile file) {
List<WarningResponder> appends = ExcelCommon.importExcel(file, 0, 1, WarningResponder.class);
ExcelOldDataVo excelDataVo = new ExcelOldDataVo();
if (CollectionUtils.isNotEmpty(appends)){
appends = appends.stream().filter(vo ->
StringUtils.isNotBlank(vo.getName())
&& StringUtils.isNotBlank(vo.getCtnm())
&& StringUtils.isNotBlank(vo.getCnnm())
).collect(Collectors.toList());
String key = UUID.randomUUID().toString().replaceAll("-", "");
redisTemplate.opsForValue().set(ADDRESS_BOOK_TEMP_REDIS_KEY + key, JSON.toJSONString(appends), 30, TimeUnit.MINUTES);
excelDataVo.setKey(key);
excelDataVo.setList(appends);
}
return ResultJson.ok(excelDataVo);
}
@ApiOperation(value = "联系人导入")
@PostMapping(value = "uploadExcel")
@CacheEvict(value = ADDRESS_BOOK_REDIS_KEY, allEntries = true)
public ResultJson uploadExcel(@RequestBody ExcelDataVo data) {
String s = redisTemplate.opsForValue().get(ADDRESS_BOOK_TEMP_REDIS_KEY + data.getKey());
if (StringUtils.isBlank(s)){
throw new MyException("文件已过期");
}
List<WarningResponder> appends = JSON.parseArray(s, WarningResponder.class);
if (CollectionUtils.isEmpty(appends)) {
throw new MyException("文件数据为空");
}
// Set<String> set = appends.stream().map(vo -> vo.getName() + "_" + vo.getPhone()).collect(Collectors.toSet());
// if (set.size() != appends.size()){
// throw new MyException("联系人重复");
// }
boolean r1 = service.remove(Wrappers.emptyWrapper());
if (!r1) {
throw new MyException("通讯录数据删除失败");
}
// 新增创建时间
Date date = new Date();
appends = appends.stream().map(vo -> vo.setCreateTime(date).setLevel(dictMapping(vo.getLevelLabel())).encryptPhone())
.collect(Collectors.toList());
if (!service.saveBatch(appends)) {
throw new MyException("表格数据新增失败");
}
return ResultJson.ok("数据新增成功");
}
private Integer dictMapping(String label) {
if (label == null) {
return null;
}
switch (label) {
case "分管副市(县)长":
return 1;
case "常务副市(县)长":
return 2;
case "市(县)长":
return 3;
case "书记":
return 4;
default:
return null;
}
}
private String dictMappingReverse(Integer level) {
if (level == null) {
return null;
}
switch (level) {
case 1:
return "分管副市(县)长";
case 2:
return "常务副市(县)长";
case 3:
return "市(县)长";
case 4:
return "书记";
default:
return null;
}
}
@ApiOperation(value = "添加")
@PostMapping(value = "save")
public ResultJson insert(@RequestBody @Validated(Insert.class) WarningResponder model) {
// 暂时不做数据唯一性校验
// if (CollectionUtils.isNotEmpty(
// service.lambdaQuery()
// .list())
// ) {
// return ResultJson.error("重复新增");
// }
model.setCreateTime(new Date()).encryptPhone();
return ResultJson.ok(service.save(model));
}
@ApiOperation(value = "修改")
@PostMapping(value = "edit")
public ResultJson update(@RequestBody @Validated(Update.class) WarningResponder model) {
// 暂时不做数据唯一性校验
// if (CollectionUtils.isNotEmpty(
// service.lambdaQuery()
// .list())
// ) {
// return ResultJson.error("重复修改");
// }
model.encryptPhone();
return ResultJson.ok(service.updateById(model));
}
@ApiOperation(value = "删除")
@GetMapping(value = "del/{id}")
public ResultJson delete(@PathVariable("id") Integer id) {
if (Objects.isNull(service.getById(id))) {
return ResultJson.error("当前数据不存在");
}
return ResultJson.ok(service.removeById(id));
}
@ApiOperation(value = "预警呼叫等级")
@GetMapping(value = "getWarnCallLevelDict")
public ResultJson getWarnCallLevelDict() {
Map<Integer, String> dictMap = new LinkedHashMap<>();
dictMap.put(4, "书记");
dictMap.put(3, "市(县)长");
dictMap.put(2, "常务副市(县)长");
dictMap.put(1, "分管副市(县)长");
return ResultJson.ok(dictMap);
}
}

View File

@ -0,0 +1,20 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.AbUdR;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface AbUdRMapper extends BaseMapper<AbUdR> {
IPage<AbUdR> page(@Param("page") IPage<AbUdR> page, @Param("dto") AbUdR dto);
List<AbUdR> find(@Param("dto") AbUdR dto);
}

View File

@ -0,0 +1,15 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.whdc.legacy.model.entity.AddressBookCity;
/**
* @author xusan
* @date 2024-05-11
*/
public interface AddressBookCityMapper extends BaseMapper<AddressBookCity> {
}

View File

@ -0,0 +1,27 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.AddressBookDto;
import com.whdc.legacy.model.entity.AddressBook;
import com.whdc.legacy.model.vo.AddressBookVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface AddressBookMapper extends BaseMapper<AddressBook> {
IPage<AddressBookVo> page(@Param("page") IPage<AddressBook> page, @Param("dto") AddressBookDto dto);
List<AddressBook> find(@Param("dto") AddressBook dto);
List<AddressBook> getListByAdnm(@Param("adcd") String adcd);
AddressBookVo getVoById(@Param("id") Integer id);
AddressBookVo getVoByOpenid(@Param("id") String id);
}

View File

@ -0,0 +1,23 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.Adinfo;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface AdinfoMapper extends BaseMapper<Adinfo> {
IPage<Adinfo> page(@Param("page") IPage<Adinfo> page, @Param("dto") Adinfo dto);
List<Adinfo> find(@Param("dto") Adinfo dto);
List<Adinfo> selectByCdOrNm(@Param("adcd") String adcd, @Param("adnm") String adnm);
Adinfo selectAdcdByAdnm(@Param("adnm") String adnm);
}

View File

@ -0,0 +1,22 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.FcDto;
import com.whdc.legacy.model.vo.FcVo;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.Fc;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface FcMapper extends BaseMapper<Fc> {
IPage<FcVo> page(@Param("page") IPage<FcVo> page, @Param("dto") FcDto dto);
List<Fc> find(@Param("dto") Fc dto);
}

View File

@ -0,0 +1,22 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.FindPageDto;
import com.whdc.legacy.model.dto.LoginInfoDto;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.LoginInfo;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface LoginInfoMapper extends BaseMapper<LoginInfo> {
IPage<LoginInfo> page(@Param("page") IPage<LoginInfo> page, @Param("dto") LoginInfoDto dto);
List<LoginInfo> find(@Param("dto") LoginInfo dto);
}

View File

@ -0,0 +1,20 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.Organization;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface OrganizationMapper extends BaseMapper<Organization> {
IPage<Organization> page(@Param("page") IPage<Organization> page, @Param("dto") Organization dto);
List<Organization> findByUserId(@Param("userId") String userId);
}

View File

@ -0,0 +1,22 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.GroupWarningDto;
import com.whdc.legacy.model.entity.QXWarning;
import com.whdc.legacy.model.vo.QXWarningVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface QXWarningMapper extends BaseMapper<QXWarning> {
List<QXWarning> find(@Param("dto") QXWarning dto);
List<QXWarningVO> findByMsgIsNull();
List<QXWarningVO> findByAutoMsgIsNull();
IPage<QXWarning> page(@Param("page") IPage<QXWarning> page, @Param("dto") GroupWarningDto dto);
List<QXWarning> list(@Param("dto") GroupWarningDto dto);
List<QXWarning> getWarnAndMsg(@Param("stm") String stm, @Param("etm") String etm);
}

View File

@ -0,0 +1,19 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.ShAddressBookDto;
import com.whdc.legacy.model.entity.ShAddressBook;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Mapper
public interface ShAddressBookMapper extends BaseMapper<ShAddressBook> {
IPage<ShAddressBook> page(@Param("page") IPage<ShAddressBook> page, @Param("dto") ShAddressBookDto dto);
}

View File

@ -0,0 +1,24 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.ShCallWordDto;
import com.whdc.legacy.model.entity.ShCallWord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Mapper
public interface ShCallWordMapper extends BaseMapper<ShCallWord> {
IPage<ShCallWord> page(@Param("page") IPage<ShCallWord> page, @Param("dto") ShCallWordDto dto);
List<ShCallWord> page(@Param("dto") ShCallWordDto dto);
}

View File

@ -0,0 +1,27 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.ShCallsDto;
import com.whdc.legacy.model.entity.ShAddressBook;
import com.whdc.legacy.model.entity.ShCalls;
import com.whdc.legacy.model.vo.ShCallsVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Mapper
public interface ShCallsMapper extends BaseMapper<ShCalls> {
IPage<ShCallsVo> page(@Param("page") IPage<ShCallsVo> page, @Param("dto") ShCallsDto dto);
List<ShAddressBook> list(@Param("dto") ShCallsDto dto);
List<ShCallsVo> listVo(@Param("dto") ShCallsDto dto);
}

View File

@ -0,0 +1,20 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.ShPeriodDto;
import com.whdc.legacy.model.entity.ShPeriod;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* :
* author: xusan
* date: 2024-07-29 17:27:25
*/
@Mapper
public interface ShPeriodMapper extends BaseMapper<ShPeriod> {
IPage<ShPeriod> page(@Param("page") IPage<ShPeriod> page, @Param("dto") ShPeriodDto dto);
}

View File

@ -0,0 +1,23 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.entity.Organization;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.UnitDict;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface UnitDictMapper extends BaseMapper<UnitDict> {
IPage<UnitDict> page(@Param("page") IPage<UnitDict> page, @Param("dto") UnitDict dto);
List<UnitDict> find(@Param("dto") UnitDict dto);
List<UnitDict> findByUserId(@Param("userId") String userId);
}

View File

@ -0,0 +1,23 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.vo.LoginVo;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.User;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface UserMapper extends BaseMapper<User> {
IPage<User> page(@Param("page") IPage<User> page, @Param("dto") User dto);
List<User> find(@Param("dto") User dto);
LoginVo findByLoginName(@Param("username") String username);
}

View File

@ -0,0 +1,21 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whdc.legacy.model.dto.CommDto;
import org.apache.ibatis.annotations.Param;
import com.whdc.legacy.model.entity.Versions;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface VersionsMapper extends BaseMapper<Versions> {
IPage<Versions> page(@Param("page") IPage<Versions> page, @Param("dto") CommDto dto);
List<Versions> find(@Param("dto") Versions dto);
}

View File

@ -0,0 +1,15 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.whdc.legacy.model.entity.WarnMsgFB;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface WarnMsgFBMapper extends BaseMapper<WarnMsgFB> {
List<WarnMsgFB> selectByWarnid(@Param("warnid") Integer warnid);
List<WarnMsgFB> find(@Param("dto") WarnMsgFB dto);
List<WarnMsgFB> selectByWarnidAndCalledPhone(@Param("warnid") Integer warnid, @Param("calledPhone") String calledPhone);
}

View File

@ -0,0 +1,20 @@
package com.whdc.legacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.whdc.legacy.model.entity.WarningResponder;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author xusan
* @date 2024-05-11
*/
public interface WarningResponderMapper extends BaseMapper<WarningResponder> {
List<WarningResponder> getListByAdnm2(@Param("adnm") String adnm);
List<WarningResponder> listByCnnmAndLevelOrderByLevelAsc(@Param("cnnm") String cnnm, @Param("levels") List<Integer> levels);
}

View File

@ -0,0 +1,26 @@
package com.whdc.legacy.model;
/**
* @author xusan
* @date 2023/4/27 9:41
*/
public class MyConstant {
public static final String
// 删除
DEL = "0",
// 未删除
REC = "1",
// redis KEY
TOKEN_KEY = "SW_TOKEN_SJQX";
/**
* -
*/
public static final String ROLE_PUSH = "data_zh_om";
public static final String REDIS_KEY = "fxkh:txl:";
}

View File

@ -0,0 +1,18 @@
package com.whdc.legacy.model.dto;
import com.whdc.legacy.model.group.Find;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author xusan
* @date 202332008:57:22
*/
@Data
public class AdcdDto {
@ApiModelProperty(value = "行政区划编号")
private String adcd;
}

View File

@ -0,0 +1,41 @@
package com.whdc.legacy.model.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @Author xusan
* @Date 2024/5/13 10:17
* @Notes
**/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(description = "市县通讯录")
public class AddressBookCityDto extends FindPageDto {
/**
*
*/
@Schema(description = "职务")
private String unit;
/**
*
*/
@Schema(description = "姓名")
private String name;
/**
*
*/
@Schema(description = "电话")
private String phone;
}

View File

@ -0,0 +1,35 @@
package com.whdc.legacy.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author xusan
* @date 202332008:57:22
*/
@Data
public class AddressBookDto extends CommDto{
@ApiModelProperty(value = "用户单位id 或 组织id")
private String dictId;
@ApiModelProperty(value = "0:组织,1:单位")
private String type;
@ApiModelProperty(value = "0:常用联系人,1:置顶联系人")
private String ftype;
@ApiModelProperty(value = "行政区划")
private String adcd;
@ApiModelProperty(value = "行政区划级别 0省,1市,2县,3镇,4村,5组 ,(点击树查询下级, 点击查询按钮查询本级)", example = "0")
private Integer adlevel;
@ApiModelProperty(value = "登录用户id")
private String userId;
@ApiModelProperty(value = "搜索框模糊查询")
private String allLikeStr;
private String v;
}

View File

@ -0,0 +1,48 @@
package com.whdc.legacy.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Author xusan
* @Date 2023/7/4 10:28
* @Notes
**/
@Data
public class ApiDto {
@ApiModelProperty(value = "开始时间, 格式应为yyyy-MM-dd HH:mm:ss", dataType = "java.lang.String", example = "2023-06-15 08:00:00")
private String startTime;
@ApiModelProperty(value = "结束时间, 格式应为yyyy-MM-dd HH:mm:ss", dataType = "java.lang.String", example = "2023-06-15 08:00:00")
private String endTime;
@ApiModelProperty(value = "页数", dataType = "java.lang.Integer", example = "1")
private Integer pageNumber = 1;
@ApiModelProperty(value = "条数", dataType = "java.lang.Integer", example = "10")
private Integer pageSize = 10;
@ApiModelProperty(value = "过滤条件", dataType = "java.lang.Array", example = "[]")
private List<Filter> filter;
@AllArgsConstructor
@NoArgsConstructor
@Data
public static class Filter {
@ApiModelProperty(value = "查询列名 publishUnit:发布单位,warnSignalType:类型,warnSignalLevel:级别", dataType = "java.lang.String", example = "publishUnit")
private String name;
@ApiModelProperty(value = "查询类型", dataType = "java.lang.String", example = "like")
private String condition;
@ApiModelProperty(value = "值", dataType = "java.lang.String", example = "%1%")
private String value;
}
}

View File

@ -0,0 +1,24 @@
package com.whdc.legacy.model.dto;
import com.whdc.legacy.model.dto.FindPageDto;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* Description:
* Created by XuSan on 2024/7/31.
*
* @author XuSan
* @version 1.0
*/
@Data
@Accessors(chain = true)
public class AutoCallDto {
private String stm;
private String etm;
private Boolean callIsPut;
private FindPageDto page;
}

View File

@ -0,0 +1,11 @@
package com.whdc.legacy.model.dto;
import lombok.Data;
import java.util.List;
@Data
public class CallPutDto {
List<String> taskIds;
}

View File

@ -0,0 +1,34 @@
package com.whdc.legacy.model.dto;
import com.whdc.legacy.model.dto.FindPageDto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Author xusan
* @Date 2024/5/14 15:17
* @Notes
**/
@Data
public class CommDto extends FindPageDto {
@ApiModelProperty(value = "用户名称")
private String name;
@ApiModelProperty(value = "用户手机号")
private String phone;
@ApiModelProperty(value = "通讯录编号")
private String abId;
@ApiModelProperty(value = "0:添加用户,1:修改用户,2:修改权限,3:删除用户")
private String type;
@ApiModelProperty(value = "版本号")
private Integer version;
@ApiModelProperty(value = "行政区划编码")
private String adcd;
}

View File

@ -0,0 +1,32 @@
package com.whdc.legacy.model.dto;
import com.whdc.legacy.model.dto.FindPageDto;
import com.whdc.legacy.model.group.Find;
import com.whdc.legacy.model.group.Insert;
import com.whdc.legacy.model.group.Update;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author xusan
* @date 202332008:57:22
*/
@Data
public class FcDto extends FindPageDto {
@ApiModelProperty(value = "用户id")
@NotNull(message = "用户id不能为空", groups = {Find.class})
private String userId;
@ApiModelProperty(value = "类型 0:常用联系人,1:置顶联系人")
@NotNull(message = "类型不能为空", groups = {Find.class})
private String type;
@ApiModelProperty(value = "联系人名称")
private String name;
@ApiModelProperty(value = "联系人手机号")
private String phone;
}

Some files were not shown because too many files have changed in this diff Show More