Commit df6fff7a by liushuangwu

Merge branch 'master' of http://pipi-gitlab.apeiwan.com/zhangshaowu/pipi-helper

 Conflicts:
	src/main/java/com/pipihelper/project/feishu/controller/FeishuTaskController.java
2 parents 9559df76 4a7e39e2
Showing 26 changed files with 659 additions and 1058 deletions
...@@ -28,6 +28,10 @@ ...@@ -28,6 +28,10 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> </dependency>
<dependency> <dependency>
......
...@@ -2,6 +2,7 @@ package com.pipihelper.project.configurer; ...@@ -2,6 +2,7 @@ package com.pipihelper.project.configurer;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
...@@ -56,8 +57,8 @@ public class WebMvcConfigurer extends WebMvcConfigurerAdapter { ...@@ -56,8 +57,8 @@ public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
// 按需配置,更多参考FastJson文档哈 // 按需配置,更多参考FastJson文档哈
converter.setFastJsonConfig(config); converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8")); converter.setDefaultCharset(StandardCharsets.UTF_8);
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
converters.add(converter); converters.add(converter);
} }
......
...@@ -30,14 +30,14 @@ public class FeiShuEventController { ...@@ -30,14 +30,14 @@ public class FeiShuEventController {
public JSONObject event(@RequestBody String s) throws Exception { public JSONObject event(@RequestBody String s) throws Exception {
JSONObject reqJsonObject = JSON.parseObject(s); JSONObject reqJsonObject = JSON.parseObject(s);
System.out.println(s); System.out.println(s);
FeiShuEventDataDecrypter d = new FeiShuEventDataDecrypter(feiShuConfig.getAppConfigMap().get(feiShuConfig.getTestHelperApp()).getEncryptKey()); FeiShuEventDataDecrypter d = new FeiShuEventDataDecrypter(feiShuConfig.getEncryptKey());
JSONObject encryptJsonObject = JSON.parseObject(d.decrypt(reqJsonObject.getString("encrypt"))); JSONObject encryptJsonObject = JSON.parseObject(d.decrypt(reqJsonObject.getString("encrypt")));
System.out.println(encryptJsonObject); System.out.println(encryptJsonObject);
if (encryptJsonObject.containsKey("challenge")) { if (encryptJsonObject.containsKey("challenge")) {
return encryptJsonObject; return encryptJsonObject;
} }
FeiShuEventDTO feiShuEventDTO = encryptJsonObject.toJavaObject(FeiShuEventDTO.class); FeiShuEventDTO feiShuEventDTO = encryptJsonObject.toJavaObject(FeiShuEventDTO.class);
if (!feiShuEventDTO.getHeader().getToken().equalsIgnoreCase(feiShuConfig.getAppConfigMap().get(feiShuConfig.getTestHelperApp()).getVerificationToken())) { if (!feiShuEventDTO.getHeader().getToken().equalsIgnoreCase(feiShuConfig.getVerificationToken())) {
return null; return null;
} }
if ("im.message.receive_v1".equalsIgnoreCase(feiShuEventDTO.getHeader().getEvent_type())) { if ("im.message.receive_v1".equalsIgnoreCase(feiShuEventDTO.getHeader().getEvent_type())) {
......
package com.pipihelper.project.controller; package com.pipihelper.project.feishu.controller;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.pipihelper.project.core.Result; import com.pipihelper.project.core.Result;
import com.pipihelper.project.core.ResultGenerator; import com.pipihelper.project.core.ResultGenerator;
import com.pipihelper.project.feishu.dto.FeiShuConfig; import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.enums.SendMsgBusinessType;
import com.pipihelper.project.feishu.service.FeiShuApiService; import com.pipihelper.project.feishu.service.FeiShuApiService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
...@@ -25,6 +24,8 @@ public class SendMsgUseFeiShu { ...@@ -25,6 +24,8 @@ public class SendMsgUseFeiShu {
@Autowired @Autowired
private FeiShuConfig feiShuConfig; private FeiShuConfig feiShuConfig;
@PostMapping("/send-msg") @PostMapping("/send-msg")
public Result sendMsg(String receiveId, String msg, String receiveIdType){ public Result sendMsg(String receiveId, String msg, String receiveIdType){
JSONObject sendMsg = new JSONObject(); JSONObject sendMsg = new JSONObject();
...@@ -32,8 +33,9 @@ public class SendMsgUseFeiShu { ...@@ -32,8 +33,9 @@ public class SendMsgUseFeiShu {
sendMsg.put("msg_type", "text"); sendMsg.put("msg_type", "text");
JSONObject content = new JSONObject(); JSONObject content = new JSONObject();
content.put("text", msg); content.put("text", msg);
sendMsg.put("content", content.toString()); sendMsg.put("content", content.toString());
feiShuApiService.sendMsg(SendMsgBusinessType.TALK.getBusinessType(), receiveIdType, sendMsg, feiShuConfig.getTestHelperApp()); feiShuApiService.sendMsg(receiveIdType, sendMsg);
return ResultGenerator.genSuccessResult(); return ResultGenerator.genSuccessResult();
} }
} }
package com.pipihelper.project.feishu.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
public class AppConfig {
private String encryptKey;
private String verificationToken;
private String appId;
private String appSecret;
private String fkChatId;
private String fkChatIdTest;
private String tableId;
private String peopleTableId;
private String taskTableId;
}
...@@ -21,10 +21,16 @@ import java.util.Map; ...@@ -21,10 +21,16 @@ import java.util.Map;
public class FeiShuConfig { public class FeiShuConfig {
private String feiShuOpenApiHost; private String feiShuOpenApiHost;
private String testHelperApp; private String encryptKey;
private String anniversaryApp; private String verificationToken;
private String appId;
private String appSecret;
private String fkChatId;
private String fkChatIdTest;
private Map<String, AppConfig> appConfigMap; private String tableId;
private String peopleTableId;
private String taskTableId;
} }
package com.pipihelper.project.feishu.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
@Getter
@AllArgsConstructor
public enum CardElements {
APP_TYPE("appType","select_static","APP类型"),
MODULE("module","select_static","业务场景"),
LEVEL("level","select_static","优先级"),
ASSIGN("assign","select_person","指派处理人"),
VERIFY("verify","select_person","转发给其他值班人"),
HANDLE("handle","button","我来"),
FINISH_TIME("finishTime","date_picker","预计完成时间"),
FINISH("finish","button","完成"),
FILE_FINISH("fileFinish","overflow","完成|完成并归档");
// FILED("button","","","");
private String action;
private String tag;
private String msg;
}
package com.pipihelper.project.feishu.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ModuleType {
FRIENDS(1,"娱乐"),
PLAY(2,"游戏"),
MIDDLEWARE(3,"中台"),
OTHER(4,"其他"),
NONE(0,"未指定");
private Integer type;
private String msg;
public static Integer getTypeByMsg(String msg) {
for (ModuleType moduleType : ModuleType.values()) {
if (moduleType.getMsg().equals(msg)) {
return moduleType.getType();
}
}
return null;
}
public static String getMsgByType(Integer type) {
for (ModuleType moduleType : ModuleType.values()) {
if (moduleType.getType().equals(type)) {
return moduleType.getMsg();
}
}
return null;
}
}
package com.pipihelper.project.feishu.enums;
import com.pipihelper.project.core.ServiceException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Getter
@AllArgsConstructor
public enum MsgCard {
//CardElements.APP_TYPE, CardElements.MODULE, CardElements.LEVEL,CardElements.ASSIGN,CardElements.VERIFY, CardElements.HANDLE, CardElements.FINISH_TIME, CardElements.FINISH
TESTER_CARD_01("tester_0", Arrays.asList(CardElements.VERIFY, CardElements.HANDLE), "待值班确认", 1),
TESTER_CARD_02("tester_1", Arrays.asList(CardElements.LEVEL, CardElements.ASSIGN), "待值班指派", 1),
TESTER_CARD_03("tester_2", Arrays.asList(CardElements.FILE_FINISH), "负责人已完成待值班已确认", 1),//问题已完成,负责人未点完成,不允许测试点完成
TESTER_CARD_04("tester_3", Arrays.asList(CardElements.FINISH_TIME,CardElements.FILE_FINISH), "值班负责任务",4),//负责人是自己的时候,可以点击填写完成时间
TESTER_CARD_05("tester_4", new ArrayList<>(), "负责人已确认待解决",4),//开发确认后,测试侧卡片
CODER_CARD_01("coder_0", Arrays.asList(CardElements.ASSIGN, CardElements.HANDLE), "待负责人确认",1),
CODER_CARD_02("coder_1", Arrays.asList(CardElements.FINISH_TIME,CardElements.FINISH), "负责人已确认待解决",4),//负责人只能完成,不能归档
FILE("file", new ArrayList<>(), "卡片固化",null);
private String type;
private List<CardElements> elements;
private String msg;
private Integer interval;
public static List<CardElements> getElementsByType(String type) {
for (MsgCard msgCard : MsgCard.values()) {
if (msgCard.getType().equals(type)) {
return msgCard.getElements();
}
}
throw new ServiceException("类型不匹配");
}
public static Integer getIntervalByType(String type) {
for (MsgCard msgCard : MsgCard.values()) {
if (msgCard.getType().equals(type)) {
return msgCard.getInterval();
}
}
throw new ServiceException("类型不匹配");
}
}
package com.pipihelper.project.feishu.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @Description: TODO
* @author: charles
* @date: 2022年06月08日 14:21
*/
@Getter
@AllArgsConstructor
public enum NoticeType {
NONE(0,"未发送提醒"),
URGENT_APP(1,"app内加急"),
URGENT_SMS(2,"短信加急"),
URGENT_PHONE(3,"电话加急"),
URGENT_APP_24(4,"app内加急"),
URGENT_SMS_24(5,"短信加急"),
URGENT_PHONE_24(6,"电话加急");
private Integer type;
private String msg;
}
package com.pipihelper.project.feishu.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum SendMsgBusinessType {
/***
* 机器人发送消息的消息类型
*/
FEEDBACKS(0,"反馈群反馈问题"),
FEEDBACKS_DATA(1,""),
TALK(2,"一般性对话"),
DUTY_NOTICE(3, "值班提醒"),
HAR(4,"解析har文件"),
SYNC_DICT(5,"同步字典"),
TEST_DATA(6,"处理测试数据"),
DEFAULT(-1,"");
private Integer businessType;
private String description;
}
...@@ -64,16 +64,16 @@ public class FeiShuApiService { ...@@ -64,16 +64,16 @@ public class FeiShuApiService {
.expireAfterWrite(Duration.ofHours(2)) .expireAfterWrite(Duration.ofHours(2))
.build(); .build();
public String getTenantToken(String appName) { public String getTenantToken() {
return FEISHU_CACHE.get("tenantAccessToken" + appName, key -> setTenantAccessToken(appName)); return FEISHU_CACHE.get("tenantAccessToken", key -> setTenantAccessToken());
} }
public String setTenantAccessToken(String appName) { public String setTenantAccessToken() {
String api = "/auth/v3/tenant_access_token/internal"; String api = "/auth/v3/tenant_access_token/internal";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
JSONObject params = new JSONObject(); JSONObject params = new JSONObject();
params.put("app_id", feiShuConfig.getAppConfigMap().get(appName).getAppId()); params.put("app_id", feiShuConfig.getAppId());
params.put("app_secret", feiShuConfig.getAppConfigMap().get(appName).getAppSecret()); params.put("app_secret", feiShuConfig.getAppSecret());
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(feiShuConfig.getFeiShuOpenApiHost() + api, params, JSONObject.class); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(feiShuConfig.getFeiShuOpenApiHost() + api, params, JSONObject.class);
System.out.println(responseEntity.getBody().get("tenant_access_token").toString()); System.out.println(responseEntity.getBody().get("tenant_access_token").toString());
return responseEntity.getBody().get("tenant_access_token").toString(); return responseEntity.getBody().get("tenant_access_token").toString();
...@@ -84,14 +84,14 @@ public class FeiShuApiService { ...@@ -84,14 +84,14 @@ public class FeiShuApiService {
* @param sendMsg * @param sendMsg
* @return * @return
*/ */
public JSONObject sendMsg(Integer businessType, String receive_id_type, JSONObject sendMsg, String appName) { public JSONObject sendMsg( String receive_id_type, JSONObject sendMsg) {
System.out.println(sendMsg.toString()); System.out.println(sendMsg.toString());
//发送消息 //发送消息
String api = "/im/v1/messages?receive_id_type={receive_id_type}"; String api = "/im/v1/messages?receive_id_type={receive_id_type}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(sendMsg.toString(), headers); HttpEntity<String> requestEntity = new HttpEntity<>(sendMsg.toString(), headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -100,7 +100,7 @@ public class FeiShuApiService { ...@@ -100,7 +100,7 @@ public class FeiShuApiService {
if (responseEntity.getBody().getJSONObject("data") == null) { if (responseEntity.getBody().getJSONObject("data") == null) {
return null; return null;
} }
log.info("业务类型:{} ,消息发送成功,接收人: {}", businessType, sendMsg.getString("receive_id")); log.info("消息发送成功,接收人: {}", sendMsg.getString("receive_id"));
return responseEntity.getBody(); return responseEntity.getBody();
} catch (Exception e) { } catch (Exception e) {
log.error("飞书:" + api + "接口调用失败" + "\n" + e); log.error("飞书:" + api + "接口调用失败" + "\n" + e);
...@@ -111,12 +111,12 @@ public class FeiShuApiService { ...@@ -111,12 +111,12 @@ public class FeiShuApiService {
@Async @Async
public JSONObject replyMsg(String message_id, JSONObject replyMsg, String appName) { public JSONObject replyMsg(String message_id, JSONObject replyMsg) {
System.out.println(replyMsg.toString()); System.out.println(replyMsg.toString());
String api = "/im/v1/messages/{message_id}/reply"; String api = "/im/v1/messages/{message_id}/reply";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(replyMsg.toString(), headers); HttpEntity<String> requestEntity = new HttpEntity<>(replyMsg.toString(), headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -130,7 +130,7 @@ public class FeiShuApiService { ...@@ -130,7 +130,7 @@ public class FeiShuApiService {
} }
@Async @Async
public JSONObject patchMsg(String message_id, JSONObject content, String appName) { public JSONObject patchMsg(String message_id, JSONObject content) {
String api = "/im/v1/messages/"; String api = "/im/v1/messages/";
OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient();
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -138,7 +138,7 @@ public class FeiShuApiService { ...@@ -138,7 +138,7 @@ public class FeiShuApiService {
Request request = new Request.Builder() Request request = new Request.Builder()
.patch(requestBody) .patch(requestBody)
.url(url + message_id) .url(url + message_id)
.addHeader("Authorization", "Bearer " + getTenantToken(appName)) .addHeader("Authorization", "Bearer " + getTenantToken())
.addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("Content-Type", "application/json; charset=utf-8")
.build(); .build();
try { try {
...@@ -152,7 +152,7 @@ public class FeiShuApiService { ...@@ -152,7 +152,7 @@ public class FeiShuApiService {
} }
@Async @Async
public JSONObject patchUrgentApp(String message_id, JSONObject content, String appName) { public JSONObject patchUrgentApp(String message_id, JSONObject content) {
String api = "/im/v1/messages/" + message_id + "/urgent_sms?user_id_type=open_id"; String api = "/im/v1/messages/" + message_id + "/urgent_sms?user_id_type=open_id";
OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient();
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -160,7 +160,7 @@ public class FeiShuApiService { ...@@ -160,7 +160,7 @@ public class FeiShuApiService {
Request request = new Request.Builder() Request request = new Request.Builder()
.patch(requestBody) .patch(requestBody)
.url(url) .url(url)
.addHeader("Authorization", "Bearer " + getTenantToken(appName)) .addHeader("Authorization", "Bearer " + getTenantToken())
.addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("Content-Type", "application/json; charset=utf-8")
.build(); .build();
try { try {
...@@ -176,7 +176,7 @@ public class FeiShuApiService { ...@@ -176,7 +176,7 @@ public class FeiShuApiService {
@Async @Async
public JSONObject patchUrgentSms(String message_id, JSONObject content, String appName) { public JSONObject patchUrgentSms(String message_id, JSONObject content) {
String api = "/im/v1/messages/" + message_id + "/urgent_app?user_id_type=open_id"; String api = "/im/v1/messages/" + message_id + "/urgent_app?user_id_type=open_id";
OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient();
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -184,7 +184,7 @@ public class FeiShuApiService { ...@@ -184,7 +184,7 @@ public class FeiShuApiService {
Request request = new Request.Builder() Request request = new Request.Builder()
.patch(requestBody) .patch(requestBody)
.url(url) .url(url)
.addHeader("Authorization", "Bearer " + getTenantToken(appName)) .addHeader("Authorization", "Bearer " + getTenantToken())
.addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("Content-Type", "application/json; charset=utf-8")
.build(); .build();
try { try {
...@@ -200,12 +200,12 @@ public class FeiShuApiService { ...@@ -200,12 +200,12 @@ public class FeiShuApiService {
// @Async // @Async
public String createTask(FeiShuCreateTaskDTO taskMsg, String openId, String appName) { public String createTask(FeiShuCreateTaskDTO taskMsg, String openId) {
log.info("调用创建任务接口,task: {}", taskMsg.toString()); log.info("调用创建任务接口,task: {}", taskMsg.toString());
String api = "/task/v1/tasks"; String api = "/task/v1/tasks";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
// headers.set("Authorization", "Bearer " + "t-d3db00058d854b3c004ffdf6453fd3e169c82043"); // headers.set("Authorization", "Bearer " + "t-d3db00058d854b3c004ffdf6453fd3e169c82043");
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
...@@ -215,7 +215,7 @@ public class FeiShuApiService { ...@@ -215,7 +215,7 @@ public class FeiShuApiService {
try { try {
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
String taskId = responseEntity.getBody().getJSONObject("data").getJSONObject("task").getString("id"); String taskId = responseEntity.getBody().getJSONObject("data").getJSONObject("task").getString("id");
collaborators(taskId, openId, appName); collaborators(taskId, openId);
return taskId; return taskId;
} catch (Exception e) { } catch (Exception e) {
throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e); throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
...@@ -223,7 +223,7 @@ public class FeiShuApiService { ...@@ -223,7 +223,7 @@ public class FeiShuApiService {
} }
public JSONObject collaborators(String taskId, String openId, String appName) { public JSONObject collaborators(String taskId, String openId) {
if (StringUtils.isBlank(openId)) { if (StringUtils.isBlank(openId)) {
return null; return null;
} }
...@@ -232,7 +232,7 @@ public class FeiShuApiService { ...@@ -232,7 +232,7 @@ public class FeiShuApiService {
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("id", openId); param.put("id", openId);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(param.toString(), headers); HttpEntity<String> requestEntity = new HttpEntity<>(param.toString(), headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -245,11 +245,11 @@ public class FeiShuApiService { ...@@ -245,11 +245,11 @@ public class FeiShuApiService {
} }
public byte[] getMessageFile(String messageId, String fileKey, String type, String appName) { public byte[] getMessageFile(String messageId, String fileKey, String type) {
String api = "/im/v1/messages/{messageId}/resources/{fileKey}/?type={type}"; String api = "/im/v1/messages/{messageId}/resources/{fileKey}/?type={type}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(headers); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
try { try {
...@@ -261,11 +261,11 @@ public class FeiShuApiService { ...@@ -261,11 +261,11 @@ public class FeiShuApiService {
} }
//获取指定部门下的员工信息 //获取指定部门下的员工信息
public JSONObject getUser(String department_id, String appName) { public JSONObject getUser(String department_id) {
String api = "/contact/v3/users/find_by_department?department_id={department_id}"; String api = "/contact/v3/users/find_by_department?department_id={department_id}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -278,11 +278,11 @@ public class FeiShuApiService { ...@@ -278,11 +278,11 @@ public class FeiShuApiService {
} }
//下载文件 //下载文件
public byte[] downloadFile(String filePath, String appName) { public byte[] downloadFile(String filePath) {
String api = "/im/v1/files/{filePath}"; String api = "/im/v1/files/{filePath}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
try { try {
...@@ -294,11 +294,11 @@ public class FeiShuApiService { ...@@ -294,11 +294,11 @@ public class FeiShuApiService {
} }
//上传文件 //上传文件
public String uploadFile(String file_type, String file_name, Integer duration, byte[] file, String appName) { public String uploadFile(String file_type, String file_name, Integer duration, byte[] file) {
String api = "/im/v1/files"; String api = "/im/v1/files";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA); headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file_type", file_type); param.add("file_type", file_type);
...@@ -316,11 +316,11 @@ public class FeiShuApiService { ...@@ -316,11 +316,11 @@ public class FeiShuApiService {
} }
//获取应用有权限的所有部门 //获取应用有权限的所有部门
public JSONObject getDepartment(String appName) { public JSONObject getDepartment() {
String api = "/contact/v3/departments?fetch_child=true"; String api = "/contact/v3/departments?fetch_child=true";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -338,15 +338,15 @@ public class FeiShuApiService { ...@@ -338,15 +338,15 @@ public class FeiShuApiService {
* *
* @return * @return
*/ */
public List<FeiShuEmployeeDTO> getEmployeeList(String appName) { public List<FeiShuEmployeeDTO> getEmployeeList() {
return EMPLOYEE_LIST_CACHE.get("employeeList", s -> setEmployeeList(appName)); return EMPLOYEE_LIST_CACHE.get("employeeList", s -> setEmployeeList());
} }
private List<FeiShuEmployeeDTO> setEmployeeList(String appName) { private List<FeiShuEmployeeDTO> setEmployeeList() {
String api = "/ehr/v1/employees?view=full&status=2&status=4&page_size=100"; String api = "/ehr/v1/employees?view=full&status=2&status=4&page_size=100";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -375,11 +375,11 @@ public class FeiShuApiService { ...@@ -375,11 +375,11 @@ public class FeiShuApiService {
* *
* @return * @return
*/ */
public List<FeiShuChatDTO> getChatList(String appName) { public List<FeiShuChatDTO> getChatList() {
String api = "/im/v1/chats"; String api = "/im/v1/chats";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -399,12 +399,12 @@ public class FeiShuApiService { ...@@ -399,12 +399,12 @@ public class FeiShuApiService {
* 群发消息 * 群发消息
* https://open.feishu.cn/document/ukTMukTMukTM/ucDO1EjL3gTNx4yN4UTM * https://open.feishu.cn/document/ukTMukTMukTM/ucDO1EjL3gTNx4yN4UTM
*/ */
public void sendBatchMsg(FeiShuBatchMsgDTO feiShuBatchMsgDTO, String appName) { public void sendBatchMsg(FeiShuBatchMsgDTO feiShuBatchMsgDTO) {
String api = "/message/v4/batch_send/"; String api = "/message/v4/batch_send/";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
try { try {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuBatchMsgDTO), headers); HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuBatchMsgDTO), headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -422,12 +422,12 @@ public class FeiShuApiService { ...@@ -422,12 +422,12 @@ public class FeiShuApiService {
* *
* @param feiShuMsgDTO * @param feiShuMsgDTO
*/ */
public void sendMsg(FeiShuMsgDTO feiShuMsgDTO, String receiveIdType, String appName) { public void sendMsg(FeiShuMsgDTO feiShuMsgDTO, String receiveIdType) {
String api = "/im/v1/messages?receive_id_type={receiveIdType}"; String api = "/im/v1/messages?receive_id_type={receiveIdType}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
try { try {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuMsgDTO), headers); HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuMsgDTO), headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -446,11 +446,11 @@ public class FeiShuApiService { ...@@ -446,11 +446,11 @@ public class FeiShuApiService {
* @param departmentId * @param departmentId
* @return * @return
*/ */
public FeiShuDepartmentDTO getDepartment(String departmentId, String appName) { public FeiShuDepartmentDTO getDepartment(String departmentId) {
String api = "/contact/v3/departments/{departmentId}"; String api = "/contact/v3/departments/{departmentId}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -471,14 +471,14 @@ public class FeiShuApiService { ...@@ -471,14 +471,14 @@ public class FeiShuApiService {
* *
* @param appToken * @param appToken
* @param tableId * @param tableId
* @param appName
* @return * @return
*/ */
public List getTableRecords(String appToken, String tableId, String appName) { public List getTableRecords(String appToken, String tableId) {
String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records"; String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers); HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api; String url = feiShuConfig.getFeiShuOpenApiHost() + api;
...@@ -508,15 +508,14 @@ public class FeiShuApiService { ...@@ -508,15 +508,14 @@ public class FeiShuApiService {
* @param appToken * @param appToken
* @param tableId * @param tableId
* @param recordId * @param recordId
* @param appName
* @param docDTO * @param docDTO
* @return * @return
*/ */
public FeiShuResultDTO updateTableRecords(String appToken, String tableId, String recordId, String appName, DocDTO docDTO) { public FeiShuResultDTO updateTableRecords(String appToken, String tableId, String recordId, DocDTO docDTO) {
String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records/{record_id}"; String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records/{record_id}";
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken(appName)); headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8"); headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(docDTO), headers); HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(docDTO), headers);
...@@ -530,4 +529,53 @@ public class FeiShuApiService { ...@@ -530,4 +529,53 @@ public class FeiShuApiService {
} }
} }
//获取主日历
public JSONObject calendars() {
//查询主日历,获取日历id
String api = "/calendar/v4/calendars/primary?user_id_type=open_id";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api;
try {
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
return responseEntity.getBody();
} catch (Exception e) {
log.error("飞书:" + api + "接口调用失败" + "\n" + e);
throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
}
}
//获取会议室列表
public List<FeiShuEmployeeDTO> getMeetingRooms() {
String api = "/ehr/v1/employees?view=full&status=2&status=4&page_size=100";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getTenantToken());
headers.set("Content-Type", "application/json; charset=utf-8");
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = feiShuConfig.getFeiShuOpenApiHost() + api;
try {
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
Type type = new TypeReference<FeiShuResultDTO<FeiShuEmployeeDTO>>() {
}.getType();
FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = new ArrayList<>();
feiShuEmployeeDTOList.addAll(feiShuResultDTO.getData().getItems());
while (feiShuResultDTO.getData().getItems().size() >= 100) {
ResponseEntity<String> next = restTemplate.exchange(url + "&page_token=" + feiShuResultDTO.getData().getPageToken(), HttpMethod.GET, requestEntity, String.class);
feiShuResultDTO = JSONObject.parseObject(next.getBody(), type);
feiShuEmployeeDTOList.addAll(feiShuResultDTO.getData().getItems());
}
log.info("花名册获取完成,总计 {} 人", feiShuEmployeeDTOList.size());
return feiShuEmployeeDTOList;
} catch (Exception e) {
throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
}
}
} }
...@@ -6,7 +6,6 @@ import com.pipihelper.project.feishu.dto.FeiShuEventHeaderDTO; ...@@ -6,7 +6,6 @@ import com.pipihelper.project.feishu.dto.FeiShuEventHeaderDTO;
import com.pipihelper.project.feishu.dto.FeiShuEventReceiveMessageDTO; import com.pipihelper.project.feishu.dto.FeiShuEventReceiveMessageDTO;
import com.pipihelper.project.tx.dto.TxConfig; import com.pipihelper.project.tx.dto.TxConfig;
import com.pipihelper.project.tx.service.TxApiService; import com.pipihelper.project.tx.service.TxApiService;
import com.pipitest.project.feishu.dto.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
...@@ -47,8 +46,8 @@ public class FeiShuEventService { ...@@ -47,8 +46,8 @@ public class FeiShuEventService {
FeiShuEventReceiveMessageDTO.Sender sender= feiShuEventReceiveMessageDTO.getSender(); FeiShuEventReceiveMessageDTO.Sender sender= feiShuEventReceiveMessageDTO.getSender();
FeiShuEventReceiveMessageDTO.Message message= feiShuEventReceiveMessageDTO.getMessage(); FeiShuEventReceiveMessageDTO.Message message= feiShuEventReceiveMessageDTO.getMessage();
//单独处理群消息 //单独处理群消息
if (message.getChat_id().equals(feiShuConfig.getAppConfigMap().get(feiShuConfig.getTestHelperApp()).getFkChatId()) if (message.getChat_id().equals(feiShuConfig.getFkChatId())
|| message.getChat_id().equals(feiShuConfig.getAppConfigMap().get(feiShuConfig.getTestHelperApp()).getFkChatIdTest())) { //判断是否为指定群消息 || message.getChat_id().equals(feiShuConfig.getFkChatIdTest())) { //判断是否为指定群消息
return; return;
} }
else { else {
......
package com.pipihelper.project.feishu.service.anniversary;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.department.FeiShuDepartmentDTO;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.dto.msg.FeiShuMsgDTO;
import com.pipihelper.project.feishu.service.FeiShuApiService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public abstract class AbstractNoticeService {
@Resource
private FeiShuConfig feiShuConfig;
@Autowired
private FeiShuApiService feiShuApiService;
/**
* 发送通知
*/
public abstract void notice();
/**
* 生成员工消息卡片
* @param feiShuEmployeeDTO
* @return
*/
public abstract FeiShuMsgDTO generateEmployeeMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO);
/**
* 生产领导消息卡片
* @param feiShuEmployeeDTO
* @return
*/
public abstract FeiShuMsgDTO generateLeaderMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO);
/**
* 获取领导OpenId
*
* @param departmentId
* @return
*/
public String getLeaderOpenId(String departmentId) {
if (StringUtils.isBlank(departmentId)) {
return "";
}
if ("0".equals(departmentId)) {
// 若递归无上级负责人,则获取企业创建人
return feiShuApiService.getUser("0", feiShuConfig.getAnniversaryApp()).getJSONObject("data").getJSONArray("items").getJSONObject(0).getString("open_id");
}
FeiShuDepartmentDTO feiShuDepartmentDTO = feiShuApiService.getDepartment(departmentId, feiShuConfig.getAnniversaryApp());
return StringUtils.isNotBlank(feiShuDepartmentDTO.getLeaderUserId()) ? feiShuDepartmentDTO.getLeaderUserId() : getLeaderOpenId(feiShuDepartmentDTO.getParentDepartmentId());
}
/**
* 给部门领导发送消息,若领导是自己,则找父部门领导
*
* @param feiShuMsgDTO
* @param feiShuEmployeeDTO
*/
public void sendMsgToLeader(FeiShuMsgDTO feiShuMsgDTO, FeiShuEmployeeDTO feiShuEmployeeDTO) {
String leaderOpenId = getLeaderOpenId(feiShuEmployeeDTO.getSystemFields().getDepartmentId());
// 领导是自己,找父部门领导
if (leaderOpenId.equals(feiShuEmployeeDTO.getUserId()) && !"0".equals(feiShuEmployeeDTO.getSystemFields().getDepartmentId())) {
leaderOpenId = getLeaderOpenId(feiShuApiService.getDepartment(feiShuEmployeeDTO.getSystemFields().getDepartmentId(), feiShuConfig.getAnniversaryApp()).getParentDepartmentId());
}
if (!leaderOpenId.equals(feiShuEmployeeDTO.getUserId()) && StringUtils.isNotBlank(leaderOpenId)) {
// 给领导发送消息
feiShuMsgDTO.setReceiveId(leaderOpenId);
feiShuApiService.sendMsg(feiShuMsgDTO, "open_id", feiShuConfig.getAnniversaryApp());
}
}
/**
* 读取模板文件
* @param file
* @return
*/
public String getInteractiveCardStr(String file){
try {
InputStream in = this.getClass().getResourceAsStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(in);
Stream<String> streamOfString= new BufferedReader(inputStreamReader).lines();
String streamToString = streamOfString.collect(Collectors.joining());
return streamToString;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
package com.pipihelper.project.feishu.service.anniversary;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.dto.msg.FeiShuMsgDTO;
import com.pipihelper.project.feishu.service.FeiShuApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 飞书入职周年提醒
*/
@Service
@Slf4j
public class AnniversaryNoticeService extends AbstractNoticeService{
@Autowired
private FeiShuApiService feiShuApiService;
@Resource
private FeiShuConfig feiShuConfig;
@Override
public void notice() {
// 1. 获取当天生日人
List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = feiShuApiService.getEmployeeList(feiShuConfig.getAnniversaryApp());
List<FeiShuEmployeeDTO> hireDayEmployees = feiShuEmployeeDTOList.stream()
.filter(feiShuEmployeeDTO -> StringUtils.isNotEmpty(feiShuEmployeeDTO.getSystemFields().getHireDate()))
.filter(feiShuEmployeeDTO -> {
LocalDate hireDay = LocalDate.parse(feiShuEmployeeDTO.getSystemFields().getHireDate());
// 使用plusYears可以避免2月29日的特殊情况.当年若无2月29日,生日则为2月28日
long years = LocalDate.now().getYear() - hireDay.getYear();
// 1,2,3,5周年时发送提醒
return hireDay.plusYears(years).equals(LocalDate.now()) && (years == 1 || years == 2 || years == 3 || years == 5);
})
.peek(feiShuEmployeeDTO -> {
// 给员工自己发消息
feiShuApiService.sendMsg(generateEmployeeMsgCard(feiShuEmployeeDTO), "open_id",feiShuConfig.getAnniversaryApp());
// 给领导发送消息
sendMsgToLeader(generateLeaderMsgCard(feiShuEmployeeDTO),feiShuEmployeeDTO);
}).collect(Collectors.toList());
log.info("{} 当日周年人: {}", LocalDate.now(), hireDayEmployees);
}
@Override
public FeiShuMsgDTO generateEmployeeMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO) {
LocalDate hireDay = LocalDate.parse(feiShuEmployeeDTO.getSystemFields().getHireDate());
long years = LocalDate.now().getYear() - hireDay.getYear();
String fileName = String.format("/templates/anniversary-employee-%s.json", years);
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr(fileName), feiShuEmployeeDTO.getSystemFields().getName()));
feiShuMsgDTO.setReceiveId(feiShuEmployeeDTO.getUserId());
return feiShuMsgDTO;
}
@Override
public FeiShuMsgDTO generateLeaderMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO) {
LocalDate hireDay = LocalDate.parse(feiShuEmployeeDTO.getSystemFields().getHireDate());
long years = LocalDate.now().getYear() - hireDay.getYear();
String fileName = String.format("/templates/anniversary-leader-%s.json", String.valueOf(years));
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr(fileName), feiShuEmployeeDTO.getSystemFields().getName()));
return feiShuMsgDTO;
}
}
package com.pipihelper.project.feishu.service.anniversary;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.msg.FeiShuMsgDTO;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.service.FeiShuApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 飞书生日提醒
*/
@Service
@Slf4j
public class BirthdayNoticeService extends AbstractNoticeService {
@Autowired
private FeiShuApiService feiShuApiService;
@Resource
private FeiShuConfig feiShuConfig;
@Override
public void notice() {
// 1. 获取当天生日人
List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = feiShuApiService.getEmployeeList(feiShuConfig.getAnniversaryApp());
List<FeiShuEmployeeDTO> birthdayEmployees = feiShuEmployeeDTOList.stream()
.filter(feiShuEmployeeDTO -> StringUtils.isNotEmpty(feiShuEmployeeDTO.getSystemFields().getBirthday()))
.filter(feiShuEmployeeDTO -> {
LocalDate birthday = LocalDate.parse(feiShuEmployeeDTO.getSystemFields().getBirthday());
// 使用plusYears可以避免2月29日的特殊情况.当年若无2月29日,生日则为2月28日
long years = LocalDate.now().getYear() - birthday.getYear();
return birthday.plusYears(years).equals(LocalDate.now());
})
.map(feiShuEmployeeDTO -> {
// 给员工自己发消息
feiShuApiService.sendMsg(generateEmployeeMsgCard(feiShuEmployeeDTO), "open_id", feiShuConfig.getAnniversaryApp());
// 给领导发送消息
sendMsgToLeader(generateLeaderMsgCard(feiShuEmployeeDTO), feiShuEmployeeDTO);
return feiShuEmployeeDTO;
}).collect(Collectors.toList());
log.info("{} 当日生日人: {}", LocalDate.now(), birthdayEmployees);
}
@Override
public FeiShuMsgDTO generateEmployeeMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO) {
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr("/templates/birthday-employee.json"), feiShuEmployeeDTO.getSystemFields().getName()));
feiShuMsgDTO.setReceiveId(feiShuEmployeeDTO.getUserId());
return feiShuMsgDTO;
}
@Override
public FeiShuMsgDTO generateLeaderMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO) {
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr("/templates/birthday-leader.json"), feiShuEmployeeDTO.getSystemFields().getName()));
return feiShuMsgDTO;
}
}
package com.pipihelper.project.feishu.service.anniversary;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.msg.FeiShuMsgDTO;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.service.FeiShuApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 飞书转正日提醒
*/
@Service
@Slf4j
public class ConversionNoticeService extends AbstractNoticeService{
@Autowired
private FeiShuApiService feiShuApiService;
@Resource
private FeiShuConfig feiShuConfig;
/**
* 逻辑来自HR
* 转正日为入职日过6个月
* 一般是入职是X月Y日,那么6个月是到X+6月Y-1日到期,第二天的X+6月Y日是转正的第一天了
* 特殊情况就是有一些月份的30日 31日入职,那么转正月份因为当月最后1天不是30号或者31号,那么我们就按照当月的最后1天作为转正日
* 最典型的就是8月31日入职,转正日期可能是2月28日,也可能是2月29日
* 或者12月31日入职,那么转正日期是6月30日(因为6月没有31号);但是1月31日入职,转正日期就是7月31日(因为7月最后1天就是31号)
*/
@Override
public void notice() {
// 1. 获取当天生日人
List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = feiShuApiService.getEmployeeList(feiShuConfig.getAnniversaryApp());
List<FeiShuEmployeeDTO> hireDayEmployees = feiShuEmployeeDTOList.stream()
.filter(feiShuEmployeeDTO -> StringUtils.isNotEmpty(feiShuEmployeeDTO.getSystemFields().getHireDate()))
.filter(feiShuEmployeeDTO -> {
LocalDate hireDay = LocalDate.parse(feiShuEmployeeDTO.getSystemFields().getHireDate());
// 使用plusMonths正好满足需求
return hireDay.plusMonths(6L).equals(LocalDate.now());
})
.map(feiShuEmployeeDTO -> {
// 给员工自己发消息
feiShuApiService.sendMsg(generateEmployeeMsgCard(feiShuEmployeeDTO), "open_id",feiShuConfig.getAnniversaryApp());
// 给领导发送消息
sendMsgToLeader(generateLeaderMsgCard(feiShuEmployeeDTO),feiShuEmployeeDTO);
return feiShuEmployeeDTO;
}).collect(Collectors.toList());
log.info("{} 当日转正人: {}", LocalDate.now(), hireDayEmployees);
}
@Override
public FeiShuMsgDTO generateEmployeeMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO){
String name = feiShuEmployeeDTO.getSystemFields().getName();
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr("/templates/conversion-employee.json"), name, name));
feiShuMsgDTO.setReceiveId(feiShuEmployeeDTO.getUserId());
return feiShuMsgDTO;
}
@Override
public FeiShuMsgDTO generateLeaderMsgCard(FeiShuEmployeeDTO feiShuEmployeeDTO) {
FeiShuMsgDTO feiShuMsgDTO = new FeiShuMsgDTO();
feiShuMsgDTO.setMsgType("interactive");
feiShuMsgDTO.setContent(String.format(getInteractiveCardStr("/templates/conversion-leader.json"), feiShuEmployeeDTO.getSystemFields().getName()));
return feiShuMsgDTO;
}
}
package com.pipihelper.project.feishu.service.doc;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.pipihelper.project.feishu.dto.AppConfig;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.FeiShuCreateTaskDTO;
import com.pipihelper.project.feishu.dto.doc.DocDTO;
import com.pipihelper.project.feishu.dto.doc.FieldsDTO;
import com.pipihelper.project.feishu.dto.doc.PeopleDTO;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.dto.msg.ContentDTO;
import com.pipihelper.project.feishu.dto.msg.FeiShuBatchMsgDTO;
import com.pipihelper.project.feishu.service.FeiShuApiService;
import com.pipihelper.project.feishu.vo.CreateTaskVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @author xiongjian
* @date 2022/7/4
*/
@Service
@Slf4j
public class DocHelperService {
@Autowired
private FeiShuApiService feiShuApiService;
@Resource
private FeiShuConfig feiShuConfig;
private final Cache<String, Map<String, String>> NAME_CACHE = Caffeine.newBuilder()
.maximumSize(5)
.expireAfterWrite(Duration.ofHours(2))
.build();
private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private Map<String, String> getNameMap() {
return NAME_CACHE.get("nameMap", map -> {
List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = feiShuApiService.getEmployeeList(feiShuConfig.getAnniversaryApp());
HashMap<String, String> nameMap = new HashMap<>(feiShuEmployeeDTOList.size());
for (FeiShuEmployeeDTO feiShuEmployeeDTO : feiShuEmployeeDTOList) {
String key = feiShuEmployeeDTO.getSystemFields().getName();
nameMap.put(key, feiShuEmployeeDTO.getUserId());
}
log.info("重建姓名-Id缓存, size: {}", nameMap.size());
return nameMap;
});
}
/**
* 人员转换器
*/
public void transferPeople() {
String app = feiShuConfig.getAnniversaryApp();
AppConfig appConfig = feiShuConfig.getAppConfigMap().get(app);
List<DocDTO> docList = feiShuApiService.getTableRecords(appConfig.getTableId(), appConfig.getPeopleTableId(), app);
for (DocDTO<FieldsDTO> docDTO : docList) {
if (Objects.isNull(docDTO.getFields().getName())) {
continue;
}
if (getNameMap().containsKey(docDTO.getFields().getName()) && CollectionUtils.isEmpty(docDTO.getFields().getPeople())) {
List<PeopleDTO> list = new ArrayList<>();
list.add(new PeopleDTO(getNameMap().get(docDTO.getFields().getName())));
docDTO.getFields().setPeople(list);
docDTO.getFields().setUserId(getNameMap().get(docDTO.getFields().getName()));
docDTO.getFields().setUpdateTime(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
docDTO.getFields().setToken("Bearer " + feiShuApiService.getTenantToken(app));
feiShuApiService.updateTableRecords(appConfig.getTableId(), appConfig.getPeopleTableId(), docDTO.getRecordId(), app, docDTO);
}
}
}
/**
* 通过表格创建任务
*/
public void createTaskByTable() {
String app = feiShuConfig.getAnniversaryApp();
AppConfig appConfig = feiShuConfig.getAppConfigMap().get(app);
List<DocDTO> docList = feiShuApiService.getTableRecords(appConfig.getTableId(), appConfig.getTaskTableId(), app);
for (DocDTO<FieldsDTO> docDTO : docList) {
if (docDTO.getFields() == null) {
continue;
}
if (StringUtils.isBlank(docDTO.getFields().getTaskName())) {
continue;
}
if (!"待创建".equals(docDTO.getFields().getStatues())) {
continue;
}
if (StringUtils.isBlank(docDTO.getFields().getCollaborators())) {
continue;
}
// 创建任务
FeiShuCreateTaskDTO feiShuCreateTaskDTO = new FeiShuCreateTaskDTO();
feiShuCreateTaskDTO.setSummary(docDTO.getFields().getTaskName());
feiShuCreateTaskDTO.setDescription(docDTO.getFields().getTaskDescription());
FeiShuCreateTaskDTO.Due due = new FeiShuCreateTaskDTO.Due();
if (docDTO.getFields().getDue() != null) {
due.setTime(String.valueOf(docDTO.getFields().getDue()).substring(0, 10));
}
feiShuCreateTaskDTO.setDue(due);
FeiShuCreateTaskDTO.OriginDTO originDTO = new FeiShuCreateTaskDTO.OriginDTO();
originDTO.setPlatformI18nName(String.format("{\"zh_cn\": \"%s\"}", docDTO.getFields().getOrigin()));
feiShuCreateTaskDTO.setOrigin(originDTO);
// 执行者
String[] collaborators = docDTO.getFields().getCollaborators().split(",|,");
List<String> collaboratorIds = new ArrayList<>();
for (String collaborator : collaborators) {
if (getNameMap().containsKey(collaborator)) {
collaboratorIds.add(getNameMap().get(collaborator));
}
}
feiShuCreateTaskDTO.setCollaboratorIds(collaboratorIds);
// 关注者
if (docDTO.getFields().getFollowers() != null) {
String[] followers = docDTO.getFields().getFollowers().split(",|,");
List<String> followerIds = new ArrayList<>();
for (String follower : followers) {
if (getNameMap().containsKey(follower)) {
followerIds.add(getNameMap().get(follower));
}
}
feiShuCreateTaskDTO.setFollowerIds(followerIds);
}
try {
// 创建任务
feiShuApiService.createTask(feiShuCreateTaskDTO, null, app);
// 发送消息
sendMsg(docDTO);
docDTO.getFields().setNote("成功");
} catch (Exception e) {
docDTO.getFields().setNote(e.getMessage());
} finally {
docDTO.getFields().setStatues("已创建");
docDTO.getFields().setUpdateTime(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
// 更新数据表
feiShuApiService.updateTableRecords(appConfig.getTableId(), appConfig.getTaskTableId(), docDTO.getRecordId(), app, docDTO);
}
}
}
public void createTask(CreateTaskVo createTaskVo) {
String app = feiShuConfig.getAnniversaryApp();
// 创建任务
FeiShuCreateTaskDTO feiShuCreateTaskDTO = new FeiShuCreateTaskDTO();
feiShuCreateTaskDTO.setSummary(createTaskVo.getSummary());
feiShuCreateTaskDTO.setDescription(createTaskVo.getDescription());
FeiShuCreateTaskDTO.Due due = new FeiShuCreateTaskDTO.Due();
ZoneId zone = ZoneId.systemDefault();
if (StringUtils.isNotBlank(createTaskVo.getDueTime())) {
// 截止时间有值按填值截止
Long time = LocalDateTime.parse(createTaskVo.getDueTime(), DATE_TIME_FORMATTER).atZone(zone).toInstant().getEpochSecond();
due.setTime(String.valueOf(time));
} else {
// 截止时间无值,按当天18点+偏移量截止
LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(18, 0)).plusHours(createTaskVo.getDueTimeOffset());
Long time = dateTime.atZone(zone).toInstant().getEpochSecond();
due.setTime(String.valueOf(time));
}
feiShuCreateTaskDTO.setDue(due);
FeiShuCreateTaskDTO.OriginDTO originDTO = new FeiShuCreateTaskDTO.OriginDTO();
originDTO.setPlatformI18nName(String.format("{\"zh_cn\": \"%s\"}", app));
feiShuCreateTaskDTO.setOrigin(originDTO);
// 执行者
if (StringUtils.isNotBlank(createTaskVo.getCollaboratorIds())){
List<String> collaboratorIds = new ArrayList<>();
for (String name : getNameMap().keySet()) {
if (createTaskVo.getCollaboratorIds().contains(name)){
collaboratorIds.add(getNameMap().get(name));
}
}
feiShuCreateTaskDTO.setCollaboratorIds(collaboratorIds);
}
// 关注者
if (StringUtils.isNotBlank(createTaskVo.getFollowerIds())){
List<String> followersIds = new ArrayList<>();
for (String name : getNameMap().keySet()) {
if (createTaskVo.getFollowerIds().contains(name)){
followersIds.add(getNameMap().get(name));
}
}
feiShuCreateTaskDTO.setFollowerIds(followersIds);
}
// 创建任务
feiShuApiService.createTask(feiShuCreateTaskDTO, null, app);
}
public void sendMsg(DocDTO<FieldsDTO> docDTO) {
if (StringUtils.isBlank(docDTO.getFields().getMsg())) {
return;
}
if (StringUtils.isBlank(docDTO.getFields().getReceiverIds())) {
return;
}
FeiShuBatchMsgDTO feiShuBatchMsgDTO = new FeiShuBatchMsgDTO();
feiShuBatchMsgDTO.setMsgType("text");
feiShuBatchMsgDTO.setContent(new ContentDTO(docDTO.getFields().getMsg()));
String[] receivers = docDTO.getFields().getReceiverIds().split(",|,");
List<String> receiverIds = new ArrayList<>();
for (String receiver : receivers) {
if (getNameMap().containsKey(receiver)) {
receiverIds.add(getNameMap().get(receiver));
}
}
feiShuBatchMsgDTO.setOpenIds(receiverIds);
// 发送消息
feiShuApiService.sendBatchMsg(feiShuBatchMsgDTO, feiShuConfig.getAnniversaryApp());
}
}
package com.pipihelper.project.interceptor;
import com.pipihelper.project.core.Result;
import com.pipihelper.project.core.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 白名单拦截器,用于控制允许访问的请求
*
* @author zlikun
* @date 2021/10/21 14:39
*/
@Slf4j
@Component
@Aspect
public class ResponseAop {
//这里改成自己项目的控制层路径
@Pointcut("execution(public * com.pipihelper.project.controller..*(..))")
public void httpResponse() {
}
//环切
@Around("httpResponse()")
public Result handlerController(ProceedingJoinPoint proceedingJoinPoint) {
Result result = new Result();
try {
//获取方法的执行结果
Object proceed = proceedingJoinPoint.proceed();
//如果方法的执行结果是Result,则将该对象直接返回
if (proceed instanceof Result) {
result = (Result) proceed;
} else {
//否则,就要封装到Result的data中
result.setData(proceed);
}
} catch (Throwable throwable) {
//如果出现了异常,调用异常处理方法将错误信息封装到Result中并返回
result = handlerException(throwable);
}
return result;
}
//异常处理
private Result handlerException(Throwable throwable) {
Result result = new Result();
//这里需要注意,返回枚举类中的枚举在写的时候应该和异常的名称相对应,以便动态的获取异常代码和异常信息,我这边是统一返回500,msg存报的异常
//获取异常名称的方法
String errorName = throwable.toString();
errorName = errorName.substring(errorName.lastIndexOf(".") + 1);
result.setMessage(errorName);
result.setCode(ResultCode.INTERNAL_SERVER_ERROR);
return result;
}
}
package com.pipihelper.project.rostering.model;
import lombok.Data;
import java.util.Date;
/**
* 指定日期内出现X个N班次
* (x=数字 n=班次名称)
* @description: 时间规则配置
* @author: zsw
* @create: 2022-10-14 18:48
**/
@Data
public class DateRuleModel {
/**
*
*/
private Date date;
private String shift;
private Integer times;
}
package com.pipihelper.project.rostering.model;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* 班次规则
* @description:
* @author: zsw
* @create: 2022-10-14 16:52
**/
@Data
public class ShiftRuleModel {
/**
* 班次名称
*/
private String name;
/**
* 每天每班次出现的人数
*/
private Integer everyDay;
/**
* 班次前允许
*/
private List<String> frontAllow;
/**
* 班次前不允许
*/
private List<String> frontDenied;
/**
* 班次后允许
*/
private List<String> backAllow;
/**
* 班次后不允许
*/
private List<String> backDenied;
/**
* 班次最大连续次数
*/
private Integer maxContinuity;
/**
* 班次最大次数后指定班次
*/
private String maxContinuityFollow;
//{"backAllow":["早班"],"backDenied":["晚班"],"everyDay":5,"frontAllow":["早班"],"frontDenied":["晚班"],"maxContinuity":5,"maxContinuityFollow":"休息","name":"早班"}
public static void main(String[] args) {
ShiftRuleModel shiftRuleModel = new ShiftRuleModel();
shiftRuleModel.setName("早班");
shiftRuleModel.setEveryDay(5);
shiftRuleModel.setFrontAllow(Lists.newArrayList("早班"));
shiftRuleModel.setFrontDenied(Lists.newArrayList("晚班"));
shiftRuleModel.setBackAllow(Lists.newArrayList("早班"));
shiftRuleModel.setBackDenied(Lists.newArrayList("晚班"));
shiftRuleModel.setMaxContinuity(5);
shiftRuleModel.setMaxContinuityFollow("休息");
String s = JSONObject.toJSONString(shiftRuleModel);
System.out.println(s);
}
}
package com.pipihelper.project.rostering.model;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;
import java.util.Date;
/**
* @description: 人员配置
* @author: zsw
* @create: 2022-10-14 18:10
**/
@Data
public class StaffRuleModel {
/**
* 班次名称
*/
private String name;
/**
* 当月班次最大出现次数
*/
private Threshold maxTimes;
/**
* 当月班次最小出现次数
*/
private Threshold minTimes;
/**
* 指定班次
*/
private Threshold fixedShift;
@Data
public static class Threshold {
/**
* 班次
*/
private String shift;
/**
* 次数
*/
private Integer times;
/**
* 日期
*/
private Date date;
}
//{"fixedShift":{"date":"2022-10-14 00:00:00","shift":"AAAA"},"maxTimes":{"shift":"AAA","times":5},"minTimes":{"shift":"AAA","times":5},"name":"xxxx"}
public static void main(String[] args) {
StaffRuleModel staffRuleModel = new StaffRuleModel();
staffRuleModel.setName("xxxx");
Threshold maxTimes = new Threshold();
maxTimes.setShift("AAA");
maxTimes.setTimes(5);
Threshold minTimes = new Threshold();
minTimes.setShift("AAA");
minTimes.setTimes(5);
Threshold fixedShift = new Threshold();
fixedShift.setDate(DateUtil.parse("2022-10-14 00:00:00"));
fixedShift.setShift("AAAA");
staffRuleModel.setMaxTimes(maxTimes);
staffRuleModel.setMinTimes(minTimes);
staffRuleModel.setFixedShift(fixedShift);
String s = JSONObject.toJSONString(staffRuleModel, SerializerFeature.WriteDateUseDateFormat);
System.out.println(s);
}
}
package com.pipihelper.project.rostering.service; package com.pipihelper.project.rostering.service;
import com.pipihelper.project.rostering.model.DateRuleModel;
import com.pipihelper.project.rostering.model.StaffRuleModel;
import com.pipihelper.project.rostering.model.RosteringModel;
import com.pipihelper.project.rostering.model.ShiftRuleModel;
import java.util.List;
/** /**
* @description: * @description:
* @author: zsw * @author: zsw
...@@ -7,5 +14,20 @@ package com.pipihelper.project.rostering.service; ...@@ -7,5 +14,20 @@ package com.pipihelper.project.rostering.service;
**/ **/
public interface RosteringService { public interface RosteringService {
/**
* 生成班次
* @param staffs 人员
* @param shifts 班次
* @param shiftRuleModels 班次规则
* @param staffRuleModels 原因规则
* @param dateRuleModels 时间规则
* @return
*/
List<RosteringModel> gen(List<String> staffs,
List<String> shifts,
List<ShiftRuleModel> shiftRuleModels,
List<StaffRuleModel> staffRuleModels,
List<DateRuleModel> dateRuleModels);
} }
package com.pipihelper.project.rostering.service.impl; package com.pipihelper.project.rostering.service.impl;
import com.pipihelper.project.rostering.model.DateRuleModel;
import com.pipihelper.project.rostering.model.RosteringModel;
import com.pipihelper.project.rostering.model.ShiftRuleModel;
import com.pipihelper.project.rostering.model.StaffRuleModel;
import com.pipihelper.project.rostering.service.RosteringService; import com.pipihelper.project.rostering.service.RosteringService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
/** /**
* @description: * @description:
* @author: zsw * @author: zsw
...@@ -10,4 +16,40 @@ import org.springframework.stereotype.Service; ...@@ -10,4 +16,40 @@ import org.springframework.stereotype.Service;
**/ **/
@Service @Service
public class RosteringServiceImpl implements RosteringService { public class RosteringServiceImpl implements RosteringService {
@Override
public List<RosteringModel> gen(List<String> staffs,
List<String> shifts,
List<ShiftRuleModel> shiftRuleModels,
List<StaffRuleModel> staffRuleModels,
List<DateRuleModel> dateRuleModels) {
//校验
verify(staffs, shifts, shiftRuleModels, staffRuleModels);
return null;
}
private void verify(List<String> staffs,
List<String> shifts,
List<ShiftRuleModel> shiftRuleModels,
List<StaffRuleModel> staffRuleModels) {
if (shiftRuleModels.stream().noneMatch(e -> shifts.contains(e.getName()))) {
throw new RuntimeException("班次配置不合法");
}
if (staffRuleModels.stream().noneMatch(e -> staffs.contains(e.getName()))) {
throw new RuntimeException("员工配置不合法");
}
}
} }
...@@ -11,16 +11,11 @@ spring: ...@@ -11,16 +11,11 @@ spring:
# 飞书相关配置参数 # 飞书相关配置参数
feishu: feishu:
feiShuOpenApiHost: https://open.feishu.cn/open-apis feiShuOpenApiHost: https://open.feishu.cn/open-apis
testHelperApp: testHelperApp encryptKey: aGTqmJcfXluKWfFWHGw5SdzIg6QIxPsp
anniversaryApp: anniversaryApp verificationToken: ChUEDdWQbyHpHUV6H5fVeL5fOP3HfBE6
appId: cli_a2cff17bd3f8d013
# 测试小助手配置 appSecret: E5vXXmRipOD6vyolib186b25XXLbdYfE
appConfigMap[testHelperApp]: fkChatId: oc_5124ee21dbdecf5d802f9e9e33dab722
encryptKey: aGTqmJcfXluKWfFWHGw5SdzIg6QIxPsp
verificationToken: ChUEDdWQbyHpHUV6H5fVeL5fOP3HfBE6
appId: cli_a2cff17bd3f8d013
appSecret: E5vXXmRipOD6vyolib186b25XXLbdYfE
fkChatId: oc_5124ee21dbdecf5d802f9e9e33dab722
# 腾讯云配置参数 # 腾讯云配置参数
tx: tx:
......
import com.google.common.base.CaseFormat; //import com.google.common.base.CaseFormat;
import freemarker.template.TemplateExceptionHandler; //import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator; //import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*; //import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback; //import org.mybatis.generator.internal.DefaultShellCallback;
//
import java.io.File; //import java.io.File;
import java.io.FileWriter; //import java.io.FileWriter;
import java.io.IOException; //import java.io.IOException;
import java.text.SimpleDateFormat; //import java.text.SimpleDateFormat;
import java.util.*; //import java.util.*;
//
/** ///**
* 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。 // * 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
*/ // */
public class CodeGenerator { //public class CodeGenerator {
//JDBC配置,请修改为你项目的实际配置 // //JDBC配置,请修改为你项目的实际配置
private static final String JDBC_URL = "jdbc:mysql://124.71.186.146:3316/t_test"; // private static final String JDBC_URL = "jdbc:mysql://124.71.186.146:3316/t_test";
private static final String JDBC_USERNAME = "weishuangshuang"; // private static final String JDBC_USERNAME = "weishuangshuang";
private static final String JDBC_PASSWORD = "weishuangshuang2020PipiTest"; // private static final String JDBC_PASSWORD = "weishuangshuang2020PipiTest";
private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; // private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
//
private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径 // private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/generator/template";//模板位置 // private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/generator/template";//模板位置
//
private static final String JAVA_PATH = "/src/main/java"; //java文件路径 // private static final String JAVA_PATH = "/src/main/java"; //java文件路径
private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径 // private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径
//
private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径 //// private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径
private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径 //// private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径 //// private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径
//
private static final String AUTHOR = "CodeGenerator";//@author // private static final String AUTHOR = "CodeGenerator";//@author
private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date // private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date
//
public static void main(String[] args) { // public static void main(String[] args) {
genCode("t_feishu_customer_feedback"); // genCode("t_feishu_customer_feedback");
//genCodeByCustomModelName("输入表名","输入自定义Model名称"); // //genCodeByCustomModelName("输入表名","输入自定义Model名称");
} // }
//
/** // /**
* 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。 // * 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。
* 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ... // * 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
* @param tableNames 数据表名称... // * @param tableNames 数据表名称...
*/ // */
public static void genCode(String... tableNames) { // public static void genCode(String... tableNames) {
for (String tableName : tableNames) { // for (String tableName : tableNames) {
genCodeByCustomModelName(tableName, null); // genCodeByCustomModelName(tableName, null);
} // }
} // }
//
/** // /**
* 通过数据表名称,和自定义的 Model 名称生成代码 // * 通过数据表名称,和自定义的 Model 名称生成代码
* 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ... // * 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
* @param tableName 数据表名称 // * @param tableName 数据表名称
* @param modelName 自定义的 Model 名称 // * @param modelName 自定义的 Model 名称
*/ // */
public static void genCodeByCustomModelName(String tableName, String modelName) { // public static void genCodeByCustomModelName(String tableName, String modelName) {
genModelAndMapper(tableName, modelName); // genModelAndMapper(tableName, modelName);
genService(tableName, modelName); // genService(tableName, modelName);
genController(tableName, modelName); // genController(tableName, modelName);
} // }
//
//
public static void genModelAndMapper(String tableName, String modelName) { // public static void genModelAndMapper(String tableName, String modelName) {
Context context = new Context(ModelType.FLAT); // Context context = new Context(ModelType.FLAT);
context.setId("Potato"); // context.setId("Potato");
context.setTargetRuntime("MyBatis3Simple"); // context.setTargetRuntime("MyBatis3Simple");
context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`"); // context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`"); // context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
//
JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration(); // JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
jdbcConnectionConfiguration.setConnectionURL(JDBC_URL); // jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
jdbcConnectionConfiguration.setUserId(JDBC_USERNAME); // jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD); // jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME); // jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration); // context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
//
PluginConfiguration pluginConfiguration = new PluginConfiguration(); // PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin"); // pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE); // pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE);
context.addPluginConfiguration(pluginConfiguration); // context.addPluginConfiguration(pluginConfiguration);
//
JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration(); // JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH); // javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE); // javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE);
context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration); // context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
//
SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration(); // SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH); // sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
sqlMapGeneratorConfiguration.setTargetPackage("mapper"); // sqlMapGeneratorConfiguration.setTargetPackage("mapper");
context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration); // context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
//
JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration(); // JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH); // javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE); // javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE);
javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER"); // javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration); // context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
//
TableConfiguration tableConfiguration = new TableConfiguration(context); // TableConfiguration tableConfiguration = new TableConfiguration(context);
tableConfiguration.setTableName(tableName); // tableConfiguration.setTableName(tableName);
if (StringUtils.isNotEmpty(modelName))tableConfiguration.setDomainObjectName(modelName); // if (StringUtils.isNotEmpty(modelName))tableConfiguration.setDomainObjectName(modelName);
tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null)); // tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
context.addTableConfiguration(tableConfiguration); // context.addTableConfiguration(tableConfiguration);
//
List<String> warnings; // List<String> warnings;
MyBatisGenerator generator; // MyBatisGenerator generator;
try { // try {
Configuration config = new Configuration(); // Configuration config = new Configuration();
config.addContext(context); // config.addContext(context);
config.validate(); // config.validate();
//
boolean overwrite = true; // boolean overwrite = true;
DefaultShellCallback callback = new DefaultShellCallback(overwrite); // DefaultShellCallback callback = new DefaultShellCallback(overwrite);
warnings = new ArrayList<String>(); // warnings = new ArrayList<String>();
generator = new MyBatisGenerator(config, callback, warnings); // generator = new MyBatisGenerator(config, callback, warnings);
generator.generate(null); // generator.generate(null);
} catch (Exception e) { // } catch (Exception e) {
throw new RuntimeException("生成Model和Mapper失败", e); // throw new RuntimeException("生成Model和Mapper失败", e);
} // }
//
if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) { // if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
throw new RuntimeException("生成Model和Mapper失败:" + warnings); // throw new RuntimeException("生成Model和Mapper失败:" + warnings);
} // }
if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName); // if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
System.out.println(modelName + ".java 生成成功"); // System.out.println(modelName + ".java 生成成功");
System.out.println(modelName + "Mapper.java 生成成功"); // System.out.println(modelName + "Mapper.java 生成成功");
System.out.println(modelName + "Mapper.xml 生成成功"); // System.out.println(modelName + "Mapper.xml 生成成功");
} // }
//
public static void genService(String tableName, String modelName) { // public static void genService(String tableName, String modelName) {
try { // try {
freemarker.template.Configuration cfg = getConfiguration(); // freemarker.template.Configuration cfg = getConfiguration();
//
Map<String, Object> data = new HashMap<>(); // Map<String, Object> data = new HashMap<>();
data.put("date", DATE); // data.put("date", DATE);
data.put("author", AUTHOR); // data.put("author", AUTHOR);
String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName; // String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
data.put("modelNameUpperCamel", modelNameUpperCamel); // data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName)); // data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
data.put("basePackage", BASE_PACKAGE); // data.put("basePackage", BASE_PACKAGE);
//
File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java"); // File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
if (!file.getParentFile().exists()) { // if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); // file.getParentFile().mkdirs();
} // }
cfg.getTemplate("service.ftl").process(data, // cfg.getTemplate("service.ftl").process(data,
new FileWriter(file)); // new FileWriter(file));
System.out.println(modelNameUpperCamel + "Service.java 生成成功"); // System.out.println(modelNameUpperCamel + "Service.java 生成成功");
//
File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java"); // File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
if (!file1.getParentFile().exists()) { // if (!file1.getParentFile().exists()) {
file1.getParentFile().mkdirs(); // file1.getParentFile().mkdirs();
} // }
cfg.getTemplate("service-impl.ftl").process(data, // cfg.getTemplate("service-impl.ftl").process(data,
new FileWriter(file1)); // new FileWriter(file1));
System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功"); // System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
} catch (Exception e) { // } catch (Exception e) {
throw new RuntimeException("生成Service失败", e); // throw new RuntimeException("生成Service失败", e);
} // }
} // }
//
public static void genController(String tableName, String modelName) { // public static void genController(String tableName, String modelName) {
try { // try {
freemarker.template.Configuration cfg = getConfiguration(); // freemarker.template.Configuration cfg = getConfiguration();
//
Map<String, Object> data = new HashMap<>(); // Map<String, Object> data = new HashMap<>();
data.put("date", DATE); // data.put("date", DATE);
data.put("author", AUTHOR); // data.put("author", AUTHOR);
String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName; // String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel)); // data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
data.put("modelNameUpperCamel", modelNameUpperCamel); // data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel)); // data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("basePackage", BASE_PACKAGE); // data.put("basePackage", BASE_PACKAGE);
//
File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java"); // File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
if (!file.getParentFile().exists()) { // if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); // file.getParentFile().mkdirs();
} // }
//cfg.getTemplate("controller-restful.ftl").process(data, new FileWriter(file)); // //cfg.getTemplate("controller-restful.ftl").process(data, new FileWriter(file));
cfg.getTemplate("controller.ftl").process(data, new FileWriter(file)); // cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));
//
System.out.println(modelNameUpperCamel + "Controller.java 生成成功"); // System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
} catch (Exception e) { // } catch (Exception e) {
throw new RuntimeException("生成Controller失败", e); // throw new RuntimeException("生成Controller失败", e);
} // }
//
} // }
//
private static freemarker.template.Configuration getConfiguration() throws IOException { // private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23); // freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH)); // cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8"); // cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg; // return cfg;
} // }
//
private static String tableNameConvertLowerCamel(String tableName) { // private static String tableNameConvertLowerCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase()); // return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
} // }
//
private static String tableNameConvertUpperCamel(String tableName) { // private static String tableNameConvertUpperCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase()); // return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
//
} // }
//
private static String tableNameConvertMappingPath(String tableName) { // private static String tableNameConvertMappingPath(String tableName) {
tableName = tableName.toLowerCase();//兼容使用大写的表名 // tableName = tableName.toLowerCase();//兼容使用大写的表名
return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName); // return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
} // }
//
private static String modelNameConvertMappingPath(String modelName) { // private static String modelNameConvertMappingPath(String modelName) {
String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName); // String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
return tableNameConvertMappingPath(tableName); // return tableNameConvertMappingPath(tableName);
} // }
//
private static String packageConvertPath(String packageName) { // private static String packageConvertPath(String packageName) {
return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName); // return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
} // }
//
} //}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!