拆分模块
This commit is contained in:
49
server/src/main/java/com/ecep/contract/AppV2.java
Normal file
49
server/src/main/java/com/ecep/contract/AppV2.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/4/16.
|
||||
*/
|
||||
public class AppV2 {
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppV2.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 添加JVM参数以解决Java代理动态加载警告
|
||||
// 这些警告来自360安全卫士的Java代理(com.baize.aegis.plugin.dependency.DependencyExtension)
|
||||
// 1. 启用代理使用跟踪
|
||||
System.setProperty("jdk.instrument.traceUsage", "true");
|
||||
// 2. 明确允许动态加载Java代理
|
||||
System.setProperty("jdk.instrument.allowNativeAccess", "true");
|
||||
// 3. 设置允许动态加载代理
|
||||
System.setProperty("jdk.enableDynamicAgentLoading", "true");
|
||||
|
||||
SpringApp.application = new SpringApplication(SpringApp.class);
|
||||
|
||||
BufferingApplicationStartup startup = new BufferingApplicationStartup(2000);
|
||||
SpringApp.application.setApplicationStartup(startup);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("应用程序启动参数:{}", (Object[]) args);
|
||||
}
|
||||
|
||||
startup.start("");
|
||||
SpringApp.context = SpringApp.application.run(args);
|
||||
|
||||
Duration between = Duration.between(startup.getBufferedTimeline().getStartTime(), Instant.now());
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("application.run() cost:{}", between);
|
||||
}
|
||||
}
|
||||
|
||||
public static final String DEFAULT_DB_HOST = "10.84.209.154"; // "db-server1.ecctrl.com"
|
||||
public static final String DEFAULT_DB_PORT = "3306";
|
||||
public static final String DEFAULT_DB_USERNAME = "supplier_ms";
|
||||
public static final String DEFAULT_DB_PASSWORD = "[TPdseO!JKMmlrpf";
|
||||
public static final String DEFAULT_DB_DATABASE = "supplier_ms";
|
||||
}
|
||||
32
server/src/main/java/com/ecep/contract/IEntityService.java
Normal file
32
server/src/main/java/com/ecep/contract/IEntityService.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
public interface IEntityService<T> {
|
||||
T findById(Integer id);
|
||||
|
||||
Page<T> findAll(Specification<T> spec, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 根据搜索文本构建了一个特定的规格化查询,以实现对实体模糊搜索
|
||||
*
|
||||
* @param searchText 要搜索的文本
|
||||
* @return 规格化查询
|
||||
*/
|
||||
Specification<T> getSpecification(String searchText);
|
||||
|
||||
/**
|
||||
* 根据搜索文本查询列表
|
||||
*/
|
||||
default List<T> search(String searchText) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
void delete(T entity);
|
||||
|
||||
T save(T entity);
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.net.CookieStore;
|
||||
import java.net.HttpCookie;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class MyPersistentCookieStore implements CookieStore {
|
||||
|
||||
|
||||
private final File file;
|
||||
private final ObjectMapper objectMapper;
|
||||
private Map<URI, List<HttpCookie>> cookiesMap = new HashMap<>();
|
||||
|
||||
public MyPersistentCookieStore(File file, ObjectMapper objectMapper) {
|
||||
this.file = file;
|
||||
this.objectMapper = objectMapper;
|
||||
if (file != null && file.exists()) {
|
||||
loadFromFile2();
|
||||
}
|
||||
}
|
||||
|
||||
private void loadFromFile2() {
|
||||
try {
|
||||
ObjectNode root = (ObjectNode) objectMapper.readTree(file);
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = root.fields(); it.hasNext(); ) {
|
||||
Map.Entry<String, JsonNode> entry = it.next();
|
||||
String key = entry.getKey();
|
||||
ArrayNode value = (ArrayNode) entry.getValue();
|
||||
|
||||
List<HttpCookie> cookies = new ArrayList<>();
|
||||
for (JsonNode node1 : value) {
|
||||
HttpCookie cookie = new HttpCookie(node1.get("name").asText(), node1.get("value").asText());
|
||||
objectMapper.updateValue(node1, cookie);
|
||||
cookies.add(cookie);
|
||||
}
|
||||
URI uri = URI.create(key);
|
||||
System.out.println(key + " -> " + uri);
|
||||
cookiesMap.put(uri, cookies);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void saveToFile2() {
|
||||
try {
|
||||
objectMapper.writeValue(file, cookiesMap);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadFromFile(File file) {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
// 假设格式为: name=value;domain=domain;path=path;expires=expires;
|
||||
String[] parts = line.split(";");
|
||||
String nameValue = parts[0];
|
||||
String[] nameValueParts = nameValue.split("=");
|
||||
String name = nameValueParts[0];
|
||||
String value = nameValueParts.length > 1 ? nameValueParts[1] : "";
|
||||
HttpCookie cookie = new HttpCookie(name, value);
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
String[] attribute = parts[i].split("=");
|
||||
if (attribute[0].equals("domain")) {
|
||||
cookie.setDomain(attribute[1]);
|
||||
} else if (attribute[0].equals("path")) {
|
||||
cookie.setPath(attribute[1]);
|
||||
} else if (attribute[0].equals("expires")) {
|
||||
// 解析日期格式并设置过期时间
|
||||
// 这里只是示例,实际需要正确解析日期格式
|
||||
Date expiresDate = new Date(Long.parseLong(attribute[1]));
|
||||
cookie.setMaxAge(expiresDate.getTime() - System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
URI uri = URI.create(cookie.getDomain());
|
||||
List<HttpCookie> cookies = cookiesMap.getOrDefault(uri, new ArrayList<>());
|
||||
cookies.add(cookie);
|
||||
cookiesMap.put(uri, cookies);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 处理文件读取错误
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void saveToFile() {
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
|
||||
for (Map.Entry<URI, List<HttpCookie>> entry : cookiesMap.entrySet()) {
|
||||
for (HttpCookie cookie : entry.getValue()) {
|
||||
String line = cookie.getName() + "=" + cookie.getValue() + ";domain=" + cookie.getDomain() + ";path=" + cookie.getPath();
|
||||
if (cookie.getMaxAge() > 0) {
|
||||
line += ";expires=" + (System.currentTimeMillis() + cookie.getMaxAge());
|
||||
}
|
||||
writer.write(line);
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 处理文件写入错误
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(URI uri, HttpCookie cookie) {
|
||||
if (cookie == null) {
|
||||
throw new NullPointerException("cookie is null");
|
||||
}
|
||||
|
||||
if (cookie.getDomain() != null) {
|
||||
URI key = getEffectiveURI(cookie);
|
||||
List<HttpCookie> cookies = cookiesMap.getOrDefault(key, new ArrayList<>());
|
||||
cookies.remove(cookie);
|
||||
cookies.add(cookie);
|
||||
cookiesMap.put(key, cookies);
|
||||
}
|
||||
|
||||
if (uri != null) {
|
||||
URI key = getEffectiveURI(uri);
|
||||
List<HttpCookie> cookies = cookiesMap.getOrDefault(key, new ArrayList<>());
|
||||
cookies.remove(cookie);
|
||||
cookies.add(cookie);
|
||||
cookiesMap.put(key, cookies);
|
||||
}
|
||||
saveToFile2();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<HttpCookie> get(URI uri) {
|
||||
URI effectiveURI = getEffectiveURI(uri);
|
||||
System.out.println("effectiveURI = " + effectiveURI);
|
||||
return cookiesMap.getOrDefault(effectiveURI, new ArrayList<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<HttpCookie> getCookies() {
|
||||
return cookiesMap.values().stream().flatMap(List::stream).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<URI> getURIs() {
|
||||
return cookiesMap.keySet().stream().toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(URI uri, HttpCookie cookie) {
|
||||
URI key = getEffectiveURI(uri);
|
||||
List<HttpCookie> httpCookies = cookiesMap.get(key);
|
||||
if (httpCookies == null) {
|
||||
return false;
|
||||
}
|
||||
return httpCookies.remove(cookie);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll() {
|
||||
cookiesMap.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
private URI getEffectiveURI(URI uri) {
|
||||
URI effectiveURI = null;
|
||||
try {
|
||||
effectiveURI = new URI("http",
|
||||
uri.getHost(),
|
||||
null, // path component
|
||||
null, // query component
|
||||
null // fragment component
|
||||
);
|
||||
} catch (URISyntaxException ignored) {
|
||||
ignored.printStackTrace();
|
||||
effectiveURI = uri;
|
||||
}
|
||||
|
||||
return effectiveURI;
|
||||
}
|
||||
|
||||
private URI getEffectiveURI(HttpCookie cookie) {
|
||||
URI effectiveURI = null;
|
||||
try {
|
||||
effectiveURI = new URI("http",
|
||||
cookie.getDomain(),
|
||||
null, // path component
|
||||
null, // query component
|
||||
null // fragment component
|
||||
);
|
||||
} catch (URISyntaxException ignored) {
|
||||
|
||||
}
|
||||
|
||||
return effectiveURI;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.CookieStore;
|
||||
import java.net.HttpCookie;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class MyPersistentCookieStore2 implements CookieStore {
|
||||
|
||||
|
||||
private final File file;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private List<HttpCookie> cookieJar = null;
|
||||
|
||||
// the cookies are indexed by its domain and associated uri (if present)
|
||||
// CAUTION: when a cookie removed from main data structure (i.e. cookieJar),
|
||||
// it won't be cleared in domainIndex & uriIndex. Double-check the
|
||||
// presence of cookie when retrieve one form index store.
|
||||
private Map<String, List<HttpCookie>> domainIndex = null;
|
||||
private Map<URI, List<HttpCookie>> uriIndex = null;
|
||||
|
||||
// use ReentrantLock instead of synchronized for scalability
|
||||
private ReentrantLock lock = null;
|
||||
|
||||
|
||||
public MyPersistentCookieStore2(File file, ObjectMapper objectMapper) {
|
||||
this.file = file;
|
||||
this.objectMapper = objectMapper;
|
||||
cookieJar = new ArrayList<>();
|
||||
domainIndex = new HashMap<>();
|
||||
uriIndex = new HashMap<>();
|
||||
|
||||
lock = new ReentrantLock(false);
|
||||
|
||||
if (file != null && file.exists()) {
|
||||
loadFromFile2();
|
||||
}
|
||||
}
|
||||
|
||||
private void loadFromFile2() {
|
||||
try {
|
||||
ObjectNode root = (ObjectNode) objectMapper.readTree(file);
|
||||
|
||||
ArrayNode cookieJarNode = (ArrayNode) root.get("cookieJar");
|
||||
for (JsonNode node1 : cookieJarNode) {
|
||||
HttpCookie cookie = new HttpCookie(node1.get("name").asText(), node1.get("value").asText());
|
||||
objectMapper.updateValue(node1, cookie);
|
||||
cookieJar.add(cookie);
|
||||
}
|
||||
|
||||
|
||||
ObjectNode domainIndexNode = (ObjectNode) root.get("domainIndex");
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = domainIndexNode.fields(); it.hasNext(); ) {
|
||||
Map.Entry<String, JsonNode> entry = it.next();
|
||||
String key = entry.getKey();
|
||||
ArrayNode value = (ArrayNode) entry.getValue();
|
||||
|
||||
List<HttpCookie> cookies = new ArrayList<>();
|
||||
for (JsonNode node1 : value) {
|
||||
HttpCookie cookie = new HttpCookie(node1.get("name").asText(), node1.get("value").asText());
|
||||
objectMapper.updateValue(node1, cookie);
|
||||
cookies.add(cookie);
|
||||
}
|
||||
domainIndex.put(key, cookies);
|
||||
}
|
||||
|
||||
ObjectNode uriIndexNode = (ObjectNode) root.get("uriIndex");
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = uriIndexNode.fields(); it.hasNext(); ) {
|
||||
Map.Entry<String, JsonNode> entry = it.next();
|
||||
String key = entry.getKey();
|
||||
ArrayNode value = (ArrayNode) entry.getValue();
|
||||
|
||||
List<HttpCookie> cookies = new ArrayList<>();
|
||||
for (JsonNode node1 : value) {
|
||||
HttpCookie cookie = new HttpCookie(node1.get("name").asText(), node1.get("value").asText());
|
||||
objectMapper.updateValue(node1, cookie);
|
||||
cookies.add(cookie);
|
||||
}
|
||||
URI uri = URI.create(key);
|
||||
System.out.println(key + " -> " + uri);
|
||||
uriIndex.put(uri, cookies);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void saveToFile2() {
|
||||
try {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
map.put("cookieJar", cookieJar);
|
||||
map.put("domainIndex", domainIndex);
|
||||
map.put("uriIndex", uriIndex);
|
||||
objectMapper.writeValue(file, map);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add one cookie into cookie store.
|
||||
*/
|
||||
public void add(URI uri, HttpCookie cookie) {
|
||||
// pre-condition : argument can't be null
|
||||
if (cookie == null) {
|
||||
throw new NullPointerException("cookie is null");
|
||||
}
|
||||
|
||||
|
||||
lock.lock();
|
||||
try {
|
||||
// remove the ole cookie if there has had one
|
||||
cookieJar.remove(cookie);
|
||||
|
||||
// add new cookie if it has a non-zero max-age
|
||||
if (cookie.getMaxAge() != 0) {
|
||||
cookieJar.add(cookie);
|
||||
// and add it to domain index
|
||||
if (cookie.getDomain() != null) {
|
||||
addIndex(domainIndex, cookie.getDomain(), cookie);
|
||||
}
|
||||
if (uri != null) {
|
||||
// add it to uri index, too
|
||||
addIndex(uriIndex, getEffectiveURI(uri), cookie);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
saveToFile2();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get all cookies, which:
|
||||
* 1) given uri domain-matches with, or, associated with
|
||||
* given uri when added to the cookie store.
|
||||
* 3) not expired.
|
||||
* See RFC 2965 sec. 3.3.4 for more detail.
|
||||
*/
|
||||
public List<HttpCookie> get(URI uri) {
|
||||
// argument can't be null
|
||||
if (uri == null) {
|
||||
throw new NullPointerException("uri is null");
|
||||
}
|
||||
|
||||
List<HttpCookie> cookies = new ArrayList<>();
|
||||
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
|
||||
lock.lock();
|
||||
try {
|
||||
// check domainIndex first
|
||||
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
|
||||
// check uriIndex then
|
||||
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cookies in cookie store, except those have expired
|
||||
*/
|
||||
public List<HttpCookie> getCookies() {
|
||||
List<HttpCookie> rt;
|
||||
|
||||
lock.lock();
|
||||
try {
|
||||
Iterator<HttpCookie> it = cookieJar.iterator();
|
||||
while (it.hasNext()) {
|
||||
if (it.next().hasExpired()) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rt = Collections.unmodifiableList(cookieJar);
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return rt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all URIs, which are associated with at least one cookie
|
||||
* of this cookie store.
|
||||
*/
|
||||
public List<URI> getURIs() {
|
||||
List<URI> uris = new ArrayList<>();
|
||||
|
||||
lock.lock();
|
||||
try {
|
||||
Iterator<URI> it = uriIndex.keySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
URI uri = it.next();
|
||||
List<HttpCookie> cookies = uriIndex.get(uri);
|
||||
if (cookies == null || cookies.size() == 0) {
|
||||
// no cookies list or an empty list associated with
|
||||
// this uri entry, delete it
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
uris.addAll(uriIndex.keySet());
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove a cookie from store
|
||||
*/
|
||||
public boolean remove(URI uri, HttpCookie ck) {
|
||||
// argument can't be null
|
||||
if (ck == null) {
|
||||
throw new NullPointerException("cookie is null");
|
||||
}
|
||||
|
||||
boolean modified = false;
|
||||
lock.lock();
|
||||
try {
|
||||
modified = cookieJar.remove(ck);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove all cookies in this cookie store.
|
||||
*/
|
||||
public boolean removeAll() {
|
||||
lock.lock();
|
||||
try {
|
||||
if (cookieJar.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
cookieJar.clear();
|
||||
domainIndex.clear();
|
||||
uriIndex.clear();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/* ---------------- Private operations -------------- */
|
||||
|
||||
|
||||
/*
|
||||
* This is almost the same as HttpCookie.domainMatches except for
|
||||
* one difference: It won't reject cookies when the 'H' part of the
|
||||
* domain contains a dot ('.').
|
||||
* I.E.: RFC 2965 section 3.3.2 says that if host is x.y.domain.com
|
||||
* and the cookie domain is .domain.com, then it should be rejected.
|
||||
* However that's not how the real world works. Browsers don't reject and
|
||||
* some sites, like yahoo.com do actually expect these cookies to be
|
||||
* passed along.
|
||||
* And should be used for 'old' style cookies (aka Netscape type of cookies)
|
||||
*/
|
||||
private boolean netscapeDomainMatches(String domain, String host) {
|
||||
if (domain == null || host == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if there's no embedded dot in domain and domain is not .local
|
||||
boolean isLocalDomain = ".local".equalsIgnoreCase(domain);
|
||||
int embeddedDotInDomain = domain.indexOf('.');
|
||||
if (embeddedDotInDomain == 0) {
|
||||
embeddedDotInDomain = domain.indexOf('.', 1);
|
||||
}
|
||||
if (!isLocalDomain && (embeddedDotInDomain == -1 || embeddedDotInDomain == domain.length() - 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if the host name contains no dot and the domain name is .local
|
||||
int firstDotInHost = host.indexOf('.');
|
||||
if (firstDotInHost == -1 && isLocalDomain) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int domainLength = domain.length();
|
||||
int lengthDiff = host.length() - domainLength;
|
||||
if (lengthDiff == 0) {
|
||||
// if the host name and the domain name are just string-compare equal
|
||||
return host.equalsIgnoreCase(domain);
|
||||
} else if (lengthDiff > 0) {
|
||||
// need to check H & D component
|
||||
String H = host.substring(0, lengthDiff);
|
||||
String D = host.substring(lengthDiff);
|
||||
|
||||
return (D.equalsIgnoreCase(domain));
|
||||
} else if (lengthDiff == -1) {
|
||||
// if domain is actually .host
|
||||
return (domain.charAt(0) == '.' &&
|
||||
host.equalsIgnoreCase(domain.substring(1)));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void getInternal1(List<HttpCookie> cookies, Map<String, List<HttpCookie>> cookieIndex,
|
||||
String host, boolean secureLink) {
|
||||
// Use a separate list to handle cookies that need to be removed so
|
||||
// that there is no conflict with iterators.
|
||||
ArrayList<HttpCookie> toRemove = new ArrayList<>();
|
||||
for (Map.Entry<String, List<HttpCookie>> entry : cookieIndex.entrySet()) {
|
||||
String domain = entry.getKey();
|
||||
List<HttpCookie> lst = entry.getValue();
|
||||
for (HttpCookie c : lst) {
|
||||
if ((c.getVersion() == 0 && netscapeDomainMatches(domain, host)) ||
|
||||
(c.getVersion() == 1 && HttpCookie.domainMatches(domain, host))) {
|
||||
if ((cookieJar.indexOf(c) != -1)) {
|
||||
// the cookie still in main cookie store
|
||||
if (!c.hasExpired()) {
|
||||
// don't add twice and make sure it's the proper
|
||||
// security level
|
||||
if ((secureLink || !c.getSecure()) &&
|
||||
!cookies.contains(c)) {
|
||||
cookies.add(c);
|
||||
}
|
||||
} else {
|
||||
toRemove.add(c);
|
||||
}
|
||||
} else {
|
||||
// the cookie has been removed from main store,
|
||||
// so also remove it from domain indexed store
|
||||
toRemove.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Clear up the cookies that need to be removed
|
||||
for (HttpCookie c : toRemove) {
|
||||
lst.remove(c);
|
||||
cookieJar.remove(c);
|
||||
|
||||
}
|
||||
toRemove.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// @param cookies [OUT] contains the found cookies
|
||||
// @param cookieIndex the index
|
||||
// @param comparator the prediction to decide whether or not
|
||||
// a cookie in index should be returned
|
||||
private <T> void getInternal2(List<HttpCookie> cookies,
|
||||
Map<T, List<HttpCookie>> cookieIndex,
|
||||
Comparable<T> comparator, boolean secureLink) {
|
||||
for (T index : cookieIndex.keySet()) {
|
||||
if (comparator.compareTo(index) == 0) {
|
||||
List<HttpCookie> indexedCookies = cookieIndex.get(index);
|
||||
// check the list of cookies associated with this domain
|
||||
if (indexedCookies != null) {
|
||||
Iterator<HttpCookie> it = indexedCookies.iterator();
|
||||
while (it.hasNext()) {
|
||||
HttpCookie ck = it.next();
|
||||
if (cookieJar.indexOf(ck) != -1) {
|
||||
// the cookie still in main cookie store
|
||||
if (!ck.hasExpired()) {
|
||||
// don't add twice
|
||||
if ((secureLink || !ck.getSecure()) &&
|
||||
!cookies.contains(ck))
|
||||
cookies.add(ck);
|
||||
} else {
|
||||
it.remove();
|
||||
cookieJar.remove(ck);
|
||||
}
|
||||
} else {
|
||||
// the cookie has been removed from main store,
|
||||
// so also remove it from domain indexed store
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
} // end of indexedCookies != null
|
||||
} // end of comparator.compareTo(index) == 0
|
||||
} // end of cookieIndex iteration
|
||||
}
|
||||
|
||||
// add 'cookie' indexed by 'index' into 'indexStore'
|
||||
private <T> void addIndex(Map<T, List<HttpCookie>> indexStore,
|
||||
T index,
|
||||
HttpCookie cookie) {
|
||||
if (index != null) {
|
||||
List<HttpCookie> cookies = indexStore.get(index);
|
||||
if (cookies != null) {
|
||||
// there may already have the same cookie, so remove it first
|
||||
cookies.remove(cookie);
|
||||
|
||||
cookies.add(cookie);
|
||||
} else {
|
||||
cookies = new ArrayList<>();
|
||||
cookies.add(cookie);
|
||||
indexStore.put(index, cookies);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// for cookie purpose, the effective uri should only be http://host
|
||||
// the path will be taken into account when path-match algorithm applied
|
||||
//
|
||||
private URI getEffectiveURI(URI uri) {
|
||||
URI effectiveURI = null;
|
||||
try {
|
||||
effectiveURI = new URI("http",
|
||||
uri.getHost(),
|
||||
null, // path component
|
||||
null, // query component
|
||||
null // fragment component
|
||||
);
|
||||
} catch (URISyntaxException ignored) {
|
||||
effectiveURI = uri;
|
||||
}
|
||||
|
||||
return effectiveURI;
|
||||
}
|
||||
}
|
||||
35
server/src/main/java/com/ecep/contract/MyProperties.java
Normal file
35
server/src/main/java/com/ecep/contract/MyProperties.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "my")
|
||||
public class MyProperties {
|
||||
@Getter
|
||||
@Setter
|
||||
private String downloadsPath;
|
||||
|
||||
|
||||
/**
|
||||
* 尝试返回当前用户的下载文件夹
|
||||
*/
|
||||
public File getDownloadDirectory() {
|
||||
String downloadsPath = getDownloadsPath();
|
||||
if (StringUtils.hasText(downloadsPath)) {
|
||||
return new File(downloadsPath);
|
||||
}
|
||||
|
||||
// 没有配置下载目录时,尝试使用默认设置
|
||||
String home = System.getProperty("user.home");
|
||||
Path path = Paths.get(home, "Downloads");
|
||||
return path.toFile();
|
||||
}
|
||||
}
|
||||
261
server/src/main/java/com/ecep/contract/SpringApp.java
Normal file
261
server/src/main/java/com/ecep/contract/SpringApp.java
Normal file
@@ -0,0 +1,261 @@
|
||||
package com.ecep.contract;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.boot.ConfigurableBootstrapContext;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.SpringApplicationHook;
|
||||
import org.springframework.boot.SpringApplicationRunListener;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
import org.springframework.boot.context.metrics.buffering.StartupTimeline;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.PropertiesPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.metrics.StartupStep;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
import com.ecep.contract.cloud.CloudRepositoriesConfig;
|
||||
import com.ecep.contract.ds.DsRepositoriesConfig;
|
||||
import com.ecep.contract.util.TaskMonitorCenter;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
|
||||
|
||||
@SpringBootApplication(exclude = {
|
||||
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration.class,
|
||||
RedisReactiveAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class
|
||||
})
|
||||
@EnableScheduling
|
||||
@EnableAsync
|
||||
@EnableCaching
|
||||
public class SpringApp {
|
||||
|
||||
private final TaskMonitorCenter taskMonitorCenter;
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringApp.class);
|
||||
|
||||
static SpringApplication application;
|
||||
static ConfigurableApplicationContext context;
|
||||
|
||||
SpringApp(TaskMonitorCenter taskMonitorCenter) {
|
||||
this.taskMonitorCenter = taskMonitorCenter;
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> requiredType) throws BeansException {
|
||||
return context.getBean(requiredType);
|
||||
}
|
||||
|
||||
public static void launch(Properties properties, MessageHolder holder) {
|
||||
|
||||
//
|
||||
holder.debug("应用程序环境准备中...");
|
||||
SpringApplication.withHook(new Hook(holder), () -> {
|
||||
// 动态地注册或修改这些组件和配置
|
||||
application.addBootstrapRegistryInitializer(registry -> {
|
||||
//
|
||||
System.out.println("registry = " + registry);
|
||||
|
||||
});
|
||||
application.addListeners(event -> {
|
||||
logger.debug("SpringApp.launch ApplicationListener, event:{}", event);
|
||||
});
|
||||
|
||||
application.addInitializers(app -> {
|
||||
logger.debug("SpringApp.launch ApplicationContextInitializer");
|
||||
ConfigurableEnvironment environment = app.getEnvironment();
|
||||
logger.debug("environment = {}", environment);
|
||||
PropertySource<?> dynamicProperties = environment.getPropertySources().get("dynamicProperties");
|
||||
if (dynamicProperties != null) {
|
||||
logger.debug("dynamicProperties = {}", dynamicProperties);
|
||||
}
|
||||
environment.getPropertySources().addLast(new PropertiesPropertySource("dynamicProperties", properties));
|
||||
// app.getBeanFactory().registerSingleton("dataSource", dataSource());
|
||||
logger.debug("app = {}", app);
|
||||
|
||||
if (app instanceof AnnotationConfigApplicationContext ctx) {
|
||||
ctx.register(DsRepositoriesConfig.class);
|
||||
ctx.register(CloudRepositoriesConfig.class);
|
||||
}
|
||||
});
|
||||
|
||||
// startup.start("");
|
||||
context = application.run();
|
||||
logger.debug("SpringApp.launch application.run().");
|
||||
// Duration between = Duration.between(startup.getBufferedTimeline().getStartTime(), Instant.now());
|
||||
// holder.info("应用程序环境加载完成... " + between);
|
||||
});
|
||||
// CompletableFuture.runAsync(() -> {
|
||||
// // 在这里调用 startup 性能分析
|
||||
// analyzeStartupPerformance(startup);
|
||||
// }, Desktop.instance.getExecutorService());
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析启动性能数据并输出到日志
|
||||
*/
|
||||
private static void analyzeStartupPerformance(BufferingApplicationStartup startup) {
|
||||
// 获取所有记录的事件
|
||||
StartupTimeline timeline = startup.getBufferedTimeline();
|
||||
if (timeline == null || timeline.getEvents().isEmpty()) {
|
||||
logger.warn("StartupTimeline 为空或没有事件!");
|
||||
return;
|
||||
}
|
||||
logger.info("总共有 {} 个事件", timeline.getEvents().size());
|
||||
|
||||
// 找出与 Bean 初始化相关的步骤
|
||||
timeline.getEvents().stream()
|
||||
.filter(event -> event.getStartupStep().getName().startsWith("spring.beans."))
|
||||
.sorted((a, b) -> Long.compare(b.getDuration().toMillis(), a.getDuration().toMillis()))
|
||||
.limit(30)
|
||||
.forEach(event -> {
|
||||
String name = event.getStartupStep().getName();
|
||||
long duration = event.getDuration().toMillis();
|
||||
logger.info("Bean 初始化阶段: {} - 耗时: {} ms", name, duration);
|
||||
|
||||
for (StartupStep.Tag tag : event.getStartupStep().getTags()) {
|
||||
if ("beanName".equals(tag.getKey())) {
|
||||
logger.info(" └── Bean 名称: {}", tag.getValue());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static String getMessage(String code, Object[] args, Locale locale) {
|
||||
return context.getMessage(code, args, locale);
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
System.out.println("SpringApp.shutdown");
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("shutdown");
|
||||
}
|
||||
if (context != null) {
|
||||
if (context.isRunning()) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRunning() {
|
||||
return context != null && context.isRunning();
|
||||
}
|
||||
|
||||
static class Hook implements SpringApplicationHook, SpringApplicationRunListener {
|
||||
MessageHolder holder;
|
||||
|
||||
Hook(MessageHolder holder) {
|
||||
this.holder = holder;
|
||||
}
|
||||
|
||||
public void debug(String msg) {
|
||||
holder.debug(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void starting(ConfigurableBootstrapContext bootstrapContext) {
|
||||
logger.debug("Desktop.starting");
|
||||
debug("Spring Application 启动中...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext,
|
||||
ConfigurableEnvironment environment) {
|
||||
logger.debug("Desktop.environmentPrepared");
|
||||
debug("初始化 Environment 中,请稍后...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextPrepared(ConfigurableApplicationContext context) {
|
||||
logger.debug("Desktop.contextPrepared");
|
||||
debug("Spring Application Context 预处理中,请稍后...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextLoaded(ConfigurableApplicationContext context) {
|
||||
logger.debug("Desktop.contextLoaded");
|
||||
debug("Spring Application Context 初始化完毕,请稍后...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void started(ConfigurableApplicationContext context, Duration timeTaken) {
|
||||
logger.debug("Desktop.started");
|
||||
debug("Spring Application 启动完毕.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
|
||||
logger.debug("Desktop.ready");
|
||||
debug("Spring Application ready.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(ConfigurableApplicationContext context, Throwable exception) {
|
||||
logger.error("Desktop.failed", exception);
|
||||
holder.error("Spring Application 启动失败(" + exception.getMessage() + ").");
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpringApplicationRunListener getRunListener(SpringApplication springApplication) {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleClosedEvent(ContextClosedEvent event) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("handleClosedEvent={}", event);
|
||||
}
|
||||
}
|
||||
|
||||
// Redis缓存配置已移至application.properties文件
|
||||
// Spring Boot会根据配置自动创建RedisCacheManager
|
||||
|
||||
@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(
|
||||
DateTimeFormatter.ofPattern(MyDateTimeUtils.DEFAULT_DATETIME_FORMAT_PATTERN)));
|
||||
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
|
||||
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(
|
||||
DateTimeFormatter.ofPattern(MyDateTimeUtils.DEFAULT_DATETIME_FORMAT_PATTERN)));
|
||||
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
|
||||
objectMapper.registerModule(javaTimeModule);
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
public static TaskMonitorCenter getTaskMonitorCenter() {
|
||||
return getBean(TaskMonitorCenter.class);
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public ScheduledExecutorService scheduledExecutorService() {
|
||||
// return Desktop.instance.getExecutorService();
|
||||
// }
|
||||
|
||||
}
|
||||
175
server/src/main/java/com/ecep/contract/cloud/AbstractCtx.java
Normal file
175
server/src/main/java/com/ecep/contract/cloud/AbstractCtx.java
Normal file
@@ -0,0 +1,175 @@
|
||||
package com.ecep.contract.cloud;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.other.service.SysConfService;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
import com.ecep.contract.util.NumberUtils;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class AbstractCtx {
|
||||
@Setter
|
||||
SysConfService confService;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
Locale locale = Locale.getDefault();
|
||||
|
||||
public SysConfService getConfService() {
|
||||
if (confService == null) {
|
||||
confService = getBean(SysConfService.class);
|
||||
}
|
||||
return confService;
|
||||
}
|
||||
|
||||
|
||||
public boolean updateText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder, String topic) {
|
||||
if (!Objects.equals(getter.get(), text)) {
|
||||
setter.accept(text);
|
||||
holder.info(topic + "修改为: " + text);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean updateAppendText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder, String topic) {
|
||||
if (StringUtils.hasText(text)) {
|
||||
String str = MyStringUtils.appendIfAbsent(getter.get(), text);
|
||||
if (!Objects.equals(getter.get(), str)) {
|
||||
setter.accept(text);
|
||||
holder.info(topic + "修改为: " + text);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, java.sql.Date date, MessageHolder holder, String topic) {
|
||||
if (date != null) {
|
||||
return updateLocalDate(getter, setter, date.toLocalDate(), holder, topic);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date, MessageHolder holder, String topic) {
|
||||
return updateLocalDate(getter, setter, date, holder, topic, false);
|
||||
}
|
||||
|
||||
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date, MessageHolder holder, String topic, boolean allowNull) {
|
||||
if (date == null && !allowNull) {
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(getter.get(), date)) {
|
||||
setter.accept(date);
|
||||
holder.info(topic + "更新为 " + date);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, String strDate, MessageHolder holder, String topic) {
|
||||
LocalDate date = null;
|
||||
if (StringUtils.hasText(strDate)) {
|
||||
try {
|
||||
date = LocalDate.parse(strDate);
|
||||
} catch (DateTimeParseException e) {
|
||||
holder.warn("无法解析的日期:" + strDate);
|
||||
}
|
||||
}
|
||||
return updateLocalDate(getter, setter, date, holder, topic);
|
||||
}
|
||||
|
||||
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, Timestamp timestamp, MessageHolder holder, String topic) {
|
||||
LocalDate date = null;
|
||||
|
||||
if (timestamp != null) {
|
||||
try {
|
||||
date = timestamp.toLocalDateTime().toLocalDate();
|
||||
} catch (DateTimeParseException e) {
|
||||
holder.warn("解析日期" + timestamp + " 异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
return updateLocalDate(getter, setter, date, holder, topic);
|
||||
}
|
||||
|
||||
public boolean updateLocalDateTime(Supplier<LocalDateTime> getter, Consumer<LocalDateTime> setter, Timestamp timestamp, MessageHolder holder, String topic) {
|
||||
LocalDateTime dateTime = null;
|
||||
|
||||
if (timestamp != null) {
|
||||
try {
|
||||
// fixed nanos
|
||||
timestamp.setNanos(0);
|
||||
dateTime = timestamp.toLocalDateTime();
|
||||
} catch (DateTimeParseException e) {
|
||||
holder.warn("解析日期" + timestamp + " 异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (!Objects.equals(getter.get(), dateTime)) {
|
||||
setter.accept(dateTime);
|
||||
holder.info(topic + "修改为: " + dateTime);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, Instant instant, MessageHolder holder, String topic) {
|
||||
if (!Objects.equals(getter.get(), instant)) {
|
||||
setter.accept(instant);
|
||||
holder.info(topic + "修改为: " + instant);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, BigDecimal value, MessageHolder holder, String topic) {
|
||||
double val = value.doubleValue();
|
||||
return updateNumber(getter, setter, val, holder, topic);
|
||||
}
|
||||
|
||||
public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, double value, MessageHolder holder, String topic) {
|
||||
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
|
||||
setter.accept(value);
|
||||
holder.info(topic + "修改为: " + value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean updateNumber(Supplier<Float> getter, Consumer<Float> setter, float value, MessageHolder holder, String topic) {
|
||||
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
|
||||
setter.accept(value);
|
||||
holder.info(topic + "修改为: " + value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public boolean updateNumber(Supplier<Integer> getter, Consumer<Integer> setter, Integer value, MessageHolder holder, String topic) {
|
||||
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
|
||||
setter.accept(value);
|
||||
holder.info(topic + "修改为: " + value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.ecep.contract.cloud;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.IdentityEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.Version;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
/**
|
||||
* 记录同步来源
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
// @Entity
|
||||
// @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
|
||||
@ToString
|
||||
@MappedSuperclass
|
||||
public abstract class CloudBaseInfo implements IdentityEntity {
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "ID", nullable = false)
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 平台编号
|
||||
*/
|
||||
@Column(name = "CLOUD_ID")
|
||||
private String cloudId;
|
||||
|
||||
/**
|
||||
* 本地更新时间戳,控制更新频率和重复更新
|
||||
*/
|
||||
@Column(name = "LATEST_UPDATE")
|
||||
private Instant latestUpdate;
|
||||
|
||||
/**
|
||||
* 关联的公司
|
||||
*/
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "COMPANY_ID")
|
||||
@ToString.Exclude
|
||||
private Company company;
|
||||
|
||||
@Version
|
||||
@ColumnDefault("0")
|
||||
@Column(name = "VERSION", nullable = false)
|
||||
private int version;
|
||||
|
||||
@Override
|
||||
public final boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null) return false;
|
||||
Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
|
||||
Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
|
||||
if (thisEffectiveClass != oEffectiveClass) return false;
|
||||
CloudBaseInfo cloudInfo = (CloudBaseInfo) o;
|
||||
return getId() != null && Objects.equals(getId(), cloudInfo.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int hashCode() {
|
||||
return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass().hashCode() : getClass().hashCode();
|
||||
}
|
||||
}
|
||||
90
server/src/main/java/com/ecep/contract/cloud/CloudInfo.java
Normal file
90
server/src/main/java/com/ecep/contract/cloud/CloudInfo.java
Normal file
@@ -0,0 +1,90 @@
|
||||
package com.ecep.contract.cloud;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
|
||||
import com.ecep.contract.CloudType;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Version;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
/**
|
||||
* 记录同步来源
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
//@org.springframework.data.relational.core.mapping.Table(name = "CLOUD_INFO")
|
||||
@Table(name = "CLOUD_INFO", schema = "supplier_ms")
|
||||
@ToString
|
||||
public class CloudInfo {
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "ID", nullable = false)
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 记录源类型
|
||||
*/
|
||||
@Column(name = "CLOUD_TYPE", length = 50)
|
||||
private CloudType type;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Column(name = "CLOUD_ID")
|
||||
private String cloudId;
|
||||
|
||||
/**
|
||||
* 本地更新时间戳,控制更新频率和重复更新
|
||||
*/
|
||||
@Column(name = "LATEST_UPDATE")
|
||||
private Instant latestUpdate;
|
||||
|
||||
/**
|
||||
* 关联的公司
|
||||
*/
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "COMPANY_ID")
|
||||
@ToString.Exclude
|
||||
private Company company;
|
||||
|
||||
@Version
|
||||
@ColumnDefault("0")
|
||||
@Column(name = "VERSION", nullable = false)
|
||||
private int version;
|
||||
|
||||
@Override
|
||||
public final boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null) return false;
|
||||
Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
|
||||
Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
|
||||
if (thisEffectiveClass != oEffectiveClass) return false;
|
||||
CloudInfo cloudInfo = (CloudInfo) o;
|
||||
return getId() != null && Objects.equals(getId(), cloudInfo.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int hashCode() {
|
||||
return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass().hashCode() : getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ecep.contract.cloud;
|
||||
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Lazy
|
||||
@Repository
|
||||
public interface CloudInfoRepository
|
||||
// curd
|
||||
extends CrudRepository<CloudInfo, Integer>, PagingAndSortingRepository<CloudInfo, Integer> {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ecep.contract.cloud;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.data.repository.config.BootstrapMode;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(basePackages = {"com.ecep.contract.cloud"}, bootstrapMode = BootstrapMode.LAZY)
|
||||
public class CloudRepositoriesConfig {
|
||||
// @Bean
|
||||
// @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
// public BeanDefinition cloudInfoRepositoryDefinition() {
|
||||
// BeanDefinition definition = new org.springframework.beans.factory.support.GenericBeanDefinition();
|
||||
// definition.setBeanClassName("com.ecep.contract.manager.cloud.CloudInfoRepository");
|
||||
// definition.setLazyInit(true);
|
||||
// return definition;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
// public BeanDefinition cloudRkRepositoryDefinition() {
|
||||
// BeanDefinition definition = new org.springframework.beans.factory.support.GenericBeanDefinition();
|
||||
// definition.setBeanClassName("com.ecep.contract.manager.cloud.u8.CloudRkRepository");
|
||||
// definition.setLazyInit(true);
|
||||
// return definition;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
// public BeanDefinition cloudTycRepositoryDefinition() {
|
||||
// BeanDefinition definition = new org.springframework.beans.factory.support.GenericBeanDefinition();
|
||||
// definition.setBeanClassName("com.ecep.contract.manager.cloud.u8.CloudTycRepository");
|
||||
// definition.setLazyInit(true);
|
||||
// return definition;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
// public BeanDefinition cloudYuRepositoryDefinition() {
|
||||
// BeanDefinition definition = new org.springframework.beans.factory.support.GenericBeanDefinition();
|
||||
// definition.setBeanClassName("com.ecep.contract.manager.cloud.u8.CloudYuRepository");
|
||||
// definition.setLazyInit(true);
|
||||
// return definition;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ecep.contract.cloud.old;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
import com.ecep.contract.model.CompanyContract;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class CompanyContactUtils {
|
||||
/**
|
||||
* 使用 map 应用到 contact, 如有更新, 则返回 true
|
||||
*/
|
||||
public static boolean applyContactByMap(CompanyContact contact, Map<String, Object> map) {
|
||||
boolean modified = false;
|
||||
String name = (String) map.get("NAME");
|
||||
String phone = (String) map.get("PHONE");
|
||||
String email = (String) map.get("EMAIL");
|
||||
String address = (String) map.get("ADDRESS");
|
||||
if (name != null) {
|
||||
// 更新备注
|
||||
if (!Objects.equals(contact.getName(), name)) {
|
||||
contact.setName(name);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (phone != null) {
|
||||
// 更新备注
|
||||
if (!Objects.equals(contact.getPhone(), phone)) {
|
||||
contact.setPhone(phone);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (email != null) {
|
||||
// 更新备注
|
||||
if (!Objects.equals(contact.getEmail(), email)) {
|
||||
contact.setEmail(email);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (address != null) {
|
||||
// 更新备注
|
||||
if (!Objects.equals(contact.getAddress(), address)) {
|
||||
contact.setAddress(address);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 要和{@link CompanyContract#getContactKey(CompanyContact)}一致
|
||||
*/
|
||||
public static String getContactKey(Map<String, Object> map) {
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
String name = (String) map.get("NAME");
|
||||
String phone = (String) map.get("PHONE");
|
||||
String email = (String) map.get("EMAIL");
|
||||
return name + phone + email;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ecep.contract.cloud.old;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.ecep.contract.model.CompanyCustomerFile;
|
||||
|
||||
public class CompanyCustomerFileUtils {
|
||||
public static boolean applyCustomerFileByMap(CompanyCustomerFile customerFile, Map<String, Object> m) {
|
||||
boolean modified = false;
|
||||
|
||||
String filePath = (String) m.get("FILE_PATH");
|
||||
String editFilePath = (String) m.get("EDIT_FILE_PATH");
|
||||
java.sql.Date signDate = (java.sql.Date) m.get("SIGN_DATE");
|
||||
Boolean valid = (Boolean) m.get("VALID");
|
||||
|
||||
if (filePath != null) {
|
||||
// file path
|
||||
if (!Objects.equals(customerFile.getFilePath(), filePath)) {
|
||||
customerFile.setFilePath(filePath);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (editFilePath != null) {
|
||||
// edit file path
|
||||
if (!Objects.equals(customerFile.getEditFilePath(), editFilePath)) {
|
||||
customerFile.setEditFilePath(editFilePath);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (signDate != null) {
|
||||
// date
|
||||
LocalDate localDate = signDate.toLocalDate();
|
||||
if (!Objects.equals(customerFile.getSignDate(), localDate)) {
|
||||
customerFile.setSignDate(localDate);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (valid != null) {
|
||||
// valid
|
||||
if (!Objects.equals(customerFile.isValid(), valid)) {
|
||||
customerFile.setValid(valid);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
public static String getCustomerFileKey(Map<String, Object> m) {
|
||||
return m.get("FILE_PATH").toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ecep.contract.cloud.old;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.ecep.contract.model.CompanyVendorFile;
|
||||
|
||||
public class CompanyVendorFileUtils {
|
||||
public static boolean applyVendorFileByMap(CompanyVendorFile vendorFile, Map<String, Object> m) {
|
||||
boolean modified = false;
|
||||
|
||||
String filePath = (String) m.get("FILE_PATH");
|
||||
String editFilePath = (String) m.get("EDIT_FILE_PATH");
|
||||
java.sql.Date signDate = (java.sql.Date) m.get("SIGN_DATE");
|
||||
Boolean valid = (Boolean) m.get("VALID");
|
||||
|
||||
if (filePath != null) {
|
||||
// file path
|
||||
if (!Objects.equals(vendorFile.getFilePath(), filePath)) {
|
||||
vendorFile.setFilePath(filePath);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (editFilePath != null) {
|
||||
// edit file path
|
||||
if (!Objects.equals(vendorFile.getEditFilePath(), editFilePath)) {
|
||||
vendorFile.setEditFilePath(editFilePath);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (signDate != null) {
|
||||
// date
|
||||
LocalDate localDate = signDate.toLocalDate();
|
||||
if (!Objects.equals(vendorFile.getSignDate(), localDate)) {
|
||||
vendorFile.setSignDate(localDate);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (valid != null) {
|
||||
// valid
|
||||
if (!Objects.equals(vendorFile.isValid(), valid)) {
|
||||
vendorFile.setValid(valid);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
public static String getVendorFileKey(Map<String, Object> m) {
|
||||
return m.get("FILE_PATH").toString();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,124 @@
|
||||
package com.ecep.contract.cloud.old;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class OldVersionSyncCustomerTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(OldVersionSyncCustomerTask.class);
|
||||
|
||||
private final OldVersionService service = SpringApp.getBean(OldVersionService.class);
|
||||
private final CompanyService companyService = SpringApp.getBean(CompanyService.class);
|
||||
|
||||
private Map<Object, List<Map<String, Object>>> oldNameGroupedMap;
|
||||
private Map<Object, List<Map<String, Object>>> contactGroupedMap;
|
||||
private File basePath;
|
||||
private String titlePrefix = "";
|
||||
|
||||
public OldVersionSyncCustomerTask() {
|
||||
updateTitle("老版本-同步客户数据");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
updateTitle("老版本-同步客户数据");
|
||||
basePath = companyService.getCustomerBasePath();
|
||||
List<Runnable> runnable = Arrays.asList(this::loadOldNames, this::loadContacts, this::syncCustomers,
|
||||
this::syncContracts);
|
||||
|
||||
for (int i = 0; i < runnable.size(); i++) {
|
||||
titlePrefix = "老版本-同步客户数据-" + (i + 1) + "/" + runnable.size() + "-";
|
||||
try {
|
||||
runnable.get(i).run();
|
||||
} catch (Exception e) {
|
||||
logger.error("运行至 {} 时,发生错误中断", titlePrefix, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void loadOldNames() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllCustomerOldNameForStream()) {
|
||||
updateTitle("载入曾用名");
|
||||
oldNameGroupedMap = stream.takeWhile(v -> !isCancelled()).parallel()
|
||||
.collect(Collectors.groupingBy(m -> m.get("GID")));
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("import Customer oldNames = {} from old version app", oldNameGroupedMap.size());
|
||||
}
|
||||
updateProgress(0.1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void loadContacts() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllCustomerContactForStream()) {
|
||||
updateTitle("载入联系人");
|
||||
contactGroupedMap = stream.takeWhile(v -> !isCancelled()).parallel()
|
||||
.collect(Collectors.groupingBy(m -> m.get("GID")));
|
||||
logger.debug("import Customer contacts = {} from old version app", contactGroupedMap.size());
|
||||
updateProgress(0.2, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncCustomers() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllCustomerForStream()) {
|
||||
updateTitle("客户信息");
|
||||
long size = service.countOfCustomer();
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
stream.takeWhile(v -> !isCancelled()).forEach(map -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
Company updated = service.syncCustomer(map, basePath, oldNameGroupedMap, contactGroupedMap);
|
||||
if (updated != null) {
|
||||
updateMessage(counter.get() + " / " + size + ">" + updated.getName());
|
||||
} else {
|
||||
updateMessage(counter.get() + " / " + size + ">" + map.get("NAME"));
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void syncContracts() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllCustomerContractForStream()) {
|
||||
updateTitle("合同信息");
|
||||
long size = service.countOfCustomerContract();
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
stream.takeWhile(v -> !isCancelled()).forEach(map -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
Contract updated = service.syncCustomerContract(map);
|
||||
if (updated != null) {
|
||||
updateMessage(counter.get() + " / " + size + ">" + updated.getName());
|
||||
} else {
|
||||
updateMessage(counter.get() + " / " + size + ">" + map.get("NO"));
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.ecep.contract.cloud.old;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
public class OldVersionSyncVendorTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(OldVersionSyncVendorTask.class);
|
||||
|
||||
private final OldVersionService service = SpringApp.getBean(OldVersionService.class);
|
||||
private final CompanyService companyService = SpringApp.getBean(CompanyService.class);
|
||||
private Map<Object, List<Map<String, Object>>> oldNameGroupedMap;
|
||||
private Map<Object, List<Map<String, Object>>> contactGroupedMap;
|
||||
private File basePath;
|
||||
private String titlePrefix = "";
|
||||
|
||||
public OldVersionSyncVendorTask() {
|
||||
updateTitle("老版本-同步供应商数据");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
basePath = companyService.getVendorBasePath();
|
||||
List<Runnable> runnable = Arrays.asList(this::loadOldNames, this::loadContacts, this::syncVendors,
|
||||
this::syncContracts);
|
||||
for (int i = 0; i < runnable.size(); i++) {
|
||||
titlePrefix = "老版本-同步供应商数据-" + (i + 1) + "/" + runnable.size() + "-";
|
||||
try {
|
||||
runnable.get(i).run();
|
||||
} catch (Exception e) {
|
||||
logger.error("运行至 {} 时,发生错误中断", titlePrefix, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void loadOldNames() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllVendorOldNameForStream()) {
|
||||
updateTitle("载入曾用名");
|
||||
oldNameGroupedMap = stream.takeWhile(v -> !isCancelled()).parallel()
|
||||
.collect(Collectors.groupingBy(m -> m.get("GID")));
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("import vendor oldNames = {} from old version app", oldNameGroupedMap.size());
|
||||
}
|
||||
updateProgress(0.1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadContacts() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllVendorContactForStream()) {
|
||||
updateTitle("载入联系人");
|
||||
contactGroupedMap = stream.takeWhile(v -> !isCancelled()).parallel()
|
||||
.collect(Collectors.groupingBy(m -> m.get("GID")));
|
||||
logger.debug("import vendor contacts = {} from old version app", contactGroupedMap.size());
|
||||
updateProgress(0.2, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncVendors() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllVendorForStream()) {
|
||||
updateTitle("客户信息");
|
||||
long size = service.countOfVendor();
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
stream.takeWhile(v -> !isCancelled()).forEach(map -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
Company updated = service.syncVendor(map, basePath, oldNameGroupedMap, contactGroupedMap);
|
||||
if (updated != null) {
|
||||
updateMessage(counter.get() + " / " + size + ">" + updated.getName());
|
||||
} else {
|
||||
updateMessage(counter.get() + " / " + size + ">" + map.get("NAME"));
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void syncContracts() {
|
||||
try (Stream<Map<String, Object>> stream = service.queryAllVendorContractForStream()) {
|
||||
updateTitle("合同信息");
|
||||
long size = service.countOfVendorContract();
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
stream.takeWhile(v -> !isCancelled()).forEach(map -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
Contract updated = service.syncVendorContract(map);
|
||||
if (updated != null) {
|
||||
updateMessage(counter.get() + " / " + size + ">" + updated.getName());
|
||||
} else {
|
||||
updateMessage(counter.get() + " / " + size + ">" + map.get("NO"));
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ecep.contract.cloud.rk;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.URI;
|
||||
|
||||
public class BlackListUpdateContext {
|
||||
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
private ObjectMapper objectMapper;
|
||||
private Proxy.Type proxyType;
|
||||
@Getter
|
||||
private Proxy socksProxy;
|
||||
@Setter
|
||||
@Getter
|
||||
private String url;
|
||||
@Getter
|
||||
private long elapse = 1440;
|
||||
|
||||
|
||||
public void setProxy(String proxy) {
|
||||
if (proxy != null) {
|
||||
URI proxyUri = URI.create(proxy);
|
||||
proxyType = Proxy.Type.valueOf(proxyUri.getScheme().toUpperCase());
|
||||
socksProxy = new Proxy(
|
||||
proxyType,
|
||||
new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public void setElapse(String value) {
|
||||
elapse = Long.parseLong(value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ecep.contract.cloud.rk;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
@Repository
|
||||
public interface CloudRkRepository extends MyRepository<CloudRk, Integer> {
|
||||
|
||||
Stream<CloudRk> findByCloudLatestAfter(Instant timestamp);
|
||||
|
||||
Stream<CloudRk> findByCloudEntUpdateAfter(Instant timestamp);
|
||||
|
||||
/**
|
||||
* 按公司查找 Cloud RK
|
||||
*
|
||||
* @param company 公司对象
|
||||
* @return Cloud RK
|
||||
*/
|
||||
Optional<CloudRk> findByCompany(Company company);
|
||||
|
||||
/**
|
||||
* 按公司查找 Cloud RK
|
||||
*
|
||||
* @param companyId 公司对象编号
|
||||
* @return Cloud RK
|
||||
*/
|
||||
Optional<CloudRk> findByCompanyId(int companyId);
|
||||
|
||||
List<CloudRk> findAllByCompanyId(int companyId);
|
||||
|
||||
long countByLatestUpdateBefore(Instant instant);
|
||||
|
||||
long countByAutoUpdateIsTrueAndLatestUpdateBefore(Instant instant);
|
||||
|
||||
List<CloudRk> findTop100ByLatestUpdateBeforeOrderByLatestUpdateDesc(Instant instant);
|
||||
|
||||
List<CloudRk> findTop100ByAutoUpdateIsTrueAndLatestUpdateBeforeOrderByLatestUpdateDesc(Instant instant);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
int deleteAllByCompany(Company company);
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package com.ecep.contract.cloud.rk;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.ecep.contract.util.FileUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.BlackReasonType;
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.cloud.CloudInfo;
|
||||
import com.ecep.contract.ds.company.repository.CompanyBlackReasonRepository;
|
||||
import com.ecep.contract.ds.company.repository.CompanyOldNameRepository;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.other.service.SysConfService;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBlackReason;
|
||||
import com.ecep.contract.util.HttpJsonUtils;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import jakarta.persistence.criteria.Path;
|
||||
import lombok.Data;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "cloud-rk")
|
||||
public class CloudRkService implements IEntityService<CloudRk> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudRkService.class);
|
||||
|
||||
public final static String ENTERPRISE_CREDIT_REPORT = "企业征信报告";
|
||||
|
||||
public static final String KEY_PROXY = "cloud.rk.proxy";
|
||||
public static final String KEY_SYNC_ELAPSE = "cloud.rk.sync.elapse";
|
||||
public static final long DEFAULT_SYNC_ELAPSE = 36000L;
|
||||
public static final String KEY_VENDOR_REPORT_URL = "cloud.rk.vendor.report.url";
|
||||
public static final String KEY_CUSTOMER_REPORT_URL = "cloud.rk.customer.report.url";
|
||||
public static final String KEY_ENT_SCORE_URL = "cloud.rk.ent_score.url";
|
||||
public static final String KEY_ENT_REPORT_URL = "cloud.rk.ent_report.url";
|
||||
public static final String KEY_ENT_FUZZY_URL = "cloud.rk.ent_fuzzy.url";
|
||||
public static final String KEY_BLACK_LIST_URL = "cloud.rk.black_list.url";
|
||||
public static final String KEY_BLACK_LIST_ELAPSE = "cloud.rk.black_list.elapse";
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 同步超时, 单位 毫秒
|
||||
*
|
||||
* @return 毫秒
|
||||
*/
|
||||
public long getSyncElapse() {
|
||||
String string = confService.getString(KEY_SYNC_ELAPSE);
|
||||
if (!StringUtils.hasText(string)) {
|
||||
return DEFAULT_SYNC_ELAPSE;
|
||||
}
|
||||
return MyStringUtils.toLong(string, DEFAULT_SYNC_ELAPSE);
|
||||
}
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class EntInfo {
|
||||
@JsonAlias("entid")
|
||||
private String id;
|
||||
@JsonAlias("entname")
|
||||
private String name;
|
||||
private boolean nowName;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private SysConfService confService;
|
||||
@Autowired
|
||||
private CloudRkRepository cloudRKRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
@Autowired
|
||||
private CompanyOldNameRepository companyOldNameRepository;
|
||||
@Autowired
|
||||
private CompanyBlackReasonRepository companyBlackReasonRepository;
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public CloudRk findById(Integer id) {
|
||||
return cloudRKRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Page<CloudRk> findAll(Specification<CloudRk> spec, Pageable pageable) {
|
||||
return cloudRKRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CloudRk> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
Path<Object> company = root.get("company");
|
||||
return builder.or(
|
||||
builder.like(company.get("name"), "%" + searchText + "%"),
|
||||
builder.like(company.get("shortName"), "%" + searchText + "%"),
|
||||
builder.like(root.get("cloudId"), "%" + searchText + "%"),
|
||||
builder.like(root.get("description"), "%" + searchText + "%"));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新黑名单列表
|
||||
*/
|
||||
public void updateBlackList(
|
||||
Company company, CloudRk cloudRk, BlackListUpdateContext context) throws IOException {
|
||||
List<String> companyNames = new ArrayList<>();
|
||||
companyNames.add(company.getName());
|
||||
// fixed 平台API使用企业名称,可能记录的是曾用名
|
||||
companyOldNameRepository.findAllByCompanyId(company.getId()).forEach(oldName -> {
|
||||
// 歧义的曾用名不采用
|
||||
if (oldName.getAmbiguity()) {
|
||||
return;
|
||||
}
|
||||
companyNames.add(oldName.getName());
|
||||
});
|
||||
|
||||
List<CompanyBlackReason> reasonList = new ArrayList<>();
|
||||
List<CompanyBlackReason> dbReasons = companyBlackReasonRepository.findAllByCompany(company);
|
||||
|
||||
companyNames.forEach(name -> {
|
||||
String url = context.getUrl() + URLEncoder.encode(name, StandardCharsets.UTF_8);
|
||||
try {
|
||||
HttpJsonUtils.get(url, json -> {
|
||||
if (!json.has("success") || !json.get("success").asBoolean()) {
|
||||
System.out.println("json = " + json.toPrettyString());
|
||||
return;
|
||||
}
|
||||
|
||||
if (json.has("data")) {
|
||||
JsonNode data = json.get("data");
|
||||
try {
|
||||
if (data.has("blackReason")) {
|
||||
for (JsonNode reason : data.get("blackReason")) {
|
||||
toCompanyBlackReasonList(company, BlackReasonType.BLACK, reason, dbReasons,
|
||||
reasonList, context.getObjectMapper());
|
||||
}
|
||||
}
|
||||
if (data.has("greyReason")) {
|
||||
for (JsonNode reason : data.get("greyReason")) {
|
||||
toCompanyBlackReasonList(company, BlackReasonType.GRAY, reason, dbReasons,
|
||||
reasonList, context.getObjectMapper());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error("{} {},json = {}", company.getName(), ex.getMessage(), json, ex);
|
||||
throw new RuntimeException(json.toString(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存JSON数据到公司目录
|
||||
String companyPath = company.getPath();
|
||||
if (StringUtils.hasText(companyPath)) {
|
||||
File dir = new File(companyPath);
|
||||
if (dir.exists()) {
|
||||
File file = new File(dir, FileUtils.FILE_BLACK_LIST_JSON);
|
||||
try {
|
||||
objectMapper.writeValue(file, json);
|
||||
} catch (IOException e) {
|
||||
logger.warn("Unable Save BlackList to {}, company:{}", file, company.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, context.getObjectMapper(), context.getSocksProxy());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
if (!reasonList.isEmpty()) {
|
||||
companyBlackReasonRepository.saveAll(reasonList);
|
||||
}
|
||||
cloudRk.setCloudBlackListUpdated(Instant.now());
|
||||
}
|
||||
|
||||
private void toCompanyBlackReasonList(
|
||||
Company company, BlackReasonType type,
|
||||
JsonNode reason, List<CompanyBlackReason> dbReasons,
|
||||
List<CompanyBlackReason> reasonList, ObjectMapper objectMapper) throws JsonMappingException {
|
||||
ObjectNode object = (ObjectNode) reason;
|
||||
String key = "rk-" + object.remove("id").asText();
|
||||
CompanyBlackReason cbr = dbReasons.stream().filter(r -> r.getKey().equals(key)).findAny()
|
||||
.orElseGet(CompanyBlackReason::new);
|
||||
objectMapper.updateValue(cbr, reason);
|
||||
cbr.setCompany(company);
|
||||
cbr.setType(type);
|
||||
cbr.setKey(key);
|
||||
reasonList.add(cbr);
|
||||
}
|
||||
|
||||
public CompletableFuture<BlackListUpdateContext> createBlackListUpdateContext() {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
BlackListUpdateContext context = new BlackListUpdateContext();
|
||||
context.setObjectMapper(objectMapper);
|
||||
context.setProxy(confService.getString(KEY_PROXY));
|
||||
context.setUrl(confService.getString(KEY_BLACK_LIST_URL));
|
||||
// context.setElapse(confService.getLong(KEY_BLACK_LIST_ELAPSE));
|
||||
return context;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true
|
||||
*/
|
||||
public boolean checkBlackListUpdateElapse(
|
||||
Company company, CloudRk cloudRk, BlackListUpdateContext context) {
|
||||
Instant start = cloudRk.getCloudBlackListUpdated();
|
||||
if (start == null) {
|
||||
return true;
|
||||
}
|
||||
Instant elapse = start.plusSeconds(context.getElapse());
|
||||
return elapse.isBefore(Instant.now());
|
||||
}
|
||||
|
||||
public CloudRk getOrCreateCloudRk(CloudInfo info) {
|
||||
Optional<CloudRk> optional = cloudRKRepository.findById(info.getId());
|
||||
return optional.orElseGet(() -> getOrCreateCloudRk(info.getCompany()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回或者创建 Cloud RK
|
||||
*
|
||||
* @param company 公司对象
|
||||
* @return Cloud RK
|
||||
*/
|
||||
public CloudRk getOrCreateCloudRk(Company company) {
|
||||
Integer companyId = company.getId();
|
||||
List<CloudRk> list = cloudRKRepository.findAllByCompanyId(companyId);
|
||||
if (list.isEmpty()) {
|
||||
CloudRk rk = new CloudRk();
|
||||
rk.setCompany(company);
|
||||
rk.setCustomerGrade("");
|
||||
rk.setCustomerScore(-1);
|
||||
rk.setVendorGrade("");
|
||||
rk.setVendorScore(-1);
|
||||
rk.setRank("");
|
||||
return cloudRKRepository.save(rk);
|
||||
}
|
||||
if (list.size() == 1) {
|
||||
return list.getFirst();
|
||||
}
|
||||
|
||||
// 查询有 CloudId 的记录
|
||||
List<CloudRk> hasCouldIdList = list.stream().filter(v -> StringUtils.hasText(v.getCloudId()))
|
||||
.collect(Collectors.toList());
|
||||
// 没有匹配到一条时
|
||||
if (hasCouldIdList.isEmpty()) {
|
||||
// 保留第一条,其他删除
|
||||
CloudRk rk = list.removeFirst();
|
||||
cloudRKRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 只有匹配到一条有 CloudId 的记录
|
||||
if (hasCouldIdList.size() == 1) {
|
||||
// 保留匹配的记录,其他删除
|
||||
CloudRk rk = hasCouldIdList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudRKRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 查询有 CloudLatest 的记录
|
||||
List<CloudRk> hasLatestList = hasCouldIdList.stream().filter(v -> v.getCloudLatest() != null)
|
||||
.collect(Collectors.toList());
|
||||
// 没有匹配到一条时
|
||||
if (hasLatestList.isEmpty()) {
|
||||
// 保留第一条,其他删除
|
||||
CloudRk rk = hasCouldIdList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudRKRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 只有匹配到一条有 CloudId 的记录
|
||||
if (hasLatestList.size() == 1) {
|
||||
// 保留匹配的记录,其他删除
|
||||
CloudRk rk = hasLatestList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudRKRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
return hasLatestList.getFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 Cloud Rk
|
||||
*
|
||||
* @param cloudRk Cloud Rk 对象
|
||||
* @return 更新的 Cloud Rk
|
||||
*/
|
||||
@CacheEvict(key = "#p0.id")
|
||||
public CloudRk save(CloudRk cloudRk) {
|
||||
return cloudRKRepository.save(cloudRk);
|
||||
}
|
||||
|
||||
@CacheEvict(key = "#p0.id")
|
||||
@Override
|
||||
public void delete(CloudRk entity) {
|
||||
cloudRKRepository.delete(entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回 在 {@link #getSyncElapse()} 毫秒前,更新的
|
||||
*
|
||||
* @return 记录条数
|
||||
*/
|
||||
public long countNeedUpdate() {
|
||||
Instant now = Instant.now();
|
||||
long elapse = getSyncElapse();
|
||||
Instant instant = now.minusSeconds(elapse);
|
||||
return cloudRKRepository.countByAutoUpdateIsTrueAndLatestUpdateBefore(instant);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回距离上次更新超过 SysConfig:cloud.rk.black_list.elapse 秒的公司
|
||||
*/
|
||||
// @Transactional
|
||||
public List<CloudRk> findNeedUpdate() {
|
||||
Instant now = Instant.now();
|
||||
long elapse = getSyncElapse();
|
||||
Instant instant = now.minusSeconds(elapse);
|
||||
return cloudRKRepository.findTop100ByAutoUpdateIsTrueAndLatestUpdateBeforeOrderByLatestUpdateDesc(instant);
|
||||
}
|
||||
|
||||
@CacheEvict
|
||||
public void deleteByCompany(Company company) {
|
||||
int deleted = cloudRKRepository.deleteAllByCompany(company);
|
||||
if (deleted > 0) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete {} records by company:#{}", deleted, company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 这个可以无法更新缓存
|
||||
@Caching(evict = {
|
||||
@CacheEvict(key = "#p0.id"),
|
||||
@CacheEvict(key = "#p1.id"),
|
||||
})
|
||||
public void resetTo(Company from, Company to) {
|
||||
List<CloudRk> list = cloudRKRepository.findAllByCompanyId(from.getId());
|
||||
for (CloudRk item : list) {
|
||||
item.setCompany(to);
|
||||
}
|
||||
cloudRKRepository.saveAll(list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.ecep.contract.cloud.rk;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.rk.ctx.CloudRkCtx;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
/**
|
||||
* 集团相关方平台同步任务
|
||||
*/
|
||||
public class CloudRkSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudRkSyncTask.class);
|
||||
|
||||
private ContractService contractService;
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
updateTitle("集团相关方平台");
|
||||
|
||||
CloudRkCtx cloudRkCtx = null;
|
||||
CloudRkService service = null;
|
||||
try {
|
||||
cloudRkCtx = new CloudRkCtx();
|
||||
service = SpringApp.getBean(CloudRkService.class);
|
||||
cloudRkCtx.setCloudRkService(service);
|
||||
} catch (BeansException e) {
|
||||
holder.error("没有找到 " + CloudServiceConstant.RK_NAME + " 服务");
|
||||
return null;
|
||||
}
|
||||
|
||||
long total = service.countNeedUpdate();
|
||||
if (total == 0) {
|
||||
holder.info("没有需要更新");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
holder.info("统计需要更新的 " + total + " 条");
|
||||
|
||||
try {
|
||||
// 每次获取100条记录
|
||||
while (!isCancelled()) {
|
||||
List<CloudRk> needUpdate = service.findNeedUpdate();
|
||||
if (needUpdate.isEmpty()) {
|
||||
holder.info("处理完成");
|
||||
break;
|
||||
}
|
||||
for (CloudRk cloudRk : needUpdate) {
|
||||
if (isCancelled()) {
|
||||
break;
|
||||
}
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + ">");
|
||||
// fixed lazy
|
||||
Company company = cloudRk.getCompany();
|
||||
if (company == null) {
|
||||
subHolder.error("数据不完整,没有关联公司");
|
||||
break;
|
||||
}
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = getCompanyService().findById(company.getId());
|
||||
cloudRk.setCompany(company);
|
||||
}
|
||||
if (cloudRk.isAutoUpdate()) {
|
||||
LocalDate date = LocalDate.now().minusYears(3);
|
||||
long count = getContractService().findAllByCompany(company).stream()
|
||||
.filter(c -> c.getSetupDate() != null)
|
||||
.filter(c -> c.getSetupDate().isAfter(date))
|
||||
.count();
|
||||
if (count == 0) {
|
||||
holder.info("公司:" + company.getName() + " 没有3年以上的合同, 取消自动更新");
|
||||
cloudRk.setAutoUpdate(false);
|
||||
}
|
||||
}
|
||||
try {
|
||||
cloudRk.setDescription("");
|
||||
if (cloudRkCtx.syncCompany(company, cloudRk, subHolder)) {
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
cloudRk.setLatestUpdate(Instant.now());
|
||||
service.save(cloudRk);
|
||||
}
|
||||
// updateProgress(counter.incrementAndGet(), total);
|
||||
}
|
||||
}
|
||||
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("运行至 {}/{} 时,发生错误中断", counter.get(), total, e);
|
||||
}
|
||||
// updateProgress(1, 1);
|
||||
return null;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> delay(int second, Executor executor) {
|
||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||
|
||||
long until = System.currentTimeMillis() + second * 1000L;
|
||||
String title = "";
|
||||
AtomicReference<Runnable> reference = new AtomicReference<>();
|
||||
Runnable runnable = () -> {
|
||||
long let = until - System.currentTimeMillis();
|
||||
if (let < 0) {
|
||||
System.out.println("complete @" + Thread.currentThread().getName());
|
||||
future.complete(null);
|
||||
} else {
|
||||
// 再次调度
|
||||
executor.execute(reference.get());
|
||||
updateTitle(title + " 延时 " + ((int) let / 1000) + "秒");
|
||||
}
|
||||
};
|
||||
reference.set(runnable);
|
||||
// 第一次调度
|
||||
executor.execute(runnable);
|
||||
return future;
|
||||
}
|
||||
|
||||
ContractService getContractService() {
|
||||
if (contractService == null) {
|
||||
contractService = getBean(ContractService.class);
|
||||
}
|
||||
return contractService;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package com.ecep.contract.cloud.rk;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.ecep.contract.util.FileUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.company.repository.CompanyContactRepository;
|
||||
import com.ecep.contract.ds.company.service.CompanyOldNameService;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class EntReportParser {
|
||||
private static final Logger logger = LoggerFactory.getLogger(EntReportParser.class);
|
||||
private ObjectMapper objectMapper;
|
||||
private Company company;
|
||||
private CloudRk cloudRk;
|
||||
private boolean modified = false;
|
||||
|
||||
|
||||
public void parse(JsonNode json) {
|
||||
if (!json.has("B1001")) {
|
||||
// 没有数据
|
||||
throw new RuntimeException("B1001 can't be null, json:" + json);
|
||||
}
|
||||
JsonNode b1001 = json.get("B1001");
|
||||
if (!b1001.has("count") || b1001.get("count").asInt() < 1 || !b1001.has("data")) {
|
||||
// 没有数据
|
||||
return;
|
||||
}
|
||||
JsonNode data = b1001.get("data");
|
||||
|
||||
updateCompanyProperty("entType", data.get("enttype"));
|
||||
updateCompanyProperty("entStatus", data.get("entstatus"));
|
||||
updateCompanyProperty("setupDate", data.get("esdate"));
|
||||
|
||||
updateCompanyUniscid(data);
|
||||
updateCompanyNameHistory(data);
|
||||
|
||||
updateCompanyProperty("regAddr", data.get("dom"));
|
||||
updateCompanyProperty("registeredCapital", data.get("regcap"));
|
||||
updateCompanyProperty("registeredCapitalCurrency", data.get("regcapcur"));
|
||||
updateCompanyProperty("legalRepresentative", data.get("frname"));
|
||||
updateCompanyProperty("district", data.get("regorgprovince"));
|
||||
updateCompanyProperty("telephone", data.get("tel"));
|
||||
updateCompanyProperty("address", data.get("oploc"));
|
||||
updateCompanyProperty("operationPeriodBegin", data.get("opfrom"));
|
||||
updateCompanyProperty("operationPeriodEnd", data.get("opto"), "-");
|
||||
updateCompanyProperty("industry", data.get("nicfulltitle"));
|
||||
|
||||
//
|
||||
updateCloudRkEntUpdateDate(data);
|
||||
|
||||
// 更新法人联系人
|
||||
updateLegalRepresentativeContact(data);
|
||||
|
||||
// 保存JSON数据到公司目录
|
||||
saveJsonToFile(json);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void updateLegalRepresentativeContact(JsonNode data) {
|
||||
String legalRepresentative = company.getLegalRepresentative();
|
||||
if (!StringUtils.hasText(legalRepresentative)) {
|
||||
return;
|
||||
}
|
||||
CompanyContact contact = null;
|
||||
boolean modified = false;
|
||||
CompanyContactRepository contactRepository = SpringApp.getBean(CompanyContactRepository.class);
|
||||
List<CompanyContact> contactList = contactRepository.findAllByCompanyAndName(company, legalRepresentative);
|
||||
if (contactList == null) {
|
||||
// db error
|
||||
return;
|
||||
}
|
||||
if (contactList.isEmpty()) {
|
||||
//没有,创建法人联系人
|
||||
contact = new CompanyContact();
|
||||
contact.setCompany(company);
|
||||
contact.setName(legalRepresentative);
|
||||
contact.setPosition("法定代表人");
|
||||
contact.setCreated(LocalDate.now());
|
||||
modified = true;
|
||||
} else {
|
||||
Optional<CompanyContact> any = contactList.stream().filter(c -> "法定代表人".equals(c.getPosition())).findAny();
|
||||
if (any.isEmpty()) {
|
||||
any = contactList.stream().findAny();
|
||||
}
|
||||
contact = any.get();
|
||||
// if (contact.getPostion() == null || !contact.setPostion().contains("法定代表人")) {
|
||||
// contact.setMemo("法定代表人");
|
||||
// modified = true;
|
||||
// }
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getEmail())) {
|
||||
String text = data.get("email").asText();
|
||||
contact.setEmail(text);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getAddress())) {
|
||||
String text = company.getAddress();
|
||||
contact.setAddress(text);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getPhone())) {
|
||||
String text = company.getTelephone();
|
||||
contact.setPhone(text);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getPosition())) {
|
||||
contact.setPosition("法定代表人");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
contactRepository.save(contact);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void updateCompanyNameHistory(JsonNode data) {
|
||||
JsonNode node = data.get("nameHistory");
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
// 历史曾用名
|
||||
String nameHistory = node.asText();
|
||||
if (!StringUtils.hasText(nameHistory)) {
|
||||
return;
|
||||
}
|
||||
List<String> historyNames = new ArrayList<>();
|
||||
for (String str : nameHistory.split(",")) {
|
||||
String trimmed = str.trim();
|
||||
if (StringUtils.hasText(trimmed)) {
|
||||
historyNames.add(trimmed);
|
||||
}
|
||||
}
|
||||
CompanyOldNameService service = SpringApp.getBean(CompanyOldNameService.class);
|
||||
List<CompanyOldName> oldNames = service.findAllByCompany(company);
|
||||
for (CompanyOldName oldName : oldNames) {
|
||||
historyNames.remove(oldName.getName());
|
||||
}
|
||||
for (String historyName : historyNames) {
|
||||
CompanyOldName oldName = new CompanyOldName();
|
||||
oldName.setName(historyName);
|
||||
oldName.setCompanyId(company.getId());
|
||||
oldName.setMemo("从相关方平台导入");
|
||||
oldName.setAmbiguity(false);
|
||||
service.save(oldName);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCompanyUniscid(JsonNode data) {
|
||||
JsonNode node = data.get("uniscid");
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String uid = node.asText();
|
||||
if (StringUtils.hasText(uid)) {
|
||||
if (!uid.equals(company.getUniscid())) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("更新 {} 的 UNISCID {} -> {}", company.getName(), company.getUniscid(), uid);
|
||||
}
|
||||
company.setUniscid(uid);
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
//fixed 当平台返回的 社会统一信用代码为空时,如果原来已经有的,则不做更新
|
||||
if (StringUtils.hasText(company.getUniscid())) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("来自平台的 UNISCID 为空,但本地{}已经记录{},不做更改", company.getName(), company.getUniscid());
|
||||
}
|
||||
} else {
|
||||
company.setUniscid("");
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 平台的数据更新时间戳
|
||||
*/
|
||||
private void updateCloudRkEntUpdateDate(JsonNode data) {
|
||||
JsonNode node = data.get("updated");
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
LocalDateTime updated = objectMapper.convertValue(node, LocalDateTime.class);
|
||||
cloudRk.setCloudEntUpdate(updated.toInstant(ZoneOffset.ofHours(8)));
|
||||
}
|
||||
|
||||
private void updateCompanyProperty(String field, JsonNode node, String... excludeValues) {
|
||||
if (node == null || node.isNull()) {
|
||||
return;
|
||||
}
|
||||
String text = node.asText();
|
||||
for (String excludeValue : excludeValues) {
|
||||
if (Objects.equals(text, excludeValue)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
updateCompanyProperty(field, node);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新属性通用方法, 数据的类型转换由 objectMapper 提供
|
||||
*
|
||||
* @param field 类属性名称
|
||||
* @param node 数据来源 json node
|
||||
*/
|
||||
private void updateCompanyProperty(String field, JsonNode node) {
|
||||
if (node == null || node.isNull()) {
|
||||
return;
|
||||
}
|
||||
PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(Company.class, field);
|
||||
if (descriptor == null) {
|
||||
logger.error("Company 的字段 {} 不存在,请确认.", field);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object oldValue = descriptor.getReadMethod().invoke(company);
|
||||
Object newValue = objectMapper.convertValue(node, descriptor.getReadMethod().getReturnType());
|
||||
if (!Objects.equals(oldValue, newValue)) {
|
||||
descriptor.getWriteMethod().invoke(company, newValue);
|
||||
modified = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void saveJsonToFile(JsonNode json) {
|
||||
String companyPath = company.getPath();
|
||||
if (StringUtils.hasText(companyPath)) {
|
||||
File dir = new File(companyPath);
|
||||
if (dir.exists()) {
|
||||
File file = new File(dir, FileUtils.FILE_B1001_JSON);
|
||||
try {
|
||||
objectMapper.writeValue(file, json);
|
||||
} catch (IOException e) {
|
||||
logger.warn("Unable Save BlackList to {}, company:{}", file, company.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
package com.ecep.contract.cloud.rk.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.SocketException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import com.ecep.contract.util.FileUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.BlackReasonType;
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.AbstractCtx;
|
||||
import com.ecep.contract.cloud.rk.CloudRkService;
|
||||
import com.ecep.contract.ds.company.service.CompanyBlackReasonService;
|
||||
import com.ecep.contract.ds.company.service.CompanyContactService;
|
||||
import com.ecep.contract.ds.company.service.CompanyOldNameService;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBlackReason;
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
import com.ecep.contract.util.HttpJsonUtils;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class CloudRkCtx extends AbstractCtx {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudRkCtx.class);
|
||||
@Setter
|
||||
private CloudRkService cloudRkService;
|
||||
@Setter
|
||||
private CompanyService companyService;
|
||||
@Setter
|
||||
private CompanyBlackReasonService companyBlackReasonService;
|
||||
@Setter
|
||||
private ObjectMapper objectMapper;
|
||||
private Proxy socksProxy;
|
||||
|
||||
public CloudRkService getCloudRkService() {
|
||||
if (cloudRkService == null) {
|
||||
cloudRkService = getBean(CloudRkService.class);
|
||||
}
|
||||
return cloudRkService;
|
||||
}
|
||||
|
||||
public CompanyService getCompanyService() {
|
||||
if (companyService == null) {
|
||||
companyService = getBean(CompanyService.class);
|
||||
}
|
||||
return companyService;
|
||||
}
|
||||
|
||||
CompanyBlackReasonService getCompanyBlackReasonService() {
|
||||
if (companyBlackReasonService == null) {
|
||||
companyBlackReasonService = getBean(CompanyBlackReasonService.class);
|
||||
}
|
||||
return companyBlackReasonService;
|
||||
}
|
||||
|
||||
ObjectMapper getObjectMapper() {
|
||||
if (objectMapper == null) {
|
||||
objectMapper = getBean(ObjectMapper.class);
|
||||
}
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
Proxy getSocksProxy() {
|
||||
if (socksProxy == null) {
|
||||
String proxy = getConfService().getString(CloudRkService.KEY_PROXY);
|
||||
URI proxyUri = URI.create(proxy);
|
||||
Proxy.Type proxyType = Proxy.Type.valueOf(proxyUri.getScheme().toUpperCase());
|
||||
socksProxy = new Proxy(
|
||||
proxyType,
|
||||
new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort())
|
||||
);
|
||||
}
|
||||
return socksProxy;
|
||||
}
|
||||
|
||||
public void post(String url, Consumer<Map<String, Object>> data, Consumer<JsonNode> consumer) throws IOException {
|
||||
HttpJsonUtils.post(url, data, consumer, getObjectMapper(), getSocksProxy());
|
||||
}
|
||||
|
||||
|
||||
public boolean syncCompany(Company company, CloudRk cloudRk, MessageHolder holder) {
|
||||
if (!StringUtils.hasText(cloudRk.getCloudId())) {
|
||||
holder.warn("未定义平台编号, 尝试从平台上自动获取");
|
||||
// 当未定义平台编号时,尝试自动获取
|
||||
if (!queryCloudIdAndSelectOne(company, cloudRk, holder)) {
|
||||
// 自动获取到平台编号失败,立即返回
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(cloudRk.getCloudId()) || cloudRk.getCloudId().equals("-")) {
|
||||
// 平台编号为 空 或 - 时,跳过同步
|
||||
holder.debug("平台编号为 空 或 - 时,跳过同步");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updated = false;
|
||||
try {
|
||||
if (updateEnterpriseInfo(company, cloudRk, holder)) {
|
||||
company = getCompanyService().save(company);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (updateBlackList(company, cloudRk, holder)) {
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (updateEnterpriseCredit(company, cloudRk, holder)) {
|
||||
// cloudRk modified
|
||||
updated = true;
|
||||
}
|
||||
if (updateCustomerScore(company, cloudRk, holder)) {
|
||||
// cloudRk modified
|
||||
updated = true;
|
||||
}
|
||||
if (updateVendorScore(company, cloudRk, holder)) {
|
||||
// cloudRk modified
|
||||
updated = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 异常
|
||||
logger.error("使用评分接口更新企业资信评价等级时发生错误", e);
|
||||
cloudRk.setDescription("评分接口错误:" + e.getMessage());
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 更新黑名单列表
|
||||
*/
|
||||
public boolean updateBlackList(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
Instant start = cloudRk.getCloudBlackListUpdated();
|
||||
if (start != null) {
|
||||
long elapse = getConfService().getLong(CloudRkService.KEY_BLACK_LIST_ELAPSE);
|
||||
if (elapse > 0) {
|
||||
Instant next = start.plusSeconds(elapse);
|
||||
if (next.isAfter(Instant.now())) {
|
||||
holder.debug("更新时间未到, 上次更新时间 = " + start);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String api = getConfService().getString(CloudRkService.KEY_BLACK_LIST_URL);
|
||||
List<String> companyNames = getCompanyService().getAllNames(company);
|
||||
|
||||
|
||||
List<CompanyBlackReason> reasonList = new ArrayList<>();
|
||||
List<CompanyBlackReason> dbReasons = getCompanyBlackReasonService().findAllByCompany(company);
|
||||
for (String name : companyNames) {
|
||||
String url = api + URLEncoder.encode(name, StandardCharsets.UTF_8);
|
||||
try {
|
||||
HttpJsonUtils.get(url, json -> {
|
||||
applyBlackReason(json, company, cloudRk, reasonList, dbReasons, holder);
|
||||
saveJsonToFile(company, json, "black-" + name + ".json", holder);
|
||||
}, getObjectMapper(), getSocksProxy());
|
||||
} catch (IOException e) {
|
||||
catchException(e, holder);
|
||||
}
|
||||
}
|
||||
|
||||
if (reasonList.isEmpty()) {
|
||||
cloudRk.setCloudBlackListUpdated(Instant.now());
|
||||
return false;
|
||||
|
||||
}
|
||||
for (CompanyBlackReason companyBlackReason : reasonList) {
|
||||
getCompanyBlackReasonService().save(companyBlackReason);
|
||||
}
|
||||
cloudRk.setCloudBlackListUpdated(Instant.now());
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean applyBlackReason(
|
||||
JsonNode json, Company company, CloudRk cloudRk,
|
||||
List<CompanyBlackReason> reasonList, List<CompanyBlackReason> dbReasons,
|
||||
MessageHolder holder
|
||||
) {
|
||||
if (isUnSuccess(json, holder)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!json.has("data")) {
|
||||
holder.error("数据异常,返回的json中没有 data 字段");
|
||||
return false;
|
||||
}
|
||||
JsonNode data = json.get("data");
|
||||
|
||||
if (data.has("blackReason")) {
|
||||
for (JsonNode reason : data.get("blackReason")) {
|
||||
try {
|
||||
toCompanyBlackReasonList(company, BlackReasonType.BLACK, reason, dbReasons, reasonList);
|
||||
} catch (JsonMappingException e) {
|
||||
holder.error("blackReason " + e.getMessage() + ", " + reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data.has("greyReason")) {
|
||||
for (JsonNode reason : data.get("greyReason")) {
|
||||
try {
|
||||
toCompanyBlackReasonList(company, BlackReasonType.GRAY, reason, dbReasons, reasonList);
|
||||
} catch (JsonMappingException e) {
|
||||
holder.error("greyReason " + e.getMessage() + ", " + reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void toCompanyBlackReasonList(
|
||||
Company company, BlackReasonType type,
|
||||
JsonNode reason, List<CompanyBlackReason> dbReasons,
|
||||
List<CompanyBlackReason> reasonList
|
||||
) throws JsonMappingException {
|
||||
ObjectNode object = (ObjectNode) reason;
|
||||
String key = "rk-" + object.remove("id").asText();
|
||||
CompanyBlackReason cbr = dbReasons.stream().filter(r -> r.getKey().equals(key)).findAny().orElseGet(CompanyBlackReason::new);
|
||||
getObjectMapper().updateValue(cbr, reason);
|
||||
cbr.setCompany(company);
|
||||
cbr.setType(type);
|
||||
cbr.setKey(key);
|
||||
reasonList.add(cbr);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 更新评分
|
||||
*/
|
||||
public boolean updateEnterpriseCredit(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
String api = getConfService().getString(CloudRkService.KEY_ENT_SCORE_URL);
|
||||
AtomicBoolean modified = new AtomicBoolean(false);
|
||||
try {
|
||||
post(api, data -> {
|
||||
data.put("entname", company.getName());
|
||||
// data.put("entid", cloudInfo.getCloudId());
|
||||
data.put("get", true);
|
||||
}, json -> {
|
||||
modified.set(applyEnterpriseCredit(json, cloudRk, holder));
|
||||
saveJsonToFile(company, json, "credit.json", holder);
|
||||
});
|
||||
} catch (IOException e) {
|
||||
catchException(e, holder);
|
||||
}
|
||||
return modified.get();
|
||||
}
|
||||
|
||||
private boolean applyEnterpriseCredit(JsonNode json, CloudRk cloudRk, MessageHolder holder) {
|
||||
if (isUnSuccess(json, holder)) {
|
||||
return false;
|
||||
}
|
||||
if (isUnHasField(json, "data", holder)) {
|
||||
return false;
|
||||
}
|
||||
JsonNode data = json.get("data");
|
||||
boolean modified = false;
|
||||
String level = "";
|
||||
String description = "";
|
||||
if (data.isNull()) {
|
||||
level = "-";
|
||||
} else {
|
||||
level = data.get("level").asText();
|
||||
description = data.get("levelDescription").asText();
|
||||
}
|
||||
|
||||
if (updateText(cloudRk::getRank, cloudRk::setRank, level, holder, "企业资信评价等级")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(cloudRk::getRankDescription, cloudRk::setRankDescription, description, holder, "企业资信评价等级说明")) {
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean isUnHasField(JsonNode json, String field, MessageHolder holder) {
|
||||
if (!json.has("data")) {
|
||||
holder.error("数据异常,返回的json中没有 data 字段");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isUnSuccess(JsonNode json, MessageHolder holder) {
|
||||
if (isUnHasField(json, "success", holder)) {
|
||||
return true;
|
||||
}
|
||||
if (!json.get("success").asBoolean()) {
|
||||
holder.error("数据异常,返回 success = false, " + json);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户信用
|
||||
*/
|
||||
public boolean updateCustomerScore(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
String url = getConfService().getString(CloudRkService.KEY_CUSTOMER_REPORT_URL);
|
||||
AtomicBoolean modified = new AtomicBoolean(false);
|
||||
try {
|
||||
post(url, data -> {
|
||||
// data.put("entName", company.getName());
|
||||
data.put("entId", cloudRk.getCloudId());
|
||||
data.put("get", true);
|
||||
}, json -> {
|
||||
modified.set(applyCustomerScore(json, company, cloudRk, holder));
|
||||
saveJsonToFile(company, json, "customer-score.json", holder);
|
||||
});
|
||||
} catch (IOException e) {
|
||||
catchException(e, holder);
|
||||
}
|
||||
return modified.get();
|
||||
}
|
||||
|
||||
private boolean applyCustomerScore(JsonNode json, Company company, CloudRk cloudRk, MessageHolder holder) {
|
||||
if (isUnSuccess(json, holder)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean modified = false;
|
||||
String grade = "";
|
||||
int score = 0;
|
||||
String description = "";
|
||||
if (isUnHasField(json, "data", holder)) {
|
||||
grade = "-";
|
||||
score = -1;
|
||||
} else {
|
||||
JsonNode data = json.get("data");
|
||||
if (data.isNull()) {
|
||||
grade = "无";
|
||||
score = -1;
|
||||
} else {
|
||||
grade = data.get("grade").asText();
|
||||
score = data.get("totalScore").asInt();
|
||||
description = data.get("description").asText();
|
||||
}
|
||||
}
|
||||
|
||||
if (updateText(cloudRk::getCustomerGrade, cloudRk::setCustomerGrade, grade, holder, "客户信用评级")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateNumber(cloudRk::getCustomerScore, cloudRk::setCustomerScore, score, holder, "客户信用总分")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(cloudRk::getCustomerDescription, cloudRk::setCustomerDescription, description, holder, "客户信用评级说明")) {
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
public boolean updateVendorScore(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
String url = getConfService().getString(CloudRkService.KEY_VENDOR_REPORT_URL);
|
||||
AtomicBoolean modified = new AtomicBoolean(false);
|
||||
try {
|
||||
post(url, data -> {
|
||||
// data.put("entName", company.getName());
|
||||
data.put("entId", cloudRk.getCloudId());
|
||||
data.put("get", true);
|
||||
}, json -> {
|
||||
modified.set(applyVendorScore(json, cloudRk, holder));
|
||||
saveJsonToFile(company, json, "vendor-score.json", holder);
|
||||
});
|
||||
} catch (IOException e) {
|
||||
catchException(e, holder);
|
||||
}
|
||||
return modified.get();
|
||||
}
|
||||
|
||||
private boolean applyVendorScore(JsonNode json, CloudRk cloudRk, MessageHolder holder) {
|
||||
if (isUnSuccess(json, holder)) {
|
||||
return false;
|
||||
}
|
||||
boolean modified = false;
|
||||
String grade = "";
|
||||
int score = 0;
|
||||
String description = "";
|
||||
if (isUnHasField(json, "data", holder)) {
|
||||
grade = "-";
|
||||
score = -1;
|
||||
} else {
|
||||
JsonNode data = json.get("data");
|
||||
if (data.isNull()) {
|
||||
grade = "无";
|
||||
score = -1;
|
||||
} else {
|
||||
grade = data.get("scoreLevel").asText();
|
||||
score = data.get("score").asInt();
|
||||
description = data.get("scoreDes").asText();
|
||||
}
|
||||
}
|
||||
|
||||
if (updateText(cloudRk::getVendorGrade, cloudRk::setVendorGrade, grade, holder, "供应商信用得分")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateNumber(cloudRk::getVendorScore, cloudRk::setVendorScore, score, holder, "供应商信用总分")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(cloudRk::getVendorDescription, cloudRk::setVendorDescription, description, holder, "供应商信用评级说明")) {
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动获取到平台编号
|
||||
*
|
||||
* @param company 公司对象
|
||||
* @param cloudRk Cloud Rk
|
||||
* @return true 更新了 cloudId,否则false
|
||||
*/
|
||||
private boolean queryCloudIdAndSelectOne(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) {
|
||||
try {
|
||||
List<CloudRkService.EntInfo> entInfos = queryEnterpriseWithFuzzy(company, cloudRk, holder);
|
||||
// 返回的查询结果为空时
|
||||
if (entInfos.isEmpty()) {
|
||||
// 设置为 -, 不在重复查找
|
||||
cloudRk.setCloudId("-");
|
||||
holder.warn("在平台中没有匹配到 " + company.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 在返回的结果中,找到与公司名字一致的一个
|
||||
Optional<CloudRkService.EntInfo> optional = entInfos.stream().filter(n -> n.getName().equals(company.getName())).findAny();
|
||||
if (optional.isPresent()) {
|
||||
cloudRk.setCloudId(optional.get().getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
//
|
||||
holder.error("在平台中查询到多个匹配 (" + entInfos.stream().map(CloudRkService.EntInfo::getName).collect(Collectors.joining(", ")) + "),请手工同步选择匹配");
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
// 异常
|
||||
holder.error("查询接口获取企业平台编号发生错误 = " + e.getMessage());
|
||||
if (logger.isErrorEnabled()) {
|
||||
logger.error("使用模糊查询接口获取 {} 企业平台编号发生错误", company.getName(), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 使用模糊查询接口查询相关企业信息
|
||||
*/
|
||||
public List<CloudRkService.EntInfo> queryEnterpriseWithFuzzy(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
String url = getConfService().getString(CloudRkService.KEY_ENT_FUZZY_URL);
|
||||
List<CloudRkService.EntInfo> results = new ArrayList<>();
|
||||
ObjectMapper objectMapper = getObjectMapper();
|
||||
try {
|
||||
HttpJsonUtils.post(url, data -> {
|
||||
data.put("theKey", company.getName());
|
||||
data.put("get", true);
|
||||
}, json -> {
|
||||
applyEnterpriseQuery(json, company, cloudRk, results, holder);
|
||||
saveJsonToFile(company, json, "fuzzy.json", holder);
|
||||
}, objectMapper, getSocksProxy());
|
||||
} catch (IOException ex) {
|
||||
catchException(ex, holder);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private boolean applyEnterpriseQuery(JsonNode json, Company company, CloudRk cloudRk, List<CloudRkService.EntInfo> results, MessageHolder holder) {
|
||||
if (!json.has("data")) {
|
||||
// 没有数据
|
||||
holder.error("数据异常,返回的json中没有 data 字段");
|
||||
return false;
|
||||
}
|
||||
JsonNode dataNode = json.get("data");
|
||||
if (!dataNode.isArray()) {
|
||||
holder.error("数据异常,返回的json中 data 字段不是数组");
|
||||
return false;
|
||||
}
|
||||
ObjectMapper objectMapper = getObjectMapper();
|
||||
|
||||
for (JsonNode node : dataNode) {
|
||||
try {
|
||||
CloudRkService.EntInfo entInfo = new CloudRkService.EntInfo();
|
||||
objectMapper.updateValue(entInfo, node);
|
||||
if (node.has("isNowName")) {
|
||||
String s = node.get("isNowName").asText();
|
||||
entInfo.setNowName(s.equals("1") || s.equals("true"));
|
||||
}
|
||||
results.add(entInfo);
|
||||
} catch (Exception e) {
|
||||
holder.error("更新企业信息失败:" + e.getMessage() + ", json=" + node.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新企业工商注册信息
|
||||
*/
|
||||
public boolean updateEnterpriseInfo(
|
||||
Company company, CloudRk cloudRk, MessageHolder holder
|
||||
) throws IOException {
|
||||
String api = getConfService().getString(CloudRkService.KEY_ENT_REPORT_URL);
|
||||
Proxy socksProxy = getSocksProxy();
|
||||
holder.debug("更新企业工商注册信息: " + company.getName() + " @ " + api + ", proxy=" + socksProxy);
|
||||
AtomicBoolean modified = new AtomicBoolean(false);
|
||||
try {
|
||||
post(api, data -> {
|
||||
data.put("entName", company.getName());
|
||||
data.put("entid", cloudRk.getCloudId());
|
||||
data.put("get", true);
|
||||
data.put("method", "data");
|
||||
data.put("nodetype", "B1001");
|
||||
}, jsonNode -> {
|
||||
modified.set(applyEnterpriseInfo(jsonNode, company, cloudRk, holder));
|
||||
saveJsonToFile(company, jsonNode, FileUtils.FILE_B1001_JSON, holder);
|
||||
});
|
||||
} catch (IOException e) {
|
||||
catchException(e, holder);
|
||||
}
|
||||
return modified.get();
|
||||
}
|
||||
|
||||
private void catchException(IOException e, MessageHolder holder) throws IOException {
|
||||
if (e instanceof SSLException) {
|
||||
holder.error("网络错误:" + e.getMessage());
|
||||
// 网络错误时,抛出异常,中断后续网络请求
|
||||
throw e;
|
||||
}
|
||||
if (e instanceof SocketException) {
|
||||
holder.error("网络错误:" + e.getMessage());
|
||||
// 网络错误时,抛出异常,中断后续网络请求
|
||||
throw e;
|
||||
}
|
||||
holder.error(e.getMessage());
|
||||
}
|
||||
|
||||
private boolean applyEnterpriseInfo(JsonNode json, Company company, CloudRk cloudRk, MessageHolder holder) {
|
||||
if (!json.has("B1001")) {
|
||||
holder.error("数据异常,返回的json中没有 B1001 字段");
|
||||
return false;
|
||||
}
|
||||
JsonNode b1001 = json.get("B1001");
|
||||
if (!b1001.has("count") || b1001.get("count").asInt() < 1 || !b1001.has("data")) {
|
||||
holder.error("数据异常,B1001 字段没有数据");
|
||||
return false;
|
||||
}
|
||||
boolean modified = false;
|
||||
JsonNode data = b1001.get("data");
|
||||
if (updateText(company::getEntType, company::setEntType, data, "enttype", holder, "企业类型")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getEntStatus, company::setEntStatus, data, "entstatus", holder, "企业状态")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(company::getSetupDate, company::setSetupDate, data, "esdate", holder, "成立日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getUniscid, company::setUniscid, data, "uniscid", holder, "企业状态")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getRegAddr, company::setRegAddr, data, "dom", holder, "注册地址")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getRegisteredCapital, company::setRegisteredCapital, data, "regcap", holder, "注册资金")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getRegisteredCapitalCurrency, company::setRegisteredCapitalCurrency, data, "regcapcur", holder, "资本金币种")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getLegalRepresentative, company::setLegalRepresentative, data, "frname", holder, "法人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getDistrict, company::setDistrict, data, "regorgprovince", holder, "注册区域")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getTelephone, company::setTelephone, data, "tel", holder, "注册电话")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getAddress, company::setAddress, data, "oploc", holder, "通讯地址")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateOperationPeriodBegin(company, data, holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateOperationPeriodEnd(company, data, holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(company::getIndustry, company::setIndustry, data, "nicfulltitle", holder, "行业")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
updateCompanyNameHistory(company, data, holder.sub("曾用名"));
|
||||
updateLegalRepresentativeContact(company, data, holder.sub("法人联系方式"));
|
||||
updateInstant(cloudRk::getCloudEntUpdate, cloudRk::setCloudEntUpdate, data, "updated", holder, "更新时间", false);
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 更新法人联系人联系方式
|
||||
*/
|
||||
private void updateLegalRepresentativeContact(Company company, JsonNode data, MessageHolder holder) {
|
||||
String legalRepresentative = company.getLegalRepresentative();
|
||||
if (!StringUtils.hasText(legalRepresentative)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
CompanyContactService contactService = SpringApp.getBean(CompanyContactService.class);
|
||||
List<CompanyContact> contactList = contactService.findAllByCompanyAndName(company, legalRepresentative);
|
||||
if (contactList == null) {
|
||||
// db error
|
||||
return;
|
||||
}
|
||||
CompanyContact contact = null;
|
||||
boolean modified = false;
|
||||
if (contactList.isEmpty()) {
|
||||
//没有,创建法人联系人
|
||||
contact = new CompanyContact();
|
||||
contact.setCompany(company);
|
||||
contact.setName(legalRepresentative);
|
||||
contact.setPosition("法定代表人");
|
||||
contact.setCreated(LocalDate.now());
|
||||
modified = true;
|
||||
} else {
|
||||
// 先尝试查找法人
|
||||
Optional<CompanyContact> any = contactList.stream().filter(c -> "法定代表人".equals(c.getPosition())).findAny();
|
||||
// 如果没有找到,列表中第一个联系人
|
||||
if (any.isEmpty()) {
|
||||
any = contactList.stream().findFirst();
|
||||
}
|
||||
contact = any.get();
|
||||
if (updateText(contact::getPosition, contact::setPosition, "法定代表人", holder, "职位")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getEmail())) {
|
||||
if (updateText(contact::getEmail, contact::setEmail, data, "email", holder, "邮箱")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getAddress())) {
|
||||
if (updateText(contact::getAddress, contact::setAddress, data, "oploc", holder, "地址")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(contact.getPhone())) {
|
||||
if (updateText(contact::getPhone, contact::setPhone, data, "tel", holder, "电话")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
contactService.save(contact);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean updateOperationPeriodBegin(Company company, JsonNode data, MessageHolder holder) {
|
||||
return updateLocalDate(company::getOperationPeriodBegin, company::setOperationPeriodBegin, data, "opfrom", holder, "营业期限起始日期", true);
|
||||
}
|
||||
|
||||
private boolean updateOperationPeriodEnd(Company company, JsonNode data, MessageHolder holder) {
|
||||
JsonNode node = data.get("opto");
|
||||
if (node == null) {
|
||||
return false;
|
||||
}
|
||||
String text = node.asText();
|
||||
if (StringUtils.hasText(text)) {
|
||||
if (text.equals("-")) {
|
||||
return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, (LocalDate) null, holder, "营业期限截至日期", true);
|
||||
}
|
||||
return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, data, "opto", holder, "营业期限截至日期", true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
private void updateCompanyNameHistory(Company company, JsonNode data, MessageHolder holder) {
|
||||
JsonNode node = data.get("nameHistory");
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
// 历史曾用名
|
||||
String nameHistory = node.asText();
|
||||
if (!StringUtils.hasText(nameHistory)) {
|
||||
return;
|
||||
}
|
||||
List<String> historyNames = new ArrayList<>();
|
||||
for (String str : nameHistory.split(",")) {
|
||||
String trimmed = str.trim();
|
||||
if (StringUtils.hasText(trimmed)) {
|
||||
historyNames.add(trimmed);
|
||||
}
|
||||
}
|
||||
CompanyOldNameService service = SpringApp.getBean(CompanyOldNameService.class);
|
||||
List<CompanyOldName> oldNames = service.findAllByCompany(company);
|
||||
for (CompanyOldName oldName : oldNames) {
|
||||
// 已经存在的移除
|
||||
historyNames.remove(oldName.getName());
|
||||
}
|
||||
for (String historyName : historyNames) {
|
||||
CompanyOldName oldName = service.createNew(company, historyName, false);
|
||||
oldName.setMemo("从相关方平台导入");
|
||||
service.save(oldName);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field, MessageHolder holder, String topic, boolean allowNull) {
|
||||
JsonNode node = data.get(field);
|
||||
if (node == null || node.isNull()) {
|
||||
return false;
|
||||
}
|
||||
LocalDate localDate = getObjectMapper().convertValue(node, LocalDate.class);
|
||||
if (localDate == null && !allowNull) {
|
||||
return false;
|
||||
}
|
||||
return updateLocalDate(getter, setter, localDate, holder, topic, allowNull);
|
||||
}
|
||||
|
||||
private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field, MessageHolder holder, String topic) {
|
||||
return updateLocalDate(getter, setter, data, field, holder, topic, false);
|
||||
}
|
||||
|
||||
private void updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, JsonNode data, String field, MessageHolder holder, String topic, boolean allowNull) {
|
||||
JsonNode node = data.get("updated");
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
LocalDateTime updated = getObjectMapper().convertValue(node, LocalDateTime.class);
|
||||
if (updated == null) {
|
||||
if (!allowNull) {
|
||||
return;
|
||||
}
|
||||
updateInstant(getter, setter, null, holder, topic);
|
||||
return;
|
||||
}
|
||||
Instant instant = updated.toInstant(ZoneOffset.ofHours(8));
|
||||
updateInstant(getter, setter, instant, holder, topic);
|
||||
}
|
||||
|
||||
private boolean updateText(Supplier<String> getter, Consumer<String> setter, JsonNode data, String field, MessageHolder holder, String topic) {
|
||||
JsonNode node = data.get(field);
|
||||
if (node == null || node.isNull()) {
|
||||
return false;
|
||||
}
|
||||
String text = node.asText();
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return false;
|
||||
}
|
||||
return updateText(getter, setter, text, holder, topic);
|
||||
}
|
||||
|
||||
private void saveJsonToFile(Company company, JsonNode json, String fileName, MessageHolder holder) {
|
||||
String companyPath = company.getPath();
|
||||
if (!StringUtils.hasText(companyPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
File dir = new File(companyPath);
|
||||
if (!dir.exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
File file = new File(dir, fileName);
|
||||
try {
|
||||
getObjectMapper().writeValue(file, json);
|
||||
holder.debug("保存文件 " + file.getName());
|
||||
} catch (IOException e) {
|
||||
holder.error("保存文件 " + file.getName() + " 发生错误:" + e.getMessage());
|
||||
logger.error("Save {}", file.getAbsolutePath(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudRk getOrCreateCloudRk(Company company) {
|
||||
return getCloudRkService().getOrCreateCloudRk(company);
|
||||
}
|
||||
|
||||
public CloudRk save(CloudRk cloudRk) {
|
||||
return getCloudRkService().save(cloudRk);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ecep.contract.cloud.tyc;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.CloudTyc;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
@Repository
|
||||
public interface CloudTycRepository extends MyRepository<CloudTyc, Integer> {
|
||||
|
||||
List<CloudTyc> findAllByCompanyId(Integer companyId);
|
||||
|
||||
Optional<CloudTyc> findByCompanyId(Integer companyId);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
int deleteAllByCompany(Company company);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.ecep.contract.cloud.tyc;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.cloud.CloudInfo;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.model.CloudTyc;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
public class CloudTycService implements IEntityService<CloudTyc> {
|
||||
public final static String TYC_ENTERPRISE_ANALYSIS_REPORT = "企业分析报告";
|
||||
public final static String TYC_ENTERPRISE_BASIC_REPORT = "基础版企业信用报告";
|
||||
public final static String TYC_ENTERPRISE_MAJOR_REPORT = "专业版企业信用报告";
|
||||
public final static String TYC_ENTERPRISE_CREDIT_REPORT = "企业信用信息公示报告";
|
||||
public static final String URL_COMPANY = "https://www.tianyancha.com/company/%s";
|
||||
public static final String URL_COMPANY_SEARCH = "https://www.tianyancha.com/search?key=%s";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudTycService.class);
|
||||
|
||||
/**
|
||||
* 天眼查报告,文件名中必须包含 天眼查 字样
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @return 是否是天眼查报告
|
||||
*/
|
||||
public static boolean isTycReport(String fileName) {
|
||||
// 文件名中包含 天眼查 字样
|
||||
return fileName.contains(CloudServiceConstant.TYC_NAME);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private CloudTycRepository cloudTycRepository;
|
||||
|
||||
public CloudTyc getOrCreateCloudTyc(CloudInfo info) {
|
||||
Optional<CloudTyc> optional = cloudTycRepository.findById(info.getId());
|
||||
return optional.orElseGet(() -> getOrCreateCloudTyc(info.getCompany()));
|
||||
}
|
||||
|
||||
public CloudTyc getOrCreateCloudTyc(Company company) {
|
||||
Integer companyId = company.getId();
|
||||
List<CloudTyc> list = cloudTycRepository.findAllByCompanyId(companyId);
|
||||
if (list.isEmpty()) {
|
||||
CloudTyc tyc = new CloudTyc();
|
||||
tyc.setCompany(company);
|
||||
tyc.setScore(-1);
|
||||
tyc.setCloudLatest(null);
|
||||
return cloudTycRepository.save(tyc);
|
||||
}
|
||||
if (list.size() == 1) {
|
||||
return list.getFirst();
|
||||
}
|
||||
|
||||
// 查询有 CloudId 的记录
|
||||
List<CloudTyc> hasCouldIdList = list.stream()
|
||||
.filter(v -> {
|
||||
return StringUtils.hasText(v.getCloudId())
|
||||
&& MyStringUtils.isAllDigit(v.getCloudId());
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 没有匹配到一条时
|
||||
if (hasCouldIdList.isEmpty()) {
|
||||
// 保留第一条,其他删除
|
||||
CloudTyc rk = list.removeFirst();
|
||||
cloudTycRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 只有匹配到一条有 CloudId 的记录
|
||||
if (hasCouldIdList.size() == 1) {
|
||||
// 保留匹配的记录,其他删除
|
||||
CloudTyc rk = hasCouldIdList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudTycRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 查询有 Score 的记录
|
||||
List<CloudTyc> hasLatestList = hasCouldIdList.stream().filter(v -> {
|
||||
return v.getScore() != null && v.getScore() > 0;
|
||||
}).collect(Collectors.toList());
|
||||
// 没有匹配到一条时
|
||||
if (hasLatestList.isEmpty()) {
|
||||
// 保留第一条,其他删除
|
||||
CloudTyc rk = hasCouldIdList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudTycRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
// 只有匹配到一条有 CloudId 的记录
|
||||
if (hasLatestList.size() == 1) {
|
||||
// 保留匹配的记录,其他删除
|
||||
CloudTyc rk = hasLatestList.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudTycRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
return hasLatestList.getFirst();
|
||||
|
||||
}
|
||||
|
||||
public CloudTyc save(CloudTyc cloudTyc) {
|
||||
return cloudTycRepository.save(cloudTyc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(CloudTyc entity) {
|
||||
cloudTycRepository.delete(entity);
|
||||
}
|
||||
|
||||
|
||||
public void deleteByCompany(Company company) {
|
||||
int deleted = cloudTycRepository.deleteAllByCompany(company);
|
||||
if (deleted > 0) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete {} records by company:#{}", deleted, company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void resetTo(Company from, Company to) {
|
||||
List<CloudTyc> list = cloudTycRepository.findAllByCompanyId(from.getId());
|
||||
for (CloudTyc item : list) {
|
||||
item.setCompany(to);
|
||||
}
|
||||
cloudTycRepository.saveAll(list);
|
||||
}
|
||||
|
||||
public CloudTyc findById(Integer id) {
|
||||
return cloudTycRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Page<CloudTyc> findAll(Specification<CloudTyc> spec, PageRequest pageable) {
|
||||
return cloudTycRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public Page<CloudTyc> findAll(Specification<CloudTyc> spec, Pageable pageable) {
|
||||
return cloudTycRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CloudTyc> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.like(root.get("cloudId"), "%" + searchText + "%");
|
||||
};
|
||||
}
|
||||
|
||||
public void syncCompany(Company company, MessageHolder holder) {
|
||||
// TODO 从天眼查同步公司信息
|
||||
holder.warn("TODO 未实现");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
@Repository
|
||||
public interface CloudYuRepository extends MyRepository<CloudYu, Integer> {
|
||||
|
||||
List<CloudYu> findAllByCompanyId(Integer companyId);
|
||||
|
||||
Optional<CloudYu> findByCompanyId(Integer companyId);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
int deleteAllByCompany(Company company);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.contract.service.ContractGroupService;
|
||||
import com.ecep.contract.model.ContractGroup;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步合同分组
|
||||
*/
|
||||
public class ContractGroupSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContractGroupSyncTask.class);
|
||||
@Setter
|
||||
private ContractGroupService contractGroupService;
|
||||
|
||||
public ContractGroupSyncTask() {
|
||||
updateTitle("用友U8系统-同步合同分组信息");
|
||||
}
|
||||
|
||||
ContractGroupService getContractGroupService() {
|
||||
if (contractGroupService == null) {
|
||||
contractGroupService = SpringApp.getBean(ContractGroupService.class);
|
||||
}
|
||||
return contractGroupService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Service service = null;
|
||||
try {
|
||||
service = SpringApp.getBean(YongYouU8Service.class);
|
||||
} catch (BeansException e) {
|
||||
logger.error("can't get bean of YongYouU8Service", e);
|
||||
holder.error("can't get bean of YongYouU8Service");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("读取 U8 系统 CM_Group 数据表...");
|
||||
List<Map<String, Object>> list = service.queryAllContractGroup();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 CM_Group 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> map : list) {
|
||||
if (isCancelled()) {
|
||||
holder.info("Cancelled");
|
||||
return null;
|
||||
}
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(map, sub);
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> map, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
|
||||
String groupCode = (String) map.get("cGroupID");
|
||||
String groupName = (String) map.get("cGroupName");
|
||||
String groupTitle = (String) map.get("cRemark");
|
||||
|
||||
ContractGroupService service = getContractGroupService();
|
||||
ContractGroup contractGroup = service.findByCode(groupCode);
|
||||
if (contractGroup == null) {
|
||||
contractGroup = service.newContractGroup();
|
||||
holder.info("新建合同分组:" + groupCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(contractGroup.getCode(), groupCode)) {
|
||||
contractGroup.setCode(groupCode);
|
||||
holder.info("合同分组代码:" + contractGroup.getCode() + " -> " + groupCode);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractGroup.getName(), groupName)) {
|
||||
contractGroup.setName(groupName);
|
||||
holder.info("合同分组名称:" + contractGroup.getName() + " -> " + groupName);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractGroup.getTitle(), groupTitle)) {
|
||||
contractGroup.setTitle(groupTitle);
|
||||
holder.info("合同分组标题:" + contractGroup.getTitle() + " -> " + groupTitle);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
service.save(contractGroup);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.contract.service.ContractKindService;
|
||||
import com.ecep.contract.model.ContractKind;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步合同分类
|
||||
*/
|
||||
public class ContractKindSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContractKindSyncTask.class);
|
||||
@Setter
|
||||
private ContractKindService contractKindService;
|
||||
|
||||
public ContractKindSyncTask() {
|
||||
updateTitle("用友U8系统-同步合同分类信息");
|
||||
}
|
||||
|
||||
ContractKindService getContractKindService() {
|
||||
if (contractKindService == null) {
|
||||
contractKindService = SpringApp.getBean(ContractKindService.class);
|
||||
}
|
||||
return contractKindService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Repository repository = null;
|
||||
try {
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
} catch (BeansException e) {
|
||||
logger.error("can't get bean of YongYouU8Repository", e);
|
||||
holder.error("can't get bean of YongYouU8Repository");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("读取 U8 系统 CM_Kind 数据表...");
|
||||
List<Map<String, Object>> list = repository.queryAllContractKind();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 CM_Kind 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> map : list) {
|
||||
if (isCancelled()) {
|
||||
holder.info("Cancelled");
|
||||
return null;
|
||||
}
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(map, sub);
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> map, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
|
||||
String typeCode = (String) map.get("KindID");
|
||||
String typeName = (String) map.get("KindName");
|
||||
String typeTitle = (String) map.get("Description");
|
||||
|
||||
ContractKindService kindService = getContractKindService();
|
||||
ContractKind contractKind = kindService.findByCode(typeCode);
|
||||
if (contractKind == null) {
|
||||
contractKind = new ContractKind();
|
||||
holder.info("新建合同分类:" + typeCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(contractKind.getCode(), typeCode)) {
|
||||
contractKind.setCode(typeCode);
|
||||
holder.info("合同分类代码:" + contractKind.getCode() + " -> " + typeCode);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractKind.getName(), typeName)) {
|
||||
contractKind.setName(typeName);
|
||||
holder.info("合同分类名称:" + contractKind.getName() + " -> " + typeName);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractKind.getTitle(), typeTitle)) {
|
||||
contractKind.setTitle(typeTitle);
|
||||
holder.info("合同分类描述:" + contractKind.getTitle() + " -> " + typeTitle);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
kindService.save(contractKind);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
|
||||
|
||||
/**
|
||||
* 用友U8系统-同步全量合同
|
||||
*/
|
||||
public class ContractSyncAllTask extends AbstContractRepairTasker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContractSyncAllTask.class);
|
||||
|
||||
|
||||
@Override
|
||||
protected void repair(MessageHolder holder) {
|
||||
updateTitle("用友U8系统-同步全量合同");
|
||||
YongYouU8Repository repository = getBean(YongYouU8Repository.class);
|
||||
|
||||
long total = repository.countAllContracts();
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
try (Stream<Map<String, Object>> stream = repository.queryAllContractForStream()) {
|
||||
stream.forEach(rs -> {
|
||||
if (isCancelled()) {
|
||||
holder.debug("Cancelled");
|
||||
return;
|
||||
}
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> ");
|
||||
try {
|
||||
repairFromCMList(rs, subHolder);
|
||||
} catch (Exception e) {
|
||||
updateMessage(e.getMessage());
|
||||
logger.error("data = {}", rs, e);
|
||||
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.contract.service.ContractGroupService;
|
||||
import com.ecep.contract.ds.contract.service.ContractKindService;
|
||||
import com.ecep.contract.ds.contract.service.ContractTypeService;
|
||||
import com.ecep.contract.ds.other.service.EmployeeService;
|
||||
import com.ecep.contract.model.ContractGroup;
|
||||
import com.ecep.contract.model.ContractKind;
|
||||
import com.ecep.contract.model.ContractType;
|
||||
import com.ecep.contract.model.Employee;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class ContractSyncContext {
|
||||
<T> T getBean(Class<T> requiredType) throws BeansException {
|
||||
return SpringApp.getBean(requiredType);
|
||||
}
|
||||
|
||||
private ContractTypeService contractTypeService;
|
||||
private ContractGroupService contractGroupService;
|
||||
private ContractKindService contractKindService;
|
||||
private EmployeeService employeeService;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
Consumer<String> consumer;
|
||||
|
||||
public ContractSyncContext() {
|
||||
}
|
||||
|
||||
private ContractTypeService getContractTypeService() {
|
||||
if (contractTypeService == null) {
|
||||
contractTypeService = getBean(ContractTypeService.class);
|
||||
}
|
||||
return contractTypeService;
|
||||
}
|
||||
|
||||
private ContractGroupService getContractGroupService() {
|
||||
if (contractGroupService == null) {
|
||||
contractGroupService = getBean(ContractGroupService.class);
|
||||
}
|
||||
return contractGroupService;
|
||||
}
|
||||
|
||||
private ContractKindService getContractKindService() {
|
||||
if (contractKindService == null) {
|
||||
contractKindService = getBean(ContractKindService.class);
|
||||
}
|
||||
return contractKindService;
|
||||
}
|
||||
|
||||
private EmployeeService getEmployeeService() {
|
||||
if (employeeService == null) {
|
||||
employeeService = getBean(EmployeeService.class);
|
||||
}
|
||||
return employeeService;
|
||||
}
|
||||
|
||||
public ContractType getTypeByCode(String typeCode) {
|
||||
return getContractTypeService().findByCode(typeCode);
|
||||
}
|
||||
|
||||
public ContractGroup getGroupByCode(String groupCode) {
|
||||
return getContractGroupService().findByCode(groupCode);
|
||||
}
|
||||
|
||||
public ContractKind getKindByName(String kindName) {
|
||||
return getContractKindService().findByName(kindName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void updateMessage(String message) {
|
||||
Consumer<String> consumer = getConsumer();
|
||||
if (consumer != null) {
|
||||
consumer.accept(message);
|
||||
}
|
||||
}
|
||||
public Employee findEmployeeByCode(String personCode) {
|
||||
return getEmployeeService().findByCode(personCode);
|
||||
}
|
||||
public Employee findEmployeeByName(String personName) {
|
||||
if (personName == null) {
|
||||
return null;
|
||||
}
|
||||
return getEmployeeService().findByName(personName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.u8.ctx.ContractCtx;
|
||||
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
|
||||
|
||||
/**
|
||||
* 合同同步任务
|
||||
*/
|
||||
public class ContractSyncTask extends AbstContractRepairTasker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContractSyncTask.class);
|
||||
private YongYouU8Repository repository;
|
||||
|
||||
public ContractSyncTask() {
|
||||
updateTitle("用友U8系统-同步合同");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void repair(MessageHolder holder) {
|
||||
updateTitle("用友U8系统-同步合同");
|
||||
try {
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
} catch (BeansException e) {
|
||||
holder.error("无法获取 YongYouU8Repository " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
if (getConfService().getBoolean(ContractCtx.KEY_SYNC_USE_LATEST_ID)) {
|
||||
syncByLatestId(holder);
|
||||
} else {
|
||||
syncByLatestDate(holder);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncByLatestId(MessageHolder holder) {
|
||||
int latestId = getConfService().getInt(ContractCtx.KEY_SYNC_BY_LATEST_ID);
|
||||
updateTitle("用友U8系统-同步合同,从 " + latestId + " 开始");
|
||||
|
||||
Long total = repository.countAllContracts(latestId);
|
||||
updateTitle("用友U8系统-同步合同,从 " + latestId + " 开始,合计 " + total + " 条");
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("sync latest Id from {}, have {} record.", latestId, total);
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
AtomicReference<Integer> reference = new AtomicReference<>(latestId);
|
||||
try (Stream<Map<String, Object>> stream = repository.queryAllContractForStream(latestId)) {
|
||||
stream.forEach(rs -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> ");
|
||||
try {
|
||||
Integer ID = (Integer) rs.get("ID");
|
||||
repairFromCMList(rs, subHolder);
|
||||
if (ID != null) {
|
||||
Integer latest = reference.get();
|
||||
if (latest == null || ID.compareTo(latest) > 0) {
|
||||
reference.set(ID);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("Contract sync failure {}, data = {}", e.getMessage(), rs, e);
|
||||
updateMessage(e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
});
|
||||
}
|
||||
getConfService().set(ContractCtx.KEY_SYNC_BY_LATEST_ID, String.valueOf(reference.get()));
|
||||
}
|
||||
|
||||
private void syncByLatestDate(MessageHolder holder) {
|
||||
String strDateTime = getConfService().getString(ContractCtx.KEY_SYNC_BY_LATEST_DATE);
|
||||
LocalDateTime latestDateTime = null;
|
||||
if (StringUtils.hasText(strDateTime)) {
|
||||
try {
|
||||
latestDateTime = LocalDateTime.parse(strDateTime);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
if (latestDateTime == null) {
|
||||
latestDateTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
|
||||
}
|
||||
updateTitle("用友U8系统-同步合同,从 " + latestDateTime + " 开始");
|
||||
|
||||
Long total = repository.countAllContracts(latestDateTime);
|
||||
updateTitle("用友U8系统-同步合同,从 " + latestDateTime + " 开始,合计 " + total + " 条");
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("from latest date {}, have {} record.", latestDateTime, total);
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
AtomicReference<LocalDateTime> reference = new AtomicReference<>(latestDateTime);
|
||||
|
||||
try (Stream<Map<String, Object>> stream = repository.queryAllContractForStream(latestDateTime)) {
|
||||
stream.forEach(rs -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> ");
|
||||
try {
|
||||
Timestamp dtDate = (Timestamp) rs.get("dtDate");
|
||||
|
||||
repairFromCMList(rs, subHolder);
|
||||
|
||||
if (dtDate != null) {
|
||||
LocalDateTime latest = reference.get();
|
||||
LocalDateTime localDate = dtDate.toLocalDateTime();
|
||||
if (latest == null || localDate.isAfter(latest)) {
|
||||
reference.set(localDate);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Contract sync failure {}, data = {}", e.getMessage(), rs, e);
|
||||
updateMessage(e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
});
|
||||
}
|
||||
getConfService().set(ContractCtx.KEY_SYNC_BY_LATEST_DATE, String.valueOf(reference.get()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.contract.service.ContractTypeService;
|
||||
import com.ecep.contract.model.ContractType;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步合同类型
|
||||
*/
|
||||
public class ContractTypeSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContractTypeSyncTask.class);
|
||||
@Setter
|
||||
private ContractTypeService contractTypeService;
|
||||
|
||||
public ContractTypeSyncTask() {
|
||||
updateTitle("用友U8系统-同步合同类型信息");
|
||||
}
|
||||
|
||||
ContractTypeService getContractTypeService() {
|
||||
if (contractTypeService == null) {
|
||||
contractTypeService = SpringApp.getBean(ContractTypeService.class);
|
||||
}
|
||||
return contractTypeService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Repository repository = null;
|
||||
try {
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
} catch (BeansException e) {
|
||||
logger.error("can't get bean of YongYouU8Service", e);
|
||||
holder.error("can't get bean of YongYouU8Service");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("读取 U8 系统 CM_Type,CM_TypeClass 数据表...");
|
||||
List<Map<String, Object>> list = repository.queryAllContractType();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 CM_Type,CM_TypeClass 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> map : list) {
|
||||
if (isCancelled()) {
|
||||
holder.info("Cancelled");
|
||||
return null;
|
||||
}
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(map, sub);
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> map, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
|
||||
String typeCode = (String) map.get("cTypeCode");
|
||||
String typeName = (String) map.get("cTypeName");
|
||||
String typeTitle = (String) map.get("cCharacter");
|
||||
String typeCatalog = (String) map.get("cClassName");
|
||||
String typeDirection = (String) map.get("cDirection");
|
||||
|
||||
ContractTypeService typeService = getContractTypeService();
|
||||
ContractType contractType = typeService.findByCode(typeCode);
|
||||
if (contractType == null) {
|
||||
contractType = new ContractType();
|
||||
holder.info("新建合同类型:" + typeCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(contractType.getCode(), typeCode)) {
|
||||
contractType.setCode(typeCode);
|
||||
holder.info("合同类型代码:" + contractType.getCode() + " -> " + typeCode);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractType.getName(), typeName)) {
|
||||
contractType.setName(typeName);
|
||||
holder.info("合同类型名称:" + contractType.getName() + " -> " + typeName);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractType.getTitle(), typeTitle)) {
|
||||
contractType.setTitle(typeTitle);
|
||||
holder.info("合同类型标题:" + contractType.getTitle() + " -> " + typeTitle);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractType.getCatalog(), typeCatalog)) {
|
||||
contractType.setCatalog(typeCatalog);
|
||||
holder.info("合同类型分类:" + contractType.getCatalog() + " -> " + typeCatalog);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(contractType.getDirection(), typeDirection)) {
|
||||
contractType.setDirection(typeDirection);
|
||||
holder.info("合同类型方向:" + contractType.getDirection() + " -> " + typeDirection);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
typeService.save(contractType);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
|
||||
import com.ecep.contract.model.CustomerCatalog;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步客户分类
|
||||
*/
|
||||
public class CustomerClassSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomerClassSyncTask.class);
|
||||
@Setter
|
||||
private CompanyCustomerService companyCustomerService;
|
||||
|
||||
public CustomerClassSyncTask() {
|
||||
updateTitle("用友U8系统-同步客户分类信息");
|
||||
}
|
||||
|
||||
CompanyCustomerService getCompanyCustomerService() {
|
||||
if (companyCustomerService == null) {
|
||||
companyCustomerService = SpringApp.getBean(CompanyCustomerService.class);
|
||||
}
|
||||
return companyCustomerService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Repository repository = null;
|
||||
try {
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
} catch (BeansException e) {
|
||||
logger.error("can't get bean of YongYouU8Repository", e);
|
||||
holder.error("can't get bean of YongYouU8Repository");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("读取 U8 系统 CustomerClass 数据表...");
|
||||
List<Map<String, Object>> list = repository.queryAllCustomerClass();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 CustomerClass 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> map : list) {
|
||||
if (isCancelled()) {
|
||||
holder.info("Cancelled");
|
||||
return null;
|
||||
}
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(map, sub);
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> map, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
|
||||
String code = (String) map.get("cCCCode");
|
||||
String name = (String) map.get("cCCName");
|
||||
|
||||
CompanyCustomerService customerService = getCompanyCustomerService();
|
||||
CustomerCatalog customerCatalog = customerService.findCatalogByCode(code);
|
||||
if (customerCatalog == null) {
|
||||
customerCatalog = new CustomerCatalog();
|
||||
holder.info("新建客户分类:" + code);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(customerCatalog.getCode(), code)) {
|
||||
customerCatalog.setCode(code);
|
||||
holder.info("客户分类代码:" + customerCatalog.getCode() + " -> " + code);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(customerCatalog.getName(), name)) {
|
||||
customerCatalog.setName(name);
|
||||
holder.info("客户分类名称:" + customerCatalog.getName() + " -> " + name);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
customerService.save(customerCatalog);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.u8.ctx.CompanyCtx;
|
||||
import com.ecep.contract.cloud.u8.ctx.CustomerCtx;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyCustomer;
|
||||
import com.ecep.contract.model.CompanyCustomerEntity;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步客户任务
|
||||
*/
|
||||
public class CustomerSyncTask extends AbstContractRepairTasker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomerSyncTask.class);
|
||||
private YongYouU8Repository repository;
|
||||
private final CustomerCtx customerCtx = new CustomerCtx();
|
||||
@Setter
|
||||
private YongYouU8Service yongYouU8Service;
|
||||
|
||||
public CustomerSyncTask() {
|
||||
updateTitle("用友U8系统-同步客户");
|
||||
}
|
||||
|
||||
private CompanyCustomerService getCompanyCustomerService() {
|
||||
return customerCtx.getCompanyCustomerService();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void repair(MessageHolder holder) {
|
||||
try {
|
||||
yongYouU8Service = getBean(YongYouU8Service.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
|
||||
return;
|
||||
}
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
yongYouU8Service.initialize(customerCtx);
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
Long total = repository.countAllCustomers();
|
||||
updateTitle("用友U8系统-同步客户,合计 " + total + " 条");
|
||||
try (Stream<Map<String, Object>> stream = repository.queryAllCustomerForStream()) {
|
||||
stream.forEach(rs -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String cusCode = (String) rs.get("cCusCode");
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> " + cusCode + " ");
|
||||
boolean modified = false;
|
||||
CompanyCustomerEntity entity = customerCtx.findOrCreateByCode(rs, cusCode, subHolder);
|
||||
Map<String, Object> map = repository.findCustomerByCusCode(entity.getCode());
|
||||
if (map == null) {
|
||||
subHolder.error("客户项不存在:" + cusCode);
|
||||
return;
|
||||
}
|
||||
if (customerCtx.applyEntityDetail(entity, map, subHolder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (modified) {
|
||||
entity = customerCtx.getCompanyCustomerEntityService().save(entity);
|
||||
}
|
||||
updateCompanyNameAndAbbName(entity, subHolder);
|
||||
updateCloudYu(entity);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("Customer sync failure {}, data = {}", e.getMessage(), rs, e);
|
||||
updateMessage(e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCloudYu(CompanyCustomerEntity entity) {
|
||||
CompanyCustomer customer = entity.getCustomer();
|
||||
if (customer == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(customer)) {
|
||||
customer = getCompanyCustomerService().findById(customer.getId());
|
||||
}
|
||||
Company company = customer.getCompany();
|
||||
if (company == null) {
|
||||
return;
|
||||
}
|
||||
CloudYu cloudYu = yongYouU8Service.getOrCreateCloudYu(company);
|
||||
if (cloudYu == null) {
|
||||
return;
|
||||
}
|
||||
cloudYu.setCustomerUpdateDate(LocalDate.now());
|
||||
cloudYu.setCloudLatest(Instant.now());
|
||||
cloudYu.setExceptionMessage("");
|
||||
yongYouU8Service.save(cloudYu);
|
||||
|
||||
}
|
||||
|
||||
private void updateCompanyNameAndAbbName(CompanyCustomerEntity entity, MessageHolder holder) {
|
||||
CompanyService companyService = customerCtx.getCompanyService();
|
||||
CompanyCustomer customer = entity.getCustomer();
|
||||
if (customer == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(customer)) {
|
||||
customer = getCompanyCustomerService().findById(customer.getId());
|
||||
}
|
||||
Company company = customer.getCompany();
|
||||
if (company == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = companyService.findById(company.getId());
|
||||
}
|
||||
boolean modified = false;
|
||||
CompanyCtx companyCtx = customerCtx.getCompanyCtx();
|
||||
if (companyCtx.updateCompanyNameIfAbsent(company, entity.getName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (companyCtx.updateCompanyAbbNameIfAbsent(company, entity.getAbbName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (modified) {
|
||||
companyService.save(company);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.CloudInfo;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 数据迁移任务,从CloudInfo迁移到CloudYu
|
||||
*/
|
||||
public class DateTransferTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateTransferTask.class);
|
||||
@Setter
|
||||
private YongYouU8Service yongYouU8Service;
|
||||
|
||||
public DateTransferTask() {
|
||||
updateTitle("用友U8系统-数据迁移任务");
|
||||
}
|
||||
|
||||
YongYouU8Service getYongYouU8Service() {
|
||||
if (yongYouU8Service == null) {
|
||||
yongYouU8Service = SpringApp.getBean(YongYouU8Service.class);
|
||||
}
|
||||
return yongYouU8Service;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Service u8Service = null;
|
||||
try {
|
||||
u8Service = getYongYouU8Service();
|
||||
} catch (BeansException e) {
|
||||
logger.error("获取用友U8服务失败", e);
|
||||
holder.error("获取用友U8服务失败");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("开始数据迁移任务...");
|
||||
Iterable<CloudInfo> cloudInfos = u8Service.findAllCloudYu();
|
||||
|
||||
// 计算总数
|
||||
int total = 0;
|
||||
for (@SuppressWarnings("unused")
|
||||
CloudInfo info : cloudInfos) {
|
||||
total++;
|
||||
}
|
||||
holder.debug("总共需要迁移的数据量: " + total + " 条");
|
||||
|
||||
// 重新获取Iterable以进行遍历
|
||||
cloudInfos = u8Service.findAllCloudYu();
|
||||
|
||||
for (CloudInfo v : cloudInfos) {
|
||||
if (isCancelled()) {
|
||||
holder.info("迁移任务已取消");
|
||||
return null;
|
||||
}
|
||||
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + total + ">");
|
||||
try {
|
||||
sync(v, sub);
|
||||
} catch (Exception e) {
|
||||
sub.error("迁移失败: " + e.getMessage());
|
||||
logger.error("迁移数据失败", e);
|
||||
}
|
||||
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
}
|
||||
|
||||
holder.info("数据迁移任务完成");
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(CloudInfo v, MessageHolder holder) {
|
||||
YongYouU8Service u8Service = getYongYouU8Service();
|
||||
CloudYu cloudYu = u8Service.getOrCreateCloudYu(v);
|
||||
|
||||
if (copyTo(v, cloudYu)) {
|
||||
u8Service.save(cloudYu);
|
||||
holder.info("成功迁移数据: " + v.getCloudId());
|
||||
} else {
|
||||
holder.debug("数据未变更,无需迁移: " + v.getCloudId());
|
||||
}
|
||||
}
|
||||
|
||||
boolean copyTo(CloudInfo v, CloudYu cloudRk) {
|
||||
boolean modified = false;
|
||||
if (!Objects.equals(cloudRk.getLatestUpdate(), v.getLatestUpdate())) {
|
||||
cloudRk.setLatestUpdate(v.getLatestUpdate());
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(cloudRk.getCompany(), v.getCompany())) {
|
||||
cloudRk.setCompany(v.getCompany());
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.other.service.DepartmentService;
|
||||
import com.ecep.contract.model.Department;
|
||||
import com.ecep.contract.model.Employee;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
/**
|
||||
* 用友U8系统-同步员工信息
|
||||
*/
|
||||
public class EmployeesSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(EmployeesSyncTask.class);
|
||||
private final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
DepartmentService departmentService;
|
||||
|
||||
public EmployeesSyncTask() {
|
||||
updateTitle("用友U8系统-同步员工信息");
|
||||
}
|
||||
|
||||
DepartmentService getDepartmentService() {
|
||||
if (departmentService == null) {
|
||||
departmentService = SpringApp.getBean(DepartmentService.class);
|
||||
}
|
||||
return departmentService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Service service = SpringApp.getBean(YongYouU8Service.class);
|
||||
|
||||
holder.debug("读取 U8 系统 Person 数据表...");
|
||||
List<Map<String, Object>> list = service.queryAllPerson();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 Person 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> rs : list) {
|
||||
if (isCancelled()) {
|
||||
holder.debug("Cancelled");
|
||||
return null;
|
||||
}
|
||||
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(rs, sub);
|
||||
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> rs, MessageHolder holder) {
|
||||
String personCode = (String) rs.get("cPersonCode");
|
||||
String personName = (String) rs.get("cPersonName");
|
||||
String departmentCode = (String) rs.get("cDepCode");
|
||||
String personEmail = (String) rs.get("cPersonEmail");
|
||||
String personPhone = (String) rs.get("cPersonPhone");
|
||||
java.sql.Timestamp personValidDate = (java.sql.Timestamp) rs.get("dPValidDate");
|
||||
java.sql.Timestamp personInValidDate = (java.sql.Timestamp) rs.get("dPInValidDate");
|
||||
boolean modified = false;
|
||||
|
||||
Employee employee = getEmployeeService().findByCode(personCode);
|
||||
// 按员工代码未匹配时,尝试使用名字去匹配
|
||||
if (employee == null) {
|
||||
employee = getEmployeeService().findByName(personName);
|
||||
if (employee == null) {
|
||||
employee = new Employee();
|
||||
employee.setCode(personCode);
|
||||
employee.setName(personName);
|
||||
employee.setActive(false);
|
||||
employee.setCreated(LocalDate.now());
|
||||
holder.info("创建员工:" + personCode + ", 姓名:" + personName + ".");
|
||||
|
||||
// consumer.accept("员工编号:" + personCode + ", 姓名:" + personName + ", 本地未创建");
|
||||
// return;
|
||||
}
|
||||
employee.setCode(personCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
MessageHolder subHolder = holder.sub(personName + ": ");
|
||||
|
||||
if (!StringUtils.hasText(employee.getName())) {
|
||||
employee.setName(personName);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(departmentCode)) {
|
||||
Department departmentByCode = getDepartmentService().findByCode(departmentCode);
|
||||
if (departmentByCode == null) {
|
||||
subHolder.warn("部门代码:" + departmentCode + "未匹配到部门");
|
||||
} else {
|
||||
if (!Objects.equals(employee.getDepartment(), departmentByCode)) {
|
||||
employee.setDepartment(departmentByCode);
|
||||
subHolder.info("更新部门:" + departmentByCode.getName());
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(personPhone)) {
|
||||
if (!Objects.equals(personPhone, employee.getPhone())) {
|
||||
employee.setPhone(personPhone);
|
||||
subHolder.info("更新电话:" + personPhone);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(personEmail)) {
|
||||
if (!Objects.equals(personEmail, employee.getEmail())) {
|
||||
employee.setEmail(personEmail);
|
||||
subHolder.info("更新Email:" + personEmail);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (personValidDate != null) {
|
||||
LocalDate localDate = personValidDate.toLocalDateTime().toLocalDate();
|
||||
if (!Objects.equals(localDate, employee.getEntryDate())) {
|
||||
employee.setEntryDate(localDate);
|
||||
subHolder.info("更新入职日期:" + localDate);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (personInValidDate != null) {
|
||||
LocalDate localDate = personInValidDate.toLocalDateTime().toLocalDate();
|
||||
if (!Objects.equals(localDate, employee.getLeaveDate())) {
|
||||
employee.setLeaveDate(localDate);
|
||||
subHolder.info("更新离职日期:" + localDate);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
getEmployeeService().save(employee);
|
||||
subHolder.info("更新保存");
|
||||
} else {
|
||||
subHolder.debug("无更新");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
|
||||
import com.ecep.contract.ds.other.service.SysConfService;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Lazy
|
||||
@Component
|
||||
@ConditionalOnBean(YongYouU8Service.class)
|
||||
public class U8DataSourceFactory {
|
||||
@Lazy
|
||||
@Autowired
|
||||
private SysConfService service;
|
||||
|
||||
public U8DataSourceFactory() {
|
||||
System.out.println("U8DataSourceFactory.U8DataSourceFactory");
|
||||
}
|
||||
|
||||
@Lazy
|
||||
@Bean
|
||||
// @ConfigurationProperties(prefix = "u8.datasource")
|
||||
public DataSource MSSQL_Server() {
|
||||
System.out.println("U8DataSourceFactory.MSSQL_Server");
|
||||
|
||||
String host = service.get("u8.db.server.ip", "192.168.1.1");
|
||||
String database = service.get("u8.db.database", "UF_DATA");
|
||||
String username = service.get("u8.db.server.name", "sa");
|
||||
String password = service.get("u8.db.server.password", "");
|
||||
boolean encrypt = service.get("u8.db.server.encrypt", false);
|
||||
boolean trustServerCertificate = service.get("u8.db.server.trustServerCertificate", true);
|
||||
|
||||
String url = "jdbc:sqlserver://" +
|
||||
host +
|
||||
";databaseName=" +
|
||||
database +
|
||||
";encrypt=" +
|
||||
encrypt +
|
||||
";trustServerCertificate=" +
|
||||
trustServerCertificate
|
||||
// + ";sslProtocol=TLSv1"
|
||||
;
|
||||
|
||||
HikariDataSource source = DataSourceBuilder.create()
|
||||
.type(HikariDataSource.class)
|
||||
.url(url)
|
||||
.username(username)
|
||||
.password(password)
|
||||
.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
|
||||
.build();
|
||||
source.setMinimumIdle(0);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.vendor.repository.VendorClassRepository;
|
||||
import com.ecep.contract.model.VendorCatalog;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 同步供应商分类
|
||||
*/
|
||||
public class VendorClassSyncTask extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(VendorClassSyncTask.class);
|
||||
@Setter
|
||||
private VendorClassRepository vendorClassRepository;
|
||||
|
||||
public VendorClassSyncTask() {
|
||||
updateTitle("用友U8系统-同步供应商分类信息");
|
||||
}
|
||||
|
||||
VendorClassRepository getVendorClassRepository() {
|
||||
if (vendorClassRepository == null) {
|
||||
vendorClassRepository = SpringApp.getBean(VendorClassRepository.class);
|
||||
}
|
||||
return vendorClassRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
YongYouU8Service service = null;
|
||||
try {
|
||||
service = SpringApp.getBean(YongYouU8Service.class);
|
||||
} catch (BeansException e) {
|
||||
logger.error("can't get bean of YongYouU8Service", e);
|
||||
holder.error("can't get bean of YongYouU8Service");
|
||||
return null;
|
||||
}
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
logger.info("读取 U8 系统 VendorClass 数据表...");
|
||||
List<Map<String, Object>> list = service.queryAllVendorClass();
|
||||
int size = list.size();
|
||||
holder.debug("总共读取 VendorClass 数据 " + size + " 条");
|
||||
|
||||
for (Map<String, Object> map : list) {
|
||||
if (isCancelled()) {
|
||||
holder.info("Cancelled");
|
||||
return null;
|
||||
}
|
||||
MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
|
||||
sync(map, sub);
|
||||
// 更新进度
|
||||
updateProgress(counter.incrementAndGet(), size);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sync(Map<String, Object> map, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
|
||||
String code = (String) map.get("cVCCode");
|
||||
String name = (String) map.get("cVCName");
|
||||
|
||||
VendorClassRepository repository = getVendorClassRepository();
|
||||
VendorCatalog vendorCatalog = repository.findByCode(code).orElse(null);
|
||||
if (vendorCatalog == null) {
|
||||
vendorCatalog = new VendorCatalog();
|
||||
holder.info("新建供应商分类:" + code);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(vendorCatalog.getCode(), code)) {
|
||||
vendorCatalog.setCode(code);
|
||||
holder.info("供应商分类代码:" + vendorCatalog.getCode() + " -> " + code);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(vendorCatalog.getName(), name)) {
|
||||
vendorCatalog.setName(name);
|
||||
holder.info("供应商分类名称:" + vendorCatalog.getName() + " -> " + name);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
repository.save(vendorCatalog);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.u8.ctx.CompanyCtx;
|
||||
import com.ecep.contract.cloud.u8.ctx.VendorCtx;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorEntityService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyVendor;
|
||||
import com.ecep.contract.model.CompanyVendorEntity;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 供应商同步任务
|
||||
*/
|
||||
public class VendorSyncTask extends AbstContractRepairTasker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(VendorSyncTask.class);
|
||||
private final VendorCtx vendorCtx = new VendorCtx();
|
||||
private CompanyVendorService companyVendorService;
|
||||
private CompanyVendorEntityService vendorEntityService;
|
||||
private YongYouU8Repository repository;
|
||||
@Setter
|
||||
private YongYouU8Service yongYouU8Service;
|
||||
|
||||
public VendorSyncTask() {
|
||||
updateTitle("用友U8系统-同步供应商");
|
||||
}
|
||||
|
||||
private CompanyVendorService getCompanyVendorService() {
|
||||
if (companyVendorService == null) {
|
||||
companyVendorService = SpringApp.getBean(CompanyVendorService.class);
|
||||
}
|
||||
return companyVendorService;
|
||||
}
|
||||
|
||||
private CompanyVendorEntityService getVendorEntityService() {
|
||||
if (vendorEntityService == null) {
|
||||
vendorEntityService = SpringApp.getBean(CompanyVendorEntityService.class);
|
||||
}
|
||||
return vendorEntityService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void repair(MessageHolder holder) {
|
||||
try {
|
||||
yongYouU8Service = getBean(YongYouU8Service.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
|
||||
return;
|
||||
}
|
||||
repository = SpringApp.getBean(YongYouU8Repository.class);
|
||||
yongYouU8Service.initialize(vendorCtx);
|
||||
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
Long total = repository.countAllVendors();
|
||||
updateTitle("用友U8系统-同步供应商,合计 " + total + " 条");
|
||||
|
||||
try (Stream<Map<String, Object>> stream = repository.queryAllVendorForStream()) {
|
||||
stream.forEach(rs -> {
|
||||
if (isCancelled()) {
|
||||
updateMessage("Cancelled");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String venCode = (String) rs.get("cVenCode");
|
||||
MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> " + venCode + " ");
|
||||
boolean modified = false;
|
||||
CompanyVendorEntity entity = vendorCtx.findOrCreateByCode(venCode, subHolder);
|
||||
Map<String, Object> map = repository.findVendorByVendCode(entity.getCode());
|
||||
if (map == null) {
|
||||
subHolder.error("供应商项不存在:" + venCode);
|
||||
return;
|
||||
}
|
||||
if (vendorCtx.applyEntityDetail(entity, map, subHolder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (modified) {
|
||||
entity = getVendorEntityService().save(entity);
|
||||
}
|
||||
updateCompanyNameAndAbbName(entity, subHolder);
|
||||
updateCloudYu(entity);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("Vendor sync failure {}, data = {}", e.getMessage(), rs, e);
|
||||
updateMessage(e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCloudYu(CompanyVendorEntity entity) {
|
||||
CompanyVendor vendor = entity.getVendor();
|
||||
if (vendor == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(vendor)) {
|
||||
vendor = getCompanyVendorService().findById(vendor.getId());
|
||||
}
|
||||
Company company = vendor.getCompany();
|
||||
if (company == null) {
|
||||
return;
|
||||
}
|
||||
CloudYu cloudYu = yongYouU8Service.getOrCreateCloudYu(company);
|
||||
if (cloudYu == null) {
|
||||
return;
|
||||
}
|
||||
cloudYu.setVendorUpdateDate(LocalDate.now());
|
||||
cloudYu.setCloudLatest(Instant.now());
|
||||
cloudYu.setExceptionMessage("");
|
||||
yongYouU8Service.save(cloudYu);
|
||||
}
|
||||
|
||||
private void updateCompanyNameAndAbbName(CompanyVendorEntity entity, MessageHolder holder) {
|
||||
CompanyService companyService = vendorCtx.getCompanyService();
|
||||
CompanyVendor vendor = entity.getVendor();
|
||||
if (vendor == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(vendor)) {
|
||||
vendor = getCompanyVendorService().findById(vendor.getId());
|
||||
}
|
||||
Company company = vendor.getCompany();
|
||||
if (company == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = companyService.findById(company.getId());
|
||||
}
|
||||
boolean modified = false;
|
||||
CompanyCtx companyCtx = vendorCtx.getCompanyCtx();
|
||||
if (companyCtx.updateCompanyNameIfAbsent(company, entity.getName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (companyCtx.updateCompanyAbbNameIfAbsent(company, entity.getAbbName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (modified) {
|
||||
companyService.save(company);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
import org.springframework.jdbc.core.ColumnMapRowMapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ContractPayWay;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Lazy
|
||||
@Repository
|
||||
@ConditionalOnBean(YongYouU8Service.class)
|
||||
public class YongYouU8Repository {
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
@Lazy
|
||||
@Autowired
|
||||
@Qualifier("MSSQL_Server")
|
||||
private DataSource dataSource;
|
||||
|
||||
private JdbcTemplate getJdbcTemplate() {
|
||||
if (jdbcTemplate == null) {
|
||||
jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
}
|
||||
return jdbcTemplate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回 U8 系统中 供应商总数
|
||||
*
|
||||
* @return 供应商总数
|
||||
*/
|
||||
public Long countAllVendors() {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from Vendor", Long.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以流式返回所有供应商数据
|
||||
*
|
||||
* @return Stream 数据流
|
||||
*/
|
||||
public Stream<Map<String, Object>> queryAllVendorForStream() {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select cVenCode,cVenName,cVenAbbName," +
|
||||
"cVCCode,cVenAddress,cast(dVenDevDate as DATE) as venDevDate," +
|
||||
"cVenBank, cVenAccount, cCreatePerson,cModifyPerson,dModifyDate " +
|
||||
"from Vendor",
|
||||
new ColumnMapRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 以 U8 供应商 的代码查询 供应商
|
||||
*
|
||||
* @param vendCode U8 供应商 的代码,vendCode 唯一
|
||||
* @return 字段和值的Map集合, 没找到匹配的记录时,返回null
|
||||
*/
|
||||
public Map<String, Object> findVendorByVendCode(String vendCode) {
|
||||
try {
|
||||
return getJdbcTemplate().queryForObject("select cVenCode,cVenName,cVenAbbName," +
|
||||
"cVCCode,cVenAddress," +
|
||||
"cast(dVenDevDate as DATE) as devDate,dModifyDate," +
|
||||
"cVenBank,cVenAccount,cCreatePerson, cModifyPerson " +
|
||||
"from Vendor where cVenCode=?", new ColumnMapRowMapper(), vendCode);
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(vendCode, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回 U8 系统中 客户总数
|
||||
*
|
||||
* @return 客户总数
|
||||
*/
|
||||
public Long countAllCustomers() {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from Customer", Long.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以流式返回所有客户数据
|
||||
*
|
||||
* @return Stream 数据流
|
||||
*/
|
||||
public Stream<Map<String, Object>> queryAllCustomerForStream() {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select cCusCode,cCusName,cCusAbbName," +
|
||||
"cCCCode,cCusAddress,cast(dCusDevDate as DATE) as cusDevDate," +
|
||||
"cCusBank,cCusAccount, cCreatePerson,cModifyPerson,dModifyDate " +
|
||||
"from Customer",
|
||||
new ColumnMapRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以 U8 客户 的代码查询 客户
|
||||
*
|
||||
* @param cusCode U8 客户 的代码,cusCode 唯一
|
||||
* @return 字段和值的Map集合
|
||||
*/
|
||||
public Map<String, Object> findCustomerByCusCode(String cusCode) {
|
||||
return getJdbcTemplate().queryForObject("select cCusCode,cCusName,cCusAbbName," +
|
||||
"cCCCode,cCusAddress," +
|
||||
"cast(dCusDevDate as DATE) as devDate,dModifyDate," +
|
||||
"cCusBank,cCusAccount,cCreatePerson,cModifyPerson " +
|
||||
"from Customer where cCusCode=?", new ColumnMapRowMapper(), cusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回 U8 系统中 合同总数
|
||||
* 在U8中合同在多个地方存在,CM_List, CM_Contract_A,CM_Contract_B,CM_Contract_C
|
||||
*
|
||||
* @return 合同总数
|
||||
*/
|
||||
public Long countAllContracts(int latestId) {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from CM_List where ID>?", Long.class, latestId);
|
||||
}
|
||||
|
||||
public Long countAllContracts(LocalDateTime dateTime) {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from CM_List where dtDate>?", Long.class, dateTime);
|
||||
}
|
||||
|
||||
public Long countAllContracts() {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from CM_List", Long.class);
|
||||
}
|
||||
|
||||
public Long countAllContractB() {
|
||||
return getJdbcTemplate().queryForObject("select count(*) from CM_Contract_B", Long.class);
|
||||
}
|
||||
|
||||
public Long countAllContractB(LocalDate latestDate) {
|
||||
return getJdbcTemplate().queryForObject(
|
||||
"select count(*) " +
|
||||
"from CM_Contract_B " +
|
||||
"where strSetupDate>=? or (dtVaryDate is not null and dtVaryDate>=?)"
|
||||
, Long.class, latestDate, latestDate);
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllContractForStream() {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select * from CM_List", new ColumnMapRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllContractForStream(int latestId) {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select * from CM_List where ID > ?",
|
||||
new ColumnMapRowMapper(),
|
||||
latestId
|
||||
);
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllContractForStream(LocalDateTime dateTime) {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select * from CM_List where dtDate > ?",
|
||||
new ColumnMapRowMapper(),
|
||||
dateTime
|
||||
);
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllContractBForStream() {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select GUID,strContractID,strContractName,strContractType,strParentID,strContractKind,strWay," +
|
||||
"strContractGrp,strContractDesc,strBisectionUnit," +
|
||||
// 时间
|
||||
"strContractOrderDate,strContractStartDate,strContractEndDate," +
|
||||
// 创建人和时间
|
||||
"strSetupPerson,strSetupDate," +
|
||||
// 生效人和时间
|
||||
"strInurePerson,strInureDate," +
|
||||
// 修改人和时间
|
||||
"strVaryPerson,dtVaryDate," +
|
||||
// 业务员
|
||||
"strPersonID, " +
|
||||
"dblTotalCurrency,dblExecCurrency,dblTotalQuantity,dblExecQuqantity " +
|
||||
"from CM_Contract_B ",
|
||||
new ColumnMapRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllContractBForStream(LocalDate latestDate) {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select GUID,strContractID,strContractName,strContractType,strParentID,strContractKind,strWay," +
|
||||
"strContractGrp,strContractDesc,strBisectionUnit," +
|
||||
// 时间
|
||||
"strContractOrderDate,strContractStartDate,strContractEndDate," +
|
||||
// 创建人和时间
|
||||
"strSetupPerson,strSetupDate," +
|
||||
// 生效人和时间
|
||||
"strInurePerson,strInureDate," +
|
||||
// 修改人和时间
|
||||
"strVaryPerson,dtVaryDate," +
|
||||
// 业务员
|
||||
"strPersonID, " +
|
||||
"dblTotalCurrency,dblExecCurrency,dblTotalQuantity,dblExecQuqantity " +
|
||||
"from CM_Contract_B where strSetupDate>=? or (dtVaryDate is not null and dtVaryDate>=?)",
|
||||
new ColumnMapRowMapper(), latestDate, latestDate
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 CM_Contract_B 表中,检索 strBisectionUnit 是 unit 的记录
|
||||
*
|
||||
* @param unit 单位编码
|
||||
* @param payWay 付款方向,付 或 收
|
||||
*/
|
||||
public Stream<Map<String, Object>> queryAllContractByUnitForStream(String unit, ContractPayWay payWay) {
|
||||
return getJdbcTemplate().queryForStream(
|
||||
"select GUID,strContractID,strContractName,strContractType,strParentID,strContractKind,strWay," +
|
||||
"strContractGrp, strContractDesc,strBisectionUnit," +
|
||||
// 时间
|
||||
"strContractOrderDate,strContractStartDate,strContractEndDate," +
|
||||
// 创建人和时间
|
||||
"strSetupPerson,strSetupDate," +
|
||||
// 生效人和时间
|
||||
"strInurePerson,strInureDate," +
|
||||
// 修改人和时间
|
||||
"strVaryPerson,dtVaryDate," +
|
||||
// 业务员
|
||||
"strPersonID, " +
|
||||
"dblTotalCurrency,dblExecCurrency,dblTotalQuantity,dblExecQuqantity " +
|
||||
"from CM_Contract_B where strBisectionUnit=? and strWay=?",
|
||||
new ColumnMapRowMapper(), unit, payWay.getText()
|
||||
);
|
||||
}
|
||||
|
||||
public Map<String, Object> queryContractDetail(String guid) {
|
||||
return getJdbcTemplate().queryForObject("select GUID,strContractID,strContractName,strContractType,strParentID,strContractKind,strWay," +
|
||||
"strContractGrp, strContractDesc,strBisectionUnit," +
|
||||
// 时间
|
||||
"strContractOrderDate,strContractStartDate,strContractEndDate," +
|
||||
// 创建人和时间
|
||||
"strSetupPerson,strSetupDate," +
|
||||
// 生效人和时间
|
||||
"strInurePerson,strInureDate," +
|
||||
// 修改人和时间
|
||||
"strVaryPerson,dtVaryDate," +
|
||||
// 业务员
|
||||
"strPersonID, " +
|
||||
"dblTotalCurrency,dblExecCurrency,dblTotalQuantity,dblExecQuqantity " +
|
||||
" from CM_Contract_B where GUID = ?", new ColumnMapRowMapper(), guid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合计合同的执行数量、金额、 不含税金额
|
||||
*
|
||||
* @param code 合同号
|
||||
* @return Map<String, Object>
|
||||
*/
|
||||
public Map<String, Object> sumContractExec(String code) {
|
||||
return getJdbcTemplate().queryForObject("select sum(decCount) as execQuantity, sum(decRateMoney) as execAmount, sum(decNoRateMoney) as execUnTaxAmount " +
|
||||
"from CM_ExecInterface " +
|
||||
"where cContractID = ?;", new ColumnMapRowMapper(), code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllContractExecByContractCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from CM_ExecInterface where cContractID=?", code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllContractItemByContractCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from CM_Contract_Item_B where strContractID=?", code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllContractPayPlanByContractCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from CM_Contract_Pay where strContractID=?", code);
|
||||
}
|
||||
|
||||
public Map<String, Object> querySalesOrderDetail(String code) {
|
||||
return getJdbcTemplate().queryForObject("select * " +
|
||||
" from SO_SOMain where cSOCode = ?", new ColumnMapRowMapper(), code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllSalesOrderItemByContractCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from SO_SODetails where cContractID=?", code);
|
||||
}
|
||||
|
||||
public Map<String, Object> queryPurchaseOrderDetail(Integer code) {
|
||||
return getJdbcTemplate().queryForObject("select * " +
|
||||
" from PO_Pomain where POID = ?", new ColumnMapRowMapper(), code);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 采购合同项
|
||||
*
|
||||
* @param code 采购合同号
|
||||
* @return List<Map < String, Object>>
|
||||
*/
|
||||
public List<Map<String, Object>> findAllPurchaseOrderItemByContractCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from PO_Podetails where ContractCode=?", code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询存货档案数据
|
||||
*
|
||||
* @param code 存货编码
|
||||
* @return Map<String, Object>
|
||||
*/
|
||||
public Map<String, Object> queryInventoryDetail(String code) {
|
||||
return getJdbcTemplate().queryForObject("select I.*, U.cComUnitName from Inventory as I left join ComputationUnit as U on I.cComUnitCode=U.cComunitCode where cInvCode = ?", new ColumnMapRowMapper(), code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllPerson() {
|
||||
return getJdbcTemplate().queryForList("select * from Person;");
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractGroup() {
|
||||
return getJdbcTemplate().queryForList("select cGroupID, cGroupName,cRemark from CM_Group;");
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractType() {
|
||||
return getJdbcTemplate().queryForList(
|
||||
"select cTypeCode, cTypeName, CM_TypeClass.cClassName, cCharacter, cDirection " +
|
||||
"from CM_Type left join CM_TypeClass on CM_Type.cClassCode = CM_TypeClass.cClassCode;");
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractKind() {
|
||||
return getJdbcTemplate().queryForList("select KindID,KindName,Description from CM_Kind;");
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllVendorClass() {
|
||||
return getJdbcTemplate().queryForList("select cVCCode, cVCName, iVCGrade from VendorClass;");
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllCustomerClass() {
|
||||
return getJdbcTemplate().queryForList("select cCCCode, cCCName, iCCGrade from CustomerClass;");
|
||||
}
|
||||
|
||||
|
||||
public List<Map<String, Object>> findAllPurchaseBillVoucherByVendorCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from PurBillVouch where cVenCode=?", code);
|
||||
}
|
||||
|
||||
public Map<String, Object> findPurchaseBillVoucherById(Integer pbvId) {
|
||||
return getJdbcTemplate().queryForObject("select * from PurBillVouch where PBVID = ?", new ColumnMapRowMapper(), pbvId);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllPurchaseBillVoucherItemByPbvId(int pbvId) {
|
||||
return getJdbcTemplate().queryForList("select * from PurBillVouchs where PBVID=?", pbvId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过合同编号查询采购
|
||||
*
|
||||
* @param contractCode 合同编号
|
||||
*/
|
||||
public List<Map<String, Object>> findAllPurchaseBillVoucherItemByContractCode(String contractCode) {
|
||||
return getJdbcTemplate().queryForList("select * from PurBillVouchs where ContractCode=?", contractCode);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllSalesBillVoucherByCustomerCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from SaleBillVouch where cCusCode=?", code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllSalesBillVoucherBySalesOrderCode(String code) {
|
||||
return getJdbcTemplate().queryForList("select * from SaleBillVouch where cSOCode=?", code);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findAllSalesBillVoucherItemBySBVID(int sbvid) {
|
||||
return getJdbcTemplate().queryForList("select * from SaleBillVouchs where SBVID=?", sbvid);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.ecep.contract.cloud.u8;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.cloud.CloudInfo;
|
||||
import com.ecep.contract.cloud.CloudInfoRepository;
|
||||
import com.ecep.contract.cloud.u8.ctx.AbstractYongYouU8Ctx;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
|
||||
import com.ecep.contract.ds.other.service.EmployeeService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "cloud.u8.enabled", havingValue = "true")
|
||||
public class YongYouU8Service implements IEntityService<CloudYu> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(YongYouU8Service.class);
|
||||
|
||||
public static final String KEY_HOST_IP = "u8.db.server.ip";
|
||||
public static final String KEY_DATABASE = "u8.db.database";
|
||||
public static final String KEY_USER_NAME = "u8.db.server.name";
|
||||
public static final String KEY_PASSWORD = "u8.db.server.password";
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
private YongYouU8Repository repository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CloudInfoRepository cloudInfoRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyVendorService companyVendorService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CloudYuRepository cloudYuRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private EmployeeService employeeService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyCustomerService companyCustomerService;
|
||||
|
||||
public YongYouU8Service() {
|
||||
|
||||
}
|
||||
|
||||
public CloudYu findById(Integer id) {
|
||||
return cloudYuRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建
|
||||
*
|
||||
* @param info 供应商信息
|
||||
* @return 供应商对象
|
||||
*/
|
||||
public CloudYu getOrCreateCloudYu(CloudInfo info) {
|
||||
Optional<CloudYu> optional = cloudYuRepository.findById(info.getId());
|
||||
return optional.orElseGet(() -> getOrCreateCloudYu(info.getCompany()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建或获取供应商云信息
|
||||
*
|
||||
* @param company 公司
|
||||
* @return 供应商云信息
|
||||
*/
|
||||
public CloudYu getOrCreateCloudYu(Company company) {
|
||||
Integer companyId = company.getId();
|
||||
List<CloudYu> list = cloudYuRepository.findAllByCompanyId(companyId);
|
||||
if (list.isEmpty()) {
|
||||
CloudYu cloudYu = new CloudYu();
|
||||
cloudYu.setCompany(company);
|
||||
cloudYu.setExceptionMessage("");
|
||||
cloudYu.setVendorUpdateDate(null);
|
||||
cloudYu.setCustomerUpdateDate(null);
|
||||
cloudYu.setCloudLatest(null);
|
||||
return cloudYuRepository.save(cloudYu);
|
||||
}
|
||||
|
||||
// 只有匹配到一条有 CloudId 的记录
|
||||
if (list.size() == 1) {
|
||||
// 保留匹配的记录,其他删除
|
||||
CloudYu rk = list.removeFirst();
|
||||
list.remove(rk);
|
||||
cloudYuRepository.deleteAll(list);
|
||||
return rk;
|
||||
}
|
||||
|
||||
return list.getFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 Cloud Yu
|
||||
*
|
||||
* @param cloudYu Cloud Yu 对象
|
||||
* @return 更新的 Cloud Yu
|
||||
*/
|
||||
public CloudYu save(CloudYu cloudYu) {
|
||||
return cloudYuRepository.save(cloudYu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(CloudYu entity) {
|
||||
cloudYuRepository.delete(entity);
|
||||
}
|
||||
|
||||
public void deleteByCompany(Company company) {
|
||||
int deleted = cloudYuRepository.deleteAllByCompany(company);
|
||||
if (deleted > 0) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete {} records by company:#{}", deleted, company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void resetTo(Company from, Company to) {
|
||||
List<CloudYu> list = cloudYuRepository.findAllByCompanyId(from.getId());
|
||||
for (CloudYu item : list) {
|
||||
item.setCompany(to);
|
||||
}
|
||||
cloudYuRepository.saveAll(list);
|
||||
}
|
||||
|
||||
public Page<CloudYu> findAll(Specification<CloudYu> spec, Pageable pageable) {
|
||||
return cloudYuRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CloudYu> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.like(root.get("cloudId"), "%" + searchText + "%");
|
||||
};
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractKind() {
|
||||
return repository.queryAllContractKind();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllVendorClass() {
|
||||
return repository.queryAllVendorClass();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllCustomerClass() {
|
||||
return repository.queryAllCustomerClass();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractType() {
|
||||
return repository.queryAllContractType();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllContractGroup() {
|
||||
return repository.queryAllContractGroup();
|
||||
}
|
||||
|
||||
public Long countAllCustomers() {
|
||||
return repository.countAllCustomers();
|
||||
}
|
||||
|
||||
public Stream<Map<String, Object>> queryAllCustomerForStream() {
|
||||
return repository.queryAllCustomerForStream();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryAllPerson() {
|
||||
return repository.queryAllPerson();
|
||||
}
|
||||
|
||||
public Map<String, Object> findVendorByVendCode(String unit) {
|
||||
return repository.findVendorByVendCode(unit);
|
||||
}
|
||||
|
||||
public Map<String, Object> findCustomerByCusCode(String unit) {
|
||||
return repository.findCustomerByCusCode(unit);
|
||||
}
|
||||
|
||||
public void initialize(AbstractYongYouU8Ctx ctx) {
|
||||
ctx.setRepository(repository);
|
||||
ctx.setCompanyService(companyService);
|
||||
ctx.setEmployeeService(employeeService);
|
||||
ctx.setCompanyVendorService(companyVendorService);
|
||||
ctx.setCompanyCustomerService(companyCustomerService);
|
||||
}
|
||||
|
||||
public Iterable<CloudInfo> findAllCloudYu() {
|
||||
return cloudInfoRepository.findAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.cloud.AbstractCtx;
|
||||
import com.ecep.contract.cloud.u8.YongYouU8Repository;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerEntityService;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
|
||||
import com.ecep.contract.ds.other.service.EmployeeService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorEntityService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyCustomer;
|
||||
import com.ecep.contract.model.CompanyCustomerEntity;
|
||||
import com.ecep.contract.model.CompanyVendor;
|
||||
import com.ecep.contract.model.CompanyVendorEntity;
|
||||
import com.ecep.contract.model.Employee;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class AbstractYongYouU8Ctx extends AbstractCtx {
|
||||
@Getter
|
||||
@Setter
|
||||
YongYouU8Repository repository;
|
||||
@Setter
|
||||
CompanyService companyService;
|
||||
@Setter
|
||||
EmployeeService employeeService;
|
||||
@Setter
|
||||
CompanyCustomerService companyCustomerService;
|
||||
@Setter
|
||||
CompanyCustomerEntityService companyCustomerEntityService;
|
||||
@Setter
|
||||
CompanyVendorService companyVendorService;
|
||||
@Setter
|
||||
CompanyVendorEntityService companyVendorEntityService;
|
||||
|
||||
|
||||
public void from(AbstractYongYouU8Ctx parent) {
|
||||
repository = parent.repository;
|
||||
companyService = parent.companyService;
|
||||
employeeService = parent.employeeService;
|
||||
companyCustomerService = parent.companyCustomerService;
|
||||
companyVendorService = parent.companyVendorService;
|
||||
}
|
||||
|
||||
public void initializeRepository(MessageHolder holder) {
|
||||
if (repository != null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
repository = getBean(YongYouU8Repository.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public CompanyService getCompanyService() {
|
||||
if (companyService == null) {
|
||||
companyService = getBean(CompanyService.class);
|
||||
}
|
||||
return companyService;
|
||||
}
|
||||
|
||||
EmployeeService getEmployeeService() {
|
||||
if (employeeService == null) {
|
||||
employeeService = getBean(EmployeeService.class);
|
||||
}
|
||||
return employeeService;
|
||||
}
|
||||
|
||||
public CompanyCustomerService getCompanyCustomerService() {
|
||||
if (companyCustomerService == null) {
|
||||
companyCustomerService = getBean(CompanyCustomerService.class);
|
||||
}
|
||||
return companyCustomerService;
|
||||
}
|
||||
|
||||
public CompanyCustomerEntityService getCompanyCustomerEntityService() {
|
||||
if (companyCustomerEntityService == null) {
|
||||
companyCustomerEntityService = getBean(CompanyCustomerEntityService.class);
|
||||
}
|
||||
return companyCustomerEntityService;
|
||||
}
|
||||
|
||||
public CompanyVendorService getCompanyVendorService() {
|
||||
if (companyVendorService == null) {
|
||||
companyVendorService = getBean(CompanyVendorService.class);
|
||||
}
|
||||
return companyVendorService;
|
||||
}
|
||||
|
||||
public CompanyVendorEntityService getCompanyVendorEntityService() {
|
||||
if (companyVendorEntityService == null) {
|
||||
companyVendorEntityService = getBean(CompanyVendorEntityService.class);
|
||||
}
|
||||
return companyVendorEntityService;
|
||||
}
|
||||
|
||||
boolean updateEmployeeByCode(Supplier<Employee> getter, Consumer<Employee> setter, String code, MessageHolder holder, String topic) {
|
||||
if (StringUtils.hasText(code)) {
|
||||
Employee employee = getEmployeeService().findByCode(code);
|
||||
if (employee != null) {
|
||||
if (!Objects.equals(getter.get(), employee)) {
|
||||
setter.accept(employee);
|
||||
holder.info(topic + "更新为 " + employee.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
boolean updateEmployeeByName(Supplier<Employee> getter, Consumer<Employee> setter, String name, MessageHolder holder, String topic) {
|
||||
if (StringUtils.hasText(name)) {
|
||||
Employee employee = getEmployeeService().findByName(name);
|
||||
if (employee != null) {
|
||||
if (!Objects.equals(getter.get(), employee)) {
|
||||
setter.accept(employee);
|
||||
holder.info(topic + "更新为 " + employee.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updateCompanyByCustomerCode(Supplier<Company> getter, Consumer<Company> setter, String customerCode, MessageHolder holder, String topic) {
|
||||
Company company = null;
|
||||
if (StringUtils.hasText(customerCode)) {
|
||||
CompanyCustomerEntityService customerEntityService = getCompanyCustomerEntityService();
|
||||
CompanyCustomerService customerService = getCompanyCustomerService();
|
||||
CompanyCustomerEntity entity = customerEntityService.findByCustomerCode(customerCode);
|
||||
if (entity == null) {
|
||||
holder.warn("无效" + topic + ":" + customerCode);
|
||||
} else {
|
||||
CompanyCustomer customer = entity.getCustomer();
|
||||
if (customer == null) {
|
||||
holder.warn("无效" + topic + ":" + customerCode);
|
||||
} else {
|
||||
if (!Hibernate.isInitialized(customer)) {
|
||||
customer = customerService.findById(customer.getId());
|
||||
}
|
||||
company = customer.getCompany();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (company == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + customerCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), company)) {
|
||||
setter.accept(company);
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = getCompanyService().findById(company.getId());
|
||||
}
|
||||
holder.info(topic + "修改为: " + company.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
boolean updateCompanyByVendorCode(Supplier<Company> getter, Consumer<Company> setter, String vendorCode, MessageHolder holder, String topic) {
|
||||
Company company = null;
|
||||
if (StringUtils.hasText(vendorCode)) {
|
||||
CompanyVendorEntityService vendorEntityService = getCompanyVendorEntityService();
|
||||
CompanyVendorService customerService = getCompanyVendorService();
|
||||
CompanyVendorEntity entity = vendorEntityService.findByCode(vendorCode);
|
||||
if (entity == null) {
|
||||
holder.warn("无效" + topic + ":" + vendorCode);
|
||||
} else {
|
||||
CompanyVendor customer = entity.getVendor();
|
||||
if (customer == null) {
|
||||
holder.warn("无效" + topic + ":" + vendorCode);
|
||||
} else {
|
||||
if (!Hibernate.isInitialized(customer)) {
|
||||
customer = customerService.findById(customer.getId());
|
||||
}
|
||||
company = customer.getCompany();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (company == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + vendorCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), company)) {
|
||||
setter.accept(company);
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = getCompanyService().findById(company.getId());
|
||||
}
|
||||
holder.info(topic + "修改为: " + company.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.company.service.CompanyBankAccountService;
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class CompanyBankAccountCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private CompanyBankAccountService companyBankAccountService;
|
||||
|
||||
CompanyBankAccountService getCompanyBankAccountService() {
|
||||
if (companyBankAccountService == null) {
|
||||
companyBankAccountService = getBean(CompanyBankAccountService.class);
|
||||
}
|
||||
return companyBankAccountService;
|
||||
}
|
||||
|
||||
public void updateBankAccount(Company company, String bank, String bankAccount, MessageHolder holder) {
|
||||
getCompanyBankAccountService().updateBankAccount(company, bank, bankAccount, holder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.service.CompanyOldNameService;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class CompanyCtx extends AbstractYongYouU8Ctx {
|
||||
/**
|
||||
* 自动创建公司的时间
|
||||
*/
|
||||
public static final String AUTO_CREATE_COMPANY_AFTER = "cloud.u8.auto-create-company-after";
|
||||
|
||||
@Setter
|
||||
private CompanyOldNameService companyOldNameService;
|
||||
|
||||
CompanyOldNameService getCompanyOldNameService() {
|
||||
if (companyOldNameService == null) {
|
||||
companyOldNameService = getBean(CompanyOldNameService.class);
|
||||
}
|
||||
return companyOldNameService;
|
||||
}
|
||||
|
||||
public boolean updateCompanyNameIfAbsent(Company company, String name, MessageHolder holder) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
return false;
|
||||
}
|
||||
if (StringUtils.hasText(company.getName())) {
|
||||
if (Objects.equals(company.getName(), name)) {
|
||||
return false;
|
||||
}
|
||||
appendOldNameIfAbsent(company, name, false, holder);
|
||||
return false;
|
||||
} else {
|
||||
return updateText(company::getName, company::setName, name, holder, "公司名称");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public boolean updateCompanyAbbNameIfAbsent(Company company, String abbName, MessageHolder holder) {
|
||||
if (!StringUtils.hasText(abbName)) {
|
||||
return false;
|
||||
}
|
||||
// 简称与公司名相同,跳过
|
||||
if (Objects.equals(company.getName(), abbName)) {
|
||||
return false;
|
||||
}
|
||||
if (StringUtils.hasText(company.getShortName())) {
|
||||
if (Objects.equals(company.getShortName(), abbName)) {
|
||||
return false;
|
||||
}
|
||||
appendOldNameIfAbsent(company, abbName, true, holder);
|
||||
return false;
|
||||
} else {
|
||||
return updateText(company::getShortName, company::setShortName, abbName, holder, "公司简称");
|
||||
}
|
||||
}
|
||||
|
||||
private void appendOldNameIfAbsent(Company company, String name, boolean ambiguity, MessageHolder holder) {
|
||||
List<CompanyOldName> oldNames = getCompanyOldNameService().findAllByCompanyAndName(company, name);
|
||||
if (oldNames.isEmpty()) {
|
||||
CompanyOldName companyOldName = getCompanyOldNameService().createNew(company, name, ambiguity);
|
||||
companyOldName.setMemo("来自" + CloudServiceConstant.U8_NAME);
|
||||
getCompanyOldNameService().save(companyOldName);
|
||||
holder.info("新增曾用名:" + name);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean syncCompany(Company company, MessageHolder holder) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public Company findOrCreateByNameOrAbbName(String name, String abbName, LocalDate developDate, MessageHolder holder) {
|
||||
Company company = getCompanyService().findAndRemoveDuplicateCompanyByNameOrAbbName(name, abbName);
|
||||
if (company != null) {
|
||||
return company;
|
||||
}
|
||||
|
||||
// 判断是否是个人
|
||||
holder.warn("企业库中找不到" + name + " 或 " + abbName + " 的企业");
|
||||
// 推测个人用户,归入散户
|
||||
if (name.length() < 4 && !name.contains("公司")) {
|
||||
company = getCompanyService().findByName("散户");
|
||||
if (company == null) {
|
||||
return null;
|
||||
}
|
||||
holder.info(name + " 个人用户归集到散户");
|
||||
return company;
|
||||
}
|
||||
|
||||
// 尝试创建公司
|
||||
company = autoCreateNewCompanyAfter(developDate, name, abbName, holder);
|
||||
if (company != null) {
|
||||
holder.info("自动创建公司:" + company.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Company autoCreateNewCompanyAfter(LocalDate devDate, String name, String abbName, MessageHolder holder) {
|
||||
if (devDate == null) {
|
||||
holder.warn("开发时间未知,不创建公司");
|
||||
return null;
|
||||
}
|
||||
CompanyService companyService = getCompanyService();
|
||||
String autoCreateAfter = getConfService().getString(AUTO_CREATE_COMPANY_AFTER);
|
||||
// 当配置存在,且开发时间小于指定时间,不创建
|
||||
if (StringUtils.hasText(autoCreateAfter)) {
|
||||
LocalDate miniDate = LocalDate.parse(autoCreateAfter);
|
||||
if (devDate.isBefore(miniDate)) {
|
||||
// 创建时间小于指定时间,不创建
|
||||
holder.warn(name + " 的开发时间 " + devDate + " 是 " + miniDate + " 之前的, 按规定不创建, 如有需要请手动创建");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Company com = companyService.createNewCompany(name);
|
||||
com.setShortName(abbName);
|
||||
return companyService.save(com);
|
||||
}
|
||||
}
|
||||
1375
server/src/main/java/com/ecep/contract/cloud/u8/ctx/ContractCtx.java
Normal file
1375
server/src/main/java/com/ecep/contract/cloud/u8/ctx/ContractCtx.java
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,303 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.old.OldVersionService;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerEntityService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyCustomer;
|
||||
import com.ecep.contract.model.CompanyCustomerEntity;
|
||||
import com.ecep.contract.model.CustomerCatalog;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class CustomerCtx extends AbstractYongYouU8Ctx {
|
||||
private static final String AUTO_CREATE_CUSTOMER_AFTER = "cloud.u8.auto-create-customer-after";
|
||||
@Setter
|
||||
private CompanyCtx companyCtx;
|
||||
@Setter
|
||||
private ContractCtx contractCtx;
|
||||
@Setter
|
||||
private CompanyBankAccountCtx companyBankAccountCtx;
|
||||
@Setter
|
||||
private CompanyCustomerEntityService customerEntityService;
|
||||
|
||||
public CompanyCtx getCompanyCtx() {
|
||||
if (companyCtx == null) {
|
||||
companyCtx = new CompanyCtx();
|
||||
companyCtx.from(this);
|
||||
}
|
||||
return companyCtx;
|
||||
}
|
||||
|
||||
ContractCtx getContractCtx() {
|
||||
if (contractCtx == null) {
|
||||
contractCtx = new ContractCtx();
|
||||
contractCtx.from(this);
|
||||
}
|
||||
return contractCtx;
|
||||
}
|
||||
|
||||
CompanyBankAccountCtx getCompanyBankAccountCtx() {
|
||||
if (companyBankAccountCtx == null) {
|
||||
companyBankAccountCtx = new CompanyBankAccountCtx();
|
||||
companyBankAccountCtx.from(this);
|
||||
}
|
||||
return companyBankAccountCtx;
|
||||
}
|
||||
|
||||
CompanyCustomerEntityService getCustomerEntityService() {
|
||||
if (customerEntityService == null) {
|
||||
customerEntityService = SpringApp.getBean(CompanyCustomerEntityService.class);
|
||||
}
|
||||
return customerEntityService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新客户相关项
|
||||
*
|
||||
* @param item
|
||||
* @param unitCode
|
||||
* @param holder
|
||||
*/
|
||||
public CompanyCustomerEntity updateCustomerEntityDetailByCode(CompanyCustomerEntity item, String unitCode, MessageHolder holder) {
|
||||
if (applyEntityDetail(item, repository.findCustomerByCusCode(unitCode), holder)) {
|
||||
item = save(item);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
public boolean applyEntityDetail(CompanyCustomerEntity item, Map<String, Object> map, MessageHolder holder) {
|
||||
|
||||
String name = (String) map.get("cCusName");
|
||||
String abbName = (String) map.get("cCusAbbName");
|
||||
String cusCode = (String) map.get("cCusCode");
|
||||
String classCode = (String) map.get("cCCCode");
|
||||
|
||||
String createPerson = (String) map.get("cCreatePerson");
|
||||
String modifyPerson = (String) map.get("cModifyPerson");
|
||||
java.sql.Date devDate = (java.sql.Date) map.get("devDate");
|
||||
java.sql.Timestamp modifyDate = (java.sql.Timestamp) map.get("dModifyDate");
|
||||
|
||||
String bank = (String) map.get("cCusBank");
|
||||
String bankAccount = (String) map.get("cCusAccount");
|
||||
|
||||
|
||||
boolean modified = false;
|
||||
if (updateText(item::getName, item::setName, name, holder, "名称")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(item::getAbbName, item::setAbbName, abbName, holder, "简称")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(item::getCode, item::setCode, cusCode, holder, "客户编号")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateCustomerCatalog(item::getCatalog, item::setCatalog, classCode, holder, "分类")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getCreator, item::setCreator, createPerson, holder, "创建人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getModifier, item::setModifier, modifyPerson, holder, "修改人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getDevelopDate, item::setDevelopDate, devDate, holder, "发展日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getModifyDate, item::setModifyDate, modifyDate, holder, "修改日期")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
LocalDate today = LocalDate.now();
|
||||
if (item.getUpdatedDate() == null || item.getUpdatedDate().isBefore(today)) {
|
||||
item.setUpdatedDate(today);
|
||||
holder.info("更新日期更新为 " + today);
|
||||
}
|
||||
}
|
||||
|
||||
CompanyCustomer customer = item.getCustomer();
|
||||
if (customer == null) {
|
||||
// 如果没有关联客户,则根据供应商名称或别名查找公司
|
||||
Company company = findOrCreateCompanyByCustomerEntity(item, holder);
|
||||
if (company != null) {
|
||||
// 找到客户
|
||||
|
||||
customer = getCompanyCustomerService().findByCompany(company);
|
||||
if (customer == null) {
|
||||
customer = createCustomerByCustomerEntity(item, holder);
|
||||
if (customer != null) {
|
||||
customer.setCompany(company);
|
||||
customer = getCompanyCustomerService().save(customer);
|
||||
}
|
||||
}
|
||||
|
||||
if (customer != null) {
|
||||
item.setCustomer(customer);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (customer != null) {
|
||||
if (!Hibernate.isInitialized(customer)) {
|
||||
customer = getCompanyCustomerService().findById(customer.getId());
|
||||
}
|
||||
Company company = customer.getCompany();
|
||||
if (company != null) {
|
||||
getCompanyBankAccountCtx().updateBankAccount(company, bank, bankAccount, holder);
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean updateCustomerCatalog(Supplier<CustomerCatalog> getter, Consumer<CustomerCatalog> setter, String catalogCode, MessageHolder holder, String topic) {
|
||||
CustomerCatalog catalog = null;
|
||||
if (StringUtils.hasText(catalogCode)) {
|
||||
catalog = getCompanyCustomerService().findCatalogByCode(catalogCode);
|
||||
}
|
||||
if (catalog == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + catalogCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), catalog)) {
|
||||
if (!Hibernate.isInitialized(catalog)) {
|
||||
catalog = getCompanyCustomerService().findCatalogByCode(catalogCode);
|
||||
}
|
||||
setter.accept(catalog);
|
||||
holder.info(topic + "修改为: " + catalog.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean syncCustomer(Company company, MessageHolder holder) {
|
||||
CompanyCustomer companyCustomer = getCompanyCustomerService().findByCompany(company);
|
||||
if (companyCustomer == null) {
|
||||
holder.error("客户未创建, 如需要请手动创建.");
|
||||
return false;
|
||||
}
|
||||
// 检索相关项
|
||||
List<CompanyCustomerEntity> entities = getCustomerEntityService().findAllByCustomer(companyCustomer);
|
||||
if (entities.isEmpty()) {
|
||||
holder.error("客户未关联任何相关项");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updated = false;
|
||||
boolean companyModified = false;
|
||||
|
||||
// 更新相关项
|
||||
for (CompanyCustomerEntity entity : entities) {
|
||||
if (!StringUtils.hasText(entity.getCode())) {
|
||||
holder.warn("相关项:" + entity.getCode() + " 无效,跳过");
|
||||
continue;
|
||||
}
|
||||
if (applyEntityDetail(entity, repository.findCustomerByCusCode(entity.getCode()), holder)) {
|
||||
entity = getCustomerEntityService().save(entity);
|
||||
}
|
||||
|
||||
if (getCompanyCtx().updateCompanyNameIfAbsent(company, entity.getName(), holder)) {
|
||||
companyModified = true;
|
||||
}
|
||||
if (getCompanyCtx().updateCompanyAbbNameIfAbsent(company, entity.getAbbName(), holder)) {
|
||||
companyModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (companyModified) {
|
||||
company = getCompanyService().save(company);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
// 更新客户的开发日期
|
||||
if (updateCustomerDevelopDate(companyCustomer, entities, holder)) {
|
||||
companyCustomer = getCompanyCustomerService().save(companyCustomer);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
for (CompanyCustomerEntity entity : entities) {
|
||||
if (getContractCtx().syncByCustomerEntity(companyCustomer, entity, holder)) {
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private boolean updateCustomerDevelopDate(CompanyCustomer companyCustomer, List<CompanyCustomerEntity> entities, MessageHolder holder) {
|
||||
LocalDate developDate = null;
|
||||
for (CompanyCustomerEntity entity : entities) {
|
||||
// 取最早的开发日期
|
||||
if (developDate == null || entity.getDevelopDate().isBefore(developDate)) {
|
||||
developDate = entity.getDevelopDate();
|
||||
}
|
||||
}
|
||||
return updateLocalDate(companyCustomer::getDevelopDate, companyCustomer::setDevelopDate, developDate, holder, "开发日期");
|
||||
}
|
||||
|
||||
public CompanyCustomerEntity findOrCreateByCode(Map<String, Object> rs, String cusCode, MessageHolder subHolder) {
|
||||
CompanyCustomerEntityService customerEntityService = getCompanyCustomerEntityService();
|
||||
CompanyCustomerEntity entity = customerEntityService.findByCustomerCode(cusCode);
|
||||
if (entity == null) {
|
||||
entity = new CompanyCustomerEntity();
|
||||
entity.setCode(cusCode);
|
||||
entity = customerEntityService.save(entity);
|
||||
subHolder.info("创建客户相关项:" + cusCode);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private CompanyCustomer createCustomerByCustomerEntity(CompanyCustomerEntity entity, MessageHolder holder) {
|
||||
LocalDate developDate = entity.getDevelopDate();
|
||||
if (developDate == null) {
|
||||
holder.warn(entity.getName() + " 没有设置开发日期,跳过");
|
||||
return null;
|
||||
}
|
||||
// 创建发展日期从2023年1月1日后的
|
||||
LocalDate start = LocalDate.of(2023, 1, 1);
|
||||
String autoCreateAfter = getConfService().getString(AUTO_CREATE_CUSTOMER_AFTER);
|
||||
if (StringUtils.hasText(autoCreateAfter)) {
|
||||
start = LocalDate.parse(autoCreateAfter);
|
||||
}
|
||||
if (developDate.isBefore(start)) {
|
||||
// start 之前的不自动创建
|
||||
holder.warn(entity.getName() + " 的发展日期 " + developDate + " 是 " + start + " 之前的, 按规定不自动创建客户, 如有需要请手动创建");
|
||||
return null;
|
||||
}
|
||||
|
||||
CompanyCustomer companyCustomer = new CompanyCustomer();
|
||||
int nextId = SpringApp.getBean(OldVersionService.class).newCompanyCustomer(entity.getName());
|
||||
companyCustomer.setId(nextId);
|
||||
companyCustomer.setDevelopDate(developDate);
|
||||
holder.info("新客户:" + entity.getName() + "分配编号:" + nextId);
|
||||
companyCustomer.setCreated(Instant.now());
|
||||
return companyCustomer;
|
||||
}
|
||||
|
||||
private Company findOrCreateCompanyByCustomerEntity(CompanyCustomerEntity entity, MessageHolder holder) {
|
||||
String name = entity.getName();
|
||||
String abbName = entity.getAbbName();
|
||||
return getCompanyCtx().findOrCreateByNameOrAbbName(name, abbName, entity.getDevelopDate(), holder);
|
||||
}
|
||||
|
||||
public CompanyCustomerEntity save(CompanyCustomerEntity entity) {
|
||||
return getCustomerEntityService().save(entity);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.other.service.InventoryCatalogService;
|
||||
import com.ecep.contract.ds.other.service.InventoryService;
|
||||
import com.ecep.contract.model.Inventory;
|
||||
import com.ecep.contract.model.InventoryCatalog;
|
||||
import com.ecep.contract.model.Price;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class InventoryCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private InventoryService inventoryService;
|
||||
@Setter
|
||||
private InventoryCatalogService inventoryCatalogService;
|
||||
|
||||
public InventoryService getInventoryService() {
|
||||
if (inventoryService == null) {
|
||||
inventoryService = getBean(InventoryService.class);
|
||||
}
|
||||
return inventoryService;
|
||||
}
|
||||
|
||||
public InventoryCatalogService getInventoryCatalogService() {
|
||||
if (inventoryCatalogService == null) {
|
||||
inventoryCatalogService = getBean(InventoryCatalogService.class);
|
||||
}
|
||||
return inventoryCatalogService;
|
||||
}
|
||||
|
||||
private boolean applyInventoryDetail(Inventory item, Map<String, Object> map, MessageHolder holder) {
|
||||
String catalogCode = (String) map.get("cInvCCode");
|
||||
String name = (String) map.get("cInvName");
|
||||
String spec = (String) map.get("cInvStd");
|
||||
String unitCode = (String) map.get("cComUnitCode");
|
||||
String unitName = (String) map.get("cComUnitName");
|
||||
String createPerson = (String) map.get("cCreatePerson");
|
||||
String modifyPerson = (String) map.get("cModifyPerson");
|
||||
Timestamp createDate = (Timestamp) map.get("dSDate");
|
||||
Timestamp modifyDate = (Timestamp) map.get("dModifyDate");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
Double outTaxRate = (Double) map.get("iTaxRate");
|
||||
Double inTaxRate = (Double) map.get("iImpTaxRate");
|
||||
// 参考成本
|
||||
Double baseCostPrice = (Double) map.get("iInvSPrice");
|
||||
// 最新成本
|
||||
Double latestCostPrice = (Double) map.get("iInvNCost");
|
||||
// 计划价/售价
|
||||
Double plannedPrice = (Double) map.get("iInvRCost");
|
||||
// 最低售价
|
||||
Double lowestSalePrice = (Double) map.get("iInvLSCost");
|
||||
// 参考售价
|
||||
Double suggestedSalePrice = (Double) map.get("iInvSCost");
|
||||
|
||||
|
||||
if (!item.isNameLock()) {
|
||||
if (updateText(item::getName, item::setName, name, holder, "名称")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!item.isSpecificationLock()) {
|
||||
if (updateText(item::getSpecification, item::setSpecification, spec, holder, "规格")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (updateText(item::getUnit, item::setUnit, unitName, holder, "单位")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updatePrice(item.getPurchasePrice(), inTaxRate, latestCostPrice, holder, "采购")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updatePrice(item.getSalePrice(), outTaxRate, suggestedSalePrice, holder, "销售")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateInventoryCatalog(item::getCatalog, item::setCatalog, catalogCode, holder, "类别")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getCreator, item::setCreator, createPerson, holder, "创建人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getCreateTime, item::setCreateTime, createDate, holder, "创建时间")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getUpdater, item::setUpdater, modifyPerson, holder, "修改人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(item::getUpdateDate, item::setUpdateDate, modifyDate, holder, "修改时间")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean updatePrice(Price price, Double taxRate, Double preTaxPrice, MessageHolder holder, String title) {
|
||||
boolean modified = false;
|
||||
if (taxRate != null) {
|
||||
if (updateNumber(price::getTaxRate, price::setTaxRate, taxRate.floatValue(), holder, title + "税率")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (preTaxPrice != null) {
|
||||
if (updateNumber(price::getPreTaxPrice, price::setPreTaxPrice, preTaxPrice, holder, title + "未税单价")) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
public boolean syncInventoryDetailByCode(Inventory inventory, String inventoryCode, MessageHolder holder) {
|
||||
if (repository == null) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Object> map = null;
|
||||
try {
|
||||
map = repository.queryInventoryDetail(inventoryCode);
|
||||
} catch (NoSuchBeanDefinitionException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
|
||||
return false;
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
holder.error("无此存货:" + inventoryCode);
|
||||
return false;
|
||||
}
|
||||
if (applyInventoryDetail(inventory, map, holder)) {
|
||||
inventory.setUpdateDate(LocalDateTime.now());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 依据存货分类编号更新存货分类
|
||||
*
|
||||
* @param getter 获取的函数
|
||||
* @param setter 设置的函数
|
||||
* @param catalogCode 存货分类编号
|
||||
* @param holder 消息处理对象
|
||||
* @param topic 主题
|
||||
* @return 是否更新
|
||||
*/
|
||||
private boolean updateInventoryCatalog(Supplier<InventoryCatalog> getter, Consumer<InventoryCatalog> setter, String catalogCode, MessageHolder holder, String topic) {
|
||||
InventoryCatalog catalog = null;
|
||||
if (StringUtils.hasText(catalogCode)) {
|
||||
catalog = getInventoryCatalogService().findByCode(catalogCode);
|
||||
}
|
||||
if (catalog == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + catalogCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), catalog)) {
|
||||
if (!Hibernate.isInitialized(catalog)) {
|
||||
catalog = getInventoryCatalogService().findByCode(catalogCode);
|
||||
}
|
||||
setter.accept(catalog);
|
||||
holder.info(topic + "修改为: " + catalog.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 依据存货编号更新存货
|
||||
*
|
||||
* @param getter 获取的函数
|
||||
* @param setter 设置的函数
|
||||
* @param inventoryCode 存货编号
|
||||
* @param holder 消息持有者
|
||||
* @param topic 主题
|
||||
* @return 是否更新
|
||||
*/
|
||||
public boolean syncInventoryDetailByCode(Supplier<Inventory> getter, Consumer<Inventory> setter, String inventoryCode, MessageHolder holder, String topic) {
|
||||
if (!StringUtils.hasText(inventoryCode)) {
|
||||
return false;
|
||||
}
|
||||
Inventory inventory = null;
|
||||
InventoryService service = getInventoryService();
|
||||
if (StringUtils.hasText(inventoryCode)) {
|
||||
inventory = service.findByCode(inventoryCode);
|
||||
if (inventory == null) {
|
||||
inventory = service.createNewInstance();
|
||||
inventory.setCode(inventoryCode);
|
||||
if (syncInventoryDetailByCode(inventory, inventoryCode, holder)) {
|
||||
inventory = getInventoryService().save(inventory);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inventory == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + inventoryCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), inventory)) {
|
||||
if (!Hibernate.isInitialized(inventory)) {
|
||||
inventory = service.findByCode(inventoryCode);
|
||||
}
|
||||
setter.accept(inventory);
|
||||
holder.info(topic + "修改为: " + inventory.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.company.service.InvoiceService;
|
||||
import com.ecep.contract.model.Invoice;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class InvoiceCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private InvoiceService invoiceService;
|
||||
|
||||
InvoiceService getInvoiceService() {
|
||||
if (invoiceService == null) {
|
||||
invoiceService = getBean(InvoiceService.class);
|
||||
}
|
||||
return invoiceService;
|
||||
}
|
||||
|
||||
public boolean updateInvoiceByNumber(Supplier<Invoice> getter, Consumer<Invoice> setter, String invoiceNumber,
|
||||
MessageHolder holder, String topic) {
|
||||
// TODO 从U8系统中获取数据
|
||||
Invoice invoice = null;
|
||||
if (StringUtils.hasText(invoiceNumber)) {
|
||||
invoice = getInvoiceService().findByCode(invoiceNumber);
|
||||
if (invoice == null) {
|
||||
invoice = new Invoice();
|
||||
invoice.setCode(invoiceNumber);
|
||||
invoice = getInvoiceService().save(invoice);
|
||||
}
|
||||
}
|
||||
if (invoice == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + invoiceNumber);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), invoice)) {
|
||||
setter.accept(invoice);
|
||||
holder.info(topic + "修改为: " + invoice.getCode());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseBillVoucherItemService;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseBillVoucherService;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseOrderItemService;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseOrdersService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyVendor;
|
||||
import com.ecep.contract.model.CompanyVendorEntity;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.model.Inventory;
|
||||
import com.ecep.contract.model.Invoice;
|
||||
import com.ecep.contract.model.PurchaseBillVoucher;
|
||||
import com.ecep.contract.model.PurchaseBillVoucherItem;
|
||||
import com.ecep.contract.model.PurchaseOrder;
|
||||
import com.ecep.contract.model.PurchaseOrderItem;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class PurchaseBillVoucherCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private PurchaseOrdersService purchaseOrdersService;
|
||||
@Setter
|
||||
private PurchaseOrderItemService purchaseOrderItemService;
|
||||
@Setter
|
||||
private PurchaseBillVoucherService purchaseBillVoucherService;
|
||||
@Setter
|
||||
private PurchaseBillVoucherItemService purchaseBillVoucherItemService;
|
||||
|
||||
InventoryCtx inventoryCtx;
|
||||
InvoiceCtx invoiceCtx;
|
||||
ContractCtx contractCtx;
|
||||
|
||||
PurchaseOrdersService getPurchaseOrdersService() {
|
||||
if (purchaseOrdersService == null) {
|
||||
purchaseOrdersService = getBean(PurchaseOrdersService.class);
|
||||
}
|
||||
return purchaseOrdersService;
|
||||
}
|
||||
|
||||
PurchaseBillVoucherService getPurchaseBillVoucherService() {
|
||||
if (purchaseBillVoucherService == null) {
|
||||
purchaseBillVoucherService = getBean(PurchaseBillVoucherService.class);
|
||||
}
|
||||
return purchaseBillVoucherService;
|
||||
}
|
||||
|
||||
private PurchaseOrderItemService getPurchaseOrderItemService() {
|
||||
if (purchaseOrderItemService == null) {
|
||||
purchaseOrderItemService = getBean(PurchaseOrderItemService.class);
|
||||
}
|
||||
return purchaseOrderItemService;
|
||||
}
|
||||
|
||||
PurchaseBillVoucherItemService getPurchaseBillVoucherItemService() {
|
||||
if (purchaseBillVoucherItemService == null) {
|
||||
purchaseBillVoucherItemService = getBean(PurchaseBillVoucherItemService.class);
|
||||
}
|
||||
return purchaseBillVoucherItemService;
|
||||
}
|
||||
|
||||
InventoryCtx getInventoryCtx() {
|
||||
if (inventoryCtx == null) {
|
||||
inventoryCtx = new InventoryCtx();
|
||||
inventoryCtx.from(this);
|
||||
}
|
||||
return inventoryCtx;
|
||||
}
|
||||
|
||||
InvoiceCtx getInvoiceCtx() {
|
||||
if (invoiceCtx == null) {
|
||||
invoiceCtx = new InvoiceCtx();
|
||||
invoiceCtx.from(this);
|
||||
}
|
||||
return invoiceCtx;
|
||||
}
|
||||
|
||||
ContractCtx getContractCtx() {
|
||||
if (contractCtx == null) {
|
||||
contractCtx = new ContractCtx();
|
||||
contractCtx.from(this);
|
||||
}
|
||||
return contractCtx;
|
||||
}
|
||||
|
||||
public void syncByCompany(Company company, MessageHolder holder) {
|
||||
PurchaseBillVoucherService voucherService = getPurchaseBillVoucherService();
|
||||
PurchaseBillVoucherItemService voucherItemService = getPurchaseBillVoucherItemService();
|
||||
List<PurchaseBillVoucher> vouchers = voucherService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("company"), company);
|
||||
}, Sort.unsorted());
|
||||
holder.debug("查找到 " + vouchers.size() + " 条专用发票记录在数据库中");
|
||||
Map<Integer, PurchaseBillVoucher> voucherMap = vouchers.stream()
|
||||
.collect(Collectors.toMap(PurchaseBillVoucher::getRefId, item -> item));
|
||||
|
||||
CompanyVendor vendor = getCompanyVendorService().findByCompany(company);
|
||||
if (vendor != null) {
|
||||
List<CompanyVendorEntity> entities = getCompanyVendorEntityService().findAllByVendor(vendor);
|
||||
holder.debug(company.getName() + " 有 "
|
||||
+ entities.stream().map(CompanyVendorEntity::getCode).collect(Collectors.joining(", ")) + " 关联项");
|
||||
for (CompanyVendorEntity entity : entities) {
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllPurchaseBillVoucherByVendorCode(entity.getCode());
|
||||
holder.debug(
|
||||
"供应商关联项: " + entity.getCode() + " 查找到 " + ds.size() + " 条专用发票记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer pbvid = (Integer) map.get("PBVID");
|
||||
if (pbvid == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 PBVID");
|
||||
continue;
|
||||
}
|
||||
holder.debug("发票 #" + pbvid);
|
||||
PurchaseBillVoucher voucher = voucherMap.get(pbvid);
|
||||
boolean voucherModified = false;
|
||||
if (voucher == null) {
|
||||
voucher = new PurchaseBillVoucher();
|
||||
voucher.setCompany(company);
|
||||
voucher.setRefId(pbvid);
|
||||
voucherMap.put(pbvid, voucher);
|
||||
voucherModified = true;
|
||||
|
||||
holder.info("新增发票记录");
|
||||
}
|
||||
|
||||
if (applyPurchaseBillVoucherDetail(voucher, map, holder.sub("-- | "))) {
|
||||
voucherModified = true;
|
||||
}
|
||||
|
||||
if (voucherModified) {
|
||||
voucher = voucherService.save(voucher);
|
||||
voucherMap.put(pbvid, voucher);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<PurchaseBillVoucherItem> items = voucherItemService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("voucher").get("company"), company);
|
||||
}, Sort.unsorted());
|
||||
|
||||
// 按 order 分组
|
||||
Map<PurchaseBillVoucher, Map<Integer, PurchaseBillVoucherItem>> itemMap = items.stream()
|
||||
.collect(Collectors.groupingBy(PurchaseBillVoucherItem::getVoucher,
|
||||
Collectors.toMap(PurchaseBillVoucherItem::getRefId, item -> item)));
|
||||
for (PurchaseBillVoucher voucher : voucherMap.values()) {
|
||||
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllPurchaseBillVoucherItemByPbvId(voucher.getRefId());
|
||||
holder.debug("专用发票#" + voucher.getRefId() + "查找到 " + ds.size() + "条条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
Map<Integer, PurchaseBillVoucherItem> subItemMap = itemMap.computeIfAbsent(voucher, k -> new HashMap<>());
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer refId = (Integer) map.get("ID");
|
||||
if (refId == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 ID");
|
||||
continue;
|
||||
}
|
||||
PurchaseBillVoucherItem item = subItemMap.remove(refId);
|
||||
boolean itemModified = false;
|
||||
if (item == null) {
|
||||
item = new PurchaseBillVoucherItem();
|
||||
item.setVoucher(voucher);
|
||||
item.setRefId(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增专用发票条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("-- | ");
|
||||
if (applyPurchaseBillVoucherItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = voucherItemService.save(item);
|
||||
}
|
||||
}
|
||||
for (PurchaseBillVoucherItem item : subItemMap.values()) {
|
||||
holder.info("删除专用发票条目");
|
||||
voucherItemService.delete(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void syncByContract(Contract contract, MessageHolder holder) {
|
||||
PurchaseBillVoucherService voucherService = getPurchaseBillVoucherService();
|
||||
PurchaseBillVoucherItemService voucherItemService = getPurchaseBillVoucherItemService();
|
||||
List<PurchaseBillVoucherItem> items = voucherItemService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("contract"), contract);
|
||||
}, Sort.unsorted());
|
||||
|
||||
Map<Integer, PurchaseBillVoucherItem> itemMap = items.stream()
|
||||
.collect(Collectors.toMap(PurchaseBillVoucherItem::getRefId, item -> item));
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllPurchaseBillVoucherItemByContractCode(contract.getCode());
|
||||
holder.debug("合同编号#" + contract.getCode() + "查找到 " + ds.size() + "条发票条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer refId = (Integer) map.get("ID");
|
||||
if (refId == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 ID");
|
||||
continue;
|
||||
}
|
||||
PurchaseBillVoucherItem item = itemMap.remove(refId);
|
||||
boolean itemModified = false;
|
||||
if (item == null) {
|
||||
item = new PurchaseBillVoucherItem();
|
||||
PurchaseBillVoucher voucher = this.updateVoucherByPBVID((Integer) map.get("PBVID"), holder);
|
||||
item.setVoucher(voucher);
|
||||
item.setRefId(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增专用发票条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("-- | ");
|
||||
if (applyPurchaseBillVoucherItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = voucherItemService.save(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PurchaseBillVoucher updateVoucherByPBVID(Integer pbvId, MessageHolder holder) {
|
||||
PurchaseBillVoucherService voucherService = getPurchaseBillVoucherService();
|
||||
PurchaseBillVoucher voucher = voucherService.findByRefId(pbvId);
|
||||
if (voucher != null) {
|
||||
return voucher;
|
||||
}
|
||||
voucher = new PurchaseBillVoucher();
|
||||
// 查询 U8 数据库
|
||||
Map<String, Object> map = repository.findPurchaseBillVoucherById(pbvId);
|
||||
applyPurchaseBillVoucherDetail(voucher, map, holder.sub("-- | "));
|
||||
voucher = voucherService.save(voucher);
|
||||
return voucher;
|
||||
}
|
||||
|
||||
private boolean applyPurchaseBillVoucherDetail(PurchaseBillVoucher voucher, Map<String, Object> map,
|
||||
MessageHolder holder) {
|
||||
String code = String.valueOf(map.get("PBVID"));
|
||||
String vendorCode = (String) map.get("cVenCode");
|
||||
String invoiceNumber = (String) map.get("cPBVCode");
|
||||
String personCode = (String) map.get("cPersonCode");
|
||||
String inCode = (String) map.get("cInCode");
|
||||
|
||||
Timestamp invoiceDate = (Timestamp) map.get("dPBVDate");
|
||||
Timestamp voucherDate = (Timestamp) map.get("dVouDate");
|
||||
|
||||
BigDecimal amount = (BigDecimal) map.get("iSum");
|
||||
|
||||
String maker = (String) map.get("cPBVMaker");
|
||||
String verifier = (String) map.get("cPBVVerifier");
|
||||
Timestamp makeTime = (Timestamp) map.get("cmaketime");
|
||||
Timestamp auditTime = (Timestamp) map.get("dverifysystime");
|
||||
|
||||
String description = (String) map.get("cPBVMemo");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("发票号码:" + invoiceNumber);
|
||||
|
||||
if (updateCompanyByVendorCode(voucher::getCompany, voucher::setCompany, vendorCode, holder, "供应商")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateInvoice(voucher::getInvoice, voucher::setInvoice, invoiceNumber, holder, "发票")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (voucher.getInvoice() != null) {
|
||||
Invoice invoice = voucher.getInvoice();
|
||||
if (updateLocalDate(invoice::getInvoiceDate, invoice::setInvoiceDate, voucherDate, holder, "开票日期")) {
|
||||
invoice = getInvoiceCtx().getInvoiceService().save(invoice);
|
||||
voucher.setInvoice(invoice);
|
||||
}
|
||||
}
|
||||
|
||||
if (updateEmployeeByCode(voucher::getEmployee, voucher::setEmployee, personCode, holder, "业务员")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(voucher::getMaker, voucher::setMaker, maker, holder, "制单人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(voucher::getVerifier, voucher::setVerifier, verifier, holder, "审核人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(voucher::getMakerDate, voucher::setMakerDate, makeTime, holder, "制单时间")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(voucher::getVerifierDate, voucher::setVerifierDate, auditTime, holder, "审核时间")) {
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(voucher.getDescription(), description)) {
|
||||
voucher.setDescription(description);
|
||||
holder.info("描述修改为: " + description);
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean applyPurchaseBillVoucherItemDetail(PurchaseBillVoucherItem item, Map<String, Object> map,
|
||||
MessageHolder holder) {
|
||||
String code = String.valueOf(map.get("ID"));
|
||||
String inventoryCode = (String) map.get("cInvCode");
|
||||
String contractCode = (String) map.get("ContractCode");
|
||||
|
||||
String title = (String) map.get("cInvCode");
|
||||
double quantity = (double) map.get("iPBVQuantity");
|
||||
BigDecimal taxRate = (BigDecimal) map.get("iOriTaxPrice");
|
||||
BigDecimal taxPrice = (BigDecimal) map.get("iTaxPrice");
|
||||
BigDecimal amount = (BigDecimal) map.get("iSum");
|
||||
|
||||
// RdsId
|
||||
|
||||
// 采购订单条目refId
|
||||
Integer purchaseOrderItemId = (Integer) map.get("iPOsID");
|
||||
|
||||
String description = (String) map.get("cdescription");
|
||||
Timestamp signDate = (Timestamp) map.get("dSignDate");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("条目:" + title + " x " + amount);
|
||||
if (updateInventory(item::getInventory, item::setInventory, inventoryCode, holder, "商品")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updatePurchaseOrderItem(item::getOrderItem, item::setOrderItem, purchaseOrderItemId, holder, "采购订单条目")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateContractByContractCode(item::getContract, item::setContract, contractCode, holder, "合同")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateNumber(item::getPrice, item::setPrice, taxPrice, holder, "含税单价")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateNumber(item::getQuantity, item::setQuantity, quantity, holder, "数量")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateAppendText(item::getDescription, item::setDescription, description, holder, "描述")) {
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
boolean updatePurchaseOrderItem(Supplier<PurchaseOrderItem> getter, Consumer<PurchaseOrderItem> setter,
|
||||
Integer orderItemRefId, MessageHolder holder, String topic) {
|
||||
PurchaseOrderItem item = null;
|
||||
if (orderItemRefId != null) {
|
||||
item = getPurchaseOrderItemService().findByRefId(orderItemRefId);
|
||||
}
|
||||
if (item == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + orderItemRefId);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), item)) {
|
||||
setter.accept(item);
|
||||
holder.info(topic + "修改为: " + item.getRefId());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updatePurchaseOrder(Supplier<PurchaseOrder> getter, Consumer<PurchaseOrder> setter, Integer orderRefId,
|
||||
MessageHolder holder, String topic) {
|
||||
PurchaseOrder order = null;
|
||||
if (orderRefId != null) {
|
||||
order = getPurchaseOrdersService().findByRefId(orderRefId);
|
||||
}
|
||||
if (order == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + orderRefId);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), order)) {
|
||||
setter.accept(order);
|
||||
holder.info(topic + "修改为: " + order.getCode());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updateContractByContractCode(Supplier<Contract> getter, Consumer<Contract> setter, String contractCode,
|
||||
MessageHolder holder, String topic) {
|
||||
Contract contract = null;
|
||||
if (contractCode != null) {
|
||||
contract = getContractCtx().findContractByCode(contractCode);
|
||||
}
|
||||
if (contract == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + contractCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), contract)) {
|
||||
setter.accept(contract);
|
||||
holder.info(topic + "修改为: " + contract.getCode());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updateInventory(Supplier<Inventory> getter, Consumer<Inventory> setter, String inventoryCode,
|
||||
MessageHolder holder, String topic) {
|
||||
return getInventoryCtx().syncInventoryDetailByCode(getter, setter, inventoryCode, holder, topic);
|
||||
}
|
||||
|
||||
private boolean updateInvoice(Supplier<Invoice> getter, Consumer<Invoice> setter, String invoiceNumber,
|
||||
MessageHolder holder, String topic) {
|
||||
return getInvoiceCtx().updateInvoiceByNumber(getter, setter, invoiceNumber, holder, topic);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseOrderItemService;
|
||||
import com.ecep.contract.ds.contract.service.PurchaseOrdersService;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.model.Inventory;
|
||||
import com.ecep.contract.model.PurchaseOrder;
|
||||
import com.ecep.contract.model.PurchaseOrderItem;
|
||||
import com.ecep.contract.util.NumberUtils;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class PurchaseOrderCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private ContractService contractService;
|
||||
@Setter
|
||||
private PurchaseOrdersService purchaseOrdersService;
|
||||
@Setter
|
||||
private PurchaseOrderItemService purchaseOrderItemService;
|
||||
|
||||
InventoryCtx inventoryCtx;
|
||||
CompanyBankAccountCtx companyBankAccountCtx;
|
||||
|
||||
InventoryCtx getInventoryCtx() {
|
||||
if (inventoryCtx == null) {
|
||||
inventoryCtx = new InventoryCtx();
|
||||
inventoryCtx.from(this);
|
||||
}
|
||||
return inventoryCtx;
|
||||
}
|
||||
|
||||
CompanyBankAccountCtx getCompanyBankAccountCtx() {
|
||||
if (companyBankAccountCtx == null) {
|
||||
companyBankAccountCtx = new CompanyBankAccountCtx();
|
||||
companyBankAccountCtx.from(this);
|
||||
}
|
||||
return companyBankAccountCtx;
|
||||
}
|
||||
|
||||
ContractService getContractService() {
|
||||
if (contractService == null) {
|
||||
contractService = getBean(ContractService.class);
|
||||
}
|
||||
return contractService;
|
||||
}
|
||||
|
||||
PurchaseOrdersService getPurchaseOrdersService() {
|
||||
if (purchaseOrdersService == null) {
|
||||
purchaseOrdersService = getBean(PurchaseOrdersService.class);
|
||||
}
|
||||
return purchaseOrdersService;
|
||||
}
|
||||
|
||||
PurchaseOrderItemService getPurchaseOrderItemService() {
|
||||
if (purchaseOrderItemService == null) {
|
||||
purchaseOrderItemService = getBean(PurchaseOrderItemService.class);
|
||||
}
|
||||
return purchaseOrderItemService;
|
||||
}
|
||||
|
||||
public List<PurchaseOrder> syncByContract(Contract contract, MessageHolder holder) {
|
||||
PurchaseOrdersService ordersService = getPurchaseOrdersService();
|
||||
PurchaseOrderItemService itemService = getPurchaseOrderItemService();
|
||||
|
||||
List<PurchaseOrder> orders = ordersService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("contract"), contract);
|
||||
}, Sort.unsorted());
|
||||
holder.debug("查找到 " + orders.size() + " 条采购订单记录在数据库中");
|
||||
Map<Integer, PurchaseOrder> ordersMap = orders.stream()
|
||||
.collect(Collectors.toMap(PurchaseOrder::getRefId, item -> item));
|
||||
|
||||
List<PurchaseOrderItem> items = itemService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("order").get("contract"), contract);
|
||||
}, Sort.unsorted());
|
||||
|
||||
// 按 order 分组
|
||||
Map<PurchaseOrder, Map<Integer, PurchaseOrderItem>> itemMap = items.stream()
|
||||
.collect(Collectors.groupingBy(PurchaseOrderItem::getOrder,
|
||||
Collectors.toMap(PurchaseOrderItem::getRefId, item -> item)));
|
||||
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllPurchaseOrderItemByContractCode(contract.getCode());
|
||||
holder.debug("查找到 " + ds.size() + " 条采购订单条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
Map<PurchaseOrder, List<PurchaseOrderItem>> updateMap = new HashMap<>();
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer poId = (Integer) map.get("POID");
|
||||
if (poId == 0) {
|
||||
holder.warn("跳过无效采购订单记录:缺少 POID");
|
||||
continue;
|
||||
}
|
||||
PurchaseOrder order = ordersMap.get(poId);
|
||||
if (order == null) {
|
||||
order = new PurchaseOrder();
|
||||
order.setContract(contract);
|
||||
order.setRefId(poId);
|
||||
|
||||
order = ordersService.save(order);
|
||||
ordersMap.put(poId, order);
|
||||
holder.info("新增采购订单 #" + poId);
|
||||
}
|
||||
}
|
||||
for (Map<String, Object> map : ds) {
|
||||
// holder.debug("条目:" + map.toString());
|
||||
Integer poId = (Integer) map.get("POID");
|
||||
if (poId == 0) {
|
||||
holder.warn("跳过无效采购订单记录:缺少 POID");
|
||||
continue;
|
||||
}
|
||||
PurchaseOrder order = ordersMap.get(poId);
|
||||
|
||||
boolean itemModified = false;
|
||||
List<PurchaseOrderItem> updates = updateMap.computeIfAbsent(order, k -> new ArrayList<>());
|
||||
|
||||
// 获取条目标识并处理 null
|
||||
Integer refId = (Integer) map.get("ID");
|
||||
if (poId == null) {
|
||||
holder.warn("跳过条目:订单 " + poId + " 缺少 ID");
|
||||
continue;
|
||||
}
|
||||
Map<Integer, PurchaseOrderItem> subItemMap = itemMap.get(order);
|
||||
PurchaseOrderItem item = null;
|
||||
if (subItemMap != null) {
|
||||
item = subItemMap.remove(refId);
|
||||
}
|
||||
|
||||
if (item == null) {
|
||||
item = new PurchaseOrderItem();
|
||||
item.setOrder(order);
|
||||
item.setRefId(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增采购订单条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("---| ");
|
||||
if (applyPurchaseOrderItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = itemService.save(item);
|
||||
}
|
||||
updates.add(item);
|
||||
}
|
||||
|
||||
for (PurchaseOrder order : updateMap.keySet()) {
|
||||
if (applyPurchaseOrderDetail(order, repository.queryPurchaseOrderDetail(order.getRefId()), holder)) {
|
||||
ordersService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
if (!itemMap.isEmpty()) {
|
||||
for (Map<Integer, PurchaseOrderItem> subMap : itemMap.values()) {
|
||||
if (!subMap.isEmpty()) {
|
||||
for (PurchaseOrderItem item : subMap.values()) {
|
||||
holder.info("删除采购订单条目");
|
||||
itemService.delete(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (PurchaseOrder order : updateMap.keySet()) {
|
||||
itemMap.remove(order);
|
||||
}
|
||||
if (!itemMap.isEmpty()) {
|
||||
holder.info("剩余 " + itemMap.size() + " 个采购订单条目");
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(updateMap.keySet());
|
||||
}
|
||||
|
||||
private boolean applyPurchaseOrderDetail(PurchaseOrder order, Map<String, Object> map, MessageHolder holder) {
|
||||
String code = (String) map.get("cPOID");
|
||||
|
||||
String venBank = (String) map.get("cVenBank");
|
||||
String venBankAccount = (String) map.get("cVenAccount");
|
||||
|
||||
String venCode = (String) map.get("cVenCode");
|
||||
String memo = (String) map.get("cMemo");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
if (!Objects.equals(order.getCode(), code)) {
|
||||
order.setCode(code);
|
||||
holder.info("订单编号更新为 " + code);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateEmployeeByCode(order::getEmployee, order::setEmployee, (String) map.get("cPersonCode"), holder,
|
||||
"业务员")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(order::getMaker, order::setMaker, (String) map.get("cMaker"), holder, "制单人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(order::getVerifier, order::setVerifier, (String) map.get("cVerifier"), holder,
|
||||
"审核人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(order::getCloser, order::setCloser, (String) map.get("cCloser"), holder, "订单关闭人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(order::getMakerDate, order::setMakerDate, (Timestamp) map.get("cmaketime"), holder,
|
||||
"制单日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(order::getModifyDate, order::setModifyDate, (Timestamp) map.get("cModifyTime"), holder,
|
||||
"修改日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(order::getVerifierDate, order::setVerifierDate, (Timestamp) map.get("cAuditTime"),
|
||||
holder, "审核日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(order::getCloserDate, order::setCloserDate, (Timestamp) map.get("dCloseTime"), holder,
|
||||
"关闭日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(order.getVendorCode(), venCode)) {
|
||||
order.setVendorCode(venCode);
|
||||
holder.info("供方代码修改为: " + venCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(order.getDescription(), memo)) {
|
||||
order.setDescription(memo);
|
||||
holder.info("描述修改为: " + memo);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
updateCompanyBankAccount(order.getContract(), venBank, venBankAccount, holder);
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
private void updateCompanyBankAccount(Contract contract, String bank, String bankAccount, MessageHolder holder) {
|
||||
if (contract == null) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(contract)) {
|
||||
contract = getContractService().findById(contract.getId());
|
||||
}
|
||||
getCompanyBankAccountCtx().updateBankAccount(contract.getCompany(), bank, bankAccount, holder);
|
||||
}
|
||||
|
||||
private boolean applyPurchaseOrderItemDetail(PurchaseOrderItem item, Map<String, Object> map,
|
||||
MessageHolder holder) {
|
||||
Integer refId = (Integer) map.get("ID");
|
||||
String inventoryCode = (String) map.get("cInvCode");
|
||||
String contractCode = (String) map.get("ContractCode");
|
||||
|
||||
String title = (String) map.get("cInvCode");
|
||||
double quantity = (double) map.get("iQuantity");
|
||||
BigDecimal taxRate = (BigDecimal) map.get("iPerTaxRate");
|
||||
BigDecimal taxPrice = (BigDecimal) map.get("iTaxPrice");
|
||||
double exclusiveTaxPrice = (double) map.get("iUnitPrice");
|
||||
BigDecimal amount = (BigDecimal) map.get("iSum");
|
||||
|
||||
Timestamp arriveDate = (Timestamp) map.get("dArriveDate");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("条目:" + title + " x " + amount);
|
||||
if (updateInventory(item::getInventory, item::setInventory, inventoryCode, holder, "商品")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(item.getRefId(), refId)) {
|
||||
item.setRefId(refId);
|
||||
holder.info("RefId修改为: " + refId);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getExclusiveTaxPrice(), exclusiveTaxPrice)) {
|
||||
item.setExclusiveTaxPrice(exclusiveTaxPrice);
|
||||
holder.info("不含税单价修改为: " + exclusiveTaxPrice);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!NumberUtils.equals(item.getPrice(), taxPrice.doubleValue())) {
|
||||
item.setPrice(taxPrice.doubleValue());
|
||||
holder.info("含税单价修改为: " + taxPrice.doubleValue());
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getTaxRate(), taxRate.doubleValue())) {
|
||||
item.setTaxRate(taxRate.doubleValue());
|
||||
holder.info("税率修改为: " + taxRate);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getQuantity(), quantity)) {
|
||||
item.setQuantity(quantity);
|
||||
holder.info("数量修改为: " + quantity);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateLocalDate(item::getArriveDate, item::setArriveDate, (Timestamp) map.get("dArriveDate"), holder,
|
||||
"开始日期")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(item.getDescription(), contractCode)) {
|
||||
item.setDescription(contractCode);
|
||||
holder.info("描述修改为: " + contractCode);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
boolean updateInventory(Supplier<Inventory> getter, Consumer<Inventory> setter, String inventoryCode,
|
||||
MessageHolder holder, String topic) {
|
||||
return getInventoryCtx().syncInventoryDetailByCode(getter, setter, inventoryCode, holder, topic);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.model.Inventory;
|
||||
import com.ecep.contract.model.PurchaseSettlementVoucher;
|
||||
import com.ecep.contract.model.PurchaseSettlementVoucherItem;
|
||||
|
||||
public class PurchaseSettlementVoucherCtx extends AbstractYongYouU8Ctx {
|
||||
InventoryCtx inventoryCtx;
|
||||
|
||||
InventoryCtx getInventoryCtx() {
|
||||
if (inventoryCtx == null) {
|
||||
inventoryCtx = new InventoryCtx();
|
||||
inventoryCtx.from(this);
|
||||
}
|
||||
return inventoryCtx;
|
||||
}
|
||||
|
||||
private boolean applyPurchaseSettlementVoucherDetail(PurchaseSettlementVoucher voucher, Map<String, Object> map,
|
||||
MessageHolder holder) {
|
||||
String code = (String) map.get("cSVCode");
|
||||
String vendorCode = (String) map.get("cVenCode");
|
||||
String personCode = (String) map.get("cPersonCode");
|
||||
double taxRate = (double) map.get("iTaxRate");
|
||||
String maker = (String) map.get("cMaker");
|
||||
Timestamp date = (Timestamp) map.get("dSVDate");
|
||||
|
||||
String description = (String) map.get("cSVMemo");
|
||||
boolean modified = false;
|
||||
if (updateText(voucher::getCode, voucher::setCode, code, holder, "编号:")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateCompanyByVendorCode(voucher::getCompany, voucher::setCompany, vendorCode, holder, "供应商")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByCode(voucher::getEmployee, voucher::setEmployee, personCode, holder, "业务员")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(voucher::getMaker, voucher::setMaker, maker, holder, "制单人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(voucher::getDate, voucher::setDate, date, holder, "日期:")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateAppendText(voucher::getDescription, voucher::setDescription, description, holder, "描述")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean applyPurchaseSettlementVoucherItemDetail(PurchaseSettlementVoucherItem item,
|
||||
Map<String, Object> map, MessageHolder holder) {
|
||||
String inventoryCode = (String) map.get("cInvCode");
|
||||
String pivCode = (String) map.get("cPIVCode");
|
||||
String accountant = (String) map.get("cbAccounter");
|
||||
Integer rdsID = (Integer) map.get("iRdsID");
|
||||
double quantity = (double) map.get("iPBVQuantity");
|
||||
String description = (String) map.get("cbMemo");
|
||||
boolean modified = false;
|
||||
if (updateInventory(item::getInventory, item::setInventory, inventoryCode, holder, "商品")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getAccountant, item::setAccountant, accountant, holder, "会计师")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateNumber(item::getQuantity, item::setQuantity, quantity, holder, "数量")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateAppendText(item::getDescription, item::setDescription, description, holder, "描述")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
boolean updateInventory(Supplier<Inventory> getter, Consumer<Inventory> setter, String inventoryCode,
|
||||
MessageHolder holder, String topic) {
|
||||
return getInventoryCtx().syncInventoryDetailByCode(getter, setter, inventoryCode, holder, topic);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.ds.contract.service.SaleOrdersService;
|
||||
import com.ecep.contract.ds.contract.service.SalesBillVoucherService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyCustomer;
|
||||
import com.ecep.contract.model.CompanyCustomerEntity;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.model.Inventory;
|
||||
import com.ecep.contract.model.SalesBillVoucher;
|
||||
import com.ecep.contract.model.SalesBillVoucherItem;
|
||||
import com.ecep.contract.model.SalesOrder;
|
||||
import com.ecep.contract.util.NumberUtils;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class SalesBillVoucherCtx extends AbstractYongYouU8Ctx {
|
||||
@Setter
|
||||
private ContractService contractService;
|
||||
@Setter
|
||||
private SaleOrdersService saleOrdersService;
|
||||
@Setter
|
||||
private SalesBillVoucherService salesBillVoucherService;
|
||||
|
||||
InventoryCtx inventoryCtx;
|
||||
|
||||
ContractService getContractService() {
|
||||
if (contractService == null) {
|
||||
contractService = getBean(ContractService.class);
|
||||
}
|
||||
return contractService;
|
||||
}
|
||||
|
||||
SaleOrdersService getSaleOrdersService() {
|
||||
if (saleOrdersService == null) {
|
||||
saleOrdersService = getBean(SaleOrdersService.class);
|
||||
}
|
||||
return saleOrdersService;
|
||||
}
|
||||
|
||||
SalesBillVoucherService getSalesBillVoucherService() {
|
||||
if (salesBillVoucherService == null) {
|
||||
salesBillVoucherService = SpringApp.getBean(SalesBillVoucherService.class);
|
||||
}
|
||||
return salesBillVoucherService;
|
||||
}
|
||||
|
||||
InventoryCtx getInventoryCtx() {
|
||||
if (inventoryCtx == null) {
|
||||
inventoryCtx = new InventoryCtx();
|
||||
inventoryCtx.from(this);
|
||||
}
|
||||
return inventoryCtx;
|
||||
}
|
||||
|
||||
public void syncByCompany(Company company, MessageHolder holder) {
|
||||
|
||||
List<SalesBillVoucher> vouchers = salesBillVoucherService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("company"), company);
|
||||
}, Sort.unsorted());
|
||||
holder.debug("查找到 " + vouchers.size() + " 条专用发票记录在数据库中");
|
||||
Map<Integer, SalesBillVoucher> voucherMap = vouchers.stream().collect(Collectors.toMap(SalesBillVoucher::getRefId, item -> item));
|
||||
|
||||
CompanyCustomer customer = getCompanyCustomerService().findByCompany(company);
|
||||
if (customer != null) {
|
||||
List<CompanyCustomerEntity> entities = getCompanyCustomerEntityService().findAllByCustomer(customer);
|
||||
for (CompanyCustomerEntity entity : entities) {
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllSalesBillVoucherByCustomerCode(entity.getCode());
|
||||
holder.debug("查找" + entity.getCode() + "到 " + ds.size() + " 条专用发票记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer sbvid = (Integer) map.get("SBVID");
|
||||
if (sbvid == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 SBVID");
|
||||
continue;
|
||||
}
|
||||
SalesBillVoucher voucher = voucherMap.get(sbvid);
|
||||
boolean voucherModified = false;
|
||||
if (voucher == null) {
|
||||
voucher = new SalesBillVoucher();
|
||||
voucher.setCompany(company);
|
||||
voucher.setRefId(sbvid);
|
||||
voucherMap.put(sbvid, voucher);
|
||||
voucherModified = true;
|
||||
|
||||
holder.info("新增专用发票记录 #" + sbvid);
|
||||
}
|
||||
if (applySalesBillVoucherDetail(voucher, map, holder)) {
|
||||
voucherModified = true;
|
||||
}
|
||||
|
||||
if (voucherModified) {
|
||||
voucher = salesBillVoucherService.save(voucher);
|
||||
voucherMap.put(sbvid, voucher);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<SalesBillVoucherItem> items = salesBillVoucherService.findAllItems((root, q, cb) -> {
|
||||
return cb.equal(root.get("voucher").get("company"), company);
|
||||
}, Sort.unsorted());
|
||||
|
||||
// 按 order 分组
|
||||
Map<SalesBillVoucher, Map<Integer, SalesBillVoucherItem>> itemMap = items.stream().collect(Collectors.groupingBy(SalesBillVoucherItem::getVoucher,
|
||||
Collectors.toMap(SalesBillVoucherItem::getRefId, item -> item)));
|
||||
for (SalesBillVoucher voucher : voucherMap.values()) {
|
||||
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllSalesBillVoucherItemBySBVID(voucher.getRefId());
|
||||
holder.debug("专用发票#" + voucher.getRefId() + "查找到 " + ds.size() + "条条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
Map<Integer, SalesBillVoucherItem> subItemMap = itemMap.computeIfAbsent(voucher, k -> new HashMap<>());
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer refId = (Integer) map.get("ID");
|
||||
if (refId == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 ID");
|
||||
continue;
|
||||
}
|
||||
SalesBillVoucherItem item = subItemMap.remove(refId);
|
||||
boolean itemModified = false;
|
||||
if (item == null) {
|
||||
item = new SalesBillVoucherItem();
|
||||
item.setVoucher(voucher);
|
||||
item.setRefId(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增专用发票条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("---| ");
|
||||
if (applySalesBillVoucherItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = salesBillVoucherService.save(item);
|
||||
}
|
||||
}
|
||||
for (SalesBillVoucherItem item : subItemMap.values()) {
|
||||
holder.info("删除无效专用发票条目");
|
||||
salesBillVoucherService.delete(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void syncBySalesOrder(SalesOrder order, MessageHolder holder) {
|
||||
SalesBillVoucherService voucherService = getSalesBillVoucherService();
|
||||
List<SalesBillVoucher> vouchers = voucherService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("order"), order);
|
||||
}, Sort.unsorted());
|
||||
holder.debug("查找到 " + vouchers.size() + " 条专用发票记录在数据库中");
|
||||
Map<Integer, SalesBillVoucher> voucherMap = vouchers.stream().collect(Collectors.toMap(SalesBillVoucher::getRefId, item -> item));
|
||||
{
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllSalesBillVoucherBySalesOrderCode(order.getCode());
|
||||
holder.debug("查找" + order.getCode() + "到 " + ds.size() + " 条专用发票记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer sbvid = (Integer) map.get("SBVID");
|
||||
if (sbvid == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 SBVID");
|
||||
continue;
|
||||
}
|
||||
SalesBillVoucher voucher = voucherMap.get(sbvid);
|
||||
boolean voucherModified = false;
|
||||
if (voucher == null) {
|
||||
voucher = new SalesBillVoucher();
|
||||
|
||||
Contract contract = order.getContract();
|
||||
if (!Hibernate.isInitialized(contract)) {
|
||||
contract = getContractService().findById(contract.getId());
|
||||
}
|
||||
voucher.setCompany(contract.getCompany());
|
||||
voucher.setRefId(sbvid);
|
||||
voucherMap.put(sbvid, voucher);
|
||||
voucherModified = true;
|
||||
|
||||
holder.info("新增专用发票记录 #" + sbvid);
|
||||
}
|
||||
if (applySalesBillVoucherDetail(voucher, map, holder)) {
|
||||
voucherModified = true;
|
||||
}
|
||||
|
||||
if (voucherModified) {
|
||||
voucher = voucherService.save(voucher);
|
||||
voucherMap.put(sbvid, voucher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<SalesBillVoucherItem> items = voucherService.findAllItems((root, q, cb) -> {
|
||||
return cb.equal(root.get("voucher").get("order"), order);
|
||||
}, Sort.unsorted());
|
||||
|
||||
// 按 order 分组
|
||||
Map<SalesBillVoucher, Map<Integer, SalesBillVoucherItem>> itemMap = items.stream().collect(Collectors.groupingBy(SalesBillVoucherItem::getVoucher,
|
||||
Collectors.toMap(SalesBillVoucherItem::getRefId, item -> item)));
|
||||
for (SalesBillVoucher voucher : voucherMap.values()) {
|
||||
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllSalesBillVoucherItemBySBVID(voucher.getRefId());
|
||||
holder.debug("专用发票#" + voucher.getRefId() + "查找到 " + ds.size() + "条条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
Map<Integer, SalesBillVoucherItem> subItemMap = itemMap.computeIfAbsent(voucher, k -> new HashMap<>());
|
||||
for (Map<String, Object> map : ds) {
|
||||
Integer refId = (Integer) map.get("AutoID");
|
||||
if (refId == 0) {
|
||||
holder.warn("跳过无效专用发票记录:缺少 AutoID");
|
||||
continue;
|
||||
}
|
||||
SalesBillVoucherItem item = subItemMap.remove(refId);
|
||||
boolean itemModified = false;
|
||||
if (item == null) {
|
||||
item = new SalesBillVoucherItem();
|
||||
item.setVoucher(voucher);
|
||||
item.setRefId(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增专用发票条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("---| ");
|
||||
if (applySalesBillVoucherItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = voucherService.save(item);
|
||||
}
|
||||
}
|
||||
for (SalesBillVoucherItem item : subItemMap.values()) {
|
||||
holder.info("删除无效专用发票条目");
|
||||
voucherService.delete(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private boolean applySalesBillVoucherDetail(SalesBillVoucher voucher, Map<String, Object> map, MessageHolder holder) {
|
||||
String code = String.valueOf(map.get("SBVID"));
|
||||
String customerCode = (String) map.get("cCusCode");
|
||||
String salesOrderCode = (String) map.get("cSOCode");
|
||||
String personCode = (String) map.get("cPersonCode");
|
||||
String inCode = (String) map.get("cDLCode");
|
||||
Timestamp billDate = (Timestamp) map.get("dDate");
|
||||
|
||||
String maker = (String) map.get("cMaker");
|
||||
String checker = (String) map.get("cChecker");
|
||||
String modifier = (String) map.get("cmodifier");
|
||||
String verifier = (String) map.get("cVerifier");
|
||||
Timestamp makeTime = (Timestamp) map.get("cmaketime");
|
||||
Timestamp verifyTime = (Timestamp) map.get("dverifysystime");
|
||||
Timestamp modifyTime = (Timestamp) map.get("dmodifysystime");
|
||||
|
||||
String description = (String) map.get("cMemo");
|
||||
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("条目:" + code + " x " + salesOrderCode);
|
||||
if (updateCompanyByCustomerCode(voucher::getCompany, voucher::setCompany, customerCode, holder, "客户")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
SalesOrder salesOrder = null;
|
||||
if (StringUtils.hasText(salesOrderCode)) {
|
||||
salesOrder = getSaleOrdersService().findByCode(salesOrderCode);
|
||||
}
|
||||
if (salesOrder == null) {
|
||||
voucher.setOrder(null);
|
||||
holder.warn("无效销售订单:" + salesOrderCode);
|
||||
modified = true;
|
||||
} else {
|
||||
if (!Objects.equals(voucher.getOrder(), salesOrder)) {
|
||||
voucher.setOrder(salesOrder);
|
||||
holder.info("销售订单修改为: " + salesOrder.getCode());
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (updateEmployeeByCode(voucher::getEmployee, voucher::setEmployee, personCode, holder, "业务员")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(voucher::getMaker, voucher::setMaker, maker, holder, "制单人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(voucher::getVerifier, voucher::setVerifier, verifier, holder, "审核人")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateLocalDateTime(voucher::getMakerDate, voucher::setMakerDate, makeTime, holder, "制单时间")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDateTime(voucher::getVerifierDate, voucher::setVerifierDate, verifyTime, holder, "审核时间")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(voucher.getDescription(), description)) {
|
||||
voucher.setDescription(description);
|
||||
holder.info("描述修改为: " + description);
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
private boolean applySalesBillVoucherItemDetail(SalesBillVoucherItem item, Map<String, Object> map, MessageHolder holder) {
|
||||
String code = String.valueOf(map.get("ID"));
|
||||
String inventoryCode = (String) map.get("cInvCode");
|
||||
String contractCode = (String) map.get("ContractCode");
|
||||
|
||||
String title = (String) map.get("cInvCode");
|
||||
double quantity = (double) map.get("iQuantity");
|
||||
double taxRate = (double) map.get("iTaxRate");
|
||||
double taxPrice = (double) map.get("iTaxUnitPrice");
|
||||
BigDecimal amount = (BigDecimal) map.get("iSum");
|
||||
|
||||
|
||||
Timestamp signDate = (Timestamp) map.get("dSignDate");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("条目:" + title + " x " + amount);
|
||||
|
||||
if (updateInventory(item::getInventory, item::setInventory, inventoryCode, holder, "商品")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!NumberUtils.equals(item.getPrice(), taxPrice)) {
|
||||
item.setPrice(taxPrice);
|
||||
holder.info("含税单价修改为: " + taxPrice);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getQuantity(), quantity)) {
|
||||
item.setQuantity(quantity);
|
||||
holder.info("数量修改为: " + quantity);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(item.getDescription(), contractCode)) {
|
||||
item.setDescription(contractCode);
|
||||
holder.info("描述修改为: " + contractCode);
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
boolean updateInventory(Supplier<Inventory> getter, Consumer<Inventory> setter, String inventoryCode, MessageHolder holder, String topic) {
|
||||
return getInventoryCtx().syncInventoryDetailByCode(getter, setter, inventoryCode, holder, topic);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import static com.ecep.contract.SpringApp.getBean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.contract.service.SaleOrdersService;
|
||||
import com.ecep.contract.ds.contract.service.SalesOrderItemService;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.model.SalesOrder;
|
||||
import com.ecep.contract.model.SalesOrderItem;
|
||||
import com.ecep.contract.util.NumberUtils;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class SalesOrderCtx extends AbstractYongYouU8Ctx {
|
||||
|
||||
@Setter
|
||||
private SaleOrdersService saleOrdersService;
|
||||
@Setter
|
||||
private SalesOrderItemService orderItemService;
|
||||
|
||||
SaleOrdersService getSaleOrdersService() {
|
||||
if (saleOrdersService == null) {
|
||||
saleOrdersService = getBean(SaleOrdersService.class);
|
||||
}
|
||||
return saleOrdersService;
|
||||
}
|
||||
|
||||
SalesOrderItemService getOrderItemService() {
|
||||
if (orderItemService == null) {
|
||||
orderItemService = getBean(SalesOrderItemService.class);
|
||||
}
|
||||
return orderItemService;
|
||||
}
|
||||
|
||||
|
||||
public List<SalesOrder> syncByContract(Contract contract, MessageHolder holder) {
|
||||
SaleOrdersService saleOrdersService = getSaleOrdersService();
|
||||
SalesOrderItemService orderItemService = getOrderItemService();
|
||||
|
||||
List<SalesOrder> orders = saleOrdersService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("contract"), contract);
|
||||
}, Sort.unsorted());
|
||||
holder.debug("查找到 " + orders.size() + " 条销售订单记录在数据库中");
|
||||
Map<String, SalesOrder> ordersMap = orders.stream().collect(Collectors.toMap(SalesOrder::getCode, item -> item));
|
||||
|
||||
List<SalesOrderItem> items = orderItemService.findAll((root, q, cb) -> {
|
||||
return cb.equal(root.get("order").get("contract"), contract);
|
||||
}, Sort.unsorted());
|
||||
|
||||
// 按 order 分组
|
||||
Map<SalesOrder, Map<String, SalesOrderItem>> itemMap = items.stream().collect(Collectors.groupingBy(SalesOrderItem::getOrder,
|
||||
Collectors.toMap(SalesOrderItem::getCode, item -> item)));
|
||||
|
||||
// 查询 U8 数据库
|
||||
List<Map<String, Object>> ds = repository.findAllSalesOrderItemByContractCode(contract.getCode());
|
||||
holder.debug("查找到 " + ds.size() + " 条销售订单条目记录在 " + CloudServiceConstant.U8_NAME);
|
||||
|
||||
Map<SalesOrder, List<SalesOrderItem>> updateMap = new HashMap<>();
|
||||
for (Map<String, Object> map : ds) {
|
||||
String orderCode = Optional.ofNullable(map.get("cSOCode")).map(Object::toString).orElse("");
|
||||
if (orderCode.isEmpty()) {
|
||||
holder.warn("跳过无效销售订单记录:缺少 cSOCode");
|
||||
continue;
|
||||
}
|
||||
SalesOrder order = ordersMap.get(orderCode);
|
||||
if (order == null) {
|
||||
order = new SalesOrder();
|
||||
order.setContract(contract);
|
||||
order.setCode(orderCode);
|
||||
|
||||
order = saleOrdersService.save(order);
|
||||
ordersMap.put(orderCode, order);
|
||||
holder.info("新增销售订单 #" + orderCode);
|
||||
}
|
||||
}
|
||||
for (Map<String, Object> map : ds) {
|
||||
// holder.debug("条目:" + map.toString());
|
||||
String orderCode = Optional.ofNullable(map.get("cSOCode")).map(Object::toString).orElse("");
|
||||
if (orderCode.isEmpty()) {
|
||||
holder.warn("跳过无效销售订单记录:缺少 cSOCode");
|
||||
continue;
|
||||
}
|
||||
SalesOrder order = ordersMap.get(orderCode);
|
||||
|
||||
boolean itemModified = false;
|
||||
List<SalesOrderItem> updates = updateMap.computeIfAbsent(order, k -> new ArrayList<>());
|
||||
|
||||
// 获取条目标识并处理 null
|
||||
String refId = Optional.ofNullable(map.get("iSOsID")).map(Object::toString).orElse("");
|
||||
if (refId.isEmpty()) {
|
||||
holder.warn("跳过条目:订单 " + orderCode + " 缺少 iSOsID");
|
||||
continue;
|
||||
}
|
||||
Map<String, SalesOrderItem> subItemMap = itemMap.get(order);
|
||||
SalesOrderItem item = null;
|
||||
if (subItemMap != null) {
|
||||
item = subItemMap.remove(refId);
|
||||
}
|
||||
|
||||
if (item == null) {
|
||||
item = new SalesOrderItem();
|
||||
item.setOrder(order);
|
||||
item.setCode(refId);
|
||||
itemModified = true;
|
||||
|
||||
holder.info("新增销售订单条目 #" + refId);
|
||||
}
|
||||
MessageHolder subHolder = holder.sub("---| ");
|
||||
if (applySaleOrderItemDetail(item, map, subHolder)) {
|
||||
itemModified = true;
|
||||
}
|
||||
if (itemModified) {
|
||||
item = orderItemService.save(item);
|
||||
}
|
||||
updates.add(item);
|
||||
}
|
||||
|
||||
for (SalesOrder order : updateMap.keySet()) {
|
||||
holder.debug("销售订单 #" + order.getCode());
|
||||
if (applySalesOrderDetail(order, repository.querySalesOrderDetail(order.getCode()), holder)) {
|
||||
saleOrdersService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
if (!itemMap.isEmpty()) {
|
||||
for (Map<String, SalesOrderItem> subMap : itemMap.values()) {
|
||||
if (!subMap.isEmpty()) {
|
||||
for (SalesOrderItem item : subMap.values()) {
|
||||
holder.info("删除销售订单条目");
|
||||
orderItemService.delete(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (SalesOrder order : updateMap.keySet()) {
|
||||
itemMap.remove(order);
|
||||
}
|
||||
if (!itemMap.isEmpty()) {
|
||||
holder.info("剩余 " + itemMap.size() + " 个销售订单条目");
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(updateMap.keySet());
|
||||
|
||||
}
|
||||
|
||||
private boolean applySalesOrderDetail(SalesOrder order, Map<String, Object> map, MessageHolder holder) {
|
||||
String code = (String) map.get("cSOCode");
|
||||
|
||||
String cCloser = (String) map.get("cCloser");
|
||||
|
||||
String memo = (String) map.get("cMemo");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
if (!Objects.equals(order.getCode(), code)) {
|
||||
order.setCode(code);
|
||||
holder.info("订单编号更新为 " + code);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateEmployeeByCode(order::getEmployee, order::setEmployee, (String) map.get("cPersonCode"), holder, "业务员")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(order::getMaker, order::setMaker, (String) map.get("cMaker"), holder, "制单人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(order::getVerifier, order::setVerifier, (String) map.get("cVerifier"), holder, "审核人")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (updateLocalDate(order::getMakerDate, order::setMakerDate, (Timestamp) map.get("dcreatesystime"), holder, "制单日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(order::getVerifierDate, order::setVerifierDate, (Timestamp) map.get("dverifysystime"), holder, "审核日期")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(order.getDescription(), memo)) {
|
||||
order.setDescription(memo);
|
||||
holder.info("描述修改为: " + memo);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
private boolean applySaleOrderItemDetail(SalesOrderItem item, Map<String, Object> map, MessageHolder holder) {
|
||||
String code = String.valueOf(map.get("iSOsID"));
|
||||
String spec = (String) map.get("cInvName");
|
||||
String title = (String) map.get("cInvName");
|
||||
double quantity = (double) map.get("iQuantity");
|
||||
double taxRate = (double) map.get("iTaxRate");
|
||||
double taxPrice = (double) map.get("iTaxUnitPrice");
|
||||
double exclusiveTaxPrice = (double) map.get("iUnitPrice");
|
||||
BigDecimal amount = (BigDecimal) map.get("iSum");
|
||||
|
||||
String memo = (String) map.get("cMemo");
|
||||
|
||||
boolean modified = false;
|
||||
|
||||
holder.debug("条目:" + title + " x " + amount);
|
||||
|
||||
|
||||
if (!Objects.equals(item.getCode(), code)) {
|
||||
item.setCode(code);
|
||||
holder.info("代码修改为: " + code);
|
||||
modified = true;
|
||||
}
|
||||
if (!Objects.equals(item.getName(), title)) {
|
||||
item.setName(title);
|
||||
holder.info("名称修改为: " + title);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getExclusiveTaxPrice(), exclusiveTaxPrice)) {
|
||||
item.setExclusiveTaxPrice(exclusiveTaxPrice);
|
||||
holder.info("不含税单价修改为: " + exclusiveTaxPrice);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getPrice(), taxPrice)) {
|
||||
item.setPrice(taxPrice);
|
||||
holder.info("含税单价修改为: " + taxPrice);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getTaxRate(), taxRate)) {
|
||||
item.setTaxRate(taxRate);
|
||||
holder.info("税率修改为: " + taxRate);
|
||||
modified = true;
|
||||
}
|
||||
if (!NumberUtils.equals(item.getQuantity(), quantity)) {
|
||||
item.setQuantity(quantity);
|
||||
holder.info("数量修改为: " + quantity);
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getStartDate, item::setStartDate, (Timestamp) map.get("dPreDate"), holder, "开始日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getEndDate, item::setEndDate, (Timestamp) map.get("dPreMoDate"), holder, "结束日期")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!Objects.equals(item.getDescription(), memo)) {
|
||||
item.setDescription(memo);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package com.ecep.contract.cloud.u8.ctx;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.old.OldVersionService;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorEntityService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyVendor;
|
||||
import com.ecep.contract.model.CompanyVendorEntity;
|
||||
import com.ecep.contract.model.VendorCatalog;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
public class VendorCtx extends AbstractYongYouU8Ctx {
|
||||
private static final String AUTO_CREATE_VENDOR_AFTER = "cloud.u8.auto-create-vendor-after";
|
||||
@Setter
|
||||
private CompanyVendorService companyVendorService;
|
||||
@Setter
|
||||
private CompanyCtx companyCtx;
|
||||
@Setter
|
||||
private ContractCtx contractCtx;
|
||||
@Setter
|
||||
private CompanyBankAccountCtx companyBankAccountCtx;
|
||||
|
||||
public CompanyCtx getCompanyCtx() {
|
||||
if (companyCtx == null) {
|
||||
companyCtx = new CompanyCtx();
|
||||
companyCtx.from(this);
|
||||
}
|
||||
return companyCtx;
|
||||
}
|
||||
|
||||
ContractCtx getContractCtx() {
|
||||
if (contractCtx == null) {
|
||||
contractCtx = new ContractCtx();
|
||||
contractCtx.from(this);
|
||||
}
|
||||
return contractCtx;
|
||||
}
|
||||
|
||||
CompanyBankAccountCtx getCompanyBankAccountCtx() {
|
||||
if (companyBankAccountCtx == null) {
|
||||
companyBankAccountCtx = new CompanyBankAccountCtx();
|
||||
companyBankAccountCtx.from(this);
|
||||
}
|
||||
return companyBankAccountCtx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新供应商相关项(相关项是 U8 系统中的 Vendor 表数据,因为同一个公司有多个相关项,因此需要一个一对多的关系来处理)详情
|
||||
*
|
||||
* @param item 供应商相关项
|
||||
* @param unitCode 供应商相关项编码
|
||||
* @param holder 消息
|
||||
*/
|
||||
public CompanyVendorEntity updateVendorEntityDetailByCode(CompanyVendorEntity item, String unitCode, MessageHolder holder) {
|
||||
if (applyEntityDetail(item, repository.findVendorByVendCode(unitCode), holder)) {
|
||||
item = save(item);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
public boolean applyEntityDetail(CompanyVendorEntity item, Map<String, Object> map, MessageHolder holder) {
|
||||
if (map == null || map.isEmpty()) {
|
||||
holder.warn("Vendor 中未检索到供应商数据");
|
||||
return false;
|
||||
}
|
||||
String name = (String) map.get("cVenName");
|
||||
String abbName = (String) map.get("cVenAbbName");
|
||||
String venCode = (String) map.get("cVenCode");
|
||||
String classCode = (String) map.get("cVCCode");
|
||||
|
||||
String createPerson = (String) map.get("cCreatePerson");
|
||||
String modifyPerson = (String) map.get("cModifyPerson");
|
||||
java.sql.Date devDate = (java.sql.Date) map.get("devDate");
|
||||
java.sql.Timestamp modifyDate = (java.sql.Timestamp) map.get("dModifyDate");
|
||||
java.sql.Timestamp createDatetime = (java.sql.Timestamp) map.get("dVenCreateDatetime");
|
||||
|
||||
String bank = (String) map.get("cVenBank");
|
||||
String bankAccount = (String) map.get("cVenAccount");
|
||||
String address = (String) map.get("cVenAddress");
|
||||
String phone = (String) map.get("cVenPhone");
|
||||
String person = (String) map.get("cVenPerson");
|
||||
|
||||
|
||||
boolean modified = false;
|
||||
if (updateText(item::getName, item::setName, name, holder, "名称")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(item::getAbbName, item::setAbbName, abbName, holder, "简称")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateText(item::getCode, item::setCode, venCode, holder, "供应商编号")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateVendorCatalog(item::getCatalog, item::setCatalog, classCode, holder, "分类")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getCreator, item::setCreator, createPerson, holder, "创建人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateEmployeeByName(item::getModifier, item::setModifier, modifyPerson, holder, "修改人")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getDevelopDate, item::setDevelopDate, devDate, holder, "开发日期")) {
|
||||
modified = true;
|
||||
}
|
||||
if (updateLocalDate(item::getModifyDate, item::setModifyDate, modifyDate, holder, "修改日期")) {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
LocalDate today = LocalDate.now();
|
||||
if (item.getUpdatedDate() == null || item.getUpdatedDate().isBefore(today)) {
|
||||
item.setUpdatedDate(today);
|
||||
holder.info("更新日期更新为 " + today);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
CompanyVendor vendor = item.getVendor();
|
||||
if (vendor == null) {
|
||||
// 如果没有关联供应商,则根据供应商名称或别名查找公司
|
||||
Company company = findOrCreateCompanyByVendorEntity(item, holder);
|
||||
if (company != null) {
|
||||
vendor = getCompanyVendorService().findByCompany(company);
|
||||
if (vendor == null) {
|
||||
vendor = createVendorByVendorEntity(item, holder);
|
||||
if (vendor != null) {
|
||||
vendor.setCompany(company);
|
||||
vendor = getCompanyVendorService().save(vendor);
|
||||
}
|
||||
}
|
||||
if (vendor != null) {
|
||||
item.setVendor(vendor);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (vendor != null) {
|
||||
if (!Hibernate.isInitialized(vendor)) {
|
||||
vendor = getCompanyVendorService().findById(vendor.getId());
|
||||
}
|
||||
Company company = vendor.getCompany();
|
||||
if (company != null) {
|
||||
getCompanyBankAccountCtx().updateBankAccount(company, bank, bankAccount, holder.sub(item.getName()));
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean updateVendorCatalog(Supplier<VendorCatalog> getter, Consumer<VendorCatalog> setter, String catalogCode, MessageHolder holder, String topic) {
|
||||
VendorCatalog catalog = null;
|
||||
if (StringUtils.hasText(catalogCode)) {
|
||||
catalog = getCompanyVendorService().findCatalogByCode(catalogCode);
|
||||
}
|
||||
if (catalog == null) {
|
||||
setter.accept(null);
|
||||
holder.warn("无效" + topic + ":" + catalogCode);
|
||||
return true;
|
||||
} else {
|
||||
if (!Objects.equals(getter.get(), catalog)) {
|
||||
if (!Hibernate.isInitialized(catalog)) {
|
||||
catalog = getCompanyVendorService().findCatalogByCode(catalogCode);
|
||||
}
|
||||
setter.accept(catalog);
|
||||
holder.info(topic + "修改为: " + catalog.getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步供应商
|
||||
*
|
||||
* @param company 要同步的供应商企业
|
||||
* @param holder 状态输出
|
||||
* @return 是否更新了供应商信息
|
||||
*/
|
||||
public boolean syncVendor(Company company, MessageHolder holder) {
|
||||
CompanyVendor companyVendor = getCompanyVendorService().findByCompany(company);
|
||||
if (companyVendor == null) {
|
||||
holder.warn("供应商未创建, 如需要请手动创建.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检索相关项
|
||||
List<CompanyVendorEntity> entities = getCompanyVendorEntityService().findAllByVendor(companyVendor);
|
||||
if (entities.isEmpty()) {
|
||||
holder.error("供应商关联任何相关项");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean updated = false;
|
||||
boolean companyModified = false;
|
||||
|
||||
// 更新相关项
|
||||
for (CompanyVendorEntity entity : entities) {
|
||||
if (!StringUtils.hasText(entity.getCode())) {
|
||||
holder.warn("相关项:" + entity.getCode() + " 无效,跳过");
|
||||
continue;
|
||||
}
|
||||
if (applyEntityDetail(entity, repository.findVendorByVendCode(entity.getCode()), holder)) {
|
||||
entity = getCompanyVendorEntityService().save(entity);
|
||||
}
|
||||
if (updateCompanyNameAndAbbNameByVendorEntity(company, entity, holder)) {
|
||||
companyModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (companyModified) {
|
||||
company = getCompanyService().save(company);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
// 更新供应商的开发日期
|
||||
if (updateVendorDevelopDate(companyVendor, entities, holder)) {
|
||||
companyVendor = getCompanyVendorService().save(companyVendor);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
// 同步供应商关联的合同
|
||||
for (CompanyVendorEntity entity : entities) {
|
||||
if (getContractCtx().syncByVendorEntity(companyVendor, entity, holder)) {
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private boolean updateCompanyNameAndAbbNameByVendorEntity(Company company, CompanyVendorEntity entity, MessageHolder holder) {
|
||||
CompanyService companyService = getCompanyService();
|
||||
if (company == null) {
|
||||
return false;
|
||||
}
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = companyService.findById(company.getId());
|
||||
}
|
||||
boolean modified = false;
|
||||
CompanyCtx companyCtx = getCompanyCtx();
|
||||
if (companyCtx.updateCompanyNameIfAbsent(company, entity.getName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
if (companyCtx.updateCompanyAbbNameIfAbsent(company, entity.getAbbName(), holder)) {
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private boolean updateVendorDevelopDate(CompanyVendor companyVendor, List<CompanyVendorEntity> entities, MessageHolder holder) {
|
||||
LocalDate developDate = null;
|
||||
for (CompanyVendorEntity entity : entities) {
|
||||
// 取最早的开发日期
|
||||
if (developDate == null || entity.getDevelopDate().isBefore(developDate)) {
|
||||
developDate = entity.getDevelopDate();
|
||||
}
|
||||
}
|
||||
return updateLocalDate(companyVendor::getDevelopDate, companyVendor::setDevelopDate, developDate, holder, "开发日期");
|
||||
}
|
||||
|
||||
public CompanyVendorEntity findOrCreateByCode(String venCode, MessageHolder subHolder) {
|
||||
CompanyVendorEntityService service = getCompanyVendorEntityService();
|
||||
CompanyVendorEntity entity = service.findByCode(venCode);
|
||||
if (entity == null) {
|
||||
entity = new CompanyVendorEntity();
|
||||
entity.setCode(venCode);
|
||||
entity = service.save(entity);
|
||||
subHolder.info("创建供应商相关项: " + venCode);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private CompanyVendor createVendorByVendorEntity(CompanyVendorEntity entity, MessageHolder holder) {
|
||||
LocalDate developDate = entity.getDevelopDate();
|
||||
if (developDate == null) {
|
||||
holder.warn(entity.getName() + " 没有设置开发日期,跳过");
|
||||
return null;
|
||||
}
|
||||
// 创建发展日期从2023年1月1日后的
|
||||
LocalDate start = LocalDate.of(2023, 1, 1);
|
||||
String autoCreateAfter = getConfService().getString(AUTO_CREATE_VENDOR_AFTER);
|
||||
if (StringUtils.hasText(autoCreateAfter)) {
|
||||
start = LocalDate.parse(autoCreateAfter);
|
||||
}
|
||||
if (developDate.isBefore(start)) {
|
||||
// start 之前的不自动创建
|
||||
holder.warn(entity.getName() + " 的发展日期 " + developDate + " 是 " + start + " 之前的, 按规定不自动创建供应商, 如有需要请手动创建");
|
||||
return null;
|
||||
}
|
||||
|
||||
CompanyVendor companyVendor = new CompanyVendor();
|
||||
int nextId = SpringApp.getBean(OldVersionService.class).newCompanyVendor(entity.getName());
|
||||
companyVendor.setId(nextId);
|
||||
companyVendor.setCatalog(entity.getCatalog());
|
||||
companyVendor.setDevelopDate(developDate);
|
||||
holder.info("新供应商:" + entity.getName() + "分配编号:" + nextId);
|
||||
companyVendor.setCreated(Instant.now());
|
||||
return companyVendor;
|
||||
}
|
||||
|
||||
|
||||
private Company findOrCreateCompanyByVendorEntity(CompanyVendorEntity entity, MessageHolder holder) {
|
||||
String name = entity.getName();
|
||||
String abbName = entity.getAbbName();
|
||||
return getCompanyCtx().findOrCreateByNameOrAbbName(name, abbName, entity.getDevelopDate(), holder);
|
||||
}
|
||||
|
||||
public CompanyVendorEntity save(CompanyVendorEntity entity) {
|
||||
return getCompanyVendorEntityService().save(entity);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ecep.contract.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
import io.swagger.v3.oas.models.servers.Server;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* OpenAPI配置类,用于配置Swagger文档
|
||||
*/
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("合同管理系统 API")
|
||||
.version("1.0")
|
||||
.description("合同管理系统的REST API文档")
|
||||
.contact(new Contact()
|
||||
.name("宋其青")
|
||||
.email("qiqing.song@ecep.com"))
|
||||
.license(new License()
|
||||
.name("内部使用")
|
||||
.url("http://10.84.210.110")))
|
||||
.servers(List.of(
|
||||
new Server().url("http://localhost:8080").description("开发环境"),
|
||||
new Server().url("http://10.84.210.110:8080").description("测试环境")
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.ecep.contract.config;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.config.Customizer;
|
||||
|
||||
import com.ecep.contract.ds.other.service.EmployeeService;
|
||||
import com.ecep.contract.model.Employee;
|
||||
import com.ecep.contract.model.EmployeeRole;
|
||||
|
||||
/**
|
||||
* Spring Security配置类
|
||||
* 用于配置安全认证和授权规则
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
private EmployeeService employeeService;
|
||||
|
||||
/**
|
||||
* 配置HTTP安全策略
|
||||
* 启用表单登录和HTTP Basic认证
|
||||
*/
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers("/login.html", "/css/**", "/js/**", "/images/**", "/webjars/**", "/login", "/error").permitAll() // 允许静态资源、登录页面和错误页面访问
|
||||
.anyRequest().authenticated() // 其他所有请求需要认证
|
||||
)
|
||||
.csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护,适合开发环境
|
||||
.formLogin(form -> form
|
||||
.loginPage("/login.html") // 直接使用静态登录页面
|
||||
.loginProcessingUrl("/login") // 登录处理URL
|
||||
.permitAll() // 允许所有人访问登录页面
|
||||
.defaultSuccessUrl("/", true) // 登录成功后重定向到首页
|
||||
.failureUrl("/login.html?error=true") // 登录失败后重定向到登录页面并显示错误
|
||||
.usernameParameter("username") // 用户名参数名
|
||||
.passwordParameter("password") // 密码参数名
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults()) // 启用HTTP Basic认证
|
||||
.logout(logout -> logout
|
||||
.logoutUrl("/logout") // 注销URL
|
||||
.logoutSuccessUrl("/login?logout=true") // 注销成功后重定向到登录页面
|
||||
.invalidateHttpSession(true) // 使会话失效
|
||||
.deleteCookies("JSESSIONID") // 删除会话cookie
|
||||
.permitAll() // 允许所有人访问注销URL
|
||||
)
|
||||
.sessionManagement(session -> session
|
||||
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // 根据需要创建会话
|
||||
.maximumSessions(1) // 每个用户最多1个会话
|
||||
.expiredUrl("/login?expired=true") // 会话过期后重定向到登录页面
|
||||
)
|
||||
.authenticationManager(authenticationManager); // 设置认证管理器
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置AuthenticationManager
|
||||
* 用于处理认证请求
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置密码编码器
|
||||
* BCryptPasswordEncoder是Spring Security推荐的密码编码器
|
||||
*/
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置基于EmployeeService的用户认证
|
||||
* 通过EmployeeService获取员工信息并转换为Spring Security的UserDetails
|
||||
*/
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
return username -> {
|
||||
// 使用EmployeeService根据用户名查找员工
|
||||
Employee employee = employeeService.findByAccount(username);
|
||||
|
||||
// 如果找不到员工,抛出UsernameNotFoundException异常
|
||||
if (employee == null) {
|
||||
throw new UsernameNotFoundException("用户不存在: " + username);
|
||||
}
|
||||
|
||||
// 检查员工是否活跃
|
||||
if (!employee.isActive()) {
|
||||
throw new UsernameNotFoundException("用户已禁用: " + username);
|
||||
}
|
||||
|
||||
// 将员工角色转换为Spring Security的GrantedAuthority
|
||||
List<GrantedAuthority> authorities = getAuthoritiesFromRoles(employee.getRoles());
|
||||
|
||||
// 创建并返回UserDetails对象
|
||||
// 注意:根据系统设计,Employee实体中没有密码字段,系统使用IP/MAC绑定认证
|
||||
// 这里使用密码编码器加密后的固定密码,确保认证流程能够正常工作
|
||||
return User.builder()
|
||||
.username(employee.getName())
|
||||
.password(passwordEncoder().encode("default123")) // 使用默认密码进行加密
|
||||
.authorities(authorities)
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将EmployeeRole列表转换为Spring Security的GrantedAuthority列表
|
||||
*/
|
||||
private List<GrantedAuthority> getAuthoritiesFromRoles(List<EmployeeRole> roles) {
|
||||
if (roles == null || roles.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 为每个角色创建GrantedAuthority
|
||||
// 系统管理员拥有ADMIN角色,其他用户拥有USER角色
|
||||
return roles.stream()
|
||||
.filter(EmployeeRole::isActive) // 只包含活跃的角色
|
||||
.map(role -> {
|
||||
if (role.isSystemAdministrator()) {
|
||||
return new SimpleGrantedAuthority("ROLE_ADMIN");
|
||||
} else {
|
||||
return new SimpleGrantedAuthority("ROLE_USER");
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// Spring Security会自动配置一个使用我们定义的UserDetailsService的DaoAuthenticationProvider
|
||||
// 移除显式的authenticationProvider Bean定义以避免警告
|
||||
// 当同时存在AuthenticationProvider和UserDetailsService Bean时,Spring Security会优先使用AuthenticationProvider
|
||||
// 而忽略直接的UserDetailsService,虽然这不影响功能,但会产生警告
|
||||
}
|
||||
39
server/src/main/java/com/ecep/contract/config/WebConfig.java
Normal file
39
server/src/main/java/com/ecep/contract/config/WebConfig.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.ecep.contract.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Web配置类,提供CORS支持等Web相关配置
|
||||
*/
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* 配置跨域资源共享(CORS)
|
||||
*/
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
// 允许所有来源
|
||||
config.addAllowedOriginPattern("*");
|
||||
// 允许所有请求头
|
||||
config.addAllowedHeader("*");
|
||||
// 允许所有HTTP方法
|
||||
config.addAllowedMethod("*");
|
||||
// 允许发送Cookie
|
||||
config.setAllowCredentials(true);
|
||||
// 设置预检请求的有效期(秒)
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
// 应用配置到所有路径
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ecep.contract.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 基础控制器,处理根路径请求和错误处理
|
||||
*/
|
||||
@RestController
|
||||
public class IndexController {
|
||||
|
||||
/**
|
||||
* 处理根路径请求,返回系统状态信息
|
||||
*/
|
||||
@GetMapping("/")
|
||||
public ResponseEntity<?> index() {
|
||||
return ResponseEntity.ok("合同管理系统 REST API 服务已启动");
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理错误路径请求,避免Whitelabel Error Page显示
|
||||
*/
|
||||
@GetMapping("/error")
|
||||
public ResponseEntity<?> error() {
|
||||
return ResponseEntity.status(404).body("请求的资源不存在");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ecep.contract.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* 登录控制器
|
||||
* 处理登录页面请求和登录相关操作
|
||||
*/
|
||||
@Controller
|
||||
public class LoginController {
|
||||
|
||||
/**
|
||||
* 提供登录页面
|
||||
* 当用户访问/login路径时,返回登录页面视图
|
||||
*/
|
||||
@GetMapping("/login")
|
||||
public String login() {
|
||||
return "login.html";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理登录成功后的跳转
|
||||
* 这个方法在Spring Security配置中通过defaultSuccessUrl指定
|
||||
*/
|
||||
@GetMapping("/login/success")
|
||||
public String loginSuccess() {
|
||||
// 登录成功后重定向到首页
|
||||
return "redirect:/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理登录失败后的跳转
|
||||
* 可以根据需要自定义登录失败的处理逻辑
|
||||
*/
|
||||
@GetMapping("/login/failure")
|
||||
public String loginFailure() {
|
||||
// 登录失败后重定向回登录页面,并添加错误参数
|
||||
return "redirect:/login?error";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ecep.contract.ds;
|
||||
|
||||
import static com.ecep.contract.AppV2.DEFAULT_DB_DATABASE;
|
||||
import static com.ecep.contract.AppV2.DEFAULT_DB_HOST;
|
||||
import static com.ecep.contract.AppV2.DEFAULT_DB_PASSWORD;
|
||||
import static com.ecep.contract.AppV2.DEFAULT_DB_PORT;
|
||||
import static com.ecep.contract.AppV2.DEFAULT_DB_USERNAME;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
|
||||
import org.springframework.data.repository.config.BootstrapMode;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(
|
||||
basePackages = {"com.ecep.contract.ds"},
|
||||
bootstrapMode = BootstrapMode.LAZY,
|
||||
repositoryFactoryBeanClass = JpaRepositoryFactoryBean.class
|
||||
)
|
||||
public class DsRepositoriesConfig {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DsRepositoriesConfig.class);
|
||||
|
||||
@Bean
|
||||
// @ConfigurationProperties(prefix = "spring.datasource")
|
||||
@Primary
|
||||
public DataSource dataSource(Environment env) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("SpringApp.dataSource, env:{}", env);
|
||||
}
|
||||
|
||||
String host = env.getProperty("db.server.host", DEFAULT_DB_HOST);
|
||||
String port = env.getProperty("db.server.port", DEFAULT_DB_PORT);
|
||||
String database = env.getProperty("db.server.database", DEFAULT_DB_DATABASE);
|
||||
String username = env.getProperty("db.server.username", DEFAULT_DB_USERNAME);
|
||||
String password = env.getProperty("db.server.password", DEFAULT_DB_PASSWORD);
|
||||
|
||||
String url = "jdbc:mysql://" + host + ":" + port + "/" + database;
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("db server url:{},user:{}", url, username);
|
||||
}
|
||||
|
||||
return DataSourceBuilder.create()
|
||||
.type(HikariDataSource.class)
|
||||
.url(url)
|
||||
.username(username)
|
||||
.password(password)
|
||||
.driverClassName("com.mysql.cj.jdbc.Driver")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
|
||||
return new JdbcTemplate(dataSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ecep.contract.ds;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.time.MonthDay;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Converter(autoApply = true)
|
||||
public class MonthDayConverter implements AttributeConverter<MonthDay, String> {
|
||||
|
||||
// 定义日期格式(月-日,两位数)
|
||||
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM-dd");
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(MonthDay attribute) {
|
||||
// 将 MonthDay 转换为数据库存储的字符串(MM-dd)
|
||||
return attribute != null ? attribute.format(FORMATTER) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MonthDay convertToEntityAttribute(String dbData) {
|
||||
// 将数据库字符串(MM-dd)转换为 MonthDay
|
||||
return dbData != null ? MonthDay.parse(dbData, FORMATTER) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ecep.contract.ds;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
|
||||
public interface MyRepository<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ecep.contract.ds.company;
|
||||
|
||||
import com.ecep.contract.ds.company.service.CompanyContactService;
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
import com.ecep.contract.util.EntityStringConverter;
|
||||
|
||||
public class CompanyContactStringConverter extends EntityStringConverter<CompanyContact> {
|
||||
|
||||
public CompanyContactStringConverter() {
|
||||
|
||||
}
|
||||
|
||||
public CompanyContactStringConverter(CompanyContactService service) {
|
||||
setInitialized(employee -> service.findById(employee.getId()));
|
||||
// setFromString(service::findByName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package com.ecep.contract.ds.company;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.ecep.contract.util.FileUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.CompanyFileType;
|
||||
import com.ecep.contract.MyDateTimeUtils;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.service.CompanyFileService;
|
||||
import com.ecep.contract.model.CompanyFile;
|
||||
|
||||
public class CompanyFileUtils {
|
||||
|
||||
public static CompanyFile fillType(String fileName, String companyName, File destDir) {
|
||||
CompanyFile companyFile = new CompanyFile();
|
||||
if (isTycReport(fileName, companyName)) {
|
||||
File dest = new File(destDir, fileName);
|
||||
companyFile.setType(CompanyFileType.CreditReport);
|
||||
companyFile.setFilePath(dest.getAbsolutePath());
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 包含公司名称 和 天眼查 的文件
|
||||
if (fileName.contains(companyName) && fileName.contains(CloudServiceConstant.TYC_NAME)) {
|
||||
LocalDateTime dateTime = LocalDateTime.now();
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm");
|
||||
int idx = fileName.indexOf("报告");
|
||||
String destName = (idx > 0 ? fileName.substring(0, fileName.indexOf("报告") + 2) + "_" : "") +
|
||||
companyName + "_天眼查_" + dateTime.format(fmt) + "." + StringUtils.getFilenameExtension(fileName);
|
||||
}
|
||||
|
||||
for (CompanyFileType value : CompanyFileType.values()) {
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件名判断是否是天眼查的报告文件
|
||||
*/
|
||||
public static boolean isTycReport(String fileName, String companyName) {
|
||||
// 文件名中必须包含 天眼查 字样
|
||||
if (!fileName.contains(CloudServiceConstant.TYC_NAME)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 文件名中必须包含 公司名称
|
||||
if (!fileName.contains(companyName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 文件名后缀需符合要求
|
||||
return FileUtils.withExtensions(fileName, FileUtils.PDF, FileUtils.DOC, FileUtils.DOCX);
|
||||
}
|
||||
|
||||
public static boolean isCompanyFile(File file) {
|
||||
String fileName = file.getName();
|
||||
if (fileName.equals(FileUtils.FILE_DB_JSON)) {
|
||||
return true;
|
||||
}
|
||||
if (fileName.equals(FileUtils.FILE_B1001_JSON)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (fileName.equals(FileUtils.FILE_BLACK_LIST_JSON)) {
|
||||
return true;
|
||||
}
|
||||
if (fileName.equals("合同列表.json")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 营业执照
|
||||
if (fileName.contains(CompanyFileService.BUSINESS_LICENSE)) {
|
||||
return true;
|
||||
}
|
||||
// 操作证
|
||||
if (fileName.contains(CompanyFileService.OPERATION_CERTIFICATE)) {
|
||||
return true;
|
||||
}
|
||||
// 许可证
|
||||
if (fileName.contains(CompanyFileService.PERMIT_CERTIFICATE)) {
|
||||
return true;
|
||||
}
|
||||
// 登记证
|
||||
if (fileName.contains(CompanyFileService.REGISTRATION_CERTIFICATE)) {
|
||||
return true;
|
||||
}
|
||||
// 组织机构代码证
|
||||
if (fileName.contains(CompanyFileService.ORGANIZATION_CODE_CERTIFICATE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件名中提取的日期信息更新对象的日期,如果文件名称中没有可识别的日期,则不进行任何更新
|
||||
* 日期提取方法参考 {@link MyDateTimeUtils#pickLocalDate(String)}
|
||||
*
|
||||
* @param file 日期来源文件对象
|
||||
* @param vendorFile 要更新的对象
|
||||
* @param getter 对象的日期获取方法
|
||||
* @param setter 对象的日期设置方法
|
||||
* @param <T> 对象泛型
|
||||
* @return 是否更新了日期
|
||||
*/
|
||||
public static <T> boolean fillApplyDateAbsent(File file, T vendorFile, Function<T, LocalDate> getter,
|
||||
BiConsumer<T, LocalDate> setter) {
|
||||
LocalDate applyDate = getter.apply(vendorFile);
|
||||
if (applyDate != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean modified = false;
|
||||
String fileName = file.getName();
|
||||
// 从文件的名称中提取日期
|
||||
LocalDate picked = MyDateTimeUtils.pickLocalDate(fileName);
|
||||
if (picked != null) {
|
||||
// 如果提取出的日期不为空,则通过setter函数将这个日期设置到vendorFile中,并将modified标志设置为true。
|
||||
setter.accept(vendorFile, picked);
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
public static boolean isHiddenFile(File file) {
|
||||
String fileName = file.getName();
|
||||
if (fileName.equals(FileUtils.FILE_DB_THUMBS)) {
|
||||
return true;
|
||||
}
|
||||
return fileName.startsWith("~$");
|
||||
}
|
||||
|
||||
public static String escapeFileName(String fileName) {
|
||||
String patternStr = "[\\\\/:*?\"<>|]";
|
||||
Pattern pattern = Pattern.compile(patternStr);
|
||||
Matcher matcher = pattern.matcher(fileName);
|
||||
return matcher.replaceAll("_");
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回 district 中关于省份的部门zi
|
||||
*
|
||||
* @param district 地区
|
||||
* @return 省份名称
|
||||
*/
|
||||
public static String getParentPrefixByDistrict(String district) {
|
||||
int indexOf = district.indexOf("省");
|
||||
if (indexOf != -1) {
|
||||
return district.substring(0, indexOf);
|
||||
}
|
||||
|
||||
indexOf = district.indexOf("自治区");
|
||||
if (indexOf != -1) {
|
||||
return district.substring(0, 2);
|
||||
}
|
||||
|
||||
indexOf = district.indexOf("市");
|
||||
if (indexOf != -1) {
|
||||
return district.substring(0, indexOf);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean exists(String path) {
|
||||
if (!StringUtils.hasText(path)) {
|
||||
return false;
|
||||
}
|
||||
File file = new File(path);
|
||||
return file.exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE supplier_ms.COMPANY_BANK_ACCOUNT
|
||||
(
|
||||
ID INT AUTO_INCREMENT NOT NULL,
|
||||
BANK_ID INT NULL,
|
||||
OPENING_BANK VARCHAR(255) NULL,
|
||||
ACCOUNT VARCHAR(255) NULL,
|
||||
CONSTRAINT pk_company_bank_account PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
ALTER TABLE supplier_ms.COMPANY_BANK_ACCOUNT
|
||||
ADD CONSTRAINT FK_COMPANY_BANK_ACCOUNT_ON_BANK FOREIGN KEY (BANK_ID) REFERENCES supplier_ms.BANK (ID);
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBankAccount;
|
||||
|
||||
public interface CompanyBankAccountRepository extends MyRepository<CompanyBankAccount, Integer> {
|
||||
|
||||
Optional<CompanyBankAccount> findByCompanyAndAccount(Company company, String account);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBlackReason;
|
||||
|
||||
@Repository
|
||||
public interface CompanyBlackReasonRepository extends MyRepository<CompanyBlackReason, Integer> {
|
||||
|
||||
List<CompanyBlackReason> findAllByCompany(Company company);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
|
||||
@Repository
|
||||
public interface CompanyContactRepository extends MyRepository<CompanyContact, Integer> {
|
||||
|
||||
Optional<CompanyContact> findFirstByCompany(Company company);
|
||||
|
||||
List<CompanyContact> findAllByCompany(Company company);
|
||||
|
||||
List<CompanyContact> findAllByCompanyAndName(Company company, String name);
|
||||
|
||||
int deleteAllByCompany(Company company);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyContract;
|
||||
import com.ecep.contract.model.Contract;
|
||||
|
||||
@Repository
|
||||
public interface CompanyContractRepository extends
|
||||
// JDBC interfaces
|
||||
CrudRepository<CompanyContract, Integer>, PagingAndSortingRepository<CompanyContract, Integer>,
|
||||
// JPA interfaces
|
||||
JpaRepository<CompanyContract, Integer>, JpaSpecificationExecutor<CompanyContract> {
|
||||
|
||||
List<CompanyContract> findByCompanyId(int companyId);
|
||||
|
||||
List<CompanyContract> findByCompany(Company company);
|
||||
|
||||
Stream<CompanyContract> findStreamByCompany(Company company);
|
||||
|
||||
Optional<CompanyContract> findByContractId(int contractId);
|
||||
|
||||
Optional<CompanyContract> findByContract(Contract contract);
|
||||
|
||||
Optional<CompanyContract> findByCompanyAndContract(Company company, Contract contract);
|
||||
|
||||
List<CompanyContract> findAllByCompany(Company company);
|
||||
|
||||
/**
|
||||
* Delete all company contracts by company
|
||||
*
|
||||
* @param company Company
|
||||
* @return 删除的记录行数
|
||||
*/
|
||||
int deleteAllByCompany(Company company);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyExtendInfo;
|
||||
|
||||
public interface CompanyExtendInfoRepository extends MyRepository<CompanyExtendInfo, Integer> {
|
||||
|
||||
List<CompanyExtendInfo> findByCompany(Company company);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ecep.contract.CompanyFileType;
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyFile;
|
||||
|
||||
public interface CompanyFileRepository extends MyRepository<CompanyFile, Integer> {
|
||||
|
||||
List<CompanyFile> findByCompany(Company company);
|
||||
|
||||
List<CompanyFile> findByCompanyAndType(Company company, CompanyFileType type);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.CompanyFileType;
|
||||
import com.ecep.contract.ds.other.repository.BaseEnumEntityRepository;
|
||||
import com.ecep.contract.model.CompanyFileTypeLocal;
|
||||
|
||||
@Repository
|
||||
public interface CompanyFileTypeLocalRepository extends BaseEnumEntityRepository<CompanyFileType, CompanyFileTypeLocal, Integer> {
|
||||
|
||||
@Override
|
||||
default CompanyFileType[] getEnumConstants() {
|
||||
return CompanyFileType.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
default CompanyFileTypeLocal newEntity() {
|
||||
return new CompanyFileTypeLocal();
|
||||
}
|
||||
|
||||
CompanyFileTypeLocal findByTypeAndLang(CompanyFileType type, String lang);
|
||||
|
||||
default CompanyFileTypeLocal getCompleteByTypeAndLang(CompanyFileType type, String lang) {
|
||||
CompanyFileTypeLocal v = findByTypeAndLang(type, lang);
|
||||
if (v == null) {
|
||||
v = newEntity();
|
||||
v.setType(type);
|
||||
v.setLang(lang);
|
||||
v.setValue(type.name());
|
||||
v = save(v);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.model.CompanyInvoiceInfo;
|
||||
|
||||
/**
|
||||
* 公司发票信息 Repository
|
||||
*/
|
||||
@Repository
|
||||
public interface CompanyInvoiceInfoRepository extends
|
||||
// JDBC interfaces
|
||||
CrudRepository<CompanyInvoiceInfo, Integer>, PagingAndSortingRepository<CompanyInvoiceInfo, Integer>,
|
||||
// JPA interfaces
|
||||
JpaRepository<CompanyInvoiceInfo, Integer>, JpaSpecificationExecutor<CompanyInvoiceInfo> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
|
||||
@Repository
|
||||
public interface CompanyOldNameRepository extends
|
||||
// JDBC interfaces
|
||||
CrudRepository<CompanyOldName, Integer>, PagingAndSortingRepository<CompanyOldName, Integer>,
|
||||
// JPA interfaces
|
||||
JpaRepository<CompanyOldName, Integer>, JpaSpecificationExecutor<CompanyOldName> {
|
||||
|
||||
List<CompanyOldName> findAllByCompanyId(Integer companyId);
|
||||
|
||||
List<CompanyOldName> findAllByCompanyIdAndName(Integer companyId, String name);
|
||||
|
||||
List<CompanyOldName> findAllByName(String name);
|
||||
|
||||
List<CompanyOldName> findByNameLike(String searchText);
|
||||
|
||||
List<CompanyOldName> findByMemoLike(String searchText);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
int deleteAllByCompanyId(Integer companyId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.model.Company;
|
||||
|
||||
@Repository
|
||||
public interface CompanyRepository extends
|
||||
// JDBC interfaces
|
||||
CrudRepository<Company, Integer>, PagingAndSortingRepository<Company, Integer>,
|
||||
// JPA interfaces
|
||||
JpaRepository<Company, Integer>, JpaSpecificationExecutor<Company> {
|
||||
|
||||
List<Company> findAllByName(String name);
|
||||
|
||||
Optional<Company> findFirstByName(String name);
|
||||
|
||||
List<Company> findAllByShortName(String shortName);
|
||||
|
||||
/**
|
||||
* @param uniscid 统一社会信用代码
|
||||
*/
|
||||
List<Company> findAllByUniscid(String uniscid);
|
||||
|
||||
@Query("select u from Company u")
|
||||
Stream<Company> findAllAsStream();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ecep.contract.ds.company.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.Invoice;
|
||||
|
||||
public interface InvoiceRepository extends MyRepository<Invoice, Integer> {
|
||||
|
||||
List<Invoice> findByCompany(Company company);
|
||||
|
||||
Invoice findByCode(String invoiceNumber);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.company.repository.CompanyBankAccountRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBankAccount;
|
||||
import com.ecep.contract.util.SpecificationUtils;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company-bank-account")
|
||||
public class CompanyBankAccountService implements IEntityService<CompanyBankAccount> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyBankAccountService.class);
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyBankAccountRepository repository;
|
||||
|
||||
|
||||
public CompanyBankAccount findByAccount(Company company, String account) {
|
||||
return repository.findByCompanyAndAccount(company, account).orElse(null);
|
||||
}
|
||||
|
||||
public void updateBankAccount(Company company, String bank, String bankAccount, MessageHolder holder) {
|
||||
boolean modified = false;
|
||||
if (!StringUtils.hasText(bankAccount)) {
|
||||
// 空账户不用存储
|
||||
return;
|
||||
}
|
||||
|
||||
CompanyBankAccount account = findByAccount(company, bankAccount);
|
||||
if (account == null) {
|
||||
account = new CompanyBankAccount();
|
||||
account.setCompany(company);
|
||||
account.setAccount(bankAccount);
|
||||
holder.info("新增银行账户" + bankAccount);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(bank)) {
|
||||
// 更新开户行
|
||||
if (!Objects.equals(account.getOpeningBank(), bank)) {
|
||||
account.setOpeningBank(bank);
|
||||
holder.info("更新开户行" + bank);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
save(account);
|
||||
}
|
||||
}
|
||||
|
||||
public CompanyBankAccount save(CompanyBankAccount account) {
|
||||
return repository.save(account);
|
||||
}
|
||||
|
||||
public List<CompanyBankAccount> findAll(Specification<CompanyBankAccount> spec, Sort sort) {
|
||||
return repository.findAll(spec, sort);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompanyBankAccount findById(Integer id) {
|
||||
return repository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Specification<CompanyBankAccount> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.and(
|
||||
builder.isNotNull(root.get("bank")),
|
||||
builder.or(
|
||||
builder.like(root.get("bank").get("name"), "%" + searchText + "%"),
|
||||
builder.like(root.get("bank").get("code"), "%" + searchText + "%")
|
||||
)
|
||||
),
|
||||
builder.like(root.get("openingBank"), "%" + searchText + "%"),
|
||||
builder.like(root.get("account"), "%" + searchText + "%")
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<CompanyBankAccount> findAll(Specification<CompanyBankAccount> spec, Pageable pageable) {
|
||||
return repository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public void delete(CompanyBankAccount entity) {
|
||||
repository.delete(entity);
|
||||
}
|
||||
|
||||
public List<CompanyBankAccount> searchByCompany(Company company, String searchText) {
|
||||
Specification<CompanyBankAccount> spec = getSpecification(searchText);
|
||||
if (company != null) {
|
||||
spec = SpecificationUtils.and(spec, (root, query, builder) -> {
|
||||
return builder.equal(root.get("company"), company);
|
||||
});
|
||||
}
|
||||
return repository.findAll(spec, Pageable.ofSize(10)).getContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.ecep.contract.util.FileUtils;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.CompanyCustomerFileType;
|
||||
import com.ecep.contract.CompanyVendorFileType;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.ds.company.CompanyFileUtils;
|
||||
import com.ecep.contract.ds.other.repository.HolidayTableRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBasicFile;
|
||||
import com.ecep.contract.model.CompanyCustomerFile;
|
||||
import com.ecep.contract.model.CompanyVendorFile;
|
||||
import com.ecep.contract.model.HolidayTable;
|
||||
|
||||
public abstract class CompanyBasicService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyBasicService.class);
|
||||
|
||||
/**
|
||||
* 调整日期到工作日
|
||||
*
|
||||
* @param date 要调整的日期
|
||||
* @return 调整的日期
|
||||
*/
|
||||
public static LocalDate adjustToWorkDay(LocalDate date) {
|
||||
if (date.getDayOfWeek() == DayOfWeek.SATURDAY) {
|
||||
// 再减去1天,到周五
|
||||
date = date.plusDays(-1);
|
||||
} else if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
|
||||
// 再减去2天,到周五
|
||||
date = date.plusDays(-2);
|
||||
}
|
||||
|
||||
HolidayTableRepository holidayTableRepository = SpringApp.getBean(HolidayTableRepository.class);
|
||||
//TODO 跳过节假日
|
||||
int tryDays = 15;
|
||||
while (tryDays-- > 0) {
|
||||
HolidayTable holidayTable = holidayTableRepository.findById(date).orElse(null);
|
||||
if (holidayTable == null) {
|
||||
// 没有节假日定义,检查是否是工作日
|
||||
DayOfWeek dayOfWeek = date.getDayOfWeek();
|
||||
if (dayOfWeek == DayOfWeek.SATURDAY) {
|
||||
date = date.plusDays(-1);
|
||||
continue;
|
||||
}
|
||||
if (dayOfWeek == DayOfWeek.SUNDAY) {
|
||||
date = date.plusDays(-2);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!holidayTable.isHoliday()) {
|
||||
// 不是节假日
|
||||
break;
|
||||
}
|
||||
date = date.plusDays(-1);
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
protected CompanyService companyService;
|
||||
|
||||
|
||||
protected boolean isEditableFile(String fileName) {
|
||||
return FileUtils.withExtensions(fileName,
|
||||
FileUtils.XLS, FileUtils.XLSX,
|
||||
FileUtils.DOC, FileUtils.DOCX);
|
||||
}
|
||||
|
||||
protected boolean isArchiveFile(String fileName) {
|
||||
return FileUtils.withExtensions(fileName,
|
||||
FileUtils.PNG, FileUtils.PDF,
|
||||
FileUtils.JPG, FileUtils.JPEG);
|
||||
}
|
||||
|
||||
public abstract <T, F extends CompanyBasicFile<T>, ID> void deleteFile(F file);
|
||||
|
||||
protected <T, F extends CompanyBasicFile<T>, ID> boolean fetchDbFiles(List<F> dbFiles, Map<String, F> map, Consumer<String> status) {
|
||||
boolean modified = false;
|
||||
List<File> editFiles = new ArrayList<>();
|
||||
// 排除掉数据库中重复的
|
||||
for (F dbFile : dbFiles) {
|
||||
String filePath = dbFile.getFilePath();
|
||||
// 没有文件信息,无效记录,删除
|
||||
if (!StringUtils.hasText(filePath)) {
|
||||
deleteFile(dbFile);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 文件不存在或者隐藏文件,删除记录
|
||||
File file = new File(filePath);
|
||||
if (!file.exists() || CompanyFileUtils.isHiddenFile(file)) {
|
||||
deleteFile(dbFile);
|
||||
continue;
|
||||
}
|
||||
|
||||
// old 是冲突的,按dbFiles顺序,旧的(list前面的)
|
||||
F old = map.put(filePath, dbFile);
|
||||
// 目录有重复删除
|
||||
if (old != null) {
|
||||
deleteFile(old);
|
||||
}
|
||||
|
||||
String editFilePath = dbFile.getEditFilePath();
|
||||
if (!Objects.equals(filePath, editFilePath)) {
|
||||
// 没有文件信息,无效记录,删除
|
||||
if (StringUtils.hasText(editFilePath)) {
|
||||
File editFile = new File(editFilePath);
|
||||
if (editFile.exists()) {
|
||||
editFiles.add(editFile);
|
||||
} else {
|
||||
dbFile.setEditFilePath("");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 类型未设置,补充类型
|
||||
if (dbFile.getType() == null) {
|
||||
if (fillFileAsDefaultType(dbFile, file, status)) {
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (File editFile : editFiles) {
|
||||
String editFilePath = editFile.getAbsolutePath();
|
||||
F dup = map.remove(editFilePath);
|
||||
// 目录有重复删除
|
||||
if (dup != null) {
|
||||
deleteFile(dup);
|
||||
}
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* dbFile 的 Type 未设置时,设置为默认类型
|
||||
*
|
||||
* @param dbFile 要设置的 对象
|
||||
* @param file 相关文件对象
|
||||
* @param status 状态输出
|
||||
* @param <T> 类型类
|
||||
* @param <F> 文件类
|
||||
* @return 是否修改了
|
||||
* @see CompanyVendorFile
|
||||
* @see CompanyVendorFileType
|
||||
* @see CompanyCustomerFile
|
||||
* @see CompanyCustomerFileType
|
||||
*/
|
||||
protected abstract <T, F extends CompanyBasicFile<T>> boolean fillFileAsDefaultType(F dbFile, File file, Consumer<String> status);
|
||||
|
||||
|
||||
protected void moveFileToCompany(Company company, List<File> needMoveToCompanyPath) {
|
||||
if (needMoveToCompanyPath.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (!Hibernate.isInitialized(company)) {
|
||||
company = companyService.findById(company.getId());
|
||||
}
|
||||
String companyPath = company.getPath();
|
||||
if (!StringUtils.hasText(companyPath)) {
|
||||
return;
|
||||
}
|
||||
for (File file : needMoveToCompanyPath) {
|
||||
File dest = new File(companyPath, file.getName());
|
||||
if (file.renameTo(dest)) {
|
||||
//
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("{} -> {}", file.getAbsolutePath(), dest.getAbsolutePath());
|
||||
}
|
||||
} else {
|
||||
//
|
||||
if (dest.exists()) {
|
||||
if (file.delete()) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete File {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 公司目录下文件更新后,待公司文件自行处理
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历扫描 path 目录下的文件,
|
||||
*
|
||||
* @param path
|
||||
* @param needMoveToCompanyPath
|
||||
* @param retrieveFiles
|
||||
* @param map
|
||||
* @param status
|
||||
* @param <T>
|
||||
* @param <F>
|
||||
*/
|
||||
protected <T, F extends CompanyBasicFile<T>> void fetchFiles(
|
||||
String path,
|
||||
List<File> needMoveToCompanyPath,
|
||||
List<F> retrieveFiles,
|
||||
Map<String, F> map,
|
||||
Consumer<String> status
|
||||
) {
|
||||
if (!StringUtils.hasText(path)) {
|
||||
return;
|
||||
}
|
||||
File dir = new File(path);
|
||||
if (!dir.exists()) {
|
||||
return;
|
||||
}
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
List<File> step1 = new ArrayList<>();
|
||||
for (File file : files) {
|
||||
// 只处理文件
|
||||
if (!file.isFile() || CompanyFileUtils.isHiddenFile(file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (CompanyFileUtils.isCompanyFile(file)) {
|
||||
needMoveToCompanyPath.add(file);
|
||||
continue;
|
||||
}
|
||||
// 先把所有文件加到列表中
|
||||
step1.add(file);
|
||||
}
|
||||
|
||||
if (!step1.isEmpty()) {
|
||||
// 第一步,处理已经存在的
|
||||
for (File file : new ArrayList<>(step1)) {
|
||||
String filePath = file.getAbsolutePath();
|
||||
if (map.containsKey(filePath)) {
|
||||
// 已记录
|
||||
F customerFile = map.get(filePath);
|
||||
if (fillFile(customerFile, file, step1, status)) {
|
||||
retrieveFiles.add(customerFile);
|
||||
}
|
||||
step1.remove(file);
|
||||
}
|
||||
}
|
||||
|
||||
// 第二步骤,再处理
|
||||
while (!step1.isEmpty()) {
|
||||
File file = step1.removeLast();
|
||||
F filled = fillFileType(file, step1, status);
|
||||
if (filled != null) {
|
||||
retrieveFiles.add(filled);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充文件类型
|
||||
*
|
||||
* @param file
|
||||
* @param fileList
|
||||
* @param status 状态输出
|
||||
* @param <T> 类型类
|
||||
* @param <F> 文件类
|
||||
*/
|
||||
protected abstract <T, F extends CompanyBasicFile<T>> F fillFileType(File file, List<File> fileList, Consumer<String> status);
|
||||
|
||||
/**
|
||||
* @param customerFile 文件对象
|
||||
* @param file 相关文件
|
||||
* @param fileList 待处理文件列表
|
||||
* @param status 状态输出
|
||||
* @param <T> 类型类
|
||||
* @param <F> 文件类
|
||||
* @return true 有修改
|
||||
*/
|
||||
protected <T, F extends CompanyBasicFile<T>> boolean fillFile(F customerFile, File file, List<File> fileList, Consumer<String> status) {
|
||||
String fileName = file.getName();
|
||||
boolean modified = CompanyFileUtils.fillApplyDateAbsent(file, customerFile, F::getSignDate, F::setSignDate);
|
||||
// 评估表
|
||||
if (isEvaluationFile(fileName)) {
|
||||
if (fillFileAsEvaluationFile(customerFile, file, fileList, status)) {
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
if (!Objects.equals(file.getAbsolutePath(), customerFile.getFilePath())) {
|
||||
customerFile.setFilePath(file.getAbsolutePath());
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 以评价表单模板。填充文件信息
|
||||
*
|
||||
* @param customerFile 文件对象
|
||||
* @param file 相关文件
|
||||
* @param fileList 待处理文件列表
|
||||
* @param status 状态输出
|
||||
* @param <T> 类型类
|
||||
* @param <F> 文件类
|
||||
* @return true:文件对象有修改,否则返回false
|
||||
*/
|
||||
protected <T, F extends CompanyBasicFile<T>> boolean fillFileAsEvaluationFile(F customerFile, File file, List<File> fileList, Consumer<String> status) {
|
||||
boolean modified = setFileTypeAsEvaluationForm(customerFile);
|
||||
String fileName = file.getName();
|
||||
|
||||
// 文件全路径
|
||||
String fileAbsolutePath = file.getAbsolutePath();
|
||||
|
||||
if (isEditableFile(fileName)) {
|
||||
// 是可编辑文件时
|
||||
if (!Objects.equals(fileAbsolutePath, customerFile.getEditFilePath())) {
|
||||
customerFile.setEditFilePath(fileAbsolutePath);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (useAsEditableFile(customerFile, file, fileList, status)) {
|
||||
modified = true;
|
||||
}
|
||||
} else if (isArchiveFile(fileName)) {
|
||||
// 存档文件时
|
||||
if (!Objects.equals(fileAbsolutePath, customerFile.getFilePath())) {
|
||||
customerFile.setFilePath(fileAbsolutePath);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (useAsArchiveFile(customerFile, file, fileList, status)) {
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
customerFile.setFilePath(file.getAbsolutePath());
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private <T, F extends CompanyBasicFile<T>> boolean useAsEditableFile(F customerFile, File file, List<File> fileList, Consumer<String> status) {
|
||||
if (fileList == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查存档文件
|
||||
if (StringUtils.hasText(customerFile.getFilePath())) {
|
||||
// 移除 存档文件
|
||||
File archiveFile = new File(customerFile.getFilePath());
|
||||
fileList.remove(archiveFile);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 未关联存档文件,去找 fileList 查
|
||||
if (fileList.isEmpty()) {
|
||||
// 文件全路径
|
||||
String fileAbsolutePath = file.getAbsolutePath();
|
||||
// 当没有其他文件时,与 EditFile 相同
|
||||
if (!Objects.equals(fileAbsolutePath, customerFile.getFilePath())) {
|
||||
customerFile.setFilePath(fileAbsolutePath);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
File archiveFile = null;
|
||||
// 文件名
|
||||
String fileName = file.getName();
|
||||
// 文件名,不含后缀
|
||||
String name = StringUtils.stripFilenameExtension(fileName);
|
||||
for (File f : fileList) {
|
||||
// 查找存档文件
|
||||
if (f.getName().startsWith(name) && isArchiveFile(f.getName())) {
|
||||
archiveFile = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 没有匹配到文件
|
||||
if (archiveFile == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fileList.remove(archiveFile)) {
|
||||
customerFile.setFilePath(archiveFile.getAbsolutePath());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private <T, F extends CompanyBasicFile<T>> boolean useAsArchiveFile(F customerFile, File file, List<File> fileList, Consumer<String> status) {
|
||||
if (fileList == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 未关联存档文件,去找 fileList 查
|
||||
if (fileList.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查可编辑文件
|
||||
if (StringUtils.hasText(customerFile.getEditFilePath())) {
|
||||
// 移除 可编辑文件
|
||||
File editFile = new File(customerFile.getEditFilePath());
|
||||
fileList.remove(editFile);
|
||||
return false;
|
||||
}
|
||||
|
||||
File editFile = null;
|
||||
// 文件名
|
||||
String fileName = file.getName();
|
||||
// 文件名,不含后缀
|
||||
String name = StringUtils.stripFilenameExtension(fileName);
|
||||
for (File f : fileList) {
|
||||
// 查找存档文件
|
||||
if (f.getName().startsWith(name) && isEditableFile(f.getName())) {
|
||||
editFile = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 没有匹配到文件
|
||||
if (editFile == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fileList.remove(editFile)) {
|
||||
String editFilePath = editFile.getAbsolutePath();
|
||||
if (!Objects.equals(editFilePath, customerFile.getEditFilePath())) {
|
||||
customerFile.setEditFilePath(editFilePath);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置文件类型为表单文件
|
||||
*
|
||||
* @param file 文件对象
|
||||
* @param <T> 类型类
|
||||
* @param <F> 文件类
|
||||
* @return true 文件对象有修改,否则false
|
||||
*/
|
||||
protected abstract <T, F extends CompanyBasicFile<T>> boolean setFileTypeAsEvaluationForm(F file);
|
||||
|
||||
/**
|
||||
* 判定 参数 fileName 是否是一个评价表文件
|
||||
*
|
||||
* @param fileName 文件名称
|
||||
* @return true 是评价表,否则false
|
||||
*/
|
||||
protected abstract boolean isEvaluationFile(String fileName);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.ds.company.repository.CompanyBlackReasonRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyBlackReason;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
public class CompanyBlackReasonService implements IEntityService<CompanyBlackReason> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyContactService.class);
|
||||
|
||||
@Autowired
|
||||
private CompanyBlackReasonRepository repository;
|
||||
|
||||
|
||||
public CompanyBlackReason findById(Integer id) {
|
||||
return repository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CompanyBlackReason> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("applyName"), "%" + searchText + "%"),
|
||||
builder.like(root.get("blackReason"), "%" + searchText + "%"),
|
||||
builder.like(root.get("description"), "%" + searchText + "%")
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<CompanyBlackReason> findAll(Specification<CompanyBlackReason> spec, Pageable pageable) {
|
||||
return repository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public void delete(CompanyBlackReason entity) {
|
||||
repository.delete(entity);
|
||||
}
|
||||
|
||||
public List<CompanyBlackReason> findAll(Specification<CompanyBlackReason> spec, Sort by) {
|
||||
return repository.findAll(spec, by);
|
||||
}
|
||||
|
||||
public List<CompanyBlackReason> findAllByCompany(Company company) {
|
||||
return repository.findAllByCompany(company);
|
||||
}
|
||||
|
||||
public CompanyBlackReason save(CompanyBlackReason companyBlackReason) {
|
||||
return repository.save(companyBlackReason);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.ds.company.repository.CompanyContactRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyContact;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
import com.ecep.contract.util.SpecificationUtils;
|
||||
|
||||
/**
|
||||
* 公司联系人服务
|
||||
*/
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company-contact")
|
||||
public class CompanyContactService implements IEntityService<CompanyContact> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyContactService.class);
|
||||
|
||||
@Autowired
|
||||
private CompanyContactRepository companyContactRepository;
|
||||
|
||||
public CompanyContact save(CompanyContact contact) {
|
||||
return companyContactRepository.save(contact);
|
||||
}
|
||||
|
||||
public void resetTo(Company from, Company to) {
|
||||
// 曾用名 关联到 updater
|
||||
List<CompanyContact> list = companyContactRepository.findAllByCompany(from);
|
||||
if (list.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (CompanyContact oldName : list) {
|
||||
oldName.setMemo(MyStringUtils.appendIfAbsent(oldName.getMemo(), "转自 " + from.getId()));
|
||||
oldName.setCompany(to);
|
||||
}
|
||||
companyContactRepository.saveAll(list);
|
||||
}
|
||||
|
||||
public void deleteByCompany(Company company) {
|
||||
int deleted = companyContactRepository.deleteAllByCompany(company);
|
||||
if (deleted > 0) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete {} records by company:#{}", deleted, company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(CompanyContact entity) {
|
||||
companyContactRepository.delete(entity);
|
||||
}
|
||||
|
||||
public CompanyContact findFirstByCompany(Company company) {
|
||||
return companyContactRepository.findFirstByCompany(company).orElse(null);
|
||||
}
|
||||
|
||||
public CompanyContact findById(Integer id) {
|
||||
return companyContactRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CompanyContact> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("name"), "%" + searchText + "%"),
|
||||
builder.like(root.get("phone"), "%" + searchText + "%"),
|
||||
builder.like(root.get("email"), "%" + searchText + "%"),
|
||||
builder.like(root.get("position"), "%" + searchText + "%"),
|
||||
builder.like(root.get("memo"), "%" + searchText + "%")
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<CompanyContact> findAll(Specification<CompanyContact> spec, Pageable pageable) {
|
||||
return companyContactRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public List<CompanyContact> searchByCompany(Company company, String userText) {
|
||||
Specification<CompanyContact> spec = SpecificationUtils.and((root, query, builder) -> {
|
||||
return builder.equal(root.get("company"), company);
|
||||
}, getSpecification(userText));
|
||||
return companyContactRepository.findAll(spec);
|
||||
}
|
||||
|
||||
public List<CompanyContact> findAll(Specification<CompanyContact> spec, Sort sort) {
|
||||
return companyContactRepository.findAll(spec, sort);
|
||||
}
|
||||
|
||||
public List<CompanyContact> findAllByCompanyAndName(Company company, String contactName) {
|
||||
return companyContactRepository.findAllByCompanyAndName(company, contactName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.ecep.contract.ds.company.repository.CompanyExtendInfoRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyExtendInfo;
|
||||
|
||||
/**
|
||||
* 公司文件服务
|
||||
*/
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company-extend-info")
|
||||
public class CompanyExtendInfoService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyExtendInfoService.class);
|
||||
@Autowired
|
||||
private CompanyExtendInfoRepository repository;
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public CompanyExtendInfo findById(int id) {
|
||||
return repository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
public List<CompanyExtendInfo> findAll(Specification<CompanyExtendInfo> spec, Sort sort) {
|
||||
return repository.findAll(spec, sort);
|
||||
}
|
||||
|
||||
@Caching(
|
||||
evict = {
|
||||
@CacheEvict(key = "#p0.id"),
|
||||
@CacheEvict(key = "'byCompany-'+#p0.company.id")
|
||||
}
|
||||
)
|
||||
public void delete(CompanyExtendInfo extendInfo) {
|
||||
repository.delete(extendInfo);
|
||||
}
|
||||
|
||||
@Caching(
|
||||
evict = {
|
||||
@CacheEvict(key = "#p0.id"),
|
||||
@CacheEvict(key = "'byCompany-'+#p0.company.id")
|
||||
}
|
||||
)
|
||||
public CompanyExtendInfo save(CompanyExtendInfo extendInfo) {
|
||||
return repository.save(extendInfo);
|
||||
}
|
||||
|
||||
@Cacheable(key = "'byCompany-'+#p0")
|
||||
public CompanyExtendInfo findByCompany(Company company) {
|
||||
List<CompanyExtendInfo> list = repository.findByCompany(company);
|
||||
if (list.isEmpty()) {
|
||||
CompanyExtendInfo extendInfo = new CompanyExtendInfo();
|
||||
extendInfo.setCompany(company);
|
||||
extendInfo.setDisableVerify(false);
|
||||
return repository.save(extendInfo);
|
||||
}
|
||||
return list.getFirst();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.CompanyFileType;
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.MyDateTimeUtils;
|
||||
import com.ecep.contract.SpringApp;
|
||||
import com.ecep.contract.cloud.rk.CloudRkService;
|
||||
import com.ecep.contract.cloud.tyc.CloudTycService;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.ds.company.CompanyFileUtils;
|
||||
import com.ecep.contract.ds.company.repository.CompanyFileRepository;
|
||||
import com.ecep.contract.ds.company.repository.CompanyFileTypeLocalRepository;
|
||||
import com.ecep.contract.ds.company.repository.CompanyOldNameRepository;
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyFile;
|
||||
import com.ecep.contract.model.CompanyFileTypeLocal;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
import com.ecep.contract.model.Contract;
|
||||
|
||||
/**
|
||||
* 公司文件服务
|
||||
*/
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company-file")
|
||||
public class CompanyFileService implements IEntityService<CompanyFile> {
|
||||
public final static String ENTERPRISE_REPORT = "企业信用报告";
|
||||
public final static String BUSINESS_LICENSE = "营业执照";
|
||||
public final static String ORGANIZATION_CODE_CERTIFICATE = "组织机构代码证";
|
||||
public final static String OPERATION_CERTIFICATE = "操作证";
|
||||
public final static String PERMIT_CERTIFICATE = "许可证";
|
||||
public final static String REGISTRATION_CERTIFICATE = "登记证";
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyFileService.class);
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyFileRepository companyFileRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyOldNameRepository companyOldNameRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyFileTypeLocalRepository fileTypeLocalRepository;
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public CompanyFile findById(Integer id) {
|
||||
return companyFileRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<CompanyFile> findAll(Specification<CompanyFile> spec, Pageable pageable) {
|
||||
return companyFileRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public List<CompanyFile> findFileByCompanyAndType(Company company, CompanyFileType type) {
|
||||
return companyFileRepository.findByCompanyAndType(company, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CompanyFile> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(builder.like(root.get("filePath"), "%" + searchText + "%"));
|
||||
};
|
||||
}
|
||||
|
||||
@Cacheable(key = "'type-locals-'+#p0")
|
||||
public Map<CompanyFileType, CompanyFileTypeLocal> findAllFileTypes(String lang) {
|
||||
return fileTypeLocalRepository.getCompleteMapByLocal(lang);
|
||||
}
|
||||
// public List<CompanyFileTypeLocal> findAllFileTypes(String lang) {
|
||||
// Map<CompanyFileType, CompanyFileTypeLocal> map =
|
||||
// fileTypeLocalRepository.getCompleteMapByLocal(lang);
|
||||
// List<CompanyFileTypeLocal> list = new ArrayList<>(map.values());
|
||||
// list.sort((o1, o2) -> Objects.compare(o1.getValue(), o2.getValue(),
|
||||
// String::compareTo));
|
||||
// return list;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 根据公司的合同的资信报告文件,推算下一个咨询报告日期
|
||||
*
|
||||
* @param company 公司
|
||||
* @param state 状态输出
|
||||
* @return 下一个咨询报告日期
|
||||
*/
|
||||
public LocalDate getNextCreditReportDate(Company company, Consumer<String> state) {
|
||||
// 检索全部合同
|
||||
ContractService contractService = SpringApp.getBean(ContractService.class);
|
||||
List<Contract> contractList = contractService.findAllByCompany(company);
|
||||
if (contractList.isEmpty()) {
|
||||
state.accept("未发现已登记的合同");
|
||||
return null;
|
||||
}
|
||||
|
||||
LocalDate minDate = LocalDate.of(2023, 1, 1);
|
||||
List<Contract> contracts = contractList.stream()
|
||||
.filter(v -> !v.getSetupDate().isBefore(minDate))
|
||||
.sorted(Comparator.comparing(Contract::getSetupDate))
|
||||
.toList();
|
||||
if (contracts.isEmpty()) {
|
||||
state.accept("没有发现待处理的合同");
|
||||
return null;
|
||||
}
|
||||
// 检索资信报告
|
||||
List<CompanyFile> files = findFileByCompanyAndType(company, CompanyFileType.CreditReport);
|
||||
if (files.isEmpty()) {
|
||||
Contract first = contracts.getFirst();
|
||||
// 没有资信报告,返回第一个合同的提交日期
|
||||
state.accept("没有资信报告,推荐使用第一个合同 " + first.getCode() + " 的日期 " + first.getSetupDate());
|
||||
return first.getSetupDate();
|
||||
}
|
||||
|
||||
for (Contract contract : contracts) {
|
||||
if (files.stream().noneMatch(v -> MyDateTimeUtils.dateValidFilter(contract.getSetupDate(), v.getApplyDate(),
|
||||
v.getExpiringDate(), 1))) {
|
||||
state.accept("发现未匹配的合同 " + contract.getCode() + " " + contract.getSetupDate());
|
||||
return contract.getSetupDate();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证企业文件
|
||||
* <p>
|
||||
* 检查是否有类型为{@link CompanyFileType#CreditReport
|
||||
* 资讯评估}的文件,且参数verifyDate在文件的{@link CompanyFile#getApplyDate()}和{@link CompanyFile#getExpiringDate()}
|
||||
* ()}指定验证日期内有
|
||||
* <p>
|
||||
* 2023-01-01后要求有资信评估报告
|
||||
*
|
||||
* @param company 检查的公司对象
|
||||
* @param verifyDate 检查日期
|
||||
* @param status 状态输出
|
||||
* @see CompanyFile
|
||||
* @see CompanyFileType
|
||||
*/
|
||||
public void verify(Company company, LocalDate verifyDate, Consumer<String> status) {
|
||||
if (verifyDate.isBefore(LocalDate.of(2023, 1, 1))) {
|
||||
// 不检查2023-01-01之前的资信评估报告
|
||||
return;
|
||||
}
|
||||
|
||||
// 查询公司的资信评估报告
|
||||
List<CompanyFile> files = findFileByCompanyAndType(company, CompanyFileType.CreditReport);
|
||||
CompanyFile companyFile = files.stream()
|
||||
.filter(v -> v.getApplyDate() != null && v.getExpiringDate() != null)
|
||||
.filter(v -> MyDateTimeUtils.dateValidFilter(verifyDate, v.getApplyDate(), v.getExpiringDate(), 30))
|
||||
.findFirst().orElse(null);
|
||||
if (companyFile == null) {
|
||||
List<LocalDate> dates = new ArrayList<>();
|
||||
|
||||
files.stream()
|
||||
.filter(v -> v.getApplyDate() != null && !verifyDate.isBefore(v.getApplyDate()))
|
||||
.max(Comparator.comparing(CompanyFile::getApplyDate))
|
||||
.map(CompanyFile::getApplyDate)
|
||||
.ifPresent(dates::add);
|
||||
|
||||
files.stream()
|
||||
.filter(v -> v.getExpiringDate() != null && !verifyDate.isAfter(v.getExpiringDate()))
|
||||
.min(Comparator.comparing(CompanyFile::getApplyDate))
|
||||
.map(CompanyFile::getApplyDate)
|
||||
.ifPresent(dates::add);
|
||||
|
||||
if (dates.isEmpty()) {
|
||||
status.accept("未匹配到资信评估报告");
|
||||
} else if (dates.size() == 1) {
|
||||
status.accept("未匹配到资信评估报告, 最接近日期:" + dates.getFirst());
|
||||
} else {
|
||||
LocalDate localDate = dates.stream().max(LocalDate::compareTo).orElse(null);
|
||||
status.accept("未匹配到资信评估报告, 最接近日期:" + localDate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存企业文件
|
||||
*
|
||||
* @param companyFile 企业文件
|
||||
* @return 保存后的企业文件
|
||||
*/
|
||||
public CompanyFile save(CompanyFile companyFile) {
|
||||
return companyFileRepository.save(companyFile);
|
||||
}
|
||||
|
||||
public List<CompanyFile> findAll(Specification<CompanyFile> spec, Sort sort) {
|
||||
return companyFileRepository.findAll(spec, sort);
|
||||
}
|
||||
|
||||
public void deleteById(int id) {
|
||||
companyFileRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public void delete(CompanyFile file) {
|
||||
companyFileRepository.delete(file);
|
||||
}
|
||||
|
||||
public List<CompanyFile> findByCompany(Company company) {
|
||||
return companyFileRepository.findByCompany(company);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置 公司文件
|
||||
*
|
||||
* @param company 要重置的公司对象
|
||||
* @param status 输出
|
||||
*/
|
||||
public boolean reBuildingFiles(Company company, Consumer<String> status) {
|
||||
List<CompanyFile> dbFiles = companyFileRepository.findByCompany(company);
|
||||
List<CompanyFile> retrieveFiles = new ArrayList<>();
|
||||
boolean modfied = false;
|
||||
|
||||
Map<String, CompanyFile> map = new HashMap<>();
|
||||
// 排除掉数据库中重复的
|
||||
for (CompanyFile dbFile : dbFiles) {
|
||||
String filePath = dbFile.getFilePath();
|
||||
// 没有文件信息,无效记录,删除
|
||||
if (!StringUtils.hasText(filePath)) {
|
||||
companyFileRepository.delete(dbFile);
|
||||
modfied = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 目录不存在,删除
|
||||
File dir = new File(filePath);
|
||||
if (!dir.exists()) {
|
||||
companyFileRepository.delete(dbFile);
|
||||
modfied = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
CompanyFile old = map.put(filePath, dbFile);
|
||||
// 目录有重复删除
|
||||
if (old != null) {
|
||||
companyFileRepository.delete(old);
|
||||
modfied = true;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, File> directoryMap = new HashMap<>();
|
||||
|
||||
// 公司目录
|
||||
if (StringUtils.hasText(company.getPath())) {
|
||||
File dir = new File(company.getPath());
|
||||
directoryMap.put(company.getName(), dir);
|
||||
}
|
||||
|
||||
// 获取所有曾用名
|
||||
for (CompanyOldName companyOldName : companyOldNameRepository.findAllByCompanyId(company.getId())) {
|
||||
String path = companyOldName.getPath();
|
||||
if (StringUtils.hasText(path)) {
|
||||
File dir = new File(path);
|
||||
directoryMap.put(companyOldName.getName(), dir);
|
||||
}
|
||||
}
|
||||
|
||||
for (Map.Entry<String, File> entry : directoryMap.entrySet()) {
|
||||
String companyName = entry.getKey();
|
||||
File dir = entry.getValue();
|
||||
if (!StringUtils.hasText(companyName)) {
|
||||
continue;
|
||||
}
|
||||
if (dir == null || !dir.exists()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) {
|
||||
// 文件系统出错或者没有相关文件
|
||||
continue;
|
||||
}
|
||||
for (File file : files) {
|
||||
// 只处理文件
|
||||
if (!file.isFile() || CompanyFileUtils.isHiddenFile(file)) {
|
||||
continue;
|
||||
}
|
||||
String filePath = file.getAbsolutePath();
|
||||
if (!map.containsKey(filePath)) {
|
||||
// 未记录
|
||||
CompanyFile filled = fillFileType(file, status);
|
||||
retrieveFiles.add(filled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
status.accept("导入 " + retrieveFiles.size() + " 个文件");
|
||||
if (retrieveFiles.isEmpty()) {
|
||||
return modfied;
|
||||
}
|
||||
|
||||
// update db
|
||||
retrieveFiles.forEach(v -> v.setCompany(company));
|
||||
companyFileRepository.saveAll(retrieveFiles);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件名生成公司文件对象,文件已经存在公司对应的存储目录下
|
||||
*
|
||||
* @param file 文件
|
||||
* @param status 状态输出
|
||||
* @return 公司文件对象
|
||||
*/
|
||||
private CompanyFile fillFileType(File file, Consumer<String> status) {
|
||||
String fileName = file.getName();
|
||||
CompanyFile companyFile = new CompanyFile();
|
||||
companyFile.setType(CompanyFileType.General);
|
||||
companyFile.setFilePath(file.getAbsolutePath());
|
||||
fillApplyDateAndExpiringDateAbsent(file, companyFile);
|
||||
|
||||
// 天眼查 基础版企业信用报告
|
||||
if (fileName.contains(CloudTycService.TYC_ENTERPRISE_BASIC_REPORT)
|
||||
|| fileName.contains(CloudTycService.TYC_ENTERPRISE_MAJOR_REPORT)
|
||||
|| fileName.contains(CloudTycService.TYC_ENTERPRISE_ANALYSIS_REPORT)) {
|
||||
companyFile.setType(CompanyFileType.CreditReport);
|
||||
fillExpiringDateAbsent(companyFile);
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 天眼查 企业信用信息公示报告
|
||||
if (fileName.contains(CloudTycService.TYC_ENTERPRISE_CREDIT_REPORT)) {
|
||||
companyFile.setType(CompanyFileType.CreditInfoPublicityReport);
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 集团相关方平台 元素征信 企业征信报告
|
||||
if (fileName.contains(CloudServiceConstant.RK_VENDOR_NAME)
|
||||
&& fileName.contains(CloudRkService.ENTERPRISE_CREDIT_REPORT)) {
|
||||
companyFile.setType(CompanyFileType.CreditReport);
|
||||
fillExpiringDateAbsent(companyFile);
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 营业执照
|
||||
if (fileName.contains(BUSINESS_LICENSE)) {
|
||||
companyFile.setType(CompanyFileType.BusinessLicense);
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 其他企业信用报告
|
||||
if (fileName.contains(ENTERPRISE_REPORT)) {
|
||||
companyFile.setType(CompanyFileType.CreditReport);
|
||||
fillExpiringDateAbsent(companyFile);
|
||||
return companyFile;
|
||||
}
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 补齐有效期
|
||||
*/
|
||||
private void fillExpiringDateAbsent(CompanyFile file) {
|
||||
LocalDate expiringDate = file.getExpiringDate();
|
||||
if (expiringDate == null) {
|
||||
LocalDate applyDate = file.getApplyDate();
|
||||
if (applyDate != null) {
|
||||
expiringDate = applyDate.plusYears(1);
|
||||
file.setExpiringDate(expiringDate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void fillApplyDateAndExpiringDateAbsent(File file, CompanyFile companyFile) {
|
||||
LocalDate applyDate = companyFile.getApplyDate();
|
||||
if (applyDate != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String fileName = file.getName();
|
||||
Pattern pattern = Pattern.compile(MyDateTimeUtils.REGEX_DATE);
|
||||
Matcher matcher = pattern.matcher(fileName);
|
||||
while (matcher.find()) {
|
||||
// 找到第一个日期,记作起始日期
|
||||
String date = matcher.group();
|
||||
try {
|
||||
LocalDate n = LocalDate.parse(date);
|
||||
companyFile.setApplyDate(n);
|
||||
|
||||
// 如果 截至日期未设置,则第二个日期记作截至日期(如有)
|
||||
LocalDate expiringDate = companyFile.getExpiringDate();
|
||||
if (expiringDate == null) {
|
||||
while (matcher.find()) {
|
||||
date = matcher.group();
|
||||
try {
|
||||
n = LocalDate.parse(date);
|
||||
companyFile.setExpiringDate(n);
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(
|
||||
"parse date failure, it used to set ExpiringDate, {} from {} by Regex:{}, @{}",
|
||||
date, fileName, MyDateTimeUtils.REGEX_DATE, companyFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("parse date failure, it used to set ApplyDate, {} from {} by Regex:{}, @{}",
|
||||
date, fileName, MyDateTimeUtils.REGEX_DATE, companyFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动文件到企业目录下
|
||||
*
|
||||
* @param company 企业对象
|
||||
* @param files 要被移动的文件集合,需要从中选择需要的
|
||||
* @param status 状态输出
|
||||
*/
|
||||
public boolean retrieveFromDownloadFiles(Company company, File[] files, Consumer<String> status) {
|
||||
Map<String, File> map = new HashMap<>();
|
||||
File home = new File(company.getPath());
|
||||
map.put(company.getName(), home);
|
||||
List<CompanyFile> retrieveFiles = new ArrayList<>();
|
||||
|
||||
// 获取所有曾用名
|
||||
for (CompanyOldName companyOldName : companyOldNameRepository.findAllByCompanyId(company.getId())) {
|
||||
String name = companyOldName.getName();
|
||||
if (!StringUtils.hasText(name)) {
|
||||
continue;
|
||||
}
|
||||
File dir = null;
|
||||
String path = companyOldName.getPath();
|
||||
if (StringUtils.hasText(path)) {
|
||||
dir = new File(path);
|
||||
}
|
||||
map.put(name, dir);
|
||||
}
|
||||
|
||||
// 对所有文件进行遍历
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
File file = files[i];
|
||||
// 只处理文件
|
||||
if (!file.isFile()) {
|
||||
continue;
|
||||
}
|
||||
String prefix = (i + 1) + "/" + files.length + ":";
|
||||
Consumer<String> inner = (str) -> {
|
||||
status.accept(prefix + str);
|
||||
};
|
||||
|
||||
String fileName = file.getName();
|
||||
inner.accept(fileName);
|
||||
for (Map.Entry<String, File> entry : map.entrySet()) {
|
||||
String companyName = entry.getKey();
|
||||
// 必须要包含公司名称否则无法区分
|
||||
if (!fileName.contains(companyName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 文件存储的目的地目录
|
||||
File dir = entry.getValue();
|
||||
if (dir == null) {
|
||||
dir = home;
|
||||
}
|
||||
|
||||
CompanyFile filled = fillDownloadFileType(company, file, companyName, dir, inner);
|
||||
if (filled != null) {
|
||||
retrieveFiles.add(filled);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
status.accept("导入 " + retrieveFiles.size() + " 个文件");
|
||||
if (retrieveFiles.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// update db
|
||||
retrieveFiles.forEach(v -> v.setCompany(company));
|
||||
companyFileRepository.saveAll(retrieveFiles);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件名生成公司文件对象
|
||||
* 文件从下载目录中导入
|
||||
*
|
||||
* @param company 公司对象
|
||||
* @param file 导入的文件对象
|
||||
* @param companyName 公司名称
|
||||
* @param destDir 目标目录
|
||||
* @param status 状态输出
|
||||
* @return 生成的公司文件对象,如果无法转换则返回null
|
||||
*/
|
||||
private CompanyFile fillDownloadFileType(Company company, File file, String companyName, File destDir,
|
||||
Consumer<String> status) {
|
||||
String fileName = file.getName();
|
||||
// 天眼查的报告
|
||||
// 目前只有 基础版企业信用报告, 企业信用信息公示报告下载保存时的文件名中没有天眼查
|
||||
if (CloudTycService.isTycReport(fileName)) {
|
||||
CompanyFile companyFile = new CompanyFile();
|
||||
companyFile.setType(CompanyFileType.CreditReport);
|
||||
fillApplyDateAbsent(file, companyFile);
|
||||
|
||||
String destFileName = fileName;
|
||||
// 重命名 基础版企业信用报告
|
||||
for (String report : Arrays.asList(
|
||||
CloudTycService.TYC_ENTERPRISE_ANALYSIS_REPORT,
|
||||
CloudTycService.TYC_ENTERPRISE_BASIC_REPORT,
|
||||
CloudTycService.TYC_ENTERPRISE_MAJOR_REPORT)) {
|
||||
|
||||
if (fileName.contains(report)) {
|
||||
LocalDate applyDate = companyFile.getApplyDate();
|
||||
if (applyDate == null) {
|
||||
applyDate = LocalDate.now();
|
||||
companyFile.setApplyDate(applyDate);
|
||||
}
|
||||
String formatted = MyDateTimeUtils.format(applyDate);
|
||||
String extension = StringUtils.getFilenameExtension(fileName);
|
||||
destFileName = String.format("%s_%s_%s_%s.%s",
|
||||
companyName, CloudServiceConstant.TYC_NAME, report, formatted, extension);
|
||||
}
|
||||
}
|
||||
|
||||
// 重新设置 企业分析报告 未普通文件
|
||||
// if (fileName.contains(CloudTycService.TYC_ENTERPRISE_ANALYSIS_REPORT)) {
|
||||
// companyFile.setType(General);
|
||||
// }
|
||||
|
||||
File dest = new File(destDir, destFileName);
|
||||
// 移动文件
|
||||
if (!file.renameTo(dest)) {
|
||||
// 移动失败时
|
||||
status.accept(fileName + " 无法移动到 " + dest.getAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
|
||||
status.accept(fileName + " 移动到 " + dest.getAbsolutePath());
|
||||
companyFile.setFilePath(dest.getAbsolutePath());
|
||||
|
||||
//
|
||||
if (companyFile.getExpiringDate() == null) {
|
||||
if (companyFile.getApplyDate() != null) {
|
||||
companyFile.setExpiringDate(companyFile.getApplyDate().plusYears(1));
|
||||
}
|
||||
}
|
||||
return companyFile;
|
||||
}
|
||||
|
||||
// 企业信用信息公示报告
|
||||
if (fileName.contains(CloudTycService.TYC_ENTERPRISE_CREDIT_REPORT)) {
|
||||
CompanyFile companyFile = new CompanyFile();
|
||||
companyFile.setType(CompanyFileType.CreditInfoPublicityReport);
|
||||
fillApplyDateAbsent(file, companyFile);
|
||||
File dest = new File(destDir, fileName);
|
||||
|
||||
// 移动文件
|
||||
if (!file.renameTo(dest)) {
|
||||
if (dest.exists()) {
|
||||
// 尝试删除已经存在的文件
|
||||
if (!dest.delete()) {
|
||||
status.accept("覆盖时,无法删除已存在的文件 " + dest.getAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
if (file.renameTo(dest)) {
|
||||
Optional<CompanyFile> one = companyFileRepository.findOne(((root, query, builder) -> {
|
||||
return builder.and(
|
||||
builder.equal(root.get("filePath"), dest.getAbsolutePath()),
|
||||
builder.equal(root.get("company"), company));
|
||||
}));
|
||||
if (one.isPresent()) {
|
||||
companyFile = one.get();
|
||||
}
|
||||
} else {
|
||||
status.accept(fileName + " 无法覆盖到 " + dest.getAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
status.accept(fileName + " 无法移动到 " + dest.getAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
status.accept(fileName + " 移动到 " + dest.getAbsolutePath());
|
||||
companyFile.setFilePath(dest.getAbsolutePath());
|
||||
|
||||
return companyFile;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当 ApplyDate 未设置时,尝试使用文件名中包含的日期
|
||||
*/
|
||||
private static void fillApplyDateAbsent(File file, CompanyFile companyFile) {
|
||||
LocalDate applyDate = companyFile.getApplyDate();
|
||||
if (applyDate != null) {
|
||||
return;
|
||||
}
|
||||
String fileName = file.getName();
|
||||
// 从文件名中提取日期
|
||||
LocalDate picked = MyDateTimeUtils.pickLocalDate(fileName);
|
||||
if (picked != null) {
|
||||
companyFile.setApplyDate(picked);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.ecep.contract.ds.company.repository.CompanyInvoiceInfoRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyInvoiceInfo;
|
||||
|
||||
/**
|
||||
* 公司发票信息服务
|
||||
*/
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company-invoice-info")
|
||||
public class CompanyInvoiceInfoService {
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyInvoiceInfoRepository repository;
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public CompanyInvoiceInfo findById(int id) {
|
||||
return repository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
public List<CompanyInvoiceInfo> searchByCompany(Company company, String searchText) {
|
||||
Specification<CompanyInvoiceInfo> spec = (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("name"), "%" + searchText + "%"),
|
||||
builder.like(root.get("taxId"), "%" + searchText + "%"),
|
||||
builder.like(root.get("address"), "%" + searchText + "%"),
|
||||
builder.like(root.get("phone"), "%" + searchText + "%"),
|
||||
builder.like(root.get("bankName"), "%" + searchText + "%"),
|
||||
builder.like(root.get("bankAccount"), "%" + searchText + "%")
|
||||
);
|
||||
};
|
||||
|
||||
if (company != null) {
|
||||
spec = spec.and((root, query, builder) -> {
|
||||
return builder.equal(root.get("company"), company);
|
||||
});
|
||||
}
|
||||
return repository.findAll(spec, Pageable.ofSize(10)).getContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.ds.company.CompanyFileUtils;
|
||||
import com.ecep.contract.ds.company.repository.CompanyOldNameRepository;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
import com.ecep.contract.util.SpecificationUtils;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
public class CompanyOldNameService implements IEntityService<CompanyOldName> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyOldNameService.class);
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyOldNameRepository companyOldNameRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
|
||||
|
||||
public CompanyOldName findById(Integer id) {
|
||||
return companyOldNameRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<CompanyOldName> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
return SpecificationUtils.andWith(searchText, this::buildSearchSpecification);
|
||||
}
|
||||
|
||||
protected Specification<CompanyOldName> buildSearchSpecification(String searchText) {
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("name"), "%" + searchText + "%"),
|
||||
builder.like(root.get("memo"), "%" + searchText + "%")
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public CompanyOldName save(CompanyOldName companyOldName) {
|
||||
return companyOldNameRepository.save(companyOldName);
|
||||
}
|
||||
|
||||
public boolean makePathAbsent(CompanyOldName companyOldName) {
|
||||
String path = companyOldName.getPath();
|
||||
if (StringUtils.hasText(path)) {
|
||||
File file = new File(path);
|
||||
if (file.exists()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
File dir = makePath(companyOldName);
|
||||
if (dir == null) {
|
||||
return false;
|
||||
}
|
||||
if (!dir.exists()) {
|
||||
return false;
|
||||
}
|
||||
companyOldName.setPath(dir.getAbsolutePath());
|
||||
return true;
|
||||
}
|
||||
|
||||
public File makePath(CompanyOldName companyOldName) {
|
||||
String oldName = companyOldName.getName();
|
||||
File basePath = companyService.getBasePath();
|
||||
Company company = companyService.findById(companyOldName.getCompanyId());
|
||||
String district = company.getDistrict();
|
||||
if (StringUtils.hasText(district)) {
|
||||
String parentPrefix = CompanyFileUtils.getParentPrefixByDistrict(district);
|
||||
if (parentPrefix != null) {
|
||||
File parent = new File(basePath, parentPrefix);
|
||||
if (!parent.exists()) {
|
||||
if (!parent.mkdir()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
String fileName = CompanyFileUtils.escapeFileName(oldName);
|
||||
File dir = new File(parent, fileName);
|
||||
if (!dir.exists()) {
|
||||
if (!dir.mkdir()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public List<CompanyOldName> findAllByName(String name) {
|
||||
return companyOldNameRepository.findAllByName(name);
|
||||
}
|
||||
|
||||
public List<CompanyOldName> findAll(Specification<CompanyOldName> spec, Sort sort) {
|
||||
return companyOldNameRepository.findAll(spec, sort);
|
||||
}
|
||||
|
||||
public List<CompanyOldName> findAllByCompany(Company company) {
|
||||
return companyOldNameRepository.findAllByCompanyId(company.getId());
|
||||
}
|
||||
|
||||
public CompanyOldName findMatchByDate(Company company, LocalDate date) {
|
||||
List<CompanyOldName> oldNames = findAllByCompany(company);
|
||||
if (oldNames == null || oldNames.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return oldNames.stream().filter(v -> {
|
||||
if (v.getAmbiguity()) {
|
||||
return false;
|
||||
}
|
||||
if (v.getBeginDate() != null && date.isBefore(v.getBeginDate())) {
|
||||
return false;
|
||||
}
|
||||
if (v.getEndDate() != null && date.isAfter(v.getEndDate())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public void deleteById(int id) {
|
||||
companyOldNameRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public void delete(CompanyOldName entity) {
|
||||
companyOldNameRepository.delete(entity);
|
||||
}
|
||||
|
||||
public List<CompanyOldName> findAllByCompanyAndName(Company company, String oldName) {
|
||||
return companyOldNameRepository.findAllByCompanyIdAndName(company.getId(), oldName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 from 的曾用名 关联到 to
|
||||
*
|
||||
* @param from from
|
||||
* @param to to
|
||||
*/
|
||||
public void resetTo(Company from, Company to) {
|
||||
// 曾用名 关联到 to
|
||||
List<CompanyOldName> list = companyOldNameRepository.findAllByCompanyId(from.getId());
|
||||
if (list.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (CompanyOldName oldName : list) {
|
||||
oldName.setMemo(MyStringUtils.appendIfAbsent(oldName.getMemo(), "转自 " + from.getId()));
|
||||
oldName.setCompanyId(to.getId());
|
||||
}
|
||||
companyOldNameRepository.saveAll(list);
|
||||
}
|
||||
|
||||
public void deleteByCompany(Company company) {
|
||||
int deleted = companyOldNameRepository.deleteAllByCompanyId(company.getId());
|
||||
if (deleted > 0) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete {} records by company:#{}", deleted, company.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据提供的搜索文本查询公司旧名称列表。
|
||||
* <p>
|
||||
* 该函数使用JPA的Specification接口构建查询条件,查找公司旧名称中包含指定文本的记录。
|
||||
* 查询结果最多返回10条记录。
|
||||
*
|
||||
* @param searchText 用于搜索的文本,将匹配公司旧名称中包含该文本的记录。
|
||||
* @return 包含匹配的公司旧名称的列表,列表中的每个元素都是一个CompanyOldName对象。
|
||||
*/
|
||||
public List<CompanyOldName> search(String searchText) {
|
||||
return companyOldNameRepository.findAll(getSpecification(searchText), Pageable.ofSize(10)).getContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<CompanyOldName> findAll(Specification<CompanyOldName> spec, Pageable pageable) {
|
||||
return companyOldNameRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
public CompanyOldName createNew(Company company, String name, boolean ambiguity) {
|
||||
CompanyOldName companyOldName = new CompanyOldName();
|
||||
companyOldName.setCompanyId(company.getId());
|
||||
companyOldName.setName(name);
|
||||
companyOldName.setAmbiguity(ambiguity);
|
||||
return companyOldName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.MyDateTimeUtils;
|
||||
import com.ecep.contract.cloud.rk.CloudRkService;
|
||||
import com.ecep.contract.cloud.tyc.CloudTycService;
|
||||
import com.ecep.contract.cloud.u8.YongYouU8Service;
|
||||
import com.ecep.contract.constant.CompanyVendorConstant;
|
||||
import com.ecep.contract.ds.company.CompanyFileUtils;
|
||||
import com.ecep.contract.ds.company.repository.CompanyRepository;
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
|
||||
import com.ecep.contract.ds.other.service.SysConfService;
|
||||
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.CompanyCustomer;
|
||||
import com.ecep.contract.model.CompanyOldName;
|
||||
import com.ecep.contract.model.CompanyVendor;
|
||||
import com.ecep.contract.util.MyStringUtils;
|
||||
import com.ecep.contract.util.SpecificationUtils;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Path;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
/**
|
||||
* 公司服务
|
||||
*/
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "company")
|
||||
public class CompanyService implements IEntityService<Company> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyService.class);
|
||||
private static final String COMPANY_BASE_PATH = "company.base.path";
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyRepository companyRepository;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private SysConfService confService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyFileService companyFileService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private ContractService contractService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyVendorService companyVendorService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyCustomerService companyCustomerService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyOldNameService companyOldNameService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CompanyContactService companyContactService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CloudRkService cloudRkService;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CloudTycService cloudTycService;
|
||||
@Lazy
|
||||
@Autowired(required = false)
|
||||
private YongYouU8Service yongYouU8Service;
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public Company findById(Integer id) {
|
||||
return companyRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Cacheable(key = "'name-'+#p0")
|
||||
public Company findByName(String name) {
|
||||
return companyRepository.findFirstByName(name).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找名称是 name 的记录
|
||||
*
|
||||
* @param name 查询的公司名称
|
||||
* @return 记录列表
|
||||
*/
|
||||
public List<Company> findAllByName(String name) {
|
||||
return companyRepository.findAllByName(name);
|
||||
}
|
||||
|
||||
public Page<Company> findAll(Specification<Company> spec, Pageable pageable) {
|
||||
return companyRepository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找
|
||||
* 重复的删除
|
||||
*
|
||||
* @param uniscid 统一社会信用代码
|
||||
* @return 公司对象
|
||||
*/
|
||||
public Company findAndRemoveDuplicateCompanyByUniscid(String uniscid) {
|
||||
// 根据统一社会信用代码去查询
|
||||
List<Company> companies = companyRepository.findAllByUniscid(uniscid);
|
||||
if (companies.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (companies.size() == 1) {
|
||||
return companies.getFirst();
|
||||
} else {
|
||||
List<Company> result = removeDuplicatesByUniscid(companies);
|
||||
if (!result.isEmpty()) {
|
||||
return result.getFirst();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找公司,根据名称或简称查询
|
||||
* <p>
|
||||
* 1. 先按照 name 查找Company记录,如果有多个记录只保留一条,保留规则参考 #removeDuplicatesByUniscid 方法
|
||||
* 2. 第一步没有匹配到时,根据名称从曾用名中查询
|
||||
* 3. 上一步没有匹配到时,根据简称从公司数据库查询匹配简称的公司
|
||||
* 4. 上一步没有匹配到时,根据简称从曾用名中查询
|
||||
* 根据简称去查询,如果有多个记录只保留一条,保留规则参考 #removeDuplicatesByUniscid 方法
|
||||
* 重复的删除
|
||||
*
|
||||
* @param name 企业名称
|
||||
* @param abbName 别名
|
||||
* @return 公司对象
|
||||
*/
|
||||
public Company findAndRemoveDuplicateCompanyByNameOrAbbName(String name, String abbName) {
|
||||
Company updater = null;
|
||||
{
|
||||
// 根据公司全名去查询
|
||||
List<Company> companies = companyRepository.findAllByName(name);
|
||||
if (companies.isEmpty()) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("No record match by {}", name);
|
||||
}
|
||||
} else if (companies.size() == 1) {
|
||||
updater = companies.getFirst();
|
||||
} else {
|
||||
List<Company> result = removeDuplicatesByUniscid(companies);
|
||||
if (!result.isEmpty()) {
|
||||
updater = result.getFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updater == null) {
|
||||
// 根据公司名称去曾用名中查询
|
||||
List<CompanyOldName> oldNames = companyOldNameService.findAllByName(name);
|
||||
if (!oldNames.isEmpty()) {
|
||||
CompanyOldName oldName = oldNames.getFirst();
|
||||
Optional<Company> optional = companyRepository.findById(oldName.getCompanyId());
|
||||
if (optional.isPresent()) {
|
||||
updater = optional.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updater == null && StringUtils.hasText(abbName) && !Objects.equals(abbName, name)) {
|
||||
// 根据公司全面去查询
|
||||
List<Company> companies = companyRepository.findAllByShortName(abbName);
|
||||
if (!companies.isEmpty()) {
|
||||
updater = companies.removeFirst();
|
||||
}
|
||||
|
||||
if (updater == null) {
|
||||
// 根据公司名称去曾用名中查询
|
||||
List<CompanyOldName> oldNames = companyOldNameService.findAllByName(abbName);
|
||||
if (!oldNames.isEmpty()) {
|
||||
CompanyOldName oldName = null;
|
||||
Optional<CompanyOldName> optional1 = oldNames.stream().filter(CompanyOldName::getAmbiguity)
|
||||
.findFirst();
|
||||
oldName = optional1.orElseGet(oldNames::getFirst);
|
||||
Optional<Company> optional = companyRepository.findById(oldName.getCompanyId());
|
||||
if (optional.isPresent()) {
|
||||
updater = optional.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return updater;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除 列表中 Uniscid 重复的
|
||||
*/
|
||||
private List<Company> removeDuplicatesByUniscid(List<Company> list) {
|
||||
List<Company> result = new ArrayList<>();
|
||||
List<Company> removes = new ArrayList<>();
|
||||
Set<String> uniqueUniscidSet = new HashSet<>();
|
||||
for (Company company : list) {
|
||||
// 名称相同后,统一社会信用编号 也相同的话,删除
|
||||
if (uniqueUniscidSet.add(company.getUniscid())) {
|
||||
// 没有记录过时
|
||||
result.add(company);
|
||||
} else {
|
||||
// 有重复时
|
||||
removes.add(company);
|
||||
}
|
||||
}
|
||||
|
||||
Company updater = result.getFirst();
|
||||
// 合并重复的
|
||||
for (Company company : removes) {
|
||||
try {
|
||||
merge(company, updater);
|
||||
} catch (Exception e) {
|
||||
logger.error("合并 {} -> {} 时发生错误:{}", company.toPrettyString(), updater.toPrettyString(), e.getMessage(),
|
||||
e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
* <p>
|
||||
* 删除前需要把关联数据解除
|
||||
* <ul>
|
||||
* <li>{@link CompanyVendorService#deleteByCompany(Company)}</li>
|
||||
* <li>{@link CompanyCustomerService#deleteByCompany(Company)}</li>
|
||||
* <li>{@link CompanyOldNameService#deleteByCompany(Company)}</li>
|
||||
* <li>{@link CompanyContactService#deleteByCompany(Company)}</li>
|
||||
* <li>{@link ContractService#deleteByCompany(Company)}</li>
|
||||
* <li>{@link CompanyContactService#deleteByCompany(Company)}</li>
|
||||
* </ul>
|
||||
* 或者 把关联数据转移到其他公司
|
||||
* <ul>
|
||||
* <li>{@link CompanyVendorService#resetTo(Company, Company)}</li>
|
||||
* <li>{@link CompanyCustomerService#resetTo(Company, Company)}</li>
|
||||
* <li>{@link CompanyOldNameService#resetTo(Company, Company)}</li>
|
||||
* <li>{@link CompanyContactService#resetTo(Company, Company)}</li>
|
||||
* <li>{@link ContractService#resetTo(Company, Company)}</li>
|
||||
* <li>{@link CompanyContactService#resetTo(Company, Company)}</li>
|
||||
* </ul>
|
||||
* </p>
|
||||
*
|
||||
* @param company 要删除的公司对象
|
||||
*/
|
||||
@Caching(evict = {
|
||||
@CacheEvict(key = "#p0.id"),
|
||||
@CacheEvict(key = "'name-'+#p0.name")
|
||||
})
|
||||
public void delete(Company company) {
|
||||
cloudRkService.deleteByCompany(company);
|
||||
cloudTycService.deleteByCompany(company);
|
||||
yongYouU8Service.deleteByCompany(company);
|
||||
|
||||
companyOldNameService.deleteByCompany(company);
|
||||
companyContactService.deleteByCompany(company);
|
||||
// 供应商和客户
|
||||
companyVendorService.deleteByCompany(company);
|
||||
companyCustomerService.deleteByCompany(company);
|
||||
|
||||
contractService.deleteByCompany(company);
|
||||
companyContactService.deleteByCompany(company);
|
||||
|
||||
companyRepository.delete(company);
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Delete Company {}", company);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 from 到 to
|
||||
* <p>
|
||||
* 下述关联数据重设绑定到 to
|
||||
* <ol>
|
||||
* <li>曾用名</li>
|
||||
* <li>供应商</li>
|
||||
* <li>客户</li>
|
||||
* <li>合同</li>
|
||||
* <li>公司合同</li>
|
||||
* </ol>
|
||||
* </p>
|
||||
*/
|
||||
public void merge(Company from, Company to) {
|
||||
// cloudRkService.findById(from.getId());
|
||||
cloudRkService.resetTo(from, to);
|
||||
cloudTycService.resetTo(from, to);
|
||||
yongYouU8Service.resetTo(from, to);
|
||||
|
||||
companyOldNameService.resetTo(from, to);
|
||||
companyContactService.resetTo(from, to);
|
||||
// 供应商和客户
|
||||
companyVendorService.resetTo(from, to);
|
||||
companyCustomerService.resetTo(from, to);
|
||||
|
||||
contractService.resetTo(from, to);
|
||||
companyContactService.resetTo(from, to);
|
||||
companyRepository.delete(from);
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Merge {} to {}", from, to);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存实体对象,异步方法
|
||||
*
|
||||
* @param company 要保存的实体对象
|
||||
* @return 返回异步调用
|
||||
*/
|
||||
public CompletableFuture<Company> asyncSave(Company company) {
|
||||
return CompletableFuture.completedFuture(companyRepository.save(company));
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存实体对象
|
||||
*
|
||||
* @param company 要保存的实体对象
|
||||
* @return 返回异步调用
|
||||
*/
|
||||
@Caching(evict = {
|
||||
@CacheEvict(key = "#p0.id"),
|
||||
@CacheEvict(key = "'name-'+#p0.name")
|
||||
})
|
||||
public Company save(Company company) {
|
||||
return companyRepository.save(company);
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return companyRepository.count();
|
||||
}
|
||||
|
||||
public long count(Specification<Company> spec) {
|
||||
return companyRepository.count(spec);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void findAllWithStream(Consumer<Stream<Company>> consumer) {
|
||||
try (Stream<Company> stream = companyRepository.findAllAsStream()) {
|
||||
consumer.accept(stream);
|
||||
}
|
||||
}
|
||||
|
||||
public File getVendorBasePath() {
|
||||
return new File(confService.getString(CompanyVendorConstant.KEY_BASE_PATH));
|
||||
}
|
||||
|
||||
public File getCustomerBasePath() {
|
||||
return new File(confService.getString(CompanyCustomerService.KEY_BASE_PATH));
|
||||
}
|
||||
|
||||
public File getBasePath() {
|
||||
return new File(confService.getString(COMPANY_BASE_PATH));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建公司目录,如果公司目录未设置,或者未存在
|
||||
*
|
||||
* @param company 要创建目录的公司对象
|
||||
* @return 是否创建了目录
|
||||
*/
|
||||
public boolean makePathAbsent(Company company) {
|
||||
String path = company.getPath();
|
||||
if (StringUtils.hasText(path)) {
|
||||
File file = new File(path);
|
||||
if (file.exists()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
File dir = makePath(company);
|
||||
if (dir == null) {
|
||||
return false;
|
||||
}
|
||||
if (!dir.exists()) {
|
||||
return false;
|
||||
}
|
||||
company.setPath(dir.getAbsolutePath());
|
||||
company.setPathExist(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建企业目录
|
||||
*
|
||||
* @param company 要创建的企业对象
|
||||
* @return 目录
|
||||
*/
|
||||
public File makePath(Company company) {
|
||||
File basePath = getBasePath();
|
||||
if (!basePath.exists()) {
|
||||
return null;
|
||||
}
|
||||
String companyName = company.getName();
|
||||
String district = company.getDistrict();
|
||||
if (StringUtils.hasText(district)) {
|
||||
String parentPrefix = CompanyFileUtils.getParentPrefixByDistrict(district);
|
||||
if (parentPrefix != null) {
|
||||
File parent = new File(basePath, parentPrefix);
|
||||
if (!parent.exists()) {
|
||||
if (!parent.mkdir()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
String fileName = CompanyFileUtils.escapeFileName(companyName);
|
||||
File dir = new File(parent, fileName);
|
||||
if (!dir.exists()) {
|
||||
if (!dir.mkdir()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动文件到企业目录下
|
||||
*
|
||||
* @param company 企业对象
|
||||
* @param files 要被移动的文件集合,需要从中选择需要的
|
||||
* @param status 状态输出
|
||||
*/
|
||||
public boolean retrieveFromDownloadFiles(Company company, File[] files, Consumer<String> status) {
|
||||
//
|
||||
boolean companyChanged = makePathAbsent(company);
|
||||
|
||||
if (!StringUtils.hasText(company.getPath())) {
|
||||
// fixed 要退出,需要保存
|
||||
if (companyChanged) {
|
||||
save(company);
|
||||
}
|
||||
status.accept("存储目录未设置,请检查");
|
||||
return false;
|
||||
}
|
||||
|
||||
File home = new File(company.getPath());
|
||||
if (!home.exists()) {
|
||||
// fixed 要退出,需要保存
|
||||
if (companyChanged) {
|
||||
company = save(company);
|
||||
}
|
||||
status.accept(company.getPath() + " 不存在,无法访问,请检查或者修改");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean retrieved = companyFileService.retrieveFromDownloadFiles(company, files, status);
|
||||
if (companyChanged) {
|
||||
save(company);
|
||||
}
|
||||
return retrieved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证企业状态
|
||||
*
|
||||
* @param company 要验证的公司
|
||||
* @param verifyDate 验证日期
|
||||
* @param status 状态输出
|
||||
*/
|
||||
public void verifyEnterpriseStatus(Company company, LocalDate verifyDate, Consumer<String> status) {
|
||||
// 检查营业状态
|
||||
String entStatus = company.getEntStatus();
|
||||
if (StringUtils.hasText(entStatus)) {
|
||||
if (entStatus.contains("注销")) {
|
||||
LocalDate end = company.getOperationPeriodEnd();
|
||||
LocalDate begin = company.getOperationPeriodBegin();
|
||||
if (begin == null || end == null) {
|
||||
// 注销时间未知,无法判断是否在 verifyDate 之后注销
|
||||
status.accept("营业状态异常:" + entStatus);
|
||||
} else {
|
||||
if (!MyDateTimeUtils.dateValidFilter(verifyDate, begin, end, 0)) {
|
||||
status.accept("营业状态异常:" + entStatus);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status.accept("营业状态异常:未设置");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<Company> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
// 判断是否全是数字
|
||||
boolean isAllDigit = MyStringUtils.isAllDigit(searchText);
|
||||
if (isAllDigit) {
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("id").as(String.class), "%" + searchText + "%"),
|
||||
builder.like(root.get("uniscid"), "%" + searchText + "%"));
|
||||
};
|
||||
}
|
||||
|
||||
Specification<Company> spec = null;
|
||||
Set<Integer> idSet = companyOldNameService.search(searchText).stream().map(CompanyOldName::getCompanyId)
|
||||
.collect(Collectors.toSet());
|
||||
if (!idSet.isEmpty()) {
|
||||
spec = SpecificationUtils.or(spec, (root, query, builder) -> {
|
||||
return root.get("id").in(idSet);
|
||||
});
|
||||
}
|
||||
|
||||
List<CompanyVendor> searchedVendors = companyVendorService.search(searchText);
|
||||
if (!searchedVendors.isEmpty()) {
|
||||
spec = SpecificationUtils.or(spec, (root, query, builder) -> {
|
||||
return builder.in(root.get("id")).value(searchedVendors.stream()
|
||||
.map(CompanyVendor::getCompany)
|
||||
.filter(Objects::nonNull)
|
||||
.map(Company::getId)
|
||||
.collect(Collectors.toSet()));
|
||||
});
|
||||
}
|
||||
|
||||
List<CompanyCustomer> searchedCustomers = companyCustomerService.search(searchText);
|
||||
if (!searchedCustomers.isEmpty()) {
|
||||
spec = SpecificationUtils.or(spec, (root, query, builder) -> {
|
||||
return builder.in(root.get("id")).value(searchedCustomers.stream()
|
||||
.map(CompanyCustomer::getCompany)
|
||||
.filter(Objects::nonNull)
|
||||
.map(Company::getId)
|
||||
.collect(Collectors.toSet()));
|
||||
});
|
||||
}
|
||||
|
||||
return SpecificationUtils.or(spec, SpecificationUtils.andWith(searchText, this::buildSearchSpecification));
|
||||
}
|
||||
|
||||
protected Specification<Company> buildSearchSpecification(String searchText) {
|
||||
return (root, query, builder) -> buildSearchPredicate(searchText, root, query, builder);
|
||||
}
|
||||
|
||||
public Predicate buildSearchPredicate(String searchText, Path<Company> root, @Nullable CriteriaQuery<?> query,
|
||||
CriteriaBuilder builder) {
|
||||
return builder.or(
|
||||
builder.like(root.get("name"), "%" + searchText + "%"),
|
||||
builder.like(root.get("shortName"), "%" + searchText + "%"),
|
||||
builder.like(root.get("uniscid"), "%" + searchText + "%"),
|
||||
builder.like(root.get("legalRepresentative"), "%" + searchText + "%"),
|
||||
builder.like(root.get("regAddr"), "%" + searchText + "%"),
|
||||
builder.like(root.get("address"), "%" + searchText + "%"),
|
||||
builder.like(root.get("memo"), "%" + searchText + "%"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 检索企业
|
||||
* 企业名称中模糊搜索
|
||||
*
|
||||
* @param searchText 搜索文本
|
||||
* @return 企业列表,返回前10个企业
|
||||
*/
|
||||
public List<Company> search(String searchText) {
|
||||
Specification<Company> spec = getSpecification(searchText);
|
||||
return companyRepository.findAll(spec, Pageable.ofSize(10)).getContent();
|
||||
}
|
||||
|
||||
public Company createNewCompany(String name) {
|
||||
Company company = new Company();
|
||||
company.setName(name);
|
||||
company.setCreated(LocalDate.now());
|
||||
return company;
|
||||
}
|
||||
|
||||
public List<String> getAllNames(Company company) {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add(company.getName());
|
||||
companyOldNameService.findAllByCompany(company).forEach(oldName -> {
|
||||
// 歧义的曾用名不采用
|
||||
if (oldName.getAmbiguity()) {
|
||||
return;
|
||||
}
|
||||
list.add(oldName.getName());
|
||||
});
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ecep.contract.ds.company.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.ecep.contract.IEntityService;
|
||||
import com.ecep.contract.ds.company.repository.InvoiceRepository;
|
||||
import com.ecep.contract.model.Invoice;
|
||||
|
||||
@Lazy
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "invoice")
|
||||
public class InvoiceService implements IEntityService<Invoice> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(InvoiceService.class);
|
||||
|
||||
@Autowired
|
||||
private InvoiceRepository repository;
|
||||
|
||||
|
||||
@Cacheable(key = "#p0")
|
||||
public Invoice findById(Integer id) {
|
||||
return repository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Specification<Invoice> getSpecification(String searchText) {
|
||||
if (!StringUtils.hasText(searchText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (root, query, builder) -> {
|
||||
return builder.or(
|
||||
builder.like(root.get("code"), "%" + searchText + "%"),
|
||||
builder.like(root.get("description"), "%" + searchText + "%")
|
||||
);
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Invoice> findAll(Specification<Invoice> spec, Pageable pageable) {
|
||||
return repository.findAll(spec, pageable);
|
||||
}
|
||||
|
||||
@CacheEvict(key = "#p0.id")
|
||||
public void delete(Invoice entity) {
|
||||
repository.delete(entity);
|
||||
}
|
||||
|
||||
public List<Invoice> findAll(Specification<Invoice> spec, Sort by) {
|
||||
return repository.findAll(spec, by);
|
||||
}
|
||||
|
||||
public Invoice findByCode(String invoiceNumber) {
|
||||
return repository.findByCode(invoiceNumber);
|
||||
}
|
||||
|
||||
@CacheEvict(key = "#p0.id")
|
||||
public Invoice save(Invoice invoice) {
|
||||
return repository.save(invoice);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.ecep.contract.ds.company.tasker;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.cloud.rk.CloudRkService;
|
||||
import com.ecep.contract.cloud.rk.ctx.CloudRkCtx;
|
||||
import com.ecep.contract.cloud.tyc.CloudTycService;
|
||||
import com.ecep.contract.cloud.u8.YongYouU8Service;
|
||||
import com.ecep.contract.cloud.u8.ctx.CompanyCtx;
|
||||
import com.ecep.contract.cloud.u8.ctx.ContractCtx;
|
||||
import com.ecep.contract.cloud.u8.ctx.CustomerCtx;
|
||||
import com.ecep.contract.cloud.u8.ctx.VendorCtx;
|
||||
import com.ecep.contract.constant.CloudServiceConstant;
|
||||
import com.ecep.contract.model.CloudRk;
|
||||
import com.ecep.contract.model.CloudYu;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 合并更新
|
||||
*/
|
||||
public class CompanyCompositeUpdateTasker extends Tasker<Object> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompanyCompositeUpdateTasker.class);
|
||||
|
||||
CloudRkCtx cloudRkCtx = new CloudRkCtx();
|
||||
|
||||
@Setter
|
||||
private CloudRkService cloudRkService;
|
||||
@Setter
|
||||
private CloudTycService cloudTycService;
|
||||
@Setter
|
||||
private YongYouU8Service yongYouU8Service;
|
||||
@Setter
|
||||
private Company company;
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
|
||||
updateProgress(0.1, 1);
|
||||
syncFromCloudRk(holder);
|
||||
updateProgress(0.3, 1);
|
||||
syncFromYongYouU8(holder);
|
||||
updateProgress(0.6, 1);
|
||||
syncFromCloudTyc(holder);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private void syncFromCloudRk(MessageHolder holder) {
|
||||
holder.debug("1. 从 " + CloudServiceConstant.RK_NAME + " 更新...");
|
||||
try {
|
||||
cloudRkService = getBean(CloudRkService.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.RK_NAME + " 服务");
|
||||
return;
|
||||
}
|
||||
CloudRk cloudRk = cloudRkService.getOrCreateCloudRk(company);
|
||||
if (cloudRk == null) {
|
||||
holder.error("无法创建或获取 CloudRk 对象");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
cloudRkCtx.setCloudRkService(cloudRkService);
|
||||
if (cloudRkCtx.syncCompany(company, cloudRk, holder)) {
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
cloudRk.setDescription(e.getMessage());
|
||||
} finally {
|
||||
cloudRk.setLatestUpdate(Instant.now());
|
||||
cloudRkService.save(cloudRk);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncFromYongYouU8(MessageHolder holder) {
|
||||
holder.debug("2. 从 " + CloudServiceConstant.U8_NAME + " 更新...");
|
||||
try {
|
||||
yongYouU8Service = getBean(YongYouU8Service.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
|
||||
return;
|
||||
}
|
||||
|
||||
CloudYu cloudYu = yongYouU8Service.getOrCreateCloudYu(company);
|
||||
if (cloudYu == null) {
|
||||
holder.error("无法创建或获取 CloudYu 对象");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
CompanyCtx companyCtx = new CompanyCtx();
|
||||
yongYouU8Service.initialize(companyCtx);
|
||||
if (companyCtx.syncCompany(company, holder)) {
|
||||
holder.info("更新");
|
||||
}
|
||||
|
||||
VendorCtx vendorCtx = new VendorCtx();
|
||||
yongYouU8Service.initialize(vendorCtx);
|
||||
vendorCtx.setCompanyCtx(companyCtx);
|
||||
if (vendorCtx.syncVendor(company, holder)) {
|
||||
cloudYu.setVendorUpdateDate(LocalDate.now());
|
||||
}
|
||||
|
||||
CustomerCtx customerCtx = new CustomerCtx();
|
||||
yongYouU8Service.initialize(customerCtx);
|
||||
customerCtx.setCompanyCtx(companyCtx);
|
||||
if (customerCtx.syncCustomer(company, holder)) {
|
||||
cloudYu.setCustomerUpdateDate(LocalDate.now());
|
||||
}
|
||||
|
||||
ContractCtx contractCtx = new ContractCtx();
|
||||
yongYouU8Service.initialize(contractCtx);
|
||||
contractCtx.syncContract(company, holder);
|
||||
|
||||
cloudYu.setCloudLatest(Instant.now());
|
||||
cloudYu.setExceptionMessage("");
|
||||
} catch (Exception e) {
|
||||
String message = e.getMessage();
|
||||
holder.error("同步过程中发生错误: " + message);
|
||||
// 保留255个字符
|
||||
if (message.length() > 255) {
|
||||
message = message.substring(0, 255);
|
||||
}
|
||||
cloudYu.setExceptionMessage(message);
|
||||
} finally {
|
||||
cloudYu.setLatestUpdate(Instant.now());
|
||||
yongYouU8Service.save(cloudYu);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncFromCloudTyc(MessageHolder holder) {
|
||||
holder.debug("3. 从 " + CloudServiceConstant.TYC_NAME + " 更新...");
|
||||
try {
|
||||
cloudTycService = getBean(CloudTycService.class);
|
||||
} catch (BeansException e) {
|
||||
holder.warn("未启用 " + CloudServiceConstant.TYC_NAME + " 服务");
|
||||
return;
|
||||
}
|
||||
cloudTycService.syncCompany(company, holder);
|
||||
updateProgress(1, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.ecep.contract.ds.company.tasker;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.company.service.CompanyFileService;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
/**
|
||||
* 对所有公司的文件进行重置
|
||||
*/
|
||||
public class CompanyFilesRebuildTasker extends Tasker<Object> {
|
||||
private CompanyFileService companyFileService;
|
||||
|
||||
public CompanyFilesRebuildTasker() {
|
||||
updateTitle("合同文件重置");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
Pageable pageRequest = PageRequest.ofSize(200);
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
Specification<Company> spec = null;
|
||||
// Specification<Contract> spec = (root, query, cb) -> {
|
||||
// return cb.greaterThan(root.get("created"), Instant.now().minusSeconds(TimeUnit.DAYS.toSeconds(360)));
|
||||
// };
|
||||
updateTitle("遍历所有公司,对每个可以公司的文件进行“重置”操作");
|
||||
long total = getCompanyService().count(spec);
|
||||
while (true) {
|
||||
if (isCancelled()) {
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
Page<Company> page = getCompanyService().findAll(spec, pageRequest);
|
||||
if (page.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (Company company : page) {
|
||||
if (isCancelled()) {
|
||||
break;
|
||||
}
|
||||
|
||||
String prefix = counter.get() + " / " + total + "> " + company.getName() + " #" + company.getId() + "> ";
|
||||
getCompanyFileService().reBuildingFiles(company, holder.sub(prefix)::info);
|
||||
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
}
|
||||
if (!page.hasNext()) {
|
||||
break;
|
||||
}
|
||||
pageRequest = page.nextPageable();
|
||||
}
|
||||
|
||||
return super.call();
|
||||
}
|
||||
|
||||
|
||||
private CompanyFileService getCompanyFileService() {
|
||||
if (companyFileService == null) {
|
||||
companyFileService = getBean(CompanyFileService.class);
|
||||
}
|
||||
return companyFileService;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ecep.contract.ds.company.tasker;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import com.ecep.contract.MessageHolder;
|
||||
import com.ecep.contract.ds.company.service.CompanyService;
|
||||
import com.ecep.contract.ds.contract.tasker.ContractVerifyComm;
|
||||
import com.ecep.contract.model.Company;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.ui.Tasker;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class CompanyVerifyTasker extends Tasker<Object> {
|
||||
@Setter
|
||||
private CompanyService companyService;
|
||||
@Getter
|
||||
@Setter
|
||||
private Company company;
|
||||
|
||||
|
||||
ContractVerifyComm comm = new ContractVerifyComm();
|
||||
AtomicBoolean verified = new AtomicBoolean(true);
|
||||
|
||||
public CompanyService getCompanyService() {
|
||||
if (companyService == null) {
|
||||
companyService = getBean(CompanyService.class);
|
||||
}
|
||||
return companyService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object call() throws Exception {
|
||||
comm.setVerifyCompanyPath(false);
|
||||
comm.setVerifyCompanyStatus(false);
|
||||
comm.setVerifyCompanyCredit(false);
|
||||
return execute(new MessageHolderImpl() {
|
||||
@Override
|
||||
public void addMessage(Level level, String message) {
|
||||
super.addMessage(level, message);
|
||||
if (level.intValue() > Level.INFO.intValue()) {
|
||||
verified.set(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object execute(MessageHolder holder) throws Exception {
|
||||
updateTitle("验证企业是否符合合规要求");
|
||||
|
||||
verify(company, holder);
|
||||
|
||||
if (verified.get()) {
|
||||
updateMessage(Level.CONFIG, "合规验证通过");
|
||||
} else {
|
||||
updateMessage(Level.SEVERE, "合规验证不通过");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 核验公司名下的所有合同
|
||||
*
|
||||
* @param company 公司
|
||||
* @param holder 输出
|
||||
*/
|
||||
private void verify(Company company, MessageHolder holder) {
|
||||
LocalDate now = LocalDate.now();
|
||||
getCompanyService().verifyEnterpriseStatus(company, now, holder::info);
|
||||
|
||||
// 验证所有的合同
|
||||
List<Contract> list = comm.getContractService().findAllByCompany(company);
|
||||
if (list.isEmpty()) {
|
||||
holder.debug("!没有相关合同!");
|
||||
return;
|
||||
}
|
||||
holder.debug("检索到相关合同 " + list.size() + " 个");
|
||||
AtomicInteger counter = new AtomicInteger(0);
|
||||
long total = list.size();
|
||||
for (Contract contract : list) {
|
||||
holder.debug("核验合同:" + contract.getCode() + ", " + contract.getName());
|
||||
comm.verify(company, contract, holder.sub("-- "));
|
||||
updateProgress(counter.incrementAndGet(), total);
|
||||
}
|
||||
updateProgress(1, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.ecep.contract.ds.contract;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.ecep.contract.ds.contract.service.ContractService;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.util.EntityStringConverter;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
@Lazy
|
||||
@Component
|
||||
public class ContractStringConverter extends EntityStringConverter<Contract> {
|
||||
@Lazy
|
||||
@Autowired
|
||||
ContractService service;
|
||||
|
||||
public ContractStringConverter() {
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
setInitialized(project -> service.findById(project.getId()));
|
||||
setSuggestion(service::search);
|
||||
// TODO 按名称找出,容易出问题
|
||||
setFromString(service::findByName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#
|
||||
# drop table if exists CONTRACT_COST;
|
||||
|
||||
create table if not exists PROJECT_COST
|
||||
(
|
||||
ID int auto_increment
|
||||
primary key,
|
||||
CONTRACT_ID int null comment '合同编号',
|
||||
PROJECT_ID int null comment '项目编号',
|
||||
APPLY_DATE date null comment '申请日期',
|
||||
STANDARD_CONTRACT_TEXT bit default b'0' not null comment '是否是标准合同文本',
|
||||
STANDARD_PAY_WAY bit default b'0' not null comment '是否是标准付款方式',
|
||||
NO_STANDARD_PAY_WAY_TEXT varchar(255) null comment '非标准付款方式文本',
|
||||
NO_STANDARD_CONTRACT_TEXT varchar(255) null comment '非标准合同文本',
|
||||
ON_SITE_POSITION_FEE float default 0 not null comment '现场就位费',
|
||||
ON_SITE_SERVICE_FEE float default 0 not null comment '现场服务费',
|
||||
ASSEMBLY_SERVICE_FEE float default 0 not null comment '装机服务费',
|
||||
TECHNICAL_SERVICE_FEE float default 0 not null comment '技术服务费',
|
||||
BID_SERVICE_FEE float default 0 not null comment '投标服务费',
|
||||
FREIGHT_COST float default 0 not null comment '运费',
|
||||
GUARANTEE_LETTER_FEE float default 0 not null comment '保函费',
|
||||
TAX_AND_SURCHARGES float default 0 not null comment '营业税及附加费',
|
||||
GROSS_PROFIT_MARGIN double default 0 not null comment '毛利率',
|
||||
IN_EXCLUSIVE_TAX_AMOUNT double default 0 not null comment '不含税进项总金额',
|
||||
IN_QUANTITY double default 0 not null comment '进项总数',
|
||||
IN_TAX_AMOUNT double default 0 not null comment '含税进项总金额',
|
||||
OUT_EXCLUSIVE_TAX_AMOUNT double default 0 not null comment '不含税出项总金额',
|
||||
OUT_QUANTITY double default 0 not null comment '出项总数',
|
||||
OUT_TAX_AMOUNT double default 0 not null comment '含税出项总金额',
|
||||
constraint CONTRACT_COST_CONTRACT_ID_fk
|
||||
foreign key (CONTRACT_ID) references CONTRACT (ID),
|
||||
constraint PROJECT_COST_PROJECT_ID_fk
|
||||
foreign key (PROJECT_ID) references PROJECT (ID)
|
||||
|
||||
)
|
||||
comment '项目的成本';
|
||||
|
||||
|
||||
/***
|
||||
转换为项目成本
|
||||
*/
|
||||
|
||||
select A.ID, A.PROJECT_ID,C.ID, P.ID from PROJECT_COST as A left join CONTRACT as C on A.CONTRACT_ID = C.ID left join PROJECT as P on C.PROJECT_ID = P.ID
|
||||
|
||||
|
||||
select pc1_0.ID,pc1_0.APPLICANT_ID,pc1_0.APPLY_DATE,pc1_0.ASSEMBLY_SERVICE_FEE,pc1_0.AUTHORIZER_FILE,pc1_0.AUTHORIZER_DATE,pc1_0.AUTHORIZER_ID,pc1_0.BID_SERVICE_FEE,pc1_0.CONTRACT_ID,pc1_0.DESCRIPTION,pc1_0.FREIGHT_COST,pc1_0.GROSS_PROFIT_MARGIN,pc1_0.GUARANTEE_LETTER_FEE,pc1_0.IMPORT_LOCK,pc1_0.IN_EXCLUSIVE_TAX_AMOUNT,pc1_0.IN_QUANTITY,pc1_0.IN_TAX_AMOUNT,pc1_0.NO_STANDARD_CONTRACT_TEXT,pc1_0.NO_STANDARD_PAY_WAY_TEXT,pc1_0.ON_SITE_SERVICE_FEE,pc1_0.OUT_EXCLUSIVE_TAX_AMOUNT,pc1_0.OUT_QUANTITY,pc1_0.OUT_TAX_AMOUNT,pc1_0.PROJECT_ID,pc1_0.STAMP_TAX,pc1_0.STAMP_TAX_FEE,pc1_0.STANDARD_CONTRACT_TEXT,pc1_0.STANDARD_PAY_WAY,pc1_0.TAX_AND_SURCHARGES,pc1_0.TAX_AND_SURCHARGES_FEE,pc1_0.TECHNICAL_SERVICE_FEE,pc1_0.VER
|
||||
from PROJECT_COST pc1_0 where pc1_0.DESCRIPTION like ? escape '' and pc1_0.PROJECT_ID=274
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE IF NOT EXISTS CONTRACT_COST_ITEM
|
||||
(
|
||||
ID INT AUTO_INCREMENT NOT NULL,
|
||||
COST_ID INT NULL comment '合同成本id',
|
||||
TITLE VARCHAR(255) NULL comment '名称',
|
||||
SPECIFICATION VARCHAR(255) NULL comment '规格',
|
||||
UNIT VARCHAR(255) NULL comment '单位',
|
||||
IN_EX_TAX_PRICE double default 0 not null comment '不含税进项单价',
|
||||
IN_TAX_RATE double default 0 not null comment '进项税率',
|
||||
IN_TAX_PRICE double default 0 not null comment '不含税进项总价',
|
||||
IN_QUANTITY double default 0 not null comment '进项数量',
|
||||
OUT_EX_TAX_PRICE double default 0 not null comment '不含税出项单价',
|
||||
OUT_TAX_RATE double default 0 not null comment '出项税率',
|
||||
OUT_TAX_PRICE double default 0 not null comment '不含税出项总价',
|
||||
OUT_QUANTITY double default 0 not null comment '出项数量',
|
||||
REMARK VARCHAR(255) NULL comment '备注',
|
||||
CREATE_TIME DATETIME NULL comment '创建时间',
|
||||
CREATE_BY INT NULL comment '创建人',
|
||||
UPDATE_TIME DATETIME NULL comment '更新时间',
|
||||
UPDATE_BY INT NULL comment '更新人',
|
||||
CONSTRAINT pk_contract_cost_item PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
ALTER TABLE PROJECT_COST_ITEM
|
||||
ADD CONSTRAINT FK_CONTRACT_COST_ITEM_ON_COST FOREIGN KEY (COST_ID) REFERENCES PROJECT_COST (ID);
|
||||
|
||||
ALTER TABLE PROJECT_COST_ITEM
|
||||
ADD CONSTRAINT FK_CONTRACT_COST_ITEM_ON_CREATE_BY FOREIGN KEY (CREATE_BY) REFERENCES EMPLOYEE (ID);
|
||||
|
||||
ALTER TABLE PROJECT_COST_ITEM
|
||||
ADD CONSTRAINT FK_CONTRACT_COST_ITEM_ON_UPDATE_BY FOREIGN KEY (UPDATE_BY) REFERENCES EMPLOYEE (ID);
|
||||
@@ -0,0 +1,76 @@
|
||||
create table SALES_BILL_VOUCHER
|
||||
(
|
||||
ID int auto_increment
|
||||
primary key,
|
||||
CODE varchar(255) null,
|
||||
DESCRIPTION text null,
|
||||
EMPLOYEE_ID int null,
|
||||
MAKER_ID int null,
|
||||
MAKER_DATE datetime null,
|
||||
VERIFIER_ID int null,
|
||||
MODIFY_DATE datetime null,
|
||||
VERIFIER_DATE datetime null,
|
||||
REF_ID int default 0 not null,
|
||||
COMPANY_ID int null,
|
||||
constraint SALES_BILL_VOUCHER_COMPANY_ID_fk
|
||||
foreign key (COMPANY_ID) references COMPANY (ID)
|
||||
on delete set null,
|
||||
constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk
|
||||
foreign key (MAKER_ID) references EMPLOYEE (ID)
|
||||
on delete set null,
|
||||
constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk_2
|
||||
foreign key (VERIFIER_ID) references EMPLOYEE (ID)
|
||||
on delete set null,
|
||||
constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk_3
|
||||
foreign key (EMPLOYEE_ID) references EMPLOYEE (ID)
|
||||
on delete set null
|
||||
);
|
||||
|
||||
create table SALES_BILL_VOUCHER_ITEM
|
||||
(
|
||||
ID int auto_increment
|
||||
primary key,
|
||||
REF_ID int default 0 not null,
|
||||
VOUCHER_ID int null,
|
||||
INVENTORY_ID int null,
|
||||
DESCRIPTION text null,
|
||||
QUANTITY double default 0 not null,
|
||||
PRICE double default 0 not null,
|
||||
constraint SALES_BILL_VOUCHER_ITEM_INVENTORY_ID_fk
|
||||
foreign key (INVENTORY_ID) references INVENTORY (ID)
|
||||
on delete set null,
|
||||
constraint SALES_BILL_VOUCHER_ITEM_SALES_BILL_VOUCHER_ID_fk
|
||||
foreign key (VOUCHER_ID) references SALES_BILL_VOUCHER (ID)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
* 获取采购单的采购单
|
||||
*/
|
||||
select V.*
|
||||
from PURCHASE_BILL_VOUCHER as V
|
||||
join (select distinct VI.VOUCHER_ID
|
||||
from PURCHASE_BILL_VOUCHER_ITEM as VI
|
||||
left join PURCHASE_ORDER_ITEM as OI on VI.PURCHASE_ORDER_ITEM_ID = OI.ID
|
||||
where ORDER_ID = 159) as U on V.ID = U.VOUCHER_ID;
|
||||
/**
|
||||
* 获取采购单的采购单
|
||||
*/
|
||||
select pbv1_0.ID,
|
||||
pbv1_0.CODE,
|
||||
pbv1_0.COMPANY_ID,
|
||||
pbv1_0.DESCRIPTION,
|
||||
pbv1_0.EMPLOYEE_ID,
|
||||
pbv1_0.INVOICE_ID,
|
||||
pbv1_0.MAKER_ID,
|
||||
pbv1_0.MAKER_DATE,
|
||||
pbv1_0.MODIFY_DATE,
|
||||
pbv1_0.REF_ID,
|
||||
pbv1_0.VERIFIER_ID,
|
||||
pbv1_0.VERIFIER_DATE
|
||||
from PURCHASE_BILL_VOUCHER pbv1_0
|
||||
where pbv1_0.ID in ((select distinct pbvi1_0.VOUCHER_ID
|
||||
from PURCHASE_BILL_VOUCHER_ITEM pbvi1_0
|
||||
left join PURCHASE_ORDER_ITEM oi1_0 on oi1_0.ID = pbvi1_0.PURCHASE_ORDER_ITEM_ID
|
||||
where oi1_0.ORDER_ID = ?));
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.model.ContractBidVendor;
|
||||
|
||||
@Repository
|
||||
public interface ContractBidVendorRepository extends
|
||||
// JDBC interfaces
|
||||
CrudRepository<ContractBidVendor, Integer>, PagingAndSortingRepository<ContractBidVendor, Integer>,
|
||||
// JPA interfaces
|
||||
JpaRepository<ContractBidVendor, Integer>, JpaSpecificationExecutor<ContractBidVendor> {
|
||||
|
||||
List<ContractBidVendor> findByContractId(Integer contractId);
|
||||
|
||||
List<ContractBidVendor> findByContractIdAndCompanyId(Integer contractId, Integer companyId);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.ContractCatalog;
|
||||
|
||||
@Repository
|
||||
public interface ContractCatalogRepository extends MyRepository<ContractCatalog, Integer> {
|
||||
|
||||
Optional<ContractCatalog> findByCode(String code);
|
||||
|
||||
Optional<ContractCatalog> findByName(String name);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ContractFileType;
|
||||
import com.ecep.contract.model.Contract;
|
||||
import com.ecep.contract.model.ContractFile;
|
||||
|
||||
@Repository
|
||||
public interface ContractFileRepository extends JpaRepository<ContractFile, Integer>, JpaSpecificationExecutor<ContractFile> {
|
||||
List<ContractFile> findByContract(Contract contract);
|
||||
|
||||
List<ContractFile> findAllByContract(Contract contract);
|
||||
|
||||
List<ContractFile> findAllByContractAndType(Contract contract, ContractFileType type);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ContractFileType;
|
||||
import com.ecep.contract.ds.other.repository.BaseEnumEntityRepository;
|
||||
import com.ecep.contract.model.ContractFileTypeLocal;
|
||||
|
||||
@Repository
|
||||
public interface ContractFileTypeLocalRepository
|
||||
extends BaseEnumEntityRepository<ContractFileType, ContractFileTypeLocal, Integer> {
|
||||
@Override
|
||||
default ContractFileType[] getEnumConstants() {
|
||||
return ContractFileType.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
default ContractFileTypeLocal newEntity() {
|
||||
return new ContractFileTypeLocal();
|
||||
}
|
||||
|
||||
ContractFileTypeLocal findByTypeAndLang(ContractFileType type, String lang);
|
||||
|
||||
default ContractFileTypeLocal getCompleteByTypeAndLang(ContractFileType type, String lang) {
|
||||
ContractFileTypeLocal v = findByTypeAndLang(type, lang);
|
||||
if (v == null) {
|
||||
v = newEntity();
|
||||
v.setType(type);
|
||||
v.setLang(lang);
|
||||
v.setValue(type.name());
|
||||
v = save(v);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.ContractGroup;
|
||||
|
||||
@Repository
|
||||
public interface ContractGroupRepository extends MyRepository<ContractGroup, Integer> {
|
||||
|
||||
Optional<ContractGroup> findByCode(String code);
|
||||
|
||||
Optional<ContractGroup> findFirstByNameContains(String name);
|
||||
|
||||
Optional<ContractGroup> findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.model.ContractItem;
|
||||
|
||||
@Repository
|
||||
public interface ContractItemRepository extends JpaRepository<ContractItem, Integer>, JpaSpecificationExecutor<ContractItem> {
|
||||
|
||||
List<ContractItem> findByContractId(int contractId);
|
||||
|
||||
List<ContractItem> findByInventoryId(int inventoryId);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ecep.contract.ds.contract.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.ecep.contract.ds.MyRepository;
|
||||
import com.ecep.contract.model.ContractKind;
|
||||
|
||||
@Repository
|
||||
public interface ContractKindRepository extends MyRepository<ContractKind, Integer> {
|
||||
Optional<ContractKind> findByCode(String code);
|
||||
|
||||
Optional<ContractKind> findByName(String name);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user