Commit ccd54f84 authored by neo's avatar neo

[dev] delete AopSharding databases

parent a8cecf99
package pwc.taxtech.atms.common.datasource;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
@Aspect
public class AopShardingHolder {
private static Logger logger = LoggerFactory.getLogger(AopShardingHolder.class);
private static final String DATABASE_NAME_HEADER = "from";
private static final String DATABASE_NAME_SPLIT = "@";
@Autowired
HttpServletRequest request;
@Pointcut("execution(public * pwc.taxtech.atms.controller.*.*(..))")
public void pointCut() {
// 定义Pointcut 此方法不能有返回值,该方法只是一个标示
}
@Before("pointCut()")
public void before(JoinPoint joinPoint) {
try {
String header = request.getHeader(DATABASE_NAME_HEADER);
if (StringUtils.isNotBlank(header)) {
if (logger.isDebugEnabled()) {
logger.debug("aop set datasource:{}", header);
}
String[] arr = StringUtils.split(header, DATABASE_NAME_SPLIT);
String name = arr[0];
if (name.length() > 0 && !StringUtils.contains(name, DATABASE_NAME_SPLIT)) {
ShardingContextHolder.setDataSourceKey(name);
}
}
} catch (Exception e) {
logger.error("aop set database error.", e);
}
}
@After("pointCut()")
public void after(JoinPoint joinPoint) {
}
@AfterThrowing(pointcut = "pointCut()", throwing = "error")
public void afterThrowing(JoinPoint joinPoint, Throwable error) {
}
}
\ No newline at end of file
package pwc.taxtech.atms.common.datasource;
public class DataSourceConfig {
private String url;
private String username;
private String password;
private Integer clientTimeout;
private Integer threadNum;
private Integer transferFileType;
private boolean renameUploaded;
private Integer retryTimes;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getClientTimeout() {
return clientTimeout;
}
public void setClientTimeout(Integer clientTimeout) {
this.clientTimeout = clientTimeout;
}
public Integer getThreadNum() {
return threadNum;
}
public void setThreadNum(Integer threadNum) {
this.threadNum = threadNum;
}
public Integer getTransferFileType() {
return transferFileType;
}
public void setTransferFileType(Integer transferFileType) {
this.transferFileType = transferFileType;
}
public boolean isRenameUploaded() {
return renameUploaded;
}
public void setRenameUploaded(boolean renameUploaded) {
this.renameUploaded = renameUploaded;
}
public Integer getRetryTimes() {
return retryTimes;
}
public void setRetryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
}
}
package pwc.taxtech.atms.common.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pwc.taxtech.atms.exception.ParameterException;
public class DataSourceFactory implements KeyedPooledObjectFactory<String, DruidDataSource> {
private static final Logger logger = LoggerFactory.getLogger(DataSourceFactory.class);
private DataSourceConfig dataSourceConfig;
private static final String SYMBOL = "demo_db_name";
public DataSourceFactory(DataSourceConfig dataSourceConfig) {
this.dataSourceConfig = dataSourceConfig;
}
@Override
public PooledObject<DruidDataSource> makeObject(String s) throws Exception {
if (StringUtils.isBlank(s)) {
throw new ParameterException("empty database name.");
}
DruidDataSource dynamicDataSource = new DruidDataSource();
String url = StringUtils.replace(dataSourceConfig.getUrl(), SYMBOL, s);
dynamicDataSource.setUrl(url);
dynamicDataSource.setUsername(dataSourceConfig.getUsername());
dynamicDataSource.setPassword(dataSourceConfig.getPassword());
dynamicDataSource.init();
return new DefaultPooledObject<>(dynamicDataSource);
}
@Override
public void destroyObject(String s, PooledObject<DruidDataSource> pooledObject) throws Exception {
pooledObject.getObject().close();
}
@Override
public boolean validateObject(String s, PooledObject<DruidDataSource> pooledObject) {
try {
return pooledObject.getObject().isEnable();
} catch (Exception e) {
logger.error("Failed to validate DruidDataSource: ", e);
}
return false;
}
@Override
public void activateObject(String s, PooledObject<DruidDataSource> pooledObject) throws Exception {
}
@Override
public void passivateObject(String s, PooledObject<DruidDataSource> pooledObject) throws Exception {
}
}
package pwc.taxtech.atms.common.datasource;
public class ShardingContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
/**
* 设置数据库名
*
* @param key key
*/
public static void setDataSourceKey(String key) {
contextHolder.set(key);
}
/**
* 获取数据库名
*
* @return key
*/
public static String getDataSourceKey() {
return contextHolder.get();
}
}
package pwc.taxtech.atms.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.common.util.NPOIHelper;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.BalanceSubTotalDto;
import pwc.taxtech.atms.dto.vatdto.BalanceWithSubTotalsResultDto;
import pwc.taxtech.atms.dto.vatdto.ClearTableDto;
import pwc.taxtech.atms.dto.vatdto.ImportBalanceDto;
import pwc.taxtech.atms.dto.vatdto.JsonParentCodesLookup;
import pwc.taxtech.atms.dto.vatdto.JsonTrialBalanceTreeNode;
import pwc.taxtech.atms.dto.vatdto.TrialBalanceFilter;
import pwc.taxtech.atms.dto.vatdto.VatEnterpriseAccountDto;
import pwc.taxtech.atms.service.ICitTBDataImportService;
import pwc.taxtech.atms.service.IdentityService;
import pwc.taxtech.atms.service.impl.DataImportServiceImpl;
import pwc.taxtech.atms.vat.dao.DataImportModel;
import pwc.taxtech.atms.vat.dpo.TrialBalanceDto;
import pwc.taxtech.atms.vat.service.TBDataImportService;
import pwc.taxtech.atms.vat.service.impl.FileUploadAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static pwc.taxtech.atms.constant.Constant.DEFAULT_HAS_HEADER;
import static pwc.taxtech.atms.constant.Constant.HEADER_ROW_INDEX;
@RequestMapping(value = "api/v1/DataImport")
@RestController
public class TBDataImportController {
private static Logger LOGGER = LoggerFactory.getLogger(TBDataImportController.class);
@Autowired
TBDataImportService tbDataImportService;
static final String CIT_CATEGORY = "CIT";
static final String STANDARD_CATEGORY = "STD";
@Autowired
private ICitTBDataImportService citTbDataImport;
@Autowired
private DataImportServiceImpl dataImportService;
@Autowired
private IdentityService identityService;
@Autowired
private FileUploadAdapter fileUploadAdapter;
@RequestMapping(value = "GetBalanceDataForDisplay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @ResponseBody
String getBalanceDataForDisplay(@RequestBody JSONObject param) {
String category = param.get("category").toString();
int fromPeriod = Integer.parseInt(param.get("fromPeriod").toString());
int toPeriod = Integer.parseInt(param.get("toPeriod").toString());
String criteria = param.get("criteria").toString();
TrialBalanceFilter filter = new TrialBalanceFilter();
if (StringUtils.isNotBlank(criteria) && !"null".equals(criteria)) {
JSONObject jsonObject = new JSONObject();
filter = jsonObject.getObject(criteria, TrialBalanceFilter.class);
} else {
filter = null;
}
return convertBalanceDataToUiGridTree(fromPeriod, toPeriod, filter, category);
}
private String convertBalanceDataToUiGridTree(int fromPeriod, int toPeriod, TrialBalanceFilter filter, String category) {
String result = "";
List<TrialBalanceDto> balanceList = new ArrayList<>();
if (category.equals(CIT_CATEGORY)) {
balanceList = tbDataImportService.getTrialBalanceData(fromPeriod, toPeriod);
} else {
balanceList = tbDataImportService.getTrialBalanceStdData(fromPeriod, toPeriod);
}
if (filter != null && !balanceList.isEmpty()) {
balanceList = filterTrialBalanceList(filter, balanceList);
}
if (!balanceList.isEmpty()) {
balanceList = balanceList.stream().sorted(Comparator.comparing(TrialBalanceDto::getAcctCode).thenComparing(TrialBalanceDto::getAccotCodeLength)).collect(Collectors.toList());
}
BigDecimal subTotalBegCreditBal = BigDecimal.ZERO;
BigDecimal subTotalBegDebitBal = BigDecimal.ZERO;
BigDecimal subTotalEndCreditBal = BigDecimal.ZERO;
BigDecimal subTotalEndDebitBal = BigDecimal.ZERO;
BigDecimal subTotalCreditBal = BigDecimal.ZERO;
BigDecimal subTotalDebitBal = BigDecimal.ZERO;
List<TrialBalanceDto> subTotalList = new ArrayList<>(balanceList);
boolean isFilterEmpty = true;
if (filter != null &&
(StringUtils.isNotBlank(filter.getAccountCode())
|| StringUtils.isNotBlank(filter.getAccountName())
|| filter.getAccumulatedCreditAmountFrom() != null
|| filter.getAccumulatedCreditAmountTo() != null
|| filter.getAccumulatedDebitAmountFrom() != null
|| filter.getAccumulatedDebitAmountTo() != null
|| filter.getCreditClosingBalanceFrom() != null
|| filter.getCreditClosingBalanceTo() != null
|| filter.getCreditOpeningBalanceFrom() != null
|| filter.getCreditOpeningBalanceTo() != null
|| filter.getDebitClosingBalanceFrom() != null
|| filter.getDebitClosingBalanceTo() != null
|| filter.getDebitOpeningBalanceFrom() != null
|| filter.getDebitOpeningBalanceTo() != null
|| filter.getDebitClosingBalanceFrom() != null)) {
isFilterEmpty = false;
List<String> primaryList = subTotalList.stream().filter(x -> "0".equals(x.getParentCode())).map(TrialBalanceDto::getAcctCode).collect(Collectors.toList());
if (!primaryList.isEmpty()) {
for (String parent : primaryList) {
int parentSize = parent.length();
subTotalList.removeAll(
subTotalList.stream().filter(x -> x.getAcctCode().length() != parentSize
&& x.getAcctCode().length() >= parentSize
&& x.getAcctCode().substring(0, parentSize).equals(parent)).collect(Collectors.toList()));
}
if (!subTotalList.isEmpty()) {
subTotalBegCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getBegCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalBegDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getBegDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getEndCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getEndDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getDebitBal()).doubleValue()).summaryStatistics().getSum());
}
} else {
subTotalBegCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getBegCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalBegDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getBegDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getEndCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getEndDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalCreditBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalDebitBal = BigDecimal.valueOf(subTotalList.stream().mapToDouble(y -> Objects.requireNonNull(y.getDebitBal()).doubleValue()).summaryStatistics().getSum());
}
} else {
isFilterEmpty = true;
subTotalBegCreditBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getBegCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalBegDebitBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getBegDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndCreditBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getEndCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalEndDebitBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getEndDebitBal()).doubleValue()).summaryStatistics().getSum());
subTotalCreditBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getCreditBal()).doubleValue()).summaryStatistics().getSum());
subTotalDebitBal = BigDecimal.valueOf(subTotalList.stream().filter(x -> "0".equals(x.getParentCode()))
.mapToDouble(y -> Objects.requireNonNull(y.getDebitBal()).doubleValue()).summaryStatistics().getSum());
}
//todo: add the code below here
List<JsonTrialBalanceTreeNode> tree = new ArrayList<>();
List<JsonTrialBalanceTreeNode> balanceTree = new ArrayList<>();
JsonTrialBalanceTreeNode note;
for (TrialBalanceDto item : balanceList) {
note = new JsonTrialBalanceTreeNode();
note.setAcctCode(item.getAcctCode());
note.setAccountName(item.getAccountName());
note.setBalanceId(item.getBalanceId());
note.setBegCreditBal(Objects.requireNonNull(item.getBegCreditBal()).toString());
note.setBegDebitBal(Objects.requireNonNull(item.getBegDebitBal()).toString());
note.setEndCreditBal(Objects.requireNonNull(item.getEndCreditBal()).toString());
note.setEndDebitBal(Objects.requireNonNull(item.getEndDebitBal()).toString());
note.setParentCode(item.getParentCode());
note.setCreditBal(Objects.requireNonNull(item.getCreditBal()).toString());
note.setDebitBal(Objects.requireNonNull(item.getDebitBal()).toString());
note.setAcctProp(item.getAcctProp() != null ? item.getAcctProp().toString() : "7"); // 7 means "Other" category
note.setDirection(Integer.toString(item.getDirection()));
balanceTree.add(note);
}
BalanceWithSubTotalsResultDto<JsonTrialBalanceTreeNode> balanceWithSubTotalsInfo = new BalanceWithSubTotalsResultDto<>();
BalanceSubTotalDto subtotalsInfo = new BalanceSubTotalDto();
subtotalsInfo.setBegCreditBal(subTotalBegCreditBal.toString());
subtotalsInfo.setBegDebitBal(subTotalBegDebitBal.toString());
subtotalsInfo.setEndCreditBal(subTotalEndCreditBal.toString());
subtotalsInfo.setEndDebitBal(subTotalEndDebitBal.toString());
subtotalsInfo.setCreditBal(subTotalCreditBal.toString());
subtotalsInfo.setDebitBal(subTotalDebitBal.toString());
if (isFilterEmpty) {
initTree(tree, "0", balanceTree);
} else {
JsonTrialBalanceTreeNode tempNode;
if (!balanceTree.isEmpty()) {
for (JsonTrialBalanceTreeNode row : balanceTree) {
tempNode = new JsonTrialBalanceTreeNode();
CommonUtils.copyProperties(row, tempNode);
tempNode.setAccountName(StringUtils.removeStart(row.getAccountName(), "@"));
tempNode.setChildren(new ArrayList<>());
tree.add(tempNode);
}
}
}
balanceWithSubTotalsInfo.setList(tree.stream()
.sorted(Comparator.comparing(JsonTrialBalanceTreeNode::getAcctCode)
.thenComparing(JsonTrialBalanceTreeNode::getAcctCodeLength))
.collect(Collectors.toList()));
balanceWithSubTotalsInfo.setSubTotals(subtotalsInfo);
result = JSONObject.toJSONString(balanceWithSubTotalsInfo);
return result;
}
private void initTree(List<JsonTrialBalanceTreeNode> nodes, String parentCode, List<JsonTrialBalanceTreeNode> sources) {
JsonTrialBalanceTreeNode tempNode;
//递归寻找子节点
if (sources != null && !sources.isEmpty() && !StringUtils.isEmpty(parentCode)) {
List<JsonTrialBalanceTreeNode> tempTree = sources.stream().filter(item -> parentCode.equals(item.getParentCode())).collect(Collectors.toList());
for (JsonTrialBalanceTreeNode row : tempTree) {
tempNode = new JsonTrialBalanceTreeNode();
CommonUtils.copyProperties(row, tempNode);
tempNode.setChildren(new ArrayList<>());
nodes.add(tempNode);
initTree(tempNode.getChildren(), row.getAcctCode(), sources);
}
}
}
private static List<TrialBalanceDto> filterTrialBalanceList(TrialBalanceFilter filter, List<TrialBalanceDto> balanceList) {
// Account Code: support multiple codes seperated by space:
if (StringUtils.isNotBlank(filter.getAccountCode())) {
List<String> codes = new ArrayList<>(Arrays.asList(filter.getAccountCode().split(" ")));
balanceList = balanceList.stream().filter(x -> codes.contains(x.getAcctCode())).collect(Collectors.toList());
}
// Account Name: support multiple codes seperated by space:
if (StringUtils.isNotBlank(filter.getAccountName())) {
List<String> names = new ArrayList<>(Arrays.asList(filter.getAccountName().split(" ")));
List<TrialBalanceDto> ds = new ArrayList<>();
for (String name : names) {
ds.addAll(balanceList.stream().filter(x -> x.getAccountName().contains(name)).collect(Collectors.toList()));
}
balanceList = ds;
}
// Debit Opening Balance:
if (filter.getDebitOpeningBalanceFrom() != null || filter.getDebitOpeningBalanceTo() != null) {
if (filter.getDebitOpeningBalanceFrom() != null && filter.getDebitOpeningBalanceTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getDebitOpeningBalanceFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getDebitOpeningBalanceTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getDebitOpeningBalanceFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getDebitOpeningBalanceFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getDebitOpeningBalanceTo().doubleValue())
.collect(Collectors.toList());
}
}
// Credit Opening Balance:
if (filter.getCreditOpeningBalanceFrom() != null || filter.getCreditOpeningBalanceTo() != null) {
if (filter.getCreditOpeningBalanceFrom() != null && filter.getCreditOpeningBalanceTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getCreditOpeningBalanceFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getCreditOpeningBalanceTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getCreditOpeningBalanceFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getCreditOpeningBalanceFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getCreditOpeningBalanceTo().doubleValue())
.collect(Collectors.toList());
}
}
// Accumulated Debit Balance:
if (filter.getAccumulatedDebitAmountFrom() != null || filter.getAccumulatedDebitAmountTo() != null) {
if (filter.getAccumulatedDebitAmountFrom() != null && filter.getAccumulatedDebitAmountTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getAccumulatedDebitAmountFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getAccumulatedDebitAmountTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getAccumulatedDebitAmountFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getAccumulatedDebitAmountFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getAccumulatedDebitAmountTo().doubleValue())
.collect(Collectors.toList());
}
}
// Accumulated Credit Balance:
if (filter.getAccumulatedCreditAmountFrom() != null || filter.getAccumulatedCreditAmountTo() != null) {
if (filter.getAccumulatedCreditAmountFrom() != null && filter.getAccumulatedCreditAmountTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getAccumulatedCreditAmountFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getAccumulatedCreditAmountTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getAccumulatedCreditAmountFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getAccumulatedCreditAmountFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getAccumulatedCreditAmountTo().doubleValue())
.collect(Collectors.toList());
}
}
// Closing Debit Balance:
if (filter.getDebitClosingBalanceFrom() != null || filter.getDebitClosingBalanceTo() != null) {
if (filter.getDebitClosingBalanceFrom() != null && filter.getDebitClosingBalanceTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getDebitClosingBalanceFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getDebitClosingBalanceTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getDebitClosingBalanceFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getAccumulatedCreditAmountFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getDebitClosingBalanceTo().doubleValue())
.collect(Collectors.toList());
}
}
// Closing Credit Balance:
if (filter.getCreditClosingBalanceFrom() != null || filter.getCreditClosingBalanceTo() != null) {
if (filter.getCreditClosingBalanceFrom() != null && filter.getCreditClosingBalanceTo() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getCreditClosingBalanceFrom().doubleValue()
&& x.getBegDebitBal().doubleValue() <= filter.getCreditClosingBalanceTo().doubleValue())
.collect(Collectors.toList());
} else if (filter.getDebitClosingBalanceFrom() != null) {
balanceList = balanceList.stream()
.filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() >= filter.getCreditClosingBalanceFrom().doubleValue())
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream().filter(x -> x.getBegDebitBal() != null
&& x.getBegDebitBal().doubleValue() <= filter.getCreditClosingBalanceTo().doubleValue())
.collect(Collectors.toList());
}
}
assert filter.isHideAllZeroRecords() != null;
if (filter.isHideAllZeroRecords()) {
balanceList = balanceList.stream()
.filter(x -> ((x.getBegCreditBal() != null && x.getBegCreditBal().doubleValue() != 0)
|| (x.getEndDebitBal() != null && x.getEndDebitBal().doubleValue() != 0)
|| (x.getBegDebitBal() != null && x.getBegDebitBal().doubleValue() != 0)
|| (x.getEndDebitBal() != null && x.getEndDebitBal().doubleValue() != 0)
|| (x.getCreditBal() != null && x.getCreditBal().doubleValue() != 0)
|| (x.getDebitBal() != null && x.getDebitBal().doubleValue() != 0)))
.collect(Collectors.toList());
}
return balanceList;
}
@ApiOperation(value = "clearTableByPeriods", notes = "")
@RequestMapping(value = "clearTableByPeriods", method = RequestMethod.POST)
public OperationResultDto<Boolean> clearTableByPeriods(@RequestBody ClearTableDto clearTb) {
return citTbDataImport.clearTableByPeriods(clearTb.getPeriods());
}
@ApiOperation(value = "ImportBalance", notes = "")
@RequestMapping(value = "ImportBalance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity importBalanceList(@RequestBody ImportBalanceDto importDto) {
OperationResultDto result = dataImportService.importTrialBalance(importDto.getBalanceList(), importDto.getImportType(),
importDto.getServiceTypeId(),
identityService.getIdentityUser().getId()
);
LOGGER.info("import balance result {}", JSON.toJSONString(result));
return ResponseEntity.ok(result);
}
@RequestMapping(value = "GetParentCodesForDisplay", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @ResponseBody
String GetParentCodesForDisplay(String category) {
return convertParentCodeListToUiGridTree(category);
}
private String convertParentCodeListToUiGridTree(String category) {
String result = "";
List<VatEnterpriseAccountDto> parentCodesList = null;
if (category.equals(CIT_CATEGORY)) {
parentCodesList = tbDataImportService.getEnterpriseAccount();
} else if (category.equals(STANDARD_CATEGORY)) {
parentCodesList = tbDataImportService.getStandardAccount();
}
List<JsonParentCodesLookup> tree = new ArrayList<>();
List<JsonParentCodesLookup> balanceTree = new ArrayList<>();
parentCodesList.forEach(a -> {
JsonParentCodesLookup note;
note = new JsonParentCodesLookup();
note.setAcctCode(a.getAcctCode());
note.setAccountName(a.getName());
note.setParentCode(StringUtils.isBlank(a.getParentCode()) ? "0" : a.getParentCode());
note.setAcctProp(a.getAcctProp() != null ? a.getAcctProp().toString() : "7");
note.setDirection(Integer.toString(a.getDirection()));
balanceTree.add(note);
});
initParentCodeTree(tree, "0", balanceTree);
tree = tree.stream().sorted(Comparator.comparing(JsonParentCodesLookup::getAcctCode).thenComparing(JsonParentCodesLookup::getAcctCodeLength)).collect(Collectors.toList());
result = JSONObject.toJSONString(tree);
return result;
}
private void initParentCodeTree(List<JsonParentCodesLookup> nodes, String parentCode, List<JsonParentCodesLookup> sources) {
JsonParentCodesLookup tempNode;
List<JsonParentCodesLookup> tempTree = sources.stream().filter(a -> a.getParentCode().equals(parentCode)).collect(Collectors.toList());
for (JsonParentCodesLookup jsonParentCodesLookup : tempTree) {
tempNode = new JsonParentCodesLookup();
tempNode.setAcctCode(jsonParentCodesLookup.getAcctCode());
tempNode.setAccountName(jsonParentCodesLookup.getAccountName());
tempNode.setParentCode(jsonParentCodesLookup.getParentCode());
tempNode.setAcctProp(jsonParentCodesLookup.getAcctProp());
tempNode.setDirection(jsonParentCodesLookup.getDirection());
tempNode.setChildren(new ArrayList<>());
nodes.add(tempNode);
initParentCodeTree(tempNode.getChildren(), jsonParentCodesLookup.getAcctCode(), sources);
}
}
@ApiOperation(value = "getFileContent", notes = "")
@RequestMapping(value = "FileContent/{tempFileName}/{selectedSheetIndex}/{topRowNumber}", method = RequestMethod.GET)
public ResponseEntity getFileContent(@PathVariable String tempFileName, @PathVariable Integer selectedSheetIndex,
@PathVariable Integer topRowNumber) {
DataImportModel dataImportModel;
String fullFilePath = fileUploadAdapter.getLastFilePathByFileName(tempFileName);
if (fullFilePath != null) {
try (FileInputStream fis = new FileInputStream(new File(fullFilePath));) {
dataImportModel = NPOIHelper.renderTBDataTableFromExcel(fis, selectedSheetIndex, HEADER_ROW_INDEX,
DEFAULT_HAS_HEADER, topRowNumber);
dataImportModel.setSelectedSheetIndex(selectedSheetIndex);
return ResponseEntity.ok(dataImportModel);
} catch (FileNotFoundException e) {//TODO: replace exception filter (neo)
e.printStackTrace();
return ResponseEntity.status(SC_INTERNAL_SERVER_ERROR).build();
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(SC_INTERNAL_SERVER_ERROR).build();
}
} else {
return ResponseEntity.ok().build();
}
}
}
......@@ -5,6 +5,6 @@ public class Exceptions {
public static final FormulaException BB_REPORT_NULL = new FormulaException("cell report is null");
public static final FormulaException BB_CELL_DATA_NULL = new FormulaException("cell data is null");
public static final FormulaException BB_CELL_DATA_EMPTY = new FormulaException("cell data is empty");
public static final FormulaException BB_EMPTY = new FormulaException("db name is empty");
public static final FormulaException PROJECT_EMPTY = new FormulaException("project is empty");
public static final FormulaException BAD_BBVO_PARAMS = new FormulaException("bad params for bb fromular express data");
}
package pwc.taxtech.atms.service;
import pwc.taxtech.atms.dto.OperationResultDto;
import java.util.List;
public interface ICitTBDataImportService {
OperationResultDto<Boolean> clearTableByPeriods(List<Integer> periods);
}
package pwc.taxtech.atms.service.impl;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.constant.enums.EnumServiceType;
import pwc.taxtech.atms.constant.enums.EnumTbImportType;
import pwc.taxtech.atms.constant.enums.EnumValidationType;
import pwc.taxtech.atms.constant.enums.ServiceType;
import pwc.taxtech.atms.constant.enums.VatImportType;
import pwc.taxtech.atms.vat.dao.DataImportMapper;
import pwc.taxtech.atms.dao.EnterpriseAccountMapper;
import pwc.taxtech.atms.dao.ProjectMapper;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.taxadmin.DataImportedStatusDto;
import pwc.taxtech.atms.dto.vatdto.BalanceAccountDto;
import pwc.taxtech.atms.entity.EnterpriseAccount;
import pwc.taxtech.atms.entity.EnterpriseAccountExample;
import pwc.taxtech.atms.entity.Project;
import pwc.taxtech.atms.entity.ProjectExample;
import pwc.taxtech.atms.vat.dao.BalanceMapper;
import pwc.taxtech.atms.vat.dao.CompanyBalanceMapper;
import pwc.taxtech.atms.vat.dao.ValidationInfoMapper;
import pwc.taxtech.atms.vat.dao.VatEnterpriseAccountMapper;
import pwc.taxtech.atms.vat.dao.DataImportServiceMapper;
import pwc.taxtech.atms.vat.dpo.ImportBalanceCount;
import pwc.taxtech.atms.vat.entity.Balance;
import pwc.taxtech.atms.vat.entity.BalanceExample;
import pwc.taxtech.atms.vat.entity.CompanyBalance;
import pwc.taxtech.atms.vat.entity.CompanyBalanceExample;
import pwc.taxtech.atms.vat.entity.ValidationInfoExample;
import pwc.taxtech.atms.vat.entity.VatEnterpriseAccount;
import pwc.taxtech.atms.vat.entity.VatEnterpriseAccountExample;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class DataImportServiceImpl {
private static final String _companyBalancetable = "CompanyBalance";
private static final String _balancetable = "Balance";
private static final String _validationtable = "ValidationInfo";
private static final int FIRST_OR_DEFAULT = 0;
@Autowired
private DataImportMapper mapper;
@Autowired
private CompanyBalanceMapper companyBalanceMapper;
@Autowired
private ProjectMapper projectMapper;
@Autowired
private EnterpriseAccountMapper enterpriseAccountMapper;
@Autowired
private VatEnterpriseAccountMapper vatEnterpriseAccountMapper;
@Autowired
private ValidationInfoMapper validationInfoMapper;
@Autowired
private DataImportServiceMapper dataImportServiceMapper;
@Autowired
private BalanceMapper balanceMapper;
@Autowired
private SqlSessionTemplate dynamicSqlSessionTemplate;
public OperationResultDto importTrialBalance(List<CompanyBalance> balanceList, Integer importType,
Integer serviceTypeId, String userId) {
try {
OperationResultDto result = new OperationResultDto();
if (serviceTypeId == ServiceType.VAT.getCode().intValue()) {
int period = balanceList.get(0).getPeriodId().intValue();
// DataImportedStatusDto dataImportedStatus = new DataImportedStatusDto();
//
// dataImportedStatus.setPeriod(period);
// dataImportedStatus.setDbName(PROJECT_DB_NAME);
// dataImportedStatus.setDataType(ProjectImportDataType.TrialBalance.getCode());
// dataImportedStatus.setStartTime(new Date());
//覆盖导入之前删除数据
if (importType == EnumTbImportType.CoverImport.getCode()) {
clearTableData(period, _companyBalancetable);
}
balanceList.forEach(m -> companyBalanceMapper.insert(m));
//TODO: sql bulk copy insert tobe impl(neo)
//SynAccountFromTaxAdmin(period, userId);
Boolean isSuccess = refreshTrialBalance(period, serviceTypeId, userId);
result.setResult(isSuccess);
ValidationInfoExample validationInfoExample = new ValidationInfoExample();
validationInfoExample.createCriteria().andImportTypeIdEqualTo(0).andPeriodIdEqualTo(period).andErrorLevelIsNotNull();
Long exceptionCount = validationInfoMapper.countByExample(validationInfoExample);
// dataImportedStatus.setTotalCount(balanceList.size());
// dataImportedStatus.setExceptionCount(exceptionCount.intValue());
// dataImportedStatus.setSuccessedCount(dataImportedStatus.getTotalCount() - dataImportedStatus.getExceptionCount());
// dataImportedStatus.setEndTime(new Date());
// UpdateDataImportedStatu(Lists.newArrayList(dataImportedStatus));
} else if (serviceTypeId == ServiceType.CIT.getCode()) {//TODO import cit (neo)
}
return result;
} catch (Exception e) {
e.printStackTrace();
return new OperationResultDto(false, e.getMessage());
}
}
private String[] UpdateDataImportedStatu(ArrayList<DataImportedStatusDto> dataImportedStatusDtos) {
// todo:[validation] skip update data imported status (neo)
return null;
}
private Boolean refreshTrialBalance(int period, Integer serviceTypeId, String userId) {
CompanyBalanceExample companyBalanceExample = new CompanyBalanceExample();
companyBalanceExample.createCriteria().andPeriodIdEqualTo(period);
List<CompanyBalance> list = companyBalanceMapper.selectByExample(companyBalanceExample);
if (list != null && !list.isEmpty()) {
//同步账套
synAccountFromTaxAdmin(period, userId);
//先删除数据
clearTableData(period, _balancetable);
mapper.deleteTbValidation(period, EnumValidationType.TrialBalance.getCode());
CompanyBalanceExample example = new CompanyBalanceExample();
example.createCriteria().andPeriodIdEqualTo(period);
List<CompanyBalance> companyBalanceList = companyBalanceMapper.selectByExample(example);
// validationAcctCode(period, userId);//todo:[validation] to be open future(neo)
initBalance(companyBalanceList, period, serviceTypeId);
calculateYearColumn();
// duplicatedValidation(period, userId);//todo:[validation] to be open future(neo)
// validationPeriodBal(period, userId);
// validationDebitCreditBalance(period, userId);
// validataionBegDebitAndBegCredit(period, userId);
// upAndDownValidation(period, userId);
//ToDo(add exception msg)
// ValidationInfoExample infoExample=new ValidationInfoExample();
// infoExample.createCriteria().andPeriodIdEqualTo(period).andImportTypeIdEqualTo(EnumValidationType.TrialBalance.getCode());
// List<ValidationInfo> infos =validationInfoMapper.selectByExample(infoExample);
// DictionaryExample dictionaryExample = new DictionaryExample();
// dictionaryExample.createCriteria().andDictKeyEqualTo(DictionaryConstant.WFImportBalanceTable);
}
return true;
}
private void calculateYearColumn() {
Integer maxMonth= dataImportServiceMapper.maxBalancePeriod();
if(maxMonth!=null&&maxMonth.intValue()>0) {
String sql = "update Balance b, (select sum(DebitBal) as sDebitBal, sum(CreditBal) as sCreditBal ,acctcode, 1 as PeriodId from Balance where PeriodId = 1 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal, sum(CreditBal) as sCreditBal ,acctcode, 2 as PeriodId from Balance where PeriodId <= 2 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 3 as PeriodId from Balance where PeriodId <= 3 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 4 as PeriodId from Balance where PeriodId <= 4 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 5 as PeriodId from Balance where PeriodId <= 5 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 6 as PeriodId from Balance where PeriodId <= 6 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 7 as PeriodId from Balance where PeriodId <= 7 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 8 as PeriodId from Balance where PeriodId <= 8 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 9 as PeriodId from Balance where PeriodId <= 9 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 10 as PeriodId from Balance where PeriodId <= 10 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 11 as PeriodId from Balance where PeriodId <= 11 " +
" group by acctcode " +
" union all " +
" select sum(DebitBal) as sDebitBal,sum(CreditBal) as sCreditBal ,acctcode, 12 as PeriodId from Balance where PeriodId <=12 " +
" group by acctcode " +
" ) as tmp " +
" set YearDebitBal = sDebitBal, YearCreditBal = sCreditBal where b.acctcode = tmp.acctcode and b.PeriodId = tmp.PeriodId ;";
exeCommand(sql);
}
}
private void exeCommand(String command) {
try (SqlSession sqlSession = dynamicSqlSessionTemplate.getSqlSessionFactory().openSession();) {
ScriptRunner scriptRunner = new ScriptRunner(sqlSession.getConnection());
scriptRunner.setAutoCommit(true);
scriptRunner.runScript(new StringReader(command));
}
}
private List<Balance> initBalance(List<CompanyBalance> companyBalanceList, int period, Integer serviceTypeId) {
List<Balance> addlist = new ArrayList<>();
List<VatEnterpriseAccount> vats = vatEnterpriseAccountMapper.selectByExample(null);
companyBalanceList.forEach(compbalance -> {
Optional<VatEnterpriseAccount> directionDto = vats.stream().filter(m -> m.getAcctCode().equals(compbalance.getAcctCode()))
.findFirst();
if (directionDto.isPresent()) {
Integer direction = directionDto.get().getDirection();
Balance balanceDto = new Balance();
balanceDto.setBalanceId(UUID.randomUUID().toString());
balanceDto.setPeriodId(compbalance.getPeriodId());
balanceDto.setAcctCode(compbalance.getAcctCode());
balanceDto.setCustomerCode(compbalance.getCustomerCode());
balanceDto.setMonthId(compbalance.getMonthId());
balanceDto.setIsDummy(null);
//1.根据期初余额设置期初借方,期初贷方的值
if (compbalance.getBegBal() != null && compbalance.getEndBal() != null) {
balanceDto.setBegBal(compbalance.getBegBal());
balanceDto.setEndBal(compbalance.getEndBal());
if (direction == 1) {
balanceDto.setBegDebitBal(balanceDto.getBegBal());
balanceDto.setBegCreditBal(new BigDecimal(0));
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setBegCreditBal(balanceDto.getBegBal());
balanceDto.setBegDebitBal(new BigDecimal(0));
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
//判断是否选中了发生额
if (compbalance.getDebitBal() == null && compbalance.getCreditBal() == null) {
if (direction == 1) {
balanceDto.setDebitBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
balanceDto.setCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setDebitBal(new BigDecimal(0));
balanceDto.setCreditBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
}
} else {
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
}
}
//2.期末借方,期末贷方不为空
else if (compbalance.getBegBal() != null && compbalance.getEndDebitBal() != null && compbalance.getEndCreditBal() != null) {
balanceDto.setBegBal(compbalance.getBegBal());
balanceDto.setEndDebitBal(compbalance.getEndDebitBal());
balanceDto.setEndCreditBal(compbalance.getEndCreditBal());
balanceDto.setEndBal((balanceDto.getEndDebitBal().subtract(balanceDto.getEndCreditBal()))
.multiply(new BigDecimal(direction)));
if (direction == 1) {
balanceDto.setBegDebitBal(balanceDto.getBegBal());
balanceDto.setBegCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setBegCreditBal(balanceDto.getBegBal());
balanceDto.setBegDebitBal(new BigDecimal(0));
}
//判断是否选中了发生额
if (compbalance.getDebitBal() == null && compbalance.getCreditBal() == null) {
if (direction == 1) {
balanceDto.setDebitBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
balanceDto.setCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setDebitBal(new BigDecimal(0));
balanceDto.setCreditBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
}
} else {
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
}
}
//3.发生额不为空
else if (compbalance.getBegBal() != null && compbalance.getDebitBal() != null && compbalance.getCreditBal() != null) {
balanceDto.setBegBal(compbalance.getBegBal());
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
if (direction == 1) {
balanceDto.setBegDebitBal(balanceDto.getBegBal());
balanceDto.setBegCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setBegCreditBal(balanceDto.getBegBal());
balanceDto.setBegDebitBal(new BigDecimal(0));
}
if (compbalance.getEndBal() == null && compbalance.getEndDebitBal() == null && compbalance.getEndCreditBal() == null) {
balanceDto.setEndBal((balanceDto.getDebitBal().subtract(balanceDto.getCreditBal()))
.multiply(new BigDecimal(direction)).add(balanceDto.getBegBal()));
if (direction == 1) {
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
} else if (compbalance.getEndBal() != null) {
balanceDto.setEndBal(compbalance.getEndBal());
if (direction == 1) {
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
} else if (compbalance.getEndDebitBal() != null && compbalance.getEndCreditBal() != null) {
balanceDto.setEndDebitBal(compbalance.getEndDebitBal());
balanceDto.setEndCreditBal(compbalance.getEndCreditBal());
balanceDto.setEndBal((balanceDto.getEndDebitBal().subtract(balanceDto.getEndCreditBal())
.multiply(new BigDecimal(direction))));
}
}
//4.根据期初借方,期初贷方的值设置期初余额
else if (compbalance.getBegDebitBal() != null && compbalance.getBegCreditBal() != null && compbalance.getDebitBal() != null && compbalance.getCreditBal() != null) {
balanceDto.setBegDebitBal(compbalance.getBegDebitBal());
balanceDto.setBegCreditBal(compbalance.getBegCreditBal());
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
balanceDto.setBegBal((balanceDto.getBegDebitBal().subtract(balanceDto.getBegCreditBal()))
.multiply(new BigDecimal(direction)));
if (compbalance.getEndBal() == null && compbalance.getEndDebitBal() == null && compbalance.getEndCreditBal() == null) {
balanceDto.setEndBal((balanceDto.getDebitBal().subtract(balanceDto.getCreditBal()))
.multiply(new BigDecimal(direction)).add(balanceDto.getBegBal()));
if (direction == 1) {
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
} else if (compbalance.getEndBal() != null) {
balanceDto.setEndBal(compbalance.getEndBal());
if (direction == 1) {
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
} else if (compbalance.getEndDebitBal() != null && compbalance.getEndCreditBal() != null) {
balanceDto.setEndDebitBal(compbalance.getEndDebitBal());
balanceDto.setEndCreditBal(compbalance.getEndCreditBal());
balanceDto.setEndBal((balanceDto.getEndDebitBal().subtract(balanceDto.getEndCreditBal()))
.multiply(new BigDecimal(direction)));
}
}
//5.根据期初借方,期初贷方的值设置期初余额
else if (compbalance.getBegDebitBal() != null && compbalance.getBegCreditBal() != null && compbalance.getEndDebitBal() != null && compbalance.getEndCreditBal() != null) {
balanceDto.setBegDebitBal(compbalance.getBegDebitBal());
balanceDto.setBegCreditBal(compbalance.getBegCreditBal());
balanceDto.setEndDebitBal(compbalance.getEndDebitBal());
balanceDto.setEndCreditBal(compbalance.getEndCreditBal());
balanceDto.setBegBal((balanceDto.getBegDebitBal().subtract(balanceDto.getBegCreditBal()))
.multiply(new BigDecimal(direction)));
balanceDto.setEndBal((balanceDto.getEndDebitBal().subtract(balanceDto.getEndCreditBal()))
.multiply(new BigDecimal(direction)));
//判断是否选中了发生额
if (compbalance.getDebitBal() == null && compbalance.getCreditBal() == null) {
if (direction == 1) {
balanceDto.setDebitBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
balanceDto.setCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setDebitBal(new BigDecimal(0));
balanceDto.setCreditBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
}
} else {
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
}
}
//6.根据期初借方,期初贷方的值设置期初余额
else if (compbalance.getBegDebitBal() != null && compbalance.getBegCreditBal() != null && compbalance.getEndBal() != null) {
balanceDto.setBegDebitBal(compbalance.getBegDebitBal());
balanceDto.setBegCreditBal(compbalance.getBegCreditBal());
balanceDto.setEndBal(compbalance.getEndBal());
balanceDto.setBegBal((balanceDto.getBegDebitBal().subtract(balanceDto.getBegCreditBal()))
.multiply(new BigDecimal(direction)));
if (direction == 1) {
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
//判断是否选中了发生额
if (compbalance.getDebitBal() == null && compbalance.getCreditBal() == null) {
if (direction == 1) {
balanceDto.setDebitBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
balanceDto.setCreditBal(new BigDecimal(0));
} else if (direction == -1) {
balanceDto.setDebitBal(new BigDecimal(0));
balanceDto.setCreditBal(balanceDto.getEndBal().subtract(balanceDto.getBegBal()));
}
} else {
balanceDto.setDebitBal(compbalance.getDebitBal());
balanceDto.setCreditBal(compbalance.getCreditBal());
}
}
addlist.add(balanceDto);
}
});
if (addlist.size() > 0) {
List<ImportBalanceCount> result = dataImportServiceMapper.resultBalance(period, VatImportType.AuditAdjust.getCode());
result.forEach(v -> {
BigDecimal value = (v.debit.subtract(v.credit)).multiply(new BigDecimal(v.direction));
List<Balance> items = addlist.stream().filter(p -> {
return p.getAcctCode().equals(v.acctCode) || v.acctCode.startsWith(p.getAcctCode());
}).collect(Collectors.toList());
if (items.size() > 0) {
items.forEach(item -> {
if (item != null) {
item.setDebitBal(item.getDebitBal().add(v.debit));
item.setCreditBal(item.getCreditBal().add(v.credit));
if (v.direction == 0) {
item.setEndDebitBal(item.getEndDebitBal().add(value));
} else {
item.setEndCreditBal(item.getEndCreditBal().add(value));
}
item.setEndBal(item.getEndBal().add(value));
}
});
if (!items.stream().anyMatch(p -> p.getAcctCode().equals(v.acctCode))) {
addList(addlist, v.acctCode, period, value, v);
}
} else {
VatEnterpriseAccountExample example = new VatEnterpriseAccountExample();
example.createCriteria().andAcctCodeLike(v.acctCode);
List<VatEnterpriseAccount> accts = vatEnterpriseAccountMapper.selectByExample(example);
if (accts.size() == 0) {
addList(addlist, v.acctCode, period, value, v);
} else {
accts.forEach(acct -> {
addList(addlist, acct.getAcctCode(), period, value, v);
});
if (!accts.stream().anyMatch(p -> p.getAcctCode().equals(v.acctCode))) {
addList(addlist, v.acctCode, period, value, v);
}
}
}
});
//插入账套中有CompanyBalance没有的数据
InsertCodeNotInBalance(addlist, period);
}
//VAT时立即批量插入到balance
if (serviceTypeId == EnumServiceType.VAT.getCode() && !addlist.isEmpty()) {//TODO(buil copy insert)
addlist.forEach(m -> balanceMapper.insert(m));
}
return addlist;
}
//EnterpriseAccount表中有,balance没有的科目,补全balance表科目
private void InsertCodeNotInBalance(List<Balance> addlist, int period) {
VatEnterpriseAccountExample example = new VatEnterpriseAccountExample();
List<String> accCode = new ArrayList<>();
addlist.forEach(m -> accCode.add(m.getAcctCode()));
example.createCriteria().andAcctCodeNotIn(accCode);
List<VatEnterpriseAccount> reult = vatEnterpriseAccountMapper.selectByExample(example);
Set<String> accts = new HashSet<>();
reult.forEach(m -> accts.add(m.getAcctCode()));
accts.forEach(m -> addList(addlist, m, period));
DealCodeNotInBalance(addlist, period);
}
//处理子科目导入,但父科目没导入的情况,需要计算父科目
private void DealCodeNotInBalance(List<Balance> addlist, int period) {
Set<String> acctcodes = new HashSet<>();
for (Balance b : addlist) {
if (b.getPeriodId().intValue() == period) {
acctcodes.add(b.getAcctCode());
}
}
VatEnterpriseAccountExample example = new VatEnterpriseAccountExample();
example.createCriteria().andAcctCodeIn(Lists.newArrayList(acctcodes));
List<VatEnterpriseAccount> result = vatEnterpriseAccountMapper.selectByExample(example);
List<BalanceAccountDto> balanceAddList = new ArrayList<>();
if (result != null && !result.isEmpty()) {
addlist.forEach(c -> {
result.forEach(a -> {
if (c.getAcctCode() == a.getAcctCode() && c.getPeriodId().intValue() == period) {
BalanceAccountDto bad = new BalanceAccountDto();
bad.BalanceId = c.getBalanceId();
bad.PeriodId = c.getPeriodId();
bad.AcctCode = c.getAcctCode();
bad.BegDebitBal = c.getBegDebitBal();
bad.BegCreditBal = c.getBegCreditBal();
bad.DebitBal = c.getDebitBal();
bad.CreditBal = c.getCreditBal();
bad.BegBal = c.getBegBal();
bad.EndBal = c.getEndBal();
bad.EndDebitBal = c.getEndDebitBal();
bad.EndCreditBal = c.getEndCreditBal();
bad.AcctLevel = a.getAcctLevel();
bad.ParentCode = a.getParentCode();
bad.Direction = a.getDirection();
bad.StdCode = a.getStdCode();
bad.IsDummy = c.getIsDummy();
balanceAddList.add(bad);
}
});
});
balanceAddList.stream().sorted(Comparator.comparing(BalanceAccountDto::getAcctCode));
}
//补全的科目数据
List<BalanceAccountDto> balanceInsertList = balanceAddList.stream().filter(m -> m.IsDummy == 0).collect(Collectors.toList());
if (balanceInsertList.size() == 0) {
return;
}
List<BalanceAccountDto> list = balanceInsertList.stream().filter(x -> x.AcctLevel != null).collect(Collectors.toList());
if (list != null && list.size() > 0) {
int maxLevel = balanceInsertList.stream().max(Comparator.comparing(BalanceAccountDto::getAcctLevel)).get().getAcctLevel();
while (maxLevel > 0) {
int finalMaxLevel = maxLevel;
List<BalanceAccountDto> toDealList = balanceInsertList.stream().filter(m -> m.getAcctLevel() == finalMaxLevel).distinct().collect(Collectors.toList());
for (BalanceAccountDto dto : toDealList) {
Balance balanceDto = addlist.stream().filter(x -> x.getBalanceId() == dto.BalanceId).findFirst().get();
BalanceAccountDto addDto = balanceAddList.stream().filter(x -> x.BalanceId == dto.BalanceId).findFirst().get();
//判断在原来CompanyBalance表中有子科目或者孙子科目
List<BalanceAccountDto> oldChildList = balanceAddList.stream().filter(a -> a.AcctCode.startsWith(dto.AcctCode)
&& a.AcctCode != dto.AcctCode && a.IsDummy == null).distinct().collect(Collectors.toList());
//获取所有子节点
List<BalanceAccountDto> childList = balanceAddList.stream().filter(a -> a.ParentCode == dto.AcctCode).distinct().collect(Collectors.toList());
//在原来CompanyBalance表中有子科目或者孙子科目
if (oldChildList != null && oldChildList.size() > 0) {
balanceDto.setIsDummy(1);
addDto.IsDummy = 1;
} else {
balanceDto.setIsDummy(0);
addDto.IsDummy = 0;
}
if (childList != null && childList.size() > 0) {
BigDecimal begBal = new BigDecimal(0);
BigDecimal debitBal = new BigDecimal(0);
BigDecimal crediBal = new BigDecimal(0);
for (BalanceAccountDto bad : childList) {
begBal = begBal.add(bad.BegBal.multiply(new BigDecimal(bad.Direction)).multiply(new BigDecimal(dto.Direction)));
debitBal = debitBal.add(bad.DebitBal);
crediBal = crediBal.add(bad.CreditBal);
}
balanceDto.setBegBal(begBal);
balanceDto.setDebitBal(debitBal);
balanceDto.setCreditBal(crediBal);
balanceDto.setEndBal(balanceDto.getEndBal().add(balanceDto.getDebitBal().subtract(balanceDto.getCreditBal())).multiply(new BigDecimal(dto.Direction)));
if (dto.Direction == 1) {
balanceDto.setBegDebitBal(balanceDto.getBegBal());
balanceDto.setBegCreditBal(new BigDecimal(0));
balanceDto.setEndDebitBal(balanceDto.getEndBal());
balanceDto.setEndCreditBal(new BigDecimal(0));
} else {
balanceDto.setBegDebitBal(new BigDecimal(0));
balanceDto.setBegCreditBal(balanceDto.getBegBal());
balanceDto.setEndDebitBal(new BigDecimal(0));
balanceDto.setEndCreditBal(balanceDto.getEndBal());
}
//修改关联列表值
addDto.BegBal = balanceDto.getBegBal();
addDto.DebitBal = balanceDto.getDebitBal();
addDto.CreditBal = balanceDto.getCreditBal();
addDto.EndBal = balanceDto.getEndBal();
addDto.BegDebitBal = balanceDto.getBegDebitBal();
addDto.BegCreditBal = balanceDto.getBegCreditBal();
addDto.EndDebitBal = balanceDto.getEndDebitBal();
addDto.EndCreditBal = balanceDto.getEndCreditBal();
}
}
maxLevel--;
}
}
AddNextPeriodData(addlist, period);
}
private void AddNextPeriodData(List<Balance> addlist, int period) {
if (period < 12) {
for (int i = period + 1; i <= 12; i++) {
//判断是否已经导入过数据
CompanyBalanceExample example = new CompanyBalanceExample();
example.createCriteria().andPeriodIdEqualTo(i);
List<CompanyBalance> companylist = companyBalanceMapper.selectByExample(example);
if (companylist != null && companylist.size() > 0) {
break;
} else {
int finalI1 = i;
List<Balance> periodList = addlist.stream().filter(x -> x.getPeriodId() == (finalI1 - 1)).collect(Collectors.toList());
int finalI = i;
periodList.forEach(dto -> {
Balance balance = new Balance();
balance.setBalanceId(UUID.randomUUID().toString());
balance.setPeriodId(finalI);
balance.setAcctCode(dto.getAcctCode());
balance.setCustomerCode(dto.getCustomerCode());
balance.setBegDebitBal(dto.getEndDebitBal());
balance.setBegCreditBal(dto.getEndCreditBal());
balance.setBegBal(dto.getEndBal());
balance.setEndBal(dto.getEndBal());
balance.setEndDebitBal(dto.getEndDebitBal());
balance.setEndCreditBal(dto.getEndCreditBal());
balance.setDebitBal(new BigDecimal(0));
balance.setCreditBal(new BigDecimal(0));
balance.setMonthId(finalI);
balance.setIsDummy(null);
;
addlist.add(balance);
});
//删除该月的balance表数据
BalanceExample example1 = new BalanceExample();
example1.createCriteria().andPeriodIdEqualTo(i);
balanceMapper.deleteByExample(example1);
}
}
}
}
private void addList(List<Balance> addlist, String acctCode, int period, BigDecimal value, ImportBalanceCount v) {
Balance balance = new Balance();
balance.setBalanceId(UUID.randomUUID().toString());
balance.setPeriodId(period);
balance.setAcctCode(acctCode);
balance.setBegDebitBal(new BigDecimal(0));
balance.setBegCreditBal(new BigDecimal(0));
balance.setBegBal(new BigDecimal(0));
balance.setDebitBal(v.debit);
balance.setCreditBal(v.credit);
balance.setEndDebitBal(v.direction == 0 ? value : new BigDecimal(0));
balance.setEndCreditBal(v.direction == 0 ? new BigDecimal(0) : value);
balance.setEndBal(value);
addlist.add(balance);
}
private void addList(List<Balance> addlist, String acctCode, int period) {
Balance balance = new Balance();
balance.setBalanceId(UUID.randomUUID().toString());
balance.setPeriodId(period);
balance.setAcctCode(acctCode);
balance.setBegDebitBal(new BigDecimal(0));
balance.setBegCreditBal(new BigDecimal(0));
balance.setBegBal(new BigDecimal(0));
balance.setDebitBal(new BigDecimal(0));
balance.setCreditBal(new BigDecimal(0));
balance.setEndDebitBal(new BigDecimal(0));
balance.setEndCreditBal(new BigDecimal(0));
balance.setEndBal(new BigDecimal(0));
balance.setIsDummy(0);
balance.setMonthId(period);
balance.setCustomerCode("");
addlist.add(balance);
}
private void validationAcctCode(int period, String userId) {//(todo:[validation] to be continue (neo)
}
private void synAccountFromTaxAdmin(int period, String userId) {
ProjectExample example = new ProjectExample();
example.createCriteria().andDbNameEqualTo(ShardingContextHolder.getDataSourceKey());
List<Project> plist = projectMapper.selectByExample(example);
if (plist != null && !plist.isEmpty()) {
Project pFirst = plist.get(FIRST_OR_DEFAULT);
if (pFirst.getEnterpriseAccountSetId() != null && !pFirst.getEnterpriseAccountSetId().isEmpty()) {
String easId = pFirst.getEnterpriseAccountSetId();
EnterpriseAccountExample accountExample = new EnterpriseAccountExample();
accountExample.createCriteria().andEnterpriseAccountSetIdEqualTo(easId);
List<EnterpriseAccount> taxList = enterpriseAccountMapper.selectByExample(accountExample);
taxList.stream().sorted(Comparator.comparing(EnterpriseAccount::getUpdateTime));
List<VatEnterpriseAccount> proList = vatEnterpriseAccountMapper.selectByExample(null);
proList.stream().sorted(Comparator.comparing(VatEnterpriseAccount::getCreateTime));
if (taxList != null && !taxList.isEmpty()) {
if (proList == null || proList.isEmpty() || (!proList.isEmpty() && proList.get(FIRST_OR_DEFAULT)
.getCreateTime().before(taxList.get(FIRST_OR_DEFAULT).getUpdateTime()))) {
accountExample.createCriteria().andEnglishNameEqualTo(easId);
synAccountData(enterpriseAccountMapper.selectByExample(accountExample), period, userId);
}
}
}
}
}
private void synAccountData(List<EnterpriseAccount> importList, int period, String userId) {
importList.stream().forEach(m -> {
VatEnterpriseAccountExample vatEnterpriseAccountExample = new VatEnterpriseAccountExample();
vatEnterpriseAccountExample.createCriteria().andAcctCodeEqualTo(m.getCode());
List<VatEnterpriseAccount> result = vatEnterpriseAccountMapper.selectByExample(vatEnterpriseAccountExample);
if (result == null || result.isEmpty()) {
VatEnterpriseAccount account = new VatEnterpriseAccount();
account.setId(UUID.randomUUID().toString());
account.setAcctCode(m.getCode());
account.setName(StringUtil.isEmpty(m.getName()) ? m.getCode() : m.getName());
account.setParentCode(m.getParentCode());
account.setFullName(m.getFullName());
account.setAcctProp(m.getAcctProp());
account.setSubProp(m.getSubProp());
account.setAcctLevel(m.getAcctLevel());
account.setDirection(m.getDirection());
account.setIsLeaf(m.getIsLeaf());
account.setIsActive(m.getIsActive());
account.setEnglishName(m.getEnglishName());
account.setStdCode(m.getStdCode());
account.setEnterpriseAccountSetId(m.getEnterpriseAccountSetId());
account.setIsDummy(0);
account.setIsInVoucher(0);
account.setCreatorId(userId);
account.setUpdatorId(userId);
account.setCreateTime(new Date());
account.setUpdateTime(new Date());
vatEnterpriseAccountMapper.insert(account);
} else if (!StringUtil.isNotEmpty(m.getName())) {
result.forEach(n -> {
if (!n.getName().equals(m.getName())) {
n.setName(m.getName());
n.setIsDummy(0);
n.setUpdatorId(userId);
n.setUpdateTime(new Date());
vatEnterpriseAccountMapper.updateByPrimaryKeySelective(n);
}
});
}
});
}
private void clearTableData(int period, String companyBalanceTable) {
if (period > 0) {
mapper.deleteByNameAndPeriod(companyBalanceTable, period);
} else {
mapper.truncateByName(companyBalanceTable);
}
}
}
package pwc.taxtech.atms.service.impl;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.common.datasource.DataSourceConfig;
import pwc.taxtech.atms.common.datasource.DataSourceFactory;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.exception.ParameterException;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
@Service("DynamicDataSource")
public class DataSourcePoolService extends AbstractRoutingDataSource {
private GenericKeyedObjectPool<String, DruidDataSource> dataSourcePool;
@Value("${jdbc_url_demo}")
private String demoUrl;
@Value("${jdbc_user}")
private String jdbcUser;
@Value("${jdbc_password}")
private String jdbcPwd;
@PostConstruct
public void init() throws Exception {
DataSourceConfig config = new DataSourceConfig();
config.setUrl(demoUrl);
config.setUsername(jdbcUser);
config.setPassword(jdbcPwd);
GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setMaxTotalPerKey(1);
poolConfig.setMaxIdlePerKey(1);
dataSourcePool = new GenericKeyedObjectPool<>(new DataSourceFactory(config), poolConfig);
this.setTargetDataSources(Maps.newHashMap());
}
@Override
protected Object determineCurrentLookupKey() {
return ShardingContextHolder.getDataSourceKey();
}
@Override
protected synchronized DataSource determineTargetDataSource() {
try {
String key = ShardingContextHolder.getDataSourceKey();
DruidDataSource dataSource = dataSourcePool.borrowObject(key);
dataSourcePool.returnObject(key, dataSource);
return dataSource;
} catch (Exception e) {
throw new RuntimeException("determineTargetDataSource error.", e);
}
}
private void createDataSource(String key) {
if (StringUtils.isBlank(key)) {
throw new ParameterException("DataSource name is empty.");
}
try {
dataSourcePool.addObject(key);
} catch (Exception e) {
throw new RuntimeException("createDataSource error.", e);
}
}
@Bean
public SqlSessionFactory dynamicSqlSessionFactory(
@Qualifier("DynamicDataSource") DataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:pwc/taxtech/atms/vat/dao/**/*Mapper.xml"));
return bean.getObject();
}
@Bean
public SqlSessionTemplate dynamicSqlSessionTemplate(
@Qualifier("dynamicSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
public JdbcTemplate dynamicJdbcTemplate(@Qualifier("DynamicDataSource")DataSource dynamicDataSource) {
return new JdbcTemplate(dynamicDataSource);
}
}
package pwc.taxtech.atms.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.constant.VatErpImportValidation;
import pwc.taxtech.atms.dao.CitTBDataImportMapper;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.service.ICitTBDataImportService;
import java.util.List;
@Service
public class ICitTBDataImportServiceImpl implements ICitTBDataImportService {
private static Logger LOGGER = LoggerFactory.getLogger(ICitTBDataImportServiceImpl.class);
@Autowired
CitTBDataImportMapper citTBDataImportMapper;
@Override
public OperationResultDto<Boolean> clearTableByPeriods(List<Integer> periods) {
return clearTableByPeriods(periods, true);
}
public OperationResultDto<Boolean> clearTableByPeriods(List<Integer> periods, Boolean isClearTb) {
try {
periods.forEach(period -> {
clearCustTable(period, VatErpImportValidation.CompanyBalanceTbName);
if (isClearTb) {
clearCustTable(period, VatErpImportValidation.CustBalanceTb);
}
clearCustTable(period, VatErpImportValidation.BalanceTb);
clearVoucherTable(period);
clearRemapTable(period);
});
return OperationResultDto.SUCCESS_EMPTY;
}catch (Exception e){
LOGGER.error("ClearTableByPeriods method error",e);
return OperationResultDto.errorFor(e.getMessage());
}
}
private void clearRemapTable(Integer period) {
citTBDataImportMapper.deleteByNameAndPeriod(VatErpImportValidation.AccountRemapTb, isImportByPeriod(period) ? period : null);
}
private void clearVoucherTable(Integer period) {
citTBDataImportMapper.deleteByNameAndPeriod(VatErpImportValidation.VoucherTbName, isImportByPeriod(period) ? period : null);
}
//清除试算平衡相关的Table
private void clearCustTable(Integer period, String tbName) {
if (isImportByPeriod(period) && !tbName.equals(VatErpImportValidation.BalanceTb))
if (tbName.equals(VatErpImportValidation.CompanyBalanceTbName) || tbName.equals(VatErpImportValidation.CustBalanceTb)) {
citTBDataImportMapper.deleteByPeriod(period, tbName);
if(tbName.equals(VatErpImportValidation.CustBalanceTb)){
citTBDataImportMapper.deleteByGreaterPeriod(period, tbName);
}
}
else citTBDataImportMapper.deleteByNameAndPeriod(tbName, null);
}
private Boolean isImportByPeriod(int period) {
return period >= 0;
}
}
......@@ -72,8 +72,8 @@ public class FormulaAgent extends VatAbstractService {
return null;
}
public String getPastProjectDbName(int year, String orgId) {
return adminMp.getPastProjectDbName(year, orgId);
public String getPastProjectId(int year, String orgId) {
return adminMp.getPastProjectId(year, orgId);
}
public CellData getCellData(String templateId, String cellId, int periodId) {
......
......@@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.common.util.SpringContextUtil;
import pwc.taxtech.atms.constant.enums.CellDataSourceType;
import pwc.taxtech.atms.constant.enums.EnumOperationType;
......@@ -24,8 +23,6 @@ import pwc.taxtech.atms.dto.vatdto.ReportCellDataSourceDto;
import pwc.taxtech.atms.dto.vatdto.ReportDataDto;
import pwc.taxtech.atms.dto.vatdto.VatEnterpriseAccountResultDto;
import pwc.taxtech.atms.entity.*;
import pwc.taxtech.atms.entity.EnterpriseAccount;
import pwc.taxtech.atms.entity.EnterpriseAccountExample;
import pwc.taxtech.atms.exception.NotSupportedException;
import pwc.taxtech.atms.service.impl.CellConfigTranslater;
import pwc.taxtech.atms.vat.dpo.DataSourceCellDataDto;
......@@ -97,9 +94,7 @@ public class ReportServiceImpl extends VatAbstractService implements ReportServi
}
}
String dbName = ShardingContextHolder.getDataSourceKey();
Map<String, Object> map = new HashMap<>();
map.put("dbName", dbName);
map.put("period", period);
map.put("projectId", projectId);
map.put("templateGroupId", templateGroupId);
......
......@@ -9,7 +9,6 @@ import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.common.util.MyAsserts;
import pwc.taxtech.atms.constant.enums.FormulaDataSourceDetailType;
import pwc.taxtech.atms.dpo.CellTemplatePerGroupDto;
......@@ -110,26 +109,12 @@ public class BB extends FunctionBase implements FreeRefFunction {
// bo.disCount();
CellData cellData = null;
String dbName = agent.getPastProjectDbName(curPeriod.getCurYear(),
String projectId = agent.getPastProjectId(curPeriod.getCurYear(),
formulaContext.getOrganizationId());
MyAsserts.assertNotEmpty(dbName, Exceptions.BB_EMPTY);
String currentProjectDb = ShardingContextHolder.getDataSourceKey();
if (currentProjectDb.equals(dbName)) {
cellData = agent.getCellData(cellTemplateData.getReportTemplateId(),
cellTemplateData.getCellTemplateId(), curPeriod.getCurPeriod());
} else {
try {
ShardingContextHolder.setDataSourceKey(dbName);
cellData = agent.getCellData(cellTemplateData.getReportTemplateId(),
cellTemplateData.getCellTemplateId(), curPeriod.getCurPeriod());
} catch (Exception e) {
LOGGER.warn("get data exception with dbName{} currentDb {}", dbName, currentProjectDb, e);
throw e;
} finally {
ShardingContextHolder.setDataSourceKey(currentProjectDb);
}
}
MyAsserts.assertNotEmpty(projectId, Exceptions.PROJECT_EMPTY);
cellData = agent.getCellData(cellTemplateData.getReportTemplateId(),
cellTemplateData.getCellTemplateId(), curPeriod.getCurPeriod());
nullCellDto.extractFromGroup(bo, curPeriod, cellData, cellTemplateData);
// todo: fix datasource name by templateList(neo)
......
package pwc.taxtech.atms;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.common.util.DateUtils;
import pwc.taxtech.atms.entity.*;
import pwc.taxtech.atms.vat.entity.PeriodTemplate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DataMigration extends CommonIT {
@Autowired
private JdbcTemplate jdbcTemplate;
private List<Map<String, Object>> template20180622List;
private List<Map<String, Object>> templateList;
private List<CellTemplate> cellTemplates;
private List<Template> templates;
private List<Map<String, Object>> cellTemplate20180622List;
//1. 这个是原本的id
String templateGroupId = "'3916DCBA-B8B5-4C99-BF65-FF85F6A5FBE7'";
//2.这个是新的templategroupid
Long templateGroupIdLong = 16207462143234048L;
@Test
public void doMigration(){
doMigrationTemplateGroup();
doMigrationTemplate();
doMigrationCellTemplate();
doMigrationCellTemplateConfig();
}
@Test
public void doMigrationTemplateGroup() {
String sql = "Select * from TemplateGroup_20180622 where id=" + templateGroupId;
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
// sql = "DELETE FROM template_group";
// jdbcTemplate.execute(sql);
TemplateGroup templateGroup;
for (Map<String, Object> item : queryForList) {
templateGroup = new TemplateGroup();
this.templateGroupIdLong = distributedIdService.nextId();
templateGroup.setId(this.templateGroupIdLong);
templateGroup.setName((MapUtils.getString(item, "Name")));
templateGroup.setServiceTypeId((MapUtils.getString(item, "ServiceTypeId")));
templateGroup.setIndustryIds((MapUtils.getString(item, "IndustryIds")));
templateGroup.setPayTaxType((MapUtils.getInteger(item, "PayTaxType") != null ? MapUtils.getInteger(item, "PayTaxType") : 0));
templateGroup.setGroupType((MapUtils.getInteger(item, "GroupType")));
templateGroup.setCopyFrom(0L);
templateGroup.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
templateGroup.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
templateGroup.setIsSystemType((MapUtils.getBoolean(item, "IsSystemType")));
templateGroup.setCreateBy(StringUtils.EMPTY);
templateGroup.setUpdateBy(StringUtils.EMPTY);
templateGroupMapper.insert(templateGroup);
}
}
@Test
public void doMigrationTemplate() {
String sql = "Select * from Template_20180622 where TemplateGroupId=" + templateGroupId;
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
// sql = "DELETE FROM template";
// jdbcTemplate.execute(sql);
Template template;
for (Map<String, Object> item : queryForList) {
template = new Template();
template.setId(distributedIdService.nextId());
template.setName(MapUtils.getString(item, "Name"));
template.setCode(MapUtils.getString(item, "Code") != null ? MapUtils.getString(item, "Code") : StringUtils.EMPTY);
template.setPath(MapUtils.getString(item, "Path"));
template.setReportType(MapUtils.getInteger(item, "ReportType") != null ? MapUtils.getInteger(item, "ReportType") : 0);
template.setOrderIndex(MapUtils.getInteger(item, "OrderIndex"));
template.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
template.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
template.setIsSystemType(MapUtils.getBoolean(item, "IsSystemType"));
template.setIsActiveAssociation(MapUtils.getBoolean(item, "IsActiveAssociation"));
template.setParentId(MapUtils.getString(item, "ParentId") != null ? MapUtils.getString(item, "ParentId") : StringUtils.EMPTY);
template.setCreateBy(StringUtils.EMPTY);
template.setUpdateBy(StringUtils.EMPTY);
template.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupId")));
templateMapper.insert(template);
}
}
/**
* 根据老表templategroupid获取新表id
*
* @param id 老表templategroupid
* @return 新表templategroupid
*/
private Long getIdFromExistTable(String id) {
try {
String sql = "SELECT `Name`,UpdateTime from TemplateGroup_20180622 where id='" + id + "'";
Map<String, Object> result = jdbcTemplate.queryForMap(sql);
String name = MapUtils.getString(result, "Name");
String updateTime = MapUtils.getString(result, "UpdateTime");
sql = "SELECT id from template_group a WHERE a.update_time='" + updateTime + "' AND `name`='" + name + "'";
result = jdbcTemplate.queryForMap(sql);
return MapUtils.getLong(result, "id");
} catch (Exception e) {
return 0L;
}
}
//todo:cell_template --220081
@Test
public void doMigrationCellTemplate() {
String sql = "SELECT * FROM CellTemplate_20180622 WHERE ReportTemplateId IN " +
"(SELECT id FROM Template_20180622 WHERE TemplateGroupId IN(" + templateGroupId + ") " +
" AND path LIKE '%VatTemplate/DefaultVersion/%')";
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
System.out.println(sql);
// sql = "DELETE FROM cell_template";
// System.out.println(sql);
// jdbcTemplate.execute(sql);
CellTemplate cellTemplate;
cellTemplates = new ArrayList<>();
List<CellTemplate> cellTemplateList = new ArrayList<>();
sql = "SELECT id,`Name`,Code,CreateTime from Template_20180622";
template20180622List = jdbcTemplate.queryForList(sql);
// sql = "SELECT id,`name`,code,create_time from template";
// templateList = jdbcTemplate.queryForList(sql);
templates = templateMapper.selectByExample(new TemplateExample());
int i = 0, j = 0;
for (Map<String, Object> item : queryForList) {
i++;
j++;
cellTemplate = new CellTemplate();
cellTemplate.setId(distributedIdService.nextId());
cellTemplate.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateId")));
cellTemplate.setRowIndex(MapUtils.getInteger(item, "RowIndex"));
cellTemplate.setRowName(MapUtils.getString(item, "RowName") != null ? MapUtils.getString(item, "RowName") : "");
cellTemplate.setColumnIndex(MapUtils.getInteger(item, "ColumnIndex"));
cellTemplate.setColumnName(MapUtils.getString(item, "ColumnName") != null ? MapUtils.getString(item, "ColumnName") : "");
cellTemplate.setComment(MapUtils.getString(item, "Comment") != null ? MapUtils.getString(item, "Comment") : "");
cellTemplate.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
cellTemplate.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
cellTemplate.setCopyFromId(0L);
cellTemplate.setDataType(MapUtils.getInteger(item, "DataType") != null ? MapUtils.getInteger(item, "DataType") : 0);
cellTemplate.setIsReadOnly(MapUtils.getInteger(item, "IsReadOnly") != null ? MapUtils.getBoolean(item, "IsReadOnly") : false);
cellTemplate.setUpdateBy(StringUtils.EMPTY);
cellTemplate.setCreateBy(StringUtils.EMPTY);
// cellTemplateMapper.insert(cellTemplate);
cellTemplateList.add(cellTemplate);
System.out.println("i=" + i);
System.out.println("j=" + j);
if (i == 1000 && j < queryForList.size()) {
cellTemplateMapper.batchInsert2(cellTemplateList);
cellTemplateList.clear();
i = 0;
} else {
if (j == queryForList.size()) {
cellTemplateMapper.batchInsert2(cellTemplateList);
cellTemplateList.clear();
}
}
}
//handleList(queryForList, 2);
}
/**
* 根据template老表Id获取新表Id
*
* @param id template老表Id
* @return
*/
private Long getIdFromExistTable2(String id) {
try {
// String sql = "SELECT `Name`,Code,CreateTime from Template_20180622 where id='" + id + "'";
// System.out.println(sql);
Map<String, Object> item = template20180622List.stream()
.filter(a -> MapUtils.getString(a, "id").equals(id))
.findFirst().get();
//Map<String, Object> result = jdbcTemplate.queryForMap(sql);
String name = MapUtils.getString(item, "Name");
String code = MapUtils.getString(item, "Code");
String createTime = MapUtils.getString(item, "CreateTime");
//template20180622List.remove(item);
// item = templateList.stream()
// .filter(a -> MapUtils.getString(a, "name").equals(name)
// && MapUtils.getString(a, "code").equals(code)
// && MapUtils.getString(a, "create_time").equals(createTime))
// .findFirst().get();
Template template = templates.stream()
.filter(a -> a.getName().equals(name) && a.getCode().equals(code)
&& a.getCreateTime().equals(DateUtils.strToDateLong(createTime))
&& a.getTemplateGroupId().equals(templateGroupIdLong))
.findFirst().get();
//sql = "SELECT id from template a WHERE create_time='" + createTime + "' AND `name`='" + name + "' AND code='" + code + "'";
//System.out.println(sql);
//result = jdbcTemplate.queryForMap(sql);
Long newId = template.getId();
//templateList.remove(item);
return newId;
} catch (Exception e) {
return 0L;
} finally {
}
}
/**
* 多线程处理list
*
* @param data 数据list
* @param threadNum 线程数
*/
public synchronized void handleList(List<Map<String, Object>> data, int threadNum) {
int length = data.size();
int tl = length % threadNum == 0 ? length / threadNum : (length
/ threadNum + 1);
for (int i = 0; i < threadNum; i++) {
int end = (i + 1) * tl;
HandleThread thread = new HandleThread("线程[" + (i + 1) + "] ", data, i * tl, end > length ? length : end);
System.out.println("线程[" + (i + 1) + "] started");
thread.start();
}
}
class HandleThread extends Thread {
private String threadName;
private List<Map<String, Object>> data;
private int start;
private int end;
public HandleThread(String threadName, List<Map<String, Object>> data, int start, int end) {
this.threadName = threadName;
this.data = data;
this.start = start;
this.end = end;
}
public void run() {
// TODO 这里处理数据
CellTemplate cellTemplate;
for (Map<String, Object> item : data) {
cellTemplate = new CellTemplate();
cellTemplate.setId(distributedIdService.nextId());
//cellTemplate.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateId")));
cellTemplate.setRowIndex(MapUtils.getInteger(item, "RowIndex"));
cellTemplate.setRowName(MapUtils.getString(item, "RowName") != null ? MapUtils.getString(item, "RowName") : "");
cellTemplate.setColumnIndex(MapUtils.getInteger(item, "ColumnIndex"));
cellTemplate.setColumnName(MapUtils.getString(item, "ColumnName") != null ? MapUtils.getString(item, "ColumnName") : "");
cellTemplate.setComment(MapUtils.getString(item, "Comment") != null ? MapUtils.getString(item, "Comment") : "");
cellTemplate.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
cellTemplate.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
cellTemplate.setCopyFromId(0L);
cellTemplate.setDataType(MapUtils.getInteger(item, "DataType") != null ? MapUtils.getInteger(item, "DataType") : 0);
cellTemplate.setIsReadOnly(MapUtils.getBoolean(item, "IsReadOnly") != null ? MapUtils.getBoolean(item, "IsReadOnly") : true);
cellTemplate.setUpdateBy(StringUtils.EMPTY);
cellTemplate.setCreateBy(StringUtils.EMPTY);
synchronized (cellTemplates) {
cellTemplates.add(cellTemplate);
}
if (cellTemplates.size() == 100) {
synchronized (cellTemplates) {
cellTemplateMapper.batchInsert2(cellTemplates);
cellTemplates.clear();
}
System.out.println(threadName + "处理了" + data.size() + "条!");
}
//cellTemplateMapper.insert(cellTemplate);
}
synchronized (cellTemplates) {
cellTemplateMapper.batchInsert2(cellTemplates);
cellTemplates.clear();
}
System.out.println(threadName + "处理了" + data.size() + "条!");
//doMigrationCellTemplate();
// List<String> subList = data.subList(start, end)/*.add("^&*")*/;
// System.out.println(threadName+"处理了"+subList.size()+"条!");
}
}
//todo:cell_template_config --76577
@Test
public void doMigrationCellTemplateConfig() {
String sql = "SELECT *\n" +
"FROM CellTemplateConfig_20180622\n" +
"WHERE ReportTemplateId IN(SELECT\n" +
" id\n" +
" FROM Template_20180622\n" +
" WHERE TemplateGroupId IN(" + templateGroupId + ")\n" +
" AND path LIKE '%VatTemplate/DefaultVersion/%')\n" +
" AND celltemplateid IN(SELECT\n" +
" id\n" +
" FROM CellTemplate_20180622\n" +
" WHERE ReportTemplateId IN(SELECT\n" +
" id\n" +
" FROM Template_20180622\n" +
" WHERE TemplateGroupId IN(" + templateGroupId + ")\n" +
" AND path LIKE '%VatTemplate/DefaultVersion/%'))";
System.out.println(sql);
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
// sql = "DELETE FROM cell_template_config";
// System.out.println(sql);
// jdbcTemplate.execute(sql);
sql = "SELECT id,`Name`,Code,CreateTime from Template_20180622 ";
template20180622List = jdbcTemplate.queryForList(sql);
templates = templateMapper.selectByExample(new TemplateExample());
cellTemplates = cellTemplateMapper.selectByExample(new CellTemplateExample());
sql = "SELECT id,ReportTemplateId,RowIndex,ColumnIndex from CellTemplate_20180622 WHERE ReportTemplateId IN " +
"(SELECT id FROM Template_20180622 WHERE TemplateGroupId IN" +
"(" + templateGroupId + ") AND path LIKE '%VatTemplate/DefaultVersion/%')";
cellTemplate20180622List = jdbcTemplate.queryForList(sql);
List<CellTemplateConfig> cellTemplateConfigList = new ArrayList<>();
CellTemplateConfig cellTemplateConfig;
int i = 0, j = 0;
for (Map<String, Object> item : queryForList) {
i++;
j++;
cellTemplateConfig = new CellTemplateConfig();
cellTemplateConfig.setId(distributedIdService.nextId());
cellTemplateConfig.setCellTemplateId(getIdFromExistTable3(MapUtils.getString(item, "CellTemplateId"), MapUtils.getString(item, "ReportTemplateId")));
cellTemplateConfig.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateId")));
cellTemplateConfig.setDataSourceType(MapUtils.getInteger(item, "DataSourceType"));
cellTemplateConfig.setFormula(MapUtils.getString(item, "Formula") != null ? MapUtils.getString(item, "Formula") : "");
cellTemplateConfig.setFormulaDescription(MapUtils.getString(item, "FormulaDescription") != null ? MapUtils.getString(item, "FormulaDescription") : "");
cellTemplateConfig.setAccountCodes(MapUtils.getString(item, "AccountCodes") != null ? MapUtils.getString(item, "AccountCodes") : "");
cellTemplateConfig.setInvoiceType(MapUtils.getInteger(item, "InvoiceType") != null ? MapUtils.getInteger(item, "InvoiceType") : 0);
cellTemplateConfig.setTaxRate(MapUtils.getString(item, "TaxRate") != null ? MapUtils.getString(item, "TaxRate") : "");
cellTemplateConfig.setInvoiceAmountType(MapUtils.getInteger(item, "InvoiceAmountType") != null ? MapUtils.getInteger(item, "InvoiceAmountType") : 0);
cellTemplateConfig.setModelIds(MapUtils.getString(item, "ModelIds") != null ? MapUtils.getString(item, "ModelIds") : "");
cellTemplateConfig.setCreateBy(MapUtils.getString(item, "Creator") != null ? MapUtils.getString(item, "Creator") : "");
cellTemplateConfig.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
cellTemplateConfig.setUpdateBy(MapUtils.getString(item, "Updater") != null ? MapUtils.getString(item, "Updater") : "");
cellTemplateConfig.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
cellTemplateConfig.setInvoiceCategory(MapUtils.getString(item, "InvoiceCategory") != null ? MapUtils.getString(item, "InvoiceCategory") : "");
cellTemplateConfig.setFormulaDataSource(MapUtils.getString(item, "FormulaDataSource") != null ? MapUtils.getString(item, "FormulaDataSource") : "");
cellTemplateConfig.setValidation(MapUtils.getString(item, "Validation") != null ? MapUtils.getString(item, "Validation") : "");
cellTemplateConfig.setValidationDescription(MapUtils.getString(item, "ValidationDescription") != null ? MapUtils.getString(item, "ValidationDescription") : "");
cellTemplateConfig.setVoucherKeyword(MapUtils.getString(item, "VoucherKeyword") != null ? MapUtils.getString(item, "VoucherKeyword") : "");
System.out.println("i=" + i);
System.out.println("j=" + j);
cellTemplateConfigList.add(cellTemplateConfig);
if (i == 10 && j < queryForList.size()) {
cellTemplateConfigMapper.batchInsert2(cellTemplateConfigList);
cellTemplateConfigList.clear();
i = 0;
} else {
if (j == queryForList.size()) {
cellTemplateConfigMapper.batchInsert2(cellTemplateConfigList);
cellTemplateConfigList.clear();
}
}
}
}
/**
* 根据templateid 和 celltemplateid 获取新表cellTemplate id
*
* @param id celltemplateid
* @param id2 templateid
* @return
*/
private Long getIdFromExistTable3(String id, String id2) {
try {
//根据templateid 获取 新表 templateid
Long templateId = getIdFromExistTable2(id2);
//根据新表templateid 还有 rowIndex,columnIndex 获取 celltemplate 新表Id
Map<String, Object> item = cellTemplate20180622List.stream()
.filter(a -> MapUtils.getString(a, "id").equals(id))
.findFirst().get();
Integer rowIndex = MapUtils.getInteger(item, "RowIndex");
Integer columnIndex = MapUtils.getInteger(item, "ColumnIndex");
CellTemplate cellTemplate = cellTemplates.stream()
.filter(a -> a.getReportTemplateId().equals(templateId)
&& a.getRowIndex().equals(rowIndex)
&& a.getColumnIndex().equals(columnIndex))
.findFirst().get();
return cellTemplate.getId();
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
//todo:organization_service_template_group --284
@Test
public void doMigrationOrganizationServiceTemplateGroup() {
String sql = "Select * from OrganizationServiceTemplateGroup";
System.out.println(sql);
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
sql = "DELETE FROM organization_service_template_group";
System.out.println(sql);
jdbcTemplate.execute(sql);
OrganizationServiceTemplateGroup organizationServiceTemplateGroup;
for (Map<String, Object> item : queryForList) {
organizationServiceTemplateGroup = new OrganizationServiceTemplateGroup();
organizationServiceTemplateGroup.setId(distributedIdService.nextId());
organizationServiceTemplateGroup.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupId")));
organizationServiceTemplateGroup.setOrganizationId(MapUtils.getString(item, "OrganizationId"));
organizationServiceTemplateGroup.setServiceTypeId(MapUtils.getString(item, "ServiceTypeId"));
organizationServiceTemplateGroupMapper.insert(organizationServiceTemplateGroup);
}
}
//todo:tax_payer_report_rule --120
@Test
public void doMigrationTaxPayerReportRule() {
String sql = "Select * from TaxPayerReportRule_20180622";
System.out.println(sql);
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
sql = "DELETE FROM tax_payer_report_rule";
System.out.println(sql);
jdbcTemplate.execute(sql);
TaxPayerReportRule taxPayerReportRule;
for (Map<String, Object> item : queryForList) {
taxPayerReportRule = new TaxPayerReportRule();
taxPayerReportRule.setId(distributedIdService.nextId());
taxPayerReportRule.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupId")));
taxPayerReportRule.setOrganizationId(MapUtils.getString(item, "OrganizationId"));
taxPayerReportRule.setTaxPayerType(MapUtils.getInteger(item, "TaxPayerType"));
taxPayerReportRule.setIsDefault(MapUtils.getBoolean(item, "IsDefault"));
taxPayerReportRule.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
taxPayerReportRule.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
taxPayerReportRule.setCreateBy(StringUtils.EMPTY);
taxPayerReportRule.setUpdateBy(StringUtils.EMPTY);
taxPayerReportRuleMapper.insert(taxPayerReportRule);
}
}
//todo:tax_rule_setting --13
@Test
public void doMigrationTaxRuleSetting() {
String sql = "Select * from TaxRuleSetting_20180622";
System.out.println(sql);
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
sql = "DELETE FROM tax_rule_setting";
System.out.println(sql);
jdbcTemplate.execute(sql);
TaxRuleSetting taxRuleSetting;
for (Map<String, Object> item : queryForList) {
taxRuleSetting = new TaxRuleSetting();
taxRuleSetting.setId(distributedIdService.nextId());
taxRuleSetting.setTaxBase(MapUtils.getString(item, "TaxBase"));
taxRuleSetting.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
taxRuleSetting.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
taxRuleSetting.setGroupName(MapUtils.getString(item, "GroupName"));
taxRuleSetting.setName(MapUtils.getString(item, "Name"));
taxRuleSetting.setIsDefault(MapUtils.getBoolean(item, "IsDefault"));
taxRuleSetting.setTaxRate(new BigDecimal(MapUtils.getFloat(item, "TaxRate")));
taxRuleSetting.setCreateBy(StringUtils.EMPTY);
taxRuleSetting.setUpdateBy(StringUtils.EMPTY);
taxRuleSettingMapper.insert(taxRuleSetting);
}
}
private List<Map<String, Object>> taxRuleSetting20180622List;
private List<TaxRuleSetting> taxRuleSettingList;
//todo:tax_rule_setting_organization --17
@Test
public void doMigrationTaxRuleSettingOrganization() {
String sql = "Select * from TaxRuleSettingOrganization_20180622";
System.out.println(sql);
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
sql = "DELETE FROM tax_rule_setting_organization";
System.out.println(sql);
jdbcTemplate.execute(sql);
sql = "SELECT id,CreateTime FROM TaxRuleSetting_20180622";
taxRuleSetting20180622List = jdbcTemplate.queryForList(sql);
taxRuleSettingList = taxRuleSettingMapper.selectByExample(new TaxRuleSettingExample());
TaxRuleSettingOrganization taxRuleSettingOrganization;
for (Map<String, Object> item : queryForList) {
taxRuleSettingOrganization = new TaxRuleSettingOrganization();
taxRuleSettingOrganization.setId(distributedIdService.nextId());
taxRuleSettingOrganization.setTaxSettingId(getIdFromExistTable4(MapUtils.getString(item, "TaxSettingId")));
taxRuleSettingOrganization.setOrganizationId(MapUtils.getString(item, "OrganizationId"));
taxRuleSettingOrganization.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
taxRuleSettingOrganization.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
taxRuleSettingOrganization.setCreateBy(StringUtils.EMPTY);
taxRuleSettingOrganization.setUpdateBy(StringUtils.EMPTY);
taxRuleSettingOrganizationMapper.insert(taxRuleSettingOrganization);
}
}
/**
* 获取taxSetting 新表Id
*
* @param id 旧表Id
* @return 新表Id
*/
private Long getIdFromExistTable4(String id) {
try {
Map<String, Object> item = taxRuleSetting20180622List.stream()
.filter(a -> MapUtils.getString(a, "id").equals(id))
.findFirst().get();
String name = MapUtils.getString(item, "Name");
String createTime = MapUtils.getString(item, "CreateTime");
TaxRuleSetting taxRuleSetting = taxRuleSettingList.stream()
.filter(a -> a.getName().equals(name)
&& a.getCreateTime().equals(createTime))
.findFirst().get();
Long newId = taxRuleSetting.getId();
return newId;
} catch (Exception e) {
return 0L;
} finally {
}
}
//todo: ProjectServiceType_20180622 --40
@Test
public void insertChieseCharacter() {
ShardingContextHolder.setDataSourceKey("a1800010");
PeriodTemplate periodTemplate = new PeriodTemplate();
periodTemplate.setId(distributedIdService.nextId());
periodTemplate.setUpdateBy("张三");
periodTemplateMapper.insertSelective(periodTemplate);
Template template = new Template();
template.setId(distributedIdService.nextId());
template.setUpdateBy("张三");
templateMapper.insertSelective(template);
}
}
package pwc.taxtech.atms;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import pwc.taxtech.atms.common.datasource.ShardingContextHolder;
import pwc.taxtech.atms.vat.dao.ReportMapper;
import pwc.taxtech.atms.vat.entity.Report;
import pwc.taxtech.atms.vat.entity.ReportExample;
import java.util.List;
public class DataSourceSwitch extends CommonIT {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private ReportMapper reportMapper;
@Test
public void insertChieseCharacter() {
ShardingContextHolder.setDataSourceKey("a1700000");
ReportExample example = new ReportExample();
example.createCriteria().andTemplateIdEqualTo(Long.valueOf("9951852766564352"))
.andPeriodEqualTo(1);
List<Report> reports = reportMapper.selectByExample(example);
System.out.println(reports.size());
ShardingContextHolder.setDataSourceKey("a1800013");
System.out.println(reportMapper.selectByExample(example).size());
ShardingContextHolder.setDataSourceKey("a1700000");
System.out.println(reportMapper.selectByExample(example).size());
}
}
......@@ -55,5 +55,5 @@ public interface FormulaAdminMapper extends MyMapper {
" AND p.Is_Active = 1 " +
" AND ROWNUM=1"+
"ORDER BY ps.Service_Type_ID ")
String getPastProjectDbName(@Param("year") int year, @Param("orgId") String organizationId);
String getPastProjectId(@Param("year") int year, @Param("orgId") String organizationId);
}
......@@ -137,10 +137,10 @@
B.PERIOD,
B.TEMPLATE_ID
FROM
${DB_NAME}.REPORT b
REPORT b
WHERE
b.PERIOD = #{period,jdbcType=INTEGER}
AND B.PROJECT_ID = #{projectID,jdbcType=VARCHAR}
AND B.PROJECT_ID = #{projectId,jdbcType=VARCHAR}
)
D
ON
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment