Commit b0d55663 authored by neo's avatar neo

[dev] delete TB Journal finace Customs voucher Import Controller And Service

parent 5011ee91
......@@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.vat.entity.CellComment;
import pwc.taxtech.atms.vat.service.CellCommentService;
import pwc.taxtech.atms.vat.service.impl.CellCommentServiceImpl;
import java.util.List;
import java.util.Optional;
......@@ -17,7 +17,7 @@ import java.util.Optional;
@RequestMapping(value = "api/v1/CellComment")
public class CellCommentController {
@Autowired
CellCommentService cellCommentService;
CellCommentServiceImpl cellCommentService;
@RequestMapping(value = "List", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public OperationResultDto<List<CellComment>> getCellComments(@RequestParam("cellDataId") Optional<Long> cellDataId) {
......
package pwc.taxtech.atms.controller;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dpo.PagingDto;
import pwc.taxtech.atms.dto.PagingResultDto;
import pwc.taxtech.atms.dto.vatdto.CustomsInvoiceDto;
import pwc.taxtech.atms.dto.vatdto.CustomsInvoiceFilter;
import pwc.taxtech.atms.dto.vatdto.ImportCustomsInvoiceDto;
import pwc.taxtech.atms.dto.vatdto.JsonCustomsInvoiceDto;
import pwc.taxtech.atms.service.IdentityService;
import pwc.taxtech.atms.thirdparty.ExcelUtil;
import pwc.taxtech.atms.vat.service.impl.CustomsInvoiceServiceImpl;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;
@RestController
@RequestMapping(value = "api/v1/CustomsInvoice")
public class CustomsInvoiceController {
@Autowired
CustomsInvoiceServiceImpl customsInvoiceService;
@Autowired
private IdentityService identityService;
@RequestMapping(value = "GetCustomsInvoiceDataForDisplay", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getCustomsInvoiceDataForDisplay(@RequestParam Integer fromPeriod, @RequestParam Integer toPeriod, @RequestParam String criteria, @RequestParam String pagination) {
CustomsInvoiceFilter filter = new CustomsInvoiceFilter();
if (StringUtils.isNotBlank(criteria) && !"null".equals(criteria)) {
filter = JSONObject.parseObject(criteria, CustomsInvoiceFilter.class);
} else {
filter = null;
}
PagingDto paging = new PagingDto();
if (StringUtils.isNotBlank(pagination) && !"null".equals(pagination)) {
paging = JSONObject.parseObject(pagination, PagingDto.class);
} else {
paging = null;
}
return convertCustomsInvoiceDataToJson(fromPeriod, toPeriod, filter, paging);
}
@RequestMapping(value = "GetCustomsInvoiceDataForDisplay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String postCustomsInvoiceDataForDisplay(@RequestParam Integer fromPeriod, @RequestParam Integer toPeriod, @RequestParam String criteria, @RequestParam String pagination) {
return getCustomsInvoiceDataForDisplay(fromPeriod, toPeriod, criteria, pagination);
}
@RequestMapping(value = "GetCustomsInvoicesByPeriodId/{periodId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity getCustomsInvoicesByPeriodId(@PathVariable Integer periodId) {
return ResponseEntity.ok().body(customsInvoiceService.getCustomsInvoicesByPeriodId(periodId));
}
@RequestMapping(value = "getCustomsInvoicesValidates/{periodId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity getCustomsInvoicesValidates(@PathVariable Integer periodId) {
return ResponseEntity.ok().body(customsInvoiceService.getCustomsInvoicesValidates(periodId));
}
@RequestMapping(value = "ExportQueryData/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void exportQueryData(@RequestParam String criteria, HttpServletResponse response) {
CustomsInvoiceFilter filter = new CustomsInvoiceFilter();
if (StringUtils.isNotBlank(criteria) && !criteria.equals("null")) {
filter = JSONObject.parseObject(criteria, CustomsInvoiceFilter.class);
} else {
filter = null;
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + UUID.randomUUID() + ".xlsx");
response.setHeader("x-file-name", UUID.randomUUID() + ".xlsx");
OutputStream os = null;
try {
os = response.getOutputStream();
int count = getDownloadFilePath(filter, os);
if (count == 0) {
response.setStatus(SC_NO_CONTENT);
} else {
response.setStatus(SC_OK);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private int getDownloadFilePath(CustomsInvoiceFilter filter, OutputStream outputStream) {
List<JsonCustomsInvoiceDto> list = GetCustomsInvoiceDataList(filter);
if (list.size() == 0) {
return 0;
}
Map<String, String> header = new HashMap<>();
header.put("RecordNumber", "RecordNumber");
header.put("PeriodId", "期间");
header.put("IssueDate", "开具日期");
header.put("PayNum", "海关缴款书号码");
header.put("InvoiceAmount", "金额");
header.put("InvoiceTaxAmount", "税额");
header.put("AuditResult", "稽核结果");
ExcelUtil.exportExcel(header, list, outputStream);
return list.size();
}
private List<JsonCustomsInvoiceDto> GetCustomsInvoiceDataList(CustomsInvoiceFilter filter) {
List<CustomsInvoiceDto> balanceList = customsInvoiceService.getCustomsInvoicesByPeriodIds(filter.getPeriodFrom(), filter.getPeriodTo());
if (filter != null && !balanceList.isEmpty()) {
balanceList = filterCustomsInvoiceDataList(filter, balanceList);
}
List<JsonCustomsInvoiceDto> recordList = new ArrayList<>();
JsonCustomsInvoiceDto record;
int indexNumber = 1;
for (CustomsInvoiceDto dto : balanceList) {
record = new JsonCustomsInvoiceDto();
CommonUtils.copyProperties(dto, record);
record.setRecordNumber(String.valueOf(indexNumber));
record.setIssueDate(DateFormat.getDateInstance().format(dto.getIssueDate()));
record.setInvoiceTaxAmount(dto.getInvoiceTaxAmount() != null ? dto.getInvoiceTaxAmount().toString() : "0.00");
record.setInvoiceAmount(dto.getInvoiceAmount() != null ? dto.getInvoiceAmount().toString() : "0.00");
recordList.add(record);
indexNumber++;
}
return recordList;
}
private String convertCustomsInvoiceDataToJson(int fromPeriod, int toPeriod, CustomsInvoiceFilter filter, PagingDto pagination) {
String result = StringUtils.EMPTY;
List<CustomsInvoiceDto> balanceList = customsInvoiceService.getCustomsInvoicesByPeriodIds(fromPeriod, toPeriod);
if (filter != null && !balanceList.isEmpty()) {
balanceList = filterCustomsInvoiceDataList(filter, balanceList);
}
if (pagination != null) {
int pageAskingFor = 0;
if (pagination.getPageIndex() > 0) {
pageAskingFor = pagination.getPageIndex() - 1;
}
pagination.setTotalCount(balanceList.size());
balanceList = balanceList.stream().skip(pageAskingFor * pagination.getPageSize()).limit(pagination.getPageSize()).collect(Collectors.toList());
}
List<JsonCustomsInvoiceDto> recordList = new ArrayList<>();
JsonCustomsInvoiceDto record;
int indexNumber = 1;
for (CustomsInvoiceDto dto : balanceList) {
record = new JsonCustomsInvoiceDto();
CommonUtils.copyProperties(dto, record);
record.setRecordNumber(String.valueOf(indexNumber));
record.setIssueDate(DateFormat.getDateInstance().format(dto.getIssueDate()));
record.setInvoiceTaxAmount(dto.getInvoiceTaxAmount() != null ? dto.getInvoiceTaxAmount().toString() : "0.00");
record.setInvoiceAmount(dto.getInvoiceAmount() != null ? dto.getInvoiceAmount().toString() : "0.00");
recordList.add(record);
indexNumber++;
}
PagingResultDto<JsonCustomsInvoiceDto> listWithPaging = new PagingResultDto<>();
listWithPaging.setPageInfo(pagination);
listWithPaging.setList(recordList);
result = JSONObject.toJSONString(listWithPaging);
return result;
}
private List<CustomsInvoiceDto> filterCustomsInvoiceDataList(CustomsInvoiceFilter filter, List<CustomsInvoiceDto> balanceList) {
if (!balanceList.isEmpty()) {
if (StringUtils.isNotBlank(filter.getPayNum())) {
String[] names = filter.getPayNum().split(" ");
List<CustomsInvoiceDto> ds = new ArrayList<>();
for (String name : names) {
ds.addAll(balanceList.stream().filter(a -> a.getPayNum().contains(name)).collect(Collectors.toList()));
}
balanceList = ds;
}
}
if (filter.getTaxAmountFrom() != null || filter.getTaxAmountTo() != null) {
if (filter.getTaxAmountFrom() != null && filter.getTaxAmountTo() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceTaxAmount() != null
&& (filter.getTaxAmountFrom().compareTo(a.getInvoiceAmount()) < 1
&& filter.getTaxAmountTo().compareTo(a.getInvoiceAmount()) > -1))
.collect(Collectors.toList());
} else if (filter.getTaxAmountFrom() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceTaxAmount() != null
&& filter.getTaxAmountFrom().compareTo(a.getInvoiceAmount()) < 1)
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceTaxAmount() != null
&& filter.getTaxAmountTo().compareTo(a.getInvoiceAmount()) > -1)
.collect(Collectors.toList());
}
}
if (filter.getInvoiceAmountFrom() != null || filter.getInvoiceAmountTo() != null) {
if (filter.getInvoiceAmountFrom() != null && filter.getInvoiceAmountTo() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceAmount() != null
&& (filter.getInvoiceAmountFrom().compareTo(a.getInvoiceAmount()) < 1
&& filter.getInvoiceAmountTo().compareTo(a.getInvoiceAmount()) > -1))
.collect(Collectors.toList());
} else if (filter.getInvoiceAmountFrom() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceAmount() != null
&& filter.getInvoiceAmountFrom().compareTo(a.getInvoiceAmount()) < 1)
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream()
.filter(a -> a.getInvoiceAmount() != null
&& filter.getInvoiceAmountTo().compareTo(a.getInvoiceAmount()) > -1)
.collect(Collectors.toList());
}
}
if (filter.getInvoiceStartDate() != null || filter.getInvoiceEndDate() != null) {
if (filter.getInvoiceStartDate() != null && filter.getInvoiceEndDate() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getIssueDate() != null
&& (filter.getInvoiceStartDate().compareTo(a.getIssueDate()) < 1
&& filter.getInvoiceEndDate().compareTo(a.getIssueDate()) > -1))
.collect(Collectors.toList());
} else if (filter.getInvoiceStartDate() != null) {
balanceList = balanceList.stream()
.filter(a -> a.getIssueDate() != null
&& filter.getInvoiceStartDate().compareTo(a.getIssueDate()) < 1)
.collect(Collectors.toList());
} else {
balanceList = balanceList.stream()
.filter(a -> a.getIssueDate() != null
&& filter.getInvoiceEndDate().compareTo(a.getIssueDate()) > -1)
.collect(Collectors.toList());
}
}
return balanceList;
}
@RequestMapping(value = "ImportCustomsInvoice", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity ImportBalanceList(@RequestBody ImportCustomsInvoiceDto importDto) {
String userId = identityService.getIdentityUser().getId();
return ResponseEntity.ok(customsInvoiceService.ImportCustomsInvoice(importDto.CustomsList, importDto.ImportType, userId));
}
}
package pwc.taxtech.atms.controller;
import io.swagger.annotations.ApiOperation;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.thymeleaf.util.StringUtils;
import pwc.taxtech.atms.constant.VatErpImportValidation;
import pwc.taxtech.atms.constant.enums.ImportType;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.ImportDataDto;
import pwc.taxtech.atms.service.IdentityService;
import pwc.taxtech.atms.vat.service.impl.FinanceDataImportServiceImpl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@RestController
@RequestMapping("/api/v1/financeImportData")
public class FinanceDataImportController {
private final static String ImportMethod_OneClick = "oneClick";
private final static String OneClickUploadPath = "~/FinanceDataUpload/OneClickFile";
private final static String UniversalUploadExcelPath = "~/FinanceDataUpload/UniversalExcelFile";
private final static String UniversalUploadCsvPath = "~/FinanceDataUpload/UniversalCsvlFile";
private static Logger logger = LoggerFactory.getLogger(FinanceDataImportController.class);
@Autowired
private FinanceDataImportServiceImpl financeDataImport;
@Autowired
private IdentityService identityService;
@ApiOperation(value = "")
@RequestMapping(value = "checkData/basicCheck", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity getBasicValidationResults() {
return ResponseEntity.ok().body(financeDataImport.getBasicValidationResults(identityService.getIdentityUser().getId()));
}
@RequestMapping(value = "importData/financeDataUpload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity FinanceDataUpload(@RequestParam String importMethod, MultipartHttpServletRequest request) {
if (request.getFileMap().size() == 0) {
return ResponseEntity.ok(new OperationResultDto(false, "NoFile"));
}
if (StringUtils.isEmpty(importMethod)) {
return ResponseEntity.ok(new OperationResultDto(false, "importMethod is empty"));
}
if (!IsSameFileExtenstion(request.getFileMap())) {
return ResponseEntity.ok(new OperationResultDto(false, "file extension is not same"));
}
try {
OperationResultDto<ImportDataDto> result = new OperationResultDto<>();
int uploadFileCount = 0;
String mappedPath = "";
String fileGuid = UUID.randomUUID().toString().toUpperCase();
String fileExtension = getExtension(request.getFileMap());
for (MultipartFile file : request.getFileMap().values()) {
mappedPath = SetUploadFolderPath(importMethod, fileExtension);
String fileFullPath = Paths.get(mappedPath, fileGuid + "_" + file.getName()).toString();
if (SaveFile(file, mappedPath, fileFullPath)) {
uploadFileCount++;
}
}
if (uploadFileCount == request.getFileMap().size()) {
result.setResult(true);
result.setResultMsg("");
ImportDataDto dataDto = new ImportDataDto();
dataDto.Guid = fileGuid;
dataDto.Number = uploadFileCount;
dataDto.FileExtension = fileExtension;
result.setData(dataDto);
}
return ResponseEntity.ok(result);
} catch (Exception ex) {
Map<String, String> error = new HashMap<>();
ex.printStackTrace();
error.put(UUID.randomUUID().toString(), ex.getMessage());
OperationResultDto<ImportDataDto> errorResult = new OperationResultDto<ImportDataDto>(false, "Upload File error");
errorResult.setErrors(error);
ImportDataDto dataDto = new ImportDataDto();
dataDto.Guid = "";
dataDto.Number = 0;
dataDto.FileExtension = "";
errorResult.setData(dataDto);
return ResponseEntity.ok(errorResult);
}
}
@RequestMapping(value = "importData/importFinancedata", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity FinanceImportData(@RequestParam String importMethod, @RequestParam String fileName,
@RequestParam String importType, @RequestParam(required = false) String fileGuid,
@RequestParam Integer period, @RequestParam(required = false) String fileExtension,
@RequestParam(required = false) String projectYear) {
String userId = identityService.getIdentityUser().getId();
if (StringUtils.isEmpty(importMethod)) {
return ResponseEntity.ok(new OperationResultDto(false, "importMethod is empty"));
}
if (StringUtils.isEmpty(fileName)) {
return ResponseEntity.ok(new OperationResultDto(false, "fileName is empty"));
}
if (StringUtils.isEmpty(importType)) {
return ResponseEntity.ok(new OperationResultDto(false, "importType is empty"));
}
if (StringUtils.isEmpty(fileGuid)) {
return ResponseEntity.ok(new OperationResultDto(false, "fileGuid is empty"));
}
if (period == null) {
return ResponseEntity.ok(new OperationResultDto(false, "periodStr is empty"));
}
if (StringUtils.isEmpty(fileExtension)) {
return ResponseEntity.ok(new OperationResultDto(false, "fileExtension is empty"));
}
Integer projectYearInt = !StringUtils.isEmpty(projectYear) ? Integer.parseInt(projectYear) : -1;
int importFileCount = 0;
String mappedPath = SetUploadFolderPath(importMethod, fileExtension);
OperationResultDto<List<ImportDataDto>> result = new OperationResultDto<>();
List<ImportDataDto> importResults = new ArrayList<>();
String[] fileList = fileName.split(",");
List<String> toDeleteFilesPath = new ArrayList<>();
if (importType.equals(ImportType.Override.getCode() + "")) {
//如果导入文件只有voucher的话,那么就不用删除CustBalance表中当前期间的数据
Boolean isClearCustTb = fileList.length == 1 && fileList[0].toLowerCase().startsWith(VatErpImportValidation.VoucherTbName.toLowerCase()) ? false : true;
//1. 删除TB相关表的数据
financeDataImport.ClearTable(period, isClearCustTb);
}
//2. 删除ValidationInfo中Erp相关的数据
financeDataImport.DeleteErpValidation();
//3. 开始导入数据
for (String f : fileList) {
String fileFullPath = Paths.get(mappedPath, fileGuid + "_" + f).toString();
String schemaPath = "~/Resource";
toDeleteFilesPath.add(fileFullPath);
ImportDataDto importResult = financeDataImport.ImportData(projectYear, importMethod, importType, period, fileFullPath, f, schemaPath, userId);
if (importResult.Result) {
importFileCount++;
} else {
importResults.add(importResult);
}
}
if (importFileCount == fileList.length) {
financeDataImport.UpdateCompanyBalanceNullValue();
result.setResult(true);
result.setResultMsg("");
result.setData(importResults);
toDeleteFilesPath.forEach(f ->
{
if (new File(f).exists()) {
new File(f).delete();
logger.info("成功删除财务数据导入文件:" + f);
}
});
} else {
result.setResult(false);
result.setData(importResults);
String msg = "导入数据出错: " + "\r\n";
for (ImportDataDto m : importResults)
msg += (m.FileName + "\r\n");
result.setResultMsg(msg);
}
return ResponseEntity.ok(result);
}
private Boolean IsSameFileExtenstion(Map<String, MultipartFile> files) {
Set<String> extension = new HashSet<>();
for (MultipartFile file : files.values()) {
extension.add(file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()));
}
if (extension.size() == 1) {
return true;
} else {
return false;
}
}
private String getExtension(Map<String, MultipartFile> files) {
MultipartFile file = files.values().stream().findFirst().get();
return file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
}
private String SetUploadFolderPath(String importMethod, String fileExtension) {
String folderPath = "";
if (importMethod == ImportMethod_OneClick) {
folderPath = OneClickUploadPath;
} else {
if (fileExtension == "csv") {
folderPath = UniversalUploadCsvPath;
}
if (fileExtension == "xls" || fileExtension == "xlsx") {
folderPath = UniversalUploadExcelPath;
}
}
return folderPath;
}
private Boolean SaveFile(MultipartFile file, String mappedPath, String fileFullPath) {
Map<String, String> error = new HashMap<>();
try {
if (!new File(mappedPath).exists()) {
new File(mappedPath).mkdirs();
}
SaveAs(file, fileFullPath);
} catch (Exception ex) {
return false;
}
return true;
}
private void SaveAs(MultipartFile file, String fileFullPath) {
try (FileOutputStream fos = new FileOutputStream(new File(fileFullPath));
InputStream inputStream = file.getInputStream();) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
fos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.controller;
import com.google.errorprone.annotations.FormatString;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RestController;
import pwc.taxtech.atms.dto.vatdto.ImportVoucherDto;
import pwc.taxtech.atms.dto.vatdto.QueryJeDto;
import pwc.taxtech.atms.service.IdentityService;
import pwc.taxtech.atms.vat.service.impl.JournalEntryImportServiceImpl;
@RestController
@RequestMapping(value = "/api/v1/journalEntryImport")
public class JournalEntryImportController {
@Autowired
private JournalEntryImportServiceImpl journalEntryDataImportService;
@Autowired
private IdentityService identityService;
@ApiOperation(value = "queryJournalEntryData", notes = "")
@RequestMapping(value = "/queryJournalEntryData", method = RequestMethod.POST)
public ResponseEntity queryJournalEntryData(@RequestBody QueryJeDto queryJeDto) {
return ResponseEntity.ok(journalEntryDataImportService.qeryJournalEntryData(queryJeDto));
}
@ApiOperation(value = "getValidationInfo", notes = "")
@RequestMapping(value = "getValidationInfo/{type}/{period}", method = RequestMethod.GET)
public ResponseEntity getValidationInfo(@PathVariable Integer type, @PathVariable Integer period) {
return ResponseEntity.ok(journalEntryDataImportService.getValidationInfoList(type, period));
}
@RequestMapping(value = "importJournalEntry", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity ImportJournalEntryData(@RequestBody ImportVoucherDto importParam) {
journalEntryDataImportService.ImportJournalEntryData(importParam.VoucherList, importParam.ImportType,
identityService.getIdentityUser().getId());
return ResponseEntity.ok().build();
}
@RequestMapping(value = "importAuditAdjust/{period}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity ImportAuditAdjust(@RequestBody ImportVoucherDto importParam, @PathVariable Integer period) {
return ResponseEntity.ok().body(journalEntryDataImportService.ImportAuditAdjust(importParam.VoucherList,
period, importParam.ImportType, identityService.getIdentityUser().getId()));
}
@RequestMapping(value = "getAuditAdjust/{period}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity GetAuditAdjust(@PathVariable Integer period) {
return ResponseEntity.ok().body(journalEntryDataImportService.GetAuditAdjust(period));
}
@RequestMapping(value = "queryAuditAdjust", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity QueryAuditAdjust(QueryJeDto queryDto) {
return ResponseEntity.ok().body(journalEntryDataImportService.QueryAuditAdjust(queryDto));
}
}
package pwc.taxtech.atms.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RestController;
import pwc.taxtech.atms.constant.enums.VoucherSearchEnum;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.QueryVoucherParmDto;
import pwc.taxtech.atms.dto.vatdto.VatEnterpriseAccountDto;
import pwc.taxtech.atms.vat.service.TBDataImportService;
import pwc.taxtech.atms.vat.service.VoucherService;
import java.util.List;
@RequestMapping(value = "api/v1/voucher")
@RestController
public class VoucherController {
@Autowired
VoucherService voucherService;
@Autowired
TBDataImportService tbDataImportService;
private static final Logger logger = LoggerFactory.getLogger(VoucherController.class);
@RequestMapping(value = "voucherSelectAdvancedByEntry", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public OperationResultDto<Object> voucherSelectAdvancedByEntry(@RequestBody QueryVoucherParmDto parmDto) {
try {
return voucherService.voucherSelectAdvancedByEntry(parmDto.getListQueryCondition(), VoucherSearchEnum.values()[parmDto.getMainRelation()], parmDto.isAllJe(), parmDto.getPagingInfo());
} catch (Exception ex) {
logger.error("voucherSelectAdvancedByEntryError", ex);
}
OperationResultDto<Object> result = new OperationResultDto<>();
result.setResult(false);
return result;
}
@RequestMapping(value = "voucherSelectAdvancedCount", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public OperationResultDto<Object> voucherSelectAdvancedCount(@RequestBody QueryVoucherParmDto parmDto) {
try {
return voucherService.voucherSelectAdvancedCount(parmDto.getListQueryCondition(), VoucherSearchEnum.values()[parmDto.getMainRelation()], parmDto.isEntryShow(), parmDto.isAllJe());
} catch (Exception ex) {
logger.error("voucherSelectAdvancedCountError", ex);
}
OperationResultDto<Object> result = new OperationResultDto<>();
result.setResult(false);
return result;
}
@RequestMapping(value = "getEnterpriseAccount",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<VatEnterpriseAccountDto> getEnterpriseAccount(){
return tbDataImportService.getEnterpriseAccount();
}
@RequestMapping(value = "voucherSelectAdvancedByVoucher", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public OperationResultDto<Object> voucherSelectAdvancedByVoucher(QueryVoucherParmDto parmDto)
{
try {
return voucherService.voucherSelectAdvancedByVoucher(parmDto.getListQueryCondition(), VoucherSearchEnum.values()[parmDto.getMainRelation()], parmDto.isAllJe(), parmDto.getPagingInfo());
} catch (Exception ex) {
logger.error("voucherSelectAdvancedByVoucherError", ex);
}
OperationResultDto<Object> result = new OperationResultDto<>();
result.setResult(false);
return result;
}
}
package pwc.taxtech.atms.dto.vatdto;
import java.util.List;
public class ImportVoucherDto {
public List<VoucherDtoOnlyForImport> VoucherList;
public Integer ImportType;
}
package pwc.taxtech.atms.dto.vatdto;
import java.math.BigDecimal;
import java.util.List;
public class QueryVoucherDto {
private List<VoucherDto> voucherList;
//凭证总数
private int vidCount;
//分录总数
private int itemIdCount;
private BigDecimal debitSum;
private BigDecimal creditSum;
public List<VoucherDto> getVoucherList() {
return voucherList;
}
public void setVoucherList(List<VoucherDto> voucherList) {
this.voucherList = voucherList;
}
public int getVidCount() {
return vidCount;
}
public void setVidCount(int vidCount) {
this.vidCount = vidCount;
}
public int getItemIdCount() {
return itemIdCount;
}
public void setItemIdCount(int itemIdCount) {
this.itemIdCount = itemIdCount;
}
public BigDecimal getDebitSum() {
return debitSum;
}
public void setDebitSum(BigDecimal debitSum) {
this.debitSum = debitSum;
}
public BigDecimal getCreditSum() {
return creditSum;
}
public void setCreditSum(BigDecimal creditSum) {
this.creditSum = creditSum;
}
}
package pwc.taxtech.atms.dto.vatdto;
import org.thymeleaf.util.StringUtils;
import pwc.taxtech.atms.vat.entity.Voucher;
import java.math.BigDecimal;
import java.util.Date;
public class VoucherDto {
private String voucherId;
private String vid;
private Date date;
//private String GroupNum ;
private String group;
private Integer period;
private String customerCode;
private String customerName;
private String summary;
private String acctCode;
private BigDecimal debit;
private BigDecimal credit;
private BigDecimal debitQty;
private BigDecimal creditQty;
private Long attach;
private Long itemId;
private Integer status;
private Date createdTime;
private Integer isManual;
private Integer manualUser;
private Date manualTime;
private String stdCode;
private String mappingReason;
private Integer mappingUser;
private Date mappingTime;
private String manualReason;
private String foreignCurrency;
private BigDecimal foreignDebit;
private BigDecimal foreignCredit;
private String checkedBy;
private String issuedBy;
private String bookedBy;
private String cashier;
/**
* 是否被凭证重分类过
*/
private Boolean isRecate;
private Integer originalPeriod;
private String acctCodeAndNameShow; //界面显示
private String customerCodeAndNameShow; //界面显示
private String stdCodeAndNameShow; //界面显示
private String groupShow; //界面显示
private int vIdCount;//凭证总数
private int itemIdCount;//分录总数
private BigDecimal debitSum;
private BigDecimal creditSum;
private int auditCount;//审计调整总数
public String getVoucherId() {
return voucherId;
}
public void setVoucherId(String voucherId) {
this.voucherId = voucherId;
}
public String getvId() {
return vid;
}
public void setvId(String vid) {
this.vid = vid;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Integer getPeriod() {
return period;
}
public void setPeriod(Integer period) {
this.period = period;
}
public String getCustomerCode() {
return customerCode;
}
public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getAcctCode() {
return acctCode;
}
public void setAcctCode(String acctCode) {
this.acctCode = acctCode;
}
public BigDecimal getDebit() {
return debit;
}
public void setDebit(BigDecimal debit) {
this.debit = debit;
}
public BigDecimal getCredit() {
return credit;
}
public void setCredit(BigDecimal credit) {
this.credit = credit;
}
public BigDecimal getDebitQty() {
return debitQty;
}
public void setDebitQty(BigDecimal debitQty) {
this.debitQty = debitQty;
}
public BigDecimal getCreditQty() {
return creditQty;
}
public void setCreditQty(BigDecimal creditQty) {
this.creditQty = creditQty;
}
public Long getAttach() {
return attach;
}
public void setAttach(Long attach) {
this.attach = attach;
}
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Integer getIsManual() {
return isManual;
}
public void setIsManual(Integer isManual) {
this.isManual = isManual;
}
public Integer getManualUser() {
return manualUser;
}
public void setManualUser(Integer manualUser) {
this.manualUser = manualUser;
}
public Date getManualTime() {
return manualTime;
}
public void setManualTime(Date manualTime) {
this.manualTime = manualTime;
}
public String getStdCode() {
return stdCode;
}
public void setStdCode(String stdCode) {
this.stdCode = stdCode;
}
public String getMappingReason() {
return mappingReason;
}
public void setMappingReason(String mappingReason) {
this.mappingReason = mappingReason;
}
public Integer getMappingUser() {
return mappingUser;
}
public void setMappingUser(Integer mappingUser) {
this.mappingUser = mappingUser;
}
public Date getMappingTime() {
return mappingTime;
}
public void setMappingTime(Date mappingTime) {
this.mappingTime = mappingTime;
}
public String getManualReason() {
return manualReason;
}
public void setManualReason(String manualReason) {
this.manualReason = manualReason;
}
public String getForeignCurrency() {
return foreignCurrency;
}
public void setForeignCurrency(String foreignCurrency) {
this.foreignCurrency = foreignCurrency;
}
public BigDecimal getForeignDebit() {
return foreignDebit;
}
public void setForeignDebit(BigDecimal foreignDebit) {
this.foreignDebit = foreignDebit;
}
public BigDecimal getForeignCredit() {
return foreignCredit;
}
public void setForeignCredit(BigDecimal foreignCredit) {
this.foreignCredit = foreignCredit;
}
public String getCheckedBy() {
return checkedBy;
}
public void setCheckedBy(String checkedBy) {
this.checkedBy = checkedBy;
}
public String getIssuedBy() {
return issuedBy;
}
public void setIssuedBy(String issuedBy) {
this.issuedBy = issuedBy;
}
public String getBookedBy() {
return bookedBy;
}
public void setBookedBy(String bookedBy) {
this.bookedBy = bookedBy;
}
public String getCashier() {
return cashier;
}
public void setCashier(String cashier) {
this.cashier = cashier;
}
public Boolean getRecate() {
return isRecate;
}
public void setRecate(Boolean recate) {
isRecate = recate;
}
public Integer getOriginalPeriod() {
return originalPeriod;
}
public void setOriginalPeriod(Integer originalPeriod) {
this.originalPeriod = originalPeriod;
}
public String getAcctCodeAndNameShow() {
return acctCodeAndNameShow;
}
public void setAcctCodeAndNameShow(String acctCodeAndNameShow) {
this.acctCodeAndNameShow = acctCodeAndNameShow;
}
public String getCustomerCodeAndNameShow() {
return customerCodeAndNameShow;
}
public void setCustomerCodeAndNameShow(String customerCodeAndNameShow) {
this.customerCodeAndNameShow = customerCodeAndNameShow;
}
public String getStdCodeAndNameShow() {
return stdCodeAndNameShow;
}
public void setStdCodeAndNameShow(String stdCodeAndNameShow) {
this.stdCodeAndNameShow = stdCodeAndNameShow;
}
public String getGroupShow() {
return groupShow;
}
public void setGroupShow(String groupShow) {
this.groupShow = groupShow;
}
public int getvIdCount() {
return vIdCount;
}
public void setvIdCount(int vIdCount) {
this.vIdCount = vIdCount;
}
public int getItemIdCount() {
return itemIdCount;
}
public void setItemIdCount(int itemIdCount) {
this.itemIdCount = itemIdCount;
}
public BigDecimal getDebitSum() {
return debitSum;
}
public void setDebitSum(BigDecimal debitSum) {
this.debitSum = debitSum;
}
public BigDecimal getCreditSum() {
return creditSum;
}
public void setCreditSum(BigDecimal creditSum) {
this.creditSum = creditSum;
}
public int getAuditCount() {
return auditCount;
}
public void setAuditCount(int auditCount) {
this.auditCount = auditCount;
}
public VoucherDto extractFromVoucher(Voucher v) {
setVoucherId(v.getVoucherId());
setvId(v.getVid());
setDate(v.getDate());
setGroup(v.getGroup());
setPeriod(v.getPeriod());
setCustomerCode(v.getCustomerCode());
setCustomerName(v.getCustomerName());
setSummary(v.getSummary());
setAcctCode(v.getAcctCode());
setDebit(v.getDebit());
setCredit(v.getCredit());
setAttach(v.getAttach());
if (v.getItemId() != null)
setItemId(Long.parseLong(v.getItemId()));
setCreatedTime(v.getCreateTime());
setOriginalPeriod(v.getOriginalPeriod());
setStatus(v.getStatus());
setStdCode(v.getStdCode());
setMappingReason(v.getMappingReason());
if (!StringUtils.isEmpty(v.getMappingReason()))
setMappingUser(Integer.valueOf(v.getMappingUser()));
setMappingTime(v.getMappingTime());
return this;
}
}
package pwc.taxtech.atms.dto.vatdto;
import pwc.taxtech.atms.vat.entity.Voucher;
import java.math.BigDecimal;
import java.util.Date;
public class VoucherDtoOnlyForImport {
public String VoucherId;
public String vid;
public Date date;
public String Group;
public Integer Period;
public String CustomerCode;
public String CustomerName;
public String Summary;
public String AcctCode;
public BigDecimal Debit;
public BigDecimal Credit;
public Long Attach;
public String ItemId;
public Date CreateTime;
public Integer ImportType;
public String CreatorId;
public Integer MonthId;
public Integer OriginalPeriod;
public Integer Status;
public Integer PartBilledPeriod;
public Integer BilledPeriod;
public Integer getPeriod() {
return Period;
}
public Voucher extractVoucher() {
Voucher voucher = new Voucher();
voucher.setVoucherId(VoucherId);
voucher.setVid(vid);
voucher.setDate(date);
voucher.setGroup(Group);
voucher.setPeriod(Period);
voucher.setCustomerCode(CustomerCode);
voucher.setCustomerName(CustomerName);
voucher.setSummary(Summary);
voucher.setAcctCode(AcctCode);
voucher.setDebit(Debit);
voucher.setCredit(Credit);
voucher.setAttach(Attach);
voucher.setItemId(ItemId);
voucher.setCreateTime(CreateTime);
voucher.setImportType(ImportType);
voucher.setCreatorId(CreatorId);
voucher.setMonthId(MonthId);
voucher.setOriginalPeriod(OriginalPeriod);
voucher.setStatus(Status);
voucher.setPartBilledPeriod(PartBilledPeriod);
voucher.setBilledPeriod(BilledPeriod);
return voucher;
}
}
package pwc.taxtech.atms.vat.dao;
import java.util.List;
public class DataImportModel {
private List<String> sheetNameList;
private List<List<String>> dataList;
private List<String> mappingResult;
private int selectedSheetIndex;
private int lastRowIndex;
private Boolean result;
private String resultMsg;
public List<String> getSheetNameList() {
return sheetNameList;
}
public void setSheetNameList(List<String> sheetNameList) {
this.sheetNameList = sheetNameList;
}
public List<List<String>> getDataList() {
return dataList;
}
public void setDataList(List<List<String>> dataList) {
this.dataList = dataList;
}
public List<String> getMappingResult() {
return mappingResult;
}
public void setMappingResult(List<String> mappingResult) {
this.mappingResult = mappingResult;
}
public int getSelectedSheetIndex() {
return selectedSheetIndex;
}
public void setSelectedSheetIndex(int selectedSheetIndex) {
this.selectedSheetIndex = selectedSheetIndex;
}
public int getLastRowIndex() {
return lastRowIndex;
}
public void setLastRowIndex(int lastRowIndex) {
this.lastRowIndex = lastRowIndex;
}
public Boolean getResult() {
return result;
}
public void setResult(Boolean result) {
this.result = result;
}
public String getResultMsg() {
return resultMsg;
}
public void setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
}
}
package pwc.taxtech.atms.vat.service;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.vat.entity.CellComment;
import java.util.List;
import java.util.Optional;
public interface CellCommentService {
OperationResultDto<List<CellComment>> getCellComments(Optional<Long> cellDataId);
}
package pwc.taxtech.atms.vat.service;
import pwc.taxtech.atms.dto.vatdto.VatEnterpriseAccountDto;
import pwc.taxtech.atms.vat.dpo.TrialBalanceDto;
import pwc.taxtech.atms.vat.entity.VatEnterpriseAccount;
import java.util.List;
public interface TBDataImportService {
List<TrialBalanceDto> getTrialBalanceData(int fromPeriod, int toPeriod);
List<TrialBalanceDto> getTrialBalanceStdData(int fromPeriod, int toPeriod);
List<VatEnterpriseAccountDto> getEnterpriseAccount();
List<VatEnterpriseAccountDto> getStandardAccount();
}
package pwc.taxtech.atms.vat.service;
import pwc.taxtech.atms.constant.enums.VoucherSearchEnum;
import pwc.taxtech.atms.dpo.PagingDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.QueryConditionDto;
import java.util.List;
public interface VoucherService {
/**
* 按分录显示查询
*
* @param listQueryCondition 查询条件模板
* @param mainRelation 查询条件之间的逻辑关系
* @param allJe 显示全部凭证
* @param pagingInfo 分页信息
* @return 分录信息
*/
OperationResultDto<Object> voucherSelectAdvancedByEntry(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum mainRelation, boolean allJe, PagingDto pagingInfo) throws Exception;
/**
* 根据满足查询条件返回总数
*
* @param listQueryCondition 查询条件模板
* @param mainRelation 查询条件之间的逻辑关系
* @param isEntryShow 是否为分录显示
* @param allJe 显示全部凭证
* @return 满足条件的总条数
*/
OperationResultDto<Object> voucherSelectAdvancedCount(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum mainRelation, boolean isEntryShow, boolean allJe) throws Exception;
/**
* 按凭证显示查询
*
* @param listQueryCondition 查询条件模板
* @param mainRelation 查询条件之间的逻辑关系
* @param allJe 显示全部凭证
* @param pagingInfo 分页信息
* @return 凭证信息
*/
OperationResultDto<Object> voucherSelectAdvancedByVoucher(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum voucherSearchEnum, boolean allJe, PagingDto pagingInfo) throws Exception;
}
......@@ -4,14 +4,12 @@ import org.springframework.stereotype.Service;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.vat.entity.CellComment;
import pwc.taxtech.atms.vat.entity.CellCommentExample;
import pwc.taxtech.atms.vat.service.CellCommentService;
import java.util.List;
import java.util.Optional;
@Service
public class CellCommentServiceImpl extends VatAbstractService implements CellCommentService {
@Override
public class CellCommentServiceImpl extends VatAbstractService {
public OperationResultDto<List<CellComment>> getCellComments(Optional<Long> cellDataId) {
OperationResultDto resultDto = new OperationResultDto();
try {
......
package pwc.taxtech.atms.vat.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.constant.enums.EnumTbImportType;
import pwc.taxtech.atms.constant.enums.EnumValidationType;
import pwc.taxtech.atms.dto.FieldsMapper;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.CustomsInvoiceDto;
import pwc.taxtech.atms.vat.dao.ValidationInfoMapper;
import pwc.taxtech.atms.vat.entity.CustomsInvoice;
import pwc.taxtech.atms.vat.entity.CustomsInvoiceExample;
import pwc.taxtech.atms.vat.entity.ValidationInfo;
import pwc.taxtech.atms.vat.entity.ValidationInfoExample;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Service
public class CustomsInvoiceServiceImpl extends VatAbstractService {
@Autowired
private ValidationInfoMapper validationInfoMapper;
public List<CustomsInvoiceDto> getCustomsInvoicesByPeriodIds(int fromPeriod, int toPeriod) {
CustomsInvoiceExample example = new CustomsInvoiceExample();
example.setOrderByClause(" PayNum");
example.createCriteria().andPeriodIdBetween(fromPeriod, toPeriod);
List<CustomsInvoiceDto> result = new ArrayList<>();
customsInvoiceMapper.selectByExample(example).forEach(a -> {
CustomsInvoiceDto dto = new CustomsInvoiceDto();
CommonUtils.copyProperties(a, dto);
result.add(dto);
});
int seqNo = 1;
DecimalFormat df = new DecimalFormat("#.00");
for (CustomsInvoiceDto dto : result) {
dto.setSeqNo(seqNo++);
if (dto.getInvoiceAmount() != null) {
dto.setInvoiceAmount(new BigDecimal(df.format(dto.getInvoiceAmount())));
}
if (dto.getInvoiceTaxAmount() != null) {
dto.setInvoiceTaxAmount(new BigDecimal(df.format(dto.getInvoiceTaxAmount())));
}
}
return result;
}
public List<CustomsInvoiceDto> getCustomsInvoicesByPeriodId(Integer periodId) {
CustomsInvoiceExample example = new CustomsInvoiceExample();
example.createCriteria().andPeriodIdEqualTo(periodId);
List<CustomsInvoice> result = customsInvoiceMapper.selectByExample(example);
result.sort(Comparator.comparing(CustomsInvoice::getPayNum));
int seqNo = 1;
List<CustomsInvoiceDto> dtos = new ArrayList<>(result.size());
for (CustomsInvoice ci : result) {
CustomsInvoiceDto dto = new CustomsInvoiceDto();
try {
FieldsMapper.map(ci, dto);
dto.setSeqNo(seqNo++);
dto.setInvoiceAmount(ci.getInvoiceAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
dto.setInvoiceTaxAmount(ci.getInvoiceTaxAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return dtos;
}
public OperationResultDto<List<ValidationInfo>> getCustomsInvoicesValidates(Integer periodId) {
ValidationInfoExample example = new ValidationInfoExample();
List<ValidationInfo> result = new ArrayList<>();
if (periodId == null) {
example.createCriteria().andImportTypeIdEqualTo(EnumValidationType.CustomInvoice.getCode());
result = validationInfoMapper.selectByExample(example);
} else {
example.createCriteria().andImportTypeIdEqualTo(EnumValidationType.CustomInvoice.getCode()).andPeriodIdEqualTo(periodId);
result.addAll(validationInfoMapper.selectByExample(example));
example.createCriteria().andImportTypeIdEqualTo(EnumValidationType.CustomInvoice.getCode()).andPeriodIdIsNull();
result.addAll(validationInfoMapper.selectByExample(example));
}
OperationResultDto<List<ValidationInfo>> resultOpt = new OperationResultDto<>();
resultOpt.setResult(true);
resultOpt.setResultMsg("");
resultOpt.setData(result);
return resultOpt;
}
public OperationResultDto ImportCustomsInvoice(List<CustomsInvoice> custList, int importType, String userId) {
try {
int periodId = 0;
if (importType == EnumTbImportType.CoverImport.getCode()) {
periodId = custList.get(0).getPeriodId().intValue();
CustomsInvoiceExample example = new CustomsInvoiceExample();
example.createCriteria().andPeriodIdEqualTo(periodId);
customsInvoiceMapper.deleteByExample(example);
}
custList.forEach(c -> {
c.setCreatorId(userId);
});
custList.forEach(m -> customsInvoiceMapper.insert(m));
// UpdateCustomsInvoiceValidation(userId, periodId);//todo:[validation] to be continue (neo)
return new OperationResultDto(true, "");
} catch (Exception ex) {
return new OperationResultDto(false, ex.getMessage());
}
}
}
package pwc.taxtech.atms.vat.service.impl;
import com.alibaba.fastjson.JSON;
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.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.constant.enums.EnumValidationType;
import pwc.taxtech.atms.constant.enums.ErpCheckType;
import pwc.taxtech.atms.constant.enums.ImageType;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.DataCheckDto;
import pwc.taxtech.atms.dto.vatdto.ImportDataDto;
import pwc.taxtech.atms.dto.vatdto.VoucherDto;
import pwc.taxtech.atms.vat.dao.ValidationInfoMapper;
import pwc.taxtech.atms.vat.dao.VoucherMapper;
import pwc.taxtech.atms.vat.dpo.VoucherAccountMto;
import pwc.taxtech.atms.vat.dpo.VoucherBalanceDto;
import pwc.taxtech.atms.vat.entity.ValidationInfo;
import pwc.taxtech.atms.vat.entity.ValidationInfoExample;
import pwc.taxtech.atms.vat.entity.Voucher;
import pwc.taxtech.atms.vat.entity.VoucherExample;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static pwc.taxtech.atms.constant.Constant.*;
import static pwc.taxtech.atms.constant.VATCommon.ReValidate;
import static pwc.taxtech.atms.constant.VATCommon.ValidationExisted;
import static pwc.taxtech.atms.constant.enums.EnumValidationType.ErpBasicCheck;
import static pwc.taxtech.atms.constant.enums.ImageType.Alert;
@Service
public class FinanceDataImportServiceImpl {
@Autowired
private ValidationInfoMapper validationInfoMapper;
@Autowired
private VoucherMapper voucherMapper;
@Autowired
private SqlSessionTemplate dynamicSqlSessionTemplate;
private Logger logger = LoggerFactory.getLogger(FinanceDataImportServiceImpl.class);
public OperationResultDto<List<DataCheckDto>> getBasicValidationResults(String userId) {
Integer number = 1;
List<DataCheckDto> results = new ArrayList<>();
OperationResultDto<List<DataCheckDto>> operationResult = new OperationResultDto<>();
List<ValidationInfo> dtos = getValidationData(ErpBasicCheck.getCode());
if (dtos != null && dtos.size() > 0) {
dtos.forEach(b -> {
DataCheckDto dataCheckDto = new DataCheckDto();
dataCheckDto.setDataCheckType(b.getValidationResult());
dataCheckDto.setImageTypeId(b.getErrorLevel() != null ? b.getErrorLevel() : -1);
dataCheckDto.setTips(b.getValidationTips());
dataCheckDto.setErrorCount(b.getNumber() != null ? b.getNumber() : -1);
dataCheckDto.setErpCheckTypeId(b.getErpCheckTypeId() != null ? b.getErpCheckTypeId() : -1);
dataCheckDto.setValidationDetails(b.getValidationDetails());
results.add(dataCheckDto);
operationResult.setResultMsg(ValidationExisted);
});
} else {
List<VoucherAccountMto> comAcctChks = validationInfoMapper.getCompanyBalanceAcctChecks();
List<VoucherAccountMto> vAcctChks = validationInfoMapper.getVoucherAccountChecks();
List<VoucherBalanceDto> vDebCrdSingleChk = getSingleVoucherCheck();
List<VoucherDto> vEmptyItem = getVoucherEmptyCheck(true, false, false, false, false);
List<VoucherDto> vEmptyGroup = getVoucherEmptyCheck(false, false, true, false, false);
List<VoucherDto> vEmptyAcctCode = getVoucherEmptyCheck(false, false, false, true, false);
List<VoucherDto> vEmptySummary = getVoucherEmptyCheck(false, false, false, false, true);
if (comAcctChks.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_ComBalanceAcctValidate,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(ImageType.Warning, VatErpImportValidation.Const_ComBalanceAcctUnValidate, comAcctChks.size(),
VatErpImportValidation.Const_ComBalanceAcctUnValidate_Tips
, ErpCheckType.ComBalanceAcctUnValidate, 0, JSON.toJSONString(comAcctChks)));
}
if (vAcctChks.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VoucherAcctValidate,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(ImageType.Warning, VatErpImportValidation.Const_VoucherAcctUnValidate, vAcctChks.size(),
VatErpImportValidation.Const_VoucherAcctUnValidate_Tips
, ErpCheckType.VoucherAcctValidate, 0, JSON.toJSONString(vAcctChks)));
}
if (vDebCrdSingleChk.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VSingleDebitCreditValidate,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(Alert, VatErpImportValidation.Const_VSingleDebitCreditUnValidate,
vDebCrdSingleChk.size(), VatErpImportValidation.Const_VSingleDebitCreditUnValidate_Tips
, ErpCheckType.VSingleDebitCreditUnValidate, 0, JSON.toJSONString(vDebCrdSingleChk)));
}
if (vEmptyItem.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VEmptyCheckValidateItemId,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(Alert, VatErpImportValidation.Const_VEmptyCheckUnValidateItemId,
vEmptyItem.size(), VatErpImportValidation.Const_VEmptyCheckUnValidateItemId_Tips
, ErpCheckType.VEmptyCheckUnValidateItemId, 0, JSON.toJSONString(vEmptyItem)));
}
if (vEmptyGroup.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VEmptyCheckValidateGroup,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(Alert, VatErpImportValidation.Const_VEmptyCheckUnValidateGroup,
vEmptyGroup.size(), VatErpImportValidation.Const_VEmptyCheckUnValidateGroup_Tips
, ErpCheckType.VEmptyCheckUnValidateGroup, 0, JSON.toJSONString(vEmptyGroup)));
}
if (vEmptyAcctCode.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VEmptyCheckValidateAcctCode,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(ImageType.Error, VatErpImportValidation.Const_VEmptyCheckUnValidateAcctCode,
vEmptyAcctCode.size(), VatErpImportValidation.Const_VEmptyCheckUnValidateAcctCode_Tips
, ErpCheckType.VEmptyCheckUnValidateAcctCode, 0, JSON.toJSONString(vEmptyAcctCode)));
}
if (vEmptySummary.size() == 0) {
results.add(setDataCheckItem(ImageType.Success, VatErpImportValidation.Const_VEmptyCheckValidateSummary,
0, "", ErpCheckType.Success));
} else {
results.add(setDataCheckItem(Alert, VatErpImportValidation.Const_VEmptyCheckUnValidateSummary,
vEmptySummary.size(), VatErpImportValidation.Const_VEmptyCheckUnValidateSummary_Tips
, ErpCheckType.VEmptyCheckUnValidateSummary, 0, JSON.toJSONString(vEmptySummary)));
}
operationResult.setResultMsg(ReValidate);
convertDataCheckDtoToValidationInfo(results, ErpBasicCheck.getCode(), userId).forEach(m -> {
validationInfoMapper.insert(m);
});
}
results.sort(Comparator.comparing(DataCheckDto::getDataCheckType));
for (DataCheckDto m : results) {
m.setNum(number);
m.setImagePic(setCheckImage(ImageType.fromCode(m.getImageTypeId())));
number++;
}
operationResult.setResult(true);
operationResult.setData(results);
return operationResult;
}
private List<ValidationInfo> convertDataCheckDtoToValidationInfo(List<DataCheckDto> basicItems, int typeId, String userId) {
List<ValidationInfo> results = new ArrayList<>();
basicItems.forEach(item -> {
ValidationInfo vi = new ValidationInfo();
vi.setId(UUID.randomUUID().toString());
vi.setValidationResult(item.getDataCheckType());
vi.setValidationDetails(item.getValidationDetails());
vi.setErrorLevel(item.getImageTypeId());
vi.setValidationTips(item.getTips());
vi.setNumber(item.getErrorCount());
vi.setImportTypeId(typeId);
vi.setErpCheckTypeId(item.getErpCheckTypeId());
vi.setPeriodId(item.getPeriod());
vi.setCreateTime(new Date());
vi.setCreatorId(userId);
});
return results;
}
private String setCheckImage(ImageType imageTypeId) {
String imgbase64 = null;
switch (imageTypeId) {
case Alert:
imgbase64 = imageToBase64ByImagePath(IMAGE_PATH_INFORMATION, IMAGE_FORMART_);
break;
case Error:
imgbase64 = imageToBase64ByImagePath(IMAGE_PATH_ERROR, IMAGE_FORMART_);
break;
case Success:
imgbase64 = imageToBase64ByImagePath(IMAGE_PATH_SUCCESS, IMAGE_FORMART_);
break;
case Warning:
imgbase64 = imageToBase64ByImagePath(IMAGE_PATH_WARN, IMAGE_FORMART_);
break;
}
return imgbase64;
}
private String imageToBase64ByImagePath(String imagPath, String format) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
logger.debug("read image path is {}",imagPath);
BufferedImage bufferedImage = ImageIO.read(new File(imagPath));
ImageIO.write(bufferedImage, format, outputStream);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outputStream.toByteArray());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException("read image some error");//TODO:should be replace some exception filter(neo)
}
private DataCheckDto setDataCheckItem(ImageType imageType, String type, int count, String tips,
ErpCheckType checkType, int periodId, String validationDetails) {
DataCheckDto rawData = new DataCheckDto();
rawData.setImageTypeId(imageType.getCode());
rawData.setDataCheckType(type);
rawData.setErrorCount(count);
rawData.setTips(tips);
rawData.setPeriod(periodId);
rawData.setErpCheckTypeId(checkType.getCode());
rawData.setValidationDetails(validationDetails);
return rawData;
}
private DataCheckDto setDataCheckItem(ImageType imageType, String type, int count, String tips,
ErpCheckType checkType) {
DataCheckDto rawData = new DataCheckDto();
rawData.setImageTypeId(imageType.getCode());
rawData.setDataCheckType(type);
rawData.setErrorCount(count);
rawData.setTips(tips);
rawData.setPeriod(0);
rawData.setErpCheckTypeId(checkType.getCode());
rawData.setValidationDetails(null);
return rawData;
}
private List<VoucherDto> getVoucherEmptyCheck(boolean itemId, boolean period, boolean group, boolean acctCode, boolean summary) {
VoucherExample example = new VoucherExample();
if (itemId) {
example.createCriteria().andItemIdIsNotNull();
if (voucherMapper.countByExample(example) > 0) {
example.createCriteria().andItemIdIsNull();
}
} else if (period) {
example.createCriteria().andPeriodIsNull();
} else if (group) {
example.createCriteria().andGroupIsNull();
} else if (acctCode) {
example.createCriteria().andAcctCodeIsNull();
} else if (summary) {
example.createCriteria().andSummaryIsNull();
}
List<Voucher> vouchers = voucherMapper.selectByExample(example);
if (vouchers != null && !vouchers.isEmpty()) {
List<VoucherDto> dtos = new ArrayList<>(vouchers.size());
vouchers.forEach(m -> {
dtos.add(new VoucherDto().extractFromVoucher(m));
});
return dtos;
}
return new ArrayList<>();
}
private List<VoucherBalanceDto> getSingleVoucherCheck() {
List<VoucherBalanceDto> vouchers = validationInfoMapper.getSingleVoucherCheck();
if (vouchers != null && !vouchers.isEmpty()) {
List<VoucherBalanceDto> parentVouchers = vouchers.stream().filter(dto -> dto.getCustomerCode() == null ||
dto.getCustomerCode().isEmpty()).collect(Collectors.toList());
parentVouchers.forEach(m -> {
List<VoucherBalanceDto> children = parentVouchers.stream().filter(dto -> m.getVid().equals(dto.getVid())
&& m.getPeriod().intValue() == dto.getPeriod().intValue()
&& m.getGroup().equals(dto.getGroup()) && dto.getCustomerCode() != null
&& !dto.getCustomerCode().isEmpty()).collect(Collectors.toList());
children.sort(Comparator.comparing(VoucherBalanceDto::getItemId));
m.setChildren(children);
});
// parentVouchers.sort(Comparator.comparing(VoucherBalanceDto::getAcctCode));
// parentVouchers.sort(Comparator.comparing(VoucherBalanceDto::getvId));
// parentVouchers.sort(Comparator.comparing(VoucherBalanceDto::getGroup));
// parentVouchers.sort(Comparator.comparing(VoucherBalanceDto::getItemId));
return parentVouchers;
}
return new ArrayList<>();
}
//判断ValidationInfo中是否存在typeId的数据
private List<ValidationInfo> getValidationData(Integer typeId, Integer periodId) {
ValidationInfoExample example = new ValidationInfoExample();
if (periodId != null && periodId > 0) {
example.createCriteria().andImportTypeIdEqualTo(typeId.intValue()).andPeriodIdEqualTo(periodId.intValue());
} else example.createCriteria().andImportTypeIdEqualTo(typeId.intValue());
return validationInfoMapper.selectByExample(example);
}
private List<ValidationInfo> getValidationData(Integer typeId) {
return getValidationData(typeId, null);
}
public Boolean ClearTable(int period, Boolean isClearCustTb) {
if (isClearCustTb == null) isClearCustTb = true;
ClearCustTable(period, VatErpImportValidation.CompanyBalanceTbName);
if (isClearCustTb) {
ClearCustTable(period, VatErpImportValidation.CustBalanceTb);
}
ClearCustTable(period, VatErpImportValidation.BalanceTb);
ClearVoucherTable(period);
ClearRemapTable(period);
return true;
}
private void ClearVoucherTable(int period) {
String command = IsImportByPeriod(period)
? "DELETE FROM " + VatErpImportValidation.VoucherTbName + " WHERE Period = " + period
: "TRUNCATE TABLE " + VatErpImportValidation.VoucherTbName;
exeCommand(command);
}
private boolean IsImportByPeriod(int period) {
return period >= 0;
}
private void ClearRemapTable(int period) {
String command = IsImportByPeriod(period)
? "DELETE FROM " + VatErpImportValidation.AccountRemapTb + " WHERE Period = " + period
: "TRUNCATE TABLE " + VatErpImportValidation.AccountRemapTb;
exeCommand(command);
}
private void ClearCustTable(int period, String tbName) {
String command = "";
if (IsImportByPeriod(period) && tbName != VatErpImportValidation.BalanceTb) {
if (tbName == VatErpImportValidation.CompanyBalanceTbName) {
command = String.format("DELETE FROM %s WHERE PeriodId = %s", tbName, period);
}
if (tbName == VatErpImportValidation.CustBalanceTb) {
command = String.format("DELETE FROM %s WHERE PeriodId >= %s", tbName, period);
}
} else {
command = "TRUNCATE TABLE " + tbName;
}
exeCommand(command);
}
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));
}
}
public void DeleteErpValidation() {
List<Integer> deleteTypes = Lists.<Integer>newArrayList(EnumValidationType.ErpBasicCheck.getCode(),
EnumValidationType.ErpCorrect.getCode(),
EnumValidationType.ErpDuplicate.getCode());
ValidationInfoExample example = new ValidationInfoExample();
example.createCriteria().andImportTypeIdIn(deleteTypes);
validationInfoMapper.deleteByExample(example);
}
public ImportDataDto ImportData(String projectYear, String importMethod, String importType, Integer period,
String fileFullPath, String f, String schemaPath, String userId) {
logger.info("开始导入数据: importMethod: {0}, importType: {1}", importMethod, importType);
ImportDataDto importResult = new ImportDataDto();
String ZipFileFolder = "";
try {
if (importMethod == VatErpImportValidation.ImportMethod_OneClick) {
// UnZipDataFile(fileFullPath, schemaPath);//todo: import data tobe continue(neo)
// ImportBalance(ZipFileFolder, period);
// ImportVoucher(ZipFileFolder, period);
}
if (importMethod == VatErpImportValidation.ImportMethod_Universal) {
// UniversalImportData(period, fileFullPath, f.getName(), schemaPath);
}
// SynAccountFromTaxAdmin(period, userId);
importResult.Result = true;
} catch (Exception ex) {
importResult.Result = false;
}
return importResult;
}
public void UpdateCompanyBalanceNullValue() {
String command = "UPDATE CompanyBalance SET BegDebitBal = 0 WHERE BegDebitBal IS NULL"
+ " UPDATE CompanyBalance SET BegCreditBal = 0 WHERE BegCreditBal IS NULL"
+ " UPDATE CompanyBalance SET BegBal = 0 WHERE BegBal IS NULL"
+ " UPDATE CompanyBalance SET EndBal = 0 WHERE EndBal IS NULL"
+ " UPDATE CompanyBalance SET EndDebitBal = 0 WHERE EndDebitBal IS NULL"
+ " UPDATE CompanyBalance SET EndCreditBal = 0 WHERE EndCreditBal IS NULL"
+ " UPDATE CompanyBalance SET DebitBal = 0 WHERE DebitBal IS NULL"
+ " UPDATE CompanyBalance SET CreditBal = 0 WHERE CreditBal IS NULL";
exeCommand(command);
}
}
package pwc.taxtech.atms.vat.service.impl;
import com.google.common.collect.Lists;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.common.PagingList;
import pwc.taxtech.atms.constant.Constant;
import pwc.taxtech.atms.constant.DataImport;
import pwc.taxtech.atms.constant.enums.EnumTbImportType;
import pwc.taxtech.atms.constant.enums.EnumValidationType;
import pwc.taxtech.atms.constant.enums.VatImportType;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dpo.PagingDto;
import pwc.taxtech.atms.dto.PagingResultDto;
import pwc.taxtech.atms.dto.vatdto.QueryJeDto;
import pwc.taxtech.atms.dto.vatdto.VoucherDto;
import pwc.taxtech.atms.dto.vatdto.VoucherDtoOnlyForImport;
import pwc.taxtech.atms.vat.dao.JournalEntryImportMapper;
import pwc.taxtech.atms.vat.dao.ValidationInfoMapper;
import pwc.taxtech.atms.vat.dao.VoucherMapper;
import pwc.taxtech.atms.vat.entity.ValidationInfo;
import pwc.taxtech.atms.vat.entity.ValidationInfoExample;
import pwc.taxtech.atms.vat.entity.Voucher;
import pwc.taxtech.atms.vat.entity.VoucherExample;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import static pwc.taxtech.atms.constant.Constant.WholeYear;
@Service
public class JournalEntryImportServiceImpl {
@Autowired
JournalEntryImportMapper journalEntryImportMapper;
@Autowired
ValidationInfoMapper validationInfoMapper;
private final static String _tableName = "Voucher";
private final static String _validationTableName = "ValidationInfo";
@Autowired
private VoucherMapper voucherMapper;
public PagingResultDto<VoucherDto> qeryJournalEntryData(QueryJeDto queryJeDto) {
PagingResultDto<VoucherDto> qResult = new PagingResultDto<VoucherDto>();
qResult.setPageInfo(queryJeDto.getPageInfo());
qResult.setList(new ArrayList<>());
qResult.setCalculateData(new VoucherDto());
List<Voucher> pageResultList = journalEntryImportMapper.pageQuery(VatImportType.JournalEntry.getCode(),
queryJeDto.getPeriodId(), (queryJeDto.getPageInfo().getPageIndex()-1) * queryJeDto.getPageInfo().getPageSize(),
queryJeDto.getPageInfo().getPageSize());
Integer pageCount = journalEntryImportMapper.pageQueryCount(VatImportType.JournalEntry.getCode(),
queryJeDto.getPeriodId());
Integer vIdCount = journalEntryImportMapper.pageVidCount(VatImportType.JournalEntry.getCode(),
queryJeDto.getPeriodId());
//查询结果总数
qResult.getPageInfo().setTotalCount(pageCount);
//分录总数
qResult.getCalculateData().setItemIdCount(pageCount == null ? 0 : pageCount);
//凭证总数
qResult.getCalculateData().setvIdCount(vIdCount == null ? 0 : vIdCount);
//所有凭证的借贷方sum
BigDecimal debitSum = new BigDecimal(0);
BigDecimal creditSum = new BigDecimal(0);
int MonthId = 0, Summary = 0;
for (Voucher voucher : pageResultList) {
debitSum.add(voucher.getDebit() != null ? voucher.getDebit() : new BigDecimal(0));
creditSum.add(voucher.getDebit() != null ? voucher.getCredit() : new BigDecimal(0));
if (voucher.getMonthId() != null) MonthId = 1;
if (voucher.getSummary() != null) Summary = 1;
}
for (Voucher voucher : pageResultList) {
if (voucher.getMonthId() == null && MonthId == 1) voucher.setMonthId(0);
if (voucher.getSummary() == null && Summary == 1) voucher.setSummary("");
qResult.getList().add(new VoucherDto().extractFromVoucher(voucher));
}
return qResult;
}
public List<ValidationInfo> getValidationInfoList(Integer type, Integer period) {
ValidationInfoExample validationInfoExample = new ValidationInfoExample();
if (period.intValue() != WholeYear)
validationInfoExample.createCriteria().andImportTypeIdEqualTo(type).andPeriodIdEqualTo(period);
else validationInfoExample.createCriteria().andImportTypeIdEqualTo(type);
return validationInfoMapper.selectByExample(validationInfoExample);
}
public void ImportJournalEntryData(List<VoucherDtoOnlyForImport> journalEntryList, Integer importType, String userId) {
if (journalEntryList != null && journalEntryList.size() > 0) {
Set<Integer> periods = journalEntryList.stream().collect(Collectors.groupingBy(
VoucherDtoOnlyForImport::getPeriod, Collectors.counting())).keySet();
journalEntryList.forEach(m -> {
m.VoucherId = UUID.randomUUID().toString();
m.CreatorId = userId;
m.CreateTime = new Date();
});
if (importType == EnumTbImportType.CoverImport.getCode()) {
periods.forEach(m -> ClearTableData(m, _tableName));
}
journalEntryList.forEach(m -> voucherMapper.insert(m.extractVoucher()));
// ValidateJournalEntryByPeriods(userId);//todo:[validation] to be continue (neo)
}
}
private void ClearTableData(Integer period, String tableName) {
switch (tableName) {
case _tableName:
VoucherExample example = new VoucherExample();
example.createCriteria().andPeriodEqualTo(period).andImportTypeEqualTo(VatImportType.JournalEntry.getCode());
voucherMapper.deleteByExample(period > 0 ? example : null);
break;
case _validationTableName:
ValidationInfoExample example1 = new ValidationInfoExample();
example1.createCriteria().andPeriodIdEqualTo(period).andImportTypeIdEqualTo(EnumValidationType.JournalEntry.getCode());
validationInfoMapper.deleteByExample(period > 0 ? example1 : null);
}
}
public OperationResultDto<List<OperationResultDto<List<VoucherDtoOnlyForImport>>>> ImportAuditAdjust(List<VoucherDtoOnlyForImport> voucherList,
int period, Integer importType, String userId) {
OperationResultDto<List<OperationResultDto<List<VoucherDtoOnlyForImport>>>> result = new OperationResultDto<>();
result.setResult(true);
int num = 1;
for (VoucherDtoOnlyForImport v : voucherList) {
v.VoucherId = UUID.randomUUID().toString();
v.vid = String.format("%sNO%s", new SimpleDateFormat("MMddHHmmss").format(new Date()), num);
v.Group = v.vid;
num++;
v.CreatorId = userId;
if (v.CreateTime == null) {
v.date = new Date();
v.CreateTime = v.date;
}
v.ImportType = VatImportType.AuditAdjust.getCode();
}
result.setData(new ArrayList<>());
List<VoucherDtoOnlyForImport> emptyItems = voucherList.stream().filter(dto -> StringUtils.isEmptyOrWhitespaceOnly(dto.AcctCode)
|| dto.Credit == null || dto.Debit == null).collect(Collectors.toList());
if (emptyItems.size() > 0) {
result.setResult(false);
OperationResultDto<List<VoucherDtoOnlyForImport>> rr = new OperationResultDto<>();
rr.setData(emptyItems);
rr.setResult(false);
rr.setResultMsg(DataImport.EmptyField);
result.getData().add(rr);
}
emptyItems = voucherList.stream().filter(dto -> (dto.AcctCode != null && dto.AcctCode.length() > 50)
|| (dto.Summary != null && dto.Summary.length() > 500)).collect(Collectors.toList());
if (emptyItems.size() > 0) {
result.setResult(false);
result.setResult(false);
OperationResultDto<List<VoucherDtoOnlyForImport>> rr = new OperationResultDto<>();
rr.setData(emptyItems);
rr.setResult(false);
rr.setResultMsg(DataImport.OverLengthField);
result.getData().add(rr);
}
if (result.getResult()) {
if (importType == EnumTbImportType.CoverImport.getCode()) {
Set<Integer> perods = voucherList.stream().collect(Collectors.groupingBy(VoucherDtoOnlyForImport::getPeriod,
Collectors.counting())).keySet();
VoucherExample example = new VoucherExample();
example.createCriteria().andPeriodIn(Lists.newArrayList(period)).andImportTypeEqualTo(VatImportType.AuditAdjust.getCode());
voucherMapper.deleteByExample(example);
}
voucherList.forEach(m -> voucherMapper.insert(m.extractVoucher()));
}
return result;
}
public List<Voucher> GetAuditAdjust(int period) {
VoucherExample example = new VoucherExample();
example.createCriteria().andPeriodEqualTo(period).andImportTypeEqualTo(VatImportType.AuditAdjust.getCode());
List<Voucher> result = voucherMapper.selectByExample(example);
result.stream().sorted(Comparator.comparing(Voucher::getAcctCode));
return result;
}
public PagingResultDto<Voucher> QueryAuditAdjust(QueryJeDto queryDto) {
PagingResultDto<Voucher> qRsult = new PagingResultDto<>();
qRsult.setPageInfo(queryDto.getPageInfo());
qRsult.setList(new ArrayList<>());
qRsult.setCalculateData(new Voucher());
VoucherExample example = new VoucherExample();
VoucherExample.Criteria criteria = example.createCriteria();
criteria.andImportTypeEqualTo(VatImportType.AuditAdjust.getCode());
if (queryDto.getPeriodId() > Constant.WholeYear) criteria.andPeriodEqualTo(queryDto.getPeriodId());
List<Voucher> query = voucherMapper.selectByExample(example);
if (qRsult.getPageInfo() == null) qRsult.setPageInfo(new PagingDto());
qRsult.getPageInfo().setTotalCount(query.size());
BigDecimal sumDebit = new BigDecimal(0);
BigDecimal sumCredit = new BigDecimal(0);
if (query.size() > 0)
for (Voucher v : query) {
sumDebit = sumDebit.add(v.getDebit());
sumCredit = sumCredit.add(v.getCredit());
}
qRsult.getCalculateData().setDebit(sumDebit);
qRsult.getCalculateData().setCredit(sumCredit);
if (qRsult.getPageInfo().getTotalCount() > 0) {
PagingList pagingList = new PagingList(query, qRsult.getPageInfo());
qRsult.setList(pagingList.getPagingList());
}
return qRsult;
}
}
......@@ -905,9 +905,6 @@ public class ReportServiceImpl extends VatAbstractService implements ReportServi
CellDataSourceType cellDataSourceType = CellDataSourceType.getDSType(dataSourceType);
String result = StringUtils.EMPTY;
switch (cellDataSourceType) {
case Voucher:
result = JSON.toJSONString(voucherMapper.selectVoucherWithEnterpriseAccount());
break;
case OutputInvoice:
result = JSON.toJSONString(outputVATInvoiceMapper.selectOutputInvoiceAndItem());
break;
......@@ -1013,18 +1010,6 @@ public class ReportServiceImpl extends VatAbstractService implements ReportServi
}
}
itemStrValue = JSON.toJSONString(inputVATInvoiceItemExtendDtos);
} else if (dataSource.getType().equals(FormulaDataSourceType.Voucher.getCode())) {
DataSourceDetailExample dataSourceDetailExample = new DataSourceDetailExample();
dataSourceDetailExample.createCriteria().andDataSourceIdEqualTo(datasSourceId).andDataSourceTypeEqualTo(CellDataSourceType.Voucher.getCode());
List<DataSourceDetail> dataSourceDetails = dataSourceDetailMapper.selectByExample(dataSourceDetailExample);
List<Voucher> vouchers = new ArrayList<>();
for (DataSourceDetail dataSourceDetail : dataSourceDetails) {
if (StringUtils.isNotBlank(dataSourceDetail.getItemValue())) {
Voucher voucher = voucherMapper.selectByPrimaryKey(dataSourceDetail.getItemValue());
vouchers.add(voucher);
}
}
itemStrValue = JSON.toJSONString(vouchers);
} else {
itemStrValue = StringUtils.EMPTY;
}
......
package pwc.taxtech.atms.vat.service.impl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.vatdto.VatEnterpriseAccountDto;
import pwc.taxtech.atms.vat.dpo.TrialBalanceDto;
import pwc.taxtech.atms.vat.entity.VatEnterpriseAccount;
import pwc.taxtech.atms.vat.entity.VatEnterpriseAccountExample;
import pwc.taxtech.atms.vat.entity.VatStandardAccount;
import pwc.taxtech.atms.vat.entity.VatStandardAccountExample;
import pwc.taxtech.atms.vat.service.TBDataImportService;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class TBDataImportServiceImpl extends VatAbstractService implements TBDataImportService {
@Override
public List<TrialBalanceDto> getTrialBalanceData(int fromPeriod, int toPeriod) {
long fromMonth = (long) fromPeriod;
long toMonth = (long) toPeriod;
// Map<String, Object> monthMap = new HashMap<>();
// monthMap.put("fromMonth", fromMonth);
// monthMap.put("toMonth", toMonth);
List<TrialBalanceDto> queryList = companyBalanceMapper.companyBalanceLeftJoinEnterpriseAccount(Long.toString(fromMonth), Long.toString(toMonth));
List<TrialBalanceDto> result = new ArrayList<>();
queryList.stream().collect(Collectors.groupingBy(TrialBalanceDto::getAcctCode)).forEach((a, b) -> {
TrialBalanceDto item = b.get(0);
TrialBalanceDto trialBalanceDto = new TrialBalanceDto();
trialBalanceDto.setAcctCode(item.getAcctCode());
trialBalanceDto.setCustomerCode(item.getCustomerCode());
trialBalanceDto.setBegDebitBal(item.getPeriodId() == fromPeriod ? item.getBegDebitBal() : BigDecimal.ZERO);
trialBalanceDto.setBegCreditBal(item.getPeriodId() == fromPeriod ? item.getBegCreditBal() : BigDecimal.ZERO);
trialBalanceDto.setBegBal(item.getPeriodId() == fromPeriod ? item.getBegBal() : BigDecimal.ZERO);
trialBalanceDto.setEndBal(item.getPeriodId() == toPeriod ? item.getEndBal() : BigDecimal.ZERO);
trialBalanceDto.setEndDebitBal(item.getPeriodId() == toPeriod ? item.getEndDebitBal() : BigDecimal.ZERO);
trialBalanceDto.setEndCreditBal(item.getPeriodId() == toPeriod ? item.getEndCreditBal() : BigDecimal.ZERO);
double summaryA = b.stream().mapToDouble(c -> Objects.requireNonNull(c.getDebitBal()).doubleValue()).summaryStatistics().getSum();
trialBalanceDto.setDebitBal(BigDecimal.valueOf(summaryA));
double summaryB = b.stream().mapToDouble(c -> Objects.requireNonNull(c.getCreditBal()).doubleValue()).summaryStatistics().getSum();
trialBalanceDto.setCreditBal(BigDecimal.valueOf(summaryB));
trialBalanceDto.setParentCode(item.getParentCode());
trialBalanceDto.setAccountName(item.getAccountName());
trialBalanceDto.setAcctProp(item.getAcctProp());
trialBalanceDto.setDirection(item.getDirection());
result.add(trialBalanceDto);
});
return result;
}
@Override
public List<TrialBalanceDto> getTrialBalanceStdData(int fromPeriod, int toPeriod) {
long fromMonth = (long) fromPeriod;
long toMonth = (long) toPeriod;
Map<String, Object> monthMap = new HashMap<>();
monthMap.put("fromMonth", fromMonth);
monthMap.put("toMonth", toMonth);
List<TrialBalanceDto> queryList = vatStandardAccountMapper.selectProjectStandardAccountLeftJoinBalanceStdManual(Long.toString(fromMonth), Long.toString(toMonth));
List<TrialBalanceDto> result = new ArrayList<>();
queryList.stream().collect(Collectors.groupingBy(TrialBalanceDto::getAcctCode)).forEach((a, b) -> {
TrialBalanceDto item = b.get(0);
TrialBalanceDto trialBalanceDto = new TrialBalanceDto();
trialBalanceDto.setAcctCode(item.getAcctCode());
trialBalanceDto.setCustomerCode(item.getCustomerCode());
trialBalanceDto.setBegDebitBal(item.getPeriodId() == fromPeriod ? item.getBegDebitBal() : BigDecimal.ZERO);
trialBalanceDto.setBegCreditBal(item.getPeriodId() == fromPeriod ? item.getBegCreditBal() : BigDecimal.ZERO);
trialBalanceDto.setBegBal(item.getPeriodId() == fromPeriod ? item.getBegBal() : BigDecimal.ZERO);
trialBalanceDto.setEndBal(item.getPeriodId() == toPeriod ? item.getEndBal() : BigDecimal.ZERO);
trialBalanceDto.setEndDebitBal(item.getPeriodId() == toPeriod ? item.getEndDebitBal() : BigDecimal.ZERO);
trialBalanceDto.setEndCreditBal(item.getPeriodId() == toPeriod ? item.getEndCreditBal() : BigDecimal.ZERO);
double summaryA = b.stream().mapToDouble(c -> Objects.requireNonNull(c.getDebitBal()).doubleValue()).summaryStatistics().getSum();
trialBalanceDto.setDebitBal(BigDecimal.valueOf(summaryA));
double summaryB = b.stream().mapToDouble(c -> Objects.requireNonNull(c.getCreditBal()).doubleValue()).summaryStatistics().getSum();
trialBalanceDto.setCreditBal(BigDecimal.valueOf(summaryB));
trialBalanceDto.setParentCode(item.getParentCode());
trialBalanceDto.setAccountName(item.getAccountName());
trialBalanceDto.setAcctProp(item.getAcctProp());
trialBalanceDto.setDirection(item.getDirection());
result.add(trialBalanceDto);
});
return result;
}
@Override
public List<VatEnterpriseAccountDto> getEnterpriseAccount() {
List<VatEnterpriseAccount> list = vatEnterpriseAccountMapper.selectByExample(new VatEnterpriseAccountExample());
List<VatEnterpriseAccountDto> resultList = new ArrayList<>();
list.forEach(a -> {
VatEnterpriseAccountDto vatEnterpriseAccountDto = new VatEnterpriseAccountDto();
CommonUtils.copyProperties(a, vatEnterpriseAccountDto);
resultList.add(vatEnterpriseAccountDto);
});
return resultList;
}
@Override
public List<VatEnterpriseAccountDto> getStandardAccount() {
VatStandardAccountExample example = new VatStandardAccountExample();
example.setDistinct(true);
List<VatStandardAccount> vatStandardAccountList = vatStandardAccountMapper.selectByExample(example);
List<VatEnterpriseAccountDto> vatEnterpriseAccountDtoList = new ArrayList<>();
vatStandardAccountList.forEach(a -> {
VatEnterpriseAccountDto vatEnterpriseAccountDto = new VatEnterpriseAccountDto();
vatEnterpriseAccountDto.setAcctCode(a.getCode());
vatEnterpriseAccountDto.setParentCode(StringUtils.isBlank(a.getParentCode()) ? "0" : a.getParentCode());
vatEnterpriseAccountDto.setName(a.getName());
vatEnterpriseAccountDto.setAcctProp(a.getAcctProp());
vatEnterpriseAccountDto.setDirection(a.getDirection());
});
return vatEnterpriseAccountDtoList;
}
@Deprecated
private List<TrialBalanceDto> dealNullValue(List<TrialBalanceDto> dataList) {
int begDebitBal = 0, begCreditBal = 0, begBal = 0, endBal = 0;
int endDebitBal = 0, endCreditBal = 0, debitBal = 0, creditBal = 0, monthId = 0, customerCode = 0;
if (dataList != null && !dataList.isEmpty()) {
if (dataList.stream().anyMatch(a -> a.getMonthId() != null)) {
monthId = 1;
}
if (dataList.stream().anyMatch(a -> StringUtils.isNotBlank(a.getCustomerCode()))) {
customerCode = 1;
}
if (dataList.stream().anyMatch(p -> p.getBegDebitBal() != null)) {
begDebitBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getBegCreditBal() != null)) {
begCreditBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getBegBal() != null)) {
begBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getEndBal() != null)) {
endBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getEndDebitBal() != null)) {
endDebitBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getEndCreditBal() != null)) {
endCreditBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getDebitBal() != null)) {
debitBal = 1;
}
if (dataList.stream().anyMatch(p -> p.getCreditBal() != null)) {
creditBal = 1;
}
for (TrialBalanceDto compbalance : dataList) {
if (compbalance.getMonthId() == null && monthId == 1) {
compbalance.setMonthId(0);
}
if (customerCode == 0) {
compbalance.setCustomerCode(null);
}
if (compbalance.getBegDebitBal() == null && begDebitBal == 1) {
compbalance.setBegDebitBal(BigDecimal.ZERO);
}
if (compbalance.getBegCreditBal() == null && begCreditBal == 1) {
compbalance.setBegCreditBal(BigDecimal.ZERO);
}
if (compbalance.getBegBal() == null && begBal == 1) {
compbalance.setBegBal(BigDecimal.ZERO);
}
if (compbalance.getEndBal() == null && endBal == 1) {
compbalance.setEndBal(BigDecimal.ZERO);
}
if (compbalance.getEndDebitBal() == null && endDebitBal == 1) {
compbalance.setEndDebitBal(BigDecimal.ZERO);
}
if (compbalance.getEndCreditBal() == null && endCreditBal == 1) {
compbalance.setEndCreditBal(BigDecimal.ZERO);
}
if (compbalance.getDebitBal() == null && debitBal == 1) {
compbalance.setDebitBal(BigDecimal.ZERO);
}
if (compbalance.getCreditBal() == null && creditBal == 1) {
compbalance.setCreditBal(BigDecimal.ZERO);
}
}
}
return dataList;
}
}
......@@ -85,7 +85,5 @@ public class VatAbstractService {
public FtpService ftpService;
@Autowired
public CellDataSourceMapper cellDataSourceMapper;
@Autowired
public VoucherMapper voucherMapper;
}
package pwc.taxtech.atms.vat.service.impl;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import pwc.taxtech.atms.constant.VoucherSelect;
import pwc.taxtech.atms.constant.enums.VoucherLevelEnum;
import pwc.taxtech.atms.constant.enums.VoucherSearchEnum;
import pwc.taxtech.atms.dpo.PagingDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.vatdto.QueryConditionDto;
import pwc.taxtech.atms.dto.vatdto.QueryVoucherDto;
import pwc.taxtech.atms.dto.vatdto.QueryVoucherMainDto;
import pwc.taxtech.atms.dto.vatdto.VidCountDto;
import pwc.taxtech.atms.dto.vatdto.VoucherDto;
import pwc.taxtech.atms.dto.vatdto.VoucherMainDto;
import pwc.taxtech.atms.dto.vatdto.VoucherTmplDto;
import pwc.taxtech.atms.vat.service.VoucherService;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class VoucherServiceImpl extends VatAbstractService implements VoucherService {
@Resource(name = "dynamicJdbcTemplate")
JdbcTemplate jdbcTemplate;
@Override
public OperationResultDto<Object> voucherSelectAdvancedByEntry(List<QueryConditionDto> listQueryCondition,
VoucherSearchEnum mainRelation, boolean allJe,
PagingDto pagingInfo) throws Exception {
OperationResultDto<Object> result = new OperationResultDto<>();
StringBuffer exceptionString = new StringBuffer();
String sqlWhere = getSqlWhereCondition(listQueryCondition, mainRelation, allJe, exceptionString);
if (StringUtils.isNotBlank(exceptionString.toString())) {
result.setResult(false);
result.setResultMsg(exceptionString.toString());
return result;
}
String sql = StringUtils.EMPTY;
if (allJe) {
if (pagingInfo != null) {
sql = "SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`GROUP`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"e.`FullName`," +
"`Debit`," +
"`Credit`," +
"TB.`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"e.StdCode," +
"TB.VoucherStd," +
"s.FullName AS StdName" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"c.`Period`," +
"`Date`," +
"c.`GROUP`," +
"`ItemId`," +
"c.`VId`," +
"`Summary`," +
"`Debit`," +
"`Credit`," +
"`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"`StdCode` AS VoucherStd" +
" FROM " +
"(" +
"SELECT DISTINCT" +
"`Period`," +
"`GROUP`," +
"`VId`" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`GROUP`," +
"`VId`" +
" FROM " +
"Voucher " + sqlWhere +
") tbl" +
") abc" +
" LEFT JOIN Voucher c ON abc.`Period` = c.`Period`" +
"AND abc.`GROUP` = c.`GROUP`" +
"AND abc.`VId` = c.`VId`" +
") TB" +
" LEFT JOIN EnterpriseAccount e ON TB.AcctCode = e.AcctCode" +
" LEFT JOIN StandardAccount s ON e.StdCode = s. CODE" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`GROUP`," +
"`VId`" +
"LIMIT " + pagingInfo.getPageSize() * (pagingInfo.getPageIndex() - 1) + "," + pagingInfo.getPageSize();
} else {
sql = "SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`GROUP`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"e.`FullName`," +
"`Debit`," +
"`Credit`," +
"TB.`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"e.StdCode," +
"TB.VoucherStd," +
"s.FullName AS StdName" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"c.`Period`," +
"`Date`," +
"c.`GROUP`," +
"`ItemId`," +
"c.`VId`," +
"`Summary`," +
"`Debit`," +
"`Credit`," +
"`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"`StdCode` AS VoucherStd" +
" FROM " +
"(" +
"SELECT DISTINCT" +
"`Period`," +
"`GROUP`," +
"`VId`" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`GROUP`," +
"`VId`" +
" FROM " +
"Voucher " + sqlWhere +
") tbl" +
") abc" +
" LEFT JOIN Voucher c ON abc.`Period` = c.`Period`" +
"AND abc.`GROUP` = c.`GROUP`" +
"AND abc.`VId` = c.`VId`" +
") TB" +
" LEFT JOIN EnterpriseAccount e ON TB.AcctCode = e.AcctCode" +
" LEFT JOIN StandardAccount s ON e.StdCode = s. CODE" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`GROUP`," +
"`VId`";
}
} else {
if (pagingInfo != null) {
sql = "SELECT " +
"*" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`Group`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"e.`FullName`," +
"`Debit`," +
"`Credit`," +
"TB.`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"e.StdCode," +
"TB.VoucherStd AS VoucherStd," +
"s.FullName AS StdName" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`Group`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"`Debit`," +
"`Credit`," +
"`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"`StdCode` AS VoucherStd" +
" FROM " +
"Voucher" + sqlWhere +
") TB" +
" LEFT JOIN EnterpriseAccount e ON TB.AcctCode = e.AcctCode" +
" LEFT JOIN StandardAccount s ON e.StdCode = s. CODE" +
") RowNumVoucher" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`" +
"LIMIT " + pagingInfo.getPageSize() * (pagingInfo.getPageIndex() - 1) + "," + pagingInfo.getPageSize();
} else {
sql = "SELECT " +
"*" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`Group`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"e.`FullName`," +
"`Debit`," +
"`Credit`," +
"TB.`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"e.StdC.ode," +
"TB.VoucherStd AS VoucherStd," +
"s.FullName AS StdName" +
" FROM " +
"(" +
"SELECT " +
"`VoucherId`," +
"`Period`," +
"`Date`," +
"`Group`," +
"`ItemId`," +
"`VId`," +
"`Summary`," +
"`Debit`," +
"`Credit`," +
"`AcctCode`," +
"`CustomerCode`," +
"`CustomerName`," +
"`StdCode` AS VoucherStd" +
" FROM " +
"Voucher" + sqlWhere +
") TB" +
" LEFT JOIN EnterpriseAccount e ON TB.AcctCode = e.AcctCode" +
" LEFT JOIN StandardAccount s ON e.StdCode = s. CODE" +
") RowNumVoucher" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`";
}
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
List<VoucherDto> voucherDtos = new ArrayList<>();
queryForList.forEach(a -> {
VoucherDto dto = new VoucherDto();
dto.setVoucherId(a.get("VoucherId") == null ? "" : a.get("VoucherId").toString());
dto.setPeriod(Integer.parseInt(a.get("Period") == null ? "" : a.get("Period").toString()));
dto.setDate(DateTime.parse(a.get("Date") == null ? "" : a.get("Date").toString()).toDate());
dto.setGroup(a.get("Group") == null ? "" : a.get("Group").toString());
dto.setvId(a.get("VId") == null ? "" : a.get("VId").toString());
dto.setSummary(a.get("Summary") == null ? "" : a.get("Summary").toString());
dto.setAcctCode(a.get("AcctCode") == null ? "" : a.get("AcctCode").toString());
dto.setDebit(BigDecimal.valueOf(Double.valueOf(a.get("Debit") == null ? "" : a.get("Debit").toString())));
dto.setCredit(BigDecimal.valueOf(Double.valueOf(a.get("Credit") == null ? "" : a.get("Credit").toString())));
dto.setGroupShow(a.get("Group") == null ? "" : a.get("Group").toString() + "-" + a.get("VId") == null ? "" : a.get("VId").toString());
dto.setAcctCodeAndNameShow(a.get("AcctCode") == null ? "" : a.get("AcctCode").toString() + (StringUtils.isNotBlank(a.get("FullName") == null ? "" : a.get("FullName").toString()) ? "/" + a.get("FullName") : null));
dto.setCustomerCode(a.get("CustomerCode") == null ? "" : a.get("CustomerCode").toString());
dto.setCustomerName(a.get("CustomerName") == null ? "" : a.get("CustomerName").toString());
dto.setCustomerCodeAndNameShow(a.get("CustomerCode") == null ? "" : a.get("CustomerCode").toString() + (StringUtils.isNotBlank(a.get("CustomerName") == null ? "" : a.get("CustomerName").toString()) ? "/" + a.get("CustomerName") == null ? "" : a.get("CustomerName").toString() : null));
dto.setStdCodeAndNameShow(a.get("StdCode") == null ? "" : a.get("StdCode").toString() + (StringUtils.isNotBlank(a.get("StdName") == null ? "" : a.get("StdName").toString()) ? "/" + a.get("StdName") == null ? "" : a.get("StdName").toString() : null));
dto.setStdCode(a.get("VoucherStd") == null ? "" : a.get("VoucherStd").toString());
voucherDtos.add(dto);
});
QueryVoucherDto dto = new QueryVoucherDto();
dto.setVoucherList(voucherDtos);
dto.setItemIdCount(voucherDtos.size());
dto.setCreditSum(new BigDecimal(voucherDtos.stream().mapToDouble(a -> a.getCredit().doubleValue()).summaryStatistics().getSum()));
dto.setDebitSum(new BigDecimal(voucherDtos.stream().mapToDouble(a -> a.getDebit().doubleValue()).summaryStatistics().getSum()));
dto.setVidCount((int) voucherDtos.stream().map(a -> new VidCountDto(a.getvId(), a.getGroup(), a.getPeriod())).distinct().count());
result.setResult(true);
result.setData(dto);
}
return result;
}
@Override
public OperationResultDto<Object> voucherSelectAdvancedCount(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum mainRelation, boolean isEntryShow, boolean allJe) throws Exception {
OperationResultDto<Object> result = new OperationResultDto<>();
StringBuffer exceptionString = new StringBuffer(StringUtils.EMPTY);
String sqlWhere = getSqlWhereCondition(listQueryCondition, mainRelation, allJe, exceptionString);
if (StringUtils.isNotBlank(exceptionString)) {
result.setResult(false);
result.setResultMsg(exceptionString.toString());
return result;
}
String sql = StringUtils.EMPTY;
if (isEntryShow) {
if (allJe) {
sql = "select count(1) as TotalCount from" +
" (select distinct Period,`Group`,VId from" +
" (select Period,`Group`,VId from Voucher " + sqlWhere + ")TB)abc" +
" left join Voucher c on abc.Period=c.Period and abc.`Group`=c.`Group` and abc.VId=c.VId";
} else {
sql = "select count(1) as TotalCount from Voucher " + sqlWhere;
}
} else {
sql = "Select count(1) as TotalCount from (select Period,`Group`,VId from Voucher " + sqlWhere + " group by Period,`Group`,VId)TB";
}
int total = jdbcTemplate.queryForObject(sql, int.class);
result.setResult(true);
result.setData(total);
return null;
}
@Override
public OperationResultDto<Object> voucherSelectAdvancedByVoucher(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum mainRelation, boolean allJe, PagingDto pagingInfo) throws Exception {
OperationResultDto<Object> resultDto = new OperationResultDto<>();
OperationResultDto<Object> result = new OperationResultDto<>();
StringBuffer exceptionString = new StringBuffer();
String sqlWhere = getSqlWhereCondition(listQueryCondition, mainRelation, allJe, exceptionString);
if (StringUtils.isNotBlank(exceptionString.toString())) {
result.setResult(false);
result.setResultMsg(exceptionString.toString());
return result;
}
String sql = StringUtils.EMPTY;
if (allJe) {
if (pagingInfo != null) {
sql = "SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"DebitSum," +
"CreditSum," +
"ItemCount" +
" FROM " +
"(" +
"SELECT " +
"TB.`Period`," +
"TB.`Group`," +
"TB.`VId`," +
"TB.`Date`," +
"TB.DebitSum," +
"TB.CreditSum," +
"TB.ItemCount" +
" FROM " +
"(" +
"SELECT " +
"c.`Period`," +
"c.`Group`," +
"c.`VId`," +
"c.`Date`," +
"sum(c.`Debit`) AS DebitSum," +
"sum(c.`Credit`) AS CreditSum," +
"count(1) AS ItemCount" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`Group`," +
"`VId`" +
" FROM " +
"Voucher " + sqlWhere +
" GROUP BY " +
"`Period`," +
"`Group`," +
"`VId`" +
") abc" +
" LEFT JOIN Voucher c ON abc.`Period` = c.`Period`" +
"AND abc.`Group` = c.`Group`" +
"AND abc.`VId` = c.`VId`" +
" GROUP BY " +
"c.`Period`," +
"c.`Group`," +
"c.`VId`," +
"c.`Date`" +
") TB" +
") tmp" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`" +
"LIMIT " + pagingInfo.getPageSize() * (pagingInfo.getPageIndex() - 1) + "," + pagingInfo.getPageSize();
} else {
sql = "SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"DebitSum," +
"CreditSum," +
"ItemCount" +
" FROM " +
"(" +
"SELECT " +
"TB.`Period`," +
"TB.`Group`," +
"TB.`VId`," +
"TB.`Date`," +
"TB.DebitSum," +
"TB.CreditSum," +
"TB.ItemCount" +
" FROM " +
"(" +
"SELECT " +
"c.`Period`," +
"c.`Group`," +
"c.`VId`," +
"c.`Date`," +
"sum(c.`Debit`) AS DebitSum," +
"sum(c.`Credit`) AS CreditSum," +
"count(1) AS ItemCount" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`Group`," +
"`VId`" +
" FROM " +
"Voucher " + sqlWhere +
" GROUP BY " +
"`Period`," +
"`Group`," +
"`VId`" +
") abc" +
" LEFT JOIN Voucher c ON abc.`Period` = c.`Period`" +
"AND abc.`Group` = c.`Group`" +
"AND abc.`VId` = c.`VId`" +
" GROUP BY " +
"c.`Period`," +
"c.`Group`," +
"c.`VId`," +
"c.`Date`" +
") TB" +
") tmp" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`";
}
} else {
if (pagingInfo != null) {
sql = "SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"DebitSum," +
"CreditSum," +
"ItemCount" +
" FROM " +
"(" +
"SELECT " +
"TB.`Period`," +
"TB.`Group`," +
"TB.`VId`," +
"TB.`Date`," +
"TB.DebitSum," +
"TB.CreditSum," +
"TB.ItemCount" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"sum(`Debit`) AS DebitSum," +
"sum(`Credit`) AS CreditSum," +
"count(1) AS ItemCount" +
" FROM " +
"Voucher " + sqlWhere +
" GROUP BY " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`" +
") TB" +
") abc" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`" +
"LIMIT " + pagingInfo.getPageSize() * (pagingInfo.getPageIndex() - 1) + "," + pagingInfo.getPageSize();
} else {
sql = "SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"DebitSum," +
"CreditSum," +
"ItemCount" +
" FROM " +
"(" +
"SELECT " +
"TB.`Period`," +
"TB.`Group`," +
"TB.`VId`," +
"TB.`Date`," +
"TB.DebitSum," +
"TB.CreditSum," +
"TB.ItemCount" +
" FROM " +
"(" +
"SELECT " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`," +
"sum(`Debit`) AS DebitSum," +
"sum(`Credit`) AS CreditSum," +
"count(1) AS ItemCount" +
" FROM " +
"Voucher " + sqlWhere +
" GROUP BY " +
"`Period`," +
"`Group`," +
"`VId`," +
"`Date`" +
") TB" +
") abc" +
" ORDER BY " +
"`Period`," +
"`Date`," +
"`Group`," +
"`VId`";
}
}
List<Map<String, Object>> queryResult = jdbcTemplate.queryForList(sql);
List<VoucherMainDto> voucherMainDtos = new ArrayList<>();
queryResult.forEach(a -> {
VoucherMainDto voucherMainDto = new VoucherMainDto();
voucherMainDto.setPeriod(Integer.parseInt(a.get("Period") == null ? "" : a.get("Period").toString()));
voucherMainDto.setGroup(a.get("Group") == null ? "" : a.get("Group").toString());
voucherMainDto.setvId(a.get("VId") == null ? "" : a.get("VId").toString());
voucherMainDto.setDate(DateTime.parse(a.get("Date") == null ? "" : a.get("Date").toString()).toDate());
voucherMainDto.setDebitSum(new BigDecimal(Double.valueOf(a.get("DebitSum") == null ? "" : a.get("DebitSum").toString())));
voucherMainDto.setCreditSum(new BigDecimal(Double.valueOf(a.get("CreditSum") == null ? "" : a.get("CreditSum").toString())));
voucherMainDto.setGroupShow(a.get("Group") == null ? "" : a.get("Group").toString() + "-" + a.get("VId") == null ? "" : a.get("VId").toString());
voucherMainDto.setItemCount(Integer.valueOf(a.get("ItemCount") == null ? "" : a.get("ItemCount").toString()));
voucherMainDtos.add(voucherMainDto);
});
Function<VoucherMainDto, List<Object>> compositeKey = voucherRecord -> Arrays.asList(voucherRecord.getPeriod(), voucherRecord.getvId(), voucherRecord.getGroup());
Map<Object, List<VoucherMainDto>> resultGroupMap = voucherMainDtos.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
List<VoucherMainDto> resultGroup = new ArrayList<>();
resultGroupMap.forEach((k, v) -> resultGroup.add(v.stream().findFirst().get()));
if (voucherMainDtos.size() != resultGroup.size()) {
List<VoucherMainDto> expectedList = new ArrayList<>(voucherMainDtos);
expectedList.removeAll(resultGroup);
for (VoucherMainDto temp : expectedList) {
VoucherMainDto alerMto = resultGroup.stream()
.filter(t -> t.getPeriod() == temp.getPeriod() && t.getvId().equals(temp.getvId()) && t.getGroup().equals(temp.getGroup())).findFirst().get();
alerMto.setDebitSum(alerMto.getDebitSum().add(temp.getDebitSum()));
alerMto.setCreditSum(alerMto.getCreditSum().add(temp.getCreditSum()));
alerMto.setItemCount(alerMto.getItemCount() + temp.getItemCount());
}
}
QueryVoucherMainDto dto = new QueryVoucherMainDto();
dto.setVoucherMainList(resultGroup);
dto.setItemIdCount(resultGroup.stream().mapToInt(a -> a.getItemCount()).sum());
dto.setCreditSum(new BigDecimal(resultGroup.stream().mapToDouble(a -> a.getCreditSum().doubleValue()).sum()));
dto.setDebitSum(new BigDecimal(resultGroup.stream().mapToDouble(a -> a.getDebitSum().doubleValue()).sum()));
dto.setvIdCount(resultGroup.size());
resultDto.setResult(true);
resultDto.setData(dto);
return resultDto;
}
private String getSqlWhereCondition(List<QueryConditionDto> listQueryCondition, VoucherSearchEnum mainRelation, boolean allJe, StringBuffer exceptionString) throws Exception {
//what does this statement used for?
exceptionString = new StringBuffer(StringUtils.EMPTY);
if (mainRelation != VoucherSearchEnum.S_AndAll && mainRelation != VoucherSearchEnum.S_OrAll) {
throw new Exception("条件关系定义错误");
}
List<VoucherTmplDto> tmpls = new ArrayList<>();
for (QueryConditionDto queryConditionDto : listQueryCondition) {
switch (queryConditionDto.getConditionName()) {
case VoucherSelect.S_CorpAcctCoding:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`AcctCode`"
, mainRelation
, null));
break;
case VoucherSelect.S_CorpAcctName:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "EnterpriseAccount.`Name`"
, mainRelation
, null));
break;
case VoucherSelect.S_VoucherType:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Group`"
, mainRelation
, null));
break;
case VoucherSelect.S_VoucherVId:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`VId`"
, mainRelation
, null));
break;
case VoucherSelect.S_VoucherSummary:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Summary`"
, mainRelation
, null));
break;
case VoucherSelect.S_Period:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Period`"
, mainRelation
, null));
break;
case VoucherSelect.S_Debit:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Debit`"
, mainRelation
, null));
break;
case VoucherSelect.S_Credit:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Credit`"
, mainRelation
, null));
break;
case VoucherSelect.S_Date:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "`Date`"
, mainRelation
, null));
break;
case VoucherSelect.S_CustomerCode:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "Voucher.CustomerCode"
, mainRelation
, null));
break;
case VoucherSelect.S_CustomerName:
tmpls.add(createQueryScriptByTmplList(Arrays.asList(queryConditionDto.getSearchValue().trim().split("\\s+"))
, VoucherSearchEnum.values()[queryConditionDto.getSearchKeyWord() - 1]
, "Voucher.CustomerName"
, mainRelation
, null));
break;
default:
throw new Exception("未处理的条件类型:" + queryConditionDto.getConditionName());
}
}
tmpls.forEach(p -> {
if (StringUtils.isBlank(p.getSql())) {
tmpls.remove(p);
}
});
return getSqlWhereCondition(tmpls);
}
private VoucherTmplDto createQueryScriptByTmplList(List<String> strList, VoucherSearchEnum relation, String columnName, VoucherSearchEnum logic, String strValue) throws Exception {
VoucherTmplDto temp = new VoucherTmplDto();
temp.setLogic(logic);
StringBuffer sb = new StringBuffer();
sb.append("(");
int count = strList.size();
switch (relation) {
case S_EqualAnyKey:
for (int i = 0; i < count; i++) {
sb.append(columnName + "='" + strList.get(i) + "'" + (i < (count - 1) ? " or " : ")"));
}
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
case S_AnyHeaderKey:
for (int i = 0; i < count; i++) {
sb.append(columnName + "='" + strList.get(i) + "'" + (i < (count - 1) ? " or " : ")"));
}
temp.setSort(VoucherLevelEnum.SecondSort.getCode());
break;
case S_AllKey:
for (int i = 0; i < count; i++) {
sb.append(columnName + "like'" + strList.get(i) + "'" + (i < (count - 1) ? " and " : ")"));
}
temp.setSort(VoucherLevelEnum.SecondSort.getCode());
break;
case S_ContainAnyKey:
for (int i = 0; i < count; i++) {
sb.append(columnName + "like'" + strList.get(i) + "'" + (i < (count - 1) ? " or " : ")"));
}
temp.setSort(VoucherLevelEnum.SecondSort.getCode());
break;
case S_OrAll:
break;
case S_AndAll:
break;
case S_Equal:
sb.append(columnName + " ='" + strValue + "'");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
case S_Greater:
sb.append(columnName + " >'" + strValue + "'");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
case S_GreaterEqual:
sb.append(columnName + " >='" + strValue + "'");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
//小于
case S_Less:
sb.append(columnName + "< '" + strValue + "')");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
//小于等于
case S_LessEqual:
sb.append(columnName + "<= '" + strValue + "')");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
case S_Manual:
sb.append(columnName + "=1");
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
case S_Industry:
sb.append(columnName + " is null");
temp.setSort(VoucherLevelEnum.ThirdSort.getCode());
break;
case S_FromTo:
if (strList.size() != 2) {
throw new Exception("数据格式错误");
}
if (!"null".equals(strList.get(0).toLowerCase()) && !"null".equals(strList.get(1).toLowerCase())) {
if ("`Debit`".equals(columnName) || "`Credit`".equals(columnName)) {
sb.append(columnName + ">=" + Double.valueOf(strList.get(0)) + " And " + columnName + " <=" + Double.valueOf(strList.get(1)) + ")");
} else {
sb.append(columnName + ">='" + strList.get(0) + "' And " + columnName + " <= '" + strList.get(1) + "')");
}
} else if ("null".equals(strList.get(0).toLowerCase()) && "null".equals(strList.get(1).toLowerCase())) {
break;
} else if (!"null".equals(strList.get(0).toLowerCase()) && "null".equals(strList.get(1).toLowerCase())) {
if ("`Debit`".equals(columnName) || "`Credit`".equals(columnName)) {
sb.append(columnName + ">=" + Double.valueOf(strList.get(0)) + ")");
} else {
sb.append(columnName + ">='" + strList.get(0) + "')");
}
} else if ("null".equals(strList.get(0).toLowerCase()) && !"null".equals(strList.get(1).toLowerCase())) {
if ("`Debit`".equals(columnName) || "`Credit`".equals(columnName)) {
sb.append(columnName + " <=" + Double.valueOf(strList.get(1)) + ")");
} else {
sb.append(columnName + " <= '" + strList.get(1) + "')");
}
}
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
break;
default:
}
temp.setSql(sb.toString());
String acctStrs = StringUtils.EMPTY;
if ("EnterpriseAccount.`Name`".equals(columnName)) {
acctStrs = "select AcctCode from EnterpriseAccount where " + temp.getSql();
List<Map<String, Object>> result = jdbcTemplate.queryForList(acctStrs);
int num = result.size();
if (num > 0) {
sb = new StringBuffer();
sb.append("(");
for (int idx = 0; idx < num; idx++) {
Map<String, Object> item = result.get(idx);
sb.append("AcctCode='" + item.get("AcctCode") + "'" + (idx < (num - 1) ? " or " : ")"));
}
temp.setSort(VoucherLevelEnum.FirstSort.getCode());
temp.setSql(sb.toString());
} else {
temp.setSql("(AcctCode is null)");
temp.setSort(VoucherLevelEnum.ThirdSort.getCode());
}
}
return temp;
}
private String getSqlWhereCondition(List<VoucherTmplDto> tmplList) throws Exception {
List<VoucherTmplDto> smallTemp = tmplList.stream().sorted(Comparator.comparing(VoucherTmplDto::getSort).reversed()).collect(Collectors.toList());
int count = 1;
int tCount = smallTemp.size();
StringBuilder sqlWhere = new StringBuilder();
if (tCount > 0) {
sqlWhere.append(" where");
}
for (VoucherTmplDto t : smallTemp) {
String logic = StringUtils.EMPTY;
if (t.getLogic().equals(VoucherSearchEnum.S_OrAll)) {
logic = " OR";
} else if (t.getLogic().equals(VoucherSearchEnum.S_AndAll)) {
logic = " AND";
} else {
throw new Exception("未处理的条件关系:" + t.getLogic().toString());
}
sqlWhere.append(" ").append(t.getSql()).append(count < tCount ? logic + " " : " ");
count++;
}
return sqlWhere.toString();
}
}
\ No newline at end of file
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