diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/BandConfigService.java b/src/main/java/com/cmsen/ticket/application/manager/service/BandConfigService.java new file mode 100644 index 0000000..bb2ffce --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/BandConfigService.java @@ -0,0 +1,25 @@ +package com.cmsen.ticket.application.manager.service; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.BandConfig; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2023/9/25 16:06 + **/ +public interface BandConfigService { + RestResponse list(Map params); + + RestResponse update(BandConfig bandConfig); + + RestResponse delete(Integer id); + + RestResponse export(Map params, HttpServletResponse response); + + RestResponse upload(MultipartFile file); +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/InvoiceImageService.java b/src/main/java/com/cmsen/ticket/application/manager/service/InvoiceImageService.java deleted file mode 100644 index fcdeb1e..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/InvoiceImageService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; -import com.cmsen.ticket.domain.entity.manager.InvoiceImage; - -import javax.servlet.http.HttpServletResponse; -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/3/3 14:14 - **/ -public interface InvoiceImageService { - RestResponse list(Map params); - - RestResponse selectImg(Integer id); - - RestResponse selectByPrimaryKey(Integer id); - - RestResponse create(InvoiceImage invoiceImage); - - RestResponse update(InvoiceImage invoiceImage); - - RestResponse delete(Integer id); - - RestResponse deleteBatch(String ids); - - RestResponse download(Integer id, HttpServletResponse response); - - RestResponse exportExcel(Map params, HttpServletResponse response); - - RestResponse downloadImages(Map params, HttpServletResponse response); - - RestResponse downloadXmls(Map params, HttpServletResponse response); - - RestResponse downloadXmlsPoc(Map params, HttpServletResponse response); - - RestResponse getUnMatchImg(String reportId); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/JsadapterService.java b/src/main/java/com/cmsen/ticket/application/manager/service/JsadapterService.java index bd0f796..4cb6030 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/JsadapterService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/JsadapterService.java @@ -1,12 +1,16 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.Jsadapter; import java.util.Map; public interface JsadapterService { RestResponse list(Map params); + RestResponse create(Jsadapter jsadapter); + + RestResponse update(Jsadapter jsadapter); RestResponse delete(Integer id); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/MtAgreementService.java b/src/main/java/com/cmsen/ticket/application/manager/service/MtAgreementService.java deleted file mode 100644 index 7a07c4f..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/MtAgreementService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; -import org.springframework.web.multipart.MultipartFile; - -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2022/10/9 16:06 - **/ -public interface MtAgreementService { - - RestResponse getList(Map params); - - RestResponse upload(MultipartFile file); - -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/MtListPcService.java b/src/main/java/com/cmsen/ticket/application/manager/service/MtListPcService.java deleted file mode 100644 index a46c3a5..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/MtListPcService.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; -import org.springframework.web.multipart.MultipartFile; - -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2022/11/17 16:06 - **/ -public interface MtListPcService { - - RestResponse listMeetPic(Map params); - - RestResponse deletePic(Long id); - - RestResponse meetPicUpload(MultipartFile file); - - RestResponse insertPic(MultipartFile file, String reqId, String picType, String expenseName, String extId); - - RestResponse reqList2(String reqName); - - RestResponse valueSetList(String category); - - RestResponse meetingSpeakerList(String reqId); - - RestResponse listMeeting(Map params); - - - RestResponse getOrgListByPid(Integer pid, String orgName); - - RestResponse checkinList(Map params); - - - RestResponse getEditFlag(String roleId); - - RestResponse meetingDetails(Long id); - - RestResponse meetRevoke(String reqId); - - RestResponse meetReActive(String reqId); - - RestResponse speakerFallBack(Long id); - - RestResponse checkinReset(String reqId); - - RestResponse checkinDel(Long id); - - RestResponse listSignMeet(Map params); - - RestResponse listSignMeetAttend(Map params); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/PaymentService.java b/src/main/java/com/cmsen/ticket/application/manager/service/PaymentService.java deleted file mode 100644 index 3588cc4..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/PaymentService.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; -import com.cmsen.ticket.domain.dto.SubmitOrderMatchDto; -import com.cmsen.ticket.domain.entity.SupplierOrder; - -import java.util.Map; - - -public interface PaymentService { - - RestResponse list(Map params); - - - - - - - - - - - RestResponse listCompany(String keyword); - - RestResponse listOrg(String keyword); - - RestResponse codeList(); - - RestResponse getCompOrg(String userId); - - RestResponse getUserList(String keyword); - - RestResponse getSupplierList(String orgCode, String keyword, String isDigital); - - - RestResponse deleteHeader(String billId); - - RestResponse orderList(Map params); - - RestResponse createOrder(SupplierOrder supplierOrder); - - RestResponse updateOrder(SupplierOrder supplierOrder); - - RestResponse deleteOrder(String ids, String orderNo); - - RestResponse listItems(Map params); - - RestResponse submitOrderMatchList(SubmitOrderMatchDto dto); - - RestResponse deleteOrderMatch(Long matchId); - - RestResponse submitBill(String billId); - - RestResponse recallBill(String billId); - - RestResponse backBill(String billId); - - RestResponse matchBill(String billId); - - RestResponse getPayTypeList(String keyword); - - RestResponse getMaterialList(String keyword); - - RestResponse getWhiteCompList(String keyword); - - RestResponse listContracts(Map params); - - RestResponse listPurchaces(Map params); - - RestResponse getFlowType(); - - RestResponse listBrands(Map params); - - RestResponse listReceives(Map params); - - RestResponse listInternals(Map params); - - RestResponse valueSetList(String category, Integer pid, String keywords); - - RestResponse getSysConfig(String code); - - RestResponse getBillName(String businessType, String userName); - - RestResponse getMatchFlag(String roleId, String userId, String costCenter); - - RestResponse getMatchFinFlag(String roleId, String userId); - - RestResponse getTransferUser(Map params); - - RestResponse transferBill(String billId, String owner, String toUserId); - - RestResponse listForTransfer(Map params); - - RestResponse transferBatch(Map params, String current, String target); - - RestResponse transferRecallBatch(Map params); - - RestResponse listOwner(String keyword); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/PreferencesService.java b/src/main/java/com/cmsen/ticket/application/manager/service/PreferencesService.java index 8aa438e..b02882b 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/PreferencesService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/PreferencesService.java @@ -1,6 +1,7 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.Preferences; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; @@ -15,6 +16,10 @@ import java.util.Map; public interface PreferencesService { RestResponse list(Map params); + RestResponse update(Preferences preferences); + + RestResponse insert(Preferences preferences); + RestResponse delete(Integer id); RestResponse export(Map params, HttpServletResponse response); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/ProcureOrderService.java b/src/main/java/com/cmsen/ticket/application/manager/service/ProcureOrderService.java index 267c2d3..9f9c7e0 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/ProcureOrderService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/ProcureOrderService.java @@ -1,6 +1,8 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.SupplierPo; +import com.cmsen.ticket.domain.entity.SupplierPoLine; import org.springframework.web.multipart.MultipartFile; import java.util.Map; @@ -12,11 +14,18 @@ public interface ProcureOrderService { RestResponse detail(String po); + RestResponse create(SupplierPo supplierPo); + + RestResponse update(SupplierPo supplierPo); RestResponse deletePo(Integer id); RestResponse lineList(Map params); + RestResponse createLine(SupplierPoLine supplierPoLine); + + RestResponse updateLine(SupplierPoLine supplierPoLine); + RestResponse deleteLine(String ids, String po); RestResponse uploadPo(MultipartFile file); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/RuleService.java b/src/main/java/com/cmsen/ticket/application/manager/service/RuleService.java index eb44796..f59ba30 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/RuleService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/RuleService.java @@ -1,6 +1,7 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.Rule; import java.util.Map; @@ -12,6 +13,9 @@ import java.util.Map; public interface RuleService { RestResponse list(Map params); + RestResponse create(Rule rule); + + RestResponse update(Rule rule); RestResponse delete(Integer ids); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SearchValueService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SearchValueService.java new file mode 100644 index 0000000..3798eb9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SearchValueService.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.application.manager.service; + +import com.cmsen.common.http.response.RestResponse; + +public interface SearchValueService { + RestResponse clients(); + + RestResponse rules(Integer type); + + RestResponse ticketTypes(); + + RestResponse orgs(); +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SmartImageCheckService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SmartImageCheckService.java deleted file mode 100644 index 5211e91..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SmartImageCheckService.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; -import com.cmsen.ticket.domain.entity.manager.ComplianceCheck; -import com.cmsen.ticket.domain.response.Response; -import org.springframework.web.multipart.MultipartFile; - -import java.util.List; -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/9/9 16:20 - **/ -public interface SmartImageCheckService { - - Response> getImages(String id); - - - Response batchCheck(List reportIds); - - Response compliance(String reportId); - - Response uploadImage(MultipartFile file, String reportId); - - Response forcePassed(List ids); - - Response> getComlianceCheckList(String id); - - Response approved(String id); - - Response rejected(String id, String comment); - - - Response deleteErrorReport(String reportId); - - Response updateErrorReport(Long id, String newReportId); - - Response reCheckErrorReport(Long id); - - RestResponse reportLine(String id); - - Response> getLineImageList(String id); - - - RestResponse getLogList(Map params); - - Response> getErrImages(String reportId); - - RestResponse editRemark(String reportId, String ext02); - - Response delPaperImage(String id); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SqlDownloadService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SqlDownloadService.java index 01b7c34..3b70309 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SqlDownloadService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SqlDownloadService.java @@ -1,14 +1,20 @@ package com.cmsen.ticket.application.manager.service; +import com.cmsen.ticket.domain.dto.SqlDownloadDto; import com.cmsen.ticket.domain.response.Response; import javax.servlet.http.HttpServletResponse; +import java.util.List; import java.util.Map; /** * @author OWTS */ public interface SqlDownloadService { + Response> getListData(SqlDownloadDto downloadDto); + + Response>> getListData2(SqlDownloadDto downloadDto); + //Response exportListData(SqlDownloadDto downloadDto, HttpServletResponse response); Response exportListData(Map params, HttpServletResponse response); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SupplierService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SupplierService.java index 77e931d..1b082bf 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SupplierService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SupplierService.java @@ -7,25 +7,204 @@ */ package com.cmsen.ticket.application.manager.service; +import com.alibaba.fastjson.JSONObject; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.dto.LineMatchListDto; import com.cmsen.ticket.domain.dto.SubmitLineMatchDto; -import com.cmsen.ticket.domain.entity.SupplierMaterialUom; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.entity.manager.SysUser; import com.cmsen.ticket.domain.response.Response; -import com.cmsen.ticket.interfaces.facade.form.SupplierInvoiceMatchForm; -import com.cmsen.ticket.interfaces.facade.manager.form.SupplierUpdatePriceForm; +import com.cmsen.ticket.interfaces.facade.manager.form.*; +import org.springframework.web.multipart.MultipartFile; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; import java.util.List; +import java.util.Map; public interface SupplierService { + + + // ---------------供应商管理--------------- + + RestResponse selectList(); + + RestResponse updateAccountPeriod(CorporateInvoice invoice); + + RestResponse supplierSelectStatus(); + /** - * 提交行匹配列表 + * 供应商信息列表 */ - Response submitLineMatchList(SubmitLineMatchDto dto); + RestResponse supplierInformationList(SupplierSearchForm form); + + /** + * 供应商信息创建 + */ + RestResponse supplierInformationCreate(Supplier supplier); + + /** + * 供应商信息更新 + */ + RestResponse supplierInformationUpdate(Supplier supplier); + + /** + * 供应商信息删除 + */ + RestResponse supplierInformationDelete(@NotNull Integer id); + + // ---------------供应商SITE_CODE--------------- + + /** + * 供应商SITE_CODE信息列表 + */ + RestResponse supplierSiteCodeList(@NotNull String code); + + /** + * 供应商SITE_CODE信息创建 + */ + RestResponse supplierSiteCodeCreate(SupplierSite supplierSite); + + /** + * 供应商SITE_CODE信息更新 + */ + RestResponse supplierSiteCodeUpdate(SupplierSite supplierSite); + + /** + * 供应商SITE_CODE信息删除 + */ + RestResponse supplierSiteCodeDelete(@NotNull Integer id); + + // ---------------订单管理--------------- + + /** + * 订单信息列表 + */ + RestResponse supplierOrderList(SupplierOrderSearchForm form); + + /** + * 冻结订单信息列表 + */ + RestResponse supplierRefundOrderList(SupplierOrderSearchForm form); + + /** + * 批量删除收货数据 + * + * @param ids + * @return + */ + RestResponse supplierOrderUpdate(String ids); + + /** + * 数据清理 + * + * @return + */ + RestResponse supplierOrderClear(); + + /** + * PO查询 + * + * @param form + * @return + */ + RestResponse supplierOrderPOSearch(SupplierOrderSearchForm form); + + RestResponse supplierOrderPOExportExcel(Map params, HttpServletResponse response); + + RestResponse supplierOrderPODownloadImages(Map params, HttpServletResponse response); + + RestResponse supplierOrderMatchReport(Map params, HttpServletResponse response); + + RestResponse supplierOrderReport(Map params, HttpServletResponse response, SupplierOrderSearchForm form); + // ---------------物料管理--------------- + + /** + * 物料信息列表 + */ + RestResponse supplierMaterialList(SupplierMaterialSearchForm form); + + /** + * 物料信息创建 + */ + RestResponse supplierMaterialCreate(SupplierMaterial supplierMaterial); + + /** + * 物料信息更新 + */ + RestResponse supplierMaterialUpdate(SupplierMaterial supplierMaterial); + + /** + * 物料信息删除 + */ + RestResponse supplierMaterialDelete(@NotNull Integer id); + + + // ---------------例外物料--------------- + + /** + * 例外物料列表 + */ + RestResponse supplierMaterialFilterList(SupplierMaterialFilterSearchForm form); + + /** + * 例外物料创建 + */ + RestResponse supplierMaterialFilterCreate(SupplierMaterialFilter supplierMaterialFilter); + + /** + * 例外物料更新 + */ + RestResponse supplierMaterialFilterUpdate(SupplierMaterialFilter supplierMaterialFilter); + + /** + * 例外物料删除 + */ + RestResponse supplierMaterialFilterDelete(@NotNull Integer id); + + // ---------------单位换算--------------- + + /** + * 单位换算列表 + */ + RestResponse supplierMaterialUomList(SupplierMaterialUOMSearchForm form); + + /** + * 单位换算创建 + */ + RestResponse supplierMaterialUomCreate(SupplierMaterialUom supplierMaterialUom); + + /** + * 单位换算更新 + */ + RestResponse supplierMaterialUomUpdate(SupplierMaterialUom supplierMaterialUom); + + /** + * 单位换算删除 + */ + RestResponse supplierMaterialUomDelete(@NotNull Integer id); + + // ---------------发票匹配--------------- + /** * 发票匹配列表
* 匹配条件:ticketCode、seller、number、buyer */ RestResponse SupplierInvoiceMatchList(SupplierInvoiceMatchForm form); + + /** + * 按供应商代码匹配订单 + * + * @param invoiceId 供应商代码 + * @param all 1 物料 2 金额 3 金额+物料 4 全部 + * @param orderNo 该值不为空时查询订单明细 + */ + RestResponse supplierInvoiceMatchOrderList(String invoiceId, Integer all, String orderNo, Integer pageNum, Integer pageSize); + + RestResponse supplierOrderPOList(String orderNo, Integer pageNum, Integer pageSize); + RestResponse autoSmartMatching(String invoiceId, String directCode); RestResponse autoSmartMatchingOld(String invoiceId); @@ -33,21 +212,176 @@ public interface SupplierService { RestResponse autoSmartMatchingOutIn(String invoiceId, String directCode); RestResponse materialAutoMatching(String invoiceId, String directCode); - RestResponse matchInvoices(String numberS, String numberE, Integer invoiceType); + + /** + * 更新供应商代码匹配订单结果信息 + */ + RestResponse supplierInvoiceMatchInfoList(String invoiceId); + + /** + * 更新供应商代码匹配订单结果信息 + */ + RestResponse supplierInvoiceMatchInfoUpdate(SupplierMatching form); + + /** + * 发票匹配列表 + */ + RestResponse supplierInvoiceItemsList(String itemId, String id); + + /** + * 发票匹配列表 + */ + RestResponse supplierInvoiceItemsListAll(String itemId, Integer pageNo, Integer pageSize); + + /** + * 发票匹配列表 + */ + RestResponse supplierInvoiceItemsListAllExport(HttpServletResponse response, String invoiceId); + + /** + * 发票附件列表 + */ + RestResponse supplierInvoiceAttachmentList(String itemId); + + /** + * 上传供应商 + */ + RestResponse importFile(MultipartFile file); + + Response uploadInvoiceAttachment(SupplierInvoiceAttachmentForm form); + + /** + * 发票附件删除 + */ + RestResponse supplierInvoiceAttachmentDelete(Integer id); + + /** + * 发票操作日志列表 + */ + RestResponse supplierInvoiceMatchLogList(String itemId); + + + /** + * by owts ... + */ + RestResponse getMatchedList(String invoiceId); + + /** + * 获取行匹配 订单列表 + */ + Response> lineMatchList(LineMatchListDto dto); + + /** + * 提交行匹配列表 + */ + Response submitLineMatchList(SubmitLineMatchDto dto); + + /** + * 根据Item获取其下面匹配的订单 + */ + Response> lineMatchListByItem(String itemId); /** * 匹配完成 */ Response completeMatching(List ids, String invoiceId); + /** + * 虚拟匹配 + */ + Response inventedMatching(LineMatchListDto dto); + /** + * 清除匹配 + */ + Response clearMatching(List ids); + + Response> getInvoiceTypes(boolean search); + + Response> getInvoiceOrgs(boolean search, String name); + + Response> getOwners(String keyword); + + Response revokeInvoice(String invoiceId); + Response passReview(String invoiceId, String exchangeRateDate); + + Response resendInvoice(String invoiceId); + + RestResponse matchInvoices(String numberS, String numberE, Integer invoiceType); + + RestResponse confirmSend(InvoiceConfirmAndSendForm invoiceConfirmAndSendForm); + + RestResponse updateMatchType(CorporateInvoice corporateInvoice); + + RestResponse updatePriceType(CorporateInvoice corporateInvoice); RestResponse updatePrice(SupplierUpdatePriceForm form); + RestResponse priceLogs(String id); + + Response lineMatchById(Long id); RestResponse updateUom(String invoiceId, String sellerTaxId); + /** + * 添加地址信息 + * + * @param orderStr + * @return + */ + RestResponse addAress(String orderStr); + + /** + * 获取Ap发票信息 + * + * @param invoiceId + * @return + */ + RestResponse getSupplierOrderItem(String invoiceId); + + /** + * 获取Ap发票信息 + * + * @param status + * @return + */ + RestResponse getSupplierOrderItemMore(String status); + + /** + * 更新Ap发票信息 + * + * @param invoiceStr + * @return + */ + RestResponse upInvoice(String invoiceStr); + + /** + * 虚拟匹配 + */ + + RestResponse importStatement(MultipartFile file); + + RestResponse exportSupplierInvoiceAttachmentList(HttpServletResponse response, String pId); + + RestResponse uploadPOfile(MultipartFile file); + Response createSupplierMaterialUom(List supplierMaterialUoms); + RestResponse getSupplierByInvoiceId(String invoiceId); + + RestResponse getSupplierByNameLike(String name); + + RestResponse saveSupplier(Supplier supplier); + + List listAll(); + + void sendDataToXTPT(String method, JSONObject params); + void syncUomFromMapping(String invoiceId, String supplierCode); + RestResponse importSupplierOrderRefund(MultipartFile file); + + RestResponse getSupplierOrderRefund(); + + + RestResponse deleteRefundOrders(String ids); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysCorInvoiceService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysCorInvoiceService.java index 2ed0cb1..282ac75 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysCorInvoiceService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysCorInvoiceService.java @@ -1,9 +1,86 @@ package com.cmsen.ticket.application.manager.service; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoiceItems; +import com.cmsen.ticket.domain.vo.FileVo; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + /** * @author OWTS * @version 1.0.0 * @date 2021/2/19 9:49 **/ public interface SysCorInvoiceService { - } + + RestResponse receiveLines(String pid); + RestResponse corporateLines(String pid); + + RestResponse receiveList(Integer pageSize, Integer pageNum, String status,String selNo); + + RestResponse list(Map params); + + RestResponse create(CorporateInvoice corporateInvoice); + RestResponse createLine(CorporateInvoiceItems item); + + RestResponse update(CorporateInvoice corporateInvoice); + + RestResponse delete(String id); + +// RestResponse importFile(MultipartFile file); + + RestResponse exportExcel(HttpServletResponse response, Map params); + + RestResponse exportImages(HttpServletResponse response, Map params); + + RestResponse selectById(String id); + + RestResponse download(String id, HttpServletResponse response); + + RestResponse upload(MultipartFile[] files, String type, String com,String invoiceType); + RestResponse uploadReceive(MultipartFile[] files, String type, String com); + + RestResponse uploadAtt(MultipartFile[] files, String id); + + RestResponse uploadInvPdf(MultipartFile files); + + RestResponse updateData(MultipartFile file); + + RestResponse updateDeductStatus(); + + RestResponse completeCheck(String invoiceId); + + RestResponse getAllSubjects(); + + RestResponse getAllSubjectsTreeNode(); + + + RestResponse getSubjectById(String invoiceId); + + RestResponse updateSubject(CorporateInvoice corporateInvoice); + + void updatePOAndHTBH(CorporateInvoice corporateInvoice); + + RestResponse exportInvoiceReport(Map params, HttpServletResponse response); + + RestResponse exportByMultiNumber(Map params, HttpServletResponse response); + + RestResponse exportValidExcel(HttpServletResponse response, Map params); + + RestResponse refundTicket(String id); + + RestResponse importAdvanceOfPayment(MultipartFile file); + + RestResponse pushListUpload(MultipartFile file); + + RestResponse pushKofox(String invoiceId); + + JSONObject ncImport(List fileVoList); + + void dealNcExport(int ncImportId,int userId,String type,String originalFilename,String companyId); +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysExpenseTypeService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysExpenseTypeService.java deleted file mode 100644 index 33e616f..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysExpenseTypeService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; - -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/3/2 13:22 - **/ -public interface SysExpenseTypeService { - RestResponse list(Map params); - - - RestResponse delete(Integer id); - - RestResponse selectByPaimaryKey(Integer id); - - RestResponse updateIsDel(Integer id, String isDel); - - RestResponse getPidList(Integer pid); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysExtraFieldsService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysExtraFieldsService.java deleted file mode 100644 index 6bbcdd1..0000000 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysExtraFieldsService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.cmsen.ticket.application.manager.service; - -import com.cmsen.common.http.response.RestResponse; - -import java.util.Map; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/3/2 13:33 - **/ -public interface SysExtraFieldsService { - RestResponse list(Map params); - - - RestResponse delete(Integer id); - - RestResponse selectByPaimaryKey(Integer id); -} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysLogoService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysLogoService.java new file mode 100644 index 0000000..0b2e19c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysLogoService.java @@ -0,0 +1,19 @@ +package com.cmsen.ticket.application.manager.service; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.manager.SysLogo; +import org.springframework.web.multipart.MultipartFile; + + +/** + * @author OWTS + * @version 1.0.0 + * @date 2022/8/24 15:40 + **/ +public interface SysLogoService { + RestResponse select(); + + RestResponse create(SysLogo sysLogo); + + RestResponse update(MultipartFile file, String typeStr, String str, Long id); +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysPolicyService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysPolicyService.java index 71914e0..a0db1bf 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysPolicyService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysPolicyService.java @@ -1,6 +1,7 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.ExpenseUse; import java.util.Map; @@ -14,6 +15,9 @@ public interface SysPolicyService { RestResponse selectByPrimaryKey(Integer id); + RestResponse create(ExpenseUse expenseUse); + + RestResponse update(ExpenseUse expenseUse); RestResponse delete(Integer ids); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysProxySetService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysProxySetService.java index 28efb1b..28e3aa6 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysProxySetService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysProxySetService.java @@ -1,15 +1,18 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.ProxySysUser; import java.util.Map; public interface SysProxySetService { RestResponse list(Map params); + RestResponse create(ProxySysUser proxySysUser); RestResponse delete(Integer id); + RestResponse update(ProxySysUser proxySysUser); RestResponse selectUserList(String keyword); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysProxyUserService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysProxyUserService.java index 4c7aee0..1cf898c 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysProxyUserService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysProxyUserService.java @@ -1,17 +1,20 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.ProxyUser; import java.util.Map; public interface SysProxyUserService { RestResponse list(Map params); + RestResponse create(ProxyUser proxyUser); // RestResponse update(ProxyUser proxyUser); RestResponse delete(Integer id); + RestResponse update(ProxyUser proxyUser); RestResponse selectUserList(String name); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysRulesService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysRulesService.java index 13242b4..f76e12b 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysRulesService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysRulesService.java @@ -1,6 +1,7 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.RuleConfig; import java.util.Map; @@ -14,6 +15,10 @@ public interface SysRulesService { RestResponse selectByPrimaryKey(Integer id); + RestResponse create(RuleConfig ruleConfig); + + RestResponse update(RuleConfig ruleConfig); + RestResponse delete(Integer ids); RestResponse getRuleType(); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/SysExtraValueService.java b/src/main/java/com/cmsen/ticket/application/manager/service/SysWhitelistService.java similarity index 54% rename from src/main/java/com/cmsen/ticket/application/manager/service/SysExtraValueService.java rename to src/main/java/com/cmsen/ticket/application/manager/service/SysWhitelistService.java index 09d1785..1f429c4 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/SysExtraValueService.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/SysWhitelistService.java @@ -1,21 +1,23 @@ package com.cmsen.ticket.application.manager.service; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.Company; -import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * @author OWTS * @version 1.0.0 - * @date 2021/3/2 14:19 + * @date 2021/2/22 9:21 **/ -public interface SysExtraValueService { +public interface SysWhitelistService { RestResponse list(Map params); RestResponse selectByPrimaryKey(Integer id); - RestResponse delete(Integer ids); + RestResponse create(Company company); - RestResponse export(HttpServletResponse response); + RestResponse update(Company company); + + RestResponse delete(Integer id); } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/BandConfigServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/BandConfigServiceImpl.java new file mode 100644 index 0000000..38bbdf0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/BandConfigServiceImpl.java @@ -0,0 +1,159 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import cn.hutool.core.io.IoUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.FileMime; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.BandConfigService; +import com.cmsen.ticket.domain.entity.BandConfig; +import com.cmsen.ticket.domain.mapper.BandConfigMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class BandConfigServiceImpl implements BandConfigService { + + @Resource + private BandConfigMapper bandConfigMapper; + + @Override + public RestResponse list(Map params) { + params.put("pageNum",params.get("pageNo").toString()); + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + + List list = bandConfigMapper.list(params); + int count = bandConfigMapper.count(params); + + return RestResponse.success(PaginationUtil.getPageResult(count, params, list)); + } + + + @Override + public RestResponse update(BandConfig bandConfig) { + bandConfigMapper.updateByPrimaryKeySelective(bandConfig); + return RestResponse.success(); + } + + @Override + public RestResponse delete(Integer id) { + bandConfigMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } + + @Override + public RestResponse export(Map params, HttpServletResponse response) { + + response.reset(); + ServletOutputStream out = null; + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=export.xlsx"); + out = response.getOutputStream(); + List list = bandConfigMapper.list(params); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "Band配置") + .head(BandConfig.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + //response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Transactional + @Override + public RestResponse upload(MultipartFile file) { + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + //先进行判断:为空 + for (int i = 0; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + if(StringUtil.isEmpty(sheetRowDatum.get(0))){ + return RestResponse.failure("第"+(i+2)+"行的BAND为空,请检查!"); + } + if(StringUtil.isEmpty(sheetRowDatum.get(1))){ + return RestResponse.failure("第"+(i+2)+"行的AREA为空,请检查!"); + } + if(StringUtil.isEmpty(sheetRowDatum.get(2))){ + return RestResponse.failure("第"+(i+2)+"行的ITEM为空,请检查!"); + } + if(StringUtil.isEmpty(sheetRowDatum.get(3))){ + return RestResponse.failure("第"+(i+2)+"行的RATE为空,请检查!"); + } + } + //数据处理 + for (int i = 0; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + String band = StringUtil.trim(String.valueOf(sheetRowDatum.get(0))); + String area = StringUtil.trim(String.valueOf(sheetRowDatum.get(1))); + String item = StringUtil.trim(String.valueOf(sheetRowDatum.get(2))); + + BandConfig bean = bandConfigMapper.selectRate(band, area, item); + if(bean == null){//插入 + BandConfig bandConfig = new BandConfig(){{ + setBandValue(band); + setArea(area); + setItem(item); + setRate(StringUtil.trim(String.valueOf(sheetRowDatum.get(3)))); + setExt01(StringUtil.trim(String.valueOf(sheetRowDatum.get(4)))); + setExt02(StringUtil.trim(String.valueOf(sheetRowDatum.get(5)))); + setExt03(StringUtil.trim(String.valueOf(sheetRowDatum.get(6)))); + setExt04(StringUtil.trim(String.valueOf(sheetRowDatum.get(7)))); + setExt05(StringUtil.trim(String.valueOf(sheetRowDatum.get(8)))); + setExt06(StringUtil.trim(String.valueOf(sheetRowDatum.get(9)))); + setExt07(StringUtil.trim(String.valueOf(sheetRowDatum.get(10)))); + setExt08(StringUtil.trim(String.valueOf(sheetRowDatum.get(11)))); + setExt09(StringUtil.trim(String.valueOf(sheetRowDatum.get(12)))); + setExt10(StringUtil.trim(String.valueOf(sheetRowDatum.get(13)))); + }}; + bandConfigMapper.insertSelective(bandConfig); + }else{//更新 + BandConfig bandConfig = new BandConfig(){{ + setId(bean.getId()); + setRate(StringUtil.trim(String.valueOf(sheetRowDatum.get(3)))); + setExt01(StringUtil.trim(String.valueOf(sheetRowDatum.get(4)))); + setExt02(StringUtil.trim(String.valueOf(sheetRowDatum.get(5)))); + setExt03(StringUtil.trim(String.valueOf(sheetRowDatum.get(6)))); + setExt04(StringUtil.trim(String.valueOf(sheetRowDatum.get(7)))); + setExt05(StringUtil.trim(String.valueOf(sheetRowDatum.get(8)))); + setExt06(StringUtil.trim(String.valueOf(sheetRowDatum.get(9)))); + setExt07(StringUtil.trim(String.valueOf(sheetRowDatum.get(10)))); + setExt08(StringUtil.trim(String.valueOf(sheetRowDatum.get(11)))); + setExt09(StringUtil.trim(String.valueOf(sheetRowDatum.get(12)))); + setExt10(StringUtil.trim(String.valueOf(sheetRowDatum.get(13)))); + }}; + bandConfigMapper.updateByPrimaryKeySelective(bandConfig); + } + } + + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("数据导入失败"); + } + + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/JsadapterServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/JsadapterServiceImpl.java new file mode 100644 index 0000000..963c9a2 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/JsadapterServiceImpl.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.JsadapterService; +import com.cmsen.ticket.domain.entity.Jsadapter; +import com.cmsen.ticket.domain.mapper.JsadapterMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class JsadapterServiceImpl implements JsadapterService { + + @Resource + private JsadapterMapper jsadapterMapper; + + @Override + public RestResponse list(Map params) { + PaginationUtil.paginationInit(params); + + List list = jsadapterMapper.listByParams(params); + int total = jsadapterMapper.countByParams(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Override + public RestResponse create(Jsadapter jsadapter) { + jsadapterMapper.insert(jsadapter); + return RestResponse.success(); + } + + @Override + public RestResponse update(Jsadapter jsadapter) { + jsadapterMapper.updateByPrimaryKeySelective(jsadapter); + return RestResponse.success(); + } + + @Override + public RestResponse delete(Integer id) { + jsadapterMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/PreferencesServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/PreferencesServiceImpl.java new file mode 100644 index 0000000..b2def1e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/PreferencesServiceImpl.java @@ -0,0 +1,146 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import cn.hutool.core.io.IoUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.FileMime; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.PreferencesService; +import com.cmsen.ticket.domain.entity.Preferences; +import com.cmsen.ticket.domain.mapper.manager.PreferencesMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2023/6/26 16:06 + **/ +@Slf4j +@Service +public class PreferencesServiceImpl implements PreferencesService { + + @Resource + private PreferencesMapper preferencesMapper; + + @Override + public RestResponse list(Map params) { + //PaginationUtil.paginationInit(params); + params.put("pageNum",params.get("pageNo").toString()); + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + + List list = preferencesMapper.list(params); + int count = preferencesMapper.count(params); + + return RestResponse.success(PaginationUtil.getPageResult(count, params, list)); + } + + + @Override + public RestResponse update(Preferences preferences) { + preferencesMapper.updateByPrimaryKeySelective(preferences); + return RestResponse.success(); + } + + @Override + public RestResponse insert(Preferences preferences) { + preferencesMapper.insert(preferences); + return RestResponse.success(); + } + + @Override + public RestResponse delete(Integer id) { + preferencesMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } + + @Override + public RestResponse export(Map params, HttpServletResponse response) { + + response.reset(); + ServletOutputStream out = null; + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=export.xlsx"); + out = response.getOutputStream(); + List list = preferencesMapper.list(params); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "费用优选项") + .head(Preferences.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + //response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Transactional + @Override + public RestResponse upload(MultipartFile file) { + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + //先进行判断:为空 + for (int i = 0; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + if(StringUtil.isEmpty(sheetRowDatum.get(0))){ + return RestResponse.failure("第"+(i+2)+"行的发票类型为空,请检查!"); + } + if(StringUtil.isEmpty(sheetRowDatum.get(1))){ + return RestResponse.failure("第"+(i+2)+"行的消费类型为空,请检查!"); + } + if(StringUtil.isEmpty(sheetRowDatum.get(2))){ + return RestResponse.failure("第"+(i+2)+"行的费用类型为空,请检查!"); + } + } + //数据处理 + for (int i = 0; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + int invoiceType = Integer.parseInt(StringUtil.trim(String.valueOf(sheetRowDatum.get(0)))); //发票类型 + String consumptionType = StringUtil.trim(String.valueOf(sheetRowDatum.get(1))); //消费类型 + + Preferences bean = preferencesMapper.selectByTicketTypeAndConsumeType(invoiceType, consumptionType); + if(bean == null){//插入 + Preferences preferences = new Preferences(){{ + setInvoiceType(invoiceType); + setConsumptionType(consumptionType); + setExpenseTypes(StringUtil.trim(String.valueOf(sheetRowDatum.get(2)))); + }}; + preferencesMapper.insert(preferences); + }else{//更新 + Preferences preferences = new Preferences(){{ + setId(bean.getId()); + setExpenseTypes(StringUtil.trim(String.valueOf(sheetRowDatum.get(2)))); + }}; + preferencesMapper.updateByPrimaryKeySelective(preferences); + } + } + + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("数据导入失败"); + } + + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/ProcureOrderServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/ProcureOrderServiceImpl.java new file mode 100644 index 0000000..4ed19ed --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/ProcureOrderServiceImpl.java @@ -0,0 +1,412 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.alibaba.excel.EasyExcel; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.ProcureOrderService; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.Supplier; +import com.cmsen.ticket.domain.entity.SupplierPo; +import com.cmsen.ticket.domain.entity.SupplierPoLine; +import com.cmsen.ticket.domain.mapper.CorporateInvoiceMapper; +import com.cmsen.ticket.domain.mapper.SupplierMapper; +import com.cmsen.ticket.domain.mapper.SupplierPoLineMapper; +import com.cmsen.ticket.domain.mapper.SupplierPoMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.cmsenframework.security.RequestSecurityPolicy; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.InputStream; +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class ProcureOrderServiceImpl implements ProcureOrderService { + + @Resource + private SupplierPoMapper supplierPoMapper; + + @Resource + private SupplierPoLineMapper supplierPoLineMapper; + + @Resource + private SupplierMapper supplierMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Override + public RestResponse list(Map params) { + + PaginationUtil.paginationInit(params); + List list = supplierPoMapper.list(params); + int count = supplierPoMapper.count(params); + + return RestResponse.success(PaginationUtil.getPageResult(count, params, list)); + } + + @Override + public RestResponse detail(String po) { + SupplierPo supplierPo = supplierPoMapper.selectByPo(po); + + List line = supplierPoLineMapper.selectByPo(po); + supplierPo.setLine(line); + + return RestResponse.success(supplierPo); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(SupplierPo supplierPo) { + + supplierPo.setNetAmount("0"); + supplierPo.setCreateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + supplierPo.setCreateDate(new Date()); + + supplierPoMapper.insertSelective(supplierPo); + + return RestResponse.success(supplierPo); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(SupplierPo supplierPo) { + supplierPo.setUpdateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + supplierPo.setUpdateDate(new Date()); + + supplierPoMapper.updateByPrimaryKeySelective(supplierPo); + + return RestResponse.success(supplierPo); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse deletePo(Integer id) { + SupplierPo supplierPo = supplierPoMapper.selectByPrimaryKey(id); + + if(supplierPo == null){ + return RestResponse.failure("采购订单不存在,请确认"); + } + + supplierPoMapper.deleteByPo(supplierPo.getPo()); + + supplierPoLineMapper.deleteByPo(supplierPo.getPo()); + + return RestResponse.success(); + } + + @Override + public RestResponse lineList(Map params) { + + PaginationUtil.paginationInit(params); + List list = supplierPoLineMapper.list(params); + int count = supplierPoLineMapper.count(params); + + return RestResponse.success(PaginationUtil.getPageResult(count, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse createLine(SupplierPoLine supplierPoLine) { + supplierPoLine.setCreateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + supplierPoLine.setCreateDate(new Date()); + + supplierPoLineMapper.insertSelective(supplierPoLine); + + //更新po金额 + SupplierPo supplierPo = supplierPoMapper.selectByPo(supplierPoLine.getPo()); + supplierPo.setNetAmount(new BigDecimal(supplierPo.getNetAmount()).add(new BigDecimal(supplierPoLine.getNetLineAmount())).toString()); + supplierPoMapper.updateByPrimaryKeySelective(supplierPo); + + return RestResponse.success(supplierPoLine); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse updateLine(SupplierPoLine supplierPoLine) { + + //得到原来的明细行 + SupplierPoLine oldLine = supplierPoLineMapper.selectByPrimaryKey(supplierPoLine.getId()); + if(!oldLine.getNetLineAmount().equals(supplierPoLine.getNetLineAmount())){ + //更新po金额 + SupplierPo supplierPo = supplierPoMapper.selectByPo(supplierPoLine.getPo()); + supplierPo.setNetAmount(new BigDecimal(supplierPo.getNetAmount()).subtract(new BigDecimal(oldLine.getNetLineAmount())).add(new BigDecimal(supplierPoLine.getNetLineAmount())).toString()); + supplierPoMapper.updateByPrimaryKeySelective(supplierPo); + } + + supplierPoLine.setUpdateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + supplierPoLine.setUpdateDate(new Date()); + + supplierPoLineMapper.updateByPrimaryKeySelective(supplierPoLine); + + return RestResponse.success(supplierPoLine); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse deleteLine(String ids, String po) { + if(StringUtil.isBlank(ids)){ + return RestResponse.failure("请选择要删除的明细行"); + } + + String[] idArr = ids.split(","); + for (String id : idArr) { + + SupplierPoLine supplierPoLine = supplierPoLineMapper.selectByPrimaryKey(Integer.parseInt(id)); + + //更新po金额 + SupplierPo supplierPo = supplierPoMapper.selectByPo(po); + supplierPo.setNetAmount(new BigDecimal(supplierPo.getNetAmount()).subtract(new BigDecimal(supplierPoLine.getNetLineAmount())).toString()); + supplierPoMapper.updateByPrimaryKeySelective(supplierPo); + + //删除行记录 + supplierPoLineMapper.deleteById(Integer.parseInt(id)); + } + return RestResponse.success(); + } + + @Transactional + @Override + public RestResponse uploadPo(MultipartFile file) { + try { + InputStream inputStream = file.getInputStream(); + + //PO数据 + List> sheetRowData1 = EasyExcel.read(inputStream).sheet(0).doReadSync(); + //数据必填判断 + for (int i = 0; i < sheetRowData1.size(); i++) { + Map sheetRowDatum = sheetRowData1.get(i); + String po = StringUtil.trim(String.valueOf(sheetRowDatum.get(0))); + String companyCode = StringUtil.trim(String.valueOf(sheetRowDatum.get(4))); + String supplierCode = StringUtil.trim(String.valueOf(sheetRowDatum.get(5))); + String supplierName = StringUtil.trim(String.valueOf(sheetRowDatum.get(6))); + //String netAmount = StringUtil.trim(String.valueOf(sheetRowDatum.get(7))); + String currency = StringUtil.trim(String.valueOf(sheetRowDatum.get(8))); + String costCenter = StringUtil.trim(String.valueOf(sheetRowDatum.get(9))); + String requestersName = StringUtil.trim(String.valueOf(sheetRowDatum.get(10))); + + if(StringUtil.isBlank(po) || StringUtil.isBlank(companyCode) || StringUtil.isBlank(supplierCode) + || StringUtil.isBlank(supplierName) || StringUtil.isBlank(currency) + || StringUtil.isBlank(costCenter)|| StringUtil.isBlank(requestersName)){ + return RestResponse.failure("po导入中存在必填项为空,请检查!"); + } + } + + //数据po处理 + for (int i = 0; i < sheetRowData1.size(); i++) { + + Map sheetRowDatum = sheetRowData1.get(i); + String po = StringUtil.trim(String.valueOf(sheetRowDatum.get(0))); + String versionNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(1) == null ? "" : sheetRowDatum.get(1))); + // 2024 0709 orderDate作为 税额 去除千分号 + String orderDate = StringUtil.trim(String.valueOf(sheetRowDatum.get(2) == null ? "" : sheetRowDatum.get(2))).replace(",",""); + String contractNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(3) == null ? "" : sheetRowDatum.get(3))); + String companyCode = StringUtil.trim(String.valueOf(sheetRowDatum.get(4))); + String supplierCode = StringUtil.trim(String.valueOf(sheetRowDatum.get(5))); + String supplierName = StringUtil.trim(String.valueOf(sheetRowDatum.get(6))); + String netamount = StringUtil.trim(String.valueOf(sheetRowDatum.get(7))).replace(",",""); + String currency = StringUtil.trim(String.valueOf(sheetRowDatum.get(8))); + String costCenter = StringUtil.trim(String.valueOf(sheetRowDatum.get(9))); + String requestersName = StringUtil.trim(String.valueOf(sheetRowDatum.get(10))); + String poType = StringUtil.trim(String.valueOf(sheetRowDatum.get(11) == null ? "" : sheetRowDatum.get(11))); + String contacts = StringUtil.trim(String.valueOf(sheetRowDatum.get(12) == null ? "" : sheetRowDatum.get(12))); + String mailAddress = StringUtil.trim(String.valueOf(sheetRowDatum.get(13) == null ? "" : sheetRowDatum.get(13))); + + if(StringUtils.isNotEmpty(supplierCode)){ + Supplier supplier = supplierMapper.selectCodeByNameAndCode2(null,supplierCode); + if(null==supplier){ + supplier = new Supplier(); + supplier.setCode(supplierCode); + supplier.setName(supplierName); + supplier.setTaxNo(supplierName); + supplier.setStatus(1); + supplierMapper.insert(supplier); + } + } + + // 2024-05-13 目前用versionNo 表示 发票号码 更新 发票中的PO + if(StringUtils.isNotEmpty(versionNo)){ + List invoices = corporateInvoiceMapper.selectByInvoiceNumber(versionNo); + for (CorporateInvoice invoice : invoices) { + Integer status = invoice.getStatus(); + if(1!=status){ + // 不在已完成中 + invoice.setPo(po); + invoice.setUpdateDate(new Date()); + corporateInvoiceMapper.updateByPrimaryKeySelective(invoice); + } + } + } + if(po.startsWith("virtual")){ + SupplierPo bean = new SupplierPo(); + bean.setPo(po); + bean.setVersionNo(versionNo); + bean.setOrderDate(orderDate); + bean.setContractNo(contractNo); + bean.setCompanyCode(companyCode); + bean.setSupplierCode(supplierCode); + bean.setSupplierName(supplierName); + bean.setCurrency(currency); + bean.setCostCenter(costCenter); + bean.setRequestersName(requestersName); + bean.setPoType(poType); + bean.setContacts(contacts); + bean.setMailAddress(mailAddress); + bean.setNetAmount(netamount); + bean.setCreateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + bean.setCreateDate(new Date()); + supplierPoMapper.insertSelective(bean); + }else{ + SupplierPo supplierPo = supplierPoMapper.selectByNumber(versionNo); + if(supplierPo != null){ + supplierPo.setPo(po); + supplierPo.setOrderDate(orderDate); + supplierPo.setContractNo(contractNo); + supplierPo.setCompanyCode(companyCode); + supplierPo.setSupplierCode(supplierCode); + supplierPo.setSupplierName(supplierName); + supplierPo.setCurrency(currency); + supplierPo.setCostCenter(costCenter); + supplierPo.setRequestersName(requestersName); + supplierPo.setPoType(poType); + supplierPo.setContacts(contacts); + supplierPo.setMailAddress(mailAddress); + supplierPo.setNetAmount(netamount); + supplierPo.setUpdateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + supplierPo.setUpdateDate(new Date()); + supplierPo.setExt01(versionNo); + supplierPoMapper.updateByPrimaryKeySelective(supplierPo); + }else{ + SupplierPo bean = new SupplierPo(); + bean.setPo(po); + bean.setVersionNo(versionNo); + bean.setOrderDate(orderDate); + bean.setContractNo(contractNo); + bean.setCompanyCode(companyCode); + bean.setSupplierCode(supplierCode); + bean.setSupplierName(supplierName); + bean.setCurrency(currency); + bean.setCostCenter(costCenter); + bean.setRequestersName(requestersName); + bean.setPoType(poType); + bean.setContacts(contacts); + bean.setMailAddress(mailAddress); + bean.setNetAmount(netamount); + bean.setCreateBy(String.valueOf(RequestSecurityPolicy.getUserId())); + bean.setCreateDate(new Date()); + supplierPoMapper.insertSelective(bean); + } + } + + } + + //PO-line数据 +// InputStream inputStream2 = file.getInputStream(); +// List> sheetRowData2 = EasyExcel.read(inputStream2).sheet(1).doReadSync(); +// //数据必填判断 +// for (int i = 0; i < sheetRowData2.size(); i++) { +// Map sheetRowDatum = sheetRowData2.get(i); +// String po = StringUtil.trim(String.valueOf(sheetRowDatum.get(0) == null ? "" :sheetRowDatum.get(0))); +// String lineNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(1)== null ? "" :sheetRowDatum.get(1))); +// String materialNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(2)== null ? "" :sheetRowDatum.get(2))); +// String materialDesc = StringUtil.trim(String.valueOf(sheetRowDatum.get(3)== null ? "" :sheetRowDatum.get(3))); +// String quantity = StringUtil.trim(String.valueOf(sheetRowDatum.get(4)== null ? "" :sheetRowDatum.get(4))); +// String unit = StringUtil.trim(String.valueOf(sheetRowDatum.get(5)== null ? "" :sheetRowDatum.get(5))); +// String unitPrice = StringUtil.trim(String.valueOf(sheetRowDatum.get(6)== null ? "" :sheetRowDatum.get(6))).replace(",",""); +// String tax = StringUtil.trim(String.valueOf(sheetRowDatum.get(7)== null ? "" :sheetRowDatum.get(7))); +// String discount = StringUtil.trim(String.valueOf(sheetRowDatum.get(8)== null ? "" :sheetRowDatum.get(8))); +// String netLineAmount = StringUtil.trim(String.valueOf(sheetRowDatum.get(9)== null ? "" :sheetRowDatum.get(9))).replace(",",""); +// +// if(StringUtil.isBlank(po) || StringUtil.isBlank(lineNo) || StringUtil.isBlank(materialNo) +// || StringUtil.isBlank(materialDesc) || StringUtil.isBlank(quantity) +// || StringUtil.isBlank(unit)|| StringUtil.isBlank(unitPrice) +// // 2024-02-22 不需要必填 +//// || StringUtil.isBlank(tax) +//// || StringUtil.isBlank(discount) +// || StringUtil.isBlank(netLineAmount)){ +// return RestResponse.failure("po-line导入中存在必填项为空,请检查!"); +// } +// +// //判断po号是否存在 +// SupplierPo supplierPo = supplierPoMapper.selectByPo(po); +// if(supplierPo == null){ +// return RestResponse.failure("po-line中的PO号("+po+")不存在,请检查!"); +// } +// } +// +// //数据po-line处理 +// String uuid = StringUtil.UUID(); +// for (int i = 0; i < sheetRowData2.size(); i++) { +// Map sheetRowDatum = sheetRowData2.get(i); +// String po = StringUtil.trim(String.valueOf(sheetRowDatum.get(0))); +// SupplierPo supplierPo = supplierPoMapper.selectByPo(po); +// if(supplierPo == null){ +// return RestResponse.failure("po-line中的PO号("+po+")不存在,请检查!"); +// } +// +// String lineNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(1)== null ? "" :sheetRowDatum.get(1))); +// String materialNo = StringUtil.trim(String.valueOf(sheetRowDatum.get(2)== null ? "" :sheetRowDatum.get(2))); +// String materialDesc = StringUtil.trim(String.valueOf(sheetRowDatum.get(3)== null ? "" :sheetRowDatum.get(3))); +// String quantity = StringUtil.trim(String.valueOf(sheetRowDatum.get(4)== null ? "" :sheetRowDatum.get(4))).replace(",",""); +// String unit = StringUtil.trim(String.valueOf(sheetRowDatum.get(5)== null ? "" :sheetRowDatum.get(5))); +// String unitPrice = StringUtil.trim(String.valueOf(sheetRowDatum.get(6)== null ? "" :sheetRowDatum.get(6))).replace(",",""); +// String tax = StringUtil.trim(String.valueOf(sheetRowDatum.get(7)== null ? "" :sheetRowDatum.get(7))).replace(",",""); +// String discount = StringUtil.trim(String.valueOf(sheetRowDatum.get(8)== null ? "" :sheetRowDatum.get(8))).replace(",",""); +// String netLineAmount = StringUtil.trim(String.valueOf(sheetRowDatum.get(9)).replace(",","")).replace(",",""); +// String payDate = StringUtil.trim(String.valueOf(sheetRowDatum.get(10) == null ? "" : sheetRowDatum.get(10))); +// +// SupplierPoLine line = supplierPoLineMapper.selectByPoAndLineNo(po, lineNo); +// if(line != null){ +// line.setMaterialNo(materialNo); +// line.setMaterialDesc(materialDesc); +// line.setQuantity(quantity); +// line.setUnit(unit); +// line.setUnitPrice(unitPrice); +// line.setTax(tax); +// line.setDiscount(discount); +// line.setNetLineAmount(netLineAmount); +// line.setPayDate(payDate); +// line.setExt01(uuid);//记录本次导入 +// line.setUpdateBy(String.valueOf(RequestSecurityPolicy.getUserId())); +// line.setUpdateDate(new Date()); +// supplierPoLineMapper.updateByPrimaryKeySelective(line); +// }else{ +// SupplierPoLine bean = new SupplierPoLine(); +// bean.setPo(po); +// bean.setLineNo(lineNo); +// bean.setMaterialNo(materialNo); +// bean.setMaterialDesc(materialDesc); +// bean.setQuantity(quantity); +// bean.setUnit(unit); +// bean.setUnitPrice(unitPrice); +// bean.setTax(tax); +// bean.setDiscount(discount); +// bean.setNetLineAmount(netLineAmount); +// bean.setPayDate(payDate); +// bean.setExt01(uuid);//记录本次导入 +// bean.setCreateBy(String.valueOf(RequestSecurityPolicy.getUserId())); +// bean.setCreateDate(new Date()); +// supplierPoLineMapper.insertSelective(bean); +// } +// } + + //更新po的金额 +// supplierPoMapper.updateAmount(uuid); + + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("po导入失败"); + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/RuleServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/RuleServiceImpl.java new file mode 100644 index 0000000..6adaee0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/RuleServiceImpl.java @@ -0,0 +1,82 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.RuleService; +import com.cmsen.ticket.domain.entity.Rule; +import com.cmsen.ticket.domain.mapper.RuleMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author + * @version 1.0.0 + * @date 2024/2/18 16:23 + **/ +@Slf4j +@Service +public class RuleServiceImpl implements RuleService { + @Resource + private RuleMapper ruleMapper; + + @Override + public RestResponse list(Map params) { + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + List list = ruleMapper.listByParams(params); + int total = ruleMapper.countByParams(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(Rule rule) { + try { + int count = ruleMapper.checkRule(rule.getName(), rule.getType(), null); + if (count > 0) { + return RestResponse.failure("该类型的规则名称已存在。"); + } + rule.setClientId(1); + ruleMapper.insertSelective(rule); + return RestResponse.success(rule); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(Rule rule) { + try { + int count = ruleMapper.checkRule(rule.getName(), rule.getType(), rule.getId()); + if (count > 0) { + return RestResponse.failure("该类型的规则名称已存在。"); + } + + ruleMapper.updateByPrimaryKeySelective(rule); + return RestResponse.success(rule); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + ruleMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SearchValueServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SearchValueServiceImpl.java new file mode 100644 index 0000000..b115f3d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SearchValueServiceImpl.java @@ -0,0 +1,44 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SearchValueService; +import com.cmsen.ticket.domain.mapper.CustomerMapper; +import com.cmsen.ticket.domain.mapper.RuleMapper; +import com.cmsen.ticket.domain.mapper.TicketTypeMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class SearchValueServiceImpl implements SearchValueService { + @Resource + private CustomerMapper customerMapper; + + @Resource + private SysOrgMapper sysOrgMapper; + @Resource + private RuleMapper ruleMapper; + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Override + public RestResponse clients() { + return RestResponse.success(customerMapper.queryAll(null)); + } + + @Override + public RestResponse rules(Integer type) { + return RestResponse.success(ruleMapper.list(type)); + } + + @Override + public RestResponse ticketTypes() { + return RestResponse.success(ticketTypeMapper.list()); + } + + @Override + public RestResponse orgs() { + return RestResponse.success(sysOrgMapper.list(null)); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SqlDownloadServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SqlDownloadServiceImpl.java new file mode 100644 index 0000000..1d35006 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SqlDownloadServiceImpl.java @@ -0,0 +1,143 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import cn.hutool.core.io.IoUtil; +import cn.hutool.poi.excel.ExcelUtil; +import cn.hutool.poi.excel.ExcelWriter; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.SqlDownloadService; +import com.cmsen.ticket.domain.dto.SqlDownloadDto; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.response.Response; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + */ +@Service +public class SqlDownloadServiceImpl implements SqlDownloadService { + + @Resource + private JdbcTemplate jdbcTemplate; + @Resource + private SysUserMapper sysUserMapper; + + @Override + public Response> getListData(SqlDownloadDto downloadDto) { + try { + if (StringUtil.isNotBlank(downloadDto.getStatement()) && downloadDto.getStatement().toLowerCase().startsWith("select")) { + + //先查询总数 + String interfaceListSql = downloadDto.getStatement(); + List> resTotal = sysUserMapper.execSelectSql(interfaceListSql); + if (resTotal.isEmpty()) { + return Response.failure("查询记录为空"); + }else{//查询每个分页数据 + int s = (Integer.parseInt(downloadDto.getPageNo()) - 1) * Integer.parseInt(downloadDto.getPageSize()); + int e = Integer.parseInt(downloadDto.getPageSize()); + interfaceListSql = downloadDto.getStatement() + " limit "+ s +"," + e; + List> res = sysUserMapper.execSelectSql(interfaceListSql); + Map dataMap = new HashMap<>(); + dataMap.put("total",resTotal.size()); + dataMap.put("data",res); + return Response.success(dataMap); + } + + + + /*List> res = jdbcTemplate.queryForList(downloadDto.getStatement()); + if (res.isEmpty()) { + return Response.failure("查询记录为空"); + }*/ + + } + return Response.failure("请输入正确的sql语句"); + } catch (Exception e) { + return Response.failure(e.getMessage()); + } + } + + @Override + public Response>> getListData2(SqlDownloadDto downloadDto) { + try { + if (StringUtil.isNotBlank(downloadDto.getStatement()) && downloadDto.getStatement().toLowerCase().startsWith("select")) { + + List> res = jdbcTemplate.queryForList(downloadDto.getStatement()); + if (res.isEmpty()) { + return Response.failure("查询记录为空"); + } + return Response.success(res); + } + return Response.failure("请输入正确的sql语句"); + } catch (Exception e) { + return Response.failure(e.getMessage()); + } + } + + /*@Override + public Response exportListData(SqlDownloadDto downloadDto, HttpServletResponse response) { + if (StringUtil.isBlank(downloadDto.getStatement()) || !downloadDto.getStatement().toLowerCase().startsWith("select")) { + return Response.failure("请输入正确的sql语句"); + } + ServletOutputStream out = null; + ExcelWriter writer = null; + try { + out = response.getOutputStream(); + List> rows = jdbcTemplate.queryForList(downloadDto.getStatement()); + if (rows.isEmpty()) { + return Response.failure("查询记录为空"); + } + if (rows.size() > 5000) { + return Response.failure("导出记录不可大于5000条"); + } + writer = ExcelUtil.getWriter(true); + writer.write(rows, true); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); + response.setHeader("Content-Disposition", "attachment;filename=SQL_EXPORT_DATA.xlsx"); + writer.flush(out, true); + } catch (Exception e) { + return null; + } finally { + IoUtil.close(writer); + IoUtil.close(out); + } + return null; + }*/ + + @Override + public Response exportListData(Map params, HttpServletResponse response) { + if (StringUtil.isBlank(params.get("statement").toString()) || !params.get("statement").toString().toLowerCase().startsWith("select")) { + return Response.failure("请输入正确的sql语句"); + } + ServletOutputStream out = null; + ExcelWriter writer = null; + try { + out = response.getOutputStream(); + List> rows = jdbcTemplate.queryForList(params.get("statement").toString()); + if (rows.isEmpty()) { + return Response.failure("查询记录为空"); + } + if (rows.size() > 5000) { + return Response.failure("导出记录不可大于5000条"); + } + writer = ExcelUtil.getWriter(true); + writer.write(rows, true); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); + response.setHeader("Content-Disposition", "attachment;filename=SQL_EXPORT_DATA.xlsx"); + writer.flush(out, true); + } catch (Exception e) { + return null; + } finally { + IoUtil.close(writer); + IoUtil.close(out); + } + return null; + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierMaterialDefineServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierMaterialDefineServiceImpl.java index f2e2e02..5452870 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierMaterialDefineServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierMaterialDefineServiceImpl.java @@ -4,10 +4,13 @@ import com.cmsen.common.http.response.RestResponse; import com.cmsen.ticket.application.manager.service.SupplierMaterialDefineService; import com.cmsen.ticket.domain.entity.SupplierMaterialDefine; import com.cmsen.ticket.domain.mapper.SupplierMaterialDefineMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; +import java.util.List; import java.util.Map; /** @@ -21,10 +24,13 @@ public class SupplierMaterialDefineServiceImpl implements SupplierMaterialDefine @Resource private SupplierMaterialDefineMapper mapper; - @Override public RestResponse list(Map params) { - return null; + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + + List list = mapper.listByParams(params); + int total = mapper.countByParams(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); } @Override diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierServiceImpl.java index fa119b4..bce9cda 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierServiceImpl.java @@ -7,12 +7,21 @@ */ package com.cmsen.ticket.application.manager.service.impl; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ZipUtil; +import cn.hutool.http.HttpRequest; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ContentEnctype; import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.FileMime; import com.cmsen.common.util.StringUtil; import com.cmsen.ticket.application.manager.service.SupplierService; import com.cmsen.ticket.application.manager.vo.GetMaterialParamVo; @@ -21,38 +30,49 @@ import com.cmsen.ticket.application.manager.vo.SupplierInvoiceMatchOrderVo; import com.cmsen.ticket.application.manager.vo.SupplierMaterialDefineVo; import com.cmsen.ticket.application.service.SupplierOutService; import com.cmsen.ticket.bestsign.util.InterfaceUtil; -import com.cmsen.ticket.domain.dto.InvoiceItemListDto; -import com.cmsen.ticket.domain.dto.SubmitLineMatchDto; -import com.cmsen.ticket.domain.dto.SupplierPODto; -import com.cmsen.ticket.domain.dto.SupplierUomMappingDTO; +import com.cmsen.ticket.domain.dto.*; import com.cmsen.ticket.domain.entity.*; -import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; -import com.cmsen.ticket.domain.entity.manager.SysConfig; -import com.cmsen.ticket.domain.entity.manager.SysRole; -import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.entity.manager.*; import com.cmsen.ticket.domain.mapper.*; import com.cmsen.ticket.domain.mapper.manager.*; import com.cmsen.ticket.domain.response.Response; import com.cmsen.ticket.domain.util.PaginationUtil; -import com.cmsen.ticket.domain.vo.AIMaterialVO; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.util.StringUtils; +import com.cmsen.ticket.domain.vo.*; import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; -import com.cmsen.ticket.interfaces.facade.form.SupplierInvoiceMatchForm; -import com.cmsen.ticket.interfaces.facade.manager.form.SupplierUpdatePriceForm; +import com.cmsen.ticket.interfaces.facade.manager.form.*; import com.cmsen.ticket.log.service.TInterfaceLogService; import com.cmsenframework.security.RequestSecurityPolicy; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.RoundingMode; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; import java.util.*; +import java.util.stream.Collectors; @Slf4j @Service @@ -64,7 +84,7 @@ public class SupplierServiceImpl implements SupplierService { @Resource private SupplierMapper supplierMapper; @Resource - private SupplierOutService supplierOutService; + private SupplierSiteMapper supplierSiteMapper; @Resource private SupplierOrderMapper supplierOrderMapper; @Resource @@ -80,25 +100,25 @@ public class SupplierServiceImpl implements SupplierService { @Resource private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; @Resource + private FileMapper fileMapper; + @Resource private SupplierMatchingMapper supplierMatchingMapper; @Resource private SupplierMatchingLogMapper supplierMatchingLogMapper; - @Resource - private SupplierStateMapper supplierStateMapper; + @Resource private SupplierOrderItemMatchingMapper supplierOrderItemMatchingMapper; - @Resource - private SysUserOrgMapper sysUserOrgMapper; + @Resource private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; @Resource private TInterfaceLogService interfaceLogService; - @Resource - private RuiZhenOCRService ruiZhenOCRService; // @Resource // private CorporateInvoiceService corporateInvoiceService; -@Resource -private SysRoleMapper sysRoleMapper; + + @Resource + private SysUserOrgMapper sysUserOrgMapper; + @Resource private SysOrgMapper sysOrgMapper; @Resource @@ -107,278 +127,597 @@ private SysRoleMapper sysRoleMapper; @Resource private SysUserMapper sysUserMapper; @Resource + private SysRoleMapper sysRoleMapper; + @Resource private SysUserApproveMapper sysUserApproveMapper; @Resource private SysConfigMapper sysConfigMapper; + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Value("${manager-file.viewPath}") + private String viewPath; + + @Value("${file.domainName}") + private String domainName; + + @Value("${server.servlet.context-path}") + private String contextPath; + + @Value("${file.filepath}") + private String filePath; + + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + + @Resource + private SupplierOutService supplierOutService; @Resource private SupplierDiffAllowMapper supplierDiffAllowMapper; + @Resource + private AccountPeriodMapper accountPeriodMapper; + + + + @Resource + private TaxMappingMapper taxMappingMapper; + + @Resource + private SupplierStateMapper supplierStateMapper; + + @Resource + private SupplierPoMapper supplierPoMapper; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + private String PF_GATEWAY_TOKEN = null; + private final String SPLIT_STR = "::::"; public final String PRICE_CN_NAME = "单价:"; - // ---------------发票匹配--------------- - /** - * 税前逻辑处理 20220927 - * - * @param dto - */ - private Response priceBefore(SubmitLineMatchDto dto) { + + +// private static final Map COUNTER_MAP = new ConcurrentHashMap(); + + @Override + public RestResponse selectList() { + List taxMappings = taxMappingMapper.selectList(); + System.out.println(taxMappings); + return RestResponse.success(taxMappings); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse updateAccountPeriod(CorporateInvoice invoice) { try { - CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); - CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(dto.getItemId()); - List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); - Assert.notNull(item, "发票行不存在"); - List orders = dto.getOrders(); - // 20220619匹配只能有一行 - /* if(orders.size()>1 ||supplierOrderItemMatchings.size()>0){ - throw new ServiceException("只允许一个匹配行"); - }*/ - List insertList = new ArrayList<>(); - BigDecimal itemTotal = new BigDecimal(item.getTotal()); - // 0 税前 1 税后 - Integer priceType = corporateInvoice.getPriceType(); - // 0 金额 1 数量 - Integer matchType = corporateInvoice.getMatchType(); - for (SubmitLineMatchDto.SupplierOrderDto order : orders) { - //判断 supplier_material 是否存在关系 - if (StringUtil.isNotBlank(order.getItemNo())) { - SupplierMaterial supplierMaterial = new SupplierMaterial() {{ - setSupplierNo(order.getSupplierCode()); - //setMaterialNo(order.getItemNo()); - //setMaterial(order.getGoods()); - setSupplierMaterial(item.getName()); - setSpecification(item.getSpecification()); - }}; - // 20220429修改查询条件 - List lsData = supplierMaterialMapper.getList(supplierMaterial); - supplierMaterial.setMaterialNo(order.getItemNo()); - supplierMaterial.setMaterial(order.getGoods()); - supplierMaterial.setUom(order.getUom()); - if (lsData.size() == 0) { - supplierMaterialMapper.insertSelective(supplierMaterial); - } else { - // 20220517id赋值 - supplierMaterial.setId(lsData.get(0).getId()); - supplierMaterialMapper.updateByPrimaryKeySelective(supplierMaterial); - } - } + return corporateInvoiceMapper.updatePeriodById(invoice) > 0 ? RestResponse.success() : RestResponse.failure("更新异常"); + } catch (Exception e) { + log.error(e.getMessage()); + throw new ServiceException("更新异常"); + } + } - SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); - matching.setInvoiceId(dto.getInvoiceId()); - matching.setItemId(item.getId()); - matching.setOrderId(order.getId()); - matching.setName(order.getGoods()); - matching.setSpecification(item.getSpecification()); - matching.setUnit(order.getUom()); - matching.setPrice(order.getUnitPrice()); - BigDecimal price = new BigDecimal(item.getPrice()); - if (0 == corporateInvoice.getMatchType()) {//金额 - matching.setTotal(order.getUnUsedAmount() == null ? BigDecimal.ZERO : order.getUnUsedAmount()); - // 20220510修改收货数据 - matching.setQuantity(matching.getTotal().divide(order.getUnitPrice(), 2, BigDecimal.ROUND_HALF_UP).toString()); - matching.setReceivedTotal(matching.getTotal()); - } else {// 数量 - matching.setQuantity(String.valueOf(order.getUnUsedQuantity())); - matching.setTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); - matching.setDeductionAmount(BigDecimal.ZERO); - matching.setDeductionTax(BigDecimal.ZERO); - matching.setDeductionTaxRate(item.getDeductionTaxRate()); - matching.setReceivedTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); + @Override + public RestResponse supplierSelectStatus() { + List accountPeriods = accountPeriodMapper.selectByStatus(); + return RestResponse.success(accountPeriods); + } - } - // 税额赋值 - matching.setTax(BigDecimal.ZERO); + @Override + public RestResponse supplierInformationList(SupplierSearchForm form) { + int total = supplierMapper.count(form); + List supplierList = supplierMapper.list(form); + Object dataResult = PaginationUtil.getPageResult(total, form, supplierList); + return RestResponse.success(dataResult); + } - matching.setTaxRate(item.getTaxRate()); - matching.setMatchingStatus(0); - matching.setReceiveNo(order.getReceiveNo()); - matching.setOrderNo(order.getOrderNo()); - matching.setItemNo(order.getItemNo()); - // 20220712匹配total保留两位小数 - matching.setTotal(matching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); - matching.setMatchingId(""); - insertList.add(matching); - } - if (!insertList.isEmpty()) { - supplierOrderItemMatchingMapper.insertBatch(insertList); - } - updateDifference(corporateInvoice, item); + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInformationCreate(Supplier supplier) { + if (supplier == null) { + return RestResponse.failure("非法参数"); + } + try { + supplierMapper.insertSelective(supplier); + return RestResponse.success(supplier); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("创建供应商失败"); + } + } - //插入日志记录 2022/5/28 - SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ - setId(IdUtil.fastUUID()); - setPid(corporateInvoice.getId()); - setModule("InvoiceMatch"); - setMethods("SupplierOrderItemMatch"); - setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); - setCreateTime(new Date()); - setReason("完成发票行【" + item.getName() + "+" + item.getSpecification() + "】的发票匹配"); - }}; - supplierMatchingLogMapper.insert(supplierMatchingLog); + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInformationUpdate(Supplier supplier) { + if (supplier == null) { + return RestResponse.failure("非法参数"); + } + if (supplier.getId() == null || supplier.getId() == 0) { + return RestResponse.failure("供应商不存在"); + } + try { + supplierMapper.updateByPrimaryKeySelective(supplier); + return RestResponse.success(supplier); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新供应商失败"); + } + } - return Response.success(); + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInformationDelete(Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("供应商不存在"); + } + try { + supplierMapper.deleteByPrimaryKey(id); + return RestResponse.success(); } catch (Exception e) { log.error(e.getMessage(), e); - throw new ServiceException("提交异常"); + throw new ServiceException("删除供应商失败"); + } + } + + // ---------------供应商SITE_CODE--------------- + + @Override + public RestResponse supplierSiteCodeList(String code) { + if (code == null) { + return RestResponse.failure("非法参数"); } + List supplierSites = supplierSiteMapper.selectByCode(code); + return RestResponse.success(supplierSites); } + @Transactional(rollbackFor = Exception.class) @Override - public Response submitLineMatchList(SubmitLineMatchDto dto) { + public RestResponse supplierSiteCodeCreate(SupplierSite supplierSite) { + if (supplierSite == null) { + return RestResponse.failure("非法参数"); + } try { - CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); - CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(dto.getItemId()); - List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); - Assert.notNull(item, "发票行不存在"); - List orders = dto.getOrders(); - // 20220619匹配只能有一行 - /* if(orders.size()>1 ||supplierOrderItemMatchings.size()>0){ - throw new ServiceException("只允许一个匹配行"); - }*/ - List insertList = new ArrayList<>(); - BigDecimal itemTotal = new BigDecimal(item.getTotal()); - // // 0 税前 1 税后 - Integer priceType = corporateInvoice.getPriceType(); - // 税前走新逻辑20220927 - if (priceType == 1) { - return priceBefore(dto); + supplierSiteMapper.insertSelective(supplierSite); + return RestResponse.success(supplierSite); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("创建供应商SITE_CODE失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierSiteCodeUpdate(SupplierSite supplierSite) { + if (supplierSite == null) { + return RestResponse.failure("非法参数"); + } + if (supplierSite.getId() == null || supplierSite.getId() == 0) { + return RestResponse.failure("供应商SITE_CODE不存在"); + } + try { + supplierSiteMapper.updateByPrimaryKeySelective(supplierSite); + return RestResponse.success(supplierSite); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新供应商SITE_CODE失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierSiteCodeDelete(@NotNull Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("供应商SITE_CODE不存在"); + } + try { + supplierSiteMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除供应商SITE_CODE失败"); + } + } + + // ---------------订单管理--------------- + + @Override + public RestResponse supplierOrderList(SupplierOrderSearchForm form) { + SysUserOrg sysUserOrg = sysUserOrgMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + if (sysUserOrg != null && !Objects.equals(sysUserOrg.getDataAuthType(), 0)) { + if (Objects.equals(sysUserOrg.getDataAuthType(), 2)) { + form.setSearchOwner(Integer.parseInt(String.valueOf(RequestSecurityPolicy.getUserId()))); + } else { + form.setSearchOrg(Integer.parseInt(String.valueOf(RequestSecurityPolicy.getUserId()))); } - // 获取所有已匹配的数量 - BigDecimal matchedNum = BigDecimal.ZERO; - // - for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { - BigDecimal num = new BigDecimal(supplierOrderItemMatching.getQuantity()); - matchedNum = matchedNum.add(num); + } + int total = supplierOrderMapper.count(form); + List supplierOrderList = supplierOrderMapper.list(form); + Object dataResult = PaginationUtil.getPageResult(total, form, supplierOrderList); + return RestResponse.success(dataResult); + } + + @Override + public RestResponse supplierRefundOrderList(SupplierOrderSearchForm form) { + int total = supplierOrderMapper.refundCount(form); + List refundsupplierOrderList = supplierOrderMapper.listRefund(form); + Object dataResult = PaginationUtil.getPageResult(total, form, refundsupplierOrderList); + return RestResponse.success(dataResult); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierOrderUpdate(@NotNull String ids) { + + if (ids == null || StringUtil.isEmpty(ids)) { + return RestResponse.failure("收货数据不存在"); + } + try { + supplierOrderMapper.updateByOrderIds(ids, 0); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除收货数据失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierOrderClear() { + try { + //查询符合条件的order + List list = supplierOrderMapper.getClearList(); + if (list != null && list.size() > 0) { + String ids = ""; + for (SupplierOrder order : list) { + ids += order.getId().toString() + ","; + } + ids = ids.substring(0, ids.length() - 1); + supplierOrderMapper.updateByOrderIds(ids, 2); } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("数据清理失败"); + } + } + @Override + public RestResponse supplierOrderPOSearch(SupplierOrderSearchForm form) { - // 0 金额 1 数量 - Integer matchType = corporateInvoice.getMatchType(); - for (SubmitLineMatchDto.SupplierOrderDto order : orders) { - //判断 supplier_material 是否存在关系 - if (StringUtil.isNotBlank(order.getItemNo())) { - SupplierMaterial supplierMaterial = new SupplierMaterial() {{ - setSupplierNo(order.getSupplierCode()); - //setMaterialNo(order.getItemNo()); - //setMaterial(order.getGoods()); - setSupplierMaterial(item.getName()); - setSpecification(item.getSpecification()); - }}; - // 20220429修改查询条件 - List lsData = supplierMaterialMapper.getList(supplierMaterial); - supplierMaterial.setMaterialNo(order.getItemNo()); - supplierMaterial.setMaterial(order.getGoods()); - supplierMaterial.setUom(order.getUom()); - if (lsData.size() == 0) { - supplierMaterialMapper.insertSelective(supplierMaterial); - } else { - // 20220517id赋值 - supplierMaterial.setId(lsData.get(0).getId()); - supplierMaterialMapper.updateByPrimaryKeySelective(supplierMaterial); - } - } + int total = supplierOrderItemMatchingMapper.pocount(form); + List supplierOrderList = supplierOrderItemMatchingMapper.polist(form); + Object dataResult = PaginationUtil.getPageResult(total, form, supplierOrderList); + return RestResponse.success(dataResult); + } - SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); - matching.setInvoiceId(dto.getInvoiceId()); - matching.setItemId(item.getId()); - matching.setOrderId(order.getId()); - matching.setName(order.getGoods()); - matching.setSpecification(item.getSpecification()); - matching.setUnit(order.getUom()); - matching.setPrice(order.getUnitPrice()); - BigDecimal price = new BigDecimal(item.getPrice()); - if (0 == corporateInvoice.getMatchType()) {//金额 - //BigDecimal percent = order.getUnUsedAmount().divide(itemTotal, 10, BigDecimal.ROUND_HALF_UP); - matching.setTotal(order.getUnUsedAmount() == null ? BigDecimal.ZERO : order.getUnUsedAmount()); - /*if (StringUtil.isNotBlank(item.getDeductionAmount())) { - matching.setDeductionAmount(new BigDecimal(item.getDeductionAmount()).multiply(percent)); - if (StringUtil.isNotBlank(item.getDeductionTax())) { - matching.setDeductionTax(new BigDecimal(item.getDeductionTax()).multiply(percent)); - } - matching.setDeductionTaxRate(item.getDeductionTaxRate()); - }*/ - // 20220508修改收货数据 - //matching.setQuantity(matching.getTotal().divide(price, 2, BigDecimal.ROUND_HALF_UP).intValue()); - //matching.setQuantity(order.getReceivedNum()); - // 20220510修改收货数据 - matching.setQuantity(matching.getTotal().divide(order.getUnitPrice(), 2, BigDecimal.ROUND_HALF_UP).toString()); - } else {// 数量 - BigDecimal itemQuantity = new BigDecimal(item.getQuantity()); - BigDecimal orderQuantity = new BigDecimal(order.getUnUsedQuantity()); - if (itemQuantity.subtract(matchedNum).compareTo(orderQuantity) >= 0) { - matching.setQuantity(String.valueOf(order.getUnUsedQuantity())); - } else { - matching.setQuantity(String.valueOf(itemQuantity.subtract(matchedNum))); - } - matchedNum = matchedNum.add(new BigDecimal(matching.getQuantity())); - matching.setTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); - matching.setDeductionAmount(BigDecimal.ZERO); - matching.setDeductionTax(BigDecimal.ZERO); - matching.setDeductionTaxRate(item.getDeductionTaxRate()); - /*if (StringUtil.isNotBlank(item.getDeductionAmount())) { - BigDecimal percent = matching.getTotal().divide(itemTotal, 10, BigDecimal.ROUND_HALF_UP); - matching.setDeductionAmount(new BigDecimal(item.getDeductionAmount()).multiply(percent)); - if (StringUtil.isNotBlank(item.getDeductionTax())) { - matching.setDeductionTax(new BigDecimal(item.getDeductionTax()).multiply(percent)); - } - matching.setDeductionTaxRate(item.getDeductionTaxRate()); - }*/ - } + @Override + public RestResponse supplierOrderPOExportExcel(Map params, HttpServletResponse response) { + ServletOutputStream out = null; + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + StringUtils.decoderUrl(params); + List list = supplierOrderItemMatchingMapper.poMaplist(params); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "PO发票匹配") + .head(SupplierOrderItemMatching.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } - if (StringUtil.isNotBlank(item.getTax())) { - BigDecimal tot = itemTotal.add(new BigDecimal(item.getDeductionAmount() == null ? "0" : item.getDeductionAmount())); - if (tot.compareTo(BigDecimal.ZERO) != 0) { - BigDecimal percent = matching.getTotal().divide(tot, 10, BigDecimal.ROUND_HALF_UP); - matching.setTax(new BigDecimal(item.getTax()).add(new BigDecimal(item.getDeductionTax() == null ? "0" : item.getDeductionTax())).multiply(percent).setScale(2, BigDecimal.ROUND_HALF_UP)); + @Override + public RestResponse supplierOrderPODownloadImages(Map params, HttpServletResponse response) { + try { + SysConfig invImgImagesCount = sysConfigMapper.selectByCode("InvImgImagesCount"); + int count = invImgImagesCount == null ? 1000 : Integer.parseInt(invImgImagesCount.getValue()); + ServletOutputStream out = response.getOutputStream(); + List list = supplierOrderItemMatchingMapper.poMaplist(params); + List files = new ArrayList<>(); + String tempDir = uploadPath + System.currentTimeMillis(); + java.io.File fileTemp = new java.io.File(tempDir); + fileTemp.mkdir(); + List fileNames = new ArrayList<>(); + for (SupplierOrderItemMatching supplierOrderItemMatching : list) { + String fileName = supplierOrderItemMatching.getFileName(); + String downloadUri = supplierOrderItemMatching.getDownloadUri(); + if (StringUtil.isNotEmpty(downloadUri)) { + String pathname; + if (downloadUri.contains("/opt")) { + pathname = uploadPath + downloadUri.substring(downloadUri.indexOf("/opt")); } else { - matching.setTax(BigDecimal.ZERO); + pathname = uploadPath + downloadUri.substring(downloadUri.lastIndexOf("/")); + } + if (!fileName.equals("null") && new java.io.File(pathname).exists() && !fileNames.contains(pathname)) { + fileNames.add(pathname); + String fileTempName = supplierOrderItemMatching.getInvoiceCode() + "_" + supplierOrderItemMatching.getInvoiceNumber() + "-" + count + pathname.substring(pathname.lastIndexOf(".")); + java.io.File copy = FileUtil.copy(pathname, tempDir + java.io.File.separator + fileTempName, true); +// File file = FileUtil.file(pathname); + files.add(copy); + count--; + } + if (count == 0) { + break; } } - // 20220509折后判断 - /*if(priceType==0 && matchType==1){ - matching.setTotal(matching.getTotal().add(matching.getDeductionAmount()== null ? BigDecimal.ZERO : matching.getDeductionAmount())); - matching.setTax(matching.getTax().add(matching.getDeductionTax()== null ? BigDecimal.ZERO : matching.getDeductionTax())); - }*/ - matching.setReceivedTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); - - matching.setTaxRate(item.getTaxRate()); - matching.setMatchingStatus(0); - matching.setReceiveNo(order.getReceiveNo()); - matching.setOrderNo(order.getOrderNo()); - matching.setItemNo(order.getItemNo()); - // 20220712匹配total保留两位小数 - matching.setTotal(matching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); - matching.setMatchingId(""); - insertList.add(matching); } - if (!insertList.isEmpty()) { - supplierOrderItemMatchingMapper.insertBatch(insertList); + if (files.isEmpty()) { + return RestResponse.failure("无文件,请确认条件。"); } - updateDifference(corporateInvoice, item); + java.io.File[] filesArray = files.toArray(new java.io.File[0]); + String zipFileName = System.currentTimeMillis() + ".zip"; + java.io.File zipFile = ZipUtil.zip(cn.hutool.core.io.FileUtil.file(uploadPath + zipFileName), false, filesArray); + response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(zipFileName, "UTF-8")); + byte[] bytes = cn.hutool.core.io.FileUtil.readBytes(zipFile); + out.write(bytes); + out.flush(); + IoUtil.close(out); + FileUtil.del(new java.io.File(tempDir)); + return null; + } catch (Exception e) { + log.error(e.getMessage(), e); + return RestResponse.failure(e.getMessage()); + } + } - //插入日志记录 2022/5/28 - SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ - setId(IdUtil.fastUUID()); - setPid(corporateInvoice.getId()); - setModule("InvoiceMatch"); - setMethods("SupplierOrderItemMatch"); - setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); - setCreateTime(new Date()); - setReason("完成发票行【" + item.getName() + "+" + item.getSpecification() + "】的发票匹配"); - }}; - supplierMatchingLogMapper.insert(supplierMatchingLog); + @Override + public RestResponse supplierOrderMatchReport(Map params, HttpServletResponse response) { + //将,转换为, + String orderNos = params.get("orderNo").toString().replace(",", ","); + params.put("orderNos", orderNos); - return Response.success(); + ServletOutputStream out = null; + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + StringUtils.decoderUrl(params); + List list = supplierOrderItemMatchingMapper.reportlist(params); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "虚拟物料匹配报表") + .head(SupplierOrderItemMatchingReport.class) + .doWrite(list); + out.flush(); + return null; } catch (Exception e) { + response.reset(); log.error(e.getMessage(), e); - throw new ServiceException("提交异常"); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + + } + + + @Override + public RestResponse supplierOrderReport(Map params, HttpServletResponse response, SupplierOrderSearchForm form) { + //将,转换为, + ServletOutputStream out = null; + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + int userId = (int) RequestSecurityPolicy.getUserId(); + SysUserOrg sysUserOrg = sysUserOrgMapper.selectByPrimaryKey(userId); + if (sysUserOrg != null && !Objects.equals(sysUserOrg.getDataAuthType(), 0)) { + if (Objects.equals(sysUserOrg.getDataAuthType(), 2)) { + form.setSearchOwner(Integer.parseInt(String.valueOf(userId))); + } else { + form.setSearchOrg(Integer.parseInt(String.valueOf(userId))); + } + } + form.setStartNo(null); + form.setLength(1); +// int total = supplierOrderMapper.count(form); + List supplierOrderList = supplierOrderMapper.list(form); +// List list = supplierOrderItemMatchingMapper.reportlist(params); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "收货数据报表") + .head(SupplierOrder.class) + .doWrite(supplierOrderList); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + + } + + // ---------------物料管理--------------- + + + @Override + public RestResponse supplierMaterialList(SupplierMaterialSearchForm form) { + int total = supplierMaterialMapper.count(form); + List supplierMaterialList = supplierMaterialMapper.list(form); + Object dataResult = PaginationUtil.getPageResult(total, form, supplierMaterialList); + return RestResponse.success(dataResult); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialCreate(SupplierMaterial supplierMaterial) { + if (supplierMaterial == null) { + return RestResponse.failure("非法参数"); + } + try { + supplierMaterialMapper.insertSelective(supplierMaterial); + return RestResponse.success(supplierMaterial); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("创建物料失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialUpdate(SupplierMaterial supplierMaterial) { + if (supplierMaterial == null) { + return RestResponse.failure("非法参数"); + } + if (supplierMaterial.getId() == null || supplierMaterial.getId() == 0) { + return RestResponse.failure("物料不存在"); + } + try { + supplierMaterialMapper.updateByPrimaryKeySelective(supplierMaterial); + return RestResponse.success(supplierMaterial); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新物料失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialDelete(@NotNull Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("物料不存在"); + } + try { + supplierMaterialMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除物料失败"); + } + } + + // ---------------例外物料--------------- + + @Override + public RestResponse supplierMaterialFilterList(SupplierMaterialFilterSearchForm form) { + List supplierMaterialFilterList = supplierMaterialFilterMapper.list(form); + return RestResponse.success(supplierMaterialFilterList); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialFilterCreate(SupplierMaterialFilter supplierMaterialFilter) { + if (supplierMaterialFilter == null) { + return RestResponse.failure("非法参数"); + } + try { + supplierMaterialFilterMapper.insertSelective(supplierMaterialFilter); + return RestResponse.success(supplierMaterialFilter); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("创建物料失败"); } } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialFilterUpdate(SupplierMaterialFilter supplierMaterialFilter) { + if (supplierMaterialFilter == null) { + return RestResponse.failure("非法参数"); + } + if (supplierMaterialFilter.getId() == null || supplierMaterialFilter.getId() == 0) { + return RestResponse.failure("物料不存在"); + } + try { + supplierMaterialFilterMapper.updateByPrimaryKeySelective(supplierMaterialFilter); + return RestResponse.success(supplierMaterialFilter); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新物料失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierMaterialFilterDelete(@NotNull Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("物料不存在"); + } + try { + supplierMaterialFilterMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除物料失败"); + } + } + + // ---------------单位换算--------------- + + + @Override + public RestResponse supplierMaterialUomList(SupplierMaterialUOMSearchForm form) { + int total = supplierMaterialUomMapper.count(form); + List supplierMaterialUomList = supplierMaterialUomMapper.list(form); + Object dataResult = PaginationUtil.getPageResult(total, form, supplierMaterialUomList); + return RestResponse.success(dataResult); + } + + @Override + public RestResponse supplierMaterialUomCreate(SupplierMaterialUom supplierMaterialUom) { + if (supplierMaterialUom == null) { + return RestResponse.failure("非法参数"); + } + try { + supplierMaterialUomMapper.insertSelective(supplierMaterialUom); + return RestResponse.success(supplierMaterialUom); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("创建失败"); + } + } + + @Override + public RestResponse supplierMaterialUomUpdate(SupplierMaterialUom supplierMaterialUom) { + if (supplierMaterialUom == null) { + return RestResponse.failure("非法参数"); + } + if (supplierMaterialUom.getId() == null || supplierMaterialUom.getId() == 0) { + return RestResponse.failure("目标不存在"); + } + try { + supplierMaterialUomMapper.updateByPrimaryKeySelective(supplierMaterialUom); + return RestResponse.success(supplierMaterialUom); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新失败"); + } + } + + @Override + public RestResponse supplierMaterialUomDelete(@NotNull Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("目标不存在"); + } + try { + supplierMaterialUomMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除失败"); + } + } + + // ---------------发票匹配--------------- + @Override public RestResponse SupplierInvoiceMatchList(SupplierInvoiceMatchForm form) { // 1单张发票匹配、2批量发票匹配 @@ -426,18 +765,273 @@ private SysRoleMapper sysRoleMapper; } } + + + @Transactional(rollbackFor = Exception.class) @Override - public RestResponse matchInvoices(String numberS, String numberE, Integer invoiceType) { - List list = corporateInvoiceMapper.supplierInvoiceMatchInvoiceList(numberS, numberE, invoiceType); - for (InvoiceItemListDto invoiceItemListDto : list) { - invoiceItemListDto.setUsedMoney(supplierOrderItemMatchingMapper.getUsedAmountByItemId(invoiceItemListDto.getId())); - } - return RestResponse.success(list); + public RestResponse confirmSend(InvoiceConfirmAndSendForm dto) { + try { + SupplierOrder order = supplierOrderMapper.selectByPrimaryKey(dto.getOrderId()); + Assert.notNull(order, "订单行不存在"); +// List itemIds = dto.getItemIds(); + List itemDtos = dto.getItems(); + for (InvoiceItemListDto itemDto : itemDtos) { + CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(itemDto.getId()); + Assert.notNull(item, "发票行不存在"); + + SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); + String invoiceId = item.getPid(); + matching.setInvoiceId(invoiceId); + matching.setItemId(item.getId()); + matching.setOrderId(order.getId()); + matching.setName(order.getGoods()); + matching.setSpecification(item.getSpecification()); + matching.setUnit(order.getUom()); + matching.setQuantity(String.valueOf(order.getGoodsNum() == null ? 0 : order.getGoodsNum())); + matching.setPrice(order.getUnitPrice() == null ? null : order.getUnitPrice()); + matching.setTotal(itemDto.getMatchedAmount()); + + BigDecimal percent = itemDto.getMatchedAmount().divide(new BigDecimal(item.getTotal()), 5, BigDecimal.ROUND_HALF_UP); + if (StringUtil.isNotBlank(item.getTax())) { + matching.setTax(new BigDecimal(item.getTax()).multiply(percent)); + } + matching.setTaxRate(item.getTaxRate()); + matching.setMatchingStatus(0); + matching.setReceiveNo(order.getReceiveNo()); + matching.setOrderNo(order.getOrderNo()); + matching.setReceivedTotal(order.getAmount()); + matching.setItemNo(order.getItemNo()); + if (StringUtil.isNotBlank(item.getDeductionAmount())) { + matching.setDeductionAmount(new BigDecimal(item.getDeductionAmount()).multiply(percent)); + if (StringUtil.isNotBlank(item.getDeductionTax())) { + matching.setDeductionTax(new BigDecimal(item.getDeductionTax()).multiply(percent)); + } + matching.setDeductionTaxRate(item.getDeductionTaxRate()); + } + supplierOrderItemMatchingMapper.insert(matching); + + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + Assert.notNull(corporateInvoice, "发票不存在"); + ArrayList ids = new ArrayList() {{ + add(matching.getId()); + }}; + int i = supplierOrderItemMatchingMapper.completeMatching(ids); + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType != null) { + if (1 == corporateInvoiceType.getReview()) { + corporateInvoice.setMatchStatus(1); + } else if (0 == corporateInvoiceType.getReview()) { + corporateInvoice.setMatchStatus(2); + supplierOutService.sendMatchingData(ids, invoiceId); + } + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(invoiceId); + setMatchStatus(corporateInvoice.getMatchStatus()); + }}); + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("提交异常"); + } } + + //1 物料 2 金额 3 金额+物料 4 全部 + @Override + public RestResponse supplierInvoiceMatchOrderList(String invoiceId, Integer all, String orderNo, Integer pageNum, Integer pageSize) { + //新的代码逻辑 2022/5/9 + if (org.apache.commons.lang3.StringUtils.isEmpty(invoiceId)) { + return RestResponse.failure("非法参数"); + } + //!!!国内发票-含公司 || ext01=CN + //关联单据 & 一键智能匹配+ 供应商税号。 + 金龙 + //向量方式查找供应商名称 匹配 没找到 提示未找到供应商 + //匹配成功 则 调用税号查询ai接口。税号插入supplier表的taxno 。 + + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + + // 原先逻辑 + String supplierCode = corporateInvoiceMapper.selectSupplierCode(invoiceId); + boolean oldSupplierNotExistFlag = false; + if (StringUtil.isBlank(supplierCode)) { + oldSupplierNotExistFlag = true; +// return RestResponse.failure("供应商不存在"); + } + Supplier supplier = supplierMapper.selectByTaxNoCode("", supplierCode); + if (supplier == null) { + oldSupplierNotExistFlag = true; +// return RestResponse.failure("供应商不存在"); + } + supplier = supplierIsExist(oldSupplierNotExistFlag, corporateInvoice, supplier); + if (null == supplier) { + return RestResponse.failure("供应商不存在"); + } + // 20220513判断是否要关联组织 + //SysOrg buyOrg=sysOrgMapper.selectByTaxNo(corporateInvoice.getBuyerNo()); + Company buyCom = companyMapper.checkCoAndTax(null, corporateInvoice.getBuyerNo()); + + SysConfig sysConfig = sysConfigMapper.selectByCode("MATCH_INC_ORG"); + if (corporateInvoice == null) { + return RestResponse.failure("发票不存在"); + } + Integer matchType = corporateInvoice.getMatchType(); + // 20220425分页数据修改 + //List dataResult; + List result; + // 查询参数 + Map param = new HashMap<>(); + if (!supplier.getSupplierSpecial()) { + param.put("supplierCode", supplierCode); + } + param.put("all", all); + param.put("invoiceId", invoiceId); + param.put("matchType", matchType); + // 匹配公司code + if (buyCom != null) { + param.put("companyCode", buyCom.getCompanyCode()); + } + //加上orderNo参数 2022/5/9 + param.put("orderNo", orderNo); + if (sysConfig != null && sysConfig.getValue().equals("1")) { + param.put("sysOrg", corporateInvoice.getOrgId()); + } + + if (all == 1 || all == 2 || all == 3 || all == 4) { + PageHelper.startPage(pageNum, pageSize); + result = supplierOrderMapper.matchOrderBySupplierCodeNew(param); + } else { + result = new ArrayList<>(); + } + + PageInfo pageInfo = new PageInfo<>(result); + return RestResponse.success(pageInfo); + + + // 原来的代码逻辑 2022/5/9 注释 +// if (orderNo == null) { +// if (invoiceId == null) { +// return RestResponse.failure("非法参数"); +// } +// if ("".equals(invoiceId)) { +// return RestResponse.failure("供应商不存在"); +// } +// String supplierCode = corporateInvoiceMapper.selectSupplierCode(invoiceId); +// if (StringUtil.isBlank(supplierCode)) { +// return RestResponse.failure("供应商不存在"); +// } +// Integer matchType = corporateInvoiceMapper.selectByPrimaryKey(invoiceId).getMatchType(); +// // 20220425分页数据修改 +// //List dataResult; +// List result; +// // 查询参数 +// Map param = new HashMap<>(); +// param.put("supplierCode",supplierCode); +// param.put("all",all); +// param.put("invoiceId",invoiceId); +// param.put("matchType",matchType); +// //物料 +// /*if (all == 1) { +// Set materialSet = supplierMaterialMapper.selectMaterialsByInvoiceId(invoiceId, supplierCode); +// result = dataResult.stream().filter(supplierInvoiceMatchOrderVo -> materialSet.contains(supplierInvoiceMatchOrderVo.getGoods() + supplierInvoiceMatchOrderVo.getItemNo())).collect(Collectors.toList()); +// } +// // 金额/数量 +// else if (all == 2) { +// if (matchType.equals(0)) { +// Set invoiceMoneyList = supplierOrderItemMatchingMapper.calculateInvoiceSurplus(invoiceId); +// result = dataResult.stream().filter(supplierInvoiceMatchOrderVo -> invoiceMoneyList.contains(supplierInvoiceMatchOrderVo.getUnUsedAmount().setScale(0, BigDecimal.ROUND_DOWN).intValue())).collect(Collectors.toList()); +// } else { +// Set quantity = supplierOrderItemMatchingMapper.calculateInvoiceSurplusQuantity(invoiceId); +// result = dataResult.stream().filter(supplierInvoiceMatchOrderVo -> quantity.contains(supplierInvoiceMatchOrderVo.getUnUsedQuantity().toString() + supplierInvoiceMatchOrderVo.getUom())).collect(Collectors.toList()); +// } +// } +// // 金额/数量 + 物料 +// else if (all == 3) { +// if (matchType.equals(0)) { +// Set materialSet = supplierMaterialMapper.selectMaterialsByInvoiceId(invoiceId, supplierCode); +// Set invoiceMoneyList = supplierOrderItemMatchingMapper.calculateInvoiceSurplus(invoiceId); +// result = dataResult.stream().filter(supplierInvoiceMatchOrderVo -> invoiceMoneyList.contains(supplierInvoiceMatchOrderVo.getUnUsedAmount().setScale(0, BigDecimal.ROUND_DOWN).intValue()) +// && materialSet.contains(supplierInvoiceMatchOrderVo.getGoods() + supplierInvoiceMatchOrderVo.getItemNo()) +// ).collect(Collectors.toList()); +// } else { +// Set materialSet = supplierMaterialMapper.selectMaterialsByInvoiceId(invoiceId, supplierCode); +// Set quantity = supplierOrderItemMatchingMapper.calculateInvoiceSurplusQuantity(invoiceId); +// result = dataResult.stream().filter(supplierInvoiceMatchOrderVo -> +// materialSet.contains(supplierInvoiceMatchOrderVo.getGoods() + supplierInvoiceMatchOrderVo.getItemNo()) +// && quantity.contains(supplierInvoiceMatchOrderVo.getUnUsedQuantity().toString() + supplierInvoiceMatchOrderVo.getUom())). +// collect(Collectors.toList()); +// } +// }*/ +// if(all==1 || all==2 ||all==3 || all==4){ +// PageHelper.startPage(pageNum,pageSize); +// result = supplierOrderMapper.matchOrderBySupplierCodeNew(param); +// } else { +// result = new ArrayList<>(); +// } +// /*Map resMap = new HashMap<>(); +// result.parallelStream().forEach(supplierInvoiceMatchOrderVo -> { +// if (resMap.containsKey(supplierInvoiceMatchOrderVo.getOrderNo())) { +// SupplierInvoiceMatchOrderVo supplierInvoiceMatchOrderVo1 = resMap.get(supplierInvoiceMatchOrderVo.getOrderNo()); +// supplierInvoiceMatchOrderVo1.setAmount(supplierInvoiceMatchOrderVo1.getAmount().add(supplierInvoiceMatchOrderVo.getAmount())); +// supplierInvoiceMatchOrderVo1.setUsedAmount(supplierInvoiceMatchOrderVo1.getUsedAmount().add(supplierInvoiceMatchOrderVo.getUsedAmount())); +// // 20220425添加 +// resMap.put(supplierInvoiceMatchOrderVo.getOrderNo(),supplierInvoiceMatchOrderVo1); +// } else { +// resMap.put(supplierInvoiceMatchOrderVo.getOrderNo(), new SupplierInvoiceMatchOrderVo() {{ +// setOrderNo(supplierInvoiceMatchOrderVo.getOrderNo()); +// setSupplierCode(supplierInvoiceMatchOrderVo.getSupplierCode()); +// setOrgName(supplierInvoiceMatchOrderVo.getOrgName()); +// setAmount(supplierInvoiceMatchOrderVo.getAmount()); +// setUsedAmount(supplierInvoiceMatchOrderVo.getUsedAmount()); +// setOrderDate(supplierInvoiceMatchOrderVo.getOrderDate()); +// }}); +// } +// }); +// List res = new ArrayList<>(); +// resMap.forEach((k, v) -> res.add(v));*/ +// PageInfo pageInfo = new PageInfo<>(result); +// return RestResponse.success(pageInfo); +// } else if (!"".equals(orderNo)) { +// if (invoiceId != null) { +// return RestResponse.failure("非法参数supplierCode"); +// } +// List dataResult = supplierOrderMapper.selectByOrderNo(orderNo); +// for (SupplierOrder supplierOrder : dataResult) { +// supplierOrder.setUsedAmount(supplierOrderItemMatchingMapper.getUsedAmountByOrderId(supplierOrder.getId())); +// } +// PageHelper.startPage(pageNum,pageSize); +// PageInfo orderPageInfo = new PageInfo<>(dataResult); +// return RestResponse.success(orderPageInfo); +// } +// return RestResponse.failure("非法参数"); + } + + @Override + public RestResponse supplierOrderPOList(String orderNo, Integer pageNum, Integer pageSize) { + + if (orderNo == null || "".equals(orderNo)) { + return RestResponse.failure("非法参数"); + } + + //查询参数 + Map param = new HashMap<>(); + param.put("orderNo", orderNo); + PageHelper.startPage(pageNum, pageSize); + + List result = supplierOrderMapper.polist(param); + + PageInfo pageInfo = new PageInfo<>(result); + return RestResponse.success(pageInfo); + + } + + // 2024-12-11 取掉事务 插入了下次就不会再次插入了 // @Transactional @Override +// @Async public RestResponse materialAutoMatching(String invoiceId, String directSuppierCode) { try { + log.info("进入 物料匹配 invoiceId:{},supplierCode:{}",invoiceId,directSuppierCode); if (StringUtil.isBlank(invoiceId)) { return RestResponse.failure("非法参数"); } @@ -1101,6 +1695,7 @@ private SysRoleMapper sysRoleMapper; } } else if ("3".equals(matAutoMapConfig.getValue())) { // 拼接数据 + log.info("进入 物料匹配3"); SysConfig additionSpec = sysConfigMapper.selectByCode("addition_spec"); String additionSpecValue = null; if (null == additionSpec) { @@ -1139,9 +1734,11 @@ private SysRoleMapper sysRoleMapper; List corpItems = null; // 获取Item数据 corpItems = corporateInvoiceItemsMapper.selectItemsForMaterial(params); + log.info("进入 物料匹配3 corpItems=》{}",corpItems.size()); // ORDERNo 范围 String orderNos = null; SupplierMatching supplierMatching = supplierMatchingMapper.selectByPrimaryKey(invoiceId); + log.info("进入 物料匹配3 supplierMatching=》{}",JSONObject.toJSONString(supplierMatching)); if (null == supplierMatching) { } else { @@ -1152,7 +1749,7 @@ private SysRoleMapper sysRoleMapper; } // 获取Order数据 List orderMater = supplierOrderMapper.selectOrderForMaterial2(params); - + log.info("进入 物料匹配3 orderMater=》{}",orderMater.size()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); RestTemplate client = restTemplateConfig.restTemplate(); @@ -2303,7 +2900,7 @@ private SysRoleMapper sysRoleMapper; uomUnitParams.put("form_template_id", 5); uomUnitParams.put("smart_processes_id", 18); uomUnitParams.put("fields", fields); -// sendDataToXTPT(method, uomUnitParams); + sendDataToXTPT(method, uomUnitParams); } } else { log.warn("invoice warn ===============》未配置单位不匹配发送的地址"); @@ -2542,9 +3139,6 @@ private SysRoleMapper sysRoleMapper; // 判断itemNo是否已出现过 String tmpKey = supplierInvoiceMatchOrderVo.getItemNo(); int temId = supplierInvoiceMatchOrderVo.getId(); - if (tmpKey.equals("D07-1SN_8_450_BL10-BL10")) { - log.info("======================="); - } if (matchList.get(tmpKey) != null) { List tmp = matchList.get(tmpKey); boolean existFlag1 = true; @@ -2603,6 +3197,9 @@ private SysRoleMapper sysRoleMapper; } int temp = 0; for (CorporateInvoiceItems item : items2) { + if (item.getName().equals("*金属制品*直角接头")) { + log.info("123"); + } temp++; // 发票信息 BigDecimal itemTotal = new BigDecimal(item.getTotal()); @@ -2846,193 +3443,743 @@ private SysRoleMapper sysRoleMapper; return RestResponse.success(); } - public void updateDifference(CorporateInvoice corporateInvoice, CorporateInvoiceItems item) { - log.info("supplierOrderItemMatching item.getId()=>{}", item.getId()); - List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); - SysConfig config = sysConfigMapper.selectByCode("VIRTUAL_CODE"); - BigDecimal orderTotal = BigDecimal.ZERO; - // ReceivedTotal合计 - for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { - orderTotal = orderTotal.add(supplierOrderItemMatching.getTotal()).add(supplierOrderItemMatching.getTax()); - /* // 折前+数量 - if (corporateInvoice.getPriceType().equals(1) && corporateInvoice.getMatchType().equals(1)&& null != supplierOrderItemMatching.getDeductionAmount()) { - orderTotal = orderTotal.add(supplierOrderItemMatching.getDeductionAmount()); - } - // 折前+金额 - if (corporateInvoice.getPriceType().equals(1) && corporateInvoice.getMatchType().equals(0)&& null != supplierOrderItemMatching.getDeductionAmount()) { - orderTotal = orderTotal.add(supplierOrderItemMatching.getDeductionAmount()); - } - // 折前虚拟物料需要加deduction - if (corporateInvoice.getPriceType().equals(1)){ - if(item.getDeductionAmount()!=null && supplierOrderItemMatching.getItemNo().equals(config.getValue())) { - orderTotal = orderTotal.subtract(new BigDecimal(item.getDeductionAmount())); - } - }*/ - } - // 发票金额 - BigDecimal invoiceMoney = new BigDecimal(item.getTotal()); - if (StringUtil.isNotEmpty(item.getDeductionAmount())) { - invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionAmount())); + @Override + public RestResponse supplierInvoiceMatchInfoList(String invoiceId) { + if (invoiceId == null) { + return RestResponse.failure("非法参数"); } - if (StringUtil.isNotEmpty(item.getTax())) { - invoiceMoney = invoiceMoney.add(new BigDecimal(item.getTax())); + SupplierMatching dataResult = supplierMatchingMapper.selectByPrimaryKey(invoiceId); + return RestResponse.success(dataResult); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInvoiceMatchInfoUpdate(SupplierMatching form) { + if (form == null) { + return RestResponse.failure("非法参数"); } - if (StringUtil.isNotEmpty(item.getDeductionTax())) { - invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionTax())); + try { + form.setOperationTime(new Date()); + int count = supplierMatchingMapper.countByPrimaryKey(form.getInvoiceId()); + if (count > 0) { + if (StringUtil.isBlank(form.getOrderNo())) { + supplierMatchingMapper.deleteByPrimaryKey(form.getInvoiceId()); + } else { + supplierMatchingMapper.updateByPrimaryKeySelective(form); + } + } else { + supplierMatchingMapper.insertSelective(form); + } + + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(form.getInvoiceId()); + + //插入日志记录 2022/5/28 + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(form.getInvoiceId()); + setModule("InvoiceMatch"); + setMethods("SupplierMatch"); + setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); + setCreateTime(new Date()); + setReason("完成发票【" + corporateInvoice.getNumber() + "】的PO匹配"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + + return RestResponse.success(); + } catch (Exception e) { + e.printStackTrace(); + throw new ServiceException(); } + } - BigDecimal difference = invoiceMoney.subtract(orderTotal).setScale(2, BigDecimal.ROUND_HALF_UP); - log.info("invoiceMoney=>{} ,difference=>{}", invoiceMoney.toString(), difference.toString()); - BigDecimal absDiff = difference.abs(); - if (absDiff.compareTo(BigDecimal.ZERO) > 0) { - item.setDifference(difference.toString()); - } else { - item.setDifference("0"); + @Override + public RestResponse supplierInvoiceItemsList(String itemId, String id) { + if (id == null) { + if (itemId == null) { + return RestResponse.failure("非法参数"); + } + List dataResult = corporateInvoiceItemsMapper.selectItemsByPid(itemId); + for (CorporateInvoiceItems corporateInvoiceItems : dataResult) { + corporateInvoiceItems.setUsedAmount(supplierOrderItemMatchingMapper.getUsedAmountByItemId(corporateInvoiceItems.getId())); + corporateInvoiceItems.setUsedQuantity(supplierOrderItemMatchingMapper.getUsedQuantityByItemId(corporateInvoiceItems.getId())); + } + return RestResponse.success(dataResult); + } else if (!"".equals(id)) { + if (itemId != null) { + return RestResponse.failure("非法参数itemId"); + } + CorporateInvoiceItems dataResult = corporateInvoiceItemsMapper.selectByPrimaryKey(id); + dataResult.setUsedAmount(supplierOrderItemMatchingMapper.getUsedAmountByItemId(dataResult.getId())); + dataResult.setUsedQuantity(supplierOrderItemMatchingMapper.getUsedQuantityByItemId(dataResult.getId())); + return RestResponse.success(dataResult); } -// item.setPrice(null); - corporateInvoiceItemsMapper.updateByPrimaryKeySelective(item); + return RestResponse.failure(); } + @Override + public RestResponse supplierInvoiceItemsListAll(String pId, Integer pageNo, Integer pageSize) { + if (pId == null) { + return RestResponse.failure("非法参数"); + } + // 税前数据刷新20220927 + Map params = new HashMap<>(); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectById(pId); + int priceType = corporateInvoice.getPriceType(); + List dataResult = corporateInvoiceItemsMapper.selectItemsByPid(pId); +// List dataResult = corporateInvoice.getItems(); + int count = dataResult.size(); + List pageResult = null; + if (null != pageNo && null != pageSize && pageNo >= 1 && pageSize >= 1) { + int startIndex = (pageNo - 1) * pageSize; + int endIndex = startIndex + pageSize; + if (endIndex >= count) { + pageResult = dataResult.subList(startIndex, count); + } else { + pageResult = dataResult.subList(startIndex, endIndex); + } + for (CorporateInvoiceItems corporateInvoiceItems : pageResult) { + corporateInvoiceItems.setPriceType(priceType); + SupplierOrderItemUsedVo vo = supplierOrderItemMatchingMapper.getUsedItemId(corporateInvoiceItems.getId()); + corporateInvoiceItems.setUsedAmount(vo.getUsedAmount()); + corporateInvoiceItems.setUsedQuantity(new BigDecimal(vo.getUsedQuantity())); + corporateInvoiceItems.setItemMatchingList(supplierOrderItemMatchingMapper.selectListByItemId(corporateInvoiceItems.getId())); + } + CorporateInvoiceMatchingItemVo itemVo = new CorporateInvoiceMatchingItemVo(); + itemVo.setTotal(count); + itemVo.setDataResult(pageResult); + itemVo.setCurrentPage(pageNo); + itemVo.setPageSize(pageSize); + return RestResponse.success(itemVo); + } else { + for (CorporateInvoiceItems corporateInvoiceItems : dataResult) { + corporateInvoiceItems.setPriceType(priceType); + SupplierOrderItemUsedVo vo = supplierOrderItemMatchingMapper.getUsedItemId(corporateInvoiceItems.getId()); + corporateInvoiceItems.setUsedAmount(vo.getUsedAmount()); + corporateInvoiceItems.setUsedQuantity(new BigDecimal(vo.getUsedQuantity())); + corporateInvoiceItems.setItemMatchingList(supplierOrderItemMatchingMapper.selectListByItemId(corporateInvoiceItems.getId())); + } + return RestResponse.success(dataResult); + } - /** - * 服务类型发票处理20220928 - * - * @param ids - * @param invoiceId - * @return - */ - public Response completeInvoiceType1(List ids, String invoiceId) { + } + @Override + public RestResponse supplierInvoiceItemsListAllExport(HttpServletResponse response, String invoiceId) { + ServletOutputStream out = null; try { - Assert.notEmpty(ids, "ID不为空"); - Assert.notNull(invoiceId, "发票ID不为空"); - CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); - Assert.notNull(corporateInvoice, "发票不存在"); - List corporateInvoiceItems = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + if (invoiceId == null) { + return RestResponse.failure("非法参数"); + } + // 税前数据刷新20220927 + Map params = new HashMap<>(); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectById(invoiceId); + int priceType = corporateInvoice.getPriceType(); + List dataResult = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + for (CorporateInvoiceItems corporateInvoiceItems : dataResult) { + corporateInvoiceItems.setPriceType(priceType); + SupplierOrderItemUsedVo vo = supplierOrderItemMatchingMapper.getUsedItemId(corporateInvoiceItems.getId()); + corporateInvoiceItems.setUsedAmount(vo.getUsedAmount()); + corporateInvoiceItems.setUsedQuantity(new BigDecimal(vo.getUsedQuantity())); + corporateInvoiceItems.setItemMatchingList(supplierOrderItemMatchingMapper.selectListByItemId(corporateInvoiceItems.getId())); + } + + // 重新构造一个 + List resultList = new ArrayList<>(); + for (int i = 0; i < dataResult.size(); i++) { + CorporateInvoiceItems corporateInvoiceItem = dataResult.get(i); + CorporateInvoiceItemsVo target = new CorporateInvoiceItemsVo(); + BeanUtils.copyProperties(corporateInvoiceItem, target); + //先放入初始元素 + target.setIndexNo(String.valueOf(i + 1)); + target.setUnUsedAmountStr(null == target.getUnUsedAmount() ? "0" : target.getUnUsedAmount().toString()); + resultList.add(target); + // 然如分隔的title + CorporateInvoiceItemsVo lineSplit = new CorporateInvoiceItemsVo(); + lineSplit.setIndexNo("PO"); + lineSplit.setName("产品名称"); + lineSplit.setSpecification("物料号"); + lineSplit.setUnit("单位"); + lineSplit.setQuantity("数量"); + lineSplit.setPrice("单价"); + lineSplit.setTotal("收货金额"); + lineSplit.setUnUsedAmountStr("匹配金额"); + lineSplit.setTaxRate("税率"); + lineSplit.setTax("税额"); + lineSplit.setDeductionAmount("折扣金额"); + lineSplit.setDeductionTax("折扣税额"); + lineSplit.setDifference("状态"); + resultList.add(lineSplit); + + // 将已匹配的数据也写入 + List childList = corporateInvoiceItem.getItemMatchingList(); + for (SupplierOrderItemMatching matching : childList) { + CorporateInvoiceItemsVo childLine = new CorporateInvoiceItemsVo(); + childLine.setIndexNo(matching.getOrderNo()); + childLine.setName(matching.getName()); + childLine.setSpecification(matching.getItemNo()); + childLine.setUnit(matching.getUnit()); + childLine.setQuantity(matching.getQuantity()); + childLine.setPrice(matching.getPrice() == null ? "0" : matching.getPrice().toString()); + childLine.setTotal(matching.getReceivedTotal() == null ? "0" : matching.getReceivedTotal().toString()); + childLine.setUnUsedAmountStr(matching.getTotal() == null ? "0" : matching.getTotal().toString()); + childLine.setTaxRate(matching.getTaxRate()); + childLine.setTax(matching.getTax() == null ? "0" : matching.getTax().toString()); + childLine.setDeductionAmount(matching.getDeductionAmount() == null ? "0" : matching.getDeductionAmount().toString()); + childLine.setDeductionTax(matching.getDeductionTax() == null ? "0" : matching.getDeductionTax().toString()); + childLine.setDifference(matching.getMatchingStatusName()); + resultList.add(childLine); + } - Boolean b = supplierDiffAllowMapper.selectDiffAllowByOrgAndCorType(corporateInvoice.getOrgId(), corporateInvoice.getInvoiceType()); - // 20220521根据配置判断 - SysConfig config = sysConfigMapper.selectByCode("ALLOW_SERV_PARTIAL"); - if (config == null) { - throw new ServiceException("否是允许差额匹配配置缺失,请联系管理员!"); } - BigDecimal sumItem = new BigDecimal("0"); - List lsItem = new ArrayList<>(); - List supplierOrderItemMatchingsAll = new ArrayList<>(); - for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { - // 计算变量获取 - BigDecimal sumItemMatching = new BigDecimal("0"); - BigDecimal sumItemMatchingTax = new BigDecimal("0"); - BigDecimal matchingCount = supplierOrderItemMatchingMapper.sumMatchingCountByItemId(corporateInvoiceItem.getId()); - BigDecimal total = new BigDecimal(corporateInvoiceItem.getTotal() == null ? "0" : corporateInvoiceItem.getTotal()); - BigDecimal deductionAmount = new BigDecimal(corporateInvoiceItem.getDeductionAmount() == null ? "0" : corporateInvoiceItem.getDeductionAmount()); - BigDecimal totalTax = new BigDecimal(corporateInvoiceItem.getTax() == null ? "0" : corporateInvoiceItem.getTax()); - BigDecimal deductionTax = new BigDecimal(corporateInvoiceItem.getDeductionTax() == null ? "0" : corporateInvoiceItem.getDeductionTax()); - BigDecimal sumItemMoney = total.add(deductionAmount); - BigDecimal sumItemTaxMoney = totalTax.add(deductionTax); - // 金额、税额检查 + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=invoice-matching.xlsx"); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "发票匹配明细") + .head(CorporateInvoiceItemsVo.class) + .doWrite(resultList); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } - BigDecimal checkSumTotal = new BigDecimal("0"); - BigDecimal checkSumTotalTax = new BigDecimal("0"); - if (matchingCount.equals(BigDecimal.ZERO)) { - // 20220517数量为0不可通过 - //continue; - if (config.getValue().equals("0") && total.add(deductionAmount).compareTo(BigDecimal.ZERO) != 0) { - throw new ServiceException("金额匹配有差异,请检查匹配数据再提交! "); + @Override + public RestResponse supplierInvoiceAttachmentList(String itemId) { + if (itemId == null) { + return RestResponse.failure("非法参数"); + } + List files = fileMapper.selectByPid(itemId); + return RestResponse.success(files); + } + + @Override + @Transactional + public RestResponse importFile(MultipartFile file) { + String fileName = file.getOriginalFilename(); + if (!fileName.toLowerCase().endsWith("csv")) { + return RestResponse.failure("文件类型不是csv,请确认!"); + } + + List suppliers = supplierMapper.list(new SupplierSearchForm()); + Map> suppliersMap = suppliers.stream().collect(Collectors.groupingBy(Supplier::getCode)); + String lineTxt; + int line = 1; + String[] str = {}; + try { + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream())); + while ((lineTxt = bufferedReader.readLine()) != null) { + log.info("lineTxt==========>{}", lineTxt); + if (line >= 4) { + if (lineTxt == null || lineTxt.length() == 0) continue; + str = lineTxt.split("\t"); + String code = str[2]; + String name = str[4]; + String country = str[10]; + String VATRegNo = str[17]; + if (null == suppliersMap.get(code)) { + // 没有则 新增 + Supplier supplier = new Supplier(); + supplier.setCode(code); + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.insertSelective(supplier); + } else { + // 存在则判断是否更新 + Supplier supplier = suppliersMap.get(code).get(0); + if (name.equals(supplier.getName()) + && country.equals(supplier.getExt01()) + && VATRegNo.equals(supplier.getTaxNo())) { + continue; + } else { + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.updateByPrimaryKey(supplier); + } } } - boolean hasDiff = false; - /*if (matchingCount.equals(BigDecimal.ZERO)) { - hasDiff = false; - }else{ - hasDiff = new BigDecimal(corporateInvoiceItem.getDifference()).divide(matchingCount, 4, BigDecimal.ROUND_HALF_UP).abs().compareTo(new BigDecimal("0.01")) > 0; + line++; + } + return RestResponse.success(); + } catch (IOException e) { + log.error("导入 解析 供应商csv 文件异常==={}", e.getMessage()); + return RestResponse.failure("导入文件异常"); + } + } - } - if (hasDiff) { - if(config.getValue().equals("0") && total.add(deductionAmount).compareTo(BigDecimal.ZERO)!=0) { - throw new ServiceException("金额匹配有差异,请检查匹配数据再提交! "); - } - }*/ - List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(corporateInvoiceItem.getId()); - if (!supplierOrderItemMatchings.isEmpty()) { + @Transactional + @Override + public Response uploadInvoiceAttachment(SupplierInvoiceAttachmentForm form) { + try { + int userId = (int) RequestSecurityPolicy.getUserId(); + Date uploadTime = new Date(); + MultipartFile[] files = form.getFiles(); + for (MultipartFile file : files) { + String originalFilename = file.getOriginalFilename(); + String suffix = FileUtil.getSuffix(originalFilename); + String folder = Pdf2JpgHelper.generateFolder(uploadPath); + String newFileName = StringUtil.UUID() + "." + suffix; + String newViewPath = StringUtils.formatUrl(viewPath + folder + newFileName, "/"); + String newPath = uploadPath + folder + newFileName; + file.transferTo(new java.io.File(newPath)); + File file1 = new File(); + file1.setPid(form.getInvoiceId()); + file1.setType(form.getType()); + file1.setPath(newPath); + file1.setUri(newViewPath); + file1.setDescription(form.getDescription()); + file1.setUploadUser(userId); + file1.setUploadTime(uploadTime); + fileMapper.insert(file1); + + //插入日志记录 2022/5/28 + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(form.getInvoiceId()); + setModule("InvoiceMatch"); + setMethods("UploadFile"); + setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); + setCreateTime(new Date()); + setReason("上传了发票附件【" + newFileName + "】"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + } + return Response.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("附件上传失败"); + } + } - for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { - // 金额、税额处理 - checkSumTotal = checkSumTotal.add(supplierOrderItemMatching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); - checkSumTotalTax = checkSumTotalTax.add(supplierOrderItemMatching.getTax().setScale(2, BigDecimal.ROUND_HALF_UP)); + @Override + public RestResponse supplierInvoiceAttachmentDelete(Integer id) { + if (id == null || id == 0) { + return RestResponse.failure("非法参数"); + } + try { + fileMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("删除失败"); + } + } + + @Override + public RestResponse supplierInvoiceMatchLogList(String itemId) { + if (itemId == null) { + return RestResponse.failure("非法参数"); + } + List supplierMatchingLogs = supplierMatchingLogMapper.selectByPid(itemId); + return RestResponse.success(supplierMatchingLogs); + } + + @Override + public RestResponse getMatchedList(String invoiceId) { + SupplierMatching supplierMatching = supplierMatchingMapper.selectByPrimaryKey(invoiceId); +// Assert.notNull(supplierMatching,"找不到"); + if (supplierMatching != null) { + List orderNos = Arrays.stream(supplierMatching.getOrderNo().split(",")).collect(Collectors.toList()); + List list = supplierOrderMapper.selectByMatchedInfo(supplierMatching.getSupplierCode(), orderNos); + for (SupplierInvoiceMatchOrderVo supplierInvoiceMatchOrderVo : list) { + supplierInvoiceMatchOrderVo.setUsedAmount(supplierOrderItemMatchingMapper.getUsedAmountByOrderNo(supplierInvoiceMatchOrderVo.getOrderNo())); + } + return RestResponse.success(list); + } + return RestResponse.success(new ArrayList<>()); + } + + @Override + public Response> lineMatchList(LineMatchListDto dto) { + SupplierMatching supplierMatching = supplierMatchingMapper.selectByPrimaryKey(dto.getInvoiceId()); + Assert.notNull(supplierMatching, "请先选择单据"); + String orderNo = supplierMatching.getOrderNo(); + if (StringUtil.isNotBlank(orderNo)) { + dto.getOrders().addAll(Arrays.stream(orderNo.split(",")).collect(Collectors.toList())); + } else { + throw new ServiceException("请先选择单据"); + } + //dto.setSupplierCode(supplierMatching.getSupplierCode()); + dto.setQtyAmount("11"); + List supplierOrders = supplierOrderMapper.lineMatchList(dto); +// log.info("lineMatchList =>{}",JSONObject.toJSONString(supplierOrders)); +// supplierOrders.forEach(supplierOrder -> { +// supplierOrder.setUsedAmount(supplierOrderItemMatchingMapper.getUsedAmountByOrderId(supplierOrder.getId())); +// supplierOrder.setUsedQuantity(supplierOrderItemMatchingMapper.getUsedQuantityByOrderId(supplierOrder.getId())); +// }); + List collect = supplierOrders.stream().filter(supplierOrder -> supplierOrder.getUnUsedAmount().compareTo(BigDecimal.ZERO) > 0 && new BigDecimal(supplierOrder.getUnUsedQuantity()).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList()); + if (dto.getLevel() == 2 || dto.getLevel() == 3) { + CorporateInvoice invoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); + if (0 == invoice.getMatchType()) { + List collect1 = collect.stream().filter(supplierOrder -> dto.getUnUsedAmount().intValue() == supplierOrder.getUnUsedAmount().intValue()).collect(Collectors.toList()); + return Response.success(collect1); + } else { + // List collect1 = collect.stream().filter(supplierOrder -> (dto.getUnUsedQuantity().toString() + dto.getUom()).equals(supplierOrder.getUnUsedQuantity().toString() + supplierOrder.getUom())).collect(Collectors.toList()); + List collect1 = collect.stream().filter(supplierOrder -> new BigDecimal(dto.getUnUsedQuantity()).compareTo(new BigDecimal(supplierOrder.getUnUsedQuantity())) == 0 && dto.getUom().equals(supplierOrder.getUom())).collect(Collectors.toList()); + return Response.success(collect1); + } + } + return Response.success(collect); + } + @Transactional(rollbackFor = Exception.class) + @Override + public Response submitLineMatchList(SubmitLineMatchDto dto) { + try { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); + CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(dto.getItemId()); + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); + Assert.notNull(item, "发票行不存在"); + List orders = dto.getOrders(); + // 20220619匹配只能有一行 + /* if(orders.size()>1 ||supplierOrderItemMatchings.size()>0){ + throw new ServiceException("只允许一个匹配行"); + }*/ + List insertList = new ArrayList<>(); + BigDecimal itemTotal = new BigDecimal(item.getTotal()); + // // 0 税前 1 税后 + Integer priceType = corporateInvoice.getPriceType(); + // 税前走新逻辑20220927 + if (priceType == 1) { + return priceBefore(dto); + } + // 获取所有已匹配的数量 + BigDecimal matchedNum = BigDecimal.ZERO; + // + for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { + BigDecimal num = new BigDecimal(supplierOrderItemMatching.getQuantity()); + matchedNum = matchedNum.add(num); + } + + + // 0 金额 1 数量 + Integer matchType = corporateInvoice.getMatchType(); + for (SubmitLineMatchDto.SupplierOrderDto order : orders) { + //判断 supplier_material 是否存在关系 + if (StringUtil.isNotBlank(order.getItemNo())) { + SupplierMaterial supplierMaterial = new SupplierMaterial() {{ + setSupplierNo(order.getSupplierCode()); + //setMaterialNo(order.getItemNo()); + //setMaterial(order.getGoods()); + setSupplierMaterial(item.getName()); + setSpecification(item.getSpecification()); + }}; + // 20220429修改查询条件 + List lsData = supplierMaterialMapper.getList(supplierMaterial); + supplierMaterial.setMaterialNo(order.getItemNo()); + supplierMaterial.setMaterial(order.getGoods()); + supplierMaterial.setUom(order.getUom()); + if (lsData.size() == 0) { + supplierMaterialMapper.insertSelective(supplierMaterial); + } else { + // 20220517id赋值 + supplierMaterial.setId(lsData.get(0).getId()); + supplierMaterialMapper.updateByPrimaryKeySelective(supplierMaterial); } - // 金额、税额判断 - boolean isTotal = false; - boolean isTotalTax = false; - isTotal = sumItemMoney.subtract(checkSumTotal).abs().compareTo(new BigDecimal("1.5")) > 0;//0.5 - isTotalTax = sumItemTaxMoney.subtract(checkSumTotalTax).abs().compareTo(new BigDecimal("0.4")) > 0;//0.1 - // 20220908服务的不考虑匹配差异 - /*if (config.getValue().equals("0")&&(isTotal || isTotalTax)) { - throw new ServiceException("发票金额和匹配金额不相符,请检查匹配数据再提交! "); - }*/ + } - if (corporateInvoice.getPriceType() == 1) {// 税前 - if (checkSumTotal.compareTo(sumItemMoney.add(sumItemTaxMoney)) > 0) { - throw new ServiceException("匹配金额不能大于发票金额! "); + SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); + matching.setInvoiceId(dto.getInvoiceId()); + matching.setItemId(item.getId()); + matching.setOrderId(order.getId()); + matching.setName(order.getGoods()); + matching.setSpecification(item.getSpecification()); + matching.setUnit(order.getUom()); + matching.setPrice(order.getUnitPrice()); + BigDecimal price = new BigDecimal(item.getPrice()); + if (0 == corporateInvoice.getMatchType()) {//金额 + //BigDecimal percent = order.getUnUsedAmount().divide(itemTotal, 10, BigDecimal.ROUND_HALF_UP); + matching.setTotal(order.getUnUsedAmount() == null ? BigDecimal.ZERO : order.getUnUsedAmount()); + /*if (StringUtil.isNotBlank(item.getDeductionAmount())) { + matching.setDeductionAmount(new BigDecimal(item.getDeductionAmount()).multiply(percent)); + if (StringUtil.isNotBlank(item.getDeductionTax())) { + matching.setDeductionTax(new BigDecimal(item.getDeductionTax()).multiply(percent)); } + matching.setDeductionTaxRate(item.getDeductionTaxRate()); + }*/ + // 20220508修改收货数据 + //matching.setQuantity(matching.getTotal().divide(price, 2, BigDecimal.ROUND_HALF_UP).intValue()); + //matching.setQuantity(order.getReceivedNum()); + // 20220510修改收货数据 + matching.setQuantity(matching.getTotal().divide(order.getUnitPrice(), 2, BigDecimal.ROUND_HALF_UP).toString()); + } else {// 数量 + BigDecimal itemQuantity = new BigDecimal(item.getQuantity()); + BigDecimal orderQuantity = new BigDecimal(order.getUnUsedQuantity()); + if (itemQuantity.subtract(matchedNum).compareTo(orderQuantity) >= 0) { + matching.setQuantity(String.valueOf(order.getUnUsedQuantity())); + } else { + matching.setQuantity(String.valueOf(itemQuantity.subtract(matchedNum))); + } + matchedNum = matchedNum.add(new BigDecimal(matching.getQuantity())); + matching.setTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); + matching.setDeductionAmount(BigDecimal.ZERO); + matching.setDeductionTax(BigDecimal.ZERO); + matching.setDeductionTaxRate(item.getDeductionTaxRate()); - } else {// 税后 - if (checkSumTotal.compareTo(sumItemMoney) > 0) { - throw new ServiceException("匹配金额不能大于发票金额! "); + /*if (StringUtil.isNotBlank(item.getDeductionAmount())) { + BigDecimal percent = matching.getTotal().divide(itemTotal, 10, BigDecimal.ROUND_HALF_UP); + matching.setDeductionAmount(new BigDecimal(item.getDeductionAmount()).multiply(percent)); + if (StringUtil.isNotBlank(item.getDeductionTax())) { + matching.setDeductionTax(new BigDecimal(item.getDeductionTax()).multiply(percent)); } + matching.setDeductionTaxRate(item.getDeductionTaxRate()); + }*/ + } + if (StringUtil.isNotBlank(item.getTax())) { + BigDecimal tot = itemTotal.add(new BigDecimal(item.getDeductionAmount() == null ? "0" : item.getDeductionAmount())); + if (tot.compareTo(BigDecimal.ZERO) != 0) { + BigDecimal percent = matching.getTotal().divide(tot, 10, BigDecimal.ROUND_HALF_UP); + matching.setTax(new BigDecimal(item.getTax()).add(new BigDecimal(item.getDeductionTax() == null ? "0" : item.getDeductionTax())).multiply(percent).setScale(2, BigDecimal.ROUND_HALF_UP)); + } else { + matching.setTax(BigDecimal.ZERO); } - if (config.getValue().equals("1")) {// 允许多次匹配 + } + // 20220509折后判断 + /*if(priceType==0 && matchType==1){ + matching.setTotal(matching.getTotal().add(matching.getDeductionAmount()== null ? BigDecimal.ZERO : matching.getDeductionAmount())); + matching.setTax(matching.getTax().add(matching.getDeductionTax()== null ? BigDecimal.ZERO : matching.getDeductionTax())); + }*/ + matching.setReceivedTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); + matching.setTaxRate(item.getTaxRate()); + matching.setMatchingStatus(0); + matching.setReceiveNo(order.getReceiveNo()); + matching.setOrderNo(order.getOrderNo()); + matching.setItemNo(order.getItemNo()); + // 20220712匹配total保留两位小数 + matching.setTotal(matching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); + matching.setMatchingId(""); + insertList.add(matching); + } + if (!insertList.isEmpty()) { + supplierOrderItemMatchingMapper.insertBatch(insertList); + } + updateDifference(corporateInvoice, item); - } else {// 不允许多次 + //插入日志记录 2022/5/28 + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(corporateInvoice.getId()); + setModule("InvoiceMatch"); + setMethods("SupplierOrderItemMatch"); + setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); + setCreateTime(new Date()); + setReason("完成发票行【" + item.getName() + "+" + item.getSpecification() + "】的发票匹配"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + return Response.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("提交异常"); + } + } + + /** + * 税前逻辑处理 20220927 + * + * @param dto + */ + private Response priceBefore(SubmitLineMatchDto dto) { + try { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); + CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(dto.getItemId()); + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); + Assert.notNull(item, "发票行不存在"); + List orders = dto.getOrders(); + // 20220619匹配只能有一行 + /* if(orders.size()>1 ||supplierOrderItemMatchings.size()>0){ + throw new ServiceException("只允许一个匹配行"); + }*/ + List insertList = new ArrayList<>(); + BigDecimal itemTotal = new BigDecimal(item.getTotal()); + // 0 税前 1 税后 + Integer priceType = corporateInvoice.getPriceType(); + // 0 金额 1 数量 + Integer matchType = corporateInvoice.getMatchType(); + for (SubmitLineMatchDto.SupplierOrderDto order : orders) { + //判断 supplier_material 是否存在关系 + if (StringUtil.isNotBlank(order.getItemNo())) { + SupplierMaterial supplierMaterial = new SupplierMaterial() {{ + setSupplierNo(order.getSupplierCode()); + //setMaterialNo(order.getItemNo()); + //setMaterial(order.getGoods()); + setSupplierMaterial(item.getName()); + setSpecification(item.getSpecification()); + }}; + // 20220429修改查询条件 + List lsData = supplierMaterialMapper.getList(supplierMaterial); + supplierMaterial.setMaterialNo(order.getItemNo()); + supplierMaterial.setMaterial(order.getGoods()); + supplierMaterial.setUom(order.getUom()); + if (lsData.size() == 0) { + supplierMaterialMapper.insertSelective(supplierMaterial); + } else { + // 20220517id赋值 + supplierMaterial.setId(lsData.get(0).getId()); + supplierMaterialMapper.updateByPrimaryKeySelective(supplierMaterial); } + } + SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); + matching.setInvoiceId(dto.getInvoiceId()); + matching.setItemId(item.getId()); + matching.setOrderId(order.getId()); + matching.setName(order.getGoods()); + matching.setSpecification(item.getSpecification()); + matching.setUnit(order.getUom()); + matching.setPrice(order.getUnitPrice()); + BigDecimal price = new BigDecimal(item.getPrice()); + if (0 == corporateInvoice.getMatchType()) {//金额 + matching.setTotal(order.getUnUsedAmount() == null ? BigDecimal.ZERO : order.getUnUsedAmount()); + // 20220510修改收货数据 + matching.setQuantity(matching.getTotal().divide(order.getUnitPrice(), 2, BigDecimal.ROUND_HALF_UP).toString()); + matching.setReceivedTotal(matching.getTotal()); + } else {// 数量 + matching.setQuantity(String.valueOf(order.getUnUsedQuantity())); + matching.setTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); + matching.setDeductionAmount(BigDecimal.ZERO); + matching.setDeductionTax(BigDecimal.ZERO); + matching.setDeductionTaxRate(item.getDeductionTaxRate()); + matching.setReceivedTotal(order.getUnitPrice().multiply(new BigDecimal(matching.getQuantity()))); + + } + // 税额赋值 + matching.setTax(BigDecimal.ZERO); - } + matching.setTaxRate(item.getTaxRate()); + matching.setMatchingStatus(0); + matching.setReceiveNo(order.getReceiveNo()); + matching.setOrderNo(order.getOrderNo()); + matching.setItemNo(order.getItemNo()); + // 20220712匹配total保留两位小数 + matching.setTotal(matching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); + matching.setMatchingId(""); + insertList.add(matching); } - CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); - if (corporateInvoiceType != null) { - if (1 == corporateInvoiceType.getReview()) { - corporateInvoice.setMatchStatus(1); - } else if (0 == corporateInvoiceType.getReview()) { - corporateInvoice.setMatchStatus(2); - supplierOutService.sendMatchingData(ids, invoiceId); - } - corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ - setId(invoiceId); - setMatchStatus(corporateInvoice.getMatchStatus()); - }}); + if (!insertList.isEmpty()) { + supplierOrderItemMatchingMapper.insertBatch(insertList); } - + updateDifference(corporateInvoice, item); //插入日志记录 2022/5/28 - String name = "自动匹配"; - long userId = RequestSecurityPolicy.getUserId(); - if(0l!=userId){ - name =sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName(); - } SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ setId(IdUtil.fastUUID()); setPid(corporateInvoice.getId()); setModule("InvoiceMatch"); - setMethods("MatchSubmit"); + setMethods("SupplierOrderItemMatch"); + setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); setCreateTime(new Date()); - setReason("完成发票【" + corporateInvoice.getNumber() + "】的所有发票行的匹配"); + setReason("完成发票行【" + item.getName() + "+" + item.getSpecification() + "】的发票匹配"); }}; - supplierMatchingLog.setOperatorUser(name); supplierMatchingLogMapper.insert(supplierMatchingLog); return Response.success(); - } catch (ServiceException e1) { - throw e1; } catch (Exception e) { log.error(e.getMessage(), e); - throw new ServiceException("操作失败"); + throw new ServiceException("提交异常"); + } + } + + public void updateDifference(CorporateInvoice corporateInvoice, CorporateInvoiceItems item) { + log.info("supplierOrderItemMatching item.getId()=>{}", item.getId()); + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); + SysConfig config = sysConfigMapper.selectByCode("VIRTUAL_CODE"); + BigDecimal orderTotal = BigDecimal.ZERO; + // ReceivedTotal合计 + for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { + orderTotal = orderTotal.add(supplierOrderItemMatching.getTotal()).add(supplierOrderItemMatching.getTax()); + /* // 折前+数量 + if (corporateInvoice.getPriceType().equals(1) && corporateInvoice.getMatchType().equals(1)&& null != supplierOrderItemMatching.getDeductionAmount()) { + orderTotal = orderTotal.add(supplierOrderItemMatching.getDeductionAmount()); + } + // 折前+金额 + if (corporateInvoice.getPriceType().equals(1) && corporateInvoice.getMatchType().equals(0)&& null != supplierOrderItemMatching.getDeductionAmount()) { + orderTotal = orderTotal.add(supplierOrderItemMatching.getDeductionAmount()); + } + // 折前虚拟物料需要加deduction + if (corporateInvoice.getPriceType().equals(1)){ + if(item.getDeductionAmount()!=null && supplierOrderItemMatching.getItemNo().equals(config.getValue())) { + orderTotal = orderTotal.subtract(new BigDecimal(item.getDeductionAmount())); + } + }*/ + } + // 发票金额 + BigDecimal invoiceMoney = new BigDecimal(item.getTotal()); + if (StringUtil.isNotEmpty(item.getDeductionAmount())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionAmount())); + } + if (StringUtil.isNotEmpty(item.getTax())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getTax())); + } + if (StringUtil.isNotEmpty(item.getDeductionTax())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionTax())); + } + + BigDecimal difference = invoiceMoney.subtract(orderTotal).setScale(2, BigDecimal.ROUND_HALF_UP); + log.info("invoiceMoney=>{} ,difference=>{}", invoiceMoney.toString(), difference.toString()); + BigDecimal absDiff = difference.abs(); + if (absDiff.compareTo(BigDecimal.ZERO) > 0) { + item.setDifference(difference.toString()); + } else { + item.setDifference("0"); + } +// item.setPrice(null); + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(item); + } + + /** + * 删除多行处理 + * + * @param corporateInvoice + * @param item + */ + private void updateDifferenceMulti(CorporateInvoice corporateInvoice, CorporateInvoiceItems item, Long id) { + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); + + BigDecimal orderTotal = BigDecimal.ZERO; + // ReceivedTotal合计 + for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { + if (supplierOrderItemMatching.getId().toString().equals(id.toString())) continue; + + orderTotal = orderTotal.add(supplierOrderItemMatching.getTotal()).add(supplierOrderItemMatching.getTax()); + } + // 发票金额 + BigDecimal invoiceMoney = new BigDecimal(item.getTotal()); + if (StringUtil.isNotEmpty(item.getDeductionAmount())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionAmount())); + } + if (StringUtil.isNotEmpty(item.getTax())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getTax())); + } + if (StringUtil.isNotEmpty(item.getDeductionTax())) { + invoiceMoney = invoiceMoney.add(new BigDecimal(item.getDeductionTax())); + } + + BigDecimal difference = invoiceMoney.subtract(orderTotal).setScale(2, BigDecimal.ROUND_HALF_UP); + + BigDecimal absDiff = difference.abs(); + if (absDiff.compareTo(BigDecimal.ZERO) > 0) { + item.setDifference(difference.toString()); + } else { + item.setDifference("0"); } + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(item); + } + + @Override + public Response> lineMatchListByItem(String itemId) { + return Response.success(supplierOrderItemMatchingMapper.selectListByItemId(itemId)); } @Transactional @@ -3114,7 +4261,7 @@ private SysRoleMapper sysRoleMapper; file.setPid(invoiceId); file.setDescription(""); file.setUploadTime(supplierPODto.getCreateDate()); -// fileMapper.insert(file); + fileMapper.insert(file); } } } @@ -3425,7 +4572,152 @@ private SysRoleMapper sysRoleMapper; } } } - int i = supplierOrderItemMatchingMapper.completeMatching(ids); + int i = supplierOrderItemMatchingMapper.completeMatching(ids); + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType != null) { + if (1 == corporateInvoiceType.getReview()) { + corporateInvoice.setMatchStatus(1); + } else if (0 == corporateInvoiceType.getReview()) { + corporateInvoice.setMatchStatus(2); + supplierOutService.sendMatchingData(ids, invoiceId); + } + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(invoiceId); + setMatchStatus(corporateInvoice.getMatchStatus()); + }}); + } + + //插入日志记录 2022/5/28 + try { + long userId = RequestSecurityPolicy.getUserId(); + String name = "任务"; + if (userId != 0l) { + name = sysUserMapper.selectByPrimaryKey((int) userId).getName(); + } + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(corporateInvoice.getId()); + setModule("InvoiceMatch"); + setMethods("MatchSubmit"); + setCreateTime(new Date()); + setReason("完成发票【" + corporateInvoice.getNumber() + "】的所有发票行的匹配"); + }}; + supplierMatchingLog.setOperatorUser(name); + supplierMatchingLogMapper.insert(supplierMatchingLog); + } catch (Exception e) { + e.printStackTrace(); + } + + + return Response.success(); + } catch (ServiceException e1) { + throw e1; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + /** + * 服务类型发票处理20220928 + * + * @param ids + * @param invoiceId + * @return + */ + public Response completeInvoiceType1(List ids, String invoiceId) { + + try { + Assert.notEmpty(ids, "ID不为空"); + Assert.notNull(invoiceId, "发票ID不为空"); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + Assert.notNull(corporateInvoice, "发票不存在"); + List corporateInvoiceItems = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + + Boolean b = supplierDiffAllowMapper.selectDiffAllowByOrgAndCorType(corporateInvoice.getOrgId(), corporateInvoice.getInvoiceType()); + // 20220521根据配置判断 + SysConfig config = sysConfigMapper.selectByCode("ALLOW_SERV_PARTIAL"); + if (config == null) { + throw new ServiceException("否是允许差额匹配配置缺失,请联系管理员!"); + } + BigDecimal sumItem = new BigDecimal("0"); + List lsItem = new ArrayList<>(); + List supplierOrderItemMatchingsAll = new ArrayList<>(); + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + // 计算变量获取 + BigDecimal sumItemMatching = new BigDecimal("0"); + BigDecimal sumItemMatchingTax = new BigDecimal("0"); + BigDecimal matchingCount = supplierOrderItemMatchingMapper.sumMatchingCountByItemId(corporateInvoiceItem.getId()); + BigDecimal total = new BigDecimal(corporateInvoiceItem.getTotal() == null ? "0" : corporateInvoiceItem.getTotal()); + BigDecimal deductionAmount = new BigDecimal(corporateInvoiceItem.getDeductionAmount() == null ? "0" : corporateInvoiceItem.getDeductionAmount()); + BigDecimal totalTax = new BigDecimal(corporateInvoiceItem.getTax() == null ? "0" : corporateInvoiceItem.getTax()); + BigDecimal deductionTax = new BigDecimal(corporateInvoiceItem.getDeductionTax() == null ? "0" : corporateInvoiceItem.getDeductionTax()); + BigDecimal sumItemMoney = total.add(deductionAmount); + BigDecimal sumItemTaxMoney = totalTax.add(deductionTax); + // 金额、税额检查 + + BigDecimal checkSumTotal = new BigDecimal("0"); + BigDecimal checkSumTotalTax = new BigDecimal("0"); + if (matchingCount.equals(BigDecimal.ZERO)) { + // 20220517数量为0不可通过 + //continue; + if (config.getValue().equals("0") && total.add(deductionAmount).compareTo(BigDecimal.ZERO) != 0) { + throw new ServiceException("金额匹配有差异,请检查匹配数据再提交! "); + } + } + boolean hasDiff = false; + /*if (matchingCount.equals(BigDecimal.ZERO)) { + hasDiff = false; + }else{ + hasDiff = new BigDecimal(corporateInvoiceItem.getDifference()).divide(matchingCount, 4, BigDecimal.ROUND_HALF_UP).abs().compareTo(new BigDecimal("0.01")) > 0; + + } + if (hasDiff) { + if(config.getValue().equals("0") && total.add(deductionAmount).compareTo(BigDecimal.ZERO)!=0) { + throw new ServiceException("金额匹配有差异,请检查匹配数据再提交! "); + } + }*/ + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(corporateInvoiceItem.getId()); + if (!supplierOrderItemMatchings.isEmpty()) { + + + for (SupplierOrderItemMatching supplierOrderItemMatching : supplierOrderItemMatchings) { + // 金额、税额处理 + checkSumTotal = checkSumTotal.add(supplierOrderItemMatching.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP)); + checkSumTotalTax = checkSumTotalTax.add(supplierOrderItemMatching.getTax().setScale(2, BigDecimal.ROUND_HALF_UP)); + + } + // 金额、税额判断 + boolean isTotal = false; + boolean isTotalTax = false; + isTotal = sumItemMoney.subtract(checkSumTotal).abs().compareTo(new BigDecimal("1.5")) > 0;//0.5 + isTotalTax = sumItemTaxMoney.subtract(checkSumTotalTax).abs().compareTo(new BigDecimal("0.4")) > 0;//0.1 + // 20220908服务的不考虑匹配差异 + /*if (config.getValue().equals("0")&&(isTotal || isTotalTax)) { + throw new ServiceException("发票金额和匹配金额不相符,请检查匹配数据再提交! "); + }*/ + + if (corporateInvoice.getPriceType() == 1) {// 税前 + if (checkSumTotal.compareTo(sumItemMoney.add(sumItemTaxMoney)) > 0) { + throw new ServiceException("匹配金额不能大于发票金额! "); + } + + } else {// 税后 + if (checkSumTotal.compareTo(sumItemMoney) > 0) { + throw new ServiceException("匹配金额不能大于发票金额! "); + } + + } + if (config.getValue().equals("1")) {// 允许多次匹配 + + + } else {// 不允许多次 + + } + + + } + } CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); if (corporateInvoiceType != null) { if (1 == corporateInvoiceType.getReview()) { @@ -3440,37 +4732,249 @@ private SysRoleMapper sysRoleMapper; }}); } + //插入日志记录 2022/5/28 - try { - long userId = RequestSecurityPolicy.getUserId(); - String name = "任务"; - if (userId != 0l) { - name = sysUserMapper.selectByPrimaryKey((int) userId).getName(); - } + String name = "自动匹配"; + long userId = RequestSecurityPolicy.getUserId(); + if(0l!=userId){ + name =sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName(); + } + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(corporateInvoice.getId()); + setModule("InvoiceMatch"); + setMethods("MatchSubmit"); + setCreateTime(new Date()); + setReason("完成发票【" + corporateInvoice.getNumber() + "】的所有发票行的匹配"); + }}; + supplierMatchingLog.setOperatorUser(name); + supplierMatchingLogMapper.insert(supplierMatchingLog); + + return Response.success(); + } catch (ServiceException e1) { + throw e1; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + + @Transactional + @Override + public Response clearMatching(List ids) { + try { + Assert.notEmpty(ids, "ID不为空"); + for (Long id : ids) { + SupplierOrderItemMatching supplierOrderItemMatching = supplierOrderItemMatchingMapper.selectByPrimaryKey(id); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(supplierOrderItemMatching.getInvoiceId()); + CorporateInvoiceItems items = corporateInvoiceItemsMapper.selectByPrimaryKey(supplierOrderItemMatching.getItemId()); + + // 20220619虚拟物料处理 + /* SysConfig config =sysConfigMapper.selectByCode("VIRTUAL_CODE"); + if(config!=null) { + if(supplierOrderItemMatching.getItemNo().equals(config.getValue())){ + List supplierOrderItemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(items.getId()); + for (SupplierOrderItemMatching itemMatching : supplierOrderItemMatchings) { + if(itemMatching.getId().toString().equals(id.toString())) continue; + // 20220619更新匹配记录行价格、单价 + itemMatching.setTotal((new BigDecimal(itemMatching.getQuantity())).multiply(new BigDecimal(items.getPrice())).setScale(5, BigDecimal.ROUND_HALF_UP)); + itemMatching.setTax(itemMatching.getTotal().divide(new BigDecimal(items.getTotal()),10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(items.getTax())).setScale(5, BigDecimal.ROUND_HALF_UP)); + // 折后 + if(corporateInvoice.getPriceType().equals(0)){ + itemMatching.setTotal(itemMatching.getTotal().add(itemMatching.getDeductionAmount()==null?BigDecimal.ZERO:itemMatching.getDeductionAmount())); + itemMatching.setTax(itemMatching.getTotal().divide(new BigDecimal(items.getTotal()),10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(items.getTax()).add(itemMatching.getDeductionTax()==null?BigDecimal.ZERO:itemMatching.getDeductionTax())).setScale(5, BigDecimal.ROUND_HALF_UP)); + } + itemMatching.setPrice((new BigDecimal(items.getPrice())).setScale(5, BigDecimal.ROUND_HALF_UP)); + supplierOrderItemMatchingMapper.updateByPrimaryKeySelective(itemMatching); + } + } + }else{ + throw new ServiceException("未设置虚拟物料"); + }*/ + //updateDifferenceMulti(corporateInvoice, items,id); + int i = supplierOrderItemMatchingMapper.deleteByPrimaryKey(id); + updateDifference(corporateInvoice, items); + } + return Response.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + @Override + public Response> getInvoiceTypes(boolean search) { + if (search) { + List corporateInvoiceTypes = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setActive(true); + }}); + return Response.success(corporateInvoiceTypes); + } + List corporateInvoiceTypeList = corporateInvoiceTypeMapper.selectForUser((int) RequestSecurityPolicy.getUserId()); + return Response.success(corporateInvoiceTypeList); + } + + @Override + public Response> getInvoiceOrgs(boolean search, String name) { + if (search) { + List sysOrgs = sysOrgMapper.selectListByRecord(new SysOrg() {{ + setIsBusiness(true); + setName(name); + }}); + return Response.success(sysOrgs); + } + List sysOrgs = sysOrgMapper.selectForUser((int) RequestSecurityPolicy.getUserId(), name); + return Response.success(sysOrgs); + } + + @Override + public Response> getOwners(String keyword) { + List sysUsers = sysUserMapper.searchForSupplier(keyword); + return Response.success(sysUsers); + } + + @Transactional + @Override + public Response revokeInvoice(String invoiceId) { + try { + Assert.notNull(invoiceId, "ID不为空"); + SysConfig needSendBack = sysConfigMapper.selectByCode("INVOICE_REFUND_ISSEND_BACK"); + String isSend = null; + if (null != needSendBack) { + isSend = needSendBack.getValue(); + } + corporateInvoiceMapper.revokeInvoice(invoiceId, isSend); + supplierOrderItemMatchingMapper.revokeMapping(invoiceId); + + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + + //插入日志记录 2022/6/17 + SysUser sysUser = sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(invoiceId); + setModule("InvoiceMatch"); + setMethods("MatchRetrive"); + setOperatorUser(sysUser.getName()); + setCreateTime(new Date()); + setReason(sysUser.getUserName() + "撤回了发票【" + corporateInvoice.getNumber() + "】"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + + return Response.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + + @Transactional + @Override + public Response passReview(String invoiceId, String exchangeRateDate) { + try { + Assert.notNull(invoiceId, "ID不为空"); + + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(invoiceId); + setMatchStatus(2); + setExt09(exchangeRateDate); + }}); + // RPA调用判断 + SysConfig config = sysConfigMapper.selectByCode("RPA_FLAG"); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + + //插入日志记录 2022/6/17 + SysUser sysUser = null; + sysUser = sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + if (null == sysUser) { SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ setId(IdUtil.fastUUID()); - setPid(corporateInvoice.getId()); + setPid(invoiceId); setModule("InvoiceMatch"); - setMethods("MatchSubmit"); + setMethods("MatchApprove"); + setOperatorUser("自动任务"); setCreateTime(new Date()); - setReason("完成发票【" + corporateInvoice.getNumber() + "】的所有发票行的匹配"); + setReason("自动任务审核通过了发票【" + corporateInvoice.getNumber() + "】"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + } else { + String userName = sysUser.getUserName(); + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(invoiceId); + setModule("InvoiceMatch"); + setMethods("MatchApprove"); + setOperatorUser(userName); + setCreateTime(new Date()); + setReason(userName + "审核通过了发票【" + corporateInvoice.getNumber() + "】"); }}; - supplierMatchingLog.setOperatorUser(name); supplierMatchingLogMapper.insert(supplierMatchingLog); - } catch (Exception e) { - e.printStackTrace(); } + return Response.success(); + } catch (Exception e) { + log.error("passReview => error=>", e); + e.printStackTrace(); + throw new ServiceException("操作失败"); + } + } - + @Transactional + @Override + public Response resendInvoice(String invoiceId) { + try { + Assert.notNull(invoiceId, "ID不为空"); + //todo 发送 + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(invoiceId); + setMatchStatus(3); + }}); + log.info(" resend-invoice 设置重新发送=》{}", invoiceId); return Response.success(); - } catch (ServiceException e1) { - throw e1; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServiceException("操作失败"); } } + @Transactional + @Override + public RestResponse updatePriceType(CorporateInvoice corporateInvoice) { + try { + int i = supplierOrderItemMatchingMapper.checkInvoiceExist(corporateInvoice.getId()); + if (i > 0) { + return RestResponse.failure("存在匹配记录,不可修改"); + } + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(corporateInvoice.getId()); + setPriceType(corporateInvoice.getPriceType()); + }}); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + @Transactional + @Override + public RestResponse updateMatchType(CorporateInvoice corporateInvoice) { + try { + int i = supplierOrderItemMatchingMapper.checkInvoiceExist(corporateInvoice.getId()); + if (i > 0) { + return RestResponse.failure("存在匹配记录,不可修改"); + } + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(corporateInvoice.getId()); + setMatchType(corporateInvoice.getMatchType()); + }}); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } @Transactional @Override @@ -3514,47 +5018,342 @@ private SysRoleMapper sysRoleMapper; updateDifference(corporateInvoice, items); return RestResponse.success(); } - return RestResponse.failure("更新失败"); + return RestResponse.failure("更新失败"); + } catch (Exception e) { + log.error("", e); + throw new ServiceException("更新失败"); + } + } + + @Override + public RestResponse priceLogs(String id) { + return RestResponse.success(supplierMatchingLogMapper.getPriceLogsForMatching(id)); + } + + @Override + public Response lineMatchById(Long id) { + return Response.success(supplierOrderItemMatchingMapper.selectByPrimaryKey(id)); + } + + @Transactional + @Override + public RestResponse updateUom(String invoiceId, String sellerTaxId) { + log.info("updateUom invoiceID=>{} , sellerTaxId=>{}",invoiceId,sellerTaxId); + try { + String supplier = supplierMapper.selectSupplierCode(sellerTaxId); + log.info("updateUom supplier=>{} ",supplier); + List corporateInvoiceItems = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + SysConfig ispf = sysConfigMapper.selectByCode("IS_PF"); + if (StringUtil.isNotEmpty(supplier) || (null != ispf && "1".equals(ispf.getValue()))) { + log.info("updateUom true"); + log.info("updateUom corporateInvoiceItems =>{}",JSONObject.toJSONString(corporateInvoiceItems)); + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + log.info("corporateInvoiceItem.getId()=>{}", corporateInvoiceItem.getId()); + if (StringUtil.isNotBlank(corporateInvoiceItem.getOriginPrice()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginUnit()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginQuantity())) { + log.info("corporateInvoiceItem.getSpecification()=>{}", corporateInvoiceItem.getSpecification()); + log.info("corporateInvoiceItem.getName()=>{}", corporateInvoiceItem.getName()); + SupplierMaterialUom uom = supplierMaterialUomMapper.selectByItem(supplier, corporateInvoiceItem.getSpecification(), corporateInvoiceItem.getName(), + corporateInvoiceItem.getUnit());//getOriginUnit-->unit + log.info("uom====>{}", uom); + if (null != uom) { + corporateInvoiceItem.setUnit(uom.getVersUnit()); + corporateInvoiceItem.setQuantity(String.valueOf(Double.parseDouble(corporateInvoiceItem.getOriginQuantity()) * Double.parseDouble(uom.getVersNum()))); + BigDecimal price = new BigDecimal(corporateInvoiceItem.getPrice()).divide(new BigDecimal(uom.getVersNum()), 10, BigDecimal.ROUND_HALF_UP); + corporateInvoiceItem.setPrice(price.toString()); + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(corporateInvoiceItem); + } + } + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + /** + * 添加地址信息 + * + * @param orderStr + * @return + */ + @Transactional + @Override + public RestResponse addAress(String orderStr) { + try { + JSONArray ls = JSONArray.parseArray(orderStr); + SupplierOrderSearchForm query = new SupplierOrderSearchForm(); + // 处理json + for (int i = 0; i < ls.size(); i++) { + JSONObject obj = JSONObject.parseObject(ls.get(i).toString()); + obj.put("receiveTime", obj.get("receiveTime").toString().replaceAll("\\+", " ")); + SupplierOrder order = JSONObject.parseObject(obj.toString(), SupplierOrder.class); + if (order.getTaxRate() != null && order.getTaxRate().length() > 0) { + String[] tax = order.getTaxRate().split("_"); + order.setTaxRate(tax[tax.length - 1]); + } + // 20220418计算amount,保留六位小数 + BigDecimal goodNum = new BigDecimal(order.getReceivedNum()); + order.setGoodsNum(order.getReceivedNum()); + order.setAmount(goodNum.multiply(order.getUnitPrice()).setScale(6, BigDecimal.ROUND_HALF_UP)); + // 20220422修改 + order.setSource("2"); + order.setStatus(true); + query.setReceiveNo(order.getReceiveNo()); + query.setReceivedNum(order.getReceivedNum()); + query.setItemNo(order.getItemNo()); + query.setPoNumber(order.getOrderNo()); + int count = supplierOrderMapper.countReceived(query); + if (count == 0) { + supplierOrderMapper.insertSelective(order); + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + /** + * 获取Ap发票信息 + * + * @param invoiceId + * @return + */ + public RestResponse getSupplierOrderItem(String invoiceId) { + List ls = supplierOrderItemMatchingMapper.getSupplierOrderItems(invoiceId); + +// for (SupplierOrderItemsVo l : ls) { +// l.setTotal(new BigDecimal(l.getTotal()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); +// l.setTax(new BigDecimal(l.getTax()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); +// l.setDeductionAmount(new BigDecimal(l.getDeductionAmount()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); +// l.setDeductionTax(new BigDecimal(l.getDeductionTax()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); +// } + supplierOrderItemMatchingMapper.updateByFlow("1"); + return RestResponse.success(ls); + } + + /** + * 获取Ap发票信息 + * + * @param status + * @return + */ + public RestResponse getSupplierOrderItemMore(String status) { + List ls = supplierOrderItemMatchingMapper.getSupplierOrderItemsMore(status); + // invoice-group + Map> invoiceMap = ls.stream().collect(Collectors.groupingBy(SupplierOrderItemsVo::getInvoiceId)); + List> invoiceData = new ArrayList<>(); + invoiceMap.forEach((k, v) -> { + SupplierOrderItemsVo invoice01 = v.get(0); + Map invoiceObj = new LinkedHashMap<>(); + invoiceObj.put("invoiceId", invoice01.getInvoiceId()); + invoiceObj.put("pretaxAmount", invoice01.getPretaxAmount()); + BigDecimal invoiceTax = new BigDecimal("0"); + BigDecimal invoiceDeductionAmount = new BigDecimal("0"); + BigDecimal invoiceDeductionTax = new BigDecimal("0"); + List> poLine = new ArrayList<>(); + // po-group + Map> poMap = v.stream().collect(Collectors.groupingBy(SupplierOrderItemsVo::getOrderNo)); + //poMap.forEach((pk, pv) -> { + for (List pv : poMap.values()) { + Map poObj = new LinkedHashMap<>(); + SupplierOrderItemsVo po01 = pv.get(0); + poObj.put("orderNo", po01.getOrderNo()); + BigDecimal poTotal = new BigDecimal("0"); + BigDecimal poTax = new BigDecimal("0"); + BigDecimal poDeductionAmount = new BigDecimal("0"); + BigDecimal poDeductionTax = new BigDecimal("0"); + for (SupplierOrderItemsVo item : pv) { + poTotal = poTotal.add(new BigDecimal(item.getTotal()).setScale(5, BigDecimal.ROUND_HALF_UP)); + poTax = poTax.add(new BigDecimal(item.getTax()).setScale(5, BigDecimal.ROUND_HALF_UP)); + poDeductionAmount = poDeductionAmount.add(new BigDecimal(item.getDeductionAmount()).setScale(5, BigDecimal.ROUND_HALF_UP)); + poDeductionTax = poDeductionTax.add(new BigDecimal(item.getDeductionTax()).setScale(5, BigDecimal.ROUND_HALF_UP)); + + } + invoiceTax = invoiceTax.add(poTax).setScale(5, BigDecimal.ROUND_HALF_UP); + invoiceDeductionAmount = invoiceDeductionAmount.add(poDeductionAmount).setScale(5, BigDecimal.ROUND_HALF_UP); + invoiceDeductionTax = invoiceDeductionTax.add(poDeductionTax).setScale(5, BigDecimal.ROUND_HALF_UP); + + poObj.put("poTotal", poTotal); + poObj.put("poTax", poTax); + poObj.put("poDeductionAmount", poDeductionAmount); + poObj.put("poDeductionTax", poDeductionTax); + poObj.put("itemLine", pv); + poLine.add(poObj); + } + + invoiceObj.put("invoiceTax", invoiceTax); + invoiceObj.put("invoiceDeductionAmount", invoiceDeductionAmount); + invoiceObj.put("invoiceDeductionTax", invoiceDeductionTax); + invoiceObj.put("poLine", poLine); + invoiceData.add(invoiceObj); + }); + supplierOrderItemMatchingMapper.updateByFlow("1"); + return RestResponse.success(invoiceData); + } + + /** + * 更新AP信息 + * + * @param invoiceStr + * @return + */ + @Transactional + @Override + public RestResponse upInvoice(String invoiceStr) { + try { + JSONArray ls = JSONArray.parseArray(invoiceStr); + // 处理json + for (int i = 0; i < ls.size(); i++) { + JSONObject obj = JSONObject.parseObject(ls.get(i).toString()); + + corporateInvoiceMapper.updateByPrimaryKeySelective(new CorporateInvoice() {{ + setId(obj.get("invoiceId").toString()); + setMatchStatus(3); + }}); + } + log.info(" manager/supplierMoreUp 设置重新发送=》{}", invoiceStr); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + @Override + public Response inventedMatching(LineMatchListDto dto) { + if (dto.getInvoiceId() == null || dto.getInvoiceId().length() == 0) { + throw new ServiceException("invoiceId不能为空"); + } + List ls = corporateInvoiceItemsMapper.selectItemsByPid(dto.getInvoiceId()); + for (CorporateInvoiceItems item : ls) { + LineMatchListDto dot = new LineMatchListDto(); + dot.setInvoiceId(dto.getInvoiceId()); + dot.setItemId(item.getId()); + addInvented(dot); + } + return Response.success(); + } + + @Override + @Transactional + public RestResponse importStatement(MultipartFile file) { + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + // 查找所有 + Map params = new HashMap<>(); + params.put("status", "0"); + List allList = corporateInvoiceMapper.list(params); + Map> listMap = allList.stream().collect(Collectors.groupingBy(x -> null == x.getNumber() ? "" : x.getNumber())); + //数据处理 + for (int i = 1; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + String number = sheetRowDatum.get(8); + List tempList = listMap.get(number); + if (null == tempList || tempList.isEmpty()) { + return RestResponse.failure("第" + (i + 1) + "行,发票号码对应的发票不存在!请检查后再次导入!"); + } + } + +// long userId = 0l; + long userId = RequestSecurityPolicy.getUserId(); + + List insertList = new ArrayList<>(); + for (int i = 1; i < sheetRowData.size(); i++) { + Map cell = sheetRowData.get(i); + SupplierState state = new SupplierState() {{ + setPo(cell.get(0)); + setLineNo(cell.get(1)); + setDesc(cell.get(2)); + setItemNo(cell.get(3)); + setQuantity(cell.get(4)); + setUnitPrice(cell.get(5)); + setAmount(cell.get(6)); + setCurrency(cell.get(7)); + setNumber(cell.get(8)); + setIsDel("0"); + setStatus("0"); + setCreateDate(new Date()); + setCreateBy(String.valueOf(userId)); + }}; + insertList.add(state); + } + insertIntoSupplierState(insertList); + return RestResponse.success(); } catch (Exception e) { - log.error("", e); - throw new ServiceException("更新失败"); + log.error(e.getMessage(), e); + throw new ServiceException("数据对账单导入失败"); } } - @Transactional @Override - public RestResponse updateUom(String invoiceId, String sellerTaxId) { + public RestResponse exportSupplierInvoiceAttachmentList(HttpServletResponse response, String pId) { + ServletOutputStream out = null; try { - String supplier = supplierMapper.selectSupplierCode(sellerTaxId); - List corporateInvoiceItems = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); - SysConfig ispf = sysConfigMapper.selectByCode("IS_PF"); - if (StringUtil.isNotEmpty(supplier) || (null != ispf && "1".equals(ispf.getValue()))) { - for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { - log.info("corporateInvoiceItem.getId()=>{}", corporateInvoiceItem.getId()); - if (StringUtil.isNotBlank(corporateInvoiceItem.getOriginPrice()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginUnit()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginQuantity())) { - log.info("corporateInvoiceItem.getSpecification()=>{}", corporateInvoiceItem.getSpecification()); - log.info("corporateInvoiceItem.getName()=>{}", corporateInvoiceItem.getName()); - SupplierMaterialUom uom = supplierMaterialUomMapper.selectByItem(supplier, corporateInvoiceItem.getSpecification(), corporateInvoiceItem.getName(), - corporateInvoiceItem.getUnit());//getOriginUnit-->unit - log.info("uom====>{}", uom); - if (null != uom) { - corporateInvoiceItem.setUnit(uom.getVersUnit()); - corporateInvoiceItem.setQuantity(String.valueOf(Double.parseDouble(corporateInvoiceItem.getOriginQuantity()) * Double.parseDouble(uom.getVersNum()))); - BigDecimal price = new BigDecimal(corporateInvoiceItem.getPrice()).divide(new BigDecimal(uom.getVersNum()), 10, BigDecimal.ROUND_HALF_UP); - corporateInvoiceItem.setPrice(price.toString()); - corporateInvoiceItemsMapper.updateByPrimaryKeySelective(corporateInvoiceItem); - } - } + CorporateInvoice invoice = corporateInvoiceMapper.selectById(pId); + List list = corporateInvoiceItemsMapper.listByPid(pId); + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "供应商发票明细") + .head(CorporateInvoiceItemsDto.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Override + public RestResponse uploadPOfile(MultipartFile file) { + try { + if (file != null) { + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + + String filePo = originalFilename.substring(0, originalFilename.lastIndexOf(".")); + + log.info("filePO:{}", filePo); + SupplierPo supplierPO = supplierPoMapper.selectByPo(filePo); + if (null == supplierPO) { + return RestResponse.failure("supplier_po表中无此PO数据……"); } + + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + String filPath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + + UUID.randomUUID().toString().replace("-", "") + suffix; + String folder = Pdf2JpgHelper.generateFolderNoFilePo(filePath); + String finalFilePath = filePath + java.io.File.separator + folder + java.io.File.separator + filPath; + String fileViewPath = domainName + contextPath + imgVirtualPath + "/" + folder + "/" + filPath; + + InputStream inputStream = file.getInputStream(); + com.cmsen.common.util.FileUtil.saveFile(inputStream, finalFilePath); + + supplierPO.setPath(finalFilePath); + supplierPO.setUri(fileViewPath); + + supplierPoMapper.updateByPrimaryKeySelective(supplierPO); + return RestResponse.success(); } return RestResponse.success(); + } catch (Exception e) { log.error(e.getMessage(), e); - throw new ServiceException("操作失败"); + throw new ServiceException("系统异常"); } } - @Override public Response createSupplierMaterialUom(List supplierMaterialUoms) { Response res = Response.success(); @@ -3577,11 +5376,90 @@ private SysRoleMapper sysRoleMapper; return res; } + @Override + public RestResponse getSupplierByInvoiceId(String invoiceId) { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(invoiceId); + String seller = corporateInvoice.getSeller(); + String title = corporateInvoice.getTitle(); + List list = supplierMapper.selectByLikeName(seller); + return RestResponse.success(list); + } + + @Override + public RestResponse getSupplierByNameLike(String name) { + List list = supplierMapper.selectByLikeName(name); + return RestResponse.success(list); + } + + @Override + public RestResponse saveSupplier(Supplier supplier) { + // supplier的id 去找到 supplier + Supplier entity = supplierMapper.selectByPrimaryKey(supplier.getId()); + // 将原 税号 赋值给 另一个值 + String oldTaxNo = entity.getTaxNo(); + + String newSellerNo = supplier.getTaxNo(); + supplier.setExt04(oldTaxNo); + supplier.setTaxNo(newSellerNo); + // 更新税号为 invoiceId的序号 + supplierMapper.updateByPrimaryKeySelective(supplier); + return RestResponse.success(); + } + + @Override + public List listAll() { + return supplierMapper.list(new HashMap<>()); + } + + @Override + public void sendDataToXTPT(String method, JSONObject params) { + log.info("============>推送协同平台方法:{}", method); + log.info("============>推送协同平台参数:{}", params.toJSONString()); + String apiPath = null; + SysConfig xtptApiBasePath = sysConfigMapper.selectByCode("PENGFEI_XTPT_BASE_API"); + if (null != xtptApiBasePath) { + apiPath = xtptApiBasePath.getValue(); + } + JSONObject fileData = new JSONObject(); + fileData.put("jsonrpc", "2.0"); + String createApi = null; + fileData.put("method", method); + fileData.put("params", params); + String token = get_XTPT_Token(); + fileData.put("session", token); + fileData.put("timestampin", System.currentTimeMillis()); + String data = JSON.toJSONString(fileData, SerializerFeature.DisableCircularReferenceDetect); + Map paramBody = new HashMap(); + paramBody.put("body", data); + paramBody.put("Content-Type", "application/json"); + paramBody.put("Authorization", ""); + + String[] response = interfaceUtil.httpPostMan2(apiPath, paramBody); + + log.info("pengfei 未匹配表单接口 code response ==={}===={},", response[1], response[0]); + if (Integer.parseInt(response[1]) != 200) { + log.error("pengfei sendDataToXTPT 交互网络异常,响应状态:" + response[1] + ",响应体为:" + response[0]); +// mesg.append(response[0]); + } else { + + JSONObject res = JSONObject.parseObject(response[0]); + Object resultObj = res.get("result"); + if (null == resultObj) { + JSONObject error = res.getJSONObject("error"); + log.error("pengfei sendDataToXTPT接口失败=》{}", error.getString("message")); + } else { + log.error("pengfei sendDataToXTPT接口成功"); + } + } + } @Override public void syncUomFromMapping(String invoiceId, String supplierCode) { + log.info("syncUomFromMapping invoiceID=>{} , supplierCode=>{}",invoiceId,supplierCode); List listDtos = supplierMapper.selectUomMapping(supplierCode); + log.info("syncUomFromMapping listDtos=>{} ",JSONObject.toJSONString(listDtos)); List items = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + log.info("syncUomFromMapping items=>{} ",JSONObject.toJSONString(items)); for (SupplierUomMappingDTO listDto : listDtos) { String uom = listDto.getUnit(); for (CorporateInvoiceItems item : items) { @@ -3613,6 +5491,7 @@ private SysRoleMapper sysRoleMapper; smu.setRemark(remark); // 重复判断 SupplierMaterialUom exists = supplierMaterialUomMapper.selectByMaterialNo(sm.getMaterialNo()); + log.info("syncUomFromMapping exists SupplierMaterialUom=>{} ",JSONObject.toJSONString(exists)); if (null == exists) { supplierMaterialUomMapper.insertSelective(smu); } else { @@ -3626,21 +5505,213 @@ private SysRoleMapper sysRoleMapper; } + @Async(value = "SystemPool") + public void insertIntoSupplierState(List insertList) { + List list = null; + list = supplierStateMapper.list(); + // 如果已存在 + Map> stateList = list.stream().collect(Collectors.groupingBy(SupplierState::getNumber)); + for (SupplierState supplierState : insertList) { + List existList = stateList.get(supplierState.getNumber()); + if (null == existList) { +// supplierStateMapper.updateEntityIsDel(supplierState.getCreateBy(),supplierState.getNumber(),new Date()); + supplierStateMapper.insert(supplierState); + } else { + supplierStateMapper.updateEntityIsDel(supplierState.getCreateBy(), supplierState.getNumber(), new Date()); + supplierStateMapper.insert(supplierState); + } - public static void main(String asd[]) { - - String itemTaxCode = "1080126000000000000"; - String orderTaxCode = "1080124020000000000"; - if (itemTaxCode.length() >= 5 && orderTaxCode.length() >= 5 && itemTaxCode.substring(0, 5).equals(orderTaxCode.substring(0, 5))) { - log.info(itemTaxCode.substring(0, 5)); - log.info(orderTaxCode.substring(0, 5)); } } - public static double similarity(String str1, String str2) { - int maxLength = Math.max(str1.length(), str2.length()); - return 1 - (double) levenshteinDistance(str1, str2) / maxLength; + // 虚拟物料处理 + public void addInvented(LineMatchListDto dto) { + try { + if (dto.getInvoiceId() == null || dto.getInvoiceId().length() == 0) { + return; + //throw new ServiceException("invoiceId不能为空"); + } + if (dto.getItemId() == null || dto.getItemId().length() == 0) { + return; + //throw new ServiceException("itemId不能为空"); + } + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(dto.getInvoiceId()); + CorporateInvoiceItems item = corporateInvoiceItemsMapper.selectByPrimaryKey(dto.getItemId()); + List itemMatchings = supplierOrderItemMatchingMapper.selectListByItemId(item.getId()); + SysConfig config = sysConfigMapper.selectByCode("VIRTUAL_CODE"); + if (config == null) { + return; + //throw new ServiceException("未设置虚拟物料"); + } + BigDecimal macthTotal = new BigDecimal("0"); + BigDecimal macthTaxTotal = new BigDecimal("0"); + for (SupplierOrderItemMatching tmp : itemMatchings) { + if (tmp.getItemNo().equals(config.getValue())) { + return; + //throw new ServiceException("只允许一条虚拟物料"); + } + macthTotal = macthTotal.add(tmp.getTotal()); + BigDecimal lineTax = tmp.getTax() == null ? BigDecimal.ZERO : tmp.getTax().add(tmp.getDeductionTax() == null ? BigDecimal.ZERO : tmp.getDeductionTax()); + macthTaxTotal = macthTaxTotal.add(lineTax); + } + + // 0 折后 1 折前 + Integer priceType = corporateInvoice.getPriceType(); + // 0 金额 1 数量 + Integer matchType = corporateInvoice.getMatchType(); + if (corporateInvoice == null) { + return; + //throw new ServiceException("发票不能为空"); + } + if (item == null) { + return; + //throw new ServiceException("明细不能为空"); + } + + SupplierOrderItemMatching matching = new SupplierOrderItemMatching(); + if (itemMatchings.size() > 0) { + matching.setReceiveNo(itemMatchings.get(0).getReceiveNo()); + matching.setOrderNo(itemMatchings.get(0).getOrderNo()); + matching.setOrderId(itemMatchings.get(0).getOrderId()); + + } else { + return; + //throw new ServiceException("无正常匹配记录"); + } + + BigDecimal total = new BigDecimal(item.getTotal()); + BigDecimal deduct = new BigDecimal(item.getDeductionAmount() == null ? "0" : item.getDeductionAmount()); + BigDecimal diff = new BigDecimal(item.getDifference()); + BigDecimal tax = new BigDecimal(item.getTax() == null ? "0" : item.getTax()).add(new BigDecimal(item.getDeductionTax() == null ? "0" : item.getDeductionTax())); + //BigDecimal result = total.add(deduct).subtract(diff).setScale(2,BigDecimal.ROUND_HALF_UP); + BigDecimal result = total.add(deduct).setScale(2, BigDecimal.ROUND_HALF_UP); + + matching.setInvoiceId(dto.getInvoiceId()); + matching.setItemId(item.getId()); + matching.setName("虚拟物料"); + matching.setSpecification(""); + matching.setUnit(item.getUnit()); + BigDecimal price = result.subtract(macthTotal); + BigDecimal priceTax = tax.subtract(macthTaxTotal); + // 折前需要加上deduction + /* if(priceType==1){ + price = new BigDecimal(item.getDifference()).add(new BigDecimal(item.getDeductionAmount())); + + }*/ + // 税额全部加到虚拟物料0625 + /*if(item.getDeductionTax()!=null) { + matching.setDeductionTax(new BigDecimal(item.getDeductionTax())); + }else{ + matching.setDeductionTax(BigDecimal.ZERO); + }*/ + BigDecimal price2 = price.abs(); + + if (price2.compareTo(new BigDecimal("1")) <= 0) {// 20220619<=0.02不处理 + return; + //return Response.success(); + } + // 20220510price取值修改 + matching.setPrice(price.setScale(5, BigDecimal.ROUND_HALF_UP)); + matching.setTotal(matching.getPrice()); + matching.setDeductionTaxRate("0"); + matching.setQuantity("1"); + + matching.setDeductionAmount(BigDecimal.ZERO); + matching.setDeductionTaxRate("0"); + //matching.setTax(BigDecimal.ZERO); + // 添加虚拟物料税20220625 + if (StringUtil.isNotBlank(item.getTax())) { + BigDecimal deAmount = new BigDecimal(item.getDeductionAmount() == null ? "0" : item.getDeductionAmount()); + BigDecimal deTax = new BigDecimal(item.getDeductionTax() == null ? "0" : item.getDeductionTax()); + if (new BigDecimal(item.getTotal()).add(deAmount).compareTo(BigDecimal.ZERO) != 0) { + BigDecimal percent = matching.getTotal().divide(new BigDecimal(item.getTotal()).add(deAmount), 10, BigDecimal.ROUND_HALF_UP); + matching.setTax((new BigDecimal(item.getTax()).add(deTax)).multiply(percent)); + } else { + matching.setTax(BigDecimal.ZERO); + + } + } + + + matching.setReceivedTotal(matching.getPrice()); + + matching.setTaxRate("0"); + matching.setMatchingStatus(0); + + + matching.setItemNo(config.getValue()); + + //supplierOrderItemMatchingMapper.insert(matching); + // 20220712虚拟物料分摊 + for (SupplierOrderItemMatching tmpShare : itemMatchings) { + SupplierOrderItemMatching matchingShare = new SupplierOrderItemMatching(); + matching.setReceiveNo(tmpShare.getReceiveNo()); + matchingShare.setOrderNo(tmpShare.getOrderNo()); + matchingShare.setOrderId(tmpShare.getOrderId()); + matchingShare.setInvoiceId(dto.getInvoiceId()); + matchingShare.setItemId(item.getId()); + matchingShare.setName("虚拟物料"); + matchingShare.setSpecification(""); + matchingShare.setUnit(item.getUnit()); + if (macthTotal.compareTo(BigDecimal.ZERO) == 0) { + matchingShare.setPrice(price.setScale(2, BigDecimal.ROUND_HALF_UP)); + } else { + matchingShare.setPrice(tmpShare.getTotal().divide(macthTotal, 10, BigDecimal.ROUND_HALF_UP).multiply(price).setScale(2, BigDecimal.ROUND_HALF_UP)); + } + matchingShare.setTotal(matchingShare.getPrice()); + matchingShare.setDeductionTaxRate("0"); + matchingShare.setQuantity("1"); + + matchingShare.setDeductionAmount(BigDecimal.ZERO); + matchingShare.setDeductionTaxRate("0"); + if (StringUtil.isNotBlank(item.getTax())) { + if (priceTax.compareTo(BigDecimal.ZERO) != 0) { + if (macthTotal.compareTo(BigDecimal.ZERO) == 0) { + matchingShare.setTax(priceTax.setScale(2, BigDecimal.ROUND_HALF_UP)); + + } else { + BigDecimal percent = matchingShare.getTotal().divide(price, 10, BigDecimal.ROUND_HALF_UP); + matchingShare.setTax(priceTax.multiply(percent).setScale(2, BigDecimal.ROUND_HALF_UP)); + } + } else { + matchingShare.setTax(BigDecimal.ZERO); + + } + } + + + matchingShare.setReceivedTotal(matchingShare.getPrice()); + + matchingShare.setTaxRate("0"); + matchingShare.setMatchingStatus(0); + + matchingShare.setMatchingId(tmpShare.getId().toString()); + matchingShare.setItemNo(config.getValue()); + supplierOrderItemMatchingMapper.insert(matchingShare); + + } + + updateDifference(corporateInvoice, item); + + //插入日志记录 2022/5/28 + SupplierMatchingLog supplierMatchingLog = new SupplierMatchingLog() {{ + setId(IdUtil.fastUUID()); + setPid(corporateInvoice.getId()); + setModule("InvoiceMatch"); + setMethods("SupplierOrderItemMatch"); + setOperatorUser(sysUserMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()).getName()); + setCreateTime(new Date()); + setReason("完成发票行【" + item.getName() + "+" + item.getSpecification() + "】的虚拟物料匹配"); + }}; + supplierMatchingLogMapper.insert(supplierMatchingLog); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("操作失败"); + } + } + + public static int levenshteinDistance(String str1, String str2) { int[][] distance = new int[str1.length() + 1][str2.length() + 1]; @@ -3656,6 +5727,22 @@ private SysRoleMapper sysRoleMapper; return distance[str1.length()][str2.length()]; } + + public static void main(String asd[]) { + + String itemTaxCode = "1080126000000000000"; + String orderTaxCode = "1080124020000000000"; + if (itemTaxCode.length() >= 5 && orderTaxCode.length() >= 5 && itemTaxCode.substring(0, 5).equals(orderTaxCode.substring(0, 5))) { + log.info(itemTaxCode.substring(0, 5)); + log.info(orderTaxCode.substring(0, 5)); + } + } + + public static double similarity(String str1, String str2) { + int maxLength = Math.max(str1.length(), str2.length()); + return 1 - (double) levenshteinDistance(str1, str2) / maxLength; + } + public Supplier supplierIsExist(boolean oldSupplierNotExistFlag, CorporateInvoice corporateInvoice, Supplier supplier) { SysConfig config = sysConfigMapper.selectByCode("OCR_INTERFACE_GET_SELLER_NO_URL"); if (oldSupplierNotExistFlag && (null != config && org.apache.commons.lang3.StringUtils.isNotEmpty(config.getValue()))) { @@ -3761,4 +5848,202 @@ private SysRoleMapper sysRoleMapper; return null; } + @Override + public RestResponse importSupplierOrderRefund(MultipartFile file) { + log.info("========================= SupplierOrderRefund ============================"); +// String fileName = "D:\\testExcel.xlsx"; + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + Long userId = RequestSecurityPolicy.getUserId(); + SysUser user = sysUserMapper.selectByPrimaryKey(userId.intValue()); + List insertList = new ArrayList<>(); + Map exist = new HashMap<>(); + StringBuffer sb = new StringBuffer(); + Date now = new Date(); + for (int i = 0; i < sheetRowData.size(); i++) { + Map cell = sheetRowData.get(i); + String receiveNo = cell.get(1); + String supplierCode = cell.get(2); + String orderNo = cell.get(3); + String goodsNum = cell.get(4); +// String unitPrice = cell.get(5); +// String amount = cell.get(6); + String itemNo = cell.get(5); + SupplierOrderRefund refund = new SupplierOrderRefund() {{ +// setAmount(amount); + setOrderNo(orderNo); + setSupplierCode(supplierCode); +// setUnitPrice(unitPrice); + setReceiveNo(receiveNo); + setGoodsNum(goodsNum); + setItemNo(itemNo); + setStatus(0); + setCreateDate(now); + }}; + insertList.add(refund); + } + insertSupplierOrderRefund(insertList); + interfaceLogService.executeUpdateSql("call update_supplier_order_refund()"); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("先款后票数据导入失败"); + } + } + + @Override + public RestResponse getSupplierOrderRefund() { + //20260609 添加退票推送逻辑 + // 先找到所有的orderNo 分组后 再传 + List ls = new ArrayList<>(); + List orderNoList = supplierOrderItemMatchingMapper.getRefundOrderNoList(); + + for (SupplierOrderItemsVo s : orderNoList) { + log.info("getSupplierOrderRefund orderNo =>{}", s.getOrderNo()); + log.info("getSupplierOrderRefund refundID =>{}", s.getItemNo()); + log.info("getSupplierOrderRefund receivedNo =>{}", s.getReceiveNo()); + log.info("getSupplierOrderRefund orderId =>{}", s.getOrderId()); + String supplierCode = s.getSupplierCode(); + String orderNo = s.getOrderNo(); + List refundLs = supplierOrderItemMatchingMapper.getRefundList(supplierCode, orderNo); + supplierOrderItemMatchingMapper.updateRefundStatus(supplierCode, orderNo); + supplierOrderItemMatchingMapper.updateByFlow("1"); + ls.addAll(refundLs); + } + return RestResponse.success(ls); + } + + @Override + public RestResponse deleteRefundOrders(String ids) { + StringBuilder sb = new StringBuilder(); + if (org.apache.commons.lang3.StringUtils.isEmpty(ids)) { + return RestResponse.success(); + } else { + String[] idsArr = ids.split(","); + for (String s : idsArr) { + Integer rId = Integer.valueOf(s); + // + SupplierOrderRefund sor = supplierOrderMapper.selectRefundById(rId); + int status = sor.getStatus(); + String orderId = sor.getReceiveNo(); + int oId = Integer.valueOf(orderId); + supplierOrderMapper.recoverRefundData(oId); + if (2 == status) { + sb.append(rId).append(";"); + } + supplierOrderMapper.deleteRefundById(rId); + } + String errorList = sb.toString(); + return RestResponse.success(errorList); + } + } + + private void insertSupplierOrderRefund(List insertList) { + + int batchSize = 500; + + for (int i = 0; i < insertList.size(); i += batchSize) { + // 计算结束位置:防止最后一批不足 500 条越界 + int end = Math.min(i + batchSize, insertList.size()); + + // 截取当前批次数据 [开始, 结束) 左闭右开 + List batchList = insertList.subList(i, end); + + supplierMapper.insertRefundBatch(batchList); + } + + + } + + public static boolean hasAtLeast3DecimalPlaces(String numStr) { + if (org.apache.commons.lang3.StringUtils.isEmpty(numStr)) { + return false; + } + String s = numStr.trim(); + int dotIndex = s.indexOf('.'); + // 没有小数点 + if (dotIndex == -1) { + return false; + } + // 小数点后面部分 + String decimalPart = s.substring(dotIndex + 1); + // 小数点后面字符长度 >=3 + return decimalPart.length() >= 3; + } + + public String get_XTPT_Token() { +// String url = "http://pengfei.fanhaninfo.test/jsonrpc"; + String url = null; + SysConfig xtptApiBasePath = sysConfigMapper.selectByCode("PENGFEI_XTPT_BASE_API"); + if (null != xtptApiBasePath) { + url = xtptApiBasePath.getValue(); + } + String account = null; + String password = null; + + SysConfig xtptLoginAccount = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_ACCOUNT"); + if (null != xtptLoginAccount) { + account = xtptLoginAccount.getValue(); + } + SysConfig xtptLoginPassword = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_PASSWORD"); + if (null != xtptLoginPassword) { + password = xtptLoginPassword.getValue(); + } + + + String token = null; + JSONObject dataJson = new JSONObject(); + + JSONObject params = new JSONObject(); + params.put("username", account); + params.put("password", password); + + dataJson.put("jsonrpc", "2.0"); + + + String loginApi = null; + SysConfig xtptLoginApi = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_API"); + if (null != xtptLoginApi) { + loginApi = xtptLoginApi.getValue(); + } + dataJson.put("method", loginApi); + dataJson.put("params", params); + dataJson.put("timestampin", System.currentTimeMillis()); + String data = JSON.toJSONString(dataJson, SerializerFeature.DisableCircularReferenceDetect); + Map paramBody = new HashMap(); + paramBody.put("body", data); + paramBody.put("Content-Type", "application/json"); + paramBody.put("Authorization", ""); + + String[] response = interfaceUtil.httpPostMan2(url, paramBody); + + log.info("pengfei 协同平台 login 接口 code response ==={}===={},", response[1], response[0]); + if (Integer.parseInt(response[1]) != 200) { + log.error("pengfei 协同平台 login 交互网络异常,响应状态:" + response[1] + ",响应体为:" + response[0]); +// mesg.append(response[0]); + } else { + + JSONObject res = JSONObject.parseObject(response[0]); + JSONObject result = res.getJSONObject("result"); + JSONObject error = res.getJSONObject("error"); + if (null == result) { + // 保存失败 +// mesg.append("pengfei 未匹配表单接口失败"); + log.error("pengfei 协同平台 login失败=》{}", error.getString("message")); + } else { + token = result.getString("token"); + log.info("pengfei 协同平台 login 成功"); + } + } + return token; + } + @Override + public RestResponse matchInvoices(String numberS, String numberE, Integer invoiceType) { + List list = corporateInvoiceMapper.supplierInvoiceMatchInvoiceList(numberS, numberE, invoiceType); + for (InvoiceItemListDto invoiceItemListDto : list) { + invoiceItemListDto.setUsedMoney(supplierOrderItemMatchingMapper.getUsedAmountByItemId(invoiceItemListDto.getId())); + } + return RestResponse.success(list); + } } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierStateServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierStateServiceImpl.java new file mode 100644 index 0000000..6cba517 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierStateServiceImpl.java @@ -0,0 +1,53 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.ticket.application.service.SupplierStateService; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoiceItems; +import com.cmsen.ticket.domain.entity.SupplierState; +import com.cmsen.ticket.domain.mapper.SupplierStateMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; + +@Slf4j +@Service +public class SupplierStateServiceImpl implements SupplierStateService { + + + @Resource + private SupplierStateMapper supplierStateMapper; + + @Override + public void insertCorporateInvoicePO(CorporateInvoice corporateInvoice,CorporateInvoiceItems corporateInvoiceItem, String po) { + + + List list = supplierStateMapper.listByPo(po); + if(list.isEmpty()){ + + }else{ + supplierStateMapper.updateIsDel("1",po); + } + + SupplierState supplierState = new SupplierState(); + supplierState.setAmount(corporateInvoiceItem.getTotal()); + supplierState.setCode(corporateInvoice.getCode()); + supplierState.setCreateBy(String.valueOf(corporateInvoice.getOwner())); + supplierState.setDesc(corporateInvoiceItem.getName()); + supplierState.setCreateDate(new Date()); + supplierState.setUpdateDate(corporateInvoice.getUpdateDate()); + supplierState.setUpdateBy(String.valueOf(corporateInvoice.getOwner())); +// supplierState.setItemNo(); +// supplierState.setLineNo(); + supplierState.setNumber(corporateInvoice.getNumber()); + supplierState.setPo(po); + supplierState.setQuantity(corporateInvoiceItem.getQuantity()); + supplierState.setStatus(String.valueOf(corporateInvoice.getStatus())); + supplierState.setUnitPrice(corporateInvoiceItem.getPrice()); + supplierState.setUom(corporateInvoiceItem.getUnit()); + supplierState.setIsDel("0"); + supplierStateMapper.insert(supplierState); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierUomMappingServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierUomMappingServiceImpl.java index 18ca2e1..7b85ab7 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierUomMappingServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SupplierUomMappingServiceImpl.java @@ -23,6 +23,7 @@ import java.util.Map; public class SupplierUomMappingServiceImpl implements SupplierUomMappingService { @Resource private SupplierUomMappingMapper mapper; + @Override public RestResponse list(Map params) { PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); @@ -31,6 +32,7 @@ public class SupplierUomMappingServiceImpl implements SupplierUomMappingService int total = mapper.countByParams(params); return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); } + @Override public RestResponse create(SupplierUomMapping record) { mapper.insert(record); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysConfigServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysConfigServiceImpl.java index 217b403..3ba4a0e 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysConfigServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysConfigServiceImpl.java @@ -25,6 +25,10 @@ public class SysConfigServiceImpl implements SysConfigService { @Value("${manager-file.uploadPath}") private String uploadPath; + + @Resource + private SysConfigMapper sysConfigMapper; + @Override public RestResponse list(Map params) { //PaginationUtil.paginationInit(params); @@ -36,8 +40,6 @@ public class SysConfigServiceImpl implements SysConfigService { return RestResponse.success(PaginationUtil.getPageResult(count, params, list)); } - @Resource - private SysConfigMapper sysConfigMapper; @Override diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysCorInvoiceServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysCorInvoiceServiceImpl.java index 9bbfee7..5e3c8bf 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysCorInvoiceServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysCorInvoiceServiceImpl.java @@ -1,9 +1,95 @@ package com.cmsen.ticket.application.manager.service.impl; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.thread.ThreadUtil; +import cn.hutool.core.util.ZipUtil; +import cn.hutool.http.HttpRequest; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.exception.ProcessingTransactional; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.*; import com.cmsen.ticket.application.manager.service.SysCorInvoiceService; +import com.cmsen.ticket.application.manager.vo.ElementTreeNodes; +import com.cmsen.ticket.application.service.*; +import com.cmsen.ticket.bestsign.util.InterfaceUtil; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.entity.weitai.SendResult; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SupplierOrderItemMatchingMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.response.Response; +import com.cmsen.ticket.domain.util.ReflectionUtil; +import com.cmsen.ticket.domain.util.*; +import com.cmsen.ticket.domain.vo.AIMaterialVO; +import com.cmsen.ticket.domain.vo.CorInvoiceUploadVo; +import com.cmsen.ticket.domain.vo.CorporateInvoiceVo; +import com.cmsen.ticket.domain.vo.FileVo; +import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; +import com.cmsen.ticket.infrastructure.ocr2.NDOcrService; +import com.cmsen.ticket.infrastructure.ocr2.OFDUtil; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import com.cmsen.ticket.infrastructure.tools.util.NumberExtractorUtil; +import com.cmsen.ticket.interfaces.facade.form.ScannerPostDate; +import com.cmsen.ticket.log.entity.TInterfaceLog; +import com.cmsen.ticket.log.mapper.TInterfaceLogMapper; +import com.cmsenframework.security.RequestSecurityPolicy; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.apache.pdfbox.text.PDFTextStripper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.imageio.ImageIO; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.*; +import java.util.concurrent.Executor; +import java.util.stream.Collectors; + +import static com.cmsen.ticket.domain.util.Pdf2JpgHelper.generateFolder; /** @@ -14,5 +100,4551 @@ import org.springframework.stereotype.Service; @Slf4j @Service public class SysCorInvoiceServiceImpl implements SysCorInvoiceService { + @Resource + private InterfaceUtil interfaceUtil; + @Resource + private RestTemplateConfig restTemplateConfig; + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Value("${manager-file.viewPath}") + private String viewPath; + + @Resource + private WeiTaiOcrService weiTaiOcrService; + + @Resource + private SupplierServiceImpl supplierService; + + @Resource + private FileMapper fileMapper; + + @Resource + @Qualifier(value = "ScannerPool") + private Executor scannerPool; + + @Resource + private ScannerLogsMapper scannerLogsMapper; + + @Resource + private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; + + @Resource + private SysUserOrgMapper sysUserOrgMapper; + + @Resource + private SupplierOrderItemMatchingMapper supplierOrderItemMatchingMapper; + + @Value("${manager-file.watchPath}") + private String watchPath; + + @Resource + private SupplierOutService supplierOutService; + + + @Value("${spring.application.name}") + private String applicationName; + + @Resource + private AccountMappingMapper accountMappingMapper; + + @Resource + private CompanyMapper companyMapper; + + + + @Resource + private CorpInvoiceReceiveHeaderMapper corpInvoiceReceiveHeaderMapper; + + @Resource + private CorpInvoiceReceiveLineMapper corpInvoiceReceiveLineMapper; + + @Resource + private CustomerMapper customerMapper; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + @Resource + private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @Resource + private SysOrgMapper sysOrgMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private SupplierStateService supplierStateService; + + @Resource + private SysUserMapper sysUserMapper; + + @Resource + private SupplierMapper supplierMapper; + + + @Resource + private SupplierOrderMapper supplierOrderMapper; + + @Resource + private CorporateInvoiceNdJsonMappingMapper corporateInvoiceNdJsonMappingMapper; + + @Resource + private SupplierMatchingMapper supplierMatchingMapper; + + @Resource + private TInterfaceLogMapper interfaceLogMapper; + + public final String PRICE_CN_NAME = "单价:"; + + @Resource + private RuleConfigMapper ruleConfigMapper; + + @Resource + private NDOcrService ndOcrService; + + @Resource + @Qualifier(value = "ScannerSplitPool") + private Executor scannerSplitPool; + @Resource + private CorporateInvoiceScannerFilesMapper corporateInvoiceScannerFilesMapper; + @Autowired + private SupplierMaterialDefineMapper supplierMaterialDefineMapper; + + + @Override + public RestResponse receiveLines(String pid) { + List corpInvoiceReceiveLines = corpInvoiceReceiveLineMapper.selectByPid(pid); + return RestResponse.success(corpInvoiceReceiveLines); + } + + @Override + public RestResponse corporateLines(String pid) { + List CorporateInvoiceItems = corporateInvoiceItemsMapper.selectItemsByPid(pid); + return RestResponse.success(CorporateInvoiceItems); + } + + @Override + public RestResponse receiveList(Integer pageSize, Integer pageNum, String status, String selNo) { + PageInfo pageInfo = + PageHelper.startPage(pageSize, pageNum) + .doSelectPageInfo(() -> { + Map map = new HashMap<>(); + map.put("status", status); + map.put("selNo", selNo); + corpInvoiceReceiveHeaderMapper.selectList2(map); + }); + return RestResponse.success(pageInfo); + } + + @Override + public RestResponse list(Map params) { + params.remove("pageNum"); + StringUtils.decoderUrl(params); + if (params.containsKey("po") && StringUtil.isNotEmpty(params.get("po").toString())) { + String po = params.get("po").toString(); + if(po.contains(",")){ + params.remove("po"); + String[] splitPo = po.split(","); + params.put("pos",splitPo); + } + } + if (params.containsKey("invoiceStart") && StringUtil.isNotEmpty(params.get("invoiceStart").toString())) { + params.put("invoiceStart", DateFormat.parse(params.get("invoiceStart").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + if (params.containsKey("invoiceEnd") && StringUtil.isNotEmpty(params.get("invoiceEnd").toString())) { + params.put("invoiceEnd", DateFormat.parse(params.get("invoiceEnd").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + SysUserOrg sysUserOrg = sysUserOrgMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + if (sysUserOrg != null && !Objects.equals(sysUserOrg.getDataAuthType(), 0)) { + if (Objects.equals(sysUserOrg.getDataAuthType(), 2)) { + params.put("searchOwner", RequestSecurityPolicy.getUserId()); + } else { + params.put("searchOrg", RequestSecurityPolicy.getUserId()); + } + } + PaginationUtil.paginationInit(params); + params.put("isPage", "1"); + + // 2026 04 03 + if(params.containsKey("number")){ + String numbers = params.get("number").toString().replace(",",","); + if(numbers.indexOf(",")>-1){ + // 表示查询多个。 + String[] numberArr = numbers.split(","); + params.put("numbers",numberArr); + } + } + + List list = corporateInvoiceMapper.list(params); + + for (CorporateInvoice corporateInvoice : list) { + String name = corporateInvoice.getTitle(); + if (org.apache.commons.lang3.StringUtils.isEmpty(name)) { + String taxNo = corporateInvoice.getSellerNo(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(taxNo)) { + String suName = supplierMapper.selectFullNameByTaxNo(taxNo); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(suName)) { + corporateInvoice.setTitle(suName); + } + } + } + } + int total = corporateInvoiceMapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(CorporateInvoice corporateInvoice) { + try { + corporateInvoice.setDate(DateFormat.parse(corporateInvoice.getDate(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setCreateDate(new Date()); + corporateInvoice.setMatchStatus(0); + corporateInvoice.setPriceType(1); + corporateInvoiceMapper.insert(corporateInvoice); + + // 2023-07-25 如果附件类型是 发票或者收据 + List fileList = null; + fileList = fileMapper.selectByPidAndType(corporateInvoice.getId(), "发票或收据"); + log.info("fileList.size():{}", fileList.size()); + if (!fileList.isEmpty()) { + com.cmsen.ticket.domain.entity.File tempFile = fileList.get(0); + String filePath = tempFile.getPath(); + log.info("filePath:{}", filePath); + String fileType = filePath.substring(filePath.lastIndexOf(".")); + + // 判断文件类型 是jpg 直接赋值 + if (".pdf".equals(fileType.toLowerCase())) { + // 是pdf 将imgPath 转为 jpg + String newFileSubPath = Pdf2JpgHelper.pdf2OnePageImage(filePath, uploadPath, sysConfigMapper); + String newFilePath = viewPath + newFileSubPath; + corporateInvoice.setImgPath(newFilePath); + } else { + corporateInvoice.setImgPath(tempFile.getUri()); + } + corporateInvoice.setOriginalFilePath(tempFile.getUri()); + } +// SendResult sendResult = weiTaiOcrService.sendInvoice(corporateInvoice); +// corporateInvoice.setIsSend(sendResult.getResult()); +// corporateInvoice.setStatus(sendResult.getResult().equals(1) ? 0 : 2); +// corporateInvoice.setMessage(sendResult.getMessage()); + // is_del=0 and is_send=0 and ext08='2' and status=0 + corporateInvoice.setIsSend(0); + corporateInvoice.setStatus(0); + + + // 2023-10-16 判断 形式发票 根据供应商代码 需要替换成主数据中的 税号 + String type = corporateInvoice.getTicketCode(); + log.info("ticketCode===>{}", type); + if ("60100".equals(type)) { + String sellerNo = corporateInvoice.getSellerNo(); + log.info("sellerNo===>{}", sellerNo); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(sellerNo)) { + Supplier supplier = supplierMapper.selectCodeByNameAndCode2(null, sellerNo); + if (null != supplier && org.apache.commons.lang3.StringUtils.isNotEmpty(supplier.getTaxNo())) { + String taxNo = supplier.getTaxNo(); + corporateInvoice.setSellerNo(taxNo); + } + } + } + + List ruleConfigs = ruleConfigMapper.selectByClientAndTicketType(1, 2, 1); + Map> ruleMap = ruleConfigs.stream().collect(Collectors.groupingBy(ruleConfig -> ruleConfig.getRuleInfo().getName())); + + RuleConfig duplicatedNum = ruleMap.get("票号重复规则").get(0); + Rule ruleInfo = duplicatedNum.getRuleInfo(); + SysConfig DUP_INV_BY_ORG_CONFIG = sysConfigMapper.selectByCode("DUP_INV_BY_ORG"); + Integer orgId = null; + if(null!=DUP_INV_BY_ORG_CONFIG&&"1".equals(DUP_INV_BY_ORG_CONFIG.getValue())){ + orgId = corporateInvoice.getOrgId(); + } + int count = corporateInvoiceMapper.checkInvoiceNumIsExistByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode(), corporateInvoice.getId(),orgId); + if (count > 0) { + log.info("corporateInvoice.getNumber(), corporateInvoice.getCode(),corporateInvoice.getId(),{},{},{}", corporateInvoice.getNumber(), corporateInvoice.getCode(), corporateInvoice.getId()); + log.info("票号重复规则>>Result>>{}", false); + corporateInvoice.setMessage(ruleInfo.getMessageCn()); + } + corporateInvoice.setStatus(2); + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if (null == ext08Config) { + corporateInvoice.setExt08("2"); + } else { + corporateInvoice.setExt08(ext08Config.getValue()); + } + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + /** + * 添加供应商发票明细 + * + * @param item + * @return + */ + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse createLine(CorporateInvoiceItems item) { + try { + if (item.getId() == null || item.getId().equals("")) { + item.setId(StringUtil.UUID()); + } + corporateInvoiceItemsMapper.insert(item); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(CorporateInvoice corporateInvoice) { + try { + // 20220513判断是否已有匹配 + int count = supplierOrderItemMatchingMapper.selectCountByInvoiceId(corporateInvoice.getId()); + if (count > 0) { + return RestResponse.failure("请先删除已匹配订单的记录"); + } + CorporateInvoice corporateInvoicePre = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + corporateInvoice.setUpdateDate(new Date()); + + + // 2023-07-25 如果附件类型是 发票或者收据 + List fileList = null; + fileList = fileMapper.selectByPidAndType(corporateInvoice.getId(), "发票或收据"); + log.info("fileList:{}", fileList.size()); + if (!fileList.isEmpty()) { + com.cmsen.ticket.domain.entity.File tempFile = fileList.get(0); + String filePath = tempFile.getPath(); + log.info("filePath:{}", filePath); + String fileType = filePath.substring(filePath.lastIndexOf(".")); + + // 判断文件类型 是jpg 直接赋值 + if (".pdf".equals(fileType.toLowerCase())) { + // 是pdf 将imgPath 转为 jpg + String newFileSubPath = Pdf2JpgHelper.pdf2OnePageImage(filePath, uploadPath, sysConfigMapper); + String newFilePath = viewPath + newFileSubPath; + corporateInvoice.setImgPath(newFilePath); + } else { + corporateInvoice.setImgPath(tempFile.getUri()); + } + corporateInvoice.setOriginalFilePath(tempFile.getUri()); + } + // 2023-10-16 判断 形式发票 根据供应商代码 需要替换成主数据中的 税号 + + String type = corporateInvoice.getTicketCode(); + if ("60100".equals(type)) { + String sellerNo = corporateInvoice.getSellerNo(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(sellerNo)) { + Supplier supplier = supplierMapper.selectCodeByNameAndCode2(null, sellerNo); + if (null != supplier && org.apache.commons.lang3.StringUtils.isNotEmpty(supplier.getTaxNo())) { + String taxNo = supplier.getTaxNo(); + corporateInvoice.setSellerNo(taxNo); + } + } + // 形式发票走发票号重复逻辑 + SysConfig DUP_INV_BY_ORG_CONFIG = sysConfigMapper.selectByCode("DUP_INV_BY_ORG"); + Integer orgId = null; + if(null!=DUP_INV_BY_ORG_CONFIG&&"1".equals(DUP_INV_BY_ORG_CONFIG.getValue())){ + orgId = corporateInvoice.getOrgId(); + } + List ruleConfigs = ruleConfigMapper.selectByClientAndTicketType(1, 2, 1); + Map> ruleMap = ruleConfigs.stream().collect(Collectors.groupingBy(ruleConfig -> ruleConfig.getRuleInfo().getName())); + + RuleConfig duplicatedNum = ruleMap.get("票号重复规则").get(0); + Rule ruleInfo = duplicatedNum.getRuleInfo(); + int count3 = corporateInvoiceMapper.checkInvoiceNumIsExistByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode(), corporateInvoice.getId(),orgId); + if (count3 > 0) { + log.info("corporateInvoice.getNumber(), corporateInvoice.getCode(),corporateInvoice.getId(),{},{},{}", corporateInvoice.getNumber(), corporateInvoice.getCode(), corporateInvoice.getId()); + log.info("票号重复规则>>Result>>{}", false); + corporateInvoice.setMessage(ruleInfo.getMessageCn()); + corporateInvoice.setStatus(2); + } + } + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + // 20220514退票暂挂判断 + if (corporateInvoice.getStatus() != 4 && corporateInvoice.getStatus() != 5 && corporateInvoice.getStatus() != 1) { + CorporateInvoice corporateInvoiceAfter = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + if (!corporateInvoicePre.getStatus().equals(1) && corporateInvoice.getStatus().equals(1)) { +// SendResult sendResult = weiTaiOcrService.sendInvoice(corporateInvoiceAfter); +// corporateInvoice.setIsSend(sendResult.getResult()); + if (corporateInvoice.getStatus() == 4) { + // 2025-08-04 退票则将isSend重置0 + corporateInvoice.setIsSend(0); + } +// corporateInvoice.setStatus(sendResult.getResult().equals(1) ? 1 : 2); +// corporateInvoice.setMessage(sendResult.getMessage()); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + } + // 保存即验真 形式发票不走此逻辑 + if (!"60100".equals(type)) { + reValidCorInvoice(corporateInvoice.getId()); + } + // 发送OA + if (corporateInvoice.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType != null && corporateInvoiceType.getSendType() == 1) { + supplierOutService.sendInvoice(corporateInvoice, applicationName, "0"); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + } + } + CorporateInvoice fresh = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + updatePOAndHTBH(fresh); + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + /** + * 保存后即验真 + */ + + @Async(value = "SystemPool") + @Transactional(rollbackFor = Exception.class) + public void reValidCorInvoice(String invoiceId) { + try { + log.info("Start ReValid CorInvoice update >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + Customer customer = customerMapper.queryById(1); + Integer corMaxValid = customer.getCorMaxValid(); + if (corMaxValid < 1) { + return; + } + Map param = new HashMap<>(); + param.put("invoiceId", invoiceId); + param.put("corMaxValid", corMaxValid); + List corporateInvoices = corporateInvoiceMapper.selectUnValidInvoiceUpdate(param); + for (CorporateInvoice corporateInvoice : corporateInvoices) { + try { + // 20220512如果已验真就不用验真 + if (corporateInvoice.getValidStatus().equals((byte) 0)) { + log.info("corporateInvoice.getVerifiedCode()==={}", corporateInvoice.getVerifiedCode()); + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + // 删除OCR识别的发票行 + corporateInvoiceItemsMapper.deleteByPid(corporateInvoice.getId()); + List items = corporateInvoice.getItems(); + for (CorporateInvoiceItems item : items) { + corporateInvoiceItemsMapper.insert(item); + } + } + if (corporateInvoice.getValidStatus().equals((byte) 1)) { + CorporateInvoice corporateInvoice1 = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + StringBuilder message = new StringBuilder(); + TicketType ticketType = ticketTypeMapper.selectByCode(corporateInvoice1.getTicketCode()); + corporateInvoice1.setStatus(0); + corporateInvoiceService.validationRules(corporateInvoice1, message, ticketType); + log.info("===corporateInvoice1.getStatus():{}", corporateInvoice1.getStatus()); + corporateInvoice1.setMessage(message.toString()); + if (corporateInvoice1.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice1.getInvoiceType()); + if (corporateInvoiceType != null && corporateInvoiceType.getSendType() == 1) { + supplierOutService.sendInvoice(corporateInvoice1, applicationName, "0"); + } + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if (null == ext08Config) { + corporateInvoice1.setExt08("2"); + } else { + corporateInvoice1.setExt08(ext08Config.getValue()); + } + } + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice1); + } + } catch (Exception e) { + log.error(e.getMessage()); + e.printStackTrace(); + log.error("ReValid CorInvoice update Error >> {}", corporateInvoice.getId()); + } + } + log.info("End ReValid update CorInvoice >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + } catch (Exception e) { + log.info("ReValid CorInvoice update Error>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + log.error(e.getMessage(), e); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(String id) { + try { + int count = supplierOrderItemMatchingMapper.selectCountByInvoiceId(id); + if (count > 0) { + return RestResponse.failure("请先删除已匹配订单的记录"); + } + corporateInvoiceMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public RestResponse exportExcel(HttpServletResponse response, Map params) { + ServletOutputStream out = null; + try { + params.remove("pageNum"); + if (params.containsKey("po") && StringUtil.isNotEmpty(params.get("po").toString())) { + String po = params.get("po").toString(); + if(po.contains(",")){ + params.remove("po"); + String[] splitPo = po.split(","); + params.put("pos",splitPo); + } + } + if (params.containsKey("invoiceStart") && StringUtil.isNotEmpty(params.get("invoiceStart").toString())) { + params.put("invoiceStart", DateFormat.parse(params.get("invoiceStart").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + if (params.containsKey("invoiceEnd") && StringUtil.isNotEmpty(params.get("invoiceEnd").toString())) { + params.put("invoiceEnd", DateFormat.parse(params.get("invoiceEnd").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + SysUserOrg sysUserOrg = sysUserOrgMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + if (sysUserOrg != null && !Objects.equals(sysUserOrg.getDataAuthType(), 0)) { + if (Objects.equals(sysUserOrg.getDataAuthType(), 2)) { + params.put("searchOwner", RequestSecurityPolicy.getUserId()); + } else { + params.put("searchOrg", RequestSecurityPolicy.getUserId()); + } + } + List list = corporateInvoiceMapper.list(params); + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "供应商发票") + .head(CorporateInvoice.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + + @Override + public RestResponse exportValidExcel(HttpServletResponse response, Map params) { + ServletOutputStream out = null; + try { + params.put("validStatus", 1); + params.put("isDel", "all"); + List list = corporateInvoiceMapper.list3(params); + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=validReport.xlsx"); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "已验证供应商发票") + .head(CorporateInvoice3.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Override + public RestResponse refundTicket(String id) { + SysConfig needSendBack = sysConfigMapper.selectByCode("INVOICE_REFUND_ISSEND_BACK"); + String isSend = null; + if (null != needSendBack) { + isSend = needSendBack.getValue(); + } + int count = corporateInvoiceMapper.refund(id, isSend); + return RestResponse.success(); + } + + @Override + public RestResponse exportImages(HttpServletResponse response, Map params) { + ServletOutputStream out = null; + try { + if (params.containsKey("po") && StringUtil.isNotEmpty(params.get("po").toString())) { + String po = params.get("po").toString(); + if(po.contains(",")){ + params.remove("po"); + String[] splitPo = po.split(","); + params.put("pos",splitPo); + } + } + if (params.containsKey("dateStart") && StringUtil.isNotEmpty(params.get("dateStart").toString())) { + params.put("dateStart", DateFormat.parse(params.get("dateStart").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + if (params.containsKey("dateEnd") && StringUtil.isNotEmpty(params.get("dateEnd").toString())) { + params.put("dateStart", DateFormat.parse(params.get("dateEnd").toString(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + } + SysUserOrg sysUserOrg = sysUserOrgMapper.selectByPrimaryKey((int) RequestSecurityPolicy.getUserId()); + if (sysUserOrg != null && !Objects.equals(sysUserOrg.getDataAuthType(), 0)) { + if (Objects.equals(sysUserOrg.getDataAuthType(), 2)) { + params.put("searchOwner", RequestSecurityPolicy.getUserId()); + } else { + params.put("searchOrg", RequestSecurityPolicy.getUserId()); + } + } + out = response.getOutputStream(); + // 2026 04 03 + if(params.containsKey("number")){ + String numbers = params.get("number").toString().replace(",",","); + if(numbers.indexOf(",")>-1){ + // 表示查询多个。 + String[] numberArr = numbers.split(","); + params.put("numbers",numberArr); + } + } + List list = corporateInvoiceMapper.list(params); + List files = new ArrayList<>(); + List fileNames = new ArrayList<>(); + for (CorporateInvoice corporateInvoice : list) { + String fileName = corporateInvoice.getFileName(); + String downloadUri = corporateInvoice.getDownloadUri(); + if (StringUtil.isNotEmpty(downloadUri)) { + String pathname; + if (downloadUri.contains("/opt")) { + pathname = uploadPath + downloadUri.substring(downloadUri.indexOf("/opt")); + } else { + pathname = uploadPath + downloadUri.substring(downloadUri.lastIndexOf("/")); + } + if (!fileName.equals("null") && new File(pathname).exists() && !fileNames.contains(pathname)) { + fileNames.add(pathname); + files.add(cn.hutool.core.io.FileUtil.file(pathname)); + } + } + } + if (files.isEmpty()) { + return RestResponse.failure("无文件,请确认条件。"); + } + File[] filesArray = files.toArray(new File[0]); + String zipFileName = System.currentTimeMillis() + ".zip"; + String folder = generateFolder(uploadPath); + File zipFile = ZipUtil.zip(cn.hutool.core.io.FileUtil.file(uploadPath + folder + zipFileName), false, filesArray); + response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(zipFileName, "UTF-8")); + byte[] bytes = cn.hutool.core.io.FileUtil.readBytes(zipFile); + out.write(bytes); + out.flush(); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Override + public RestResponse selectById(String id) { + return RestResponse.success(corporateInvoiceMapper.selectByIdContainsNames(id)); + } + + @Override + public RestResponse download(String id, HttpServletResponse response) { + OutputStream outputStream = null; + InputStream is = null; + try { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(id); + String path = StringUtil.isNotEmpty(corporateInvoice.getOriginalFilePath()) ? corporateInvoice.getOriginalFilePath() : corporateInvoice.getImgPath(); + if (StringUtil.isEmpty(path)) { + return RestResponse.failure("无效的地址。"); + } + String fileName = path.substring(path.lastIndexOf("/") + 1); + URL url = new URL(path); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setConnectTimeout(5000); + is = conn.getInputStream(); + response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileName, "UTF-8")); + outputStream = response.getOutputStream(); + byte[] bytes = new byte[2048]; + int len; + while ((len = is.read(bytes)) > 0) { + outputStream.write(bytes, 0, len); + } + return null; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("服务器异常"); + } finally { + IoUtil.close(is); + IoUtil.close(outputStream); + } + } + + @Override + public RestResponse upload(MultipartFile[] files, String type, String com, String invoiceType) { + log.info("corinvoice upload =>{} {} {} {}", files.length, type, com, invoiceType); + if (files.length == 0) { + return RestResponse.failure("请选择文件。"); + } +// // 根据sysconfig 判断形式发票日期是否必填。 +// SysConfig corInvoiceExchangeRateDateNeedConfig = sysConfigMapper.selectByCode("INVOICE_EXCHANGE_RATE_DATE_NEED"); +// if(null!=corInvoiceExchangeRateDateNeedConfig&&"1".equals(corInvoiceExchangeRateDateNeedConfig.getValue())&&"1".equals(invoiceType)){ +// // 如果是形式发票 并设置必填 +// if(org.apache.commons.lang3.StringUtils.isEmpty(exchangeRateDate)){ +// return RestResponse.failure(corInvoiceExchangeRateDateNeedConfig.getDesc()); +// } +// } + + + try { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setCode(type); + }}).get(0); + Long logId = null; + for (MultipartFile file : files) { + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(".pdf".equalsIgnoreCase(suffix) || ".ofd".equalsIgnoreCase(suffix))) { + return RestResponse.failure("错误的文件类型,请上传PDF,OFD文件。"); + } + + String oldName = originalFilename.substring(0, originalFilename.lastIndexOf(".")); +// String savePath = "service".equals(type) ? service : goods; + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + suffix; + String folder = generateFolder(uploadPath); + String uploadFilePath = uploadPath + folder + fileName; + //添加log + ScannerLogs scannerLogs = new ScannerLogs(); + scannerLogs.setCostType(type); + scannerLogs.setCompanyId(com); + scannerLogs.setFileName(originalFilename); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setHashKey(UUID.randomUUID().toString()); + scannerLogsMapper.insert(scannerLogs); + logId = scannerLogs.getId(); + int userId = (int) RequestSecurityPolicy.getUserId(); +// int userId = 0; + file.transferTo(new File(uploadFilePath)); + boolean ofd2PdfSuccess = false; + if(".ofd".equalsIgnoreCase(suffix)){ + OFDUtil.convertToPdf(uploadFilePath, uploadFilePath.replace(".ofd",".pdf").replace(".OFD",".pdf"),12); + ofd2PdfSuccess = true; + } + + + if (ofd2PdfSuccess||".pdf".equalsIgnoreCase(suffix)) { + scannerPool.execute(() -> { + String ocrPdfPath = uploadFilePath.replace(".ofd",".pdf").replace(".OFD",".pdf"); + if ("1".equals(invoiceType)) { + // 如果是形式发票 + SysConfig ocrProformaConfig = sysConfigMapper.selectByCode("OCR_PROFORMA"); + // ocrProformaConfig = proforma 繁翰OCR-FLD ; 其他任何值 VL 大模型 + if (null == ocrProformaConfig) { + log.warn("形式发票识别未配置匹配模型采用ocr模式识别"); + } + List overseasSplitList = new ArrayList<>(); + List overseasTempList = new ArrayList<>(); + List overseasMergeList = new ArrayList<>(); + + SysConfig SPLIT_MODE_CONFIG = sysConfigMapper.selectByCode("SPLIT_MODE_CONFIG"); + // 是否要将形式发票分页后合并 是通过哪种ND Code find_page_num/spilt_pdf_merge + // find_page_num 根据页码进行合并 + // spilt_pdf_merge 先根据页码,如果页码不存在根据invoice_number 信息 判断是否合并 + if (null != SPLIT_MODE_CONFIG && "spilt_pdf_merge".equals(SPLIT_MODE_CONFIG.getValue())) { + //1. 增加一个判断文件名分支 uploadFilePath + //如果文件名含外币发票走这个分支 + //2. 先将pdf拆分成单页 + //3. 每个单页调用分类模型,返回各种类型的页面 + // 1. 分类,排序 + // 2. 根据顺序号查发票号码 + // 3,组成新文件 + // 4. 内容识别 + try { + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(ocrPdfPath)); + int totalPage = readPdf.getNumberOfPages(); + if (totalPage > 1) { + File parent = new File(ocrPdfPath); + List splitPdfs = Pdf2JpgHelper.pdfSplit(ocrPdfPath, parent.getParent()); + // 分析页码 + List pageNumList = new ArrayList<>(); + String tempPageInvoiceNumber = null; + for (String overseaInvoicePath : splitPdfs) { + String ndSearchCode = "spilt_pdf_merge"; + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(overseaInvoicePath)); + if (null == jsonDataResult) { + log.error("overseaInvoicePath===nd api response not setting or error"); + continue; + } + String fileType = jsonDataResult.getString("附件类型"); //海外形式发票 + int pageNum = jsonDataResult.getInteger("第几页"); //1 + String splitFileInvoiceNo = jsonDataResult.getString("invoice_number"); + log.info("pageNum === >{}", pageNum); + log.info("fileType === >{}", fileType); + log.info("splitFileInvoiceNo === >{}", splitFileInvoiceNo); + if (fileType.indexOf("海外形式发票") > -1) { +// if("海外形式发票".equals(fileType)){ + if (null == tempPageInvoiceNumber) { + //第一次进入 + tempPageInvoiceNumber = splitFileInvoiceNo; + overseasSplitList.add(overseaInvoicePath); + } else { + if (org.apache.commons.lang3.StringUtils.isEmpty(splitFileInvoiceNo)) { + // 如果第一张有发票号码,但第二张也是形式发票,但是没有页码。则也认为是同一张 + overseasSplitList.add(overseaInvoicePath); + } else { + // 这里改成如果是第一张发票有发票号码。和下一张也是一样的发票号则认为是同一张 + if (tempPageInvoiceNumber.equals(splitFileInvoiceNo)) { + overseasSplitList.add(overseaInvoicePath); + pageNumList.add(pageNum); + } else { + // 如果发票号不一样 则合并前置所有pdf到1个pdf中 + // 根据pageNum merge pdf成1个。 + if (splitFileInvoiceNo.indexOf(".") > -1) { + overseasSplitList.add(overseaInvoicePath); + pageNumList.add(pageNum); + } else { + tempPageInvoiceNumber = null; + String mergePdfPath = uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasSplitList); + overseasMergeList.add(mergePdfPath); + overseasSplitList = new ArrayList<>(); + overseasSplitList.add(overseaInvoicePath); + } + + } + } + } + } + } + if (!overseasSplitList.isEmpty()) { + String mergePdfPath = uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasSplitList); + overseasMergeList.add(mergePdfPath); + } + for (String splitPdf : splitPdfs) { + new File(splitPdf).delete(); + } + } + if (!overseasMergeList.isEmpty()) { + for (String s : overseasMergeList) { + if (null == ocrProformaConfig || "proforma".equals(ocrProformaConfig.getValue())) { + // 弗兰德OCR接口 + this.pdfToImagesForProforma(oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + SysConfig PROFORMA_HEAD_LINE_SPLIT_CONFIG = sysConfigMapper.selectByCode("PROFORMA_HEAD_LINE_SPLIT"); + if (null != PROFORMA_HEAD_LINE_SPLIT_CONFIG && "1".equals(PROFORMA_HEAD_LINE_SPLIT_CONFIG.getValue())) { + this.ocrProformaFromNdApiHeadLine(oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),""); + } + } + } + } else { + if (null == ocrProformaConfig || "proforma".equals(ocrProformaConfig.getValue())) { + // 弗兰德OCR接口 + this.pdfToImagesForProforma(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + SysConfig PROFORMA_HEAD_LINE_SPLIT_CONFIG = sysConfigMapper.selectByCode("PROFORMA_HEAD_LINE_SPLIT"); + if (null != PROFORMA_HEAD_LINE_SPLIT_CONFIG && "1".equals(PROFORMA_HEAD_LINE_SPLIT_CONFIG.getValue())) { + this.ocrProformaFromNdApiHeadLine(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),""); + } + } + } + + } catch (Exception e) { + log.error("将合并的文件调用海外形式发票识别,插入发票表 异常", e.getMessage()); + } + } else { + //1. 增加一个判断文件名分支 + //2. 先将pdf拆分成单页 + //3. 每个单页调用分类模型,返回各种类型的页面 + ///find_page_num 的模型code + //4. 过滤出所有类型 = 海外形式发票的pdf单页 + //5. 新的单页再走pdf分页合并模型,获取页数,譬如1-2-3-1-2 + //6. 只要碰到1或结束就把前面的pdf合并,譬如1-2-3合并一个文件,1-2合并一个文件。 + //7. 将合并的文件调用海外形式发票识别,插入发票表 + try { + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(ocrPdfPath)); + int totalPage = readPdf.getNumberOfPages(); + + if (totalPage > 1) { + File parent = new File(ocrPdfPath); + List splitPdfs = Pdf2JpgHelper.pdfSplit(ocrPdfPath, parent.getParent()); + // 分析页码 + List pageNumList = new ArrayList<>(); + for (String overseaInvoicePath : splitPdfs) { + String ndSearchCode = "find_page_num"; + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(overseaInvoicePath)); + if (null == jsonDataResult) { + log.error("overseaInvoicePath===nd api response not setting or error"); + continue; + } + String fileType = jsonDataResult.getString("附件类型"); //海外形式发票 + int pageNum = jsonDataResult.getInteger("第几页"); //1 + log.info("pageNum === >{}", pageNum); + log.info("fileType === >{}", fileType); + if ("海外形式发票".equals(fileType)) { + overseasSplitList.add(overseaInvoicePath); + pageNumList.add(pageNum); + } + } + // 根据pageNum merge pdf成1个。 + for (int i1 = 0; i1 < pageNumList.size(); i1++) { + int currentNum = pageNumList.get(i1); + if (currentNum == 1) { + // 将上一轮的pdf合并 + if (overseasTempList.isEmpty()) { + overseasTempList.add(overseasSplitList.get(i1)); + } else { + String mergePdfPath = uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasTempList); + overseasMergeList.add(mergePdfPath); + overseasTempList = new ArrayList<>(); + overseasTempList.add(overseasSplitList.get(i1)); + } + } else { + overseasTempList.add(overseasSplitList.get(i1)); + } + } + if (!overseasTempList.isEmpty()) { + String mergePdfPath = uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasTempList); + overseasMergeList.add(mergePdfPath); + } + for (String splitPdf : splitPdfs) { + new File(splitPdf).delete(); + } + } + if (!overseasMergeList.isEmpty()) { + for (String s : overseasMergeList) { + if (null == ocrProformaConfig || "proforma".equals(ocrProformaConfig.getValue())) { + // 弗兰德OCR接口 + this.pdfToImagesForProforma(oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + SysConfig PROFORMA_HEAD_LINE_SPLIT_CONFIG = sysConfigMapper.selectByCode("PROFORMA_HEAD_LINE_SPLIT"); + if (null != PROFORMA_HEAD_LINE_SPLIT_CONFIG && "1".equals(PROFORMA_HEAD_LINE_SPLIT_CONFIG.getValue())) { + this.ocrProformaFromNdApiHeadLine(oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + String ndSearchCode = "classify_proforma"; // + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(s)); + if (null == jsonDataResult) { + log.error("addProcessForExtract===nd api response not setting or error"); + return; + } + String fileType = jsonDataResult.getString("type"); + + if ("日本形式发票".equals(fileType)) { + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),"_JP"); + }else{ + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),""); + } + } + + } + } + } else { + if (null == ocrProformaConfig || "proforma".equals(ocrProformaConfig.getValue())) { + // 弗兰德OCR接口 + this.pdfToImagesForProforma(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + SysConfig PROFORMA_HEAD_LINE_SPLIT_CONFIG = sysConfigMapper.selectByCode("PROFORMA_HEAD_LINE_SPLIT"); + if (null != PROFORMA_HEAD_LINE_SPLIT_CONFIG && "1".equals(PROFORMA_HEAD_LINE_SPLIT_CONFIG.getValue())) { + this.ocrProformaFromNdApiHeadLine(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + String ndSearchCode = "classify_proforma"; // + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(ocrPdfPath)); + if (null == jsonDataResult) { + log.error("addProcessForExtract===nd api response not setting or error"); + return; + } + String fileType = jsonDataResult.getString("type"); + + if ("日本形式发票".equals(fileType)) { + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),"_JP"); + }else{ + this.ocrProformaFromNdApi(ocrPdfPath, oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),""); + } + } + } + } + } catch (Exception e) { + log.error("将合并的文件调用海外形式发票识别,插入发票表 异常", e.getMessage()); + } + } + + } else if ("0".equals(invoiceType)) { + // 如果是增值税发票 拆分多个jpg 单独识别 + Pdf2JpgHelper.pdfToImages2AndSaveCache(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), sysConfigMapper); + } else if ("2".equals(invoiceType)) { + + this.pdfToImagesForElectronic(oldName, scannerLogs.getHashKey(), ocrPdfPath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } + }); + } else { + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpeg"; + String newImagePath = watchPath + newFileName; + StorageCache.write(newFileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + newFileName, userId, 1000 * 60 * 30); + StorageCache.write("HashKey." + newFileName, scannerLogs.getHashKey(), 1000 * 60 * 30); + StorageCache.write("CorType." + newFileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + newFileName, uploadFilePath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + newFileName, scannerLogs.getId(), 1000 * 60 * 30); + OFDUtil.dealOFDToJPEG(uploadFilePath, newImagePath); + } + } + return RestResponse.success(logId); + } catch (Exception e) { + log.error(e.getMessage(), e); + return RestResponse.failure("系统错误"); + } + } + + @Override + public RestResponse uploadReceive(MultipartFile[] files, String type, String com) { + log.info("{} {} {}", files.length, type, com); + if (files.length == 0) { + return RestResponse.failure("请选择文件。"); + } + try { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setCode(type); + }}).get(0); + for (MultipartFile file : files) { + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(".pdf".equalsIgnoreCase(suffix) || ".ofd".equalsIgnoreCase(suffix))) { + return RestResponse.failure("错误的文件类型,请上传PDF,OFD文件。"); + } +// String savePath = "service".equals(type) ? service : goods; + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + suffix; + String folder = Pdf2JpgHelper.generateFolder(uploadPath); + String uploadFilePath = uploadPath + folder + fileName; + + //添加log + ScannerLogs scannerLogs = new ScannerLogs(); + scannerLogs.setCostType(type); + scannerLogs.setCompanyId(com); + scannerLogs.setFileName(originalFilename); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setHashKey(UUID.randomUUID().toString()); + scannerLogsMapper.insert(scannerLogs); + + int userId = (int) RequestSecurityPolicy.getUserId(); +// int userId = 0; + file.transferTo(new File(uploadFilePath)); + if (".pdf".equalsIgnoreCase(suffix)) { + scannerPool.execute(() -> { + Pdf2JpgHelper.pdfToImages3AndSaveCache(scannerLogs.getHashKey(), uploadFilePath, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId()); + }); + } else { + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpeg"; + String newImagePath = watchPath + newFileName; + StorageCache.write(newFileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + newFileName, userId, 1000 * 60 * 30); + StorageCache.write("HashKey." + newFileName, scannerLogs.getHashKey(), 1000 * 60 * 30); + StorageCache.write("CorType." + newFileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + newFileName, uploadFilePath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + newFileName, scannerLogs.getId(), 1000 * 60 * 30); + log.info("fileName===>{}", fileName); + log.info("corporateInvoiceType===>{}", corporateInvoiceType); + log.info("newImagePath====>{}", newImagePath); + OFDUtil.dealOFDToJPEG(uploadFilePath, newImagePath); + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + return RestResponse.failure("系统错误"); + } + } + + @Transactional + @Override + public RestResponse uploadAtt(MultipartFile[] files, String id) { + if (files.length == 0) { + return RestResponse.failure("请选择文件。"); + } + if (StringUtil.isEmpty(id)) { + return RestResponse.failure("无效的ID"); + } + try { + for (MultipartFile file : files) { + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(suffix.equalsIgnoreCase(".pdf"))) { + return RestResponse.failure("错误的文件类型,请上传PDF,OFD文件。"); + } + InputStream inputStream = file.getInputStream(); + InputStream inputStream2 = file.getInputStream(); + String folder = generateFolder(uploadPath); + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + originalFilename; + FileUtil.saveFile(inputStream, uploadPath + folder + fileName); + List> fileNames = Pdf2JpgHelper.pdfToImages2(inputStream2, uploadPath, true); + for (List name : fileNames) { + String uri = viewPath + name.get(0); + fileMapper.insert(new com.cmsen.ticket.domain.entity.File() {{ + setPid(id); + setUri(uri); + setPath(uploadPath + folder + name.get(0)); + setType(""); + }}); + } + } +// weiTaiOcrService.sendAttachment(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统异常"); + } + } + + @Override + public RestResponse uploadInvPdf(MultipartFile file) { + try { + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(suffix.equalsIgnoreCase(".pdf"))) { + return RestResponse.failure("错误的文件类型,请上传PDF,OFD文件。"); + } + InputStream inputStream = file.getInputStream(); + InputStream inputStream2 = file.getInputStream(); + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + originalFilename; + String folder = generateFolder(uploadPath); + FileUtil.saveFile(inputStream, uploadPath + folder + fileName); + List> fileNames = Pdf2JpgHelper.pdfToImages2(inputStream2, uploadPath, true); + return RestResponse.success(new HashMap() {{ + put("originalFilePath", viewPath + folder + fileName); + put("imgPath", viewPath + fileNames.get(0).get(0)); + }}); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("System Error."); + } + } + + @Transactional + @Override + public RestResponse updateData(MultipartFile file) { + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + Map> errorSheetRowData = new HashMap<>(); + for (int i = 0; i < sheetRowData.size(); i++) { + Map sheetRowDatum = sheetRowData.get(i); + String id = StringUtil.trim(String.valueOf(sheetRowDatum.get(0))); // ID + + // 判断ID是否为空 + if (StringUtil.isEmpty(id)) { + errorSheetRowData.put(i, sheetRowDatum); + + // 记录参数到日志 + log.error("[{}]: {}", i, sheetRowDatum); + continue; + } + + // 参数对象 + Map params = new HashMap<>(); + params.put("id", id); // ID + params.put("code", String.valueOf(sheetRowDatum.get(4))); // 发票代码 + params.put("number", String.valueOf(sheetRowDatum.get(5))); // 发票号码 + params.put("postingDate", DateFormat.parse(String.valueOf(sheetRowDatum.get(17)))); // 入账时间 + params.put("deductTime", DateFormat.parse(String.valueOf(sheetRowDatum.get(19)))); // 抵扣日期 + params.put("deductStatus", String.valueOf(sheetRowDatum.get(18))); // 抵扣状态 + params.put("status", CorporateInvoice.statusStrToNumber(String.valueOf(sheetRowDatum.get(16)))); // 状态 + params.put("remarks", String.valueOf(sheetRowDatum.get(15))); // 备注 + params.put("npo", String.valueOf(sheetRowDatum.get(13))); // NPO + String operator = String.valueOf(sheetRowDatum.get(10)); + params.put("operator", StringUtil.isNotEmpty(operator) ? operator.split("\\.")[0] : operator); // 操作人 + params.put("updateDate", DateFormat.parse(String.valueOf(sheetRowDatum.get(12)))); // 更新日期 + + // 记录参数到日志 + log.info("[{}]: {}", i, params); + + // 数据写入 + corporateInvoiceMapper.updateByDeductStatus(params); + + // 释放内存 + params.clear(); + } + + // 输出错误工作表行数据 + return RestResponse.success(errorSheetRowData, 200); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("数据更新失败"); + } + + } + + @Transactional + @Override + public RestResponse updateDeductStatus() { + return ProcessingTransactional.update(() -> { + corporateInvoiceMapper.updateCorInvDeductStatusTask(); + return RestResponse.success(); + }); + } + + @Transactional + @Override + public RestResponse completeCheck(String invoiceId) { + try { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectById(invoiceId); + int isSend = corporateInvoice.getIsSend(); + if (1 == isSend) { + return RestResponse.failure("数据不可重复发送"); + } + //1、一个是拼接字段,一共7个字段拼接的,(companyid) + // companyId costcenter account + CorporateInvoiceVo account = corporateInvoiceMapper.getAccount(invoiceId); + if (null != account) { + String companyId = account.getCompanyId(); + if (org.apache.commons.lang3.StringUtils.isEmpty(companyId)) { + return RestResponse.failure("公司字段不能为空"); + } + } else { + return RestResponse.failure("公司字段不能为空"); + } + + String costCenter = account.getCostCenter(); + if (org.apache.commons.lang3.StringUtils.isEmpty(costCenter)) { + return RestResponse.failure("costcenter不能为空"); + } + if (corporateInvoice.getSubject() == null) { + return RestResponse.failure("科目段不能为空"); + } + AccountMapping accountMapping = accountMappingMapper.selectBySubject(corporateInvoice.getSubject()); + if (null == accountMapping) { + return RestResponse.failure("accountMapping不存在"); + } + //2、状态控制 satus=0时才可以发送 + Integer status = corporateInvoice.getStatus(); + if (0 != status) { + return RestResponse.failure("该状态的发票不能操作"); + } + String taxNo = corporateInvoice.getSellerNo(); + if (taxNo.indexOf(" ") > -1) { + taxNo = taxNo.replace(" ", ""); + corporateInvoice.setSellerNo(taxNo); + corporateInvoiceMapper.updateTaxNo(corporateInvoice); + } + + + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("Unknown Error"); + } + } + + @Override + public RestResponse getAllSubjects() { + List accountMappings = accountMappingMapper.list(); + return RestResponse.success(accountMappings); + } + + @Override + public RestResponse getAllSubjectsTreeNode() { + List treeNodes = new ArrayList<>(); + List accountMappings = accountMappingMapper.list(); + List nodesAll = new ArrayList<>(); + for (AccountMapping accountMapping : accountMappings) { + String category = accountMapping.getCategory(); + int id = accountMapping.getId(); + String name = accountMapping.getType(); + ElementTreeNodes node = new ElementTreeNodes(); + node.setId(id); + node.setLabel(name); + node.setParent(category); + node.setChildren(null); + node.setFilterPath(category + name); + nodesAll.add(node); + } + + + Map> maps = nodesAll.stream().collect(Collectors.groupingBy(ElementTreeNodes::getParent)); + for (String key : maps.keySet()) { + ElementTreeNodes node = new ElementTreeNodes(); + node.setLabel(key); + node.setChildren(maps.get(key)); + treeNodes.add(node); + } + return RestResponse.success(treeNodes); + } + + @Override + public RestResponse getSubjectById(String invoiceId) { + AccountMapping accountMapping = accountMappingMapper.selectByInvoice(invoiceId); + if (accountMapping == null) { + return RestResponse.success(new AccountMapping()); + } + return RestResponse.success(accountMapping); + } + + @Transactional + @Override + public RestResponse updateSubject(CorporateInvoice corporateInvoice) { + try { + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("更新失败"); + } + } + + @Async(value = "SystemPool") + public void updateSellerAndBuyerNo(int invoiceType, CorporateInvoice corporateInvoice) { + // 20205-04-22 这里 + // 判断是否需要如此操作的sysconfig + // sysconfig: auto_supplier_tax_code 0 不执行 1 执行 + SysConfig auto_supplier_tax_code_config = sysConfigMapper.selectByCode("auto_supplier_tax_code"); + if (null != auto_supplier_tax_code_config) { + String auto_supplier_tax_code = auto_supplier_tax_code_config.getValue(); + if ("1".equals(auto_supplier_tax_code)) { + // 判断是形式发票还是国内发票 + if (1 == invoiceType) { + if (org.apache.commons.lang3.StringUtils.isEmpty(corporateInvoice.getSellerNo())) { + // 国外形式发票 + // 根据供应商名称去supplier表里查找对应的供应商; + //如果没找到就退出。 + String sellerName = corporateInvoice.getSeller(); + log.info("sellerName =>{}", sellerName); + List supplierList = supplierMapper.selectNotCNCompany(); + Supplier matchSupplier = runTextsText(supplierList, sellerName); + if (null != matchSupplier) { + String taxNo = matchSupplier.getTaxNo(); + if (org.apache.commons.lang3.StringUtils.isEmpty(taxNo)) { + //如果找到并且供应商税号为空,那么供应商税号赋值为供应商id,发票上税号赋值为供应商税号。 + String supplierCode = matchSupplier.getCode(); + matchSupplier.setTaxNo(supplierCode); + supplierMapper.updateByPrimaryKey(matchSupplier); + corporateInvoice.setSellerNo(supplierCode); + } else { + //如果找到并且供应商税号有值,那么供应商税号不动,发票上税号赋值为供应商税号。 + corporateInvoice.setSellerNo(taxNo); + } + corporateInvoiceMapper.updateSellerNo(corporateInvoice); + } + } + // buyerNo 匹配 + String buyer = corporateInvoice.getBuyer(); + log.info("buyer =>{}", buyer); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(buyer) && org.apache.commons.lang3.StringUtils.isEmpty(corporateInvoice.getBuyerNo())) { + //如果没找到就退出。 + List companies = companyMapper.selectNotCNCompany(); + Company matchCompany = runTextsTextCompany(companies, buyer); + if (null != matchCompany) { + corporateInvoice.setBuyerNo(matchCompany.getDutyParagraph()); + corporateInvoiceMapper.updateBuyerNo(corporateInvoice); + + // 同时这里需要根据 company判断是否是 + // BAOZUN KOREA INC. 韩国10% + // BAOZUN ASIA PTE. LTD. 和 BAOZUN ETRADE ASIA PTE. LTD. 新加坡9% + // 台湾宝尊电子商务股份有限公司 台湾5% + // 来判断是否需要在明细中 重新计算itme的total + // 供应方(供应商),需要抵扣的供应商,需要维护国家的信息。共19家,已经发到群里 + // 如果采购方和供应方的国别和上述需要抵扣的国家一致,取国家的税率 + String country = matchCompany.getExt04(); + log.info("country=>{}", country); + String taxRate = matchCompany.getExt05(); + log.info("taxRate=>{}", taxRate); + // 存在特殊情况 日本 香港 一些发票需要将发票的不含税金额 改变成含税金额 + if ("2".equals(country)) { + BigDecimal taxRateDecimal = new BigDecimal(taxRate); + List items = corporateInvoiceItemsMapper.selectItemsByPid(corporateInvoice.getId()); + for (CorporateInvoiceItems item : items) { + String price = item.getPrice(); + String total = item.getTotal(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(price)) { + BigDecimal priceDecimal = new BigDecimal(price); + BigDecimal newPrice = priceDecimal.multiply(BigDecimal.ONE.add(taxRateDecimal)).setScale(0, RoundingMode.HALF_UP); + item.setOriginPrice(price); + item.setPrice(newPrice.toString()); + SysConfig specAddPriceConfig = sysConfigMapper.selectByCode("addition_spec"); + String specAddPrice = specAddPriceConfig == null ? "0" : specAddPriceConfig.getValue(); + if ("1".equals(specAddPrice)) { + String unitPrice = new BigDecimal(item.getPrice()).setScale(0, RoundingMode.HALF_UP).toString(); + String itemNo = item.getItemNo(); + if (org.apache.commons.lang3.StringUtils.isEmpty(itemNo)) { + itemNo = ""; + } + String specification = item.getSpecification(); + if (specification.indexOf(itemNo) > -1) { + specification = specification.substring(0, specification.indexOf(itemNo)); + item.setSpecification(specification); + }else{ + item.setSpecification(itemNo + " " + item.getSpecification() + PRICE_CN_NAME + unitPrice); + } + + } + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(total)) { + BigDecimal totalDecimal = new BigDecimal(total); + String tax = item.getTax(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(tax)) { + item.setTax(tax.replace(",", "")); + BigDecimal newTotal = totalDecimal.add(new BigDecimal(tax.replace(",", ""))); + item.setTotal(newTotal.toString()); + item.setDifference(newTotal.toString()); + } else { + BigDecimal newTotal = totalDecimal.multiply(BigDecimal.ONE.add(taxRateDecimal)).setScale(0, RoundingMode.HALF_UP); + item.setTotal(newTotal.toString()); + item.setDifference(newTotal.toString()); + } + item.setTaxRate(taxRateDecimal.multiply(new BigDecimal(100)).toString()); + } + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(item); + } + } else { + + List sps = supplierMapper.selectByTaxNo(corporateInvoice.getSellerNo()); + if (sps.isEmpty()) { + return; + } + String supplierCountry = sps.get(0).getExt01(); + log.info("supplierCountry=>{}", supplierCountry); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(country) && country.equals(supplierCountry)) { + // 满足条件 获取税率后 重新复制item + if (org.apache.commons.lang3.StringUtils.isNotEmpty(taxRate)) { + BigDecimal taxRateDecimal = new BigDecimal(taxRate); + List items = corporateInvoiceItemsMapper.selectItemsByPid(corporateInvoice.getId()); + for (CorporateInvoiceItems item : items) { + String price = item.getPrice(); + String total = item.getTotal(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(price)) { + BigDecimal priceDecimal = new BigDecimal(price); + BigDecimal newPrice = priceDecimal.divide(BigDecimal.ONE.add(taxRateDecimal), 2, BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_UP); + item.setOriginPrice(price); + item.setPrice(newPrice.toString()); + SysConfig specAddPriceConfig = sysConfigMapper.selectByCode("addition_spec"); + String specAddPrice = specAddPriceConfig == null ? "0" : specAddPriceConfig.getValue(); + if ("1".equals(specAddPrice)) { + String unitPrice = new BigDecimal(item.getPrice()).setScale(2, RoundingMode.HALF_UP).toString(); + String itemNo = item.getItemNo(); + if (org.apache.commons.lang3.StringUtils.isEmpty(itemNo)) { + itemNo = ""; + } + String specification = item.getSpecification(); + if (specification.indexOf(itemNo) > -1) { + specification = specification.substring(0, specification.indexOf(itemNo)); + item.setSpecification(specification); + }else{ + item.setSpecification(itemNo + " " + item.getSpecification() + PRICE_CN_NAME + unitPrice); + } + + } + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(total)) { + BigDecimal totalDecimal = new BigDecimal(total); + BigDecimal newTotal = totalDecimal.divide(BigDecimal.ONE.add(taxRateDecimal), 2, BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_UP); + item.setTotal(newTotal.toString()); + BigDecimal tax = totalDecimal.subtract(newTotal); + item.setTax(tax.toString()); + item.setTaxRate(taxRateDecimal.multiply(new BigDecimal(100)).toString()); + item.setDifference(newTotal.toString()); + } + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(item); + } + } + } + } + + } + } + } + if (2 == invoiceType) { + //如果是国内发票: + //根据供应商名称去supplier表里查找对应的供应商(没有找到就退出),如果该供应商税号为空则赋值发票上的税号。 + if (org.apache.commons.lang3.StringUtils.isNotEmpty(corporateInvoice.getSellerNo())) { + //如果没找到就退出。 + String sellerName = corporateInvoice.getSeller(); + log.info("sellerName =>{}", sellerName); + Map params = new HashMap<>(); + List supplierList = supplierMapper.selectCNCompanyTaxNoEmpty(params); + Supplier matchSupplier = runTextsText(supplierList, sellerName); + if (null != matchSupplier) { + matchSupplier.setTaxNo(corporateInvoice.getSellerNo()); + //如果找到并且供应商税号有值,那么供应商税号不动,发票上税号赋值为供应商税号。 + supplierMapper.updateByPrimaryKey(matchSupplier); + } + } + } + } + } + } + + @Transactional + public Map syncSupplierOrder(String htNo) { + return null; + } + + public void dealSimilarMaterial(SupplierOrder supplierOrder) { + // 添加判断是否新增相似物料 + // 1.查询Supplier_Order的物料描述+单价在(相同供应商)本收货表里有无重复,如果有重复执行2 (且不为相同的itemNo) + String orderName = supplierOrder.getGoods(); + BigDecimal orderPrice = supplierOrder.getUnitPrice(); + String orderItemNo = supplierOrder.getItemNo(); + String supplierCode = supplierOrder.getSupplierCode(); + //查询Supplier_Order的物料描述+单价在本收货表里有无重复 + Map queryMap = new HashMap<>(); + queryMap.put("orderName",orderName); + queryMap.put("orderPrice",orderPrice); + queryMap.put("supplierCode",supplierCode); + queryMap.put("orderItemNo",orderItemNo); + SupplierOrder similarOrder = supplierOrderMapper.selectSimilarOrder(queryMap); + if(null!=similarOrder){ + //2.取出收货表里物料描述+单价组合,去supplier_material define表(相同供应商ext01)里查询EXTO2(收货描述)和EXT03(单价)组合是否存在A + // 如果存在就查询该物料编码是否在supplier_materia_define的similar_item_no里, + // 如果在就不处理,如果不在就append。B如果没有这个组合就新增一行。 + SupplierMaterialDefine similarMaterial = supplierMaterialDefineMapper.selectSimilar(queryMap); + if(null!=similarMaterial){ + String similarItemNos = similarMaterial.getSimilarItemNo(); + if(similarItemNos.contains(orderItemNo)){ + + }else{ + similarItemNos = similarItemNos+","+orderItemNo; + similarMaterial.setSimilarItemNo(similarItemNos); + supplierMaterialDefineMapper.updateByPrimaryKeySelective(similarMaterial); + } + }else{ + // + similarMaterial = new SupplierMaterialDefine(); + similarMaterial.setExt01(supplierCode); + similarMaterial.setExt02(orderName); + similarMaterial.setExt03(orderPrice.toString()); + String similarItemNos = similarOrder.getItemNo()+","+orderItemNo; + similarMaterial.setSimilarItemNo(similarItemNos); + similarMaterial.setItemNo(orderItemNo); + similarMaterial.setItemType("0"); + supplierMaterialDefineMapper.insert(similarMaterial); + } + } + } + + @Override + @Async(value = "SystemPool") + public void updatePOAndHTBH(CorporateInvoice corporateInvoice) { + // 2025-05-20 现需要通过开关 判断是否执行原逻辑还是走新的合同编号和PO号逻辑。 + SysConfig ocrRemarkPoConfig = sysConfigMapper.selectByCode("OCR_REMARK"); + if (null == ocrRemarkPoConfig) { + log.warn("此处未配置PO提取模式,走OCR默认"); + } + if (null == ocrRemarkPoConfig || "ocr".equals(ocrRemarkPoConfig.getValue())) { + log.info("corporateInvoice.getInvoiceType()=>{}",corporateInvoice.getInvoiceType()); + log.info("corporateInvoice.getPo()=>{}",corporateInvoice.getPo()); +// if(1==corporateInvoice.getInvoiceType()&& org.apache.commons.lang3.StringUtils.isEmpty(corporateInvoice.getPo())){ +// return; +// } + log.info("ocr start to update PO ==================================="); + // 获取config 配置 提取规则 + SysConfig REMARK_PO_START_WITH_CONFIG = sysConfigMapper.selectByCode("REMARK_PO_START_WITH"); + if (null == REMARK_PO_START_WITH_CONFIG) { + log.warn("此处未配置PO提取开头字段,无法执行"); + return; + } + SysConfig REMARK_PO_LENGTH_CONFIG = sysConfigMapper.selectByCode("REMARK_PO_LENGTH"); + int poLength = 10; + if (null == REMARK_PO_LENGTH_CONFIG) { + log.warn("此处未配置PO提取长度限制,默认10"); + return; + } else { + poLength = Integer.valueOf(REMARK_PO_LENGTH_CONFIG.getValue()); + } + String startWithPO = REMARK_PO_START_WITH_CONFIG.getValue(); + NumberExtractorUtil extractor = new NumberExtractorUtil(Arrays.asList(startWithPO.split(",")), poLength); + // 2023-07-12 赋值 PO + // 规则 PO号位数 55\45\97开头+8位 \285开头+7位 (一共10位) 若存在多个PO号,返回的PO号之前用英文逗号隔开。 + // 如果重复需要去重 + // case PO在规格型号栏中 + String pId = corporateInvoice.getId(); +// List items = corporateInvoice.getItems(); + List items = corporateInvoiceItemsMapper.selectItemsByPid(pId); + StringBuilder poCodes = new StringBuilder(); + Map poCodesMap = new HashMap<>(); + + // case PO在发票明细的规格型号里 + // 优先 从发票明细的规格型号里 调用PO识别接口 返回PO 后拼接 + for (CorporateInvoiceItems item : items) { + + // 判断 item.specification 是否包含关键字 55 45 97 285 + String specification = item.getSpecification(); + if (null == specification) continue; + + // 上面的 硬代码改成配置项 写活 + // 调用丁晨的接口 + // 需要将 备注通过接口发送给 yzj的 PO识别接口 添加 需要以XX开头的参数 +// String returnPo = interfaceUtil.getPOFromRemark(sysConfigMapper,specification); + List resPo = extractor.extractNumbers(specification); + String returnPo = String.join(",", resPo); + log.info("corItems returnPo == {}", returnPo); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(returnPo)) { + if (null == poCodesMap.get(returnPo)) { + poCodesMap.put(returnPo, specification); + poCodes.append(returnPo).append(","); + // 同时需要插入 对账单表 + supplierStateService.insertCorporateInvoicePO(corporateInvoice, item, returnPo); + } + } + } + log.info("upload Async invoice PO==>{}", corporateInvoice.getPo()); + // case PO在备注栏中 + if (poCodesMap.isEmpty()) { + String remark = corporateInvoice.getRemark(); + log.info("corporateInvoice remark =====>{}", remark); + // 需要将 备注通过接口发送给 yzj的 PO识别接口 +// String PO = interfaceUtil.getPOFromRemark(sysConfigMapper, remark); + List resPo = extractor.extractNumbers(remark); + String returnPo = String.join(",", resPo); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(returnPo)) { + corporateInvoice.setPo(returnPo); + } + } else { + log.info("corporateInvoice else remark =====>{}", poCodesMap.toString()); + corporateInvoice.setPo(poCodes.toString().substring(0, poCodes.toString().length() - 1)); + } + log.info("upload Async invoice PO from remark==>{}", corporateInvoice.getPo()); + CorporateInvoice updatePO = new CorporateInvoice(); + updatePO.setId(corporateInvoice.getId()); + updatePO.setPo(corporateInvoice.getPo()); + updatePO.setExt08(corporateInvoice.getExt08()); +// updatePO.setExt08("2"); + corporateInvoiceMapper.updateByPrimaryKeySelective(updatePO); + } else { + String invoiceId = corporateInvoice.getId(); + // 如果ext02 是采购的合同号 。TM-开头 就调用 + // 添加配置开关进入振华合同号分支 + SysConfig ZHZG_CORINVOICE_HTNO_ON_CONFIG = sysConfigMapper.selectByCode("ZHZG_CORINVOICE_HTNO_ON"); + if (null == ZHZG_CORINVOICE_HTNO_ON_CONFIG) { + log.warn("系统未配置 ZHZG_CORINVOICE_HTNO_ON "); + } + boolean zhzgSupplierMatching = false; + if (null != ZHZG_CORINVOICE_HTNO_ON_CONFIG && "1".equals(ZHZG_CORINVOICE_HTNO_ON_CONFIG.getValue())) { + log.info("corporateInvoice.ext02 = >{}", corporateInvoice.getExt02()); + String htNo = corporateInvoice.getExt02(); + if (null != htNo && htNo.startsWith("TM-")) { + Map result = syncSupplierOrder(htNo); + + if ("true".equals(result.get("success"))) { + log.info("syncSupplierOrder success=>{}","true"); + String supplierCode = result.get("supplierCode"); + log.info("syncSupplierOrder supplierCode=>{}",supplierCode); + SupplierMatching exist = null; + log.info("syncSupplierOrder invoiceId=>{}",invoiceId); + exist = supplierMatchingMapper.selectByPrimaryKey(invoiceId); + log.info("syncSupplierOrder exist=>{}",exist); + + SupplierMatching supplierMatching = new SupplierMatching(); + supplierMatching.setOrderNo(result.get("message")); + supplierMatching.setInvoiceId(invoiceId); + supplierMatching.setOperationTime(new Date()); + if (null == exist) { + log.info("syncSupplierOrder insertSelective=>{}",JSONObject.toJSONString(supplierMatching)); + supplierMatchingMapper.insertSelective(supplierMatching); + } else { + log.info("syncSupplierOrder updateByPrimaryKey=>{}",JSONObject.toJSONString(supplierMatching)); + supplierMatchingMapper.updateByPrimaryKey(supplierMatching); + } + zhzgSupplierMatching = true; + if(null!=supplierCode){ + + supplierService.materialAutoMatching(invoiceId,supplierCode); + // 单位换算映射 + supplierService.syncUomFromMapping(invoiceId,supplierCode); + // 单位换算处理 + Supplier supplier = supplierMapper.selectByCode(supplierCode); + if(null!=supplier){ + RestResponse uomResponse = supplierService.updateUom(invoiceId, supplier.getTaxNo()); + }else{ + RestResponse uomResponse = supplierService.updateUom(invoiceId, supplierCode); + } + + log.info("{} 进入匹配===========》 {}",corporateInvoice.getNumber(),invoiceId); + RestResponse restResponse1 = supplierService.autoSmartMatching(invoiceId,supplierCode); + // 匹配完成 + // 是否自动审核 auto commit + SysConfig auto_commitConfig = sysConfigMapper.selectByCode("auto_commit"); + String aotuCommit = "0"; + if(null==auto_commitConfig){ + log.warn("未配置auto_commit "); + }else{ + aotuCommit = auto_commitConfig.getValue(); + } + if("1".equals(aotuCommit)){ + List ids = supplierOrderItemMatchingMapper.selectIdsByStatusAndInvoiceId(invoiceId,null); + if(!ids.isEmpty()){ + Response response2 = supplierService.completeMatching(ids, invoiceId); + } + } + // 自动 审核通过 + // 是否自动审核 auto commit + SysConfig autoApproveConfig = sysConfigMapper.selectByCode("auto_approve"); + String autoApprove = "0"; + if(null==autoApproveConfig){ + log.warn("未配置auto_approve "); + }else{ + autoApprove = autoApproveConfig.getValue(); + } + if("1".equals(autoApprove)){ + Response passReviewRes= supplierService.passReview(invoiceId,null); + } + } + } else { + TInterfaceLog tInterfaceLog = new TInterfaceLog(); + tInterfaceLog.setId(UUID.randomUUID().toString()); + tInterfaceLog.setCreateDate(new Date()); + tInterfaceLog.setDelFlag("0"); + tInterfaceLog.setInterfaceName("获取收货信息接口异常"); + tInterfaceLog.setSendMesg("发票【" + corporateInvoice.getNumber() + "】合同号【" + corporateInvoice.getExt02() + "】获取收货信息接口异常"); + interfaceLogMapper.insert(tInterfaceLog); + } + } else { + TInterfaceLog tInterfaceLog = new TInterfaceLog(); + tInterfaceLog.setId(UUID.randomUUID().toString()); + tInterfaceLog.setCreateDate(new Date()); + tInterfaceLog.setDelFlag("0"); + tInterfaceLog.setInterfaceName("获取收货信息接口异常"); + tInterfaceLog.setSendMesg("发票【" + corporateInvoice.getNumber() + "】合同号【" + corporateInvoice.getExt02() + "】未检测到合同号"); + interfaceLogMapper.insert(tInterfaceLog); + } + } + + SysConfig ndOcrBasePathConfig = sysConfigMapper.selectByCode("ND_OCR_BASE_PATH"); + // http://nd.fanhaninfo.test/api/server/nd/ + if (null == ndOcrBasePathConfig) { + log.error("未配置匹配模型地址"); + return; + } + //走新型的VL模型识别 + String interfaceListSql = "select id,interface_name interfaceName,nd_model_no ndModelNo from data_obj_interface where interface_name = 'domestic_inv_remark'"; + List> interfaceList = sysUserMapper.execSelectSql(interfaceListSql); + // http://nd.fanhaninfo.test/ + if (interfaceList.isEmpty()) { + log.error("domestic_inv_remark识别未配置匹配模型"); + return; + } + // 模型唯一标识 + String modeName = String.valueOf(interfaceList.get(0).get("ndModelNo")); + String fullApi = ndOcrBasePathConfig.getValue() + modeName; + log.info("fullApi=>{}", fullApi); + JSONObject asset = new JSONObject(); + JSONObject json_data = new JSONObject(); + json_data.put("content", corporateInvoice.getRemark()); + asset.put("type", "json"); + asset.put("json_data", json_data); + JSONObject body = new JSONObject(); + body.put("asset", asset); + Map paramBody = new HashMap(); + paramBody.put("body", body.toJSONString()); + log.info("json.toJSONString()=>{}", body.toJSONString()); + paramBody.put("Content-Type", "application/json"); + paramBody.put("Authorization", ""); + Map resultEntity = null; + try { + resultEntity = ruiZhenOCRService.billsCropFHByNd(fullApi, body); + } catch (Exception e) { + log.error(e.getMessage()); + e.printStackTrace(); + return; + } + JSONObject jsonDataResult = (JSONObject) resultEntity.get("result"); + List mappingList = null; + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable(modeName, "invoice"); + CorporateInvoice corporateInvoice1 = new CorporateInvoice(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = jsonDataResult.get(source); + ReflectionUtil.setFieldValue(corporateInvoice1, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable(modeName, "items"); + JSONArray itemArr = jsonDataResult.getJSONArray("items"); + String allPo = ""; + for (int i = 0; i < itemArr.size(); i++) { + JSONObject itemObject = itemArr.getJSONObject(i); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String ext01 = entity.getExt01(); + if ("1".equals(ext01)) { + // 表示需要append + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + String oldValue = ReflectionUtil.getFieldValue(corporateInvoice1, dest); + if (null == oldValue || "null".equals(oldValue)) { + oldValue = ""; + } + if (oldValue.startsWith(",")) { + oldValue = oldValue.substring(1); + } + allPo = oldValue + "," + sourceValue; + ReflectionUtil.setFieldValue(corporateInvoice1, dest, allPo); + } else { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + ReflectionUtil.setFieldValue(corporateInvoice1, dest, (null == sourceValue || "null".equals(sourceValue)) ? "" : String.valueOf(sourceValue)); + } + } + } + corporateInvoice1.setId(corporateInvoice.getId()); + String po = corporateInvoice1.getPo(); + if (null != po) { + if (po.trim().equals(",")) { + corporateInvoice1.setPo(""); + } + if (po.startsWith(",")) { + corporateInvoice1.setPo(po.substring(1)); + } + } + if (null == corporateInvoice1.getPo() || "null".equals(corporateInvoice1.getPo())) { + corporateInvoice1.setPo(""); + } + corporateInvoice1.setExt08(corporateInvoice.getExt08()); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice1); + + String sellerNo = corporateInvoice.getSellerNo(); + log.info("sellerNo=>{}", sellerNo); + List suppliers = supplierMapper.selectByTaxNo(sellerNo); + + if (!suppliers.isEmpty()) { + String supplierCode = suppliers.get(0).getCode(); + SupplierMatching exist = null; + exist = supplierMatchingMapper.selectByPrimaryKey(invoiceId); + log.info("supplierMatching exist=>{} ==invoiceId:=>{}", exist, invoiceId); + if(!zhzgSupplierMatching){ + if (null == exist) { + SupplierMatching supplierMatching = new SupplierMatching(); + supplierMatching.setInvoiceId(corporateInvoice.getId()); + supplierMatching.setSupplierCode(supplierCode); + supplierMatching.setOrderNo(corporateInvoice1.getPo()); + supplierMatching.setOperationTime(new Date()); + supplierMatchingMapper.insertSelective(supplierMatching); + } else { + SupplierMatching supplierMatching = new SupplierMatching(); + supplierMatching.setInvoiceId(corporateInvoice.getId()); + supplierMatching.setSupplierCode(supplierCode); + supplierMatching.setOrderNo(corporateInvoice1.getPo()); + supplierMatching.setOperationTime(new Date()); + supplierMatchingMapper.updateByPrimaryKeySelective(supplierMatching); + } + } + + } + + + + + List itemList = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + // 根据汇率重新计算item的单价 总价 difference + String hl = corporateInvoice1.getExt04(); + log.info("hl=>{}", hl); + BigDecimal hlDecimal = new BigDecimal("1"); + try { + if ("0".equals(hl)) { + hl = "1"; + } + hlDecimal = new BigDecimal(hl); + } catch (Exception e) { + e.printStackTrace(); + hl = "1"; + log.warn("ext04 不是汇率数字:{},无法计算item", hl); + } + + //判断po是一个还是多个 + // 如果返回的一个 同时插入item是ext01 + // 如果返回不止1个。 return + for (CorporateInvoiceItems corporateInvoiceItems : itemList) { + if (itemArr.size() == 1) { + corporateInvoiceItems.setExt01(allPo); + } + if (itemArr.size() == 0) { + // 如果获取不到 取items里的specification + // 根据 sys_config 添加PO样例 正则匹配 如果匹配则 更新到ext01上。 + String specification = corporateInvoiceItems.getSpecification(); + SysConfig poRegConfig = sysConfigMapper.selectByCode("PO_REGS"); + if (null != poRegConfig) { + String regsValue = poRegConfig.getValue(); + String regs[] = regsValue.split(";"); + for (String reg : regs) { + String regPo = StringUtils.getPOByReg(specification, reg); + if (null != regPo) { + corporateInvoiceItems.setExt01(regPo); + break; + } + } + } + + } + + boolean flag = false; + String price = corporateInvoiceItems.getPrice(); + String total = corporateInvoiceItems.getTotal(); + String difference = corporateInvoiceItems.getDifference(); + String tax = corporateInvoiceItems.getTax(); + String originPrice = corporateInvoiceItems.getOriginPrice(); + if (!price.equals(originPrice)) { + flag = true; + } + if (flag) { + // 单价已改变过1次 + } else { + if ("1".equals(hl)) { + + } else { + BigDecimal priceDecimal = new BigDecimal(price).divide(hlDecimal, 2, RoundingMode.HALF_UP); + corporateInvoiceItems.setPrice(priceDecimal.toString()); + BigDecimal totalDecimal = new BigDecimal(total).divide(hlDecimal, 2, RoundingMode.HALF_UP); + corporateInvoiceItems.setTotal(totalDecimal.toString()); + BigDecimal differenceDecimal = new BigDecimal(difference).divide(hlDecimal, 2, RoundingMode.HALF_UP); + corporateInvoiceItems.setDifference(differenceDecimal.toString()); + BigDecimal taxDecimal = new BigDecimal(tax).divide(hlDecimal, 2, RoundingMode.HALF_UP); + corporateInvoiceItems.setTax(taxDecimal.toString()); + String itemNo = corporateInvoiceItems.getItemNo(); + if (org.apache.commons.lang3.StringUtils.isEmpty(itemNo)) { + itemNo = ""; + } + String specification = corporateInvoiceItems.getSpecification().replace(price, priceDecimal.toString()); + corporateInvoiceItems.setSpecification(specification); + } + } + corporateInvoiceItemsMapper.updateByPrimaryKeySelective(corporateInvoiceItems); + } + + // 经过上述处理,添加根据发票 类型 服务发票=》 + 增加控制 发票明细合并 满足2way + // 开关放在外侧 + SysConfig mergeItemsConfig = sysConfigMapper.selectByCode("MERGE_CORPORATE_INVOICE_ITEMS_ON"); + if (null == mergeItemsConfig) { + log.warn("系统未配置 MERGE_CORPORATE_INVOICE_ITEMS_ON"); + } + if (null != mergeItemsConfig && "1".equals(mergeItemsConfig.getValue())) { + Integer invoiceType = corporateInvoice.getInvoiceType(); + if (1 == invoiceType) { + // 如果是 服务类型的 + // 统计所有明细价格total和单价price + List itemsList = corporateInvoiceItemsMapper.selectItemsByPid(invoiceId); + if (!itemsList.isEmpty()) { + BigDecimal totalSum = BigDecimal.ZERO; + BigDecimal quantitySum = BigDecimal.ZERO; + BigDecimal deductionAmountSum = BigDecimal.ZERO; + BigDecimal deductionTaxSum = BigDecimal.ZERO; + BigDecimal differenceSum = BigDecimal.ZERO; + BigDecimal taxSum = BigDecimal.ZERO; + CorporateInvoiceItems oneItem = itemsList.get(0); + for (CorporateInvoiceItems it : itemsList) { + String total = it.getTotal(); + totalSum = totalSum.add(org.apache.commons.lang3.StringUtils.isEmpty(total) ? BigDecimal.ZERO : new BigDecimal(total)); + String quantity = it.getQuantity(); + if ("0".equals(quantity.trim())) { + quantity = "1"; + } + quantitySum = quantitySum.add(org.apache.commons.lang3.StringUtils.isEmpty(quantity) ? BigDecimal.ONE : new BigDecimal(quantity)); + String deductionAmount = it.getDeductionAmount(); + deductionAmountSum = deductionAmountSum.add(org.apache.commons.lang3.StringUtils.isEmpty(deductionAmount) ? BigDecimal.ZERO : new BigDecimal(deductionAmount)); + String deductionTax = it.getDeductionTax(); + deductionTaxSum = deductionTaxSum.add(org.apache.commons.lang3.StringUtils.isEmpty(deductionTax) ? BigDecimal.ZERO : new BigDecimal(deductionTax)); + String tax = it.getTax(); + taxSum = taxSum.add(org.apache.commons.lang3.StringUtils.isEmpty(tax) ? BigDecimal.ZERO : new BigDecimal(tax)); + String difference = it.getDifference(); + differenceSum = differenceSum.add(org.apache.commons.lang3.StringUtils.isEmpty(difference) ? BigDecimal.ZERO : new BigDecimal(difference)); + corporateInvoiceItemsMapper.deleteByPrimaryKey(it.getId()); + + } + oneItem.setTotal(totalSum.toString()); + oneItem.setQuantity(quantitySum.toString()); + oneItem.setTax(taxSum.toString()); + oneItem.setPrice(totalSum.divide(quantitySum, 2, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); + oneItem.setDeductionAmount(deductionAmountSum.toString()); + oneItem.setDeductionTax(deductionTaxSum.toString()); + oneItem.setDifference(differenceSum.add(taxSum).toString()); + oneItem.setName("明细合并行"); + oneItem.setSpecification(""); + oneItem.setId(UUID.randomUUID().toString()); + log.info(JSON.toJSONString(oneItem)); + corporateInvoiceItemsMapper.insert(oneItem); + } + } + } + } + } + + @Override + public RestResponse exportInvoiceReport(Map params, HttpServletResponse response) { + response.reset(); + ServletOutputStream out = null; + int userId = (int) RequestSecurityPolicy.getUserId(); + SysUser user = sysUserMapper.selectByPrimaryKey(userId); + int orgId = user.getOrgId(); + SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(orgId); + String companyId = sysOrg.getCode(); + params.put("companyId", companyId); + + Object searchDateObj = params.get("searchDate"); + if (null == searchDateObj || org.apache.commons.lang3.StringUtils.isEmpty(String.valueOf(searchDateObj))) { + String searchDate = DateUtil.format(new Date(), "yyyy-MM-dd"); + params.put("searchDate", searchDate); + } + try { + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=uploadLogs.xlsx"); + out = response.getOutputStream(); + List list = corporateInvoiceMapper.selectUploadLog(params); +// List invoices = corporateInvoiceMapper.uploadLogList(params); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "上传日志") + .head(CorInvoiceUploadVo.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + //response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + @Override + public RestResponse exportByMultiNumber(Map params, HttpServletResponse response) { + ServletOutputStream out = null; + String numbers = String.valueOf(params.get("numbers")); + String[] arr = numbers.split(","); + params.put("numbers", arr); + try { + List list = corporateInvoiceMapper.listByNumbers(params); + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=report.xlsx"); + out = response.getOutputStream(); + EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX) + .sheet(0, "供应商发票") + .head(CorporateInvoice.class) + .doWrite(list); + out.flush(); + return null; + } catch (Exception e) { + response.reset(); + log.error(e.getMessage(), e); + response.setContentType(ContentEnctype.JSON); + return RestResponse.failure(e.getMessage()); + } finally { + IoUtil.close(out); + } + } + + /** + * @Desc 电子发票 + */ + public void pdfToImagesForElectronic(String oldName, String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType, Long scannerId, long logId) { + PDDocument readPdf = null; + try { + log.info("pdfPath>>>>>>>>>>>>>>>>>>>:{}", pdfPath); + log.info(" file size >>>>>>>>>>>>>>>>>>>:{}", new File(pdfPath).length()); + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + String savePath; + int width = 0; + int height = 0; + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; +// SysConfig publicMailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); +// SysConfig supplierAdmin = sysConfigMapper.selectByCode("Supplier_Admin"); +// owner = Integer.parseInt(supplierAdmin.getValue()); +// Integer orgId = Integer.parseInt(publicMailOrg.getValue()); + Integer orgId = null; + SysOrg sysOrg = sysOrgMapper.selectByCode(com); + if (null == sysOrg) { + SysConfig publicMailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + orgId = Integer.parseInt(publicMailOrg.getValue()); + } else { + orgId = sysOrg.getId(); + } + + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + // 统计各页宽度和高度 + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { +// String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; +// savePath = uploadPath + folder + fileName; + String interfaceStr = "RZ"; + BufferedImage bufferedImage = null; + SysConfig interfaceConfig = sysConfigMapper.selectByCode("OCR_INTERFACE"); + if (interfaceConfig != null) { + interfaceStr = interfaceConfig.getValue(); + } + if (interfaceStr.equals("FH")) { + // 如果是FH接口 + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + } else { + bufferedImage = pdfRenderer.renderImageWithDPI(i, 144); + } + + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + +// String key = folder + fileName; +// log.info("StorageCache >> {} >> {}", fileName, com); +// log.info("StorageCache >> {} >> {}", "Owner." + fileName, owner); +// log.info("StorageCache >> {} >> {}", "HashKey." + fileName, hashKey); +// log.info("StorageCache >> {} >> {}", "PdfUrl." + fileName, pdfPath); +// StorageCache.write(fileName, com, 1000 * 60 * 30); +// StorageCache.write("Owner." + fileName, owner, 1000 * 60 * 30); +// StorageCache.write("HashKey." + fileName, hashKey, 1000 * 60 * 30); +// StorageCache.write("CorType." + fileName, corporateInvoiceType, 1000 * 60 * 30); +// StorageCache.write("PdfUrl." + fileName, pdfPath, 1000 * 60 * 30); +// StorageCache.write("scannerLogs." + fileName, scannerId, 1000 * 60 * 30); +// ImageIO.write(bufferedImage, "JPG", new File(savePath)); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String fileLastPageName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + "_last.jpg"; + String jpgFileWholePage = uploadPath + folder + fileName; + String jpgFileLastPage = uploadPath + folder + fileLastPageName; + ImageIO.write(jpgImage, "JPG", new File(jpgFileWholePage)); + +// + // 2023-08-13 判断图片大小 超过3M就压缩 +// File destFile = new File(jpgFile); +// BigDecimal maxSize = new BigDecimal(destFile.length()); +// BigDecimal result = maxSize.divide(new BigDecimal(1024*1024),2,BigDecimal.ROUND_HALF_UP); +// while(result.compareTo(new BigDecimal(3))>0){ +// result = Pdf2JpgHelper.scaleJpg(destFile,0.75f,jpgFile); +// } + // 通过 HF AI 接口解析 形式发票 + RuiZhenOCREntity ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(pdfPath)); + if (null == ocrEntity || 0 == ocrEntity.getResult() || + ( org.apache.commons.lang3.StringUtils.isEmpty(ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber()) + ||org.apache.commons.lang3.StringUtils.isEmpty(ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getTotal()) + ||org.apache.commons.lang3.StringUtils.isEmpty(ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getDate()) + ) + ) { + + // 睿真方式处理 + // 20230629接口方式判断 + String interfaceStr = "RZ"; + SysConfig interfaceConfig = sysConfigMapper.selectByCode("OCR_INTERFACE"); + if (interfaceConfig != null) { + interfaceStr = interfaceConfig.getValue(); + log.info("OCR_INTERFACE=>{}", interfaceStr); + } + // pdf 获取最后一页的 + Pdf2JpgHelper.pdfLastPageToImage(pdfPath, jpgFileLastPage); + long oldLength; + long newLength; + //判断文件是否写入完成 + int delay = 3000; + do { + oldLength = new File(jpgFileLastPage).length(); + log.info("File Uploading11 >> {} : {}", jpgFileLastPage, oldLength); + ThreadUtil.sleep(delay); + newLength = new File(jpgFileLastPage).length(); + log.info("File Uploading22 >> {} : {}", jpgFileLastPage, newLength); + } while (oldLength != newLength || newLength == 0); + if (interfaceStr.equals("FH")) { + ocrEntity = ruiZhenOCRService.billsCropFH(Base64Util.fileToBase64(jpgFileLastPage)); + } else { + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(jpgFileLastPage)); + } + invoiceVAT(null, oldName, ocrEntity, 2, owner, orgId, folder, fileName, pdfPath, corporateInvoiceType, logId); + + } else { + invoiceVAT(null, oldName, ocrEntity, 2, owner, orgId, folder, fileName, pdfPath, corporateInvoiceType, logId); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + public JSONObject ndApiRequest(String ndSearchCode, File pdfFile,String isJapen) { + JSONObject jsonDataResult = null; + try { + //走新型的VL模型识别 + SysConfig ndOcrBasePathConfig = sysConfigMapper.selectByCode("ND_OCR_BASE_PATH"); + // http://nd.fanhaninfo.test/api/server/nd/ + if (null == ndOcrBasePathConfig) { + log.error("形式发票识别未配置匹配模型地址"); + return null; + } + String ndOcrBasePath = ndOcrBasePathConfig.getValue(); + //走新型的VL模型识别 + + String interfaceListSql = "select id,interface_name interfaceName,nd_model_no ndModelNo from data_obj_interface where interface_name = '" + ndSearchCode + "'"; + + List> interfaceList = sysUserMapper.execSelectSql(interfaceListSql); + // http://nd.fanhaninfo.test/ + if (interfaceList.isEmpty()) { + log.error("形式发票识别未配置匹配模型"); + return null; + } + // 模型唯一标识 + String ndOcrVLModelNo = String.valueOf(interfaceList.get(0).get("ndModelNo")); + String apiUrl = ndOcrBasePath + ndOcrVLModelNo; + if("_JP".equals(isJapen)){ + apiUrl=apiUrl+"_JP"; + } + + log.info("api_url:{}", apiUrl); + // + String base64 = Base64Util.fileToBase64(pdfFile); + + String fileName = pdfFile.getName(); + String title = ""; + if (fileName.toLowerCase().endsWith("pdf")) { + title = "application/pdf"; + } else { + title = "image/png"; + } + JSONObject body = new JSONObject(); + JSONObject asset = new JSONObject(); + asset.put("type", "file"); + asset.put("name", fileName); + asset.put("base64", "data:" + title + ";base64," + base64); + body.put("asset", asset); + Map resultEntity = ruiZhenOCRService.billsCropFHByNd(apiUrl, body); + jsonDataResult = (JSONObject) resultEntity.get("result"); + } catch (Exception e) { + log.error("nd api {} => error ={} ", ndSearchCode, e.getMessage()); + } + return jsonDataResult; + } + + public void ocrProformaFromNdApiHeadLine(String oldName, String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType, Long scannerId, long logId) { + File pdfFile = new File(pdfPath); + if (!pdfFile.exists()) { + log.warn("识别文件不存在:{}", pdfPath); + return; + } + try { + JSONObject jsonDataResult = ndApiRequest("proforma_invoice_head", pdfFile,null); + if (null == jsonDataResult) { + log.error("nd api response not setting or error"); + return; + } + List mappingList = null; + RuiZhenOCREntity ocrEntity = new RuiZhenOCREntity(); +// ocrEntity.getResponse().getData().getIdentify_results() + List identify_results = new ArrayList<>(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice_head", "invoice"); + Details corporateInvoice = new Details(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = jsonDataResult.get(source); + ReflectionUtil.setFieldValue(corporateInvoice, dest, String.valueOf((null == sourceValue ? "" : sourceValue))); + } + jsonDataResult = ndApiRequest("proforma_invoice_line", pdfFile,null); + if (null == jsonDataResult) { + log.error("nd api response not setting or error"); + return; + } + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice_line", "items"); + List itemList = new ArrayList<>(); + JSONArray itemArr = jsonDataResult.getJSONArray("items"); + for (int i = 0; i < itemArr.size(); i++) { + JSONObject itemObject = itemArr.getJSONObject(i); + Item corporateInvoiceItems = new Item(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + ReflectionUtil.setFieldValue(corporateInvoiceItems, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + itemList.add(corporateInvoiceItems); + } +// corporateInvoice.setCode("60100"); + corporateInvoice.setItems(itemList); + identifyResults.setDetails(corporateInvoice); + identifyResults.setType("60100"); + identify_results.add(identifyResults); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(identify_results); + response.setData(ocrData); + ocrEntity.setResponse(response); + SysOrg sysOrg = sysOrgMapper.selectByCode(com); + Integer orgId = Optional.ofNullable(sysOrg.getId()).orElse(0); + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + if (generateFolder) { + folder = generateFolder(imagePath); + } + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileName2; + ImageIO.write(jpgImage, "JPG", new File(jpgFile)); + invoiceVAT(null, oldName, ocrEntity, 1, owner, orgId, folder, fileName2, pdfPath, corporateInvoiceType, logId); + } catch (Exception e) { + log.error("nd ocr err:{}", e.getMessage()); + e.printStackTrace(); + } + + } + + + public void ocrProformaFromNdApi(String originFilePath, String oldName, String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType, Long scannerId, long logId,String isJapen) { + File pdfFile = new File(pdfPath); + if (!pdfFile.exists()) { + log.warn("识别文件不存在:{}", pdfPath); + return; + } + + try { + JSONObject jsonDataResult = ndApiRequest("proforma_invoice", pdfFile,isJapen); + if (null == jsonDataResult) { + log.error("nd api response not setting or error"); + return; + } + List mappingList = null; + RuiZhenOCREntity ocrEntity = new RuiZhenOCREntity(); +// ocrEntity.getResponse().getData().getIdentify_results() + List identify_results = new ArrayList<>(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice", "invoice"); + Details corporateInvoice = new Details(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = jsonDataResult.get(source); + ReflectionUtil.setFieldValue(corporateInvoice, dest, String.valueOf((null == sourceValue ? "" : sourceValue))); + } + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice", "items"); + List itemList = new ArrayList<>(); + JSONArray itemArr = jsonDataResult.getJSONArray("items"); + for (int i = 0; i < itemArr.size(); i++) { + JSONObject itemObject = itemArr.getJSONObject(i); + Item corporateInvoiceItems = new Item(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + ReflectionUtil.setFieldValue(corporateInvoiceItems, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + itemList.add(corporateInvoiceItems); + } +// corporateInvoice.setCode("60100"); + corporateInvoice.setItems(itemList); + identifyResults.setDetails(corporateInvoice); + identifyResults.setType("60100"); + identify_results.add(identifyResults); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(identify_results); + response.setData(ocrData); + ocrEntity.setResponse(response); + SysOrg sysOrg = sysOrgMapper.selectByCode(com); + Integer orgId = Optional.ofNullable(sysOrg.getId()).orElse(0); + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + if (generateFolder) { + folder = generateFolder(imagePath); + } + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileName2; + ImageIO.write(jpgImage, "JPG", new File(jpgFile)); + invoiceVAT(originFilePath, oldName, ocrEntity, 1, owner, orgId, folder, fileName2, pdfPath, corporateInvoiceType, logId); + } catch (Exception e) { + log.error("nd ocr err:{}", e.getMessage()); + e.printStackTrace(); + } + } + + /** + * @param hashKey + * @param pdfPath + * @param imagePath + * @param generateFolder + * @param com + * @param owner + * @param corporateInvoiceType + * @param scannerId + * @param logId + * @Desc 形式发票 + */ + public void pdfToImagesForProforma(String oldName, String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType, Long scannerId, long logId) { + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + // 2023-07-17 + // 只取第一页作为预览的效果 img_url + // 改为拼接所有图片作为预览 供 xml发送附件 + // 统计各页宽度和高度 + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileName; + ImageIO.write(jpgImage, "JPG", new File(jpgFile)); + +// String key = folder + fileName; + log.info("StorageCache >> {} >> {}", fileName, com); + log.info("StorageCache >> {} >> {}", "Owner." + fileName, owner); + log.info("StorageCache >> {} >> {}", "HashKey." + fileName, hashKey); + log.info("StorageCache >> {} >> {}", "PdfUrl." + fileName, pdfPath); + StorageCache.write(fileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + fileName, owner, 1000 * 60 * 30); + StorageCache.write("HashKey." + fileName, hashKey, 1000 * 60 * 30); + StorageCache.write("CorType." + fileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + fileName, pdfPath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + fileName, scannerId, 1000 * 60 * 30); + SysOrg sysOrg = sysOrgMapper.selectByCode(com); + Integer orgId = Optional.ofNullable(sysOrg.getId()).orElse(0); +// Integer orgId = 0; + // 通过 HF AI 接口解析 形式发票 + RuiZhenOCREntity ocrEntity = ruiZhenOCRService.billsCropFHOfProforma(Base64Util.fileToBase64(pdfPath)); + invoiceVAT(null, oldName, ocrEntity, 1, owner, orgId, folder, fileName, pdfPath, corporateInvoiceType, logId); + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + // @Transactional + public void invoiceVAT(String originFilePath, String oldName, RuiZhenOCREntity ocrEntity, int invoiceType, int owner, + int orgId, String folder, String fileName, String pdfPath, CorporateInvoiceType corporateInvoiceType, long logId) { + if(null==ocrEntity){ + log.error("OCR 识别错误 originFilePath:{}",originFilePath); + return; + } + List identify_results = ocrEntity.getResponse().getData().getIdentify_results(); + Object poObject = ocrEntity.getResultPO(); + + + SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(orgId); + SysConfig specAddPriceConfig = sysConfigMapper.selectByCode("addition_spec"); + String specAddPrice = specAddPriceConfig == null ? "0" : specAddPriceConfig.getValue(); + for (RuiZhenOCREntity.IdentifyResults result : identify_results) { + try { + // 2025-07-23 新增。 识别结束后 如果根据发票号码 在异常中存在此发票。则将 异常发票删除。 + String invoiceNum = result.getDetails().getNumber(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(invoiceNum)) { + List oldInvoices = corporateInvoiceMapper.selectByNumberAndStatus(invoiceNum, "2"); + for (CorporateInvoice oldInvoice : oldInvoices) { + //删除 items + corporateInvoiceItemsMapper.deleteByPid(oldInvoice.getId()); + corporateInvoiceMapper.deleteByPrimaryKey(oldInvoice.getId()); + } + } +// List exFields1 = expenseTypeActiveService.selectExFields(1, 4); +// for (ExpenseTypeActive expenseTypeActive : exFields1) { +// if ("PurType".equals(expenseTypeActive.getSelectName())) { +// expenseTypeActive.setDefaultValue(corporateInvoiceType.getCode()); +// } else if ("PayCom".equalsIgnoreCase(expenseTypeActive.getSelectName())) { +// expenseTypeActive.setDefaultValue(sysOrg.getCode()); +// } +// } +// String exFieldsString1 = JsonUtil.toString(exFields1); + String uuid = StringUtil.UUID(); + Details details = result.getDetails(); + CorporateInvoice corporateInvoice = new CorporateInvoice(); + corporateInvoice.setId(uuid); + corporateInvoice.setOwner(owner); +// corporateInvoice.setExtraFields(exFieldsString1); + corporateInvoice.setOrgId(orgId); + corporateInvoice.setTitle(details.getSeller()); + corporateInvoice.setSeller(details.getSeller()); + corporateInvoice.setSellerNo(details.getSeller_tax_id()); + + + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt03())) { + corporateInvoice.setExt03(details.getExt03()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt04())) { + corporateInvoice.setExt04(details.getExt04()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt05())) { + corporateInvoice.setExt05(details.getExt05()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt06())) { + corporateInvoice.setExt06(details.getExt06()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt07())) { + corporateInvoice.setExt07(details.getExt07()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt09())) { + corporateInvoice.setExt09(details.getExt09()); + } + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt10())) { + corporateInvoice.setExt10(details.getExt10()); + } + + if (null == details.getCode() || "".equals(details.getCode())) { + corporateInvoice.setCode("0000"); + } else { + corporateInvoice.setCode(details.getCode()); + } + corporateInvoice.setNumber(details.getNumber()); + + + String dateStr = details.getDate(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(dateStr)) { + dateStr = dateStr.replace(" ", ""); + } + String formatDate = dateFormatExchange(dateStr); + corporateInvoice.setDate(formatDate); + + corporateInvoice.setTotal(details.getTotal().replace(" ", "")); + // 单独处理 + + String jpgViewPath = viewPath + folder + fileName; + log.info("jpgViewPath=>{}", jpgViewPath); + corporateInvoice.setImgPath(jpgViewPath); + corporateInvoice.setRemark(details.getRemark()); + +// corporateInvoice.setExtraFields(exFieldsString1); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(details.getBuyer()); + corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + corporateInvoice.setTicketCode(result.getType()); + corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(0); + // 修改原始文件路径20221018xp + PostBox query = new PostBox(); + query.setInvoiceNum(details.getNumber()); + // originFileName + // pdfPath = absolute路径 + // 需要切割 成viewPath + 路径 + String indexOfPath = "/opt"; + if (pdfPath.contains("/opt")) { + String filePath = pdfPath.substring(pdfPath.indexOf(indexOfPath)); + String originFileNamePath = viewPath + filePath; + log.info("originFileNamePath=>{}", originFileNamePath); + corporateInvoice.setOriginalFilePath(originFileNamePath); + } + + corporateInvoice.setVerifiedCode(details.getCheck_code()); + + if (null == details.getPretax_amount()) { + corporateInvoice.setPretaxAmount("0"); + } else { + corporateInvoice.setPretaxAmount(details.getPretax_amount()); + } + corporateInvoice.setTax(null == details.getTax() ? "0" : details.getTax().replace(" ", "")); + if (1 != invoiceType) { + // 税前金额 net amount 为0去totoal -tax + String pretaxAmount = corporateInvoice.getPretaxAmount(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(pretaxAmount)) { + BigDecimal pretaxAmountDecimal = new BigDecimal(pretaxAmount.replace(" ", "")); + if (pretaxAmountDecimal.compareTo(BigDecimal.ZERO) == 0) { + BigDecimal totalDecimal = new BigDecimal(corporateInvoice.getTotal().replace(" ", "")); + + if (org.apache.commons.lang3.StringUtils.isNotEmpty(corporateInvoice.getTax())) { + BigDecimal taxDecimal = new BigDecimal(corporateInvoice.getTax().replace(" ", "")); + corporateInvoice.setPretaxAmount(totalDecimal.subtract(taxDecimal).toString()); + } else { + corporateInvoice.setPretaxAmount(totalDecimal.toString()); + } + } + } + } + + corporateInvoice.setOperatorId(owner); + corporateInvoice.setCreateDate(new Date()); + String currency = details.getTitle(); + // 电子票和 纸票结果 共用了 title但是含义不一致 + + if (org.apache.commons.lang3.StringUtils.isEmpty(currency)) { + currency = "CNY"; + } else { + if (currency.startsWith("电子")) { + currency = details.getCurrency_code(); + }else{ + currency = "CNY"; + } + } + + corporateInvoice.setCurrency(currency); + corporateInvoice.setChecked(0); + corporateInvoice.setPo(details.getPo()); + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + corporateInvoice.setDetails(details.getItem_names()); + corporateInvoice.setInvoiceType(corporateInvoiceType.getId()); + + corporateInvoice.setIsSend(0); + corporateInvoice.setUseStatus(9); + corporateInvoice.setMatchStatus(0); + //增加保存字段 2022/8/16 + corporateInvoice.setNumberBackup(details.getNumberBackup()); + corporateInvoice.setNumberConfirm(details.getNumber_confirm()); + corporateInvoice.setCompanySeal(details.getCompany_seal()); + // 验真 + if (1 != invoiceType) { + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + } else { + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if (null == ext08Config) { + corporateInvoice.setExt08("2"); + } else { + corporateInvoice.setExt08(ext08Config.getValue()); + } + // 是否需要将原始PDF 上传为附件 + SysConfig needOriginPdf = sysConfigMapper.selectByCode("NEED_ORIGIN_PDF_FJ"); + if (null != needOriginPdf && "1".equals(needOriginPdf.getValue())) { + if (org.apache.commons.lang3.StringUtils.isNotEmpty(originFilePath)) { + log.info("pdfPath===>{}", originFilePath); + File origin = new File(originFilePath); + log.info("origin exist =>{}", origin.exists()); + int lastFlag = viewPath.lastIndexOf("/"); + com.cmsen.ticket.domain.entity.File fpqd = new com.cmsen.ticket.domain.entity.File(); + fpqd.setUploadTime(new Date()); + fpqd.setDescription(""); + fpqd.setPath(originFilePath); + fpqd.setPid(corporateInvoice.getId()); + fpqd.setType("其他"); + fpqd.setUri(viewPath + originFilePath.replace(uploadPath, "").replace("\\", "/")); + fileMapper.insert(fpqd); + } + } + } + if (null != oldName) { + if (oldName.startsWith("PSP-") || oldName.startsWith("STO-")) { + String htNo = "TM-" + oldName; + if(htNo.contains(".")){ + int dotIndex = htNo.indexOf("."); + htNo = htNo.substring(0,dotIndex); + } + corporateInvoice.setExt02(htNo); + corporateInvoice.setRemark(htNo + corporateInvoice.getRemark()); + } + } else { + if (org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt02())) { + corporateInvoice.setExt02(details.getExt02()); + } + } + if (2 == corporateInvoiceType.getId()) { + corporateInvoice.setMatchType(1); + corporateInvoice.setPriceType(0); + } else { + corporateInvoice.setMatchType(0); + corporateInvoice.setPriceType(1); + } + //如果preamout=null或是空串 则 将total赋值给pretaxamount + if (org.apache.commons.lang3.StringUtils.isEmpty(corporateInvoice.getPretaxAmount())) { + corporateInvoice.setPretaxAmount(corporateInvoice.getTotal()); + } + // + log.info("corporateInvoice message==={}", corporateInvoice.getMessage()); + + + // 形式发票 通过供应商名称去查询供应商税号 填写到 发票的 供应商的税号上。 + if (1 == invoiceType) { + String sellerName = corporateInvoice.getTitle().replace("(","(").replace(")",")"); + Supplier supplier = supplierMapper.selectByName(sellerName); + if (null != supplier) { + if (null == supplier.getTaxNo() || "".equals(supplier.getTaxNo())) { + corporateInvoice.setSellerNo(supplier.getCode()); + } else { + corporateInvoice.setSellerNo(supplier.getTaxNo()); + } + } + String po = ""; + if (null != poObject) { + po = ocrEntity.getResultPO().getPO_code().getResult(); + if (null == po) { + po = ""; + } + + corporateInvoice.setPo(po); + } + } + // 回写scannerLogs + if (0 != logId) { + corporateInvoice.setExt01(String.valueOf(logId)); + } + + // 发票日期+发票号后8位+供应商名称 + String sufix = pdfPath.substring(pdfPath.lastIndexOf(".")); + String number = corporateInvoice.getNumber(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(number) && number.length() >= 8) { + number = number.substring(number.length() - 8); + } + + String yearMonthDate = corporateInvoice.getDate(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(yearMonthDate)) { + yearMonthDate = yearMonthDate.replace("年", ""); + yearMonthDate = yearMonthDate.replace("月", ""); + yearMonthDate = yearMonthDate.replace("日", ""); + } + + //2023-08-13 根据系统配置 采用公司的中文和英文code名称 + String comName = null; + SysConfig imgVendorName = sysConfigMapper.selectByCode("img_vendor_name"); + if (null != imgVendorName) { + String imgVendorNameValue = imgVendorName.getValue(); + if (null != imgVendorNameValue && "code".equals(imgVendorNameValue)) { + List suppliers = supplierMapper.selectByTaxNo(corporateInvoice.getSellerNo()); + if (!suppliers.isEmpty()) { + comName = suppliers.get(0).getCode(); + } else { + comName = ""; + } + } + } + if (null == comName) { + comName = corporateInvoice.getSeller(); + } + String randomId = UUID.randomUUID().toString().substring(0, 2); + String newOriginFileName = yearMonthDate + number + comName + randomId + sufix; +// String urlNewOriginFileName = URLEncoder.encode(newOriginFileName); + + String oldFileUploadPath = pdfPath; + String parentPath = oldFileUploadPath.substring(0, oldFileUploadPath.lastIndexOf(File.separator)); + + if (parentPath.endsWith(File.separator)) { + + } else { + parentPath = parentPath + File.separator; + } + + log.info("pdfPath===================>{}", pdfPath); + File oldFile = new File(pdfPath); + // 先重命名 + boolean flag = oldFile.renameTo(new File(parentPath + File.separator + newOriginFileName)); + // 不成功则复制 删除源文件 + if (!flag) { + log.info("flag=======>{}", flag); + try { + FileUtils.copyFile(oldFile, new File(parentPath + File.separator + newOriginFileName)); + // 成功后删除 + oldFile.delete(); + flag = true; + } catch (Exception e) { + log.error("copy file error!"); + e.printStackTrace(); + } + } + + // originalPath 是 + String originalPath = corporateInvoice.getOriginalFilePath(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPath)) { + String originalParent = originalPath.substring(0, originalPath.lastIndexOf("/")); + if (!originalParent.endsWith("/")) { + originalParent = originalParent + "/"; + } + String newOFP = originalParent + newOriginFileName; + corporateInvoice.setOriginalFilePath(newOFP); + } + // 形式发票不需要设置 + + // 2023-07-21 设置标签编码 +// corporateInvoice.setExt06(""); + // 2023-08-01 设置 +// boolean redFlag = ocrEntity.getResultFld().getStampcolor().isStampRed(); +// corporateInvoice.setExt07(String.valueOf(redFlag)); + + + +// corporateInvoiceMapper.insert(corporateInvoice); + List corporateInvoiceItems = new ArrayList<>(); + if (1 == invoiceType) { + + List detailItems = details.getItems(); + if (detailItems != null && !detailItems.isEmpty()) { + for (Item item : detailItems) { + //2022/8/16 + if (item.getName().contains("合计") || item.getName().contains("销货清单")) { + continue; + } + if (item.getTotal().contains("-")) { + if (corporateInvoiceItems.size() > 0) { + CorporateInvoiceItems corporateInvoiceItems1 = corporateInvoiceItems.get(corporateInvoiceItems.size() - 1); + corporateInvoiceItems1.setDeductionAmount(item.getTotal()); + corporateInvoiceItems1.setDeductionTaxRate(item.getTax_rate()); + corporateInvoiceItems1.setDeductionTax(item.getTax()); + // 添加差异计算20220620 + BigDecimal total = new BigDecimal(corporateInvoiceItems1.getTotal()); + BigDecimal deductionAmount = new BigDecimal(item.getTotal()); + corporateInvoiceItems1.setDifference(total.add(deductionAmount).toString()); + } else { + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(corporateInvoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setDeductionAmount(item.getTotal()); + setDeductionTax(item.getTax()); + setDeductionTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(getOriginUnit()); + setOriginPrice(item.getPrice()); + setItemNo(item.getItemNo()); + }}); + } + } else { + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(corporateInvoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + setTax(item.getTax()); + setTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(item.getUnit()); + setOriginPrice(item.getPrice()); + setDifference(item.getTotal()); + setItemNo(item.getItemNo()); + }}); + } + } + } + } else { + corporateInvoiceItems = corporateInvoice.getItems(); + } + + for (CorporateInvoiceItems item2 : corporateInvoiceItems) { + String itemId = UUID.randomUUID().toString(); + item2.setPid(corporateInvoice.getId()); + item2.setId(itemId); + String name = item2.getName(); + if ("1".equals(specAddPrice)) { + log.info("specAddPrice:=>{}", specAddPrice); + log.info("item2.getSpecification():=>{}", item2.getSpecification()); + String unitPrice = new BigDecimal(item2.getPrice()).setScale(2, RoundingMode.HALF_UP).toString(); + String itemNo = item2.getItemNo(); + if (org.apache.commons.lang3.StringUtils.isEmpty(itemNo)) { + itemNo = ""; + } + if(null==item2.getSpecification()){ + item2.setSpecification(itemNo + PRICE_CN_NAME + unitPrice); + }else{ + if(item2.getSpecification().indexOf(itemNo)>-1){ + item2.setSpecification(itemNo + PRICE_CN_NAME + unitPrice); + }else{ + item2.setSpecification(itemNo + PRICE_CN_NAME + unitPrice + " " + item2.getSpecification()); + } + } + + } + + if (null != name && name.length() > 500) { + item2.setName(name.substring(0, 499)); + } + String itemTax = item2.getTax(); + if (org.apache.commons.lang3.StringUtils.isEmpty(itemTax)) { + item2.setTax("0"); + } + corporateInvoiceItemsMapper.insert(item2); + } + + corporateInvoiceMapper.insert(corporateInvoice); + + log.info("corporateInvoiceMapper.insert >>>{}", "新增结束"); + // 这里存在事务 问题 新增后 会进入待处理 但是如果规则校验出错,则会更新到异常。此处会有时间差 但是事务注解最开始有 后面删掉了。 + + // 如果验真没问题则进行规则校验 + if (corporateInvoice.getStatus().equals(0)) { + // 此处为异步更新 start + updatePOAndHTBH(corporateInvoice); + updateSellerAndBuyerNo(invoiceType, corporateInvoice); + // 此处为异步更新 end + StringBuilder message = new StringBuilder(); + TicketType ticketType = ticketTypeMapper.selectByCode(corporateInvoice.getTicketCode()); + log.info("corporateInvoice status ====>{}", corporateInvoice.getStatus()); + corporateInvoiceService.validationRules(corporateInvoice, message, ticketType); + log.info("===corporateInvoice1.getStatus()2:{}", corporateInvoice.getStatus()); + corporateInvoice.setMessage(message.toString()); + if (corporateInvoice.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType2 = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType2 != null && corporateInvoiceType2.getSendType() == 1) { + supplierOutService.sendInvoice(corporateInvoice, applicationName, "0"); + } + } + // 更新规则校验状态 + CorporateInvoice ruleCorporateInvoice = new CorporateInvoice(); + CorporateInvoice nowRuleCorporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if (null == ext08Config) { + nowRuleCorporateInvoice.setExt08("2"); + } else { + nowRuleCorporateInvoice.setExt08(ext08Config.getValue()); + } + ruleCorporateInvoice.setId(nowRuleCorporateInvoice.getId()); + ruleCorporateInvoice.setStatus(corporateInvoice.getStatus()); + ruleCorporateInvoice.setMessage(corporateInvoice.getMessage()); + ruleCorporateInvoice.setIsSend(nowRuleCorporateInvoice.getIsSend()); + ruleCorporateInvoice.setUseStatus(corporateInvoice.getUseStatus()); + ruleCorporateInvoice.setExt08(nowRuleCorporateInvoice.getExt08()); + corporateInvoiceMapper.updateByPrimaryKeySelective(ruleCorporateInvoice); + } + } catch (Exception e) { + log.error("发票保存异常====》{}", e.getMessage()); + e.printStackTrace(); + } + } + } + + private String dateFormatExchange(String dateStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH); + Date source = sdf.parse(dateStr); + SimpleDateFormat sdfDest = new SimpleDateFormat("yyyy年MM月dd日"); + String dest = sdfDest.format(source); + return dest; + } catch (Exception e) { + log.error(e.getMessage()); + } + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + Date source = sdf.parse(dateStr); + SimpleDateFormat sdfDest = new SimpleDateFormat("yyyy年MM月dd日"); + String dest = sdfDest.format(source); + return dest; + } catch (Exception e) { + log.error(e.getMessage()); + } + return dateStr; + } + + @Override + public RestResponse importAdvanceOfPayment(MultipartFile file) { + log.info("========================= importAdvanceOfPayment ============================"); +// String fileName = "D:\\testExcel.xlsx"; + try { + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); +// List companyList= companyMapper.queryAll(null); +// List supplierList = supplierService.listAll(); + +// Map companies = companyList.stream().collect(Collectors.toMap(Company::getName, Company::getCompanyCode)); +// Map suppliers = supplierList.stream().collect(Collectors.toMap(Supplier::getName, Supplier::getCode)); + + Long userId = RequestSecurityPolicy.getUserId(); + SysUser user = sysUserMapper.selectByPrimaryKey(userId.intValue()); + int orgId = user.getOrgId(); +// int orgId = 1; +// Long userId = 1L; + List insertList = new ArrayList<>(); + Map exist = new HashMap<>(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < sheetRowData.size(); i++) { + Map cell = sheetRowData.get(i); + String buyer = cell.get(0); + String seller = cell.get(1); + String number = cell.get(3); + String date = cell.get(4); + String pretaxAmount = cell.get(5); + String tax = cell.get(6); + String total = cell.get(7); + String po = cell.get(8); +// String taxNo = cell.get(9); + String currency = cell.get(11); + if (StringUtil.isEmpty(buyer) + || StringUtil.isEmpty(seller) + || StringUtil.isEmpty(number) + || StringUtil.isEmpty(date) + || StringUtil.isEmpty(pretaxAmount) +// ||StringUtil.isEmpty(tax) + || StringUtil.isEmpty(total) + || StringUtil.isEmpty(po) +// || StringUtil.isEmpty(taxNo) + ) { + sb.append("第" + (i + 1) + "行存在空值;【" + number + "】"); + continue; + } + + // 通过 seller 到supplier中查找 taxNo + Supplier supplier = supplierMapper.selectByName(seller); + String taxNo = null; + if (null == supplier) { + taxNo = seller; + supplier = new Supplier(); + supplier.setCode(""); + supplier.setTaxNo(seller); + supplier.setName(seller); + supplier.setStatus(1); + supplier.setSupplierSpecial(false); + supplierMapper.insert(supplier); + } else { + taxNo = supplier.getTaxNo(); + } + CorporateInvoice state = new CorporateInvoice() {{ + setId(StringUtil.UUID()); + setBuyer(cell.get(0)); + setSeller(cell.get(1)); + setTicketCode("30101"); + setNumber(cell.get(3)); + setDate(cell.get(4)); + setPretaxAmount(null == cell.get(5) ? "" : cell.get(5).replace(",", "")); + setTax(null == cell.get(6) ? "" : cell.get(6).replace(",", "").replace(",", "")); + setTotal(null == cell.get(7) ? "" : cell.get(7).replace(",", "")); + setPo(cell.get(8)); + setCurrency("CNY"); + setChecked(0); + setValidStatus((byte) 1); + setValidCount(0); + setValidDayCount(0); + setMatchStatus(0); + //corporateInvoice.setInvoiceType(); + setIsSend(0); + setOrgId(orgId); + setStatus(0); + setCreateDate(new Date()); + setOperatorId(userId.intValue()); + }}; + if (!org.apache.commons.lang3.StringUtils.isEmpty(currency)) { + state.setCurrency(currency); + } + state.setSellerNo(taxNo); + + if (null == exist.get(number)) { + insertList.add(state); + exist.put(number, 1); + // 判断是否数据库表中number重复 + List list = corporateInvoiceMapper.selectByInvoiceNumber(number); + if (list.isEmpty()) { + + } else { +// state.setStatus(2); + sb.append("第" + (i + 1) + "行,在数据表中 发票号码已重复!【" + number + "】"); + continue; +// tableFlag = true; +// sb.append(number+"数据表中 发票号码重复;"); + } + } else { + sb.append("文件内 第" + (i + 1) + "行,发票号码重复;【" + number + "】"); + continue; + } + } +// if(flag||tableFlag){ + if (sb.toString().length() > 0) { + // 校验重复 + return RestResponse.failure(sb.toString()); + } + insertIntoCorInvoices(insertList); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("先款后票数据导入失败"); + } + } + + @Async(value = "SystemPool") + public void insertIntoCorInvoices(List insertList) { + List list = null; + // 如果已存在 + for (CorporateInvoice corporateInvoice : insertList) { + corporateInvoiceMapper.insert(corporateInvoice); + } + } + + @Override + public RestResponse pushListUpload(MultipartFile file) { + log.info("========================= pushListUpload ============================"); + try { + StringBuffer sb = new StringBuffer(); + InputStream inputStream = file.getInputStream(); + List> sheetRowData = EasyExcel.read(inputStream).sheet(0).doReadSync(); + Long userId = RequestSecurityPolicy.getUserId(); + SysUser user = sysUserMapper.selectByPrimaryKey(userId.intValue()); + int orgId = user.getOrgId(); +// int orgId = 1; +// Long userId = 1L; + List pushList = new ArrayList<>(); + Map> exist = new HashMap<>(); + boolean flag = false; + for (int i = 0; i < sheetRowData.size(); i++) { + Map cell = sheetRowData.get(i); + String number = cell.get(0); + String buyer = cell.get(1); + String seller = cell.get(2); + String pretaxAmount = cell.get(3); + if (StringUtil.isEmpty(number) +// ||StringUtil.isEmpty(seller) +// ||StringUtil.isEmpty(buyer) +// ||StringUtil.isEmpty(pretaxAmount) + ) { + flag = true; + sb.append("第" + (i + 1) + "行发票号码存在空值;"); + continue; + } + if (null == exist.get(number)) { + pushList.add(number); + Map map = new HashMap<>(); + map.put("number", number); + map.put("buyer", buyer); + map.put("seller", seller); + map.put("pretaxAmount", pretaxAmount); + exist.put(number, map); + } else { + flag = true; + sb.append("文件内 第" + (i + 1) + "行,重复号码;【" + number + "】"); + } + } + if (flag) { + // 校验重复 + return RestResponse.failure(sb.toString()); + } + // 处理 ext08字段 + if (pushList.isEmpty()) { + return RestResponse.failure("无可发送数据"); + } else { + // 先判断数据是否可推送 + // CompanyCode、PONumber、VendorID、VendorName1、CostCentre、RequestersName、 + // Line、Description、MaterialNo、Qty、UnitPrice、Discount、Tota1、UofM + for (String s : pushList) { + Map map = exist.get(s); + List invoices = corporateInvoiceMapper.selectByMap(map); + boolean flag1 = false; + for (CorporateInvoice invoice : invoices) { + Integer isSend = invoice.getIsSend(); + if (1 == isSend) { + flag1 = true; + } + } + if (flag1) { + sb.append("【" + s + "】发票已发送;"); + } else { + if (!invoices.isEmpty()) { + corporateInvoiceMapper.updateExt08(invoices.get(0).getId()); + } else { + sb.append("【" + s + "】缺少匹配发票数据;"); + } + } + } + if (sb.toString().length() > 0) { + return RestResponse.failure(sb.toString()); + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("接口清单数据导入失败"); + } + } + + @Override + public RestResponse pushKofox(String invoiceId) { +// String id = corporateInvoiceMapper.selectKofoxInvoiceId(invoiceId); +// if(null==id){ +// return RestResponse.failure("发票号码:【"+invoiceId+"】,存在非必填数据为空"); +// }else{ + corporateInvoiceMapper.updateExt08(invoiceId); +// } + return RestResponse.success(); + } + + @Override + public JSONObject ncImport(List fileVoList) { + + log.info("fileVoList size=>{}",fileVoList.size()); + String baseActionUrl = "http://nd.fanhaninfo.test/"; + SysConfig actionUrlConfig = sysConfigMapper.selectByCode("NC_BASE_URL"); + if(null!=actionUrlConfig){ + baseActionUrl = actionUrlConfig.getValue(); + } +// return null; + RestTemplate client = restTemplateConfig.restTemplate(); + HttpHeaders headers = new HttpHeaders(); + // 改为从 config获取 + + + String ncSecret = "f715d3c9-3480-4a0a-934f-8fc806d41d52"; + SysConfig ncSecretConfig = sysConfigMapper.selectByCode("NC_SECRET"); + if(null!=ncSecretConfig){ + ncSecret = ncSecretConfig.getValue(); + } + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + headers.set("secret", ncSecret); + headers.set("Accept", "*/*"); + JSONObject params = new JSONObject(); + JSONObject object = new JSONObject(); + // 改为从 config获取 + String scenarioId = "171"; + SysConfig scenarioIdConfig = sysConfigMapper.selectByCode("NC_SCENARIO_ID"); + if(null!=scenarioIdConfig){ + scenarioId = scenarioIdConfig.getValue(); + } + params.put("scenarioId", Integer.valueOf(scenarioId)); + JSONArray filesArray = new JSONArray(); + // 存放base64 + Map fileMap = new HashMap<>(); + for(FileVo f:fileVoList){ + JSONArray files = new JSONArray(); + JSONObject fObj = new JSONObject(); + Map map = new HashMap<>(); + map.put("type","file"); + map.put("name",f.getFileName()); + String uuid = UUID.randomUUID().toString(); + fileMap.put(uuid,f.parseBase64Url()); + map.put("base64",uuid); + files.add(map); +// fObj.put("id", task.getId()); + fObj.put("assets", files); + Map mapUrl = new HashMap<>(); +// mapUrl.put("url",f.getSourceUrl()); + fObj.put("meta", mapUrl); + filesArray.add(fObj); + } + params.put("receiptObjects", filesArray); + // 改为从sys_config获取 + String skipProcessValue = "true"; + SysConfig ncSkillProcessConfig = sysConfigMapper.selectByCode("NC_SKILL_PROCESS"); + if(null!=ncSkillProcessConfig){ + skipProcessValue = ncSkillProcessConfig.getValue(); + } + params.put("skipProcess", "true".equals(skipProcessValue)); + log.info("params without base64=>{}",JSONObject.toJSONString(params)); + // 替换base64 + String bodyBaseStr = JSON.toJSONString(params); + for(String mapKey:fileMap.keySet()){ + bodyBaseStr = bodyBaseStr.replace(mapKey,fileMap.get(mapKey)); + } + HttpEntity request = new HttpEntity<>(bodyBaseStr, headers); +// log.info("NC IMPORT Body{}", request); + JSONObject forObject = null; + try { + forObject = client.postForObject( + baseActionUrl+"api/server/nc/record/import", + request, + JSONObject.class + ); + } catch (ResourceAccessException e) { + // 网络层面异常:超时、无法连接、断网 + log.error("调用nc导入接口网络异常", e); + } catch (HttpClientErrorException e) { + // 4xx 客户端错误 400,401,404 + log.error("调用nc导入接口4xx错误,响应体:{}", e.getResponseBodyAsString(), e); + } catch (HttpServerErrorException e) { + // 5xx 服务端异常 + log.error("调用nc导入接口5xx错误,响应体:{}", e.getResponseBodyAsString(), e); + } catch (RestClientException e) { + // 其他所有rest异常兜底 + log.error("调用nc导入接口未知异常", e); + } + return forObject; + } + + private void dealBase64Invoice(int ncImportId, int owner, String type, String originalFilename, String companyCode, JSONObject data, JSONObject file,int invoiceType){ + try { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setCode(type); + }}).get(0); + + JSONObject jsonDataResult = data; + if (null == jsonDataResult) { + log.error("nd api response not setting or error"); + return; + } + List mappingList = null; + RuiZhenOCREntity ocrEntity = new RuiZhenOCREntity(); +// ocrEntity.getResponse().getData().getIdentify_results() + if(2==invoiceType){ + // { + // "发票名称": "电子发票(增值税专用发票)", + // "分类码": "10107", + // "开票日期": "2026-03-12", + // "发票代码": "", + // "发票号码": "26312000001498706896", + // "税前金额": 1777441.8, + // "含税金额": 1884088.31 + // } + List identify_results = new ArrayList<>(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + Details corporateInvoice = new Details(); + corporateInvoice.setNumber(data.getString("发票号码")); + corporateInvoice.setCode(data.getString("发票代码")); + corporateInvoice.setDate(data.getString("开票日期")); + corporateInvoice.setPretax_amount(data.getString("税前金额")); + corporateInvoice.setTotal(data.getString("含税金额")); + identifyResults.setDetails(corporateInvoice); + identifyResults.setType(data.getString("分类码")); + identify_results.add(identifyResults); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(identify_results); + response.setData(ocrData); + ocrEntity.setResponse(response); + }else{ + // 形式发票处理 + List identify_results = new ArrayList<>(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice", "invoice"); + Details corporateInvoice = new Details(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = jsonDataResult.get(source); + ReflectionUtil.setFieldValue(corporateInvoice, dest, String.valueOf((null == sourceValue ? "" : sourceValue))); + } + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable("proforma_invoice", "items"); + List itemList = new ArrayList<>(); + JSONArray itemArr = jsonDataResult.getJSONArray("items"); + for (int i = 0; i < itemArr.size(); i++) { + JSONObject itemObject = itemArr.getJSONObject(i); + Item corporateInvoiceItems = new Item(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + ReflectionUtil.setFieldValue(corporateInvoiceItems, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + itemList.add(corporateInvoiceItems); + } +// corporateInvoice.setCode("60100"); + corporateInvoice.setItems(itemList); + identifyResults.setDetails(corporateInvoice); + identifyResults.setType("60100"); + identify_results.add(identifyResults); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(identify_results); + response.setData(ocrData); + ocrEntity.setResponse(response); + } + String oFileName = file.getString("name"); + SysOrg sysOrg = sysOrgMapper.selectByCode(companyCode); + Integer orgId = Optional.ofNullable(sysOrg.getId()).orElse(0); + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + oFileName; + String folder = Pdf2JpgHelper.generateFolderWithTitle(uploadPath,"base64"); + String pdfPath = uploadPath + folder + fileName; + // 将base64 转为 相应的文件 + String base64 = file.getString("base64"); +// if(base64.contains(",")){ +// base64 = base64.substring(base64.indexOf(",") + 1); +// } + int lastDotIndex = pdfPath.lastIndexOf('.'); + // 没有点,或者点在最后(如 readme.),直接返回原字符串 + int lastSepIndex = Math.max(pdfPath.lastIndexOf('/'), pdfPath.lastIndexOf('\\')); + // 点出现在目录分隔符前面,说明点属于文件夹名,不是文件后缀,不处理 + String noSuffixPath = ""; + if(lastDotIndex <= lastSepIndex){ + noSuffixPath = pdfPath; + }else{ + noSuffixPath = pdfPath.substring(0, lastDotIndex); + } + Base64Utils.saveMimeBase64ToFile(base64,noSuffixPath); + if(oFileName.toLowerCase().endsWith(".pdf")){ + // 如果是pdf类型 + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileName2; + ImageIO.write(jpgImage, "JPG", new File(jpgFile)); + ScannerLogs scannerLogs = scannerLogsMapper.selectByExt01(ncImportId); + invoiceVAT(pdfPath, originalFilename, ocrEntity, invoiceType, owner, orgId, folder, fileName2, pdfPath, corporateInvoiceType, null==scannerLogs?0L:scannerLogs.getId()); + }else{ + String jpgFile = uploadPath + folder + fileName; + // + pdfPath = noSuffixPath+".pdf"; + FileImgUtil.jpg2PDF(jpgFile,pdfPath); + + ScannerLogs scannerLogs = scannerLogsMapper.selectByExt01(ncImportId); + invoiceVAT(pdfPath, originalFilename, ocrEntity, invoiceType, owner, orgId, folder, fileName, pdfPath, corporateInvoiceType, null==scannerLogs?0L:scannerLogs.getId()); + } + + } catch (Exception e) { + log.error("base64 convert to proforma invoice error:{}", e.getMessage()); + e.printStackTrace(); + } + } + + @Override + public void dealNcExport(int ncImportId,int userId,String type,String originalFilename,String companyCode) { + + int getNum=0; + String ncSleepStr = "5"; + SysConfig ncSleepTime = sysConfigMapper.selectByCode("NC_SLEEP_TIME"); + if(null!=ncSleepTime){ + ncSleepStr = ncSleepTime.getValue(); + } + int ncSleep = Integer.parseInt(ncSleepStr); + + String maxTry = "5"; + SysConfig maxTryConfig = sysConfigMapper.selectByCode("NC_RETRY_MAX"); + if(null!=maxTryConfig){ + maxTry = maxTryConfig.getValue(); + } + int retayMax = Integer.parseInt(maxTry); + try { + JSONObject ncExportData = ncExport(ncImportId); + log.info("importId=》{}, get-export-val :{}",ncImportId,ncExportData.getJSONObject("data").get("status")); + while(!ncExportData.getJSONObject("data").get("status").toString().equals("format_success") && getNum < retayMax){ + ncExportData = ncExport(ncImportId); + Thread.sleep(ncSleep * 1000); + getNum++; + log.error("获取NC附件列表重试:{}", getNum); + } + ScannerLogs scannerLogs = scannerLogsMapper.selectByExt01(ncImportId); + if(!ncExportData.getJSONObject("data").get("status").equals("format_success")){ +// log.error("import id :{} ,Unexpected code {}",ncImportId, JSONObject.toJSONString(ncExportData)); + // 5次失败后记录结果到 scannerLogs表 + scannerLogs.setExt03("format_error"); + scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + throw new IOException("Unexpected code " + JSONObject.toJSONString(ncExportData)); + } + JSONArray receipts = ncExportData.getJSONObject("data").getJSONArray("receipts"); + for (int i = 0; i < receipts.size(); i++) { + JSONObject receipt = receipts.getJSONObject(i); + JSONObject source = receipt.getJSONObject("source"); + String sourceName = source.getString("name"); + // 判断文件类型 + if("Commercial Invoice".equals(sourceName)){ + // 形式发票 + JSONObject data = receipt.getJSONObject("data"); + JSONArray files = receipt.getJSONArray("files"); + JSONObject file = files.getJSONObject(0); + dealBase64Invoice(ncImportId,userId, type, originalFilename,companyCode,data,file,1); + + }else if("Proforma Invoice".equals(sourceName)){ + // 形式发票 + JSONObject data = receipt.getJSONObject("data"); + JSONArray files = receipt.getJSONArray("files"); + JSONObject file = files.getJSONObject(0); + dealBase64Invoice(ncImportId,userId, type, originalFilename,companyCode,data,file,1); + }else if("国内发票增值税发票".equals(sourceName)){ + //国内发票增值税发票 + JSONObject data = receipt.getJSONObject("data"); + JSONArray files = receipt.getJSONArray("files"); + JSONObject file = files.getJSONObject(0); + dealBase64Invoice(ncImportId,userId, type, originalFilename,companyCode,data,file,2); + } + } + scannerLogs.setExt03("format_success"); + scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + }catch (Exception e){ + log.error("NC EXPORT ERROR {}",e.getMessage()); + e.printStackTrace(); + } + + } + + public JSONObject ncExport(Integer id) { + String baseActionUrl = "http://nd.fanhaninfo.test/"; + SysConfig actionUrlConfig = sysConfigMapper.selectByCode("NC_BASE_URL"); + if(null!=actionUrlConfig){ + baseActionUrl = actionUrlConfig.getValue(); + } + RestTemplate client = restTemplateConfig.restTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + String ncSecret = "51c1bc9d-9d01-4e98-bcb4-0125bbb37cb7"; + SysConfig ncSecretConfig = sysConfigMapper.selectByCode("NC_SECRET"); + if(null!=ncSecretConfig){ + ncSecret = ncSecretConfig.getValue(); + } + headers.set("secret", ncSecret); + headers.set("Accept", "*/*"); + JSONObject params = new JSONObject(); + params.put("id", id); + HttpEntity request = new HttpEntity<>(params.toString(), headers); +// log.info("NC EXPORT Body{}", request); + JSONObject forObject = null; + try { + forObject = client.postForObject( + baseActionUrl+"api/server/nc/record/export", + request, + JSONObject.class + ); + } catch (ResourceAccessException e) { + // 网络层面异常:超时、无法连接、断网 + log.error("调用nc export 接口网络异常", e); + } catch (HttpClientErrorException e) { + // 4xx 客户端错误 400,401,404 + log.error("调用nc export 接口4xx错误,响应体:{}", e.getResponseBodyAsString(), e); + } catch (HttpServerErrorException e) { + // 5xx 服务端异常 + log.error("调用nc export 接口5xx错误,响应体:{}", e.getResponseBodyAsString(), e); + } catch (RestClientException e) { + // 其他所有rest异常兜底 + log.error("调用nc export 接口未知异常", e); + } + return forObject; + } + + private Supplier runTextsText(List suppliers, String sellerName) { + if (suppliers.isEmpty()) { + return null; + } + SysConfig AIMatchAPIConfig = sysConfigMapper.selectByCode("AI_MATERIAL_MATCH_API"); + if (null == AIMatchAPIConfig) { + log.error("未匹配值 AIMatchAPI"); + } + String AIMatchAPIValue = AIMatchAPIConfig.getValue(); + + SysConfig matMatchScoreConfig = sysConfigMapper.selectByCode("matMatchScore"); + if (null == matMatchScoreConfig) { + log.error("未匹配值 matMatchScore"); + } + String matMatchScore = matMatchScoreConfig.getValue(); + double matMatchScoreLimit = Double.parseDouble(matMatchScore); + + SysConfig scores_methodConfig = sysConfigMapper.selectByCode("scores_method"); + String scores_method = "dense+sparse"; + SysConfig scores_weightsConfig = sysConfigMapper.selectByCode("scores_weights"); + String scores_weights = "[0.4,0.2]"; + if (null != scores_methodConfig) { + scores_method = scores_methodConfig.getValue(); + } + if (null != scores_weightsConfig) { + scores_weights = scores_weightsConfig.getValue(); + } + + JSONArray textsArr = new JSONArray(); + for (Supplier supplier : suppliers) { + String name = supplier.getName(); + textsArr.add(name.toUpperCase()); + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + String token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + headers.add("session", token); + // corpItems 遍历 查找评分 + JSONObject requestBody = new JSONObject(); + requestBody.put("texts", textsArr); + JSONObject paramsAi = new JSONObject(); + paramsAi.put("scores_method", scores_method); + JSONArray jsa = JSONArray.parseArray(scores_weights); + paramsAi.put("scores_weights", jsa); + requestBody.put("params", paramsAi); + requestBody.put("text", sellerName.toUpperCase()); + String bodyJsonData = JSON.toJSONString(requestBody); + log.info("AI-mater supplier 请求数据{}", bodyJsonData); + //用HttpEntity封装整个请求报文 + HttpEntity request = new HttpEntity<>(bodyJsonData, headers); + AIMaterialVO resultVo = null; + try { + resultVo = client.postForObject(AIMatchAPIValue, request, AIMaterialVO.class); + } catch (Exception e) { + e.printStackTrace(); + } + log.info("AI-mater supplier 结果{}", JSONObject.toJSONString(resultVo)); + List ids = resultVo.getIds(); + List scores = resultVo.getScores(); + if (ids.isEmpty()) { + + } else { + int indexId = ids.get(0); + double maxScore = scores.get(0); + if (maxScore >= matMatchScoreLimit) { + return suppliers.get(indexId); + } + } + return null; + } + + + public Company runTextsTextCompany(List companies, String sellerName) { + if (companies.isEmpty()) { + return null; + } + SysConfig AIMatchAPIConfig = sysConfigMapper.selectByCode("AI_MATERIAL_MATCH_API"); + if (null == AIMatchAPIConfig) { + log.error("未匹配值 AIMatchAPI"); + } + String AIMatchAPIValue = AIMatchAPIConfig.getValue(); + + SysConfig matMatchScoreConfig = sysConfigMapper.selectByCode("matMatchScore"); + if (null == matMatchScoreConfig) { + log.error("未匹配值 matMatchScore"); + } + String matMatchScore = matMatchScoreConfig.getValue(); + double matMatchScoreLimit = Double.parseDouble(matMatchScore); + + SysConfig scores_methodConfig = sysConfigMapper.selectByCode("scores_method"); + String scores_method = "dense+sparse"; + SysConfig scores_weightsConfig = sysConfigMapper.selectByCode("scores_weights"); + String scores_weights = "[0.4,0.2]"; + if (null != scores_methodConfig) { + scores_method = scores_methodConfig.getValue(); + } + if (null != scores_weightsConfig) { + scores_weights = scores_weightsConfig.getValue(); + } + + JSONArray textsArr = new JSONArray(); + for (Company company : companies) { + String name = company.getFullName(); + if (org.apache.commons.lang3.StringUtils.isEmpty(name)) { + name = company.getName(); + } + textsArr.add(name.toUpperCase()); + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + String token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + headers.add("session", token); + // corpItems 遍历 查找评分 + JSONObject requestBody = new JSONObject(); + requestBody.put("texts", textsArr); + JSONObject paramsAi = new JSONObject(); + paramsAi.put("scores_method", scores_method); + JSONArray jsa = JSONArray.parseArray(scores_weights); + paramsAi.put("scores_weights", jsa); + requestBody.put("params", paramsAi); + requestBody.put("text", sellerName.toUpperCase()); + String bodyJsonData = JSON.toJSONString(requestBody); + log.info("AI-mater company 请求数据{}", bodyJsonData); + //用HttpEntity封装整个请求报文 + HttpEntity request = new HttpEntity<>(bodyJsonData, headers); + AIMaterialVO resultVo = null; + try { + resultVo = client.postForObject(AIMatchAPIValue, request, AIMaterialVO.class); + } catch (Exception e) { + e.printStackTrace(); + } + log.info("AI-mater supplier 结果{}", JSONObject.toJSONString(resultVo)); + List ids = resultVo.getIds(); + List scores = resultVo.getScores(); + List res = resultVo.getTexts(); + if (ids.isEmpty()) { + + } else { + double score01 = scores.get(0); + int indexId = ids.get(0); + if (score01 > matMatchScoreLimit) { + if (ids.size() >= 2) { + double score1 = scores.get(0); + double score2 = scores.get(1); + if (score1 == score2) { + String text1 = res.get(0).toLowerCase(); + String text2 = res.get(1).toLowerCase(); + if (text1.equals(sellerName.toLowerCase())) { + int indexId1 = ids.get(0); + return companies.get(indexId1); + } + if (text2.equals(sellerName.toLowerCase())) { + int indexId1 = ids.get(1); + return companies.get(indexId1); + } + } else { + return companies.get(indexId); + } + } else { + return companies.get(indexId); + } + } + } + return null; + } + + public List getInvoiceByNumber(String number,String validStatus) { + return corporateInvoiceMapper.selectByNumAndValidStatus(number, validStatus); + } + + public void eleFirstOcrLeft(String folder, String invoicePic, String uploadFilePath + , ScannerPostDate postDate, String watchPath, int userId, int orgId, String fileName, CorporateInvoiceType corporateInvoiceType + , ScannerLogs scannerLogs, String com, String uploadPath) { + List pdfPaths = new ArrayList<>(); + List needToMerge = new ArrayList<>(); + + SysConfig MAIL_OVERSEA_KEYWORD_CONFIG = sysConfigMapper.selectByCode("MAIL_OVERSEA_KEYWORD"); + String MAIL_OVERSEA_KEYWORD_VALUE = "外币发票"; + if (null == MAIL_OVERSEA_KEYWORD_CONFIG) { + log.warn("MAIL_OVERSEA_KEYWORD 未配置 采用默认外币发票"); + } else { + MAIL_OVERSEA_KEYWORD_VALUE = MAIL_OVERSEA_KEYWORD_CONFIG.getValue(); + } + + + if (fileName.indexOf(MAIL_OVERSEA_KEYWORD_VALUE) > -1) { + //1. 增加一个判断文件名分支 + //如果文件名含外币发票走这个分支 + //2. 先将pdf拆分成单页 + //3. 每个单页调用分类模型,返回各种类型的页面 + ///find_page_num 的模型code + //4. 过滤出所有类型 = 海外形式发票的pdf单页 + //5. 新的单页再走pdf分页合并模型,获取页数,譬如1-2-3-1-2 + //6. 只要碰到1或结束就把前面的pdf合并,譬如1-2-3合并一个文件,1-2合并一个文件。 + //7. 将合并的文件调用海外形式发票识别,插入发票表 + try { + SysConfig ocrProformaConfig = sysConfigMapper.selectByCode("OCR_PROFORMA"); + if (null == ocrProformaConfig) { + log.warn("形式发票识别未配置匹配模型采用ocr模式识别"); + } + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(uploadFilePath)); + int totalPage = readPdf.getNumberOfPages(); + List overseasList = new ArrayList<>(); + if (totalPage > 1) { + File parent = new File(uploadFilePath); + List splitPdfs = Pdf2JpgHelper.pdfSplit(uploadFilePath, parent.getParent()); + int i = 1; + for (String splitPdfPath : splitPdfs) { + String ndSearchCode = "classify"; // classify_proforma + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(splitPdfPath)); + if (null == jsonDataResult) { + log.error("addProcessForExtract===nd api response not setting or error"); + return; + } + String fileType = jsonDataResult.getJSONObject("json_data").getString("type"); + if ("海外形式发票".equals(fileType)) { + overseasList.add(splitPdfPath); + } + } + for (String s : overseasList) { + if (null == ocrProformaConfig || "proforma".equals(ocrProformaConfig.getValue())) { + // 弗兰德OCR接口 + this.pdfToImagesForProforma(null, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + SysConfig PROFORMA_HEAD_LINE_SPLIT_CONFIG = sysConfigMapper.selectByCode("PROFORMA_HEAD_LINE_SPLIT"); + if (null != PROFORMA_HEAD_LINE_SPLIT_CONFIG && "1".equals(PROFORMA_HEAD_LINE_SPLIT_CONFIG.getValue())) { + this.ocrProformaFromNdApiHeadLine(null, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId()); + } else { + this.ocrProformaFromNdApi(uploadFilePath, null, scannerLogs.getHashKey(), s, watchPath, false, com, userId, corporateInvoiceType, scannerLogs.getId(), scannerLogs.getId(),""); + } + } + } + + } + } catch (Exception e) { + log.error("将合并的文件调用海外形式发票识别,插入发票表 异常", e.getMessage()); + } + + + return; + } + String suffix = uploadFilePath.substring(uploadFilePath.lastIndexOf(".")); + log.info("scannerLogs.getId()=>{}", scannerLogs.getId()); + Map numberPathMap1 = new HashMap<>(); + Map numberPathMap2 = new HashMap<>(); + SysConfig SPLIT_MODE_CONFIG = sysConfigMapper.selectByCode("SPLIT_MODE_CONFIG"); + if (null != SPLIT_MODE_CONFIG && "spilt_pdf_merge".equals(SPLIT_MODE_CONFIG.getValue())) { + //1. 增加一个判断文件名分支 + //如果文件名含外币发票走这个分支 + //2. 先将pdf拆分成单页 + //3. 每个单页调用分类模型,返回各种类型的页面 + // 1. 分类,排序 + // 2. 根据顺序号查发票号码 + // 3,组成新文件 + // 4. 内容识别 + List overseasSplitList = new ArrayList<>(); + + try { + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(uploadFilePath)); + int totalPage = readPdf.getNumberOfPages(); + if (totalPage > 1) { + log.info("more pages ===>"); + File parent = new File(uploadFilePath); + List splitPdfs = Pdf2JpgHelper.pdfSplit(uploadFilePath, parent.getParent()); + // 分析页码 + List pageNumList = new ArrayList<>(); + String tempPageInvoiceNumber = null; + + for (String overseaInvoicePath : splitPdfs) { + String ndSearchCode = "spilt_pdf_merge"; + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode, new File(overseaInvoicePath)); + if (null == jsonDataResult) { + log.error("overseaInvoicePath===nd api response not setting or error"); + continue; + } + String fileType = jsonDataResult.getString("附件类型"); //海外形式发票 + int pageNum = jsonDataResult.getInteger("第几页"); //1 + String splitFileInvoiceNo = jsonDataResult.getString("invoice_number"); + log.info("pageNum === >{}", pageNum); + log.info("fileType === >{}", fileType); + log.info("splitFileInvoiceNo === >{}", splitFileInvoiceNo); + numberPathMap1.put(overseaInvoicePath, splitFileInvoiceNo); + if (fileType.indexOf("电子发票") > -1) { +// if("海外形式发票".equals(fileType)){ + if (null == tempPageInvoiceNumber) { + //第一次进入 + tempPageInvoiceNumber = splitFileInvoiceNo; + overseasSplitList.add(overseaInvoicePath); + } else { + if (org.apache.commons.lang3.StringUtils.isEmpty(splitFileInvoiceNo)) { + // 如果第一张有发票号码,但第二张也是形式发票,但是没有页码。则也认为是同一张 + overseasSplitList.add(overseaInvoicePath); + } else { + // 这里改成如果是第一张发票有发票号码。和下一张也是一样的发票号则认为是同一张 + if (tempPageInvoiceNumber.equals(splitFileInvoiceNo)) { + overseasSplitList.add(overseaInvoicePath); + pageNumList.add(pageNum); + } else { + // 如果发票号不一样 则合并前置所有pdf到1个pdf中 + // 根据pageNum merge pdf成1个。 + if (splitFileInvoiceNo.indexOf(".") > -1) { + overseasSplitList.add(overseaInvoicePath); + pageNumList.add(pageNum); + } else { + + if(overseasSplitList.size()==1){ + pdfPaths.add(overseasSplitList.get(0)); + overseasSplitList = new ArrayList<>(); + overseasSplitList.add(overseaInvoicePath); + + }else{ + String mergePdfPath = this.uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasSplitList); + numberPathMap2.put(mergePdfPath, numberPathMap1.get(overseaInvoicePath)); + pdfPaths.add(mergePdfPath); + overseasSplitList = new ArrayList<>(); + overseasSplitList.add(overseaInvoicePath); + tempPageInvoiceNumber = null; + } + + } + + } + } + } + } + } + if (!overseasSplitList.isEmpty()) { + String mergePdfPath = this.uploadPath + folder + StringUtil.UUID() + suffix; + Pdf2JpgHelper.mergePdf(mergePdfPath, overseasSplitList); + numberPathMap2.put(mergePdfPath, numberPathMap1.get(overseasSplitList.get(0))); + pdfPaths.add(mergePdfPath); + } + }else{ + log.info("one pages ===>"); + pdfPaths.add(uploadFilePath); + } + } catch (Exception e) { + log.error("将合并的文件调用海外形式发票识别,插入发票表 异常", e.getMessage()); + } + } else { + try { + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(uploadFilePath)); + int totalPage = readPdf.getNumberOfPages(); + if (totalPage > 1) { + File parent = new File(uploadFilePath); + List splitPdfs = Pdf2JpgHelper.pdfSplit(uploadFilePath, parent.getParent()); + int i = 1; + for (String splitPdfPath : splitPdfs) { + PDDocument document = PDDocument.load(new File(splitPdfPath)); + PDFTextStripper stripper = new PDFTextStripper() { + + }; + stripper.setSortByPosition(true); + String text = stripper.getText(document); + if (text.contains("第" + i + "页")) { + needToMerge.add(splitPdfPath); + i++; + } else { + // 将上一轮的 pdf 合并 + if (!needToMerge.isEmpty()) { + if (needToMerge.size() == 1) { + pdfPaths.add(needToMerge.get(0)); + } else { + String uuid = StringUtil.UUID(); + String filePath = parent.getParent() + "/" + uuid + ".pdf"; + Pdf2JpgHelper.mergePdf(filePath, needToMerge); + needToMerge = new ArrayList<>(); + pdfPaths.add(filePath); + } + } + i = 1; + // 默认为单独文件 直接上传 + pdfPaths.add(splitPdfPath); + } +// new File(splitPdfPath).delete(); + } + // 将最后一轮的 pdf 合并 + if (!needToMerge.isEmpty()) { + if (pdfPaths.isEmpty()) { + pdfPaths.add(uploadFilePath); + for (String s : needToMerge) { + new File(s).delete(); + } + } else { + if (needToMerge.size() == 1) { + pdfPaths.add(needToMerge.get(0)); + } else { + String uuid = StringUtil.UUID(); + String filePath = parent.getParent() + "/" + uuid + ".pdf"; + Pdf2JpgHelper.mergePdf(filePath, needToMerge); + pdfPaths.add(filePath); + } + } + } + } else { + pdfPaths.add(uploadFilePath); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + // + SysConfig SCANNER_TEST_MODE = sysConfigMapper.selectByCode("SCANNER_TEST_MODEL"); + if (null != SCANNER_TEST_MODE&&"1".equals(SCANNER_TEST_MODE.getValue())) { + // 保存到 corporate_invoice_scanner_files 后 异步处理 file文件。 + List filesList = new ArrayList<>(); + // 构建实体 + log.info("pdfPaths pages ===>{}",pdfPaths.size()); + for (String pdfPath : pdfPaths) { + CorporateInvoiceScannerFiles scannerFiles = new CorporateInvoiceScannerFiles() { + { + setCreateDate(new Date()); + setScannerId(scannerLogs.getId()); + setPdfPath(uploadFilePath); + setSplitFilePath(pdfPath); + setOcrStatus(0); + setVerifyStatus(0); + } + }; + String num = numberPathMap2.get(scannerFiles.getSplitFilePath()); + log.error("exist num==>{}", num); + //24312000000099947902 + if(null==num){ + log.error("exist null num ====>{}"); + corporateInvoiceScannerFilesMapper.insert(scannerFiles); + filesList.add(scannerFiles); + }else{ + scannerFiles.setInvoiceNumber(num); + List existList = getInvoiceByNumber(num,"1"); + log.error("existList==>{}", existList.isEmpty()); + if (existList.isEmpty()) { + corporateInvoiceScannerFilesMapper.insert(scannerFiles); + filesList.add(scannerFiles); + } else { + for (CorporateInvoice corporateInvoice : existList) { + corporateInvoice.setExt01(scannerLogs.getId().toString()); + corporateInvoiceMapper.updateExt01(corporateInvoice); + } + // 通过 scid 和 number 找到对应的发票是否验真通过 + log.info("scannerLogs.getId()=>{}", scannerLogs.getId()); + CorporateInvoice corporateInvoiceOK = corporateInvoiceMapper.selectByNumberAndExt01(num, scannerLogs.getId()); + if (corporateInvoiceOK.getValidStatus().equals((byte) 1)) { + // 验真成功 则 更新scannerFiles + scannerFiles.setVerifyStatus(1); + scannerFiles.setOcrCost(0); + scannerFiles.setOcrStatus(1); + scannerFiles.setOcrResult("no"); + scannerFiles.setOcrInterface("number exist and replace"); + corporateInvoiceScannerFilesMapper.insert(scannerFiles); + }else{ + corporateInvoiceScannerFilesMapper.insert(scannerFiles); + filesList.add(scannerFiles); + } + } + } + + + // 同时更新 scannerLogs + } + scannerLogs.setInvoiceUpNum(filesList.size()); + scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + log.error("filesList size() ====>{}",filesList.size()); + for (CorporateInvoiceScannerFiles scannerFiles : filesList) { + try { + Thread.sleep(1000); + }catch (Exception e){ + e.printStackTrace(); + } + scannerSplitPool.execute(() -> { + try { + String pdfPath = scannerFiles.getSplitFilePath(); + long startTime = new Date().getTime(); + // 保存到 corporate_invoice_files 后 异步处理 file文件。 国信 + String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String imgRealPath = invoicePic + File.separator + folder + newImgName; + Pdf2JpgHelper.pdfToImage2(pdfPath, imgRealPath); + RuiZhenOCREntity ocrEntity = null; + try { + ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(pdfPath)); + }catch ( Exception e){ + e.printStackTrace(); + } + scannerFiles.setOcrStatus(0); + long endTime = new Date().getTime(); + int cost = (int) (endTime - startTime); + scannerFiles.setOcrCost(cost); + scannerFiles.setOcrInterface("billsCropFHOfElectronic"); + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 第一次pdf 类型的电子票转化失败后,可以认为是纸票的pdf + // 可 将pdf 单独分页成一页一页的pdf 再次上传 fh/api/v4/AI_httpService/OC_VATinvoice_all/detail_checkrz 接口类型前缀是pdf。 + // 只取第一页 ? + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(pdfPath)); + int totalPage = readPdf.getNumberOfPages(); + String firstPagePdfPath = null; + if (totalPage > 1) { + firstPagePdfPath = pdfPath.replace(".pdf", "PageOne.pdf").replace(".PDF", "PageOne.pdf"); + }else{ + firstPagePdfPath = pdfPath; + } + try { + Pdf2JpgHelper.pdfGetOnePagePdf(pdfPath, firstPagePdfPath); + File pageOne = new File(firstPagePdfPath); + if (pageOne.exists()) { + try { + ocrEntity = ruiZhenOCRService.billsCropFHWithTitle(Base64Util.fileToBase64(firstPagePdfPath), "application/pdf"); + long endTime2 = new Date().getTime(); + cost = (int) (endTime2 - startTime); + scannerFiles.setOcrCost(cost); + scannerFiles.setOcrInterface("billsCropFHWithTitle"); + } catch (Exception e) { + log.error("识别发票异常=》{}", uploadFilePath); + } + } + SysConfig needRzDeal = sysConfigMapper.selectByCode("NEED_RZ_DEAL"); + // 比较特殊的情况 + // 如果识别出来类型是 10100 或者10102 但是发票号码 是小于10位的 基本是8位。 + if (null != ocrEntity && null != ocrEntity.getResponse() && null != ocrEntity.getResponse().getData() && null != ocrEntity.getResponse().getData().getIdentify_results() + && !ocrEntity.getResponse().getData().getIdentify_results().isEmpty()) { + try { + String type = ocrEntity.getResponse().getData().getIdentify_results().get(0).getType(); + String number = ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber(); + if (("10100".equals(type) || "10102".equals(type)) && number.length() < 10) { + ocrEntity = null; + } + } catch (Exception e) { + log.error("识别billsCropFHOfElectronic 返回异常"); + e.printStackTrace(); + } + } + if (null != needRzDeal && "1".equals(needRzDeal.getValue())) { + if (null == ocrEntity || org.apache.commons.lang3.StringUtils.isEmpty(ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber())) { + String fileNameQ = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileNameQ; + Pdf2JpgHelper.pdfLastPageToImage(firstPagePdfPath, jpgFile); + // 睿真方式处理 + // 20230629接口方式判断 + String interfaceStr = "RZ"; + SysConfig interfaceConfig = sysConfigMapper.selectByCode("OCR_INTERFACE"); + if (interfaceConfig != null) { + interfaceStr = interfaceConfig.getValue(); + log.info("OCR_INTERFACE=>{}", interfaceStr); + } + // pdf 获取最后一页的 + Pdf2JpgHelper.pdfLastPageToImage(pdfPath, jpgFile); + long oldLength; + long newLength; + //判断文件是否写入完成 + int delay = 3000; + do { + oldLength = new File(jpgFile).length(); + log.info("File Uploading113 >> {} : {}", jpgFile, oldLength); + ThreadUtil.sleep(delay); + newLength = new File(jpgFile).length(); + log.info("File Uploading223 >> {} : {}", jpgFile, newLength); + } while (oldLength != newLength || newLength == 0); + if (interfaceStr.equals("FH")) { + ocrEntity = ruiZhenOCRService.billsCropFH(Base64Util.fileToBase64(jpgFile)); + } else { + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(jpgFile)); + if(null==ocrEntity){ + // 重试一次 + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(jpgFile)); + } + } + long endTime3 = new Date().getTime(); + cost = (int) (endTime3 - startTime); + scannerFiles.setOcrCost(cost); + scannerFiles.setOcrInterface("billsCrop"); + } + } + }catch (Exception e) { + log.error("billsCropFHOfElectronic 失败后处理过程异常",e.getMessage()); + throw new ServiceException("billsCropFHOfElectronic 失败后处理过程异常"); + } + } + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 分解多个jpg 走RZ / FH 的识别接口 + Pdf2JpgHelper.pdfToImages2AndSaveCache(null, postDate.getHashKey(), pdfPath, watchPath, false, com, null, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId(), sysConfigMapper); + scannerFiles.setOcrStatus(1); + scannerFiles.setOcrResult("SAP"); + scannerFiles.setOcrInterface("pdfToImages2AndSaveCache"); + scannerFiles.setUpdateDate(new Date()); + corporateInvoiceScannerFilesMapper.update(scannerFiles); + } else { + scannerFiles.setOcrStatus(1); + scannerFiles.setOcrResult("success"); + scannerFiles.setUpdateDate(new Date()); + String number = ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber(); + scannerFiles.setInvoiceNumber(number); + List existList = getInvoiceByNumber(number,"1"); + log.error("existList==>{}", existList.isEmpty()); + if (existList.isEmpty()) { + invoiceVAT(null, null, ocrEntity, 2, userId, orgId, folder, newImgName, pdfPath, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId()); + } else { + for (CorporateInvoice corporateInvoice : existList) { + corporateInvoice.setExt01(scannerLogs.getId().toString()); + log.info("updateExt01(corporateInvoice) id=>{}",corporateInvoice.getId()); + corporateInvoiceMapper.updateExt01(corporateInvoice); + } + } +// 通过 scid 和 number 找到对应的发票是否验真通过 + log.info("scannerLogs.getId()=>{}", scannerLogs.getId()); + log.info("scannerLogs.number()=>{}", number); + CorporateInvoice corporateInvoiceOK = corporateInvoiceMapper.selectByNumberAndExt01(number, scannerLogs.getId()); + if (corporateInvoiceOK.getValidStatus().equals((byte) 1)) { +// 验真成功 则 更新scannerFiles + scannerFiles.setVerifyStatus(1); + }else{ + scannerFiles.setVerifyStatus(2); + } + corporateInvoiceScannerFilesMapper.update(scannerFiles); + } +// // 通过sql计数 更新scannerLogs +// int ct = corporateInvoiceScannerFilesMapper.getSuccessCount(scannerLogs.getId()); +// scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + + } catch (Exception e) { + e.printStackTrace(); + scannerFiles.setOcrStatus(2); + scannerFiles.setOcrResult("服务器异常,请检查日志"); + scannerFiles.setVerifyStatus(2); + corporateInvoiceScannerFilesMapper.update(scannerFiles); + log.error("服务器异常=》{}", e.getMessage()); + } + }); + } + }if (null != SCANNER_TEST_MODE&&"2".equals(SCANNER_TEST_MODE.getValue())) { + List filesList = new ArrayList<>(); + for (String pdfPath : pdfPaths) { + CorporateInvoiceScannerFiles scannerFiles = new CorporateInvoiceScannerFiles() { + { + setCreateDate(new Date()); + setScannerId(scannerLogs.getId()); + setPdfPath(uploadFilePath); + setSplitFilePath(pdfPath); + } + }; + log.error("exist null num ====>{}"); + corporateInvoiceScannerFilesMapper.insert(scannerFiles); + filesList.add(scannerFiles); + // 同时更新 scannerLogs + } + log.error("filesList size() ====>{}",filesList.size()); + for (CorporateInvoiceScannerFiles scannerFiles : filesList) { + try { + Thread.sleep(1000); + }catch (Exception e){ + e.printStackTrace(); + } + scannerSplitPool.execute(() -> { + try { + String pdfPath = scannerFiles.getSplitFilePath(); + long startTime = new Date().getTime(); + // 保存到 corporate_invoice_files 后 异步处理 file文件。 国信 + String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String imgRealPath = invoicePic + File.separator + folder + newImgName; + Pdf2JpgHelper.pdfToImage2(pdfPath, imgRealPath); + RuiZhenOCREntity ocrEntity = null; + scannerFiles.setOcrStatus(0); + long endTime = new Date().getTime(); + int cost = (int) (endTime - startTime); +// scannerFiles.setOcrCost(cost); + scannerFiles.setOcrInterface("billsCropFHOfElectronic"); + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 第一次pdf 类型的电子票转化失败后,可以认为是纸票的pdf + try { + SysConfig needRzDeal = sysConfigMapper.selectByCode("NEED_RZ_DEAL"); + // 第一次pdf 类型的电子票转化失败后,可以认为是纸票的pdf + // 可 将pdf 单独分页成一页一页的pdf 再次上传 fh/api/v4/AI_httpService/OC_VATinvoice_all/detail_checkrz 接口类型前缀是pdf。 + // 只取第一页 ? + PDDocument readPdf = null; + readPdf = PDDocument.load(new File(pdfPath)); + int totalPage = readPdf.getNumberOfPages(); + String pageLast = null; + if (totalPage > 1) { + pageLast = pdfPath.replace(".pdf", "PageLast.pdf").replace(".PDF", "PageOne.pdf"); + }else{ + pageLast = pdfPath; + } + Pdf2JpgHelper.pdfGetOnePagePdf(pdfPath, pageLast); + // 比较特殊的情况 + if (null != needRzDeal && "1".equals(needRzDeal.getValue())) { + // 睿真方式处理 + // 20230629接口方式判断 + String interfaceStr = "RZ"; + SysConfig interfaceConfig = sysConfigMapper.selectByCode("OCR_INTERFACE"); + if (interfaceConfig != null) { + interfaceStr = interfaceConfig.getValue(); + log.info("OCR_INTERFACE=>{}", interfaceStr); + } + // pdf 获取最后一页的 + long oldLength; + long newLength; + //判断文件是否写入完成 + int delay = 2000; + do { + oldLength = new File(pageLast).length(); + log.info("File Uploading11 >> {} : {}", pageLast, oldLength); + ThreadUtil.sleep(delay); + newLength = new File(pageLast).length(); + log.info("File Uploading22 >> {} : {}", pageLast, newLength); + } while (oldLength != newLength || newLength == 0); + if (interfaceStr.equals("FH")) { + ocrEntity = ruiZhenOCRService.billsCropFH(Base64Util.fileToBase64(pageLast)); + } else { + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(pageLast)); + if(null==ocrEntity){ + // 重试一次 + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(pageLast)); + } + } + long endTime3 = new Date().getTime(); + cost = (int) (endTime3 - startTime); + scannerFiles.setOcrCost(cost); + scannerFiles.setOcrInterface("RZ"); + } + }catch (Exception e) { + log.error("billsCropFHOfElectronic 失败后处理过程异常",e.getMessage()); + throw new ServiceException("billsCropRZ 失败后处理过程异常"); + } + } + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 分解多个jpg 走RZ / FH 的识别接口 + Pdf2JpgHelper.pdfToImages2AndSaveCache(null, postDate.getHashKey(), pdfPath, watchPath, false, com, null, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId(), sysConfigMapper); + scannerFiles.setOcrStatus(0); + scannerFiles.setOcrResult("SAP"); + scannerFiles.setOcrInterface("pdfToImages2AndSaveCache"); + scannerFiles.setUpdateDate(new Date()); + } else { + scannerFiles.setOcrStatus(1); + scannerFiles.setOcrResult("success"); + scannerFiles.setUpdateDate(new Date()); + String number = ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber(); + scannerFiles.setInvoiceNumber(number); +// corporateInvoiceScannerFilesMapper.update(scannerFiles); + List existList = getInvoiceByNumber(number,"1"); + log.error("existList==>{}", existList.isEmpty()); + if (existList.isEmpty()) { + invoiceVAT(null, null, ocrEntity, 2, userId, orgId, folder, newImgName, pdfPath, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId()); + } else { + for (CorporateInvoice corporateInvoice : existList) { + corporateInvoice.setExt01(scannerLogs.getId().toString()); + log.info("updateExt01(corporateInvoice) id=>{}",corporateInvoice.getId()); + corporateInvoiceMapper.updateExt01(corporateInvoice); + } + } +// 通过 scid 和 number 找到对应的发票是否验真通过 + log.info("scannerLogs.getId()=>{}", scannerLogs.getId()); + log.info("scannerLogs.number()=>{}", number); + CorporateInvoice corporateInvoiceOK = corporateInvoiceMapper.selectByNumberAndExt01(number, scannerLogs.getId()); + if (corporateInvoiceOK.getValidStatus().equals((byte) 1)) { +// 验真成功 则 更新scannerFiles + scannerFiles.setVerifyStatus(1); + }else{ + scannerFiles.setVerifyStatus(2); + } + corporateInvoiceScannerFilesMapper.update(scannerFiles); + } +// // 通过sql计数 更新scannerLogs +// int ct = corporateInvoiceScannerFilesMapper.getSuccessCount(scannerLogs.getId()); +// scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + } catch (Exception e) { + e.printStackTrace(); + scannerFiles.setOcrStatus(2); + scannerFiles.setOcrResult("服务器异常,请检查日志"); + scannerFiles.setVerifyStatus(2); + corporateInvoiceScannerFilesMapper.update(scannerFiles); + log.error("服务器异常=》{}", e.getMessage()); + } + }); + } + } else if(null==SCANNER_TEST_MODE){ + for (String pdfPath : pdfPaths) { + // 保存到 corporate_invoice_files 后 异步处理 file文件。 国信 + String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String imgRealPath = invoicePic + File.separator + folder + newImgName; + Pdf2JpgHelper.pdfToImage2(pdfPath, imgRealPath); + RuiZhenOCREntity ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(pdfPath)); + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 第一次pdf 类型的电子票转化失败后,可以认为是纸票的pdf + // 可 将pdf 单独分页成一页一页的pdf 再次上传 fh/api/v4/AI_httpService/OC_VATinvoice_all/detail_checkrz 接口类型前缀是pdf。 + // 只取第一页 ? + String firstPagePdfPath = pdfPath.replace(".pdf", "PageOne.pdf").replace(".PDF", "PageOne.pdf"); + try { + Pdf2JpgHelper.pdfGetOnePagePdf(pdfPath, firstPagePdfPath); + File pageOne = new File(firstPagePdfPath); + if (pageOne.exists()) { + try { + ocrEntity = ruiZhenOCRService.billsCropFHWithTitle(Base64Util.fileToBase64(firstPagePdfPath), "application/pdf"); + } catch (Exception e) { + log.error("识别发票异常=》{}", uploadFilePath); + } + } + SysConfig needRzDeal = sysConfigMapper.selectByCode("NEED_RZ_DEAL"); + // 比较特殊的情况 + // 如果识别出来类型是 10100 或者10102 但是发票号码 是小于10位的 基本是8位。 + if (null != ocrEntity && null != ocrEntity.getResponse() && null != ocrEntity.getResponse().getData() && null != ocrEntity.getResponse().getData().getIdentify_results() + && !ocrEntity.getResponse().getData().getIdentify_results().isEmpty()) { + try { + String type = ocrEntity.getResponse().getData().getIdentify_results().get(0).getType(); + String number = ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber(); + if (("10100".equals(type) || "10102".equals(type)) && number.length() < 10) { + ocrEntity = null; + } + } catch (Exception e) { + log.error("识别billsCropFHOfElectronic 返回异常"); + e.printStackTrace(); + } + } + if (null != needRzDeal && "1".equals(needRzDeal.getValue())) { + if (null == ocrEntity || org.apache.commons.lang3.StringUtils.isEmpty(ocrEntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber())) { + String fileNameQ = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileNameQ; + Pdf2JpgHelper.pdfLastPageToImage(firstPagePdfPath, jpgFile); + // 睿真方式处理 + // 20230629接口方式判断 + String interfaceStr = "RZ"; + SysConfig interfaceConfig = sysConfigMapper.selectByCode("OCR_INTERFACE"); + if (interfaceConfig != null) { + interfaceStr = interfaceConfig.getValue(); + log.info("OCR_INTERFACE=>{}", interfaceStr); + } + // pdf 获取最后一页的 + Pdf2JpgHelper.pdfLastPageToImage(pdfPath, jpgFile); + long oldLength; + long newLength; + //判断文件是否写入完成 + int delay = 3000; + do { + oldLength = new File(jpgFile).length(); + log.info("File Uploading11 >> {} : {}", jpgFile, oldLength); + ThreadUtil.sleep(delay); + newLength = new File(jpgFile).length(); + log.info("File Uploading22 >> {} : {}", jpgFile, newLength); + } while (oldLength != newLength || newLength == 0); + if (interfaceStr.equals("FH")) { + ocrEntity = ruiZhenOCRService.billsCropFH(Base64Util.fileToBase64(jpgFile)); + } else { + ocrEntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(jpgFile)); + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (null == ocrEntity || null == ocrEntity.getResult() || 0 == ocrEntity.getResult()) { + // 分解多个jpg 走RZ / FH 的识别接口 + Pdf2JpgHelper.pdfToImages2AndSaveCache(null, postDate.getHashKey(), pdfPath, watchPath, false, com, null, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId(), sysConfigMapper); + } else { + invoiceVAT(null, null, ocrEntity, 2, userId, orgId, folder, newImgName, pdfPath, corporateInvoiceType, null == scannerLogs ? 0L : scannerLogs.getId()); + } + } + } + } } diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysLogoServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysLogoServiceImpl.java new file mode 100644 index 0000000..543dd8b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysLogoServiceImpl.java @@ -0,0 +1,109 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.FileUtil; +import com.cmsen.ticket.application.manager.service.SysLogoService; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysLogo; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysLogoMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2022/8/24 16:06 + **/ +@Slf4j +@Service +public class SysLogoServiceImpl implements SysLogoService { + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Resource + private SysLogoMapper sysLogoMapper; + @Resource + private SysConfigMapper sysConfigMapper; + + @Override + public RestResponse select() { + SysLogo sysLogo = sysLogoMapper.getRecord(); + SysConfig sysConfig = sysConfigMapper.selectByCode("SSO_URL"); + Map sso = new HashMap<>(); + if(sysConfig != null){ + sysLogo.setSsoUrl(sysConfig.getValue()); + } + return RestResponse.success(sysLogo); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(SysLogo sysLogo) { + try { + sysLogoMapper.insertSelective(sysLogo); + return RestResponse.success(sysLogo); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public RestResponse update(MultipartFile file, String typeStr, String str, Long id) { + log.info("typeStr===={}",typeStr); + try{ + if(file != null){ + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(".png".equalsIgnoreCase(suffix))) { + return RestResponse.failure("错误的图片类型,请上传PNG图片。"); + } + } + + if(typeStr.equals("pc")){//pc logo + String uploadFilePath = uploadPath + "logoPc.png"; + InputStream inputStream = file.getInputStream(); + FileUtil.saveFile(inputStream, uploadFilePath); + }else if(typeStr.equals("base")){//app 底图 + String uploadFilePath = uploadPath + "banner.png"; + InputStream inputStream = file.getInputStream(); + FileUtil.saveFile(inputStream, uploadFilePath); + }else if(typeStr.equals("app")){//app logo + String uploadFilePath = uploadPath + "logo.png"; + InputStream inputStream = file.getInputStream(); + FileUtil.saveFile(inputStream, uploadFilePath); + }else if(typeStr.equals("sysName")){ + SysLogo sysLogo = new SysLogo(){{ + setSysName(str); + setId(id); + }}; + sysLogoMapper.updateByPrimaryKeySelective(sysLogo); + }else if(typeStr.equals("ext01")){ + SysLogo sysLogo = new SysLogo(){{ + setExt01(str); + setId(id); + }}; + sysLogoMapper.updateByPrimaryKeySelective(sysLogo); + } + return RestResponse.success(); + + }catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统异常"); + } + } + + +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysPolicyServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysPolicyServiceImpl.java new file mode 100644 index 0000000..61d91b5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysPolicyServiceImpl.java @@ -0,0 +1,77 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SysPolicyService; +import com.cmsen.ticket.domain.entity.ExpenseUse; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.mapper.ExpenseUseMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 10:14 + **/ +@Slf4j +@Service +public class SysPolicyServiceImpl implements SysPolicyService { + @Resource + private ExpenseUseMapper mapper; + + @Override + public RestResponse list(Map params) { + PaginationUtil.paginationInit(params); + List list = mapper.list(params); + int total = mapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Override + public RestResponse selectByPrimaryKey(Integer id) { + return RestResponse.success(mapper.queryById(id)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(ExpenseUse expenseUse) { + try { + mapper.insert(expenseUse); + return RestResponse.success(expenseUse); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(ExpenseUse expenseUse) { + try { + mapper.update(expenseUse); + return RestResponse.success(expenseUse); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + mapper.deleteById(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxySetServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxySetServiceImpl.java new file mode 100644 index 0000000..fab1456 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxySetServiceImpl.java @@ -0,0 +1,142 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SysProxySetService; +import com.cmsen.ticket.domain.entity.ProxySysUser; +import com.cmsen.ticket.domain.entity.ProxyUser; +import com.cmsen.ticket.domain.entity.User; +import com.cmsen.ticket.domain.mapper.ProxySysUserMapper; +import com.cmsen.ticket.domain.mapper.ProxyUserMapper; +import com.cmsen.ticket.domain.mapper.UserMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.cmsenframework.security.RequestSecurityPolicy; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class SysProxySetServiceImpl implements SysProxySetService { + @Resource + private ProxySysUserMapper mapper; + @Resource + private ProxyUserMapper proxyUserMapper; + @Resource + private UserMapper userMapper; + @Resource + private SysUserMapper sysUserMapper; + + @Override + public RestResponse list(Map params) { + //PaginationUtil.paginationInit(params); + params.put("pageNum", params.get("pageNo").toString()); + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()), Integer.parseInt(params.get("pageSize").toString())); + + if(!params.get("roleType").equals("admin")){ + params.put("proxyId",RequestSecurityPolicy.getUserId()); + } + List list = mapper.list(params); + int total = mapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(ProxySysUser proxySysUser) { + try { + int count = mapper.checkExist(proxySysUser); + if (count > 0) { + return RestResponse.failure("该代理已存在。"); + } + proxySysUser.setProxyEmail(sysUserMapper.selectByPrimaryKey(proxySysUser.getProxyId()).getEmail()); + proxySysUser.setMainEmail(sysUserMapper.selectByPrimaryKey(proxySysUser.getMainId()).getEmail()); + + //根据email判断是否存在user + User pUser = userMapper.selectByEmail(proxySysUser.getProxyEmail()); + User mUser = userMapper.selectByEmail(proxySysUser.getMainEmail()); + if (pUser != null && mUser != null) { + ProxyUser proxyUser = new ProxyUser() {{ + setProxyId(pUser.getUserId()); + setMainId(mUser.getUserId()); + }}; + proxyUserMapper.insert(proxyUser); + proxySysUser.setPuId(proxyUser.getId()); + } + + mapper.insert(proxySysUser); + return RestResponse.success(proxySysUser); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + ProxySysUser proxySysUser = mapper.selectByPrimaryKey(id); + if (proxySysUser != null && proxySysUser.getPuId() != null) { + proxyUserMapper.deleteByPrimaryKey(proxySysUser.getPuId()); + } + + mapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(ProxySysUser proxySysUser) { + try { + int count = mapper.checkExist(proxySysUser); + if (count > 0) { + return RestResponse.failure("该代理已存在。"); + } + proxySysUser.setProxyEmail(sysUserMapper.selectByPrimaryKey(proxySysUser.getProxyId()).getEmail()); + proxySysUser.setMainEmail(sysUserMapper.selectByPrimaryKey(proxySysUser.getMainId()).getEmail()); + //先删除原来的代理 + ProxySysUser oldBean = mapper.selectByPrimaryKey(proxySysUser.getId()); + if (oldBean != null && oldBean.getPuId() != null) { + proxyUserMapper.deleteByPrimaryKey(oldBean.getPuId()); + } + //根据email判断是否存在user--插入代理 + User pUser = userMapper.selectByEmail(proxySysUser.getProxyEmail()); + User mUser = userMapper.selectByEmail(proxySysUser.getMainEmail()); + if (pUser != null && mUser != null) { + ProxyUser proxyUser = new ProxyUser() {{ + setProxyId(pUser.getUserId()); + setMainId(mUser.getUserId()); + }}; + proxyUserMapper.insert(proxyUser); + proxySysUser.setPuId(proxyUser.getId()); + } + mapper.updateByPrimaryKeySelective(proxySysUser); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public RestResponse selectUserList(String keyword) { + return RestResponse.success(sysUserMapper.selectSearchList(keyword)); + } + + @Override + public RestResponse getRepresentedList() { + Integer mainId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); + return RestResponse.success(mapper.getRepresentedList(mainId)); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxyUserServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxyUserServiceImpl.java new file mode 100644 index 0000000..59d74fa --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysProxyUserServiceImpl.java @@ -0,0 +1,82 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SysProxyUserService; +import com.cmsen.ticket.domain.entity.ProxyUser; +import com.cmsen.ticket.domain.mapper.ProxyUserMapper; +import com.cmsen.ticket.domain.mapper.UserMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class SysProxyUserServiceImpl implements SysProxyUserService { + @Resource + private ProxyUserMapper mapper; + + @Resource + private UserMapper userMapper; + + @Override + public RestResponse list(Map params) { + //PaginationUtil.paginationInit(params); + params.put("pageNum",params.get("pageNo").toString()); + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + List list = mapper.list(params); + int total = mapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(ProxyUser proxyUser) { + try { + int count = mapper.checkExist(proxyUser); + if (count > 0) { + return RestResponse.failure("该代理已存在。"); + } + mapper.insert(proxyUser); + return RestResponse.success(proxyUser); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + mapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(ProxyUser proxyUser) { + try { + mapper.updateByPrimaryKeySelective(proxyUser); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public RestResponse selectUserList(String name) { + return RestResponse.success(userMapper.selectSearchList(name)); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysRulesServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysRulesServiceImpl.java new file mode 100644 index 0000000..a01524a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysRulesServiceImpl.java @@ -0,0 +1,97 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SysRulesService; +import com.cmsen.ticket.domain.entity.RuleConfig; +import com.cmsen.ticket.domain.entity.RuleType; +import com.cmsen.ticket.domain.mapper.RuleConfigMapper; +import com.cmsen.ticket.domain.mapper.RuleTypeMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.github.pagehelper.PageHelper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 14:23 + **/ +@Slf4j +@Service +public class SysRulesServiceImpl implements SysRulesService { + @Resource + private RuleConfigMapper mapper; + + @Resource + private RuleTypeMapper ruleTypeMapper; + + @Override + public RestResponse list(Map params) { + /*PageHelper.clearPage();*/ + /*StringUtils.decoderUrl(params); + PaginationUtil.paginationInit(params);*/ + PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString())); + List list = mapper.list(params); + int total = mapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Override + public RestResponse selectByPrimaryKey(Integer id) { + return RestResponse.success(mapper.selectByPrimaryKey(id)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(RuleConfig config) { + try { + int count = mapper.checkRuleAndTicketType(config.getRule(), config.getTicketType()); + if (count > 0) { + return RestResponse.failure("该规则已存在。"); + } + mapper.insert(config); + return RestResponse.success(config); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(RuleConfig config) { + try { + config.setTicketType(null); + config.setRule(null); + mapper.updateByPrimaryKeySelective(config); + return RestResponse.success(config); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + mapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public RestResponse getRuleType() { + List list = ruleTypeMapper.list(); + return RestResponse.success(list); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysUserServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysUserServiceImpl.java index 36e1e67..2316f3a 100644 --- a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysUserServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysUserServiceImpl.java @@ -29,6 +29,7 @@ import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; import com.cmsen.ticket.domain.response.Response; import com.cmsen.ticket.domain.util.PaginationUtil; +import com.cmsen.ticket.domain.util.SmsUtil; import com.cmsen.ticket.interfaces.facade.form.ChangePassword; import com.cmsen.ticket.interfaces.facade.form.LoginForm; import com.cmsenframework.security.RequestSecurityPolicy; @@ -619,7 +620,7 @@ public class SysUserServiceImpl implements SysUserService { if(sysConfig != null){ sendSmsSign = sysConfig.getValue(); } -// SmsUtil.sendSms(tel, code, sendSmsUrl, sendSmsSign); + SmsUtil.sendSms(tel, code, sendSmsUrl, sendSmsSign); sysUser.setAge(code); sysUserMapper.updateByPrimaryKeySelective(sysUser); diff --git a/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysWhitelistServiceImpl.java b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysWhitelistServiceImpl.java new file mode 100644 index 0000000..22ecf63 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/manager/service/impl/SysWhitelistServiceImpl.java @@ -0,0 +1,77 @@ +package com.cmsen.ticket.application.manager.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SysWhitelistService; +import com.cmsen.ticket.domain.entity.Company; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.mapper.CompanyMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 9:56 + **/ +@Slf4j +@Service +public class SysWhitelistServiceImpl implements SysWhitelistService { + @Resource + private CompanyMapper mapper; + + @Override + public RestResponse list(Map params) { + PaginationUtil.paginationInit(params); + List list = mapper.list(params); + int total = mapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Override + public RestResponse selectByPrimaryKey(Integer id) { + return RestResponse.success(mapper.queryById(id)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse create(Company company) { + try { + mapper.insert(company); + return RestResponse.success(company); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(Company company) { + try { + mapper.update(company); + return RestResponse.success(company); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(Integer id) { + try { + mapper.deleteById(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/service/BayerCorInvoiceService.java b/src/main/java/com/cmsen/ticket/application/service/BayerCorInvoiceService.java new file mode 100644 index 0000000..c45a5a8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/BayerCorInvoiceService.java @@ -0,0 +1,5 @@ +package com.cmsen.ticket.application.service; + +public interface BayerCorInvoiceService { + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/CorpPaymentService.java b/src/main/java/com/cmsen/ticket/application/service/CorpPaymentService.java new file mode 100644 index 0000000..1439f8b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/CorpPaymentService.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.CorpPaymentHeader; +import com.cmsen.ticket.domain.entity.CorpPaymentLine; + +/** + * 供应商付款 + * @author xp + * @version 1.0.0 + * @date 2022年5月16日 15:10:36 + **/ +public interface CorpPaymentService { + RestResponse insertPayment(CorpPaymentHeader header); + RestResponse insertHeader(CorpPaymentHeader header); + RestResponse insertLine(CorpPaymentLine line); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/CorporateInvoiceService.java b/src/main/java/com/cmsen/ticket/application/service/CorporateInvoiceService.java index 69d7518..b93d2ff 100644 --- a/src/main/java/com/cmsen/ticket/application/service/CorporateInvoiceService.java +++ b/src/main/java/com/cmsen/ticket/application/service/CorporateInvoiceService.java @@ -1,5 +1,14 @@ package com.cmsen.ticket.application.service; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.Files; +import com.cmsen.ticket.domain.entity.TicketType; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + /** * @author OWTS * @version 1.0.0 @@ -7,4 +16,31 @@ package com.cmsen.ticket.application.service; **/ public interface CorporateInvoiceService { + RestResponse invoiceReceive(CorporateInvoice corporateInvoice); + + RestResponse setValidStatus(Boolean status,String id); + + RestResponse insert(CorporateInvoice corporateInvoice); + + RestResponse selectByLoginId(Map params); + + RestResponse identify(Files files); + + RestResponse update(CorporateInvoice corporateInvoice); + + RestResponse delete(String id); + + void validationRules(CorporateInvoice corporateInvoice, StringBuilder message, TicketType ticketType); + + RestResponse getAccount(String id); + + RestResponse getOrgList(String loginId); + + RestResponse downloadMonthlyCorporateInvoicesExport(Map params, HttpServletResponse response); + + List selectByOrg(String[] corInvoiceOrg); + + RestResponse selectDetailById(String id); + + } diff --git a/src/main/java/com/cmsen/ticket/application/service/CurrencyService.java b/src/main/java/com/cmsen/ticket/application/service/CurrencyService.java new file mode 100644 index 0000000..6f6d9da --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/CurrencyService.java @@ -0,0 +1,19 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; + +import java.util.Map; + +/** + * @author ran hao yu + * @date 2020/8/7 9:15 + * @description + */ +public interface CurrencyService { + RestResponse selectList(String name); + + RestResponse selectALlColumn(String tableName); + + + RestResponse insertActive(Map map); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/CustomerService.java b/src/main/java/com/cmsen/ticket/application/service/CustomerService.java new file mode 100644 index 0000000..cf7cdae --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/CustomerService.java @@ -0,0 +1,58 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.ticket.domain.entity.Customer; + +import java.util.List; + +/** + * (Customer)表服务接口 + * + * @author ran hao yu + * @since 2020-09-18 14:11:43 + */ +public interface CustomerService { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + Customer queryById(Integer id); + + /** + * 查询多条数据 + * + * @param offset 查询起始位置 + * @param limit 查询条数 + * @return 对象列表 + */ + List queryAllByLimit(int offset, int limit); + + List queryAll(Customer customer); + + /** + * 新增数据 + * + * @param customer 实例对象 + * @return 实例对象 + */ + Customer insert(Customer customer); + + /** + * 修改数据 + * + * @param customer 实例对象 + * @return 实例对象 + */ + Customer update(Customer customer); + + /** + * 通过主键删除数据 + * + * @param id 主键 + * @return 是否成功 + */ + boolean deleteById(Integer id); + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/HLYInterfaceService.java b/src/main/java/com/cmsen/ticket/application/service/HLYInterfaceService.java new file mode 100644 index 0000000..ae2df59 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/HLYInterfaceService.java @@ -0,0 +1,10 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.ticket.common.AjaxJson; + +public interface HLYInterfaceService { + + AjaxJson saveDatas(String resBody); + + AjaxJson getReportKey(String hlyReportId); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/HelpService.java b/src/main/java/com/cmsen/ticket/application/service/HelpService.java new file mode 100644 index 0000000..de076f5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/HelpService.java @@ -0,0 +1,12 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; + +/** + * @author ran hao yu + * @date 2020/8/7 9:50 + * @description + */ +public interface HelpService { + RestResponse selectList(); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/InternationalizationService.java b/src/main/java/com/cmsen/ticket/application/service/InternationalizationService.java new file mode 100644 index 0000000..8f3e7b4 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/InternationalizationService.java @@ -0,0 +1,14 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; + +/** + * @author ran hao yu + * @date 2020/8/4 15:47 + * @description 国际化接口业务层 + */ +public interface InternationalizationService { + RestResponse selectList(); + + RestResponse getAppMenus(); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/MeetingClient.java b/src/main/java/com/cmsen/ticket/application/service/MeetingClient.java new file mode 100644 index 0000000..ef47882 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/MeetingClient.java @@ -0,0 +1,4 @@ +package com.cmsen.ticket.application.service; + +public interface MeetingClient { +} diff --git a/src/main/java/com/cmsen/ticket/application/service/SendMailService.java b/src/main/java/com/cmsen/ticket/application/service/SendMailService.java new file mode 100644 index 0000000..0d591c1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/SendMailService.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.application.service; + +public interface SendMailService { + Boolean sendVerifiedCode(String to, String verifiedCode); + + Boolean sendVerifiedText(String to, String Text); + + Boolean sendVerifiedText2(String to, String cc, String Text); + + Boolean sendSubjectAndText(String to, String subject, String Text); + + Boolean sendFileAndText(String to, String text, String files); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/SendSmsService.java b/src/main/java/com/cmsen/ticket/application/service/SendSmsService.java new file mode 100644 index 0000000..c3a23da --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/SendSmsService.java @@ -0,0 +1,14 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; + +/** + * @author ran hao yu + * @date 2020/8/17 17:03 + * @description + */ +public interface SendSmsService { + RestResponse getSmsCode(String tel); + +// RestResponse verifySmsCode(String tel,String verificationCode); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/SupplierStateService.java b/src/main/java/com/cmsen/ticket/application/service/SupplierStateService.java new file mode 100644 index 0000000..eb8396b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/SupplierStateService.java @@ -0,0 +1,12 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoiceItems; + +public interface SupplierStateService { + + + public void insertCorporateInvoicePO(CorporateInvoice corporateInvoice,CorporateInvoiceItems corporateInvoiceItem, String po); + + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/UserPcService.java b/src/main/java/com/cmsen/ticket/application/service/UserPcService.java new file mode 100644 index 0000000..357b31b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/UserPcService.java @@ -0,0 +1,21 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; +import org.springframework.web.multipart.MultipartFile; + +/** + * @author fengql + * @date 2022/8/17 11:39 + * @description 用户PC业务层接口 + */ +public interface UserPcService { + RestResponse getUrl(); + + RestResponse loginPc(String code); + + RestResponse getVerCode(String openId, String telOrEmail); + + RestResponse codeLogin(String verCode, String telOrEmail); + + RestResponse upload(MultipartFile[] files, String typeCode, String email); +} diff --git a/src/main/java/com/cmsen/ticket/application/service/WeiTaiOcrService.java b/src/main/java/com/cmsen/ticket/application/service/WeiTaiOcrService.java new file mode 100644 index 0000000..212f55c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/WeiTaiOcrService.java @@ -0,0 +1,35 @@ +package com.cmsen.ticket.application.service; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.Supplier; +import com.cmsen.ticket.domain.entity.weitai.SendResult; + +import java.util.List; +import java.util.Map; + +public interface WeiTaiOcrService { + RestResponse supplierList(Map params); + + RestResponse supplierInsert(Supplier supplier); + RestResponse supplierInsertList(List ls); + + RestResponse supplierUpdate(Supplier supplier); + + RestResponse supplierDelete(Integer id); + + RestResponse corInvoiceList(Map params); + + RestResponse corInvoiceAndPoAndDetailList(Map params); + + RestResponse updateContractOwner(String jsonStr); + + RestResponse updateInternalOwner(String jsonStr); + + RestResponse updateFlowOwner(String jsonStr); + + RestResponse updateStatus(String jsonStr); + + RestResponse updateMatchingStatus(String jsonStr); + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/CorpPaymentServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/CorpPaymentServiceImpl.java new file mode 100644 index 0000000..2c6cefc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/CorpPaymentServiceImpl.java @@ -0,0 +1,75 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.CorpPaymentService; +import com.cmsen.ticket.domain.entity.CorpPaymentHeader; +import com.cmsen.ticket.domain.entity.CorpPaymentLine; +import com.cmsen.ticket.domain.mapper.CorpPaymentHeaderMapper; +import com.cmsen.ticket.domain.mapper.CorpPaymentLineMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; + +/** + * 供应商付款 + * @author xp + * @version 1.0.0 + * @date 2022年5月16日 15:10:36 + **/ +@Slf4j +@Service +public class CorpPaymentServiceImpl implements CorpPaymentService { + @Resource + private CorpPaymentHeaderMapper corpPaymentHeaderMapper; + @Resource + private CorpPaymentLineMapper corpPaymentLineMapper; + + @Override + @Transactional + public RestResponse insertPayment(CorpPaymentHeader header){ + // 判断对象是否为空 + if(header==null){ + return RestResponse.failure("Header不能为空"); + } + // 判断明细是否为空 + if(header!=null&& (header.getPayMentLine()==null ||header.getPayMentLine().size()==0)){ + return RestResponse.failure("Line不能为空"); + + } + CorpPaymentHeader query = new CorpPaymentHeader(); + query.setRequestId(header.getRequestId()); + List ls =corpPaymentHeaderMapper.selectList(query); + if(ls.size()>0){ + return RestResponse.failure("付款记录已存在"); + } + try { + header.setId(null); + corpPaymentHeaderMapper.insertSelective(header); + List line = new ArrayList<>(); + for (CorpPaymentLine tmp : header.getPayMentLine()) { + tmp.setPId(header.getId().toString()); + line.add(tmp); + } + corpPaymentLineMapper.insertBatch(line); + }catch (Exception e){ + e.printStackTrace(); + return RestResponse.failure("操作错误"); + } + return RestResponse.success(); + } + @Override + public RestResponse insertHeader(CorpPaymentHeader header){ + corpPaymentHeaderMapper.insertSelective(header); + return RestResponse.success(); + } + @Override + public RestResponse insertLine(CorpPaymentLine line){ + corpPaymentLineMapper.insertSelective(line); + return RestResponse.success(); + + } +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/CorporateInvoiceServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/CorporateInvoiceServiceImpl.java index 62a3c0c..3d915bc 100644 --- a/src/main/java/com/cmsen/ticket/application/service/impl/CorporateInvoiceServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/service/impl/CorporateInvoiceServiceImpl.java @@ -1,8 +1,55 @@ package com.cmsen.ticket.application.service.impl; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.util.ZipUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.write.metadata.WriteSheet; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.*; import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.application.service.WeiTaiOcrService; +import com.cmsen.ticket.bestsign.util.InterfaceUtil; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.entity.weitai.SendResult; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.cmsen.ticket.domain.util.StringUtils; +import com.cmsen.ticket.domain.vo.AccountMappingVo; +import com.cmsen.ticket.domain.vo.CorporateInvoiceSummaryVo; +import com.cmsen.ticket.domain.vo.CorporateInvoiceVo; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import com.cmsenframework.security.RequestSecurityPolicy; import lombok.extern.slf4j.Slf4j; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayInputStream; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; /** * @author OWTS @@ -13,4 +60,1011 @@ import org.springframework.stereotype.Service; @Service public class CorporateInvoiceServiceImpl implements CorporateInvoiceService { + @Resource + private InterfaceUtil interfaceUtil; + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; + + @Resource + private CorporateInvoiceItemsMapper itemsMapper; + + + @Resource + private UserMapper userMapper; + + @Resource + private RuiZhenOCRService ocrService; + + @Resource + private WeiTaiOcrService weiTaiOcrService; + + @Value("${file.filepath}") + private String invoicePic; + + @Value("${file.domainName}") + private String domainName; + + @Value("${server.servlet.context-path}") + private String contextPath; + + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Resource + private RuleConfigMapper ruleConfigMapper; + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + @Resource + private FileMapper fileMapper; + + @Resource + private CompanyMapper companyMapper; + + @Resource + private CustomerMapper customerMapper; + + + @Resource + private SysOrgMapper sysOrgMapper; + + @Resource + private AccountMappingMapper accountMappingMapper; + + @Resource + private SupplierBlacklistMapper supplierBlacklistMapper; + + @Resource + private SysUserMapper sysUserMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + int totalNum=0; + int totalDeptNum=0; + Map sftpParam = new HashMap<>(); + + @Override + @Transactional(rollbackFor = Exception.class) + public RestResponse invoiceReceive(CorporateInvoice corporateInvoice) { +// ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); +// CorpInvoiceReceiveHeader corpInvoiceReceiveHeader = new CorpInvoiceReceiveHeader(); +// corpInvoiceReceiveHeader.setDateOfReceipt(new Date()); +// corpInvoiceReceiveHeader.setBuyer(corporateInvoice.getBuyer()); +// corpInvoiceReceiveHeader.setInvoiceType(corporateInvoice.getInvoiceType() == 2 ? "增值税专用发票" : "增值税普通发票"); +// corpInvoiceReceiveHeader.setSeller(corporateInvoice.getSeller()); +// corpInvoiceReceiveHeader.setInvoiceCode(corporateInvoice.getCode()); +// corpInvoiceReceiveHeader.setInvoiceNum(corporateInvoice.getNumber()); +// corpInvoiceReceiveHeader.setInvoiceDate(corporateInvoice.getDate()); +// corpInvoiceReceiveHeader.setAmountMoney(corporateInvoice.getPretaxAmount()); +// corpInvoiceReceiveHeader.setTaxAmount(corporateInvoice.getTax()); +// String pretaxAmount = corporateInvoice.getPretaxAmount(); +// String tax = corporateInvoice.getTax(); +// String total = Integer.parseInt(pretaxAmount) + Integer.parseInt(tax) + ""; +// corpInvoiceReceiveHeader.setTotalAmount(total); +// int userId = (int) RequestSecurityPolicy.getUserId(); +// User user = userMapper.selectByPrimaryKey(userId); +// corpInvoiceReceiveHeader.setUsername(user.getUsername()); +// Integer invoiceType = corporateInvoice.getInvoiceType(); +// corpInvoiceReceiveHeader.setType(invoiceType); +// if(invoiceType==2){ +// corpInvoiceReceiveHeader.setInvoiceId(corporateInvoice.getId()); +// } + + return RestResponse.success(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public RestResponse setValidStatus(Boolean status, String id) { + if (status) { + boolean b = corporateInvoiceMapper.setValidStatus(id) > 0; + status = b; + } + return RestResponse.success(status); + } + + @Override + public RestResponse getAccount(String id) { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectById(id); + corporateInvoiceMapper.updateByFlow("1"); + if (corporateInvoice.getSubject() == null) { + throw new ServiceException("科目为空"); + } + CorporateInvoiceVo account = corporateInvoiceMapper.getAccount(id); + account.setId(id); + //SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(Integer.parseInt(account.getCompanyId())); + //String code = sysOrg.getCode(); + //account.setCompanyId(code); + //手动封装List + List list = new ArrayList<>(); + AccountMappingVo accountMappingVo1 = new AccountMappingVo(); + AccountMappingVo accountMappingVo2 = new AccountMappingVo(); + AccountMappingVo accountMappingVo3 = new AccountMappingVo(); + AccountMappingVo accountMappingVo4 = new AccountMappingVo(); + + accountMappingVo1.setAccountType("Debit"); + accountMappingVo2.setAccountType("Credit"); + accountMappingVo3.setAccountType("Debit"); + accountMappingVo4.setAccountType("Credit"); + Integer subject = corporateInvoice.getSubject(); + AccountMapping accountMapping = accountMappingMapper.selectBySubject(subject); + accountMappingVo1.setAccount(accountMapping.getDebitAccount1()); + accountMappingVo2.setAccount(accountMapping.getCreditSubject1()); + accountMappingVo3.setAccount(accountMapping.getDebitAccount2()); + accountMappingVo4.setAccount(accountMapping.getCreditSubject2()); + //封装 amount from corporateInvoice + accountMappingVo1.setAmount(corporateInvoice.getTotal()); + accountMappingVo2.setAmount(corporateInvoice.getTotal()); + + accountMappingVo3.setAmount(corporateInvoice.getTax()); + accountMappingVo4.setAmount(corporateInvoice.getTax()); + // 20220711税额修改 + if(corporateInvoice.getTicketCode().equals("10101") || corporateInvoice.getTicketCode().equals("10102") || + corporateInvoice.getTicketCode().equals("10103")|| corporateInvoice.getTicketCode().equals("10108")){ + accountMappingVo3.setAmount("0"); + accountMappingVo4.setAmount("0"); + } + list.add(accountMappingVo1); + list.add(accountMappingVo2); + list.add(accountMappingVo3); + list.add(accountMappingVo4); + account.setAccountcombine(list); + return RestResponse.success(account); + } + + @Override + public RestResponse getOrgList(String loginId) { + SysUser sysUser = sysUserMapper.selectByEmail(loginId); + if(sysUser == null ){ + return RestResponse.failure("sysUser不存在,请检查"); + } + + List sysOrgs = sysOrgMapper.selectForUser(sysUser.getId(),""); + return RestResponse.success(sysOrgs); + } + + + + @Override + public RestResponse downloadMonthlyCorporateInvoicesExport(Map params, HttpServletResponse response) { + String searchDate = params.get("searchDate").toString(); + if(null==searchDate){ + return RestResponse.failure("未获取到查询条件searchDate"); + } + params.put("searchDate",searchDate.replace("-","/")); + params.put("searchDate2",searchDate); +// List list2 = corporateInvoiceMapper.listCorporateInvoiceSummary2(params); + List serviceList = corporateInvoiceMapper.listCorporateInvoiceSummary(params); + params.put("total","true"); + List totalSumList = corporateInvoiceMapper.listCorporateInvoiceSummary(params); + if(totalSumList.isEmpty()){ + return RestResponse.failure("未发现任何数据"); + }else{ + CorporateInvoiceSummaryVo totalOne = totalSumList.get(0); + if(null==totalOne){ + return RestResponse.failure("未发现任何数据"); + } + totalOne.setCostCenter(""); + totalOne.setOrgName("合计"); + serviceList.add(totalOne); + } + + + int total = 0; + for (CorporateInvoiceSummaryVo corporateInvoiceSummaryVo : serviceList) { + total = total + corporateInvoiceSummaryVo.getAssertTotal() + corporateInvoiceSummaryVo.getServiceTotal() + +corporateInvoiceSummaryVo.getAssertRefundTotal() + corporateInvoiceSummaryVo.getServiceRefundTotal(); + } + SysConfig templateLocationConfig = sysConfigMapper.selectByCode("BAYER_MONTHLY_REPORT_TEMPLATE_LOCATION"); + if(null==templateLocationConfig){ + return RestResponse.failure("未获取到模板文件配置地址BAYER_MONTHLY_REPORT_TEMPLATE_LOCATION"); + } + String templatePath = templateLocationConfig.getValue(); + java.io.File template = new java.io.File(templatePath); + if(!template.exists()){ + return RestResponse.failure("未获取到模板文件未找到"+templatePath); + } + String uuid = UUID.randomUUID().toString(); + String outputPath = templatePath.replace(".xlsx","_"+uuid+".xlsx"); + ExcelWriter writer = EasyExcel.write(outputPath) + .withTemplate(templatePath) + .build(); + + WriteSheet sheet = EasyExcel.writerSheet(0).build(); + // 填充单元格(例如模板中预留的 A5 单元格 + Map map = new HashMap<>(); + map.put("searchDate", searchDate); + map.put("total", total); + writer.fill(map,sheet); + writer.fill(serviceList,sheet); + + sheet = EasyExcel.writerSheet(1).build(); + params.put("validStatus","1"); + + + // 大货采购类发票id + List goodAssertInvoiceIdList = corporateInvoiceMapper.listReportInvoiceId(params); + log.info("goodAssertInvoiceIdList=>{}",goodAssertInvoiceIdList.size()); + // 线下发票id + List serviceInvoiceIdList = corporateInvoiceMapper.listReportServiceInvoiceIds(params); + log.info("serviceInvoiceIdList=>{}",serviceInvoiceIdList.size()); + List invoiceList = new ArrayList<>(); + for (String s : goodAssertInvoiceIdList) { + params.put("id",s); + List corporateInvoices = corporateInvoiceMapper.list4(params); + invoiceList.addAll(corporateInvoices); + } + log.info("invoiceList1=>{}",invoiceList.size()); + for (String s : serviceInvoiceIdList) { + params.put("id",s); + List corporateInvoices = corporateInvoiceMapper.list5(params); + invoiceList.addAll(corporateInvoices); + } + log.info("invoiceList2=>{}",invoiceList.size()); + writer.fill(invoiceList,sheet); + writer.finish(); + response.setContentType(FileMime.XLSX.getMimeType()); + response.setHeader("Content-Disposition", "attachment;filename=invoice-matching.xlsx"); + // 创建工作簿对象 + try { + XSSFWorkbook workbook = new XSSFWorkbook(outputPath); + // 输出流处理 + workbook.write(response.getOutputStream()); + workbook.close(); + }catch (Exception e){ + e.printStackTrace(); + }finally { + new java.io.File(outputPath).delete(); + } + return null; + } + + @Override + public List selectByOrg(String[] corInvoiceOrg) { + return corporateInvoiceMapper.queryByOrg(corInvoiceOrg); + } + + @Override + public RestResponse selectDetailById(String id) { + return RestResponse.success(corporateInvoiceMapper.selectDetailById(id)); + } + +// private void addDataAuth(Map params) { +// params.put("userId", (int) RequestSecurityPolicy.getUserId()); +// params.put("companyWord", customerMapper.selectCompanyWord()); +// SysConfig invoice_image_source = sysConfigMapper.selectByCode("INVOICE_IMAGE_SOURCE"); +// params.put("source", invoice_image_source == null ? "" : invoice_image_source.getValue()); +// } + +// // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行 +// // 具体需要返回多少行可以在`PageReadListener`的构造函数设置 +// EasyExcel.read(new java.io.File(fileName), CorporateInvoice.class, new ReadListener() { +// /** +// * 单次缓存的数据量 +// */ +// public static final int BATCH_COUNT = 3000; +// /** +// *临时存储 +// */ +// private List cachedData = new ArrayList<>(BATCH_COUNT); +// +// @Override +// public void onException(Exception exception, AnalysisContext context) throws Exception { +// +// } +// +// @Override +// public void invokeHead(Map headMap, AnalysisContext context) { +// +// } +// +// @Override +// public void invoke(CorporateInvoice data, AnalysisContext context) { +// System.out.println(">>" + data); +// cachedData.add(data); +// if (cachedData.size() >= BATCH_COUNT) { +// saveData(); +// // 存储完成清理 list +// cachedData = new ArrayList<>(BATCH_COUNT); +// } +// } +// +// @Override +// public void extra(CellExtra extra, AnalysisContext context) { +// +// } +// +// @Override +// public void doAfterAllAnalysed(AnalysisContext context) { +// saveData(); +// } +// +// @Override +// public boolean hasNext(AnalysisContext context) { +// return true; +// } +// +// /** +// * 加上存储数据库 +// */ +// private void saveData() { +// log.info("{}条数据,开始存储数据库!", cachedData.size()); +// log.info("存储数据库成功!"); +// } +// }).sheet(0).doRead(); + + + + + + + + public String getToken(){ +// String url = "http://pengfei.fanhaninfo.test/jsonrpc"; + String url = null; + SysConfig xtptApiBasePath = sysConfigMapper.selectByCode("PENGFEI_XTPT_BASE_API"); + if(null!=xtptApiBasePath){ + url = xtptApiBasePath.getValue(); + } + String account = null; + String password = null; + + SysConfig xtptLoginAccount = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_ACCOUNT"); + if(null!=xtptLoginAccount){ + account = xtptLoginAccount.getValue(); + } + SysConfig xtptLoginPassword = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_PASSWORD"); + if(null!=xtptLoginPassword){ + password = xtptLoginPassword.getValue(); + } + + String token = null; + JSONObject dataJson = new JSONObject(); + + JSONObject params = new JSONObject(); + params.put("username",account); + params.put("password",password); + + + dataJson.put("jsonrpc", "2.0"); + + + String loginApi = null; + SysConfig xtptLoginApi = sysConfigMapper.selectByCode("PENGFEI_XTPT_LOGIN_API"); + if(null!=xtptLoginApi){ + loginApi = xtptLoginApi.getValue(); + } + dataJson.put("method", loginApi); + dataJson.put("params", params); + dataJson.put("timestampin", System.currentTimeMillis()); + String data = JSON.toJSONString(dataJson, SerializerFeature.DisableCircularReferenceDetect); + Map paramBody = new HashMap(); + paramBody.put("body", data); + paramBody.put("Content-Type", "application/json"); + paramBody.put("Authorization", ""); + + String[] response = interfaceUtil.httpPostMan2(url, paramBody); + + log.info("pengfei 协同平台 login 接口 code response ==={}===={},", response[1], response[0]); + if (Integer.parseInt(response[1]) != 200) { + log.error("pengfei 协同平台 login 交互网络异常,响应状态:" + response[1] + ",响应体为:" + response[0]); +// mesg.append(response[0]); + } else { + + JSONObject res = JSONObject.parseObject(response[0]); + JSONObject result = res.getJSONObject("result"); + JSONObject error = res.getJSONObject("error"); + if (null == result) { + // 保存失败 +// mesg.append("pengfei 未匹配表单接口失败"); + log.error("pengfei 协同平台 login失败=》{}", error.getString("message")); + } else { + token = result.getString("token"); + log.info("pengfei 协同平台 login 成功"); + } + } + return token; + } + + + @Override + public RestResponse selectByLoginId(Map params) { + log.info("=========selectByLoginId==========="); + PaginationUtil.paginationInit(params); + + //List list = corporateInvoiceMapper.selectByLoginId(loginId); + //List list = corporateInvoiceMapper.selectByParams(params); + List list = corporateInvoiceMapper.selectListByParams(params); + log.info("=========selectByLoginId======list====={}",list.size()); + log.info("=========selectByLoginId======list====={}",list); + return RestResponse.success(list); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse identify(Files files) { + User user = userMapper.selectByUser(new User() {{ + setUserId(Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId()))); + }}); + if (user == null || !user.isCorInvSubmit()) { + return RestResponse.failure("用户不存在,或用户无对公权限"); + } + List picList = files.getPicList(); + if (picList == null || picList.isEmpty()) { + return RestResponse.failure("错误的图片集合"); + } + try { + List invoices = new ArrayList<>(); + for (String image : picList) { + RuiZhenOCREntity ocrEntity = ocrService.billsCrop(image); + byte[] pic = Base64Util.decode(image); + //生成图片的新名称 + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + + UUID.randomUUID().toString().replace("-", "") + ".jpg"; + //图片的路径+图片的新名称 + String imgFilePath = invoicePic + "/" + newFileName; + String getImgRealPath = domainName + contextPath + imgVirtualPath + "/" + newFileName; + //创建一个文件输出流将图片输出 + OutputStream out = null; + try { + out = new FileOutputStream(imgFilePath); + out.write(pic); + out.flush(); + } finally { + IoUtil.close(out); + } +// List exFields1 = expenseTypeActiveService.selectExFields(1, 4); +// String exFieldsString1 = JsonUtil.toString(exFields1); + List identify_results = ocrEntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults result : identify_results) { + String uuid = StringUtil.UUID(); + Details details = result.getDetails(); + CorporateInvoice corporateInvoice = new CorporateInvoice(); + corporateInvoice.setId(uuid); + corporateInvoice.setTitle(details.getSeller()); + corporateInvoice.setSeller(details.getSeller()); + corporateInvoice.setSellerNo(details.getSeller_tax_id()); + corporateInvoice.setCode(details.getCode()); + corporateInvoice.setNumber(details.getNumber()); + corporateInvoice.setDate(details.getDate()); + corporateInvoice.setTotal(details.getTotal()); + corporateInvoice.setImgPath(getImgRealPath); + corporateInvoice.setRemark(details.getRemark()); + corporateInvoice.setIsSend(0); + corporateInvoice.setLoginId(user.getEmail()); +// corporateInvoice.setExtraFields(exFieldsString1); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(details.getBuyer()); + corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + corporateInvoice.setTicketCode(result.getType()); + corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(5);//暂挂 + corporateInvoice.setVerifiedCode(details.getCheck_code()); + corporateInvoice.setPretaxAmount(details.getPretax_amount()); + corporateInvoice.setTax(details.getTax()); + corporateInvoice.setOperatorId(1); + corporateInvoice.setCreateDate(new Date()); + corporateInvoice.setCurrency("CNY"); + corporateInvoice.setChecked(0); + List corporateInvoiceItems = new ArrayList<>(); + List items = details.getItems(); + StringBuilder itemDetails = new StringBuilder(); + List itemMatchingList = new ArrayList<>(); + if (items != null && !items.isEmpty()) { + for (Item item : items) { + itemDetails.append(item.getName()).append(";"); + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(uuid); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + setItemMatchingList(itemMatchingList); + }}); + } + } + corporateInvoice.setDetails(itemDetails.toString()); + corporateInvoice.setItems(corporateInvoiceItems); + StringBuilder message = new StringBuilder(); + TicketType ticketType = ticketTypeMapper.selectByCode(result.getType()); + List ruleConfigs = ruleConfigMapper.selectByClientAndTicketType(1, ticketType.getId(), 1); + Map> ruleMap = ruleConfigs.stream().collect(Collectors.groupingBy(ruleConfig -> ruleConfig.getRuleInfo().getName())); + CheckMessage checkMessage = new CheckMessage(); + List messages = new ArrayList<>(); + checkMessage.setSubmit(true); + checkMessage.setMessageList(messages); + corporateInvoice.setCheckResult(checkMessage); + short levelStop = 3; + String lang = user.getLanguageType(); + if (ruleMap.containsKey("票号重复规则")) { + log.info("票号重复规则2>>NUM>>{}>>CODE>>{}", corporateInvoice.getNumber(), corporateInvoice.getCode()); + RuleConfig duplicatedNum = ruleMap.get("票号重复规则").get(0); + Rule ruleInfo = duplicatedNum.getRuleInfo(); + // 添加一个 同组织过滤问题 + SysConfig DUP_INV_BY_ORG_CONFIG = sysConfigMapper.selectByCode("DUP_INV_BY_ORG"); + Integer orgId = null; + if(null!=DUP_INV_BY_ORG_CONFIG&&"1".equals(DUP_INV_BY_ORG_CONFIG.getValue())){ + orgId = corporateInvoice.getOrgId(); + } + int count = corporateInvoiceMapper.checkInvoiceNumIsExistByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode(),null,orgId); + if (count > 0) { + corporateInvoice.setStatus(2); + log.info("票号重复规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + checkMessage.setSubmit(false); + CheckMessage.Message message1 = new CheckMessage.Message() {{ + setLevel(duplicatedNum.getLevel()); + setMessage(ruleInfo.getMessageCn()); + }}; + messages.add(message1); + if (duplicatedNum.getLevel().equals(levelStop)) { + checkMessage.setSubmit(false); + } + } + } + corporateInvoice.setMessage(message.toString()); + invoices.add(corporateInvoice); + } + } + return RestResponse.success(invoices); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse update(CorporateInvoice corporateInvoice) { + try { + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + List items = corporateInvoice.getItems(); + for (CorporateInvoiceItems item : items) { + itemsMapper.updateByPrimaryKeySelective(item); + } + CorporateInvoice corporateInvoice1 = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + if (corporateInvoice1.getIsSend().equals(0)) { +// SendResult sendResult = weiTaiOcrService.sendInvoice(corporateInvoice1); +// Integer integer = sendResult.getResult(); +// if (integer.equals(1)) { +// corporateInvoice1.setIsSend(1); +// corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice1); +// } else { +// corporateInvoice1.setIsSend(0); +// corporateInvoice1.setStatus(2); +// corporateInvoice1.setMessage(sendResult.getMessage()); +// corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice1); +// } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse insert(CorporateInvoice corporateInvoice) { + String po = corporateInvoice.getPo(); + try { + /*//验真 + if (StringUtil.isNotEmpty(corporateInvoice.getId())) { + RuiZhenVerifyForm verifyForm = new RuiZhenVerifyForm(); + verifyForm.setCode(corporateInvoice.getCode()); + verifyForm.setNumber(corporateInvoice.getNumber()); + String checkCode = corporateInvoice.getVerifiedCode(); + if (StringUtil.isNotEmpty(checkCode) && checkCode.length() > 6) { + verifyForm.setCheck_code(checkCode.substring(checkCode.length() - 6)); + verifyForm.setCheck_code_all(checkCode); + } + String code = corporateInvoice.getTicketCode(); + // 20220419小程序发票验证添加10104,10107 + if ("10100".equals(code) || "10104".equals(code) || "10107".equals(code)) { + verifyForm.setPretax_amount(corporateInvoice.getPretaxAmount()); + } + verifyForm.setDate(corporateInvoice.getDate()); + verifyForm.setType(code); + RuiZhenOCRVerifyEntity ocrVerifyEntity = ruiZhenOCRService.verifyInvoice(verifyForm); + RuiZhenOCRVerifyEntity.CheckResult checkResult = ocrVerifyEntity.checkSuccess(); + if (!checkResult.isSuccess()) { + return RestResponse.failure("请检查发票详情是否正确。"); + } + } else { + corporateInvoice.setId(StringUtil.UUID()); + }*/ + + if (StringUtil.isEmpty(corporateInvoice.getId())) { + corporateInvoice.setId(StringUtil.UUID()); + } + + if (!corporateInvoice.getBase64().isEmpty()) { + List base64 = corporateInvoice.getBase64(); + for (String file : base64) { + byte[] b = Base64Util.decode(file); + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String savePath = invoicePic + "/" + newFileName; + FileUtil.saveFile(new ByteArrayInputStream(b), savePath); + fileMapper.insert(new File() {{ + setPath(savePath); + setUri(domainName + contextPath + imgVirtualPath + "/" + newFileName); + setType(""); + setPid(corporateInvoice.getId()); + }}); + } + } + corporateInvoice.setMatchStatus(0); + corporateInvoice.setInvoiceType(1); + + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + + // 验真 + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if(null==ext08Config){ + corporateInvoice.setExt08("2"); + }else{ + corporateInvoice.setExt08(ext08Config.getValue()); + } + if(StringUtil.isNotBlank(po)){ + corporateInvoice.setPo(po); + } + corporateInvoiceMapper.insert(corporateInvoice); + List items = corporateInvoice.getItems(); + for (CorporateInvoiceItems item : items) { + itemsMapper.insert(item); + } + + /*CorporateInvoice corporateInvoice1 = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + SendResult sendResult = weiTaiOcrService.sendInvoice(corporateInvoice1); + Integer isSend = sendResult.getResult(); + corporateInvoice1.setIsSend(isSend); + corporateInvoice1.setStatus(isSend.equals(1) ? 0 : 2); + corporateInvoice1.setMessage(sendResult.getMessage()); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice1);*/ + + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse delete(String id) { + try { + corporateInvoiceMapper.deleteByPrimaryKey(id); + //itemsMapper.deleteByPid(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Override + public void validationRules(CorporateInvoice corporateInvoice, StringBuilder message, TicketType ticketType) { + List ruleConfigs = ruleConfigMapper.selectByClientAndTicketType(1, ticketType.getId(), 1); + Map> ruleMap = ruleConfigs.stream().collect(Collectors.groupingBy(ruleConfig -> ruleConfig.getRuleInfo().getName())); + + //2026 -01 -13 + // 人员公司税号匹配规则 + if (ruleMap.containsKey("发票税号和导入公司税号匹配规则")) { + log.info("发票税号和导入公司税号匹配规则>>"); + RuleConfig personalAndCompanyRule = ruleMap.get("发票税号和导入公司税号匹配规则").get(0); + Rule ruleInfo = personalAndCompanyRule.getRuleInfo(); + //BuyerCode 不为空,才走该规则 2022/8/22 + String taxNo = corporateInvoice.getBuyerNo(); + if(StringUtil.isNotEmpty(taxNo)){ + log.info(" 发票税号和导入公司税号匹配规则>date>>{}>>>>", taxNo); + String invoiceTaxNo = StringUtils.getStringWithOutSpecialCode(taxNo); + int orgId = corporateInvoice.getOrgId(); + SysOrg org = sysOrgMapper.selectByPrimaryKey(orgId); + String orgTaxNo = org.getTaxNo(); + if(!invoiceTaxNo.equals(orgTaxNo)){ + log.info("发票税号和导入公司税号匹配规则>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + //新增规则 2023/4/17 + //供应商黑名单 + if (ruleMap.containsKey("供应商黑名单")) { + log.info("供应商黑名单>>"); + RuleConfig supplierRule = ruleMap.get("供应商黑名单").get(0); + Rule ruleInfo = supplierRule.getRuleInfo(); + log.info("供应商黑名单>DATA>>Name>>{}>>", corporateInvoice.getSeller()); + String seller = StringUtils.getStringWithOutSpecialCode(corporateInvoice.getSeller()); + SupplierBlacklist supplierBlacklist = supplierBlacklistMapper.checkSeller(seller, 1); + if (supplierBlacklist != null) { + log.info("供应商黑名单>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + + //新增规则 2022/9/8 + //1011-发票税号对应公司匹配规则 + if (ruleMap.containsKey("发票税号对应公司匹配规则")) { + log.info("发票税号对应公司匹配规则>>{}",corporateInvoice.getTax()); + RuleConfig numberConfirmRule = ruleMap.get("发票税号对应公司匹配规则").get(0); + Rule ruleInfo = numberConfirmRule.getRuleInfo(); + //得到组织的taxNo + SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(corporateInvoice.getOrgId()); + if (sysOrg != null && !sysOrg.getTaxNo().equals(corporateInvoice.getTax())) { + log.info("发票税号对应公司匹配规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + + //规则新增 2022/8/16 + //1005-发票预制号和打印号校验 + if (ruleMap.containsKey("发票预制号和打印号校验")) { + log.info("发票预制号和打印号校验>>"); + RuleConfig numberConfirmRule = ruleMap.get("发票预制号和打印号校验").get(0); + Rule ruleInfo = numberConfirmRule.getRuleInfo(); + String number = StringUtil.isNotEmpty(corporateInvoice.getNumberBackup()) ? corporateInvoice.getNumberBackup() : corporateInvoice.getNumber(); + String number_confirm = corporateInvoice.getNumberConfirm(); + log.info("发票预制号和打印号校验>DATA>>Number>>{}>>Confirm>>{}", number, number_confirm); + if (StringUtil.isNotBlank(number_confirm) && StringUtil.isNotBlank(number)) { + String num1 = number.substring(number.length() - 1); + String num2 = number_confirm.substring(number_confirm.length() - 1); + if (!num1.equals(num2)) { + log.info("发票预制号和打印号校验>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + //1006-发票章检查规则 + if (ruleMap.containsKey("发票章检查规则")) { + log.info("发票章检查规则>>{}", corporateInvoice.getCompanySeal()); + RuleConfig stampCheckRule = ruleMap.get("发票章检查规则").get(0); + Rule ruleInfo = stampCheckRule.getRuleInfo(); + if ("0".equals(corporateInvoice.getCompanySeal())) { + log.info("发票章检查规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + + + if (ruleMap.containsKey("票号重复规则")) { + log.info("票号重复规则5>>NUM>>{}>>CODE>>{}", corporateInvoice.getNumber(), corporateInvoice.getCode()); + RuleConfig duplicatedNum = ruleMap.get("票号重复规则").get(0); + Rule ruleInfo = duplicatedNum.getRuleInfo(); + + // 添加一个 同组织过滤问题 + SysConfig DUP_INV_BY_ORG_CONFIG = sysConfigMapper.selectByCode("DUP_INV_BY_ORG"); + Integer orgId = null; + if(null!=DUP_INV_BY_ORG_CONFIG&&"1".equals(DUP_INV_BY_ORG_CONFIG.getValue())){ + orgId = corporateInvoice.getOrgId(); + } + + int count = corporateInvoiceMapper.checkInvoiceNumIsExistByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode(),corporateInvoice.getId(),orgId); + if (count > 0) { + log.info("corporateInvoice.getNumber(), corporateInvoice.getCode(),corporateInvoice.getId(),{},{},{}", corporateInvoice.getNumber(), corporateInvoice.getCode(),corporateInvoice.getId()); + log.info("票号重复规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + log.info("corporateInvoice.getStatus>>Result>>{}", corporateInvoice.getStatus()); + + if (ruleMap.containsKey("公司抬头名称检查")) { + String buyer = corporateInvoice.getBuyer(); + log.info("公司抬头名称检查>>Buyer>>{}", buyer); + RuleConfig coRule = ruleMap.get("公司抬头名称检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + Company company = companyMapper.checkCoAndTax2(buyer, null); + if (company == null) { + log.info("公司抬头名称检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + if (ruleMap.containsKey("公司税号检查")) { + String buyerNo = corporateInvoice.getBuyerNo(); + log.info("公司税号检查>>buyerNo>>{}", buyerNo); + RuleConfig coRule = ruleMap.get("公司税号检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + Company company = companyMapper.checkCoAndTax(null, buyerNo); + if (company == null) { + log.info("公司税号检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + + + + if (ruleMap.containsKey("发票开户行公司地址检查")) { + String buyerNo = corporateInvoice.getBuyerNo(); + log.info("发票开户行公司地址检查>>buyerNo>>{}", buyerNo); + RuleConfig coRule = ruleMap.get("发票开户行公司地址检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + Company company = companyMapper.checkCoAndTax(null, buyerNo); + if (company == null) { + log.info("发票开户行公司地址检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + }else{ + String addressTel = corporateInvoice.getExt04(); + String bankNo = corporateInvoice.getExt02(); + + String realAddressTel = company.getExt02(); + String realBankNo = company.getExt03(); + + if(null!=realAddressTel&&realBankNo!=null + &&addressTel.trim().equals(realAddressTel) + &&bankNo.trim().equals(realBankNo)){ + log.info("发票开户行公司地址检查>>ruleResult>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + + + if (ruleMap.containsKey("货物名称必须包含中文字符检查")) { + // 通过 pid 到item表查 + String corperateInvoiceId = corporateInvoice.getId(); + List ciis = corporateInvoiceItemsMapper.selectItemsByPid(corperateInvoiceId); + log.info("货物名称必须包含中文字符检查>>details>>{}", corperateInvoiceId); + RuleConfig coRule = ruleMap.get("货物名称必须包含中文字符检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + Boolean flag = true; + for (int i = 0; i < ciis.size(); i++) { + String details = ciis.get(i).getName(); + if(!StringUtils.hasChineseCharacter(details)){ + flag = false; + } + } + if(!flag){ + log.info("货物名称必须包含中文字符检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + + + } + + if (ruleMap.containsKey("货物名称存在租赁字样,备注栏必须标注具体地址检查")) { + String details = corporateInvoice.getDetails(); + if(null==details)return; + String remark = corporateInvoice.getRemark(); + if(null==remark)return; + log.info("货物名称存在租赁字样,备注栏必须标注具体地址检查>>details>>{}", details); + RuleConfig coRule = ruleMap.get("货物名称存在租赁字样,备注栏必须标注具体地址检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + if(details.indexOf("租赁")>-1){ + if(remark.indexOf("地址")>-1){ + + }else{ + log.info("货物名称存在租赁字样,备注栏必须标注具体地址检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + // 启运站:察尔汗站
到站:枝江
车辆类型:铁路车皮 + // 起运地 到达地 车种车号 货物信息 + if (ruleMap.containsKey("货物名称存在运费字样,备注栏必须标注起运地到达地车种车号货物信息检查")) { + String details = corporateInvoice.getDetails(); + if(null==details)return; + String remark = corporateInvoice.getRemark(); + if(null==remark)return; + log.info("货物名称存在运费字样,备注栏必须标注起运地到达地车种车号货物信息检查>>details>>{}", details); + RuleConfig coRule = ruleMap.get("货物名称存在运费字样,备注栏必须标注起运地到达地车种车号货物信息检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + if(details.indexOf("运费")>-1){ + if(remark.indexOf("起运地")>-1&&remark.indexOf("到达地")>-1&&remark.indexOf("车种车号")>-1&&remark.indexOf("货物信息")>-1){ + + }else{ + log.info("货物名称存在运费字样,备注栏必须标注起运地到达地车种车号货物信息检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + + if (ruleMap.containsKey("单位数量不能为空检查")) { + String details = corporateInvoice.getDetails(); + if(null==details)return; + String corperateInvoiceId = corporateInvoice.getId(); + List items = corporateInvoiceItemsMapper.selectItemsByPid(corperateInvoiceId); + log.info("单位数量不能为空检查>>details>>{}", details); + RuleConfig coRule = ruleMap.get("单位数量不能为空检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + Boolean flag = true; + for (int i = 0; i < items.size(); i++) { + CorporateInvoiceItems item = items.get(i); + String unit = item.getUnit(); + String quantity = item.getQuantity(); + if(org.apache.commons.lang3.StringUtils.isEmpty(unit)||org.apache.commons.lang3.StringUtils.isEmpty(quantity)){ + flag = false; + } + if("0".equals(quantity)){ + flag = false; + } + } + if(!flag){ + log.info("单位数量不能为空检查>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + // 印泥必须是红色 + if (ruleMap.containsKey("发票章印泥颜色必须为红色检查")) { + // 印泥必须是红色 + if (ruleMap.containsKey("发票章印泥颜色必须为红色检查")) { + String red = corporateInvoice.getExt07(); + log.info("发票章印泥颜色必须为红色检查>>redFlag>>{}", red); + RuleConfig coRule = ruleMap.get("发票章印泥颜色必须为红色检查").get(0); + Rule ruleInfo = coRule.getRuleInfo(); + boolean redFlag = "true".equals(red); + if(!redFlag){ + // 如果不是红色 + log.info("发票章印泥颜色必须为红色检查>>Result>>{}", redFlag); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + + + //人员公司税号匹配规则 + if (ruleMap.containsKey("人员公司税号匹配规则") ) { + log.info("人员公司税号匹配规则>>"); + RuleConfig personalAndCompanyRule = ruleMap.get("人员公司税号匹配规则").get(0); + Rule ruleInfo = personalAndCompanyRule.getRuleInfo(); + String buyerNo = StringUtils.getStringWithOutSpecialCode(corporateInvoice.getBuyerNo()); + log.info("人员公司税号匹配规则> {}>>{}>>>>",corporateInvoice.getId(), buyerNo); + boolean flag = true; + Company company = companyMapper.checkCoAndTax(null, buyerNo); + if(null==company){ + log.info("人员公司税号匹配规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + }else{ + String companyName = StringUtils.getStringWithOutSpecialCode(company.getName()); + String invoiceBuyerName = StringUtils.getStringWithOutSpecialCode(corporateInvoice.getBuyer()); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(companyName)&&org.apache.commons.lang3.StringUtils.isNotEmpty(invoiceBuyerName)){ + if(!companyName.equals(invoiceBuyerName)){ + log.info("人员公司税号匹配规则>>ruleResult>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + }else{ + log.info("人员公司税号匹配规则>>Result>>{}", false); + message.append(ruleInfo.getMessageCn()).append(";"); + corporateInvoice.setStatus(2); + } + } + } + } + } diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/CurrencyServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/CurrencyServiceImpl.java new file mode 100644 index 0000000..dd18180 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/CurrencyServiceImpl.java @@ -0,0 +1,65 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.CurrencyService; +import com.cmsen.ticket.domain.entity.Currency; +import com.cmsen.ticket.domain.mapper.CurrencyMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author ran hao yu + * @date 2020/8/7 9:15 + * @description + */ +@Slf4j +@Service +public class CurrencyServiceImpl implements CurrencyService { + @Resource + private CurrencyMapper currencyMapper; + + @Override + public RestResponse selectList(String name) { + List maps = currencyMapper.selectList(name); + return RestResponse.success(maps); + } + + @Override + public RestResponse selectALlColumn(String tableName) { + List columns = currencyMapper.selectALlColumn(tableName); + if (columns != null) { + return RestResponse.success(columns); + } else { + return RestResponse.failure("查询失败"); + } + } + + @Override + public RestResponse insertActive(Map map) { + List columns = currencyMapper.selectALlColumn("currency"); + StringBuilder stringBuilder = new StringBuilder("insert into currency ("); + StringBuilder stringBuilder1 = new StringBuilder("values("); + for (String column : columns) { + stringBuilder.append(column).append(","); + } + String sqlColumn = stringBuilder.substring(0, stringBuilder.length() - 1); + sqlColumn = sqlColumn + ")"; + log.info(sqlColumn); + for (int i = 0; i < columns.size(); i++) { + stringBuilder1.append("\"").append(map.get(columns.get(i))).append("\"").append(","); + } + String sqlValue = stringBuilder1.substring(0, stringBuilder1.length() - 1); + sqlValue = sqlValue + ")"; + log.info(stringBuilder1.toString()); + log.info(sqlValue); + String s = sqlColumn + sqlValue; + int i = currencyMapper.insertActive(s); + return null; + } + + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/CustomerServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/CustomerServiceImpl.java new file mode 100644 index 0000000..e93951f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/CustomerServiceImpl.java @@ -0,0 +1,84 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.ticket.application.service.CustomerService; +import com.cmsen.ticket.domain.entity.Customer; +import com.cmsen.ticket.domain.mapper.CustomerMapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * (Customer)表服务实现类 + * + * @author ran hao yu + * @since 2020-09-18 14:11:43 + */ +@Service("customerService") +public class CustomerServiceImpl implements CustomerService { + @Resource + private CustomerMapper customerMapper; + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + @Override + public Customer queryById(Integer id) { + return this.customerMapper.queryById(id); + } + + /** + * 查询多条数据 + * + * @param offset 查询起始位置 + * @param limit 查询条数 + * @return 对象列表 + */ + @Override + public List queryAllByLimit(int offset, int limit) { + return this.customerMapper.queryAllByLimit(offset, limit); + } + + @Override + public List queryAll(Customer customer) { + return this.customerMapper.queryAll(customer); + } + + /** + * 新增数据 + * + * @param customer 实例对象 + * @return 实例对象 + */ + @Override + public Customer insert(Customer customer) { + this.customerMapper.insert(customer); + return customer; + } + + /** + * 修改数据 + * + * @param customer 实例对象 + * @return 实例对象 + */ + @Override + public Customer update(Customer customer) { + this.customerMapper.update(customer); + return this.queryById(customer.getId()); + } + + /** + * 通过主键删除数据 + * + * @param id 主键 + * @return 是否成功 + */ + @Override + public boolean deleteById(Integer id) { + return this.customerMapper.deleteById(id) > 0; + } +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/HelpServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/HelpServiceImpl.java new file mode 100644 index 0000000..931765f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/HelpServiceImpl.java @@ -0,0 +1,27 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.HelpService; +import com.cmsen.ticket.domain.entity.Help; +import com.cmsen.ticket.domain.mapper.HelpMapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * @author ran hao yu + * @date 2020/8/7 9:50 + * @description + */ +@Service +public class HelpServiceImpl implements HelpService { + @Resource + private HelpMapper helpMapper; + + @Override + public RestResponse selectList() { + List helps = helpMapper.selectList(); + return RestResponse.success(helps); + } +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/InternationalizationServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/InternationalizationServiceImpl.java new file mode 100644 index 0000000..61bac30 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/InternationalizationServiceImpl.java @@ -0,0 +1,70 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.InternationalizationService; +import com.cmsen.ticket.domain.entity.Internationalization; +import com.cmsen.ticket.domain.entity.User; +import com.cmsen.ticket.domain.entity.VerifiedUser; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.AppMenuMapper; +import com.cmsen.ticket.domain.mapper.InternationalizationMapper; +import com.cmsen.ticket.domain.mapper.UserMapper; +import com.cmsen.ticket.domain.mapper.VerifiedUserMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsenframework.security.RequestSecurityPolicy; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * @author ran hao yu + * @date 2020/8/4 15:48 + * @description 国际化接口调用层 + */ +@Service +public class InternationalizationServiceImpl implements InternationalizationService { + @Resource + private InternationalizationMapper mapper; + + @Resource + private AppMenuMapper appMenuMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private UserMapper userMapper; + + @Resource + private VerifiedUserMapper verifiedUserMapper; + + @Override + public RestResponse selectList() { + try { + List internationalizations = mapper.selectList(); + return RestResponse.success(internationalizations, "查询国际化数据成功"); + } catch (ServiceException e) { + throw new ServiceException(e); + } + } + + @Override + public RestResponse getAppMenus() { + + SysConfig sysConfig = sysConfigMapper.selectByCode("menu_show"); + if(sysConfig != null && sysConfig.getValue().equals("2")){//角色控制 + Integer userId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); + User user = userMapper.selectByPrimaryKey(userId); + VerifiedUser verifiedUser = verifiedUserMapper.checkByTel(user.getTel()); + if(verifiedUser == null){ + return RestResponse.failure("verifiedUser不存在,请检查"); + } + + return RestResponse.success(appMenuMapper.selByType(verifiedUser.getType())); + }else{ + return RestResponse.success(appMenuMapper.listActive()); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/SendMailServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/SendMailServiceImpl.java new file mode 100644 index 0000000..2cd6901 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/SendMailServiceImpl.java @@ -0,0 +1,178 @@ +package com.cmsen.ticket.application.service.impl; + +import com.cmsen.ticket.application.service.SendMailService; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; + +import javax.activation.DataHandler; +import javax.activation.FileDataSource; +import javax.annotation.Resource; +import javax.mail.Address; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.Multipart; +import javax.mail.internet.*; +import java.util.Date; + +/** + * @author ONE MORE THING + */ +@Slf4j +@Service +public class SendMailServiceImpl implements SendMailService { + + @Resource + private JavaMailSender javaMailSender; + + @Value("${spring.mail.username}") + private String from; + +// @Value("${mail-public.username}") +// private String pub_from; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Override + public Boolean sendVerifiedCode(String to, String verifiedCode) { + try { + String title = "智能发票助手"; + SysConfig sysConfig = sysConfigMapper.selectByCode("appletTitle_Cn"); + if(sysConfig != null){ + title = sysConfig.getValue(); + } + String text = "

Dear User: Your verification code is " + verifiedCode + ", valid for 5 minutes. Please verify ASAP.
"+ + "亲爱的用户:您的验证码是" + verifiedCode + " ,有效期为五分钟,请尽快完成验证。
"+ + "【"+title+"】

"; + log.info("sendVerifiedCode >> {} >> {}", to, verifiedCode); + MimeMessage message = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(title); + helper.setText(text, true); + javaMailSender.send(message); + return true; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return false; + } + + @Override + public Boolean sendVerifiedText(String to, String Text) { + try { + String title = "智能发票管家"; + SysConfig sysConfig = sysConfigMapper.selectByCode("appletTitle_Cn"); + if(sysConfig != null){ + title = sysConfig.getValue(); + } + + log.info("sendException >> {} >> {} >> {}", from, to, Text); + MimeMessage message = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(title); + helper.setText("

"+Text+"

", true); + javaMailSender.send(message); + return true; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return false; + } + + + @Override + public Boolean sendVerifiedText2(String to, String cc, String Text) { + try { + log.info("sendVerifiedText2 >> {} >> {} >> {} >> {}", from, to, cc, Text); + MimeMessage message = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setCc(cc); + helper.setSubject("易合宝-会议信息变更通知邮件"); + helper.setText("

"+Text+"

", true); + javaMailSender.send(message); + return true; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return false; + } + + @Override + public Boolean sendSubjectAndText(String to, String subject, String Text) { + try { + log.info("sendSubjectAndText >> {} >> {} >> {} >> {}", from, to, subject, Text); + MimeMessage message = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(subject); + helper.setText("

"+Text+"

", true); + javaMailSender.send(message); + return true; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return false; + } + + @Override + public Boolean sendFileAndText(String to, String text, String filePath) { + try { + + log.info("sendFileAndText >> {} >> {} >> {}", from, to, text); + MimeMessage message = javaMailSender.createMimeMessage(); + // 设置发件人邮箱地址 + message.setFrom(new InternetAddress(from, text, "UTF-8")); + // 设置收件人邮箱地址 + //message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")}); + /*设置收件人 + To收件人 CC 抄送 BCC密送*/ + Address[] internetAddressTo = new InternetAddress().parse(to); + message.setRecipients(Message.RecipientType.TO, internetAddressTo);//一个收件人 + // 多个收件人 + /*String[] split = emails.split(";"); + InternetAddress[] address = new InternetAddress[split.length]; + for (int i = 0; i < split.length; i++) { + address[i] = new InternetAddress(split[i]); + } + message.setRecipients(Message.RecipientType.TO, address); + */ + // 设置邮件标题 + message.setSubject("智能发票管家定时任务文件"); + // 创建消息部分 + BodyPart messageBodyPart = new MimeBodyPart(); + // 消息内容 + messageBodyPart.setText(text); + // 创建多重消息 + Multipart multipart = new MimeMultipart(); + // 设置文本消息部分 + multipart.addBodyPart(messageBodyPart); + + //创建附件节点 读取本地文件,并读取附件名称 + MimeBodyPart file = new MimeBodyPart(); + DataHandler dataHandler = new DataHandler(new FileDataSource(filePath)); + file.setDataHandler(dataHandler); + file.setFileName(MimeUtility.encodeText(dataHandler.getName())); + multipart.addBodyPart(file); + message.setSentDate(new Date()); + message.setContent(multipart); + javaMailSender.send(message); + return true; + }catch (Exception e){ + e.printStackTrace(); + } + return false; + } + +} diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/SupplierOutServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/SupplierOutServiceImpl.java index a94cb6d..c49a9e6 100644 --- a/src/main/java/com/cmsen/ticket/application/service/impl/SupplierOutServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/service/impl/SupplierOutServiceImpl.java @@ -9,6 +9,7 @@ import com.cmsen.common.util.DateFormat; import com.cmsen.common.util.JsonUtil; import com.cmsen.common.util.StringUtil; import com.cmsen.ticket.application.service.SupplierOutService; +import com.cmsen.ticket.application.service.WeiTaiOcrService; import com.cmsen.ticket.domain.entity.*; import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; import com.cmsen.ticket.domain.entity.manager.SysOrg; @@ -57,6 +58,9 @@ public class SupplierOutServiceImpl implements SupplierOutService { @Value("${spring.application.name}") private String applicationName; + @Resource + private WeiTaiOcrService weiTaiOcrService; + @Resource private SupplierMapper supplierMapper; @@ -66,6 +70,8 @@ public class SupplierOutServiceImpl implements SupplierOutService { @Resource private SupplierOrderMapper supplierOrderMapper; + @Resource + private TaxMappingMapper taxMappingMapper; @Resource private SysUserMapper sysUserMapper; @@ -404,6 +410,11 @@ public class SupplierOutServiceImpl implements SupplierOutService { List items = invoice.getItems(); //发票税率 String fpsl = items == null || items.isEmpty() ? "" : items.get(0).getTaxRate(); + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(fpsl); + + //发票税率 + String sl = taxMapping == null ? "" : taxMapping.getCode(); + //发票所属部门编码 String bmbm = sysOrg == null ? "" : sysOrg.getCode(); //发票代码 @@ -489,7 +500,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { xml.append("").append("fpsl").append(""); xml.append("").append("发票税率").append(""); xml.append("").append("varchar(999)").append(""); - xml.append("").append("").append(""); + xml.append("").append(sl).append(""); xml.append(""); xml.append(""); @@ -621,6 +632,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { SupplierOrder supplierOrder = supplierOrderMapper.selectByPrimaryKey(supplierOrderItemMatching.getOrderId()); //List lsItem = supplierOrderItemMatchingMapper.selectBySupplierOrderId(supplierOrder.getOrderNo()); CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(supplierOrderItemMatching.getInvoiceId()); + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(supplierOrderItemMatching.getTaxRate()); /*//明细ID String mainId = supplierOrder.getLineNum().toString(); @@ -677,6 +689,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { //金额 String je = supplierOrderItemMatching.getTotal().toString(); //发票税率 + String sl = taxMapping == null ? "" : taxMapping.getCode(); //发票税额 String s = supplierOrderItemMatching.getTax().toString(); // 20220905添加含税金额 @@ -710,7 +723,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { detail.setFphm(fphm); detail.setFpdm(fpdm); detail.setJe(je); - detail.setSl(""); + detail.setSl(sl); detail.setS(s); detail.setHszje(totalMoney.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); @@ -733,6 +746,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { SupplierOrderItemMatching supplierOrderItemMatching = supplierOrderItemMatchingMapper.selectByPrimaryKey(itemMatchingId); SupplierOrder supplierOrder = supplierOrderMapper.selectByPrimaryKey(supplierOrderItemMatching.getOrderId()); CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(supplierOrderItemMatching.getInvoiceId()); + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(supplierOrderItemMatching.getTaxRate()); //明细ID String mainId = supplierOrder.getLineNum().toString(); @@ -747,6 +761,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { //金额 String je = supplierOrderItemMatching.getTotal().toString(); //发票税率 + String sl = taxMapping == null ? "" : taxMapping.getCode(); //发票税额 String s = supplierOrderItemMatching.getTax().toString(); @@ -770,7 +785,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { detail.setFphm(fphm); detail.setFpdm(fpdm); detail.setJe(je); - detail.setSl(""); + detail.setSl(sl); detail.setS(s); List list = new ArrayList<>(); @@ -865,7 +880,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { xml.append(""); xml.append("").append("sl").append(""); - xml.append("").append("").append(""); + xml.append("").append(sl).append(""); xml.append("true"); xml.append("true"); xml.append(""); @@ -914,6 +929,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { SupplierOrderItemMatching supplierOrderItemMatching = supplierOrderItemMatchingMapper.selectByPrimaryKey(itemMatchingId); SupplierOrder supplierOrder = supplierOrderMapper.selectByPrimaryKey(supplierOrderItemMatching.getOrderId()); CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(supplierOrderItemMatching.getInvoiceId()); + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(supplierOrderItemMatching.getTaxRate()); //明细ID String mainId = supplierOrder.getLineNum().toString(); @@ -928,6 +944,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { //金额 String je = supplierOrderItemMatching.getTotal().toString(); //发票税率 + String sl = taxMapping == null ? "" : taxMapping.getCode(); //发票税额 String s = supplierOrderItemMatching.getTax().toString(); @@ -1005,7 +1022,7 @@ public class SupplierOutServiceImpl implements SupplierOutService { xml.append(""); xml.append("").append("sl").append(""); - xml.append("").append("").append(""); + xml.append("").append(sl).append(""); xml.append("true"); xml.append("true"); xml.append(""); diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/UserServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/UserServiceImpl.java index 3b22203..21392ad 100644 --- a/src/main/java/com/cmsen/ticket/application/service/impl/UserServiceImpl.java +++ b/src/main/java/com/cmsen/ticket/application/service/impl/UserServiceImpl.java @@ -12,17 +12,15 @@ import com.cmsen.common.util.DateFormat; import com.cmsen.common.util.JsonUtil; import com.cmsen.common.util.StorageCache; import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.service.SendMailService; import com.cmsen.ticket.application.service.UserService; -import com.cmsen.ticket.domain.entity.Customer; -import com.cmsen.ticket.domain.entity.User; -import com.cmsen.ticket.domain.entity.VerifiedUser; +import com.cmsen.ticket.domain.entity.*; import com.cmsen.ticket.domain.entity.manager.SysConfig; import com.cmsen.ticket.domain.entity.manager.SysUser; -import com.cmsen.ticket.domain.mapper.CustomerMapper; -import com.cmsen.ticket.domain.mapper.UserMapper; -import com.cmsen.ticket.domain.mapper.VerifiedUserMapper; +import com.cmsen.ticket.domain.mapper.*; import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.SmsUtil; import com.cmsenframework.security.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -38,6 +36,7 @@ import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.*; +import java.util.stream.Collectors; /** * @author ran hao yu @@ -70,7 +69,14 @@ public class UserServiceImpl implements UserService, UserDetailService { @Resource private SysUserMapper sysUserMapper; @Resource + private ProxyUserMapper proxyUserMapper; + @Resource + private UserConfigListMapper userConfigListMapper; + @Resource private CustomerMapper customerMapper; + @Resource + private SendMailService sendMailService; + @Resource private SysConfigMapper sysConfigMapper; @@ -484,10 +490,10 @@ public class UserServiceImpl implements UserService, UserDetailService { user.setTel(verifiedUser.getTel()); user.setChecked(0); userMapper.insert(user); -// proxyUserMapper.insert(new ProxyUser() {{ -// setMainId(user.getUserId()); -// setProxyId(user.getUserId()); -// }}); + proxyUserMapper.insert(new ProxyUser() {{ + setMainId(user.getUserId()); + setProxyId(user.getUserId()); + }}); }else{//存在 if(StringUtil.isBlank(userOpenId.getUnionid())){ userMapper.updateUnionId(unionId, userOpenId.getUserId()); @@ -510,12 +516,12 @@ public class UserServiceImpl implements UserService, UserDetailService { sendSmsSign = sysConfig.getValue(); } -// SmsUtil.sendSms(tel, code, sendSmsUrl, sendSmsSign); + SmsUtil.sendSms(tel, code, sendSmsUrl, sendSmsSign); } else { -// Boolean sendResult = sendMailService.sendVerifiedCode(tel, String.valueOf(code)); -// if (!sendResult) { -// return RestResponse.failure("验证码发送失败"); -// } + Boolean sendResult = sendMailService.sendVerifiedCode(tel, String.valueOf(code)); + if (!sendResult) { + return RestResponse.failure("验证码发送失败"); + } } StorageCache.write(tel, code, CODE_EXPIRE_TIME); return RestResponse.success(code); @@ -800,33 +806,32 @@ public class UserServiceImpl implements UserService, UserDetailService { @Transactional @Override public RestResponse addSendEmails(List emails) { -// try { -// Integer userId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); -// userConfigListMapper.deleteByUserIdAndType(userId, "EMAIL"); -// StringBuilder params = new StringBuilder(); -// emails.forEach(email -> params.append(email).append(";")); -// if (StringUtil.isNotEmpty(params.toString())) { -// userConfigListMapper.insert(new UserConfigList() {{ -// setUserId(userId); -// setParams1(params.toString()); -// setType("EMAIL"); -// }}); -// } -// return RestResponse.success(); -// } catch (Exception e) { -// log.error(e.getMessage(), e); -// throw new ServiceException("系统错误"); -// } - return null; + try { + Integer userId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); + userConfigListMapper.deleteByUserIdAndType(userId, "EMAIL"); + StringBuilder params = new StringBuilder(); + emails.forEach(email -> params.append(email).append(";")); + if (StringUtil.isNotEmpty(params.toString())) { + userConfigListMapper.insert(new UserConfigList() {{ + setUserId(userId); + setParams1(params.toString()); + setType("EMAIL"); + }}); + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } } @Override public RestResponse selectSendEmails() { -// Integer userId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); -// UserConfigList email = userConfigListMapper.selectByUserAndType(userId, "EMAIL"); -// if (email != null && StringUtil.isNotEmpty(email.getParams1())) { -// return RestResponse.success(Arrays.stream(email.getParams1().split(";")).collect(Collectors.toList())); -// } + Integer userId = Integer.valueOf(String.valueOf(RequestSecurityPolicy.getUserId())); + UserConfigList email = userConfigListMapper.selectByUserAndType(userId, "EMAIL"); + if (email != null && StringUtil.isNotEmpty(email.getParams1())) { + return RestResponse.success(Arrays.stream(email.getParams1().split(";")).collect(Collectors.toList())); + } return RestResponse.success(new ArrayList<>()); } diff --git a/src/main/java/com/cmsen/ticket/application/service/impl/WeiTaiOcrServiceImpl.java b/src/main/java/com/cmsen/ticket/application/service/impl/WeiTaiOcrServiceImpl.java new file mode 100644 index 0000000..ba04dd0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/service/impl/WeiTaiOcrServiceImpl.java @@ -0,0 +1,462 @@ +package com.cmsen.ticket.application.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ClientHttp; +import com.cmsen.common.http.ClientHttpRequest; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.service.WeiTaiOcrService; +import com.cmsen.ticket.domain.dto.ScannerInvoiceDto; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.baozun.InterfaceRequestEntity; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.entity.weitai.LineDOCUP; +import com.cmsen.ticket.domain.entity.weitai.OCREXPRESS; +import com.cmsen.ticket.domain.entity.weitai.SendResult; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SupplierOrderItemMatchingMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.PaginationUtil; +import com.cmsen.ticket.domain.util.StringUtils; +import lombok.Cleanup; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.*; + +@Service +@Slf4j +public class WeiTaiOcrServiceImpl implements WeiTaiOcrService { + + @Resource + private SupplierMapper supplierMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private InvokeContractMapper invokeContractMapper; + + @Resource + private InvokeInternalMapper invokeInternalMapper; + + @Resource + private InvokePurchaseMapper invokePurchaseMapper; + + @Resource + private SupplierOrderHeaderMapper supplierOrderHeaderMapper; + + @Resource + private SupplierOrderItemMatchingMapper supplierOrderItemMatchingMapper; + + @Resource + private SysUserMapper sysUserMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private CorporateInvoiceScannerFilesMapper corporateInvoiceScannerFilesMapper; + + private static final List statusList = new ArrayList() {{ + add("2"); + add("4"); + add("6"); + add("8"); + add("10"); + add("12"); + add("14"); + add("99"); + }}; + + //方法二:效率比较高 备注:pageSize集合显示的分组个数,soruceDatas为集合原数据 + private static List> groupByList(List sourceDatas, + int pageSize) { + // 分组集合 + List> groupLists = new ArrayList<>(); + // 分组数据 + List tempDatas = new ArrayList<>(); + if (sourceDatas != null && pageSize > 0) { + for (int i = 0; i < sourceDatas.size(); i++) { + if (i % pageSize == 0) { + if (!tempDatas.isEmpty()) { + groupLists.add(tempDatas); + } + tempDatas = new ArrayList<>(); + tempDatas.add(sourceDatas.get(i)); + } else { + tempDatas.add(sourceDatas.get(i)); + } + } + } + if (!tempDatas.isEmpty()) { + groupLists.add(tempDatas); + } + return groupLists; + } + + @Override + public RestResponse supplierList(Map params) { + PaginationUtil.paginationInit(params); + List list = supplierMapper.list(params); + int total = supplierMapper.count(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInsert(Supplier supplier) { + try { + Supplier supplierObj =supplierMapper.selectCodeByNameAndCode2("",supplier.getCode()); + if (supplierObj==null) { + if(supplier.getTaxNo()==null){ + supplier.setTaxNo(""); + } + supplierMapper.insertSelective(supplier); + }else{ + supplier.setId(supplierObj.getId()); + supplierMapper.updateByPrimaryKeySelective(supplier); + } + return RestResponse.success(supplier); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierInsertList(List ls) { + try { + for(Supplier supplier:ls) { + Supplier supplierObj = supplierMapper.selectCodeByNameAndCode2("", supplier.getCode()); + if (supplierObj == null) { + if (supplier.getTaxNo() == null) { + supplier.setTaxNo(""); + } + supplierMapper.insertSelective(supplier); + } else { + supplier.setId(supplierObj.getId()); + supplierMapper.updateByPrimaryKeySelective(supplier); + } + } + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierUpdate(Supplier supplier) { + try { + supplierMapper.updateByPrimaryKeySelective(supplier); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RestResponse supplierDelete(Integer id) { + try { + supplierMapper.deleteByPrimaryKey(id); + return RestResponse.success(); + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + + @Override + public RestResponse corInvoiceList(Map params) { + StringUtils.decoderUrl(params); + ScannerInvoiceDto result = new ScannerInvoiceDto(); + // 优先判断是否多文件已处理 + // "completed": true, // 文件处理返回状态 若 false 则 processStatus totalQty processedQty 都为null data 数组为[] + // "processStatus":"SUCCESS", //文件处理返回状态 信息 若 FAILED 则totalQty > processedQty + // "totalQty": 20, // 发票总数 + // "processedQty": 20, // 已完成发票总数 + List scannerFiles = corporateInvoiceScannerFilesMapper.list(params); + log.info("供应商发票查询 返回scannerFile结果size=>{}",scannerFiles.size()); + result.setTotalQty(scannerFiles.size()); + result.setCompleted(true); + result.setProcessedQty(0); + result.setProcessStatus("SUCCESS"); + boolean flag = true; + boolean flag2 = true; + if(scannerFiles.isEmpty()){ + log.info("供应商发票查询 返回scannerFile结果size = 0,返回空结果Completed false"); + result.setTotalQty(scannerFiles.size()); + result.setCompleted(true); + result.setProcessedQty(0); + result.setProcessStatus("NONE"); + return RestResponse.success(result); + } + for (CorporateInvoiceScannerFiles scannerFile : scannerFiles) { +// if(scannerFile.getOcrStatus()==0||scannerFile.getVerifyStatus()==0){ + if(scannerFile.getOcrStatus()==0){ + // 表示还有ocr没执行 + log.info("供应商发票查询 有OCR未执行"); + flag = false; +// result.setProcessStatus("FAILED"); + } + if(scannerFile.getOcrStatus()==2){ + // 表示出现了异常 + log.info("供应商发票查询 有OCR失败"); + flag2 = false; + } + if(scannerFile.getOcrStatus()==1&&scannerFile.getVerifyStatus()==1){ +// if(scannerFile.getOcrStatus()==1){ + // 表示 ocr和 验真都没问题 + log.info("供应商发票查询 ocr和验真均成功 数量+1"); + result.setProcessedQty(result.getProcessedQty()+1); + } + } + if(flag&&flag2){ + log.info("供应商发票查询 无错误信息"); + }else{ + if(!flag2){ + log.info("供应商发票查询 OCR失败情况返回空的结果集"); + result.setProcessStatus("FAILED"); + result.setData(Collections.emptyList()); + return RestResponse.success(result); + } + if(!flag){ + log.info("供应商发票查询 OCR还未执行完成 Completed false"); + result.setCompleted(false); + result.setProcessedQty(null); + result.setTotalQty(null); + result.setProcessStatus(null); + return RestResponse.success(result); + } + } + + PaginationUtil.paginationInit(params); + // list 和count都需要变更参数 + params.remove("startNo"); + params.remove("length"); + List list = corporateInvoiceMapper.list2(params); + log.info("供应商发票查询 正常返回结果集111111=》{}",JSON.toJSONString(list)); + + int total = corporateInvoiceMapper.count2(params); + Object o = PaginationUtil.getPageResult(total, params, list); + result.setData(o); + return RestResponse.success(result); + } + + @Override + public RestResponse corInvoiceAndPoAndDetailList(Map params) { + StringUtils.decoderUrl(params); + PaginationUtil.paginationInit(params); + // list 和count都需要变更参数 + List list = corporateInvoiceMapper.list6(params); + return RestResponse.success(list); + } + + private byte[] netImageToBytes(String netPath) { + try { + @Cleanup + ByteArrayOutputStream os = new ByteArrayOutputStream(); + URL url = new URL(netPath); + byte[] bytes = new byte[1024]; + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setConnectTimeout(5000); + @Cleanup + InputStream is = conn.getInputStream(); + int len = -1; + while ((len = is.read(bytes)) != -1) { + os.write(bytes, 0, len); + } + return os.toByteArray(); + } catch (Exception e) { + log.error(e.getMessage(), e); + return null; + } + } + + @Override + public RestResponse updateContractOwner(String jsonStr) { + log.info("updateContractOwner====jsonStr==>>{}",jsonStr); + InterfaceRequestEntity entity = JSONArray.parseObject(jsonStr,InterfaceRequestEntity.class); + InvokeContract invokeContract = invokeContractMapper.selectByRequestId(entity.getRequestId()); + if(invokeContract != null){ + String owner = invokeContract.getOwner()+","+entity.getOwner(); + invokeContractMapper.updateOwnerByRequestId(entity.getRequestId(), owner); + }else{ + return RestResponse.failure("requestId不存在"); + } + return RestResponse.success(); + } + + @Override + public RestResponse updateInternalOwner(String jsonStr) { + log.info("updateInternalOwner====jsonStr==>>{}",jsonStr); + InterfaceRequestEntity entity = JSONArray.parseObject(jsonStr,InterfaceRequestEntity.class); + InvokeInternal invokeInternal = invokeInternalMapper.selectByRequestId(entity.getRequestId()); + if(invokeInternal != null){ + String owner = invokeInternal.getOwner()+","+entity.getOwner(); + invokeInternalMapper.updateOwnerByRequestId(entity.getRequestId(), owner); + }else{ + return RestResponse.failure("requestId不存在"); + } + return RestResponse.success(); + } + + @Override + public RestResponse updateFlowOwner(String jsonStr) { + log.info("updateFlowOwner====jsonStr==>>{}",jsonStr); + InterfaceRequestEntity entity = JSONArray.parseObject(jsonStr,InterfaceRequestEntity.class); + String flowId = entity.getFlowId(); + SysConfig sysConfig = sysConfigMapper.selectByValue("WORKFLOW_", flowId); + if(sysConfig != null){ + String code = sysConfig.getCode(); + if(code.contains("CONTRACT")){//合同 + InvokeContract invokeContract = invokeContractMapper.selectByRequestId(entity.getRequestId()); + if(invokeContract != null){ + String owner = invokeContract.getOwner()+","+entity.getOwner(); + invokeContractMapper.updateOwnerByRequestId(entity.getRequestId(), owner); + }else{ + return RestResponse.failure("requestId不存在"); + } + } + if(code.contains("INTERNAL")){//内结 + InvokeInternal invokeInternal = invokeInternalMapper.selectByRequestId(entity.getRequestId()); + if(invokeInternal != null){ + String owner = invokeInternal.getOwner()+","+entity.getOwner(); + invokeInternalMapper.updateOwnerByRequestId(entity.getRequestId(), owner); + }else{ + return RestResponse.failure("requestId不存在"); + } + } + if(code.contains("PURCHASE")){//采购 + InvokePurchase invokePurchase = invokePurchaseMapper.selectByRequestId(entity.getRequestId()); + if(invokePurchase != null){ + String owner = invokePurchase.getExt02()+","+entity.getOwner(); + invokePurchaseMapper.updateOwnerByRequestId(entity.getRequestId(), owner); + }else{ + return RestResponse.failure("requestId不存在"); + } + } + }else{ + return RestResponse.failure("无效的flowId"); + } + + return RestResponse.success(); + } + + @Override + public RestResponse updateStatus(String jsonStr) { + log.info("updateStatus====jsonStr==>>{}",jsonStr); + InterfaceRequestEntity entity = JSONArray.parseObject(jsonStr,InterfaceRequestEntity.class); + String status = entity.getStatus(); + if(!statusList.contains(status)){ + return RestResponse.failure("status值不正确"); + } + Map params = new HashMap<>(); + SupplierOrderHeader header = supplierOrderHeaderMapper.selectByBillNum(entity.getRequestId()); + if(header != null){ + if(status.equals("8")){ + //判断是否是 后票、后票充值,是--则到下一流程 10-财务节点3 + /*if(!header.getInvoiceType().equals("后票") && !header.getInvoiceType().equals("后票充值")){ + status = "10"; + }*/ + //不包含 后票 --则到下一流程 10-财务节点3 + if(!header.getInvoiceType().contains("后票")){ + status = "10"; + } + if(header.getInvoiceType().equals("后票")){ + //更新匹配表的状态--0-匹配中 + supplierOrderItemMatchingMapper.updateByOrderNo(header.getBillId(),"0"); + } + } + if(status.equals("99")){//驳回 + //更新匹配表的状态--0-匹配中 + supplierOrderItemMatchingMapper.updateByOrderNo(header.getBillId(),"0"); + } + if(header.getInvoiceType().equals("后票充值") && status.equals("6") && StringUtil.isNotEmpty(entity.getFinApprover())){//出纳付款 + String[] aAIdArr = entity.getFinApprover().split(","); + String approver = ""; + for (String oaId : aAIdArr) { + SysUser sysUser = sysUserMapper.selectByOAId(oaId); + if(sysUser != null){ + approver += sysUser.getId() + ","; + } + } + params.put("owner",approver + header.getOwner()); + } + if(status.equals("2")){//上级审批 + //标记一个字段--用于不可撤回验证 + params.put("billNumber",entity.getRequestId()); + params.put("ext04","1"); + supplierOrderHeaderMapper.updateByParams(params); + } + if(status.equals("14")){//删除匹配行 + status = "12";//重新赋值为归档 + + //删除匹配记录 + supplierOrderItemMatchingMapper.deleteByOrderNo(header.getBillId()); + } + }else{ + return RestResponse.failure("requestId不存在"); + } + + //上级审批、空接口不处理状态 + if(!status.equals("2") && !status.equals("10")){ + params.put("billNumber",entity.getRequestId()); + params.put("status",status); + params.put("approvalComment",entity.getApprovalComment()); + supplierOrderHeaderMapper.updateByParams(params); + } + + return RestResponse.success(); + } + + @Override + public RestResponse updateMatchingStatus(String jsonStr) { + log.info("updateMatchingStatus====jsonStr==>>{}",jsonStr); + Map params = new HashMap<>(); + JSONObject jsonObject = JSON.parseObject(jsonStr); + JSONArray jsonArray = jsonObject.getJSONArray("data"); + for(int i=0; i 0) { + count = Math.min(max, count); + } + ItemView itemView = new ItemView(count); + // 设置按照时间顺序收取 + itemView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending); + FindItemsResults findResults = service.findItems(folder.getId(), itemView); + service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties); + + // 遍历邮件 + for (Item item : findResults.getItems()) { + item.move(folder.getId()); + // 下载附件 + if (!item.getHasAttachments()) continue; + for (Attachment attachment : item.getAttachments()) { + if (attachment instanceof FileAttachment) { + ((FileAttachment) attachment).load(attachmentFolder + attachment.getName()); + } + } + // 移动邮件 + try { + item.move(dest.getId()); + } catch (Exception e) { + log.info("移动邮件出错:{}", item.getSubject()); + } + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/util/ExpFormConvertUtil.java b/src/main/java/com/cmsen/ticket/application/util/ExpFormConvertUtil.java new file mode 100644 index 0000000..15291c7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/util/ExpFormConvertUtil.java @@ -0,0 +1,91 @@ +package com.cmsen.ticket.application.util; + +import com.alibaba.fastjson2.JSON; +import com.cmsen.ticket.domain.entity.ExpenseTypeActive; +import com.cmsen.ticket.domain.entity.hly.FormItem; +import com.cmsen.ticket.domain.entity.hly.ReportReceive; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ExpFormConvertUtil { + + // FormItem.value -> ReportReceiveLine实体属性映射 + private static final Map VALUE_TO_RECEIVE_PROP = new HashMap<>(); + static { + VALUE_TO_RECEIVE_PROP.put("ext31", "ext31"); + VALUE_TO_RECEIVE_PROP.put("ext32", "ext32"); + VALUE_TO_RECEIVE_PROP.put("ext33", "ext33"); + VALUE_TO_RECEIVE_PROP.put("ext34", "ext34"); + VALUE_TO_RECEIVE_PROP.put("ext35", "ext35"); + VALUE_TO_RECEIVE_PROP.put("ext36", "ext36"); + VALUE_TO_RECEIVE_PROP.put("EventCode", "ext21"); + VALUE_TO_RECEIVE_PROP.put("EventFull", "ext22"); + VALUE_TO_RECEIVE_PROP.put("SubType", "ext23"); + } + + // 自定义包装类,一次性存id+pid,避免两次Map + private static class ActiveIdPidDTO { + Integer id; + Integer pid; + ActiveIdPidDTO(Integer id, Integer pid) { + this.id = id; + this.pid = pid; + } + } + + /** + * 完整处理:替换id、替换pid、回填defaultValue,返回最终JSON字符串 + * @param jsonStr 原始表单JSON + * @param activeList 数据源:提供id、pid + * @param receive 数据源:提供defaultValue + * @return 处理后JSON字符串 + */ + public static String processFormJson(String jsonStr, List activeList, ReportReceive.ReportReceiveLine receive) { + // 1. JSON转对象列表 + List itemList = JSON.parseArray(jsonStr, FormItem.class); + + // 2. 预构建 value -> id+pid 映射表 + Map valueMap = new HashMap<>(); + for (ExpenseTypeActive active : activeList) { + valueMap.put(active.getValue(), new ActiveIdPidDTO(active.getId(), active.getPid())); + } + + // 3. 遍历逐条赋值 + for (FormItem item : itemList) { + String itemValue = item.getValue(); + ActiveIdPidDTO dto = valueMap.get(itemValue); + + // 匹配到:同时替换id、pid + if (dto != null) { + item.setId(dto.id); + item.setPid(String.valueOf(dto.pid)); + } + + // 原有逻辑:替换defaultValue + String receiveProp = VALUE_TO_RECEIVE_PROP.get(itemValue); + if (receiveProp != null) { + String realVal = getFieldValue(receive, receiveProp); + if (realVal != null) { + item.setDefaultValue(realVal); + } + } + } + + // 转回JSON字符串返回 + return JSON.toJSONString(itemList); + } + + // 反射取值 + private static String getFieldValue(ReportReceive.ReportReceiveLine receive, String fieldName) { + try { + Field field = ReportReceive.ReportReceiveLine.class.getDeclaredField(fieldName); + field.setAccessible(true); + return (String) field.get(receive); + } catch (Exception e) { + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/util/FormFillUtil.java b/src/main/java/com/cmsen/ticket/application/util/FormFillUtil.java new file mode 100644 index 0000000..f969977 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/util/FormFillUtil.java @@ -0,0 +1,57 @@ +package com.cmsen.ticket.application.util; + +import com.alibaba.fastjson2.JSON; +import com.cmsen.ticket.domain.entity.hly.FormItem; +import com.cmsen.ticket.domain.entity.hly.ReportReceive; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FormFillUtil { + + // value -> ReportReceive真实属性名 + private static final Map VALUE_PROP_MAP = new HashMap<>(); + static { + VALUE_PROP_MAP.put("ou1", "ext11"); + VALUE_PROP_MAP.put("ou2", "ext12"); + VALUE_PROP_MAP.put("ou3", "ext13"); + VALUE_PROP_MAP.put("ou4", "ext14"); + VALUE_PROP_MAP.put("ou5", "ext15"); + VALUE_PROP_MAP.put("WBS", "ext17"); + VALUE_PROP_MAP.put("费用期间", "ext18"); + VALUE_PROP_MAP.put("业务描述", "ext19"); + VALUE_PROP_MAP.put("备注", "ext20"); + } + + /** + * 批量回填defaultValue + */ + public static String fillDefaultValue(List itemList, ReportReceive receive) { + for (FormItem item : itemList) { + String value = item.getValue(); + String realProp = VALUE_PROP_MAP.get(value); + if (realProp == null) { + continue; // 无映射,跳过不修改 + } + String val = getReceiveFieldValue(receive, realProp); + if (val != null) { + item.setDefaultValue(val); + } + } + + return JSON.toJSONString(itemList); + } + + // 反射获取ReportReceive指定属性值 + private static String getReceiveFieldValue(ReportReceive receive, String fieldName) { + try { + Field field = ReportReceive.class.getDeclaredField(fieldName); + field.setAccessible(true); + return (String) field.get(receive); + } catch (Exception e) { + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/application/util/RedisUtils.java b/src/main/java/com/cmsen/ticket/application/util/RedisUtils.java new file mode 100644 index 0000000..be58473 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/application/util/RedisUtils.java @@ -0,0 +1,71 @@ +//package com.cmsen.ticket.application; +// +//import lombok.extern.log4j.Log4j2; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.stereotype.Component; +// +//import javax.annotation.Resource; +//import java.util.HashSet; +//import java.util.Set; +//import java.util.concurrent.TimeUnit; +// +///** +// * @author OWTS +// */ +//@Slf4j +//@Component +//public class RedisUtils { +// +// public final String KEY_IMAGE = "SCAN_IMAGE:"; +// +// @Resource +// private RedisTemplate redisTemplate; +// +// public boolean hasKey(String key) { +// try { +// return redisTemplate.hasKey(key); +// } catch (Exception e) { +// log.error(e.getMessage(), e); +// return false; +// } +// } +// +// public void del(String... keys) { +// if (keys != null && keys.length > 0) { +// Set keySets = new HashSet<>(); +// for (String key : keys) { +// keySets.addAll(redisTemplate.keys(key)); +// } +// redisTemplate.delete(keySets); +// } +// } +// +// public Object get(String key) { +// return key == null ? null : redisTemplate.opsForValue().get(key); +// } +// +// public boolean set(String key, Object value, long time) { +// try { +// if (time > 0) { +// redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); +// } else { +// set(key, value); +// } +// return true; +// } catch (Exception e) { +// log.error(e.getMessage(), e); +// return false; +// } +// } +// +// public boolean set(String key, Object value) { +// try { +// log.info("Redis put key >> {} >> value >> {}", key, value); +// redisTemplate.opsForValue().set(key, value); +// return true; +// } catch (Exception e) { +// log.error(e.getMessage(), e); +// return false; +// } +// } +//} diff --git a/src/main/java/com/cmsen/ticket/bestsign/client/BestSignClient.java b/src/main/java/com/cmsen/ticket/bestsign/client/BestSignClient.java new file mode 100644 index 0000000..d2c344b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/client/BestSignClient.java @@ -0,0 +1,204 @@ +package com.cmsen.ticket.bestsign.client; + +import com.alibaba.fastjson.JSONObject; +import com.cmsen.ticket.bestsign.encrypt.MD5Utils; +import com.cmsen.ticket.bestsign.encrypt.RSAUtils; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import okhttp3.*; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * @Auther: xp + * @Date: 2022-07-09 + * @Description: com.jeeplus.modules.contract.bestsign.client + * @version: 1.0 + */ +@Slf4j +public class BestSignClient { + + + private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8"); + + + private final ObjectMapper objectMapper = new ObjectMapper(); + + //shared perform best + private final OkHttpClient okHttpClient = new OkHttpClient + .Builder() + .readTimeout(1, TimeUnit.MINUTES) + .build(); + + + /** + * @param uriWithParam 请求的URL和参数 + * @param method HTTP请求动词 + * @param requestData 请求的内容 + * + * @return JSON字符串 + */ + public String executeRequest(String uriWithParam, String token, String method, Object requestData,Map params) { + int retryTime = 3; + while (retryTime > 0) { + Long timestamp = System.currentTimeMillis(); + String urlWithQueryParam = String.format("%s%s", params.get("BS_host"), uriWithParam); + String signTemp = ""; + + try { + //queryToken(); + final String signRSA = signRequest(uriWithParam, timestamp, requestData, params); + signTemp = signRSA; + Headers headers = new Headers + .Builder() + .add("content-type", "application/json") + .add("bestsign-client-id", params.get("BS_clientId")) + .add("bestsign-sign-timestamp", timestamp.toString()) + .add("bestsign-signature-type", "RSA256") + .add("bestsign-signature", signRSA) + .add("Authorization", "bearer " + token) + .build(); + + final Request.Builder requestBuilder = new Request + .Builder() + .url(urlWithQueryParam) + .headers(headers); + + if (Objects.equals(method.toUpperCase(), "GET")) { + requestBuilder.get(); + } else { + final RequestBody requestBody = RequestBody.create(JSON_TYPE, requestData == null ? "" : requestData.toString()); + requestBuilder.method(method.toUpperCase(), requestBody); + } + + final Response response = okHttpClient.newCall(requestBuilder.build()).execute(); + System.out.println("response==={}"+response); + if (response.code() == 401) { + // token失效, 重新获取token + //invalidToken(token); + } else if (response.code() == 200) { + if(response.headers().get("Content-Type").equals("application/zip") || response.headers().get("Content-Type").equals("application/pdf")) { + return response.body().string(); + } + return response.body() != null ? response.body().string() : null; + }else{ + System.out.println(timestamp.toString()); + System.out.println(signTemp); + System.out.println(token); + System.out.println(urlWithQueryParam); + System.out.println(params); + } + retryTime--; + } catch (Exception ex) { + retryTime--; + ex.printStackTrace(); + System.out.println(timestamp.toString()); + System.out.println(signTemp); + System.out.println(token); + System.out.println(urlWithQueryParam); + System.out.println(params); + } + + } + return null; + } + + /** + * @param uriWithParam 请求的URL和参数 + * @param method HTTP请求动词 + * @param requestData 请求的内容 + * + * @return JSON字符串 + */ + public String executeRequestFile(String uriWithParam, String token, String method, Map requestData, Map params, List mfiles) { + int retryTime = 3; + while (retryTime > 0) { + Long timestamp = System.currentTimeMillis(); + String urlWithQueryParam = String.format("%s%s", params.get("HLY_host"), uriWithParam); + String signTemp = ""; + + try { + JSONObject json2 = new JSONObject(); + Headers headers = new Headers + .Builder() + .add("content-type", "multipart/form-data") + .add("enctype", "multipart/form-data") + .add("Authorization", "Bearer " + token) + .build(); + + //.build(); + + + //把参数传进Map中 + Map paramsMap= requestData; + final MultipartBody.Builder requestBuilder = new MultipartBody.Builder(); + for (String key : paramsMap.keySet()) { + //追加表单信息 + requestBuilder.addFormDataPart(key, paramsMap.get(key)); + } + // 添加文件 + for (String key : mfiles) { + File file = new File(key); + //追加表单信息 + requestBuilder.addFormDataPart("attachments", file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),file)); + } + //MultipartBody.Builder requestBody = new MultipartBody.Builder() + requestBuilder.setType(MultipartBody.FORM); + Request request = new Request.Builder() + .headers(headers) + .url(urlWithQueryParam) + .post(requestBuilder.build()) + .build(); + final Response response = okHttpClient.newCall(request).execute(); + log.info("response==={}",response); + if (response.code() == 200) { + + return response.body() != null ? response.body().string() : null; + }else{ + log.info(timestamp.toString()); + log.info(signTemp); + log.info(token); + log.info(urlWithQueryParam); + log.info("请求参数{}",params); + } + retryTime--; + } catch (Exception ex) { + retryTime--; + ex.printStackTrace(); + log.info(timestamp.toString()); + log.info(signTemp); + log.info(token); + log.info(urlWithQueryParam); + log.info("请求参数{}",params); + } + + } + return null; + } + + /** + * 数据加密 + * @param uriWithParam + * @param timestamp + * @param requestData + * @param params + * @return + * @throws Exception + */ + private String signRequest(String uriWithParam, Long timestamp, Object requestData,Map params) throws Exception { + String content = String.format( + "bestsign-client-id=%sbestsign-sign-timestamp=%sbestsign-signature-type=%srequest-body=%suri=%s", + params.get("BS_clientId"), + timestamp.toString(), + "RSA256", + MD5Utils.stringMD5(requestData == null ? "" : requestData.toString()), + uriWithParam); + + return RSAUtils.signRSA(content, params.get("BS_privateKey")); + } + +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/encrypt/AESCoder.java b/src/main/java/com/cmsen/ticket/bestsign/encrypt/AESCoder.java new file mode 100644 index 0000000..063aefd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/encrypt/AESCoder.java @@ -0,0 +1,115 @@ +package com.cmsen.ticket.bestsign.encrypt; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + * Created by whthomas on 15/6/23. + */ +public class AESCoder { + + public static final String KEY_ALGORITHM = "AES"; + + public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; + // public static final String CIPHER_ALGORITHM = "AES"; + + // 转换密钥 + private static Key toKey(byte[] key) { + + KeyGenerator keyGenerator = null; + try { + keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); + } catch (NoSuchAlgorithmException ex) { + ex.printStackTrace(); + return null; + } + + SecureRandom secureRandom; + try { + secureRandom = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException ex) { + ex.printStackTrace(); + return null; + } + secureRandom.setSeed(key); + + keyGenerator.init(128, secureRandom); + + // 实例化DES的材料 + SecretKey secretKey = keyGenerator.generateKey(); + return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM); + } + + /** + * 解密 + */ + public static byte[] decrypt(byte[] data, byte[] key) { + // 还原密钥 + Key translatedKey = toKey(key); + try { + // 实例化 + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + // 初始化,设置为解密模式 + cipher.init(Cipher.DECRYPT_MODE, translatedKey); + // 执行操作 + return cipher.doFinal(data); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + public static String decryptAsString(byte[] data, byte[] key) { + return new String(decrypt(data, key)); + } + + /** + * 加密 + */ + public static byte[] encrypt(byte[] data, byte[] key) { + // 还原密钥 + Key traslatedKey = toKey(key); + try { + // 实例化 + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, traslatedKey); + // 执行操作 + return cipher.doFinal(data); + } catch (Exception ex) { + return null; + } + } + + /** + * 生成密钥 + * + * @return + * @throws Exception + */ + public static byte[] initKey() { + + // 实例化 + KeyGenerator kg = null; + try { + kg = KeyGenerator.getInstance(KEY_ALGORITHM); + } catch (NoSuchAlgorithmException ex) { + ex.printStackTrace(); + return null; + } + + // 要求密钥长度为256 + kg.init(256); + + // 生成秘密密钥 + SecretKey secretKey = kg.generateKey(); + + // 获得秘密密钥 + return secretKey.getEncoded(); + } + +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/encrypt/HexUtils.java b/src/main/java/com/cmsen/ticket/bestsign/encrypt/HexUtils.java new file mode 100644 index 0000000..8644067 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/encrypt/HexUtils.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.bestsign.encrypt; + +/** + * @author whthomas + * @date 2018/6/17 + */ +public class HexUtils { + + private final static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + + public static String byteArrayToHex(byte[] byteArray) { + // 首先初始化一个字符数组,用来存放每个16进制字符 + + // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) + char[] resultCharArray = new char[byteArray.length * 2]; + // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 + int index = 0; + for (byte b : byteArray) { + resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; + resultCharArray[index++] = hexDigits[b & 0xf]; + } + // 字符数组组合成字符串返回 + return new String(resultCharArray).toLowerCase(); + } + +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/encrypt/MD5Utils.java b/src/main/java/com/cmsen/ticket/bestsign/encrypt/MD5Utils.java new file mode 100644 index 0000000..c0ae48b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/encrypt/MD5Utils.java @@ -0,0 +1,52 @@ +package com.cmsen.ticket.bestsign.encrypt; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import static com.cmsen.ticket.bestsign.encrypt.HexUtils.byteArrayToHex; + + +/** + * @author jozdoo + * @company 杭州尚尚签网络科技有限公司 + * @date 16/8/31 + * @since 3.0 + */ +public class MD5Utils { + + public static String stringMD5(String input) { + try { + // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + // 输入的字符串转换成字节数组 + byte[] inputByteArray = input.getBytes("UTF-8"); + // inputByteArray是输入字符串转换得到的字节数组 + messageDigest.update(inputByteArray); + // 转换并返回结果,也是字节数组,包含16个元素 + byte[] resultByteArray = messageDigest.digest(); + // 字符数组转换成字符串返回 + return byteArrayToHex(resultByteArray); + } catch (NoSuchAlgorithmException e) { + return null; + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("md5 request body fail. "+input); + } + } + + public static String stringMD5(byte[] inputByteArray) { + try { + // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + // inputByteArray是输入字符串转换得到的字节数组 + messageDigest.update(inputByteArray); + // 转换并返回结果,也是字节数组,包含16个元素 + byte[] resultByteArray = messageDigest.digest(); + // 字符数组转换成字符串返回 + return byteArrayToHex(resultByteArray); + } catch (NoSuchAlgorithmException e) { + return null; + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/encrypt/RSAUtils.java b/src/main/java/com/cmsen/ticket/bestsign/encrypt/RSAUtils.java new file mode 100644 index 0000000..7d22007 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/encrypt/RSAUtils.java @@ -0,0 +1,79 @@ +package com.cmsen.ticket.bestsign.encrypt; + + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +public class RSAUtils { + + private static final String SIGNATURE_ALGORITHM = "SHA256withRSA"; + private static final String CHARSET = "utf-8"; + + private static String signSHA256RSA(String input, String privateKey) throws Exception { + + byte[] b1 = Base64.getDecoder().decode(privateKey.getBytes()); + + KeyFactory kf; + try { + kf = KeyFactory.getInstance("RSA"); + + Signature privateSignature = Signature.getInstance(SIGNATURE_ALGORITHM); + + privateSignature.initSign(kf.generatePrivate(new PKCS8EncodedKeySpec(b1))); + + privateSignature.update(input.getBytes("UTF-8")); + + byte[] s = privateSignature.sign(); + //先base64 在urlEncoder + return URLEncoder.encode(Base64.getEncoder().encodeToString(s), CHARSET); + + } catch (Exception e) { + throw new Exception(e); + } + + } + + public static boolean verifySHA256RSA(byte[] data, String sign, String publicKey) throws Exception { + + try { + + sign = URLDecoder.decode(sign, CHARSET); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + + PublicKey pubKey = keyFactory + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey.getBytes()))); + + Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); + + signature.initVerify(pubKey); + signature.update(data); + + return signature.verify(Base64.getDecoder().decode(sign.getBytes())); + + } catch (Exception e) { // 签名数据失败 + throw new Exception(e); + } + + } + + public static String signRSA(String content, String privateKey) throws Exception { + return signSHA256RSA(content, privateKey); + } + + public static boolean verifySHA256RSA(String data, String sign, String publicKey) throws Exception { + + try { + return verifySHA256RSA(data.getBytes("UTF-8"), sign, publicKey); + } catch (UnsupportedEncodingException e) { + throw new Exception(e); + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/entity/TokenDataPojo.java b/src/main/java/com/cmsen/ticket/bestsign/entity/TokenDataPojo.java new file mode 100644 index 0000000..023f83a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/entity/TokenDataPojo.java @@ -0,0 +1,55 @@ +package com.cmsen.ticket.bestsign.entity; + +/** + * @Auther: xp + * @Date: 2022-07-08 + * @Description: com.jeeplus.modules.contract.util + * @version: 1.0 + */ +public class TokenDataPojo { + private String tokenType; + private String accessToken; + private String refreshToken; + private String expiration; + private String expiresIn; + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public String getExpiration() { + return expiration; + } + + public void setExpiration(String expiration) { + this.expiration = expiration; + } + + public String getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(String expiresIn) { + this.expiresIn = expiresIn; + } +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/entity/TokenPojo.java b/src/main/java/com/cmsen/ticket/bestsign/entity/TokenPojo.java new file mode 100644 index 0000000..5f556a3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/bestsign/entity/TokenPojo.java @@ -0,0 +1,46 @@ +package com.cmsen.ticket.bestsign.entity; + +/** + * @Auther: xp + * @Date: 2022-07-08 + * @Description: com.jeeplus.modules.contract.util + * @version: 1.0 + */ +public class TokenPojo { + private String code; + private String message; + private String access_token; + private TokenDataPojo data; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public TokenDataPojo getData() { + return data; + } + + public void setData(TokenDataPojo data) { + this.data = data; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } +} diff --git a/src/main/java/com/cmsen/ticket/bestsign/util/InterfaceUtil.java b/src/main/java/com/cmsen/ticket/bestsign/util/InterfaceUtil.java index d54c35c..d3ae72e 100644 --- a/src/main/java/com/cmsen/ticket/bestsign/util/InterfaceUtil.java +++ b/src/main/java/com/cmsen/ticket/bestsign/util/InterfaceUtil.java @@ -110,7 +110,7 @@ public class InterfaceUtil { .addHeader("Authorization", params.get("Authorization")) .addHeader("Content-Type", params.get("Content-Type")) .addHeader("cache-control", "no-cache") -// .addHeader("X-Trace-Id", traceId) + .addHeader("X-Trace-Id", traceId) // .addHeader("Postman-Token", "d0b912ca-ddda-4287-ad15-54d6ce95e181") .build(); /*Response response = client.newCall(request).execute(); diff --git a/src/main/java/com/cmsen/ticket/domain/dto/ScannerInvoiceDto.java b/src/main/java/com/cmsen/ticket/domain/dto/ScannerInvoiceDto.java new file mode 100644 index 0000000..87b2888 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/dto/ScannerInvoiceDto.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ScannerInvoiceDto { + + private boolean completed; + private String processStatus; + private Integer totalQty; + private Integer processedQty; + private Object data; +} diff --git a/src/main/java/com/cmsen/ticket/domain/dto/SmartImageCheckListSearchDto.java b/src/main/java/com/cmsen/ticket/domain/dto/SmartImageCheckListSearchDto.java new file mode 100644 index 0000000..1a8680c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/dto/SmartImageCheckListSearchDto.java @@ -0,0 +1,41 @@ +package com.cmsen.ticket.domain.dto; + +import com.cmsen.ticket.domain.response.PageDto; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/9/9 16:22 + **/ +@EqualsAndHashCode(callSuper = true) +@Data +public class SmartImageCheckListSearchDto extends PageDto { + @ApiModelProperty("日期起 yyyy-MM-dd") + private String dateStart; + @ApiModelProperty("日期止 yyyy-MM-dd") + private String dateEnd; + @ApiModelProperty("报告名称") + private String reportName; + @ApiModelProperty("报告ID") + private String reportId; + @ApiModelProperty("组织") + private String organization; + @ApiModelProperty("提交人") + private String submiter; + @ApiModelProperty("处理状态 0 待处理 1 待审核 2 通过 3 已处理 4 驳回 5 关闭") + private Integer processingState; + @ApiModelProperty("单据状态") + private String reportStatus; + + @ApiModelProperty(hidden = true) + private String username; + + @ApiModelProperty("显示全部") + private String showAll;//显示全部:''则不显示,非''则显示全部 + + @ApiModelProperty("policy") + private String policy; +} diff --git a/src/main/java/com/cmsen/ticket/domain/dto/SqlDownloadDto.java b/src/main/java/com/cmsen/ticket/domain/dto/SqlDownloadDto.java new file mode 100644 index 0000000..96eb741 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/dto/SqlDownloadDto.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.domain.dto; + +import lombok.Data; + +/** + * @author OWTS + */ +@Data +public class SqlDownloadDto { + private String statement; + private String pageNo; + private String pageSize; +} diff --git a/src/main/java/com/cmsen/ticket/domain/dto/SupplierMainDataDto.java b/src/main/java/com/cmsen/ticket/domain/dto/SupplierMainDataDto.java new file mode 100644 index 0000000..48f66a0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/dto/SupplierMainDataDto.java @@ -0,0 +1,70 @@ +package com.cmsen.ticket.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/10/27 15:08 + **/ +@Data +public class SupplierMainDataDto { + @ApiModelProperty("标题") + private String bt; + @ApiModelProperty("流程编号") + private String liushuihao; + @ApiModelProperty("Request Id") + private String requestid; + @ApiModelProperty("申请人姓名") + private String shenqingren; + @ApiModelProperty("工号") + private String workcode; + @ApiModelProperty("一级部门") + private String fb; + @ApiModelProperty("二级部门") + private String sshy; + @ApiModelProperty("末级部门") + private String bm; + @ApiModelProperty("所属公司") + private String company; + @ApiModelProperty("供应商名称") + private String fkgongyingsh; + @ApiModelProperty("供应商编号") + private String gysbh; + @ApiModelProperty("发票类型") + private String fplx; + @ApiModelProperty("币种") + private String bizhong; + @ApiModelProperty("操作人") + private String czr; + @ApiModelProperty("workflowid") + private String workflowid; + @ApiModelProperty("流程行") + private List processItems; + + + @lombok.Data + public static class LineData { + @ApiModelProperty("日期") + private String fyfsrquser; + @ApiModelProperty("费用类型") + private String fylx; + @ApiModelProperty("付款金额") + private String fkje; + @ApiModelProperty("成本中心") + private String cbzx; + @ApiModelProperty("发票金额") + private String fphsje; + @ApiModelProperty("发票号") + private String fph; + @ApiModelProperty("税额") + private String fpsekdk; + @ApiModelProperty("明细ID") + private String mianid; + @ApiModelProperty("付款理由") + private String fkyybz; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AbPolicyItem.java b/src/main/java/com/cmsen/ticket/domain/entity/AbPolicyItem.java new file mode 100644 index 0000000..8f32675 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AbPolicyItem.java @@ -0,0 +1,79 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author OWTS + */ +@NoArgsConstructor +@Data +public class AbPolicyItem { + @JsonProperty("id") + private String id; + @JsonProperty("remarks") + private Object remarks; + @JsonProperty("createBy") + private String createBy; + @JsonProperty("createDate") + private String createDate; + @JsonProperty("updateBy") + private String updateBy; + @JsonProperty("updateDate") + private String updateDate; + @JsonProperty("runFlag") + private String runFlag; + @JsonProperty("runBatch") + private String runBatch; + @JsonProperty("policyId") + private String policyId; + @JsonProperty("policyName") + private String policyName; + @JsonProperty("recipientName") + private String recipientName; + @JsonProperty("recipientPosition") + private String recipientPosition; + @JsonProperty("poOrganization") + private String poOrganization; + @JsonProperty("poDesc") + private String poDesc; + @JsonProperty("poReceivedDate") + private String poReceivedDate; + @JsonProperty("offerorName") + private String offerorName; + @JsonProperty("offerorPosition") + private String offerorPosition; + @JsonProperty("poOfferingDate") + private String poOfferingDate; + @JsonProperty("poRecipientPer") + private String poRecipientPer; + @JsonProperty("ownerUrl") + private String ownerUrl; + @JsonProperty("ownerName") + private String ownerName; + @JsonProperty("ownerEmail") + private String ownerEmail; + @JsonProperty("attributer1") + private String attributer1; + @JsonProperty("attributer2") + private String attributer2; + @JsonProperty("attributer3") + private String attributer3; + @JsonProperty("attributer4") + private String attributer4; + @JsonProperty("attributer5") + private String attributer5; + @JsonProperty("attributer6") + private String attributer6; + @JsonProperty("attributer7") + private String attributer7; + @JsonProperty("attributer8") + private String attributer8; + @JsonProperty("attributer9") + private String attributer9; + @JsonProperty("attributer10") + private String attributer10; + @JsonProperty("listItemId") + private String listItemId; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AccountMapping.java b/src/main/java/com/cmsen/ticket/domain/entity/AccountMapping.java new file mode 100644 index 0000000..2555c1b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AccountMapping.java @@ -0,0 +1,49 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 费用科目表 + * @TableName expense_subject + */ +@Data +public class AccountMapping implements Serializable { + /** + * 主键ID + */ + private Integer id; + + /** + * 类型 + */ + private String type; + + /** + * 借方科目1 + */ + private String debitAccount1; + + /** + * 贷方科目1 + */ + private String creditSubject1; + + /** + * 借方科目2 + */ + private String debitAccount2; + + /** + * 贷方科目2 + */ + private String creditSubject2; + + /** + * 大类 + */ + private String category; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AccountObject.java b/src/main/java/com/cmsen/ticket/domain/entity/AccountObject.java new file mode 100644 index 0000000..af1be1c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AccountObject.java @@ -0,0 +1,44 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 科目 + * @TableName account_object + */ +@Data +public class AccountObject implements Serializable { + /** + * + */ + private Integer id; + + /** + * 科目类别 + */ + private String category; + + /** + * 科目 + */ + private String account; + + /** + * 描述 + */ + private String description; + + /** + * 级别 + */ + private String level; + + /** + * 备注 + */ + private String remark; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AccountPeriod.java b/src/main/java/com/cmsen/ticket/domain/entity/AccountPeriod.java new file mode 100644 index 0000000..b39b6a0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AccountPeriod.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * + * @TableName account_period + */ +@Data +public class AccountPeriod implements Serializable { + + private static final long serialVersionUID = 1L; + /** + * + */ + private Integer id; + + /** + * + */ + private String status; + + /** + * + */ + private String period; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AppMenu.java b/src/main/java/com/cmsen/ticket/domain/entity/AppMenu.java new file mode 100644 index 0000000..a2c8aa1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AppMenu.java @@ -0,0 +1,44 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +import java.io.Serializable; + +/** + * @TableName app_menu + */ +@Data +public class AppMenu implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + @JsonIgnoreProperties + private Integer id; + /** + * + */ + private String pagePath; + /** + * + */ + private String iconPath; + /** + * + */ + private String selectedIconPath; + /** + * + */ + private String text; + /** + * + */ + private String enText; + /** + * + */ + @JsonIgnoreProperties + private Boolean active; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/AttendOrg.java b/src/main/java/com/cmsen/ticket/domain/entity/AttendOrg.java new file mode 100644 index 0000000..e807f37 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/AttendOrg.java @@ -0,0 +1,70 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * attend_org + * @author + */ +@Data +public class AttendOrg implements Serializable { + private Integer id; + + /** + * 父id + */ + private Integer pid; + + /** + * 组织CODE + */ + private String orgCode; + + /** + * 组织名称 + */ + private String orgName; + + private String isDel; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + /** + * 备注 + */ + private String remark; + + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/BandAreaConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/BandAreaConfig.java new file mode 100644 index 0000000..6d2b5c4 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/BandAreaConfig.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/22 10:54 + */ +@Data +public class BandAreaConfig implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private String band; + private String area; + private String hotel; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/BandConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/BandConfig.java new file mode 100644 index 0000000..266d21f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/BandConfig.java @@ -0,0 +1,50 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/22 10:53 + */ +@Data +public class BandConfig implements Serializable { + private static final long serialVersionUID = 1L; + @ExcelIgnore + private Integer id; + @ExcelProperty(value = "band", index = 0) + private String bandValue; + @ExcelProperty(value = "area", index = 1) + private String area; + @ExcelProperty(value = "item", index = 2) + private String item; + @ExcelProperty(value = "rate", index = 3) + private String rate; + @ExcelProperty(value = "ext01", index = 4) + private String ext01; + @ExcelProperty(value = "ext02", index = 5) + private String ext02; + @ExcelProperty(value = "ext03", index = 6) + private String ext03; + @ExcelProperty(value = "ext04", index = 7) + private String ext04; + @ExcelProperty(value = "ext05", index = 8) + private String ext05; + @ExcelProperty(value = "ext06", index = 9) + private String ext06; + @ExcelProperty(value = "ext07", index = 10) + private String ext07; + @ExcelProperty(value = "ext08", index = 11) + private String ext08; + @ExcelProperty(value = "ext09", index = 12) + private String ext09; + @ExcelProperty(value = "ext10", index = 13) + private String ext10; + + @ExcelIgnore + private String mileage; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/BzCustomer.java b/src/main/java/com/cmsen/ticket/domain/entity/BzCustomer.java new file mode 100644 index 0000000..4bb7714 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/BzCustomer.java @@ -0,0 +1,151 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * bz_customer + * @author + */ +@Data +public class BzCustomer implements Serializable { + /** + * 表ID,供其他表做外键 + */ + private Long id; + + /** + * 主键,客户ID + */ + private Long customerId; + + /** + * 客户编码 + */ + private String customerNumber; + + /** + * 客户名称 + */ + private String customerName; + + /** + * 地址 + */ + private String billAddress; + + /** + * 开票纳税人识别号 + */ + private String taxReference; + + /** + * 开票地址 + */ + private String invoiceAddress; + + /** + * 开票电话 + */ + private String invoicePhone; + + /** + * 开户行 + */ + private String bankName; + + /** + * 开户账号 + */ + private String bankAccountNum; + + /** + * 详细说明 + */ + private String description; + + /** + * 启用标识 + */ + private String enabledFlag; + + /** + * 后台处理组ID,供分批、并发控制用 + */ + private Long processGroupId; + + /** + * 后台处理状态,约定: +PENDING/用户已确认,数据可以导入 +ERROR/出错,数据验证不通过 +COMPLETE/数据已经进入接口,用户不可以修改 + */ + private String processStatus; + + /** + * 后台处理日期 + */ + private Date processDate; + + /** + * 后台处理信息 + */ + private String processMessage; + + /** + * 备注,有条件的话做成多行文本 + */ + private String comments; + + /** + * 行版本号,用来处理锁 + */ + private Long rowVersionNumber; + + private Date creationDate; + + private Long createdBy; + + private Long lastUpdatedBy; + + private Date lastUpdateDate; + + private Long lastUpdateLogin; + + private String attributeCategory; + + private String attribute1; + + private String attribute2; + + private String attribute3; + + private String attribute4; + + private String attribute5; + + private String attribute6; + + private String attribute7; + + private String attribute8; + + private String attribute9; + + private String attribute10; + + private String attribute11; + + private String attribute12; + + private String attribute13; + + private String attribute14; + + private String attribute15; + + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CheckMessage.java b/src/main/java/com/cmsen/ticket/domain/entity/CheckMessage.java new file mode 100644 index 0000000..9402f69 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CheckMessage.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class CheckMessage { + // 是否能提交 + private Boolean submit; + //错误消息集合 + private List messageList = new ArrayList<>(); + + @Data + public static class Message { + private int level = 1; + private String message; + } +} + + diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveHeader.java b/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveHeader.java new file mode 100644 index 0000000..9a0d6a3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveHeader.java @@ -0,0 +1,112 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * + * @TableName corp_invoice_receive_header + */ +@Data +public class CorpInvoiceReceiveHeader implements Serializable { + /** + * + */ + private Integer id; + + /** + * + */ + private Date dateOfReceipt; + + /** + * + */ + private String buyer; + private String buyerCode; + + /** + * + */ + private String invoiceType; + + /** + * + */ + private String seller; + private String sellerCode; + + /** + * + */ + private String invoiceCode; + + /** + * + */ + private String invoiceNum; + + /** + * + */ + private String invoiceDate; + private String invoiceRemark; + + /** + * + */ + private String amountMoney; + + /** + * + */ + private String taxAmount; + + /** + * + */ + private String totalAmount; + + /** + * + */ + private String username; + + /** + * + */ + private Integer type; + + /** + * + */ + private String oddNum; + + /** + * + */ + private String validStatus; + + /** + * + */ + private String remarks; + + /** + * + */ + private String status; + + private List lines = new ArrayList<>(); + + private static final long serialVersionUID = 1L; + + private String ticketCode; + private String verifiedCode; + private String imgUrl; + private String sendStatus; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveLine.java b/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveLine.java new file mode 100644 index 0000000..3cfa3f9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorpInvoiceReceiveLine.java @@ -0,0 +1,125 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * + * @TableName corp_invoice_receive_line + */ +@Data +public class CorpInvoiceReceiveLine implements Serializable { + /** + * + */ + private String id; + + /** + * + */ + private String pid; + + /** + * + */ + private String name; + + /** + * + */ + private String unit; + + /** + * + */ + private String quantity; + + /** + * + */ + private String price; + + /** + * + */ + private String total; + + /** + * + */ + private String extraFields; + + /** + * + */ + private String specification; + + /** + * + */ + private String taxRate; + + /** + * + */ + private String tax; + + /** + * 抵扣金额 + */ + private String deductionAmount; + + /** + * 抵扣税率 + */ + private String deductionTaxRate; + + /** + * 抵扣税额 + */ + private String deductionTax; + + /** + * + */ + private Integer isDel; + + /** + * 差异 + */ + private String difference; + + /** + * + */ + private String originUnit; + + /** + * + */ + private String originQuantity; + + /** + * + */ + private String originPrice; + + private static final long serialVersionUID = 1L; + +// public BigDecimal getUnUsedAmount() { +// if (usedAmount == null) return new BigDecimal(total); +// return new BigDecimal(total).subtract(usedAmount).setScale(2,BigDecimal.ROUND_HALF_UP); +// } +// +// public Integer getUnUsedQuantity() { +// if (usedQuantity == null) return new BigDecimal(quantity).intValue(); +// return new BigDecimal(quantity).intValue() - usedQuantity; +// } + + public String getDifference() { + if (difference == null) return total; + if (difference.equals("")) return "0"; + return difference; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentHeader.java b/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentHeader.java new file mode 100644 index 0000000..c801c78 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentHeader.java @@ -0,0 +1,92 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * + * @TableName corp_payment_header + */ +@Data +public class CorpPaymentHeader implements Serializable { + /** + * + */ + private Integer id; + + /** + * + */ + private String businessCompany; + + /** + * + */ + private String payNum; + + /** + * + */ + private String name; + + /** + * + */ + private String type; + + /** + * + */ + private String currency; + + /** + * + */ + private Long amount; + + /** + * + */ + private String submitName; + + /** + * + */ + private Date submitDate; + + /** + * + */ + private String status; + + /** + * + */ + private String checker; + + /** + * + */ + private String costCenter; + + /** + * + */ + private String document; + private String vendor; + private String vendorCode; + private String requestId; + private String ext01;//记录workflowId + private String ext02; + private String ext03; + private String ext04; + private String ext05; + + private static final long serialVersionUID = 1L; + + private List payMentLine = new ArrayList<>(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentLine.java b/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentLine.java new file mode 100644 index 0000000..37771b2 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorpPaymentLine.java @@ -0,0 +1,74 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * + * @TableName corp_payment_line + */ +@Data +public class CorpPaymentLine implements Serializable { + /** + * + */ + private Integer id; + + /** + * + */ + private String pId; + + /** + * + */ + private String expenseType; + + /** + * + */ + private String invoiceCode; + + /** + * + */ + private String invoiceNum; + + /** + * + */ + private String invoiceDate; + + /** + * + */ + private String tax; + + /** + * + */ + private String taxAmount; + + /** + * + */ + private String currency; + + /** + * + */ + private String amount;//总价 + + /** + * + */ + private String received; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice.java b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice.java index 58d1a0c..29b1267 100644 --- a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice.java +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice.java @@ -165,6 +165,9 @@ public class CorporateInvoice implements Serializable { @ExcelIgnore private String payDate; + @ExcelIgnore + private CheckMessage checkResult = new CheckMessage(); + @ExcelIgnore private List base64 = new ArrayList<>(); diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice3.java b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice3.java new file mode 100644 index 0000000..1679620 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoice3.java @@ -0,0 +1,422 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.cmsen.common.http.response.Validation; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.domain.util.StringUtils; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import org.springframework.format.annotation.DateTimeFormat; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @TableName corporate_invoice + */ +@Data +public class CorporateInvoice3 implements Serializable { + + @NotNull(message = "required", groups = {Validation.Update.class}) + @ExcelIgnore + private String id; + + @ExcelIgnore + private Integer orgId; + + @ExcelIgnore + private String title; + + @ExcelIgnore + private Integer invoiceType; + + @ExcelProperty(value = "发票代码", index = 3) + private String code; + + //供应商代码 + @ExcelIgnore + private String supplierCode; + + @ExcelProperty(value = "发票号码", index = 4) + private String number; + + @ExcelProperty(value = "发票日期", index = 5) + private String date; + + @ExcelProperty(value = "总金额", index = 8) + private String total; + + @ExcelIgnore + private String imgPath; + + @ExcelIgnore + private String extraFields; + + @ExcelIgnore + private String remark; + + @ExcelIgnore + private String loginId; + + @ExcelIgnore + private Integer isSend; + + @ExcelIgnore + private String entryId; + + @ExcelProperty(value = "更新日期", index = 11) + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8") + private Date updateDate; + + @ExcelIgnore + private List items = new ArrayList<>(); + + @ExcelProperty(value = "销售方", index = 2) + private String seller; + @ExcelIgnore + private String vendor; + + @ExcelIgnore + private String sellerNo; + + @ExcelProperty(value = "购买方", index = 0) + private String buyer; + @ExcelIgnore + private String fullBuyer; + + @ExcelIgnore + private String buyerNo; + + @ExcelIgnore + private String originalFilePath; + + @ExcelProperty(value = "NPO", index = 12) + private String po; + + @ExcelIgnore + private String ticketCode; + + @ExcelProperty(value = "发票类型", index = 1) + private String ticketCodeStr; + + @ExcelIgnore + private String kind; + + /* 0 未处理 1 已处理 2 异常 3 pending */ + @ExcelIgnore + private Integer status; + + /** + * 0 待处理 1 待审核 2 未发送 3 已发送 + */ + @ExcelIgnore + private Integer matchStatus; + + @ExcelIgnore + private String verifiedCode; + + @ExcelIgnore + private String fileName; + + @ExcelProperty(value = "金额", index = 6) + private String pretaxAmount; + + @ExcelProperty(value = "税额", index = 7) + private String tax; + +// @ExcelProperty(value = "发票内容", index = 13) + @ExcelIgnore + private String details; + + @ExcelProperty(value = "操作人", index = 9) + private String operator; + + @ExcelIgnore + private Integer operatorId; + + @ExcelProperty(value = "创建日期", index = 10) + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8") + private Date createDate; + + @ExcelIgnore + private String currency; + + @ExcelIgnore + private Integer checked; + + @ExcelProperty(value = "备注", index = 13) + private String desc; + + @ExcelIgnore + private String message; + + @ExcelIgnore + private String showTitle; + + @ExcelIgnore + private String payDate; + + @ExcelIgnore + private CheckMessage checkResult = new CheckMessage(); + + @ExcelIgnore + private List base64 = new ArrayList<>(); + + @ExcelIgnore + private List files = new ArrayList<>(); + // New filed added + +// @ExcelProperty(value = "入账日期", index = 16) + @DateTimeFormat(pattern = "yyyy-MM-dd") + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") + @ExcelIgnore + private Date postingDate; + +// @ExcelProperty(value = "抵扣日期", index = 18) + @DateTimeFormat(pattern = "yyyy-MM-dd") + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") + @ExcelIgnore + private Date deductTime; + +// @ExcelProperty(value = "抵扣状态", index = 17) + @ExcelIgnore + private String deductStatus; + + @ExcelIgnore + private String downloadUri; + + /** + * 0 未验真 1已验真 + */ + @ExcelIgnore + private Byte validStatus; + + /** + * 总验真次数 + */ + @ExcelIgnore + private Integer validCount; + + /** + * 当日验真次数 + */ + @ExcelIgnore + private Integer validDayCount; + + @ExcelProperty(value = "状态", index = 14) + private String statusStr; + + @ExcelIgnore + private Integer owner; + + @ExcelIgnore + private String ownerName; + @ExcelIgnore + private String invoiceTypeName; + @ExcelIgnore + private String orgName; + + /** + * 使用状态 0 未使用 1 已使用 2 后票 + */ + @ExcelIgnore + private Integer useStatus; + + @ExcelIgnore + private int percent; + + @ExcelIgnore + private Integer subject; + + // 0 金额 1 数量 + @ExcelIgnore + private Integer matchType; + + // 0 折后 1 折前 + @ExcelIgnore + private Integer priceType; + + @ExcelIgnore + private String period; //增加字段 + @ExcelIgnore + private String received; + + @ExcelIgnore + private String numberBackup; + @ExcelIgnore + private String numberConfirm; + @ExcelIgnore + private String companySeal; + @ExcelIgnore + private String deductionAmount;//抵扣金额 + @ExcelIgnore + private String ext01; + @ExcelIgnore + private String ext02; + @ExcelIgnore + private String ext03; + @ExcelIgnore + private String ext04; + @ExcelIgnore + private String ext05; + + @ExcelIgnore + private String ext06; + @ExcelIgnore + private String ext07; + @ExcelIgnore + private String ext08; + @ExcelIgnore + private String ext09; + @ExcelIgnore + private String ext10; + + @ExcelIgnore + private String different;//差异金额 total - deductionAmount + @ExcelIgnore + private String taxRate;//税率 + @ExcelIgnore + private String ticketType; + @ExcelIgnore + private String docName; + @ExcelIgnore + private Integer del; + @ExcelProperty(value = "是否删除", index = 15) + private String delStr; + + public String getDelStr(){ + if(del == null) return ""; + switch (del) { + case 0: + return "未删除"; + case 1: + return "已删除"; + default: + return ""; + } + } + + + public static Integer statusStrToNumber(String str) { + if (str == null) return null; + switch (str.toLowerCase()) { + case "已处理": + return 1; + case "异常": + return 2; + case "pending": + return 3; + case "未处理": + return 0; + case "退票": + return 4; + case "暂挂": + return 5; + default: + return null; + } + } + + public String getDownloadUri() { + if (StringUtil.isNotEmpty(this.originalFilePath)) { + return this.originalFilePath; + } + return this.imgPath; + } + + public String getFileName() { + if (StringUtil.isNotEmpty(this.originalFilePath)) { + return this.number + this.originalFilePath.substring(this.originalFilePath.lastIndexOf(".")); + } + if (StringUtil.isNotEmpty(this.imgPath)) { + return this.number + this.imgPath.substring(this.imgPath.lastIndexOf(".")); + } + return "null"; + } + + public String getShowTitle() { + return this.message; + } + + public String getDeductStatus() { + return StringUtil.isEmpty(deductStatus) ? "未抵扣" : deductStatus; + } + +// public String getTicketCodeStr() { +// if (ticketCode == null) return ""; +// switch (ticketCode) { +// case "10101":s +// return "增值税普通发票"; +// case "10100": +// return "增值税专用发票"; +// case "10107": +// return "增值税电子专用发票"; +// case "10102": +// return "增值税电子普通发票"; +// case "30100": +// return "形式发票"; +// case "30101": +// return "收据"; +// default: +// return ""; +// } +// } + + public String getStatusStr() { + if (status == null) return ""; + switch (status) { + case 1: + return "已处理"; + case 2: + return "异常"; + case 3: + return "Pending"; + case 0: + return "未处理"; + case 4: + return "退票"; + case 5: + return "暂挂"; + default: + return ""; + } + } + + public String getImgPath() { + return imgPath == null ? null : StringUtils.formatUrl(imgPath, "/"); + } + + public void setImgPath(String imgPath) { + this.imgPath = imgPath == null ? null : StringUtils.formatUrl(imgPath, "/"); + } + + public String getOriginalFilePath() { + return originalFilePath == null ? null : StringUtils.formatUrl(originalFilePath, "/"); + } + + public void setOriginalFilePath(String originalFilePath) { + this.originalFilePath = originalFilePath == null ? null : StringUtils.formatUrl(originalFilePath, "/"); + } + + public String getSeller() { + return StringUtils.getStringWithOutSpecialCode2(seller); + } + + public void setSeller(String seller) { + this.seller = StringUtils.getStringWithOutSpecialCode2(seller); + } + + public String getBuyer() { + return StringUtils.getStringWithOutSpecialCode2(buyer); + } + + public void setBuyer(String buyer) { + this.buyer = StringUtils.getStringWithOutSpecialCode2(buyer); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceItems.java b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceItems.java index 0f98448..937b9f2 100644 --- a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceItems.java +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceItems.java @@ -75,9 +75,6 @@ public class CorporateInvoiceItems implements Serializable { if(priceType==0) { total = total.replace("¥",""); if (usedAmount == null) return new BigDecimal(total==null?"0":total); -// log.info("total=>{}",total); -// log.info("deductionAmount=>{}",deductionAmount); -// log.info("usedAmount=>{}",usedAmount); return new BigDecimal(total).add(new BigDecimal(deductionAmount == null ? "0" : deductionAmount)).subtract(usedAmount).setScale(2, BigDecimal.ROUND_HALF_UP); }else{ total = total.replace("¥",""); diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceNdJsonMapping.java b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceNdJsonMapping.java new file mode 100644 index 0000000..3763011 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceNdJsonMapping.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.util.Date; + +@Data +public class CorporateInvoiceNdJsonMapping { + private int id; + private String kind; + private String jsonLocate; + private String mappingSource; + private String mappingDest; + private int available; + private int isDel; + private Date create_date; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceScannerFiles.java b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceScannerFiles.java new file mode 100644 index 0000000..9866786 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CorporateInvoiceScannerFiles.java @@ -0,0 +1,43 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; + +@Data +@Slf4j +public class CorporateInvoiceScannerFiles { + + + private int id; + private Long scannerId; + private String invoiceNumber; + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8") + private Date createDate; + + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8") + private Date updateDate; + + private int ocrCost; + private String pdfPath; + private String splitFilePath; + private String ocrResult; + private int ocrStatus; + private int verifyStatus; + private String ocrInterface; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + private String ext06; + private String ext07; + private String ext08; + private String ext09; + private String ext10; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/CreditItem.java b/src/main/java/com/cmsen/ticket/domain/entity/CreditItem.java new file mode 100644 index 0000000..f8d9da5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/CreditItem.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * + * @TableName mt_checkin + */ +@Data +public class CreditItem implements Serializable { + private String referenceNum; + private String transactionDate; + private String employeeId; + private String lastFourDigit; + private String cardType; + private String merchant; + private String amount; + private String currency; + + public CreditItem() { + } + + public CreditItem(String referenceNum, String transactionDate, String employeeId, + String lastFourDigit, String cardType, String merchant, + String amount, String currency) { + this.referenceNum = referenceNum; + this.transactionDate = transactionDate; + this.employeeId = employeeId; + this.lastFourDigit = lastFourDigit; + this.cardType = cardType; + this.merchant = merchant; + this.amount = amount; + this.currency = currency; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Currency.java b/src/main/java/com/cmsen/ticket/domain/entity/Currency.java new file mode 100644 index 0000000..1aee78a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Currency.java @@ -0,0 +1,20 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Currency { + private Integer id; + + private String name; + + private String isDel; + + private String code; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/DeductionCompany.java b/src/main/java/com/cmsen/ticket/domain/entity/DeductionCompany.java new file mode 100644 index 0000000..5c645e8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/DeductionCompany.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 可抵扣公司 + * + * @TableName deduction_company + */ +@Data +public class DeductionCompany implements Serializable { + + private Integer id; + + private String name; + + private String code; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/DeductionReportEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/DeductionReportEntity.java new file mode 100644 index 0000000..1a93628 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/DeductionReportEntity.java @@ -0,0 +1,70 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import lombok.Data; + +/** + * DeductionReport Data + * + * @author OWTS + * @version 1.0.0 + * @date 2021/9/1 17:08 + **/ +@ColumnWidth(20) +@Data +public class DeductionReportEntity { + @ExcelProperty(value = "是否勾选*", index = 0) + private String isChoose; + @ExcelProperty(value = "数电发票号码", index = 1) + private String invoiceNumSD; + @ExcelProperty(value = "发票代码", index = 2) + private String invoiceCode; + @ExcelProperty(value = "发票号码", index = 3) + private String invoiceNum; + @ExcelProperty(value = "开票日期*", index = 4) + private String invoiceDate; + @ExcelProperty(value = "金额*", index = 5) + private String invoiceMoney; + @ExcelProperty(value = "票面税额*", index = 6) + private String tax1; + @ExcelProperty(value = "有效抵扣税额*", index = 7) + private String tax2; + @ExcelProperty(value = "购买方识别号*", index = 8) + private String buyerCode; + @ExcelProperty(value = "销售方纳税人名称*", index = 9) + private String seller; + @ExcelProperty(value = "销售方纳税人识别号*", index = 10) + private String sellerCode; + @ExcelProperty(value = "发票来源", index = 11) + private String invoiceSource; + @ExcelProperty(value = "票种", index = 12) + private String invoiceType; + @ExcelProperty(value = "发票状态", index = 13) + private String invoiceStatus; + @ExcelProperty(value = "红字锁定标志", index = 14) + private String redLockSign; + @ExcelProperty(value = "转内销证明编号", index = 15) + private String proveNum; + @ExcelProperty(value = "业务类型", index = 16) + private String businessType; + @ExcelProperty(value = "勾选时间", index = 17) + private String chooseDate; + @ExcelProperty(value = "发票风险等级", index = 18) + private String riskLevel; + @ExcelProperty(value = "单据编号", index = 19) + private String reportKey; + @ExcelProperty(value = "eReceipt_ID", index = 20) + private String eReceiptId; + @ExcelProperty(value = "购买方", index = 21) + private String orgUnit2; + @ExcelProperty(value = "付款日期", index = 22) + private String paidDate; + + @ExcelProperty(value = "费用类型", index = 23) + private String expenseTypeName; + @ExcelProperty(value = "Concur发票状态", index = 24) + private String concurInvoiceStatus; + @ExcelProperty(value = "验真描述", index = 25) + private String vaildDesc; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ErrorReport.java b/src/main/java/com/cmsen/ticket/domain/entity/ErrorReport.java new file mode 100644 index 0000000..d5f1a76 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ErrorReport.java @@ -0,0 +1,36 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 异常报告 + * + * @TableName error_report + */ +@Data +public class ErrorReport implements Serializable { + /** + * 主键ID + */ + private Long id; + + /** + * 报告 + */ + private String reportId; + + /** + * 状态 + */ + private String status; + + /** + * 创建时间 + */ + private Date createTime; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReport.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReport.java new file mode 100644 index 0000000..bf75f51 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReport.java @@ -0,0 +1,203 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * exp_comb_report + * @author + */ +@Data +public class ExpCombReport implements Serializable { + private Long combReportId; + + /** + * 报告名称 + */ + private String combReportName; + + /** + * 开始日期 + */ + private String combStart; + + /** + * 结束日期 + */ + private String combEnd; + + /** + * POLICY + */ + private String policy; + + /** + * 用户ID + */ + private Integer userId; + + /** + * 是否传送 0/否 1/是 + */ + private Integer isSend; + + /** + * Concur ID + */ + private String concurId; + + /** + * 报告生成时间 + */ + private String combTime; + + /** + * 备注 + */ + private String remark; + + private static final long serialVersionUID = 1L; + + public Long getCombReportId() { + return combReportId; + } + + public void setCombReportId(Long combReportId) { + this.combReportId = combReportId; + } + + public String getCombReportName() { + return combReportName; + } + + public void setCombReportName(String combReportName) { + this.combReportName = combReportName; + } + + public String getCombStart() { + return combStart; + } + + public void setCombStart(String combStart) { + this.combStart = combStart; + } + + public String getCombEnd() { + return combEnd; + } + + public void setCombEnd(String combEnd) { + this.combEnd = combEnd; + } + + public String getPolicy() { + return policy; + } + + public void setPolicy(String policy) { + this.policy = policy; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public Integer getIsSend() { + return isSend; + } + + public void setIsSend(Integer isSend) { + this.isSend = isSend; + } + + public String getConcurId() { + return concurId; + } + + public void setConcurId(String concurId) { + this.concurId = concurId; + } + + public String getCombTime() { + return combTime; + } + + public void setCombTime(String combTime) { + this.combTime = combTime; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + @Override + public boolean equals(Object that) { + if (this == that) { + return true; + } + if (that == null) { + return false; + } + if (getClass() != that.getClass()) { + return false; + } + ExpCombReport other = (ExpCombReport) that; + return (this.getCombReportId() == null ? other.getCombReportId() == null : this.getCombReportId().equals(other.getCombReportId())) + && (this.getCombReportName() == null ? other.getCombReportName() == null : this.getCombReportName().equals(other.getCombReportName())) + && (this.getCombStart() == null ? other.getCombStart() == null : this.getCombStart().equals(other.getCombStart())) + && (this.getCombEnd() == null ? other.getCombEnd() == null : this.getCombEnd().equals(other.getCombEnd())) + && (this.getPolicy() == null ? other.getPolicy() == null : this.getPolicy().equals(other.getPolicy())) + && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) + && (this.getIsSend() == null ? other.getIsSend() == null : this.getIsSend().equals(other.getIsSend())) + && (this.getConcurId() == null ? other.getConcurId() == null : this.getConcurId().equals(other.getConcurId())) + && (this.getCombTime() == null ? other.getCombTime() == null : this.getCombTime().equals(other.getCombTime())) + && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((getCombReportId() == null) ? 0 : getCombReportId().hashCode()); + result = prime * result + ((getCombReportName() == null) ? 0 : getCombReportName().hashCode()); + result = prime * result + ((getCombStart() == null) ? 0 : getCombStart().hashCode()); + result = prime * result + ((getCombEnd() == null) ? 0 : getCombEnd().hashCode()); + result = prime * result + ((getPolicy() == null) ? 0 : getPolicy().hashCode()); + result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); + result = prime * result + ((getIsSend() == null) ? 0 : getIsSend().hashCode()); + result = prime * result + ((getConcurId() == null) ? 0 : getConcurId().hashCode()); + result = prime * result + ((getCombTime() == null) ? 0 : getCombTime().hashCode()); + result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(getClass().getSimpleName()); + sb.append(" ["); + sb.append("Hash = ").append(hashCode()); + sb.append(", combReportId=").append(combReportId); + sb.append(", combReportName=").append(combReportName); + sb.append(", combStart=").append(combStart); + sb.append(", combEnd=").append(combEnd); + sb.append(", policy=").append(policy); + sb.append(", userId=").append(userId); + sb.append(", isSend=").append(isSend); + sb.append(", concurId=").append(concurId); + sb.append(", combTime=").append(combTime); + sb.append(", remark=").append(remark); + sb.append(", serialVersionUID=").append(serialVersionUID); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReportSub.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReportSub.java new file mode 100644 index 0000000..a917caa --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpCombReportSub.java @@ -0,0 +1,91 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * exp_comb_report_sub + * @author + */ +@Data +public class ExpCombReportSub implements Serializable { + private Long id; + + /** + * exp_comb_report表的ID + */ + private Integer combReportId; + + /** + * expense_reports表的ID + */ + private Integer expenseReprotsId; + + private static final long serialVersionUID = 1L; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getCombReportId() { + return combReportId; + } + + public void setCombReportId(Integer combReportId) { + this.combReportId = combReportId; + } + + public Integer getExpenseReprotsId() { + return expenseReprotsId; + } + + public void setExpenseReprotsId(Integer expenseReprotsId) { + this.expenseReprotsId = expenseReprotsId; + } + + @Override + public boolean equals(Object that) { + if (this == that) { + return true; + } + if (that == null) { + return false; + } + if (getClass() != that.getClass()) { + return false; + } + ExpCombReportSub other = (ExpCombReportSub) that; + return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) + && (this.getCombReportId() == null ? other.getCombReportId() == null : this.getCombReportId().equals(other.getCombReportId())) + && (this.getExpenseReprotsId() == null ? other.getExpenseReprotsId() == null : this.getExpenseReprotsId().equals(other.getExpenseReprotsId())); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); + result = prime * result + ((getCombReportId() == null) ? 0 : getCombReportId().hashCode()); + result = prime * result + ((getExpenseReprotsId() == null) ? 0 : getExpenseReprotsId().hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(getClass().getSimpleName()); + sb.append(" ["); + sb.append("Hash = ").append(hashCode()); + sb.append(", id=").append(id); + sb.append(", combReportId=").append(combReportId); + sb.append(", expenseReprotsId=").append(expenseReprotsId); + sb.append(", serialVersionUID=").append(serialVersionUID); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActive.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActive.java new file mode 100644 index 0000000..6fea2ea --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActive.java @@ -0,0 +1,50 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ExpenseTypeActive { + private Integer id; + + private String value; + + private String valueName; + + private Integer pid; + + private String isDel; + + private String selectName; + + private String category; + + private Integer required; + + private Integer sort; + + private String type; + + private String defaultValue; + + private Integer kind; + + private Integer exPid; + + private Integer childId; + + private List child = new ArrayList<>(); + // private List subs = new ArrayList<>(); + private String binding; + + private Integer targetId; + + private Boolean editAble; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActiveTtListConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActiveTtListConfig.java new file mode 100644 index 0000000..53c9590 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeActiveTtListConfig.java @@ -0,0 +1,21 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 动态字段 list 类型配置 + * @TableName expense_type_active_tt_list_config + */ +@Data +public class ExpenseTypeActiveTtListConfig implements Serializable { + + private String listName; + + private String type; + + private String value; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeSub.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeSub.java new file mode 100644 index 0000000..7ab718f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseTypeSub.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * expense_type_sub + * + * @author + */ +@Data +public class ExpenseTypeSub implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + /** + * expense_type.ID + */ + private Integer parentId; + /** + * 费用类型名 + */ + private String name; + /** + * code + */ + private String codes; + /** + * 0/未删除 1、已删除 + */ + private Boolean isDel; + private String spendCategory; + private String categoryName; + private String categoryCode; + + private String nameEn; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ExpenseUse.java b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseUse.java new file mode 100644 index 0000000..edb99d4 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ExpenseUse.java @@ -0,0 +1,71 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ExpenseUse implements Serializable { + private static final long serialVersionUID = -30853226593305773L; + /** + * 费用用途表自增唯一ID + */ + @ExcelProperty(value = "ID", index = 0) + private Integer id; + /** + * 费用用途的值 + */ + @ExcelProperty(value = "费控政策", index = 1) + private String value; + + @ExcelProperty(value = "费控政策英文", index = 2) + private String valueEn; + /** + * 0为未删除,1为已删除,默认为0 + */ + @ExcelIgnore + private String isDel; + + @ExcelIgnore + private Integer clientId; + + @ExcelProperty(value = "组别", index = 4) + private String groups; + + @ExcelProperty(value = "费控代码", index = 3) + private String codes; + + @ExcelProperty(value = "Key", index = 5) + private String keyword; + + @ExcelIgnore + private String mesg; + + @ExcelIgnore + private String mesgEn; + + @ExcelIgnore + private String ext01; + + @ExcelIgnore + private String ext02; + + @ExcelIgnore + private String ext03; + + @ExcelIgnore + private String ext04; + + @ExcelIgnore + private String ext05; + + @ExcelIgnore + private String relevance; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Files.java b/src/main/java/com/cmsen/ticket/domain/entity/Files.java new file mode 100644 index 0000000..83090fe --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Files.java @@ -0,0 +1,44 @@ +package com.cmsen.ticket.domain.entity; + +import com.cmsen.ticket.domain.util.StringUtils; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class Files { + private Integer id; + + private String fileName; + + private String invoiceId; + + private String filePath; + + private List picList = new ArrayList<>(); + + private String openId; + + private String reportId; + + private String mqId; + private String type;//如果是1,代表是系统图库 + private String autoInsert; + + private Long efilesId; + + /** 关联 efiles 表的 TYPE(如 3002),仅 list2 查询时带出,不对应 files 表字段 */ + private String efilesType; + + private String status; + private String ext01;//记录附件类型 + private String ext02;//记录原始附件类型 + private String ext03;//删除标记:Y + private String ext04; + private String ext05;//H-报告头 + + public String getFilePath() { + return filePath == null ? null : StringUtils.formatUrl(filePath, "/"); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig.java new file mode 100644 index 0000000..53d8eea --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig.java @@ -0,0 +1,68 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * 发票附件配置 + * + * @TableName files_config + */ +@AllArgsConstructor +@NoArgsConstructor +@Data +public class FilesConfig implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + private Integer id; + /** + * 附件识别类型code + */ + private String type; + /** + * 附件去向0 无 1 item 2 attendee + */ + private Integer toType; + /** + * 客制化字段 + */ + private String custom1; + /** + * 客制化字段 + */ + private String custom2; + /** + * 客制化字段 + */ + private String custom3; + /** + * 客制化字段 + */ + private String custom4; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06;//ND解析后的二次解析interfacename + + private String ext07;//expensetypeid,需要进行二次解析的费用类型id + + private String ext08; + + private String ext09; + + private String ext10; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig2.java b/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig2.java new file mode 100644 index 0000000..a6a1af0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/FilesConfig2.java @@ -0,0 +1,59 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class FilesConfig2 implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + private Integer id; + /** + * 附件识别类型code + */ + private String type; + /** + * 附件去向0 无 1 item 2 attendee + */ + private Integer toType; + /** + * 客制化字段 + */ + private String custom1; + /** + * 客制化字段 + */ + private String custom2; + /** + * 客制化字段 + */ + private String custom3; + /** + * 客制化字段 + */ + private String custom4; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06;//ND解析后的二次解析interfacename + + private String ext07;//expensetypeid,需要进行二次解析的费用类型id + + private String ext08; + + private String ext09; + + private String ext10; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/FilesOcr.java b/src/main/java/com/cmsen/ticket/domain/entity/FilesOcr.java new file mode 100644 index 0000000..6e4b006 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/FilesOcr.java @@ -0,0 +1,53 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 发票附件识别结果 + * + * @TableName files_ocr + */ +@Data +public class FilesOcr implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + private Long id; + /** + * 类型 + */ + private String type; + /** + * 附件日期 + */ + private String invDate; + /** + * 总额 + */ + private String amount; + /** + * 识别结果 + */ + private String verifiedData; + /** + * 发票ID + */ + private String invoiceId; + /** + * 附件ID + */ + private Integer filesId; + + private String ext01;//type=3002 讲者正面照保存extId + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Help.java b/src/main/java/com/cmsen/ticket/domain/entity/Help.java new file mode 100644 index 0000000..ff2b891 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Help.java @@ -0,0 +1,113 @@ +package com.cmsen.ticket.domain.entity; + +public class Help { + private Integer id; + + private String title; + + private String reasonOne; + + private String solutionOne; + + private String reasonTwo; + + private String solutionTwo; + + private String reasonThree; + + private String solutionThree; + + private String reasonFour; + + private String solutionFour; + + private String isDel; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getReasonOne() { + return reasonOne; + } + + public void setReasonOne(String reasonOne) { + this.reasonOne = reasonOne; + } + + public String getSolutionOne() { + return solutionOne; + } + + public void setSolutionOne(String solutionOne) { + this.solutionOne = solutionOne; + } + + public String getReasonTwo() { + return reasonTwo; + } + + public void setReasonTwo(String reasonTwo) { + this.reasonTwo = reasonTwo; + } + + public String getSolutionTwo() { + return solutionTwo; + } + + public void setSolutionTwo(String solutionTwo) { + this.solutionTwo = solutionTwo; + } + + public String getReasonThree() { + return reasonThree; + } + + public void setReasonThree(String reasonThree) { + this.reasonThree = reasonThree; + } + + public String getSolutionThree() { + return solutionThree; + } + + public void setSolutionThree(String solutionThree) { + this.solutionThree = solutionThree; + } + + public String getReasonFour() { + return reasonFour; + } + + public void setReasonFour(String reasonFour) { + this.reasonFour = reasonFour; + } + + public String getSolutionFour() { + return solutionFour; + } + + public void setSolutionFour(String solutionFour) { + this.solutionFour = solutionFour; + } + + public String getIsDel() { + return isDel; + } + + public void setIsDel(String isDel) { + this.isDel = isDel; + } +} \ No newline at end of file diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Internationalization.java b/src/main/java/com/cmsen/ticket/domain/entity/Internationalization.java new file mode 100644 index 0000000..bfaad0b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Internationalization.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Internationalization { + private Integer id; + + private String common; + + private String ch; + + private String en; + + private String isDel; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/InvokeBrand.java b/src/main/java/com/cmsen/ticket/domain/entity/InvokeBrand.java new file mode 100644 index 0000000..184420d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/InvokeBrand.java @@ -0,0 +1,165 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * invoke_brand + * @author + */ +@Data +public class InvokeBrand implements Serializable { + private Long id; + + /** + * flowId + */ + private String flowId; + private String flowIdName; + + /** + * 主流程编号-流水号 + */ + private String mainProcessNumber; + + /** + * 主流程(品牌/市场)-标题 + */ + private String mainProcess; + + /** + * 所属公司Code + */ + private String companyCode; + + /** + * 所属公司 + */ + private String companyName; + + /** + * 成本中心Code + */ + private String orgCode; + + /** + * 成本中心 + */ + private String orgName; + + /** + * 是否为数字营销:0-是 1-否 + */ + private String isDigitalMarket; + + /** + * 币种 + */ + private String currency; + + /** + * 供应商Code + */ + private String supplierCode; + + /** + * 供应商名称 + */ + private String supplierName; + /** + * 开户行分行 + */ + private String branchBank; + + /** + * 账户信息 + */ + private String accountInfo; + /** + * 付款类型 0-非DM内结,1-DM内结,2-任务付款 + */ + private String payType; + + /** + * 申请人 + */ + private String applyMan; + private String applyManName; + + private Boolean isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + /** + * requestId + */ + private String ext01; + + private String ext02;//流程金额--同yszd + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06; + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + private static final long serialVersionUID = 1L; + + private String brandCompany;//品牌公司名 + private String isSupplierCon;//是否有供应商合同 + private String isOperateCost;//是否店铺运营平台推广费用 + private String gh;//工号 + private String zj;//职级 + private String bm;//部门 + private String fb;//分部 + private String sshy;//所属行业 + private String yszd;//所需资源-投入的成本金额 + + + private String payTypeId; + public String getPayTypeId() { + if (payType == null) { + return null; + } + switch (payType) { + case "非DM内结": + return "0"; + case "DM内结": + return "1"; + case "任务付款": + return "2"; + default: + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/InvokeContract.java b/src/main/java/com/cmsen/ticket/domain/entity/InvokeContract.java new file mode 100644 index 0000000..6451bf9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/InvokeContract.java @@ -0,0 +1,149 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * invoke_contract + * @author + */ +@Data +public class InvokeContract implements Serializable { + private Long id; + + /** + * 分类 + */ + private String classify; + + /** + * 流程编号 + */ + private String processNo; + + /** + * 流程标题 + */ + private String processTitle; + + /** + * 申请人 + */ + private String applyMan; + private String applyManName; + + /** + * 合同名称 + */ + private String contractName; + + /** + * 合同类型 + */ + private String contractType; + + /** + * 合同类型2 + */ + private String contractType2; + + /** + * 我方签约公司名称 + */ + private String ourSignCompany; + private String ourSignCompanyName; + + /** + * 对方签约公司名称 + */ + private String otherSignCompany; + private String otherSignCompanyName; + + /** + * 合同开始时间 + */ + private String contractStartTime; + + /** + * 合同到期时间 + */ + private String contractEndTime; + + /** + * 签订类型 + */ + private String signType; + + /** + * 签署类型 + */ + private String affixType; + + /** + * 币种 + */ + private String currency; + + /** + * 合同期限 + */ + private String contractTerm; + + /** + * 是否为非经营性采购 + */ + private String isNonPurchase; + + /** + * owner + */ + private String owner; + + private Boolean isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + private String ext01;//requestId + + private String ext02;//oa创建时间 + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06; + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/InvokeInternal.java b/src/main/java/com/cmsen/ticket/domain/entity/InvokeInternal.java new file mode 100644 index 0000000..4d5d6d2 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/InvokeInternal.java @@ -0,0 +1,122 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * invoke_internal + * @author + */ +@Data +public class InvokeInternal implements Serializable { + private Long id; + + /** + * flowId + */ + private String flowId; + + /** + * 流程编码 + */ + private String processNumber; + + /** + * 流程标题 + */ + private String processTitle; + + /** + * 收款方成本中心Code + */ + private String collectOrgCode; + + /** + * 收款方成本中心 + */ + private String collectOrgName; + + /** + * 申请人 + */ + private String applyMan; + private String applyManName; + + /** + * OA创建时间 + */ + private String oaCreateTime; + + /** + * 付款方所属公司Code + */ + private String payCompanyCode; + + /** + * 付款方所属公司 + */ + private String payCompanyName; + + /** + * 收款方所属公司Code + */ + private String collectCompanyCode; + + /** + * 收款方所属公司 + */ + private String collectCompanyName; + + private String owner; + + private Boolean isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + /** + * requestId + */ + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06; + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/InvokePurchase.java b/src/main/java/com/cmsen/ticket/domain/entity/InvokePurchase.java new file mode 100644 index 0000000..e5efb49 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/InvokePurchase.java @@ -0,0 +1,222 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +/** + * invoke_purchase + * @author + */ +@Data +public class InvokePurchase implements Serializable { + private Long id; + + /** + * 采购下单流程编号 + */ + private String purchaseNumber; + + /** + * 源引采购下单流程 + */ + private String purchase; + + /** + * 非经营性采购流程编号 + */ + private String nonPurchaseNumber; + + /** + * 源引非经营性采购流程 + */ + private String nonPurchase; + + /** + * 相关合同流程编号 + */ + private String contractNumber; + + /** + * 源引相关合同流程 + */ + private String contract; + + /** + * 成本中心Code + */ + private String orgCode; + + /** + * 成本中心 + */ + private String orgName; + + /** + * GS项目批号(原项目批号A,限TIC/EIC) + */ + private String gsNum; + + /** + * OA通用项目批号(原项目批号B) + */ + private String oaNum; + + /** + * 合同流程中对方签约公司名称 + */ + private String otherSignCompany; + + /** + * 合同开始日期 + */ + private String contractStartTime; + + /** + * 合同结束日期 + */ + private String contractEndTime; + + /** + * 金额 + */ + private BigDecimal amount; + + /** + * 合同中财务结算条款 + */ + private String financeTerms; + + /** + * 源引收货/验收流程-多流程 + */ + private String checkProcess; + + /** + * 是否修改明细行成本中心:0-是 1-否 + */ + private String isChange; + + /** + * 采购部上级审批人(实习生专用) + */ + private String highApprover; + + private Boolean isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + private String ext01;//requestId + + private String ext02;//owner + + private String ext03;//商品名称 + + private String ext04;//所属行业 + private String deptTitle;//所属行业-名称 + + private String ext05;//GS项目批号-项目名称 + + private String ext06;//OA项目批号-项目名称 + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + /** + * 申请人 + */ + private String applyMan; + private String applyManName; + + /** + * 对接单号 + */ + private String abutmentNo; + + /** + * 所属公司Code + */ + private String companyCode; + + /** + * 所属公司 + */ + private String companyName; + + /** + * 币种 + */ + private String currency; + + /** + * 供应商Code + */ + private String supplierCode; + + /** + * 供应商 + */ + private String supplierName; + + /** + * 开户行分行 + */ + private String branchBank; + + /** + * 账户信息 + */ + private String accountInfo; + + /** + * 抄送干系人ID + */ + private String stakeholder; + + /** + * 抄送干系人 + */ + private String stakeholderName; + + /** + * 是否预付款0是, 1否 + */ + private String isAdvancePay; + + /** + * 是否外部来源0是, 1否 + */ + private String isOtherSource; + + /** + * OA创建时间 + */ + private String oaCreateTime; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/InvokeReceive.java b/src/main/java/com/cmsen/ticket/domain/entity/InvokeReceive.java new file mode 100644 index 0000000..65b7865 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/InvokeReceive.java @@ -0,0 +1,90 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * invoke_receive + * @author + */ +@Data +public class InvokeReceive implements Serializable { + private Integer id; + + /** + * 收货流程编号 + */ + private String receiveNumber; + + /** + * 收货流程标题 + */ + private String receiveTitle; + + /** + * OA创建人 + */ + private String oaCreateBy; + private String oaCreateByName; + + /** + * OA创建时间 + */ + private String oaCreateTime; + + /** + * 对接单号 + */ + private String abutmentNo; + + private Boolean isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + /** + * requestId + */ + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private String ext06; + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Jsadapter.java b/src/main/java/com/cmsen/ticket/domain/entity/Jsadapter.java new file mode 100644 index 0000000..765c5e0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Jsadapter.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +@Data +public class Jsadapter { + private Integer id; + + private String jsFunction; + + private String desc; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Material.java b/src/main/java/com/cmsen/ticket/domain/entity/Material.java new file mode 100644 index 0000000..4cddcb3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Material.java @@ -0,0 +1,53 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * material + * @author + */ +@Data +public class Material implements Serializable { + private Long id; + + /** + * 代码 + */ + private String code; + + /** + * 名称 + */ + private String material; + + /** + * 描述 + */ + private String description; + + /** + * 类型 + */ + private String type; + + /** + * 状态 + */ + private String status; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/PaymentType.java b/src/main/java/com/cmsen/ticket/domain/entity/PaymentType.java new file mode 100644 index 0000000..8f749de --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/PaymentType.java @@ -0,0 +1,43 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * payment_type + * @author + */ +@Data +public class PaymentType implements Serializable { + private Long id; + + /** + * 代码 + */ + private String code; + + /** + * 名称 + */ + private String name; + + /** + * 备注 + */ + private String remark; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/PcUrlEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/PcUrlEntity.java new file mode 100644 index 0000000..208ab04 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/PcUrlEntity.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.entity; + + +import lombok.Data; + +import java.io.Serializable; + +/** + * user_pc + * @author + */ +@Data +public class PcUrlEntity implements Serializable { + + private String url; + private String appId; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/PostBox.java b/src/main/java/com/cmsen/ticket/domain/entity/PostBox.java new file mode 100644 index 0000000..139fda8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/PostBox.java @@ -0,0 +1,214 @@ +package com.cmsen.ticket.domain.entity; + +import com.cmsen.ticket.domain.util.StringUtils; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * post_box + * + * @author + */ +@Data +public class PostBox implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private String subject; + private String from; + private String ticketType; + private String buyer; + private String invoiceMoney; + private String invoiceNum; + private String identifyResult; + private String invoiceDate; + private String receiveDate; + private String filePath; + private Integer userId; + private Boolean repeat; + private Boolean submit; + private Boolean del; + private Integer reportId; + private Integer type; + private String originalPath; + private Date createTime; + private Boolean isChecked = false; + + public String getFilePath() { + return filePath == null ? null : StringUtils.formatUrl(filePath, "/"); + } + + public void setFilePath(String filePath) { + this.filePath = filePath == null ? null : StringUtils.formatUrl(filePath, "/"); + } + + public String getOriginalPath() { + return originalPath == null ? null : StringUtils.formatUrl(originalPath, "/"); + } + + public void setOriginalPath(String originalPath) { + this.originalPath = originalPath == null ? null : StringUtils.formatUrl(originalPath, "/"); + } + + //新增加的属性 2022/11/9 + /** + * 发票类型(出租车票,飞机票。。。) + */ + private String invoiceType; + + /** + * 消费类型 + */ + private String consumeType; + + /** + * 币种 + */ + private String currency; + + /** + * 城市 + */ + private String city; + + /** + * 供应商 + */ + private String supplier; + + /** + * 发票代码 + */ + private String invoiceCode; + + /** + * 上车时间(出租车才有) + */ + private String getOnTime; + + /** + * 下车时间(出租车才有) + */ + private String debusTime; + + /** + * 备注说明 + */ + private String descr; + + /** + * 扫描时所扫描的图片路径 + */ + private String imgPath; + + /** + * 用户所对应的客户ID(每个用户有自己所属的公司,所属的公司有所属的客户,一个客户下面可以有多个公司) + */ + private Integer client; + + private String checkCode; + + private String tax; + + private String dataJson; + + private String preTax; + + private String taxRate; + + /** + * 0 否 1 是 是否需要验真 + */ + private Boolean needValid; + + /** + * 0 否 1 是 验真状态 + */ + private Boolean validStatus; + + /** + * 验真次数 + */ + private Integer validCount; + + /** + * 当日验真次数 + */ + private Integer validDayCount; + + private String loginId; + + private String ext01;//1:自己解析,0:OCR解析,2:异常后OCR解析 + + private String ext02;//验证Fail的message + + private String ext03; + + private String ext04;//SyncInvoiceImgTask定时任务标记 + + private String ext05;//验真结果的type + + + private Integer[] matching; + + private Integer matchingPid; + + private Integer matchingId; + + private String otherFields; + + private String expenseFields; + private String tradeDate;//交易日期 + private String invoiceStatus;//发票状态 (0代表无票,1代表普票,2代表税票) + private String reimburseMoney; + private String invoiceId; + + + private String invoiceTypeCode; + private String date; + private String details; + private String kind; + private String number; + private String typeCode; + private String buyerCode; + private String sellerCode; + private String seller; + private String title; + + + private String receiptId; + + /** + * 是否发送concur:0否1是 0-未发送 1-已发送 2-已同步 + */ + private String isSend; + + private String ext06;//report_entry_id + + private String ext07;//report_id + + private String ext08;//ext40 + + private String ext09;//supplierCode + + private String ext10;//buyerCode + + public Integer[] getMatching() { + if (this.matchingPid == null || this.matchingId == null) { + return new Integer[]{0, 0}; + } + return new Integer[]{matchingPid, matchingId}; + } + + public String getImgPath() { + return imgPath == null ? null : StringUtils.formatUrl(imgPath, "/"); + } + + + private String messCn; + private String messEn; + + private String filedValue; + private String reportKey; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/PostBoxSubmitVo.java b/src/main/java/com/cmsen/ticket/domain/entity/PostBoxSubmitVo.java new file mode 100644 index 0000000..8b7c558 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/PostBoxSubmitVo.java @@ -0,0 +1,19 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/1/8 16:05 + **/ +@Data +public class PostBoxSubmitVo { + @NotNull + private List ids; + @NotNull + private Integer reportId; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/PostBoxVo.java b/src/main/java/com/cmsen/ticket/domain/entity/PostBoxVo.java new file mode 100644 index 0000000..e7a228b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/PostBoxVo.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/1/8 15:39 + **/ +@Data +public class PostBoxVo { + private String title; + private List result = new ArrayList<>(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Preferences.java b/src/main/java/com/cmsen/ticket/domain/entity/Preferences.java new file mode 100644 index 0000000..0da4d33 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Preferences.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * preferences + * + * @author + */ +@Data +public class Preferences implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 偏好设置表唯一自增主键id + */ + @ExcelIgnore + private Integer id; + /** + * 发票类型 + */ + @ExcelProperty(value = "发票类型") + private Integer invoiceType; + /** + * 消费类型 + */ + @ExcelProperty(value = "消费类型") + private String consumptionType; + /** + * 费用类型 + */ + @ExcelProperty(value = "费用类型") + private String expenseTypes; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ProxySysUser.java b/src/main/java/com/cmsen/ticket/domain/entity/ProxySysUser.java new file mode 100644 index 0000000..3dc47b6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ProxySysUser.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * proxy_sys_user + * + * @author + */ +@Data +public class ProxySysUser implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private Integer proxyId;//被代理人 + private String proxyEmail; + private String proxyUser; + private Integer mainId;//代理人 + private String mainEmail; + private String mainUser; + + private Integer puId;//proxy_user表的id +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ProxyUser.java b/src/main/java/com/cmsen/ticket/domain/entity/ProxyUser.java new file mode 100644 index 0000000..ab89834 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ProxyUser.java @@ -0,0 +1,20 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * proxy_user + * + * @author + */ +@Data +public class ProxyUser implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private Integer proxyId; + private String proxyUser; + private Integer mainId; + private String mainUser; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ReimDetailReportEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/ReimDetailReportEntity.java new file mode 100644 index 0000000..9d60574 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ReimDetailReportEntity.java @@ -0,0 +1,90 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import lombok.Data; + +/** + * ReimDetailReportEntity Data + * + * @author OWTS + * @version 1.0.0 + * @date 2021/9/1 17:08 + **/ +@ColumnWidth(20) +@Data +public class ReimDetailReportEntity { + @ExcelProperty(value = "所属公司", index = 0) + private String orgUnit2; + @ExcelProperty(value = "报销单号", index = 1) + private String reportId; + @ExcelProperty(value = "报告key", index = 2) + private String reportKey; + @ExcelProperty(value = "Employee ID", index = 3) + private String employeeId; + @ExcelProperty(value = "姓名", index = 4) + private String employeeName; + @ExcelProperty(value = "审批状态", index = 5) + private String approvalStatusName; + @ExcelProperty(value = "付款状态", index = 6) + private String paymentStatusName; + @ExcelProperty(value = "付款日期", index = 7) + private String paidDate; + @ExcelProperty(value = "政策名称", index = 8) + private String policy; + @ExcelProperty(value = "报告名称", index = 9) + private String reportName; + @ExcelProperty(value = "提交人", index = 10) + private String userLoginId; + @ExcelProperty(value = "提交日期", index = 11) + private String sumitDate; + + @ExcelProperty(value = "行ID", index = 12) + private String reportEntryId; + @ExcelProperty(value = "费用类型", index = 13) + private String expenseTypeName; + @ExcelProperty(value = "费用成本中心", index = 14) + private String orgUnit4; + @ExcelProperty(value = "交易日期", index = 15) + private String transactionDate; + @ExcelProperty(value = "报销金额", index = 16) + private String postedAmount; + @ExcelProperty(value = "币种", index = 17) + private String transactionCurrencyCode; + @ExcelProperty(value = "付款方式", index = 18) + private String paymentTypeName; + @ExcelProperty(value = "供应商", index = 19) + private String vendorDescription; + + @ExcelProperty(value = "发票代码", index = 20) + private String invoiceCode; + @ExcelProperty(value = "发票号码", index = 21) + private String invoiceNum; + @ExcelProperty(value = "Concur发票号码", index = 22) + private String concurInvoiceNum; + @ExcelProperty(value = "开票日期", index = 23) + private String invoiceDate; + @ExcelProperty(value = "销售方名称", index = 24) + private String seller; + @ExcelProperty(value = "销售方税号", index = 25) + private String sellerCode; + @ExcelProperty(value = "购买方名称", index = 26) + private String buyer; + @ExcelProperty(value = "购买方税号", index = 27) + private String buyerCode; + @ExcelProperty(value = "金额", index = 28) + private String invoiceMoney; + @ExcelProperty(value = "不含税金额", index = 29) + private String preTax; + @ExcelProperty(value = "税额", index = 30) + private String tax; + @ExcelProperty(value = "票种", index = 31) + private String invoiceType; + @ExcelProperty(value = "eReceipt_ID", index = 32) + private String eReceiptId; + @ExcelProperty(value = "警告信息", index = 33) + private String warningMess; + @ExcelProperty(value = "验真描述", index = 34) + private String vaildDesc; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ReportExportEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/ReportExportEntity.java new file mode 100644 index 0000000..922f398 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ReportExportEntity.java @@ -0,0 +1,159 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import lombok.Data; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/9/15 16:26 + **/ +@ColumnWidth(20) +@Data +public class ReportExportEntity { + @ExcelProperty(value = "组织") + private String orgUnit1; + @ExcelProperty(value = "报告ID") + private String reportId; + @ExcelProperty(value = "报告key") + private String reportKey; + @ExcelProperty(value = "姓名") + private String employeeName; + @ExcelProperty(value = "审批状态") + private String approvalStatusName; + @ExcelProperty(value = "付款状态") + private String paymentStatusName; + @ExcelProperty(value = "付款日期") + private String paidDate; + @ExcelProperty(value = "政策ID") + private String plicyId; + @ExcelProperty(value = "ORG_UNIT1") + private String orgUnit11; + @ExcelProperty(value = "ORG_UNIT2") + private String orgUnit22; + @ExcelProperty(value = "ORG_UNIT3") + private String orgUnit33; + @ExcelProperty(value = "ORG_UNIT4") + private String orgUnit44; + @ExcelProperty(value = "ORG_UNIT5") + private String orgUnit55; + @ExcelProperty(value = "ORG_UNIT6") + private String orgUnit66; + @ExcelProperty(value = "报告名称") + private String reportName; + @ExcelProperty(value = "提交人") + private String userLoginId; + @ExcelProperty(value = "提交日期") + private String sumitDate; + @ExcelProperty(value = "报告状态") + private String approvalStatusCode; + @ExcelProperty(value = "当前审核人") + private String approvalLogin; + @ExcelProperty(value = "行ID") + private String reportEntryId; + @ExcelProperty(value = "费用类型") + private String expenseTypeName; + @ExcelProperty(value = "交易日期") + private String transactionDate; + @ExcelProperty(value = "金额") + private String approvedAmount; + @ExcelProperty(value = "币种") + private String transactionCurrencyCode; + @ExcelProperty(value = "付款方式") + private String paymentTypeName; + @ExcelProperty(value = "供应商") + private String vendorDescription; + @ExcelProperty(value = "LINE_ORG_UNIT1") + private String orgUnit111; + @ExcelProperty(value = "LINE_ORG_UNIT2") + private String orgUnit222; + @ExcelProperty(value = "LINE_ORG_UNIT3") + private String orgUnit333; + @ExcelProperty(value = "LINE_ORG_UNIT4") + private String orgUnit444; + @ExcelProperty(value = "LINE_ORG_UNIT5") + private String orgUnit555; + @ExcelProperty(value = "LINE_ORG_UNIT6") + private String orgUnit666; + @ExcelProperty(value = "Custom1") + private String custom1; + @ExcelProperty(value = "Custom2") + private String custom2; + @ExcelProperty(value = "Custom3") + private String custom3; + @ExcelProperty(value = "Custom4") + private String custom4; + @ExcelProperty(value = "Custom5") + private String custom5; + @ExcelProperty(value = "Custom6") + private String custom6; + @ExcelProperty(value = "Custom7") + private String custom7; + @ExcelProperty(value = "Custom8") + private String custom8; + @ExcelProperty(value = "Custom9") + private String custom9; + @ExcelProperty(value = "Custom10") + private String custom10; + @ExcelProperty(value = "Custom11") + private String custom11; + @ExcelProperty(value = "Custom12") + private String custom12; + @ExcelProperty(value = "Custom13") + private String custom13; + @ExcelProperty(value = "Custom14") + private String custom14; + @ExcelProperty(value = "Custom15") + private String custom15; + @ExcelProperty(value = "Custom16") + private String custom16; + @ExcelProperty(value = "Custom17") + private String custom17; + @ExcelProperty(value = "Custom18") + private String custom18; + @ExcelProperty(value = "Custom19") + private String custom19; + @ExcelProperty(value = "Custom20") + private String custom20; + @ExcelProperty(value = "Custom21") + private String custom21; + @ExcelProperty(value = "Custom22") + private String custom22; + @ExcelProperty(value = "Custom23") + private String custom23; + @ExcelProperty(value = "Custom24") + private String custom24; + @ExcelProperty(value = "Custom25") + private String custom25; + @ExcelProperty(value = "Custom26") + private String custom26; + @ExcelProperty(value = "Custom27") + private String custom27; + @ExcelProperty(value = "Custom28") + private String custom28; + @ExcelProperty(value = "Custom29") + private String custom29; + @ExcelProperty(value = "Custom30") + private String custom30; + @ExcelProperty(value = "Custom31") + private String custom31; + @ExcelProperty(value = "Custom32") + private String custom32; + @ExcelProperty(value = "Custom33") + private String custom33; + @ExcelProperty(value = "Custom34") + private String custom34; + @ExcelProperty(value = "Custom35") + private String custom35; + @ExcelProperty(value = "Custom36") + private String custom36; + @ExcelProperty(value = "Custom37") + private String custom37; + @ExcelProperty(value = "Custom38") + private String custom38; + @ExcelProperty(value = "Custom39") + private String custom39; + @ExcelProperty(value = "Custom40") + private String custom40; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ReportImages.java b/src/main/java/com/cmsen/ticket/domain/entity/ReportImages.java new file mode 100644 index 0000000..83dad3b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ReportImages.java @@ -0,0 +1,39 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 面单影像 + * @TableName report_images + */ +@Data +public class ReportImages implements Serializable { + /** + * + */ + private Long id; + + /** + * + */ + private String reportId; + + /** + * + */ + private String imgUri; + + private String source; + + private Date createDate; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Result.java b/src/main/java/com/cmsen/ticket/domain/entity/Result.java new file mode 100644 index 0000000..99098bd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Result.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class Result { + + private Result result; + + private boolean success; + + private User user; + + @JsonProperty("token") + private String token; + + @Data + public static class User{ + + private Integer id; + + private String userNmae; + + private String passWord; + + private String name; + } + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Rule.java b/src/main/java/com/cmsen/ticket/domain/entity/Rule.java new file mode 100644 index 0000000..11e9e4e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Rule.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * rule + * + * @author + */ +@Data +public class Rule implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private String name; + private String messageEn; + private String messageCn; + private Integer clientId; + private Integer type; + private String typeName; + private String remark; + private String sort; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/RuleConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/RuleConfig.java new file mode 100644 index 0000000..e2c1c82 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/RuleConfig.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.domain.entity; + +import com.cmsen.common.http.response.Validation; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * rule_config + * + * @author + */ +@Data +public class RuleConfig implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + @NotNull(message = "required", groups = {Validation.Create.class}) + private Integer rule; + private String ruleName; + /** + * 0所有票种有效 + */ + @NotNull(message = "required", groups = {Validation.Create.class}) + private Integer ticketType; + private String ticketName; + private String ticketNameEn; + /** + * 1/通知 2、警告 3,禁止 + */ + private Short level; + /** + * 参数 + */ + private String params; + private Integer clientId; + @JsonIgnore + private Rule ruleInfo; + private Integer type; + private String typeName; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/RuleType.java b/src/main/java/com/cmsen/ticket/domain/entity/RuleType.java new file mode 100644 index 0000000..6623f78 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/RuleType.java @@ -0,0 +1,38 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * rule_type + * @author + */ +@Data +public class RuleType implements Serializable { + private Long id; + + /** + * code + */ + private String code; + + /** + * name + */ + private String name; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ScannerCenterFiles.java b/src/main/java/com/cmsen/ticket/domain/entity/ScannerCenterFiles.java new file mode 100644 index 0000000..17bdc65 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ScannerCenterFiles.java @@ -0,0 +1,25 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +@Data +public class ScannerCenterFiles implements Serializable { + + private int id; + private String uploadFilePath; + private String isFinished; + private int pageSize; + private int currentPage; + private Date createDate; + private Date updateDate; + private String reportId; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + private String currentDealFile; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ScannerLogs.java b/src/main/java/com/cmsen/ticket/domain/entity/ScannerLogs.java new file mode 100644 index 0000000..e57fae6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ScannerLogs.java @@ -0,0 +1,39 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import org.springframework.format.annotation.DateTimeFormat; + +import java.io.Serializable; +import java.util.Date; + +/** + * 扫描仪日志 + */ +@Data +public class ScannerLogs implements Serializable { + + private static final long serialVersionUID = 1L; + private Long id; + private String companyId; + private String costType; + private String fileName; + private Integer invoiceUpNum; + private Integer errorNum; + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date sendTime; + private String hashKey; + private String machineCode; + private String invoiceId; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + private String ext06; + private String ext07; + private String ext08; + private String ext09; + private String ext10; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/Signin.java b/src/main/java/com/cmsen/ticket/domain/entity/Signin.java new file mode 100644 index 0000000..6dc6c1b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/Signin.java @@ -0,0 +1,105 @@ +package com.cmsen.ticket.domain.entity; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * + * @TableName signin + */ +//@TableName(value ="signin") +@Data + +public class Signin implements Serializable { + + private boolean success; + + private Signin result; + /** + * + */ +// @TableId + private Integer id; + + /** + * + */ + private String eventName; + + /** + * + */ + private String eventId; + + private String meetFormat; + + /** + * + */ + private String startTime; + + /** + * + */ + private String endTime; + + /** + * + */ + private Integer relationId; + + /** + * + */ + private String organizer; + + /** + * + */ + private String coOrganizer; + + /** + * + */ + private String sponsor; + + /** + * + */ + private String longitude; + + /** + * + */ + private String latitude; + + /** + * + */ + private String activityAddress; + + /** + * + */ + private Integer signinNum; + + + @JsonProperty("qrcode") + private String QRCode; + + /** + * scene + */ + private String scene; + + /** + * 路径 + */ + private String path; + +// @TableField(exist = false) + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierBlacklist.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierBlacklist.java new file mode 100644 index 0000000..169156b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierBlacklist.java @@ -0,0 +1,41 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * null + * + * @TableName supplier_blacklist + */ +@Data +public class SupplierBlacklist implements Serializable { + /** + * This field was generated by MyBatis Generator. + * This field corresponds to the database table supplier_blacklist + * + * @mbg.generated 2021-02-23 16:00:58 + */ + private static final long serialVersionUID = 1L; + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + private Integer id; + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + private String name; + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + private String code; + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + private String taxId; + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + private Integer client; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierDiffAllow.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierDiffAllow.java new file mode 100644 index 0000000..4989a8e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierDiffAllow.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 差异配置 + * @TableName supplier_diff_allow + */ +@Data +public class SupplierDiffAllow implements Serializable { + + private Integer id; + + private Integer orgId; + + private Integer corTypeId; + + private Boolean diffAllow; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderHeader.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderHeader.java new file mode 100644 index 0000000..070296d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderHeader.java @@ -0,0 +1,468 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +/** + * supplier_order_header + * @author + */ +@Data +public class SupplierOrderHeader implements Serializable { + /** + * 唯一主键 + */ + private String billId; + + /** + * 单据编号 + */ + private String billNumber; + + /** + * 单据名称 + */ + private String billName; + + /** + * 标题特殊备注 + */ + private String billNameRemark; + + /** + * 发票类型 + */ + private String invoiceType; + + /** + * 业务类型 + */ + private String businessType; + + /** + * 所属公司Code + */ + private String companyCode; + + /** + * 所属公司 + */ + private String companyName; + + /** + * 成本中心Code + */ + private String orgCode; + + /** + * 成本中心 + */ + private String orgName; + + /** + * 币种 + */ + private String currency; + + /** + * 付款金额 + */ + private BigDecimal payAmount; + + /** + * 约定/计划付款时间 + */ + private String payDate; + + /** + * 申请人 + */ + private String applyMan; + + /** + * GS项目批号 + */ + private String gsNum; + + /** + * OA通用项目批号 + */ + private String oaNum; + + /** + * 供应商Code + */ + private String supplierCode; + + /** + * 供应商名称 + */ + private String supplierName; + + /** + * 开户行分行 + */ + private String branchBank; + + /** + * 账户信息 + */ + private String accountInfo; + + /** + * 付款类型 + */ + private String payType; + + /** + * 援引源引非经营性采购流程 + */ + private String nonPurchase; + + /** + * 源引采购下单流程 + */ + private String purchase; + + /** + * 源引相关合同流程 + */ + private String contract; + + /** + * 主流程品牌市场 + */ + private String brand; + + /** + * 抄送干系人 + */ + private String stakeholder; + + /** + * 店铺支付宝账户 + */ + private String alipay; + + /** + * 活动开始时间 + */ + private String activityStartTime; + + /** + * 活动结束时间 + */ + private String activityEndTime; + + /** + * 保证金冻结开始时间 + */ + private String freezeStartTime; + + /** + * 保证金冻结结束时间 + */ + private String freezeEndTime; + + /** + * 是否为数字营销:0-是 1-否 + */ + private String isDigitalMarket; + + /** + * 是否为内部员工工资付款:0-是 1-否 + */ + private String isInnerPay; + + /** + * 是否为境内(不包括港澳台地区)公司对境外公司(包括港澳台地区)的付款:0-是 1-否 + */ + private String isAbroadPay; + + /** + * 审批意见 + */ + private String approvalComment; + + /** + * 提交日期 + */ + private String submitDate; + + /** + * 是否收票:0是, 1否,2 无需收票 + */ + private String isCollect; + + /** + * 是否匹配完成:0是, 1否 + */ + private String isMatch; + + /** + * 状态: 0-草稿 2-上级审批 4-财务节点2 6-出纳付款 8-发票匹配 10-财务节点3 12-归档 99-撤销 + */ + private String status; + + private String isDel; + + /** + * 所属人 + */ + private String owner; + private String ownerNames; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + private String ext01;//记录workflowId + + private String ext02;//是否收票同步:0是1否 + + private String ext03;//是否修改明细行成本中心:0是1否 + + private String ext04;//记录上级审批标记:1--不可撤回 + + private String ext05;//记录经由转办的人员 + + private String ext06; + + private String ext07; + + private String ext08; + + private String ext09; + + private String ext10; + + /** + * 援引收货流程 + */ + private String received; + + /** + * 援引内结流程 + */ + private String internal; + + /** + * 是否有相关合同流程:0-是 1-否 + */ + private String havContract; + + /** + * 是否有发票照片:0-是 1-否 + */ + private String havInvoice; + + /** + * Kol名字 + */ + private String kolName; + + /** + * 姓名 + */ + private String kolFullName; + + /** + * 身份证号码 + */ + private String uid; + + /** + * 供应商类型:1-企业 0-个人 + */ + private String supplierType; + + /** + * 是否白名单:0-是 1-否 + */ + private String isWhiteList; + + /** + * 白名单公司 + */ + private String whiteCompany; + + /** + * 其他公司 + */ + private String otherCompany; + + //援引合同信息 + private InvokeContract invokeContract; + + //援引采购信息 + private InvokePurchase invokePurchase; + + //援引品牌信息 + private InvokeBrand invokeBrand; + + //援引收货 + private InvokeReceive invokeReceive; + + //援引内结 + private InvokeInternal invokeInternal; + + private static final long serialVersionUID = 1L; + + private String statusStr; + + public String getStatusStr() { + if (status == null) { + return null; + } + switch (status) { + case "0": + return "草稿"; + case "2": + return "上级审批"; + case "4": + return "行业财务主管2"; + case "6": + return "出纳付款"; + case "8": + return "发票匹配"; + case "10": + return "行业财务主管3"; + case "12": + return "归档"; + case "99": + return "驳回"; + default: + return null; + } + } + + private String invoiceTypeId;//0-先票 1-后票 2-无票 + public String getInvoiceTypeId() { + if (invoiceType == null) { + return null; + } + switch (invoiceType) { + case "先票": + return "0"; + case "后票": + return "1"; + case "后票充值": + return "1"; + case "无票": + return "2"; + case "形式发票先票": + return "0"; + case "形式发票后票": + return "1"; + default: + return null; + } + } + + private String isRecharge; + public String getIsRecharge() { + if (invoiceType == null) { + return null; + } + switch (invoiceType) { + case "先票": + return "1"; + case "后票": + return "1"; + case "后票充值": + return "0"; + case "无票": + return "1"; + case "形式发票先票": + return "1"; + case "形式发票后票": + return "1"; + default: + return null; + } + } + + private String workflowIdType; + public String getWorkflowIdType() { + if (businessType == null) { + return null; + } + switch (businessType) { + case "普通付款申请单": + return "WORKFLOWID_NORMAL"; + case "采购付款申请单": + return "WORKFLOWID_PURCHASE"; + case "品牌服务&市场推广付款申请单": + return "WORKFLOWID_BRAND"; + default: + return null; + } + } + + private String isProforma;//是否形式发票:0是1否 + public String getIsProforma() { + if (invoiceType == null) { + return null; + } + switch (invoiceType) { + case "先票": + return "1"; + case "后票": + return "1"; + case "后票充值": + return "1"; + case "无票": + return "1"; + case "形式发票先票": + return "0"; + case "形式发票后票": + return "0"; + default: + return null; + } + } + + private String invoiceTypeKZ;//发票类型控制 + public String getInvoiceTypeKZ() { + if (invoiceType == null) { + return null; + } + switch (invoiceType) { + case "先票": + return "0"; + case "形式发票先票": + return "1"; + case "后票": + return "2"; + case "后票充值": + return "3"; + case "形式发票后票": + return "4"; + case "无票": + return "5"; + default: + return null; + } + } + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderRefund.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderRefund.java new file mode 100644 index 0000000..1d53c9b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOrderRefund.java @@ -0,0 +1,69 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import org.springframework.format.annotation.DateTimeFormat; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author lm + * + */ +@Data +public class SupplierOrderRefund implements Serializable { + + private static final long serialVersionUID = 1L; + @ExcelProperty(value = "ID", index = 1) + private Integer id; + private String receiveNo; + @ExcelProperty(value = "供应商代码", index = 0) + private String supplierCode; + @ExcelProperty(value = "订单编号", index = 2) + private String orderNo; + @ExcelProperty(value = "数量", index = 7) + private String goodsNum; + @ExcelProperty(value = "收货", index = 8) + private String receivedNum; + @ExcelProperty(value = "单价", index = 10) + private String unitPrice; + @ExcelProperty(value = "金额", index = 11) + private String amount; + @ExcelProperty(value = "ITEM", index = 4) + private String itemNo; + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8") + private Date createDate; + private int status; + + @ExcelIgnore + private String ext01; + @ExcelIgnore + private String ext02; + @ExcelIgnore + private String ext03; + @ExcelIgnore + private String ext04; + @ExcelIgnore + private String ext05;//剩余匹配金额 + + private String vStatusName; + + public String getvStatusName() { + + switch (status){ + case 0: + return "新增"; + case 1: + return "已处理"; + case 2: + return "已发送EBS"; + default: + return ""; + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierOwnerTransfer.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOwnerTransfer.java new file mode 100644 index 0000000..97f9ad2 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierOwnerTransfer.java @@ -0,0 +1,85 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * supplier_owner_transfer + * @author + */ +@Data +public class SupplierOwnerTransfer implements Serializable { + private Long id; + + /** + * 上一次转办ID + */ + private Long lastId; + + /** + * 单据ID + */ + private String billId; + + /** + * 所有者 + */ + private String owner; + + /** + * 原始创建者 + */ + private String creator; + + /** + * 原有审批人from + */ + private String current; + + /** + * 目标审批人to + */ + private String target; + + /** + * 状态:0-无效 1-有效 2-撤销 + */ + private String status; + + private String isDel; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierPo.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierPo.java new file mode 100644 index 0000000..c34e5be --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierPo.java @@ -0,0 +1,119 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * supplier_po + * @author + */ +@Data +public class SupplierPo { + private Integer id; + + private String po; + + /** + * 版本 + */ + private String versionNo; + + /** + * 订单日期 + */ + private String orderDate; + + /** + * 合同编号 + */ + private String contractNo; + + /** + * 采购公司Code + */ + private String companyCode; + + /** + * 供应商编码 + */ + private String supplierCode; + + /** + * 供应商名称 + */ + private String supplierName; + + /** + * 金额 + */ + private String netAmount; + + /** + * 币种 + */ + private String currency; + + /** + * 成本中心 + */ + private String costCenter; + + /** + * 下单人 + */ + private String requestersName; + + /** + * po类型 + */ + private String poType; + + private String process; + + /** + * 联系人 + */ + private String contacts; + + /** + * 电子邮件 + */ + private String mailAddress; + + /** + * 附件存储地址 + */ + private String path; + + /** + * 附件访问地址 + */ + private String uri; + + private Boolean isDel; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + private String createBy; + + private Date createDate; + + private String updateBy; + + private Date updateDate; + + private List line = new ArrayList<>(); + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierPoLine.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierPoLine.java new file mode 100644 index 0000000..06b82d3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierPoLine.java @@ -0,0 +1,112 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * supplier_po_line + * @author + */ +@Data +public class SupplierPoLine implements Serializable { + private Integer id; + + private String po; + + /** + * 合同编号 + */ + private String contract; + + /** + * 供应商编号 + */ + private String supplierCode; + + /** + * 物料号 + */ + private String materialNo; + + /** + * 物料描述 + */ + private String materialDesc; + + /** + * 行号 + */ + private String lineNo; + + /** + * 付款日期 + */ + private String payDate; + + /** + * 数量 + */ + private String quantity; + + /** + * 单位 + */ + private String unit; + + /** + * 单价 + */ + private String unitPrice; + + /** + * 增值税额 + */ + private String tax; + + /** + * 折扣 + */ + private String discount; + + /** + * po行总额 + */ + private String netLineAmount; + + private String ext01;//记录当次导入 + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 创建人 + */ + private String updateBy; + + /** + * 创建时间 + */ + private Date updateDate; + + private String isDel; + + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SupplierSite.java b/src/main/java/com/cmsen/ticket/domain/entity/SupplierSite.java new file mode 100644 index 0000000..8c9bf98 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SupplierSite.java @@ -0,0 +1,27 @@ +package com.cmsen.ticket.domain.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author jared.Yan (yanhuaiwen@163.com) + */ +@Data +public class SupplierSite implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private String code; + private String siteCode; + private Integer orgId; + private String email; + private String source; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date syncTime; + private Boolean enable; + private String vEnableName; + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") + private Date vSyncDate; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/SysNotification.java b/src/main/java/com/cmsen/ticket/domain/entity/SysNotification.java new file mode 100644 index 0000000..7977f62 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/SysNotification.java @@ -0,0 +1,45 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 系统通知 + * + * @TableName sys_notification + */ +@Data +public class SysNotification implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + private Integer id; + /** + * 标题 + */ + private String title; + /** + * 内容 + */ + private String content; + /** + * 级别 + */ + private Byte level; + /** + * 更新时间 + */ + private Date updateTime; + private String updateTime1; + /** + * 排序 + */ + private Integer sort; + /** + * 删除标记 + */ + private Boolean isDel; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/T10Attendee.java b/src/main/java/com/cmsen/ticket/domain/entity/T10Attendee.java new file mode 100644 index 0000000..ae7a595 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/T10Attendee.java @@ -0,0 +1,143 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * t_10_attendee + * + * @author + */ +@Data +public class T10Attendee implements Serializable { + private static final long serialVersionUID = 1L; + /** + * UUID + */ + private String id; + /** + * OCRID + */ + private String ocrId; + private String attendId; + /** + * ocr状态 + */ + private String ocrFlag; + /** + * 参与人类型 + */ + private String attendeeTypeCode; + /** + * 参与人类型Id + */ + private String attendeeTypeId; + /** + * 名 + */ + private String firstName; + /** + * 姓 + */ + private String lastName; + /** + * 中间名 + */ + private String middleinitial; + /** + * 前缀 + */ + private String suffix; + /** + * 公司 + */ + private String company; + /** + * 标题 + */ + private String title; + /** + * 外部Id + */ + private String externalId; + /** + * 年例外 + */ + private String hasExceptionsPrevYear; + /** + * 例外 + */ + private String hasExceptionsYtd; + /** + * 去年金额 + */ + private String totalAmountPrevYear; + /** + * 金额 + */ + private String totalAmountYtd; + /** + * 版本 + */ + private String versionNumber; + /** + * 所属名称 + */ + private String ownerName; + /** + * 所属人登录Id + */ + private String ownerLoginId; + /** + * 货币 + */ + private String currencyCode; + /** + * 是否激活 + */ + private String active; + + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String custom5; + private String custom6; + private String custom7; + private String custom8; + private String custom9; + private String custom10; + private String custom11; + private String custom12; + private String custom13; + private String custom14; + private String custom15; + private String custom16; + private String custom17; + private String custom18; + private String custom19; + private String custom20; + private String custom21; + private String custom22; + private String custom23; + private String custom24; + private String custom25; + + private String attributer1; + private String attributer2; + private String attributer3; + private String attributer4; + private String attributer5; + + private String invoiceId; + + /** + * 备注信息 + */ + private String remarks; + + public String getName() { + return (this.lastName == null ? "" : this.lastName) + (this.firstName == null ? "" : this.firstName); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeExt.java b/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeExt.java new file mode 100644 index 0000000..c679896 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeExt.java @@ -0,0 +1,76 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * t_10_attendee_ext + * @author + */ +@Data +public class T10AttendeeExt implements Serializable { + private Long id; + + /** + * extId + */ + private String extId; + + /** + * 讲者 + */ + private String speaker; + + /** + * 电话 + */ + private String speakerTel; + + /** + * 邮箱 + */ + private String speakerEmail; + + private String isDel; + + private String ext01; + + private String ext02; + + private String ext03; + + private String ext04; + + private String ext05; + + /** + * 创建人 + */ + private String createBy; + + /** + * 创建时间 + */ + private Date createDate; + + /** + * 更新人 + */ + private String updateBy; + + /** + * 更新时间 + */ + private Date updateDate; + + /** + * 备注 + */ + private String remark; + + private static final long serialVersionUID = 1L; + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeType.java b/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeType.java new file mode 100644 index 0000000..3d8565e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/T10AttendeeType.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * t_10_attendee_type + * + * @author + */ +@Data +public class T10AttendeeType implements Serializable { + private static final long serialVersionUID = 1L; + /** + * UUID + */ + private String id; + /** + * ocr状态 + */ + private String ocrFlag; + /** + * 名称 + */ + private String name; + /** + * 编码 + */ + private String code; + /** + * 表单Id + */ + private String attendFormId; + /** + * 连接Id + */ + private String connectorId; + /** + * 类型Id + */ + private String typeId; + /** + * 备注信息 + */ + private String remarks; + private Byte tag; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/T10Employee.java b/src/main/java/com/cmsen/ticket/domain/entity/T10Employee.java new file mode 100644 index 0000000..92efccd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/T10Employee.java @@ -0,0 +1,303 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +@Data +public class T10Employee implements Serializable { + private static final long serialVersionUID = 1L; + /** + * UUID + */ + private String id; + /** + * 员工Id + */ + private String empId; + /** + * 邮箱 + */ + private String userEmail; + /** + * 登录Id + */ + private String loginId; + /** + * 姓名-名 + */ + private String firstName; + /** + * 姓名-姓 + */ + private String lastName; + /** + * 组织1 + */ + private String orgUnit1; + /** + * 组织2 + */ + private String orgUnit2; + /** + * 组织3 + */ + private String orgUnit3; + /** + * 组织4 + */ + private String orgUnit4; + /** + * + */ + private String orgUnit5; + /** + * + */ + private String orgUnit6; + /** + * 属性1 + */ + private String attributer1; + /** + * 属性2 + */ + private String attributer2; + /** + * 属性3 + */ + private String attributer3; + /** + * 属性4 + */ + private String attributer4; + /** + * 属性5 + */ + private String attributer5; + /** + * 属性6 + */ + private String attributer6; + /** + * 属性7 + */ + private String attributer7; + /** + * 属性8 + */ + private String attributer8; + /** + * 属性9 + */ + private String attributer9; + /** + * 属性10 + */ + private String attributer10; + /** + * 创建者 + */ + private String createBy; + /** + * 创建时间 + */ + private Date createDate; + /** + * 更新者 + */ + private String updateBy; + /** + * 更新时间 + */ + private Date updateDate; + /** + * 备注信息 + */ + private String remarks; + /** + * + */ + private String expenseApprover; + /** + * + */ + private String expenseApproverEmployeeid; + /** + * 扩展11 + */ + private String ext11; + /** + * 扩展11 + */ + private String ext12; + /** + * 扩展11 + */ + private String ext13; + /** + * 扩展11 + */ + private String ext14; + /** + * 扩展11 + */ + private String ext15; + /** + * 扩展11 + */ + private String ext16; + /** + * 扩展11 + */ + private String ext17; + /** + * 扩展11 + */ + private String ext18; + /** + * 扩展11 + */ + private String ext19; + /** + * 扩展11 + */ + private String ext20; + /** + * 是否激活 + */ + private String active; + /** + * 科目 + */ + private String cashAdvanceAccountCode; + /** + * crnKey + */ + private String crnKey; + /** + * ctryCode + */ + private String ctryCode; + /** + * subCode + */ + private String ctrySubCode; + /** + * 自定义1 + */ + private String custom1; + /** + * 自定义 + */ + private String custom2; + /** + * 自定义 + */ + private String custom3; + /** + * 自定义 + */ + private String custom4; + /** + * 自定义 + */ + private String custom5; + /** + * 自定义 + */ + private String custom6; + /** + * 自定义 + */ + private String custom7; + /** + * 自定义 + */ + private String custom8; + /** + * 自定义 + */ + private String custom9; + /** + * 自定义 + */ + private String custom10; + /** + * 自定义 + */ + private String custom11; + /** + * 自定义 + */ + private String custom12; + /** + * 自定义 + */ + private String custom13; + /** + * 自定义 + */ + private String custom14; + /** + * 自定义 + */ + private String custom15; + /** + * 自定义 + */ + private String custom16; + /** + * 自定义 + */ + private String custom17; + /** + * 自定义 + */ + private String custom18; + /** + * 自定义 + */ + private String custom19; + /** + * 自定义 + */ + private String custom20; + /** + * 自定义 + */ + private String custom21; + /** + * 是否发票审批 + */ + private String invoiceApprover; + /** + * 发票审批人 + */ + private String invoiceUser; + /** + * 是否测试 + */ + private String isTestEmp; + /** + * ledgerkey + */ + private String ledgerKey; + /** + * ledgerName + */ + private String ledgerName; + /** + * 本地名 + */ + private String localeName; + /** + * 是否临时用户 + */ + private String tripUser; + /** + * mi + */ + private String mi; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/TPublicWorkday.java b/src/main/java/com/cmsen/ticket/domain/entity/TPublicWorkday.java new file mode 100644 index 0000000..3312c98 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/TPublicWorkday.java @@ -0,0 +1,33 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 国家法定节假日表_dabaohong_2022-05-10 + * @TableName t_public_workday + */ +@Data +public class TPublicWorkday implements Serializable { + /** + * + */ + private Long id; + + /** + * 日期 + */ + private Date workDay; + + /** + * 工作日:0; +法定节假日:1; +周末加班调休:2; +周末 :3; + */ + private Integer dayType; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/TaxMapping.java b/src/main/java/com/cmsen/ticket/domain/entity/TaxMapping.java new file mode 100644 index 0000000..515296c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/TaxMapping.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * null + * + * @TableName tax_mapping + */ +@Data +public class TaxMapping implements Serializable { + /** + * This field was generated by MyBatis Generator. + * This field corresponds to the database table tax_mapping + * + * @mbg.generated 2021-02-25 13:15:04 + */ + private static final long serialVersionUID = 1L; + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + private Integer id; + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + private String taxRate; + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + private String code; + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + private Integer client; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/TicketType.java b/src/main/java/com/cmsen/ticket/domain/entity/TicketType.java new file mode 100644 index 0000000..8c92b55 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/TicketType.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * ticket_type + * + * @author + */ +@Data +public class TicketType implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 票种表唯一自增主键 + */ + private Integer id; + /** + * 票种的值 + */ + private String value; + private Integer pid; + /** + * 0为未删除,1为已删除,默认为0 + */ + private String isDel; + /** + * 语言 + */ + private String language; + private String code; + private String invctype; + private Boolean isErcpt; + private String taxRate; + + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/TicketTypeMapping.java b/src/main/java/com/cmsen/ticket/domain/entity/TicketTypeMapping.java new file mode 100644 index 0000000..e33da58 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/TicketTypeMapping.java @@ -0,0 +1,39 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 发票类型匹配表 + * @TableName ticket_type_mapping + */ +@Data +public class TicketTypeMapping implements Serializable { + /** + * + */ + private Integer id; + + /** + * 票种code + */ + private String ticketCode; + + /** + * 发票title + */ + private String title; + + /** + * 票种mapping + */ + private String ticketCodeMapping; + + /** + * 是否可用 + */ + private Boolean active; + + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/TokenDetail.java b/src/main/java/com/cmsen/ticket/domain/entity/TokenDetail.java new file mode 100644 index 0000000..c2b7198 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/TokenDetail.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Date; + +/** + * token 详细信息实体类 + * + * @author Wray + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class TokenDetail { + private Integer userId; + private String openId; + private Date ExpiryTime; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/UploadInvoiceDetailEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/UploadInvoiceDetailEntity.java new file mode 100644 index 0000000..b7766b9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/UploadInvoiceDetailEntity.java @@ -0,0 +1,73 @@ +package com.cmsen.ticket.domain.entity; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import lombok.Data; + +/** + * UploadInvoiceDetail Data + * + * @author OWTS + * @version 1.0.0 + * @date 2021/9/1 17:08 + **/ +@ColumnWidth(20) +@Data +public class UploadInvoiceDetailEntity { + @ExcelProperty(value = "eReceipt _ID", index = 0) + private String receiptId; + @ExcelProperty(value = "员工姓名", index = 1) + private String employeeName; + @ExcelProperty(value = "Employee ID", index = 2) + private String employeeId; + @ExcelProperty(value = "发票日期", index = 3) + private String invoiceDate; + @ExcelProperty(value = "发票代码", index = 4) + private String invoiceCode; + @ExcelProperty(value = "发票号码", index = 5) + private String invoiceNum; + @ExcelProperty(value = "发票金额", index = 6) + private String invoiceMoney; + @ExcelProperty(value = "税额", index = 7) + private String tax; + @ExcelProperty(value = "票种", index = 8) + private String invoiceType; + @ExcelProperty(value = "购买方", index = 9) + private String buyer; + @ExcelProperty(value = "供应方", index = 10) + private String seller; + @ExcelProperty(value = "发票类型", index = 11) + private String invoiceType2; + @ExcelProperty(value = "上传时间", index = 12) + private String uploadTime; + @ExcelProperty(value = "发票状态", index = 13) + private String invoiceStatus; + + @ExcelProperty(value = "组织", index = 14) + private String orgUnit2; + @ExcelProperty(value = "费用成本中心", index = 15) + private String orgUnit4; + @ExcelProperty(value = "报告ID", index = 16) + private String reportId; + @ExcelProperty(value = "报告key", index = 17) + private String reportKey; + @ExcelProperty(value = "Login ID", index = 18) + private String loginId; + @ExcelProperty(value = "状态", index = 19) + private String approvalStatusName; + @ExcelProperty(value = "付款状态", index = 20) + private String paymentStatusName; + @ExcelProperty(value = "付款日期", index = 21) + private String paidDate; + @ExcelProperty(value = "政策名称", index = 22) + private String policy; + @ExcelProperty(value = "报告名称", index = 23) + private String reportName; + @ExcelProperty(value = "费用类型", index = 24) + private String expenseTypeName; + @ExcelProperty(value = "提交日期", index = 25) + private String sumitDate; + @ExcelProperty(value = "验真描述", index = 26) + private String vaildDesc; + +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/UserConfigList.java b/src/main/java/com/cmsen/ticket/domain/entity/UserConfigList.java new file mode 100644 index 0000000..6f23fc1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/UserConfigList.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * user_config_list + * + * @author + */ +@Data +public class UserConfigList implements Serializable { + private static final long serialVersionUID = 1L; + private Integer id; + private Integer userId; + private String params1; + private String params2; + private String params3; + private String params4; + private String params5; + private String type; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/UserGuide.java b/src/main/java/com/cmsen/ticket/domain/entity/UserGuide.java new file mode 100644 index 0000000..0186e6d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/UserGuide.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 用户向导 + * + * @TableName user_guide + */ +@Data +public class UserGuide implements Serializable { + private static final long serialVersionUID = 1L; + /** + * + */ + private Integer id; + /** + * 标题 + */ + private String title; + /** + * 标题 + */ + private String titleEn; + /** + * 内容 + */ + private String content; + /** + * 内容 + */ + private String contentEn; + /** + * 更新时间 + */ + private Date updateTime; + /** + * 排序 + */ + private Integer sort; + /** + * 删除标记 + */ + private Boolean isDel; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/UserPc.java b/src/main/java/com/cmsen/ticket/domain/entity/UserPc.java new file mode 100644 index 0000000..e37f40a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/UserPc.java @@ -0,0 +1,95 @@ +package com.cmsen.ticket.domain.entity; + + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; +/** + * user_pc + * @author + */ +@Data +public class UserPc implements Serializable { + /** + * 用户的唯一标识自增id + */ + private Integer userId; + + /** + * 用户对应的微信openID + */ + private String openid; + + /** + * 用户姓名 + */ + private String username; + + /** + * 用户密码 + */ + private String pwd; + + /** + * 用户年龄 + */ + private String age; + + /** + * 用户邮箱 + */ + private String email; + + /** + * 用户电话 + */ + private String tel; + + /** + * 0为未删除,1为已删除,默认为0 + */ + private String isDel; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 更新时间 + */ + private Date updateTime; + + /** + * 用户的语言状态(比如cn=中文,en=英语) + */ + private String languageType; + + /** + * 验证码 + */ + private Integer verificationCode; + + /** + * 验证时间 + */ + private String verifyTime; + + /** + * 所属公司ID + */ + private Integer companyId; + + private Integer client; + + /** + * 0/未验证 1/已验证 + */ + private String isChecked; + + private static final long serialVersionUID = 1L; + + private String type; + private BandConfig bandConfig; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/ValueSetConfig.java b/src/main/java/com/cmsen/ticket/domain/entity/ValueSetConfig.java new file mode 100644 index 0000000..753b70b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/entity/ValueSetConfig.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.entity; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class ValueSetConfig implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer id; + private String category; + private String listId; + private String parma1; + private String param2; + private String param3; +} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/baozun/Invoke2Entity.java b/src/main/java/com/cmsen/ticket/domain/entity/baozun/Invoke2Entity.java deleted file mode 100644 index 8031e66..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/baozun/Invoke2Entity.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.cmsen.ticket.domain.entity.baozun; - -import lombok.Data; - -import java.io.Serializable; - -/** - * 援引 - * @author - */ -@Data -public class Invoke2Entity implements Serializable { - //requestid - private String requestid; - //流程名称 - private String requestname; - //创建时间 - private String createdate; - //流程编号 - private String LCBH; - //收款方成本中心 - private String DEPARTMENT_CODE_CR; - //申请人 - private String shenqingren; - //付款方所属公司 - private String FKFSSGS; - //收款方所属公司 - private String SKFSSGS; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/collect/CollectCompany.java b/src/main/java/com/cmsen/ticket/domain/entity/collect/CollectCompany.java deleted file mode 100644 index bb4bbf7..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/collect/CollectCompany.java +++ /dev/null @@ -1,632 +0,0 @@ -package com.cmsen.ticket.domain.entity.collect; - -import java.util.Date; - -public class CollectCompany { - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.id - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String id; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.company_name - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String companyName; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.tax_no - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String taxNo; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext1 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext1; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext2 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext2; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext3 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext3; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext4 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext4; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext5 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext5; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext6 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext6; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext7 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext7; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext8 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext8; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext9 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext9; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.ext10 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String ext10; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.del_flag - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String delFlag; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.create_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String createBy; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.update_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private Date updateDate; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.update_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String updateBy; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.create_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private Date createDate; - - /** - * - * This field was generated by MyBatis Generator. - * This field corresponds to the database column collect_company.remarks - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - private String remarks; - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.id - * - * @return the value of collect_company.id - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getId() { - return id; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.id - * - * @param id the value for collect_company.id - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setId(String id) { - this.id = id == null ? null : id.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.company_name - * - * @return the value of collect_company.company_name - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getCompanyName() { - return companyName; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.company_name - * - * @param companyName the value for collect_company.company_name - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setCompanyName(String companyName) { - this.companyName = companyName == null ? null : companyName.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.tax_no - * - * @return the value of collect_company.tax_no - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getTaxNo() { - return taxNo; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.tax_no - * - * @param taxNo the value for collect_company.tax_no - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setTaxNo(String taxNo) { - this.taxNo = taxNo == null ? null : taxNo.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext1 - * - * @return the value of collect_company.ext1 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt1() { - return ext1; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext1 - * - * @param ext1 the value for collect_company.ext1 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt1(String ext1) { - this.ext1 = ext1 == null ? null : ext1.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext2 - * - * @return the value of collect_company.ext2 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt2() { - return ext2; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext2 - * - * @param ext2 the value for collect_company.ext2 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt2(String ext2) { - this.ext2 = ext2 == null ? null : ext2.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext3 - * - * @return the value of collect_company.ext3 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt3() { - return ext3; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext3 - * - * @param ext3 the value for collect_company.ext3 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt3(String ext3) { - this.ext3 = ext3 == null ? null : ext3.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext4 - * - * @return the value of collect_company.ext4 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt4() { - return ext4; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext4 - * - * @param ext4 the value for collect_company.ext4 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt4(String ext4) { - this.ext4 = ext4 == null ? null : ext4.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext5 - * - * @return the value of collect_company.ext5 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt5() { - return ext5; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext5 - * - * @param ext5 the value for collect_company.ext5 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt5(String ext5) { - this.ext5 = ext5 == null ? null : ext5.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext6 - * - * @return the value of collect_company.ext6 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt6() { - return ext6; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext6 - * - * @param ext6 the value for collect_company.ext6 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt6(String ext6) { - this.ext6 = ext6 == null ? null : ext6.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext7 - * - * @return the value of collect_company.ext7 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt7() { - return ext7; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext7 - * - * @param ext7 the value for collect_company.ext7 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt7(String ext7) { - this.ext7 = ext7 == null ? null : ext7.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext8 - * - * @return the value of collect_company.ext8 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt8() { - return ext8; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext8 - * - * @param ext8 the value for collect_company.ext8 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt8(String ext8) { - this.ext8 = ext8 == null ? null : ext8.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext9 - * - * @return the value of collect_company.ext9 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt9() { - return ext9; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext9 - * - * @param ext9 the value for collect_company.ext9 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt9(String ext9) { - this.ext9 = ext9 == null ? null : ext9.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.ext10 - * - * @return the value of collect_company.ext10 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getExt10() { - return ext10; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.ext10 - * - * @param ext10 the value for collect_company.ext10 - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setExt10(String ext10) { - this.ext10 = ext10 == null ? null : ext10.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.del_flag - * - * @return the value of collect_company.del_flag - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getDelFlag() { - return delFlag; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.del_flag - * - * @param delFlag the value for collect_company.del_flag - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setDelFlag(String delFlag) { - this.delFlag = delFlag == null ? null : delFlag.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.create_by - * - * @return the value of collect_company.create_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getCreateBy() { - return createBy; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.create_by - * - * @param createBy the value for collect_company.create_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setCreateBy(String createBy) { - this.createBy = createBy == null ? null : createBy.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.update_date - * - * @return the value of collect_company.update_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public Date getUpdateDate() { - return updateDate; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.update_date - * - * @param updateDate the value for collect_company.update_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.update_by - * - * @return the value of collect_company.update_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getUpdateBy() { - return updateBy; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.update_by - * - * @param updateBy the value for collect_company.update_by - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setUpdateBy(String updateBy) { - this.updateBy = updateBy == null ? null : updateBy.trim(); - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.create_date - * - * @return the value of collect_company.create_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public Date getCreateDate() { - return createDate; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.create_date - * - * @param createDate the value for collect_company.create_date - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - /** - * This method was generated by MyBatis Generator. - * This method returns the value of the database column collect_company.remarks - * - * @return the value of collect_company.remarks - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public String getRemarks() { - return remarks; - } - - /** - * This method was generated by MyBatis Generator. - * This method sets the value of the database column collect_company.remarks - * - * @param remarks the value for collect_company.remarks - * - * @mbg.generated Tue Oct 17 20:56:34 CST 2023 - */ - public void setRemarks(String remarks) { - this.remarks = remarks == null ? null : remarks.trim(); - } -} \ No newline at end of file diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/AddAttendeeDto.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/AddAttendeeDto.java deleted file mode 100644 index cafb139..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/AddAttendeeDto.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/10/28 13:51 - **/ - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -@Data -public class AddAttendeeDto { - @JsonProperty("AttendeeTypeCode") - private String AttendeeTypeCode; - @JsonProperty("AttendeeTypeID") - private String AttendeeTypeID; - @JsonProperty("FirstName") - private String FirstName; - @JsonProperty("LastName") - private String LastName; - @JsonProperty("Company") - private String Company; - @JsonProperty("Title") - private String Title; - @JsonProperty("ID") - private String ID; - @JsonProperty("OwnerLoginID") - private String OwnerLoginID; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendDetail.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendDetail.java deleted file mode 100644 index e9cc1de..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendDetail.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AttendDetail { - @JsonProperty("ID") - private String ID; - @JsonProperty("EntryID") - private String EntryID; - @JsonProperty("AttendeeID") - private String AttendeeID; - @JsonProperty("Amount") - private String Amount; - @JsonProperty("AssociatedAttendeeCount") - private String AssociatedAttendeeCount; - @JsonProperty("AssociatedAttendeeID") - private String AssociatedAttendeeID; - @JsonProperty("Custom1") - private String Custom1; - @JsonProperty("Custom2") - private String Custom2; - @JsonProperty("Custom3") - private String Custom3; - @JsonProperty("Custom4") - private String Custom4; - @JsonProperty("Custom5") - private String Custom5; - @JsonProperty("AttendeeStatus") - private String AttendeeStatus; - @JsonProperty("TaskID") - private String TaskID; - - public String getID() { - return ID; - } - - public void setID(String ID) { - this.ID = ID; - } - - public String getEntryID() { - return EntryID; - } - - public void setEntryID(String entryID) { - EntryID = entryID; - } - - public String getAttendeeID() { - return AttendeeID; - } - - public void setAttendeeID(String attendeeID) { - AttendeeID = attendeeID; - } - - public String getAmount() { - return Amount; - } - - public void setAmount(String amount) { - Amount = amount; - } - - public String getAssociatedAttendeeCount() { - return AssociatedAttendeeCount; - } - - public void setAssociatedAttendeeCount(String associatedAttendeeCount) { - AssociatedAttendeeCount = associatedAttendeeCount; - } - - public String getCustom1() { - return Custom1; - } - - public void setCustom1(String custom1) { - Custom1 = custom1; - } - - public String getCustom2() { - return Custom2; - } - - public void setCustom2(String custom2) { - Custom2 = custom2; - } - - public String getCustom3() { - return Custom3; - } - - public void setCustom3(String custom3) { - Custom3 = custom3; - } - - public String getCustom4() { - return Custom4; - } - - public void setCustom4(String custom4) { - Custom4 = custom4; - } - - public String getCustom5() { - return Custom5; - } - - public void setCustom5(String custom5) { - Custom5 = custom5; - } - - public String getAttendeeStatus() { - return AttendeeStatus; - } - - public void setAttendeeStatus(String attendeeStatus) { - AttendeeStatus = attendeeStatus; - } - - public String getTaskID() { - return TaskID; - } - - public void setTaskID(String taskID) { - TaskID = taskID; - } - - public String getAssociatedAttendeeID() { - return AssociatedAttendeeID; - } - - public void setAssociatedAttendeeID(String associatedAttendeeID) { - AssociatedAttendeeID = associatedAttendeeID; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendListData.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendListData.java deleted file mode 100644 index 2f2f31d..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/AttendListData.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import java.util.List; -import java.util.Map; - -/** - * attend接收参数类 - */ -public class AttendListData { - private boolean state; - - private List> data; - - private String message; - - private int totalCount; - - private String errCode; - - public boolean getState() { - return this.state; - } - - public void setState(boolean state) { - this.state = state; - } - - public List> getData() { - return this.data; - } - - public void setData(List> data) { - this.data = data; - } - - public String getMessage() { - return this.message; - } - - public void setMessage(String message) { - this.message = message; - } - - public int getTotalCount() { - return this.totalCount; - } - - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } - - public String getErrCode() { - return this.errCode; - } - - public void setErrCode(String errCode) { - this.errCode = errCode; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/CityResult.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/CityResult.java deleted file mode 100644 index 00c060d..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/CityResult.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.List; - -/** - * @Author OWTS > - * @Date 2020/11/12 - * @Description - */ -public class CityResult { - @JsonProperty("total") - private int totalNum; - @JsonProperty("rows") - private List rows = new ArrayList<>(); - - public CityResult() { - } - - @Override - public String toString() { - return "CityResult{" + - "totalNum=" + totalNum + - ", rows=" + rows + - '}'; - } - - public int getTotalNum() { - return totalNum; - } - - public void setTotalNum(int totalNum) { - this.totalNum = totalNum; - } - - public List getRows() { - return rows; - } - - public void setRows(List rows) { - this.rows = rows; - } - - public static class ConcurCity { - @JsonProperty("staType") - private String staType; - @JsonProperty("staName") - private String staName; - @JsonProperty("cityCode") - private String cityCode; - @JsonProperty("cityName") - private String cityName; - @JsonProperty("custom1") - private String custom1; - @JsonProperty("custom2") - private String custom2; - @JsonProperty("custom3") - private String custom3; - @JsonProperty("custom4") - private String custom4; - @JsonProperty("updateDate") - private String updateDate; - - public ConcurCity() { - } - - @Override - public String toString() { - return "ConcurCity{" + - "staType='" + staType + '\'' + - ", staName='" + staName + '\'' + - ", cityCode='" + cityCode + '\'' + - ", cityName='" + cityName + '\'' + - ", custom1='" + custom1 + '\'' + - ", custom2='" + custom2 + '\'' + - ", custom3='" + custom3 + '\'' + - ", custom4='" + custom4 + '\'' + - ", updateDate='" + updateDate + '\'' + - '}'; - } - - public String getUpdateDate() { - return updateDate; - } - - public void setUpdateDate(String updateDate) { - this.updateDate = updateDate; - } - - public String getStaType() { - return staType; - } - - public void setStaType(String staType) { - this.staType = staType; - } - - public String getStaName() { - return staName; - } - - public void setStaName(String staName) { - this.staName = staName; - } - - public String getCityCode() { - return cityCode; - } - - public void setCityCode(String cityCode) { - this.cityCode = cityCode; - } - - public String getCityName() { - return cityName; - } - - public void setCityName(String cityName) { - this.cityName = cityName; - } - - public String getCustom1() { - return custom1; - } - - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - public String getCustom2() { - return custom2; - } - - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - public String getCustom3() { - return custom3; - } - - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - public String getCustom4() { - return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurConfigEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurConfigEntity.java deleted file mode 100644 index 292932b..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurConfigEntity.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * @Author OWTS > - * @Date 2020/11/18 - * @Description - */ -@Component -@Data -@ConfigurationProperties(prefix = "concur") -public class ConcurConfigEntity { - private Boolean active; - private Boolean syncUserActive; - private String baseUrl; - private String tokenRoute = "/sys/login"; - private String userName; - private String password; - - private String delegators = "/ocr/getDelegators"; - - private String wechatSend = "/weixin/addReport"; - - private String createReportRoute = "/ocr/createReport"; - private String getReportStateRoute = "/ocr/getReportStateNew"; - - private String getReportV4State = "/ocr/getReportV4State"; - - private String getTaxRateInfoV4 = "/ocr/getTaxRateInfoV4"; - - private String upReportRoute = "/ocr/upReport"; - private String upEntryRoute = "/ocr/upEntry"; - private String delEntryRoute = "/ocr/delEntry"; - private String checkEntryRoute = "/ocr/checkEntryList"; - - private String checkEntryReportRoute = "/ocr/checkEntry"; - - private String checkPeceiptIdRoute = "/ocr/getReceiptState"; - - private String checkEntryExist = "/ocr/getEntryMesg"; - - - private String t10Employee = "/today/employee/t10Employee/list"; - - private String reportMain = "/today/report/t10ReportMain/list"; - - private String attendeeList = "/ocr/attend/t10Attendee/list"; - - private String poList = "/c009/podetail/tC009PoNumber/list"; - - private String addAttendee = "/ocr/addAttend"; - - private String reportById = "/today/report/t10ReportMain/queryById"; - - private String entryItemization = "/today/report/t10EntryItemization/list"; - - private String entryItemizationById = "/today/report/t10EntryItemization/queryById"; - - private String entryAssociations = "/today/report/t10EntryAssociations/list"; - - private String getImageId = "/ocr/getEntryImageId"; - - private String upInvoiceState = "/ocr/upInvoiceState"; - - private String upReceiptV4 = "/ocr/upReceiptEntryV4"; - - private String upTaxRateV4 = "/ocr/upTaxRateV4"; - - private String abPolicy = "/sfdc/policy/tSfPolicy/list"; - - private String createWeChatProcess = "/today/flow/createStartFormData"; - - private String submitWeChatProcess = "/today/flow/submitFormData"; - - private String rollbackWeChatProcess = "/today/flow/deleteProcIns"; - - private String entryImages = "/ocr/getEntryImage"; - private String sendApInvoice = "/today/kettle/setOcrId"; - - private String contractView = "/contract/getView"; - private String contractCancel = "/contract/Undo"; - - private String approveReport = "/ocr/approveReport"; - private String approveReportV4 = "/ocr/approveReportV4"; - - private String submitReportV4 = "/ocr/submitReportV4"; - - private String upReportV4Custom = "/ocr/upReportV4Custom"; - - //配置是否进行getConcurImage的定时任务 - private boolean entryImagesActive = true; - - private ConcurLoginInfo concurLoginInfo; - private OcrConcur ocrConcur; - - private Guni guni; - - - @Data - public static class ConcurLoginInfo { - private String userName; - private String count; - private String secret; - private String token; - } - - @Data - public static class OcrConcur { - private String templateID; - private String execUser; - private String action; - } - - @Data - public static class Guni { - private boolean active; - private String loginUrl; - private String listUrl; - private String userName; - private String secret; - private int count; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurEntryEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurEntryEntity.java deleted file mode 100644 index 2a752f1..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurEntryEntity.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * @Author OWTS > - * @Date 2020/11/18 - * @Description - */ -@Data -public class ConcurEntryEntity { - //是否电子票,从票种配置表中获取 - @JsonProperty("ERCPT") - public String ERCPT; - //报销单明细ID - private String entryId; - //报销人邮箱 - private String loginId; - //拍照人Email - @JsonProperty("CreatedBy") - private String CreatedBy; - //备注 - @JsonProperty("BZ") - private String BZ; - //费用类型 Category,expense Type ID - @JsonProperty("FYDL") - private String FYDL; - //地址ID - @JsonProperty("DD") - private String DD; - //费率类型 - private String FYXL; - //Report ID - @JsonProperty("ReportID") - private String ReportID; - //Amount报销金额 - @JsonProperty("BSJE") - private String BSJE; - //Currency货币类型 - @JsonProperty("Currency") - private String Currency; - //供应商说明 - @JsonProperty("GYS") - private String GYS; - //发票类型 - private String third_type; - //税率 - private String tax; - @JsonProperty("FYRQ") - private String FYRQ; //交易日期 - @JsonProperty("FPHM") - private String FPHM; - @JsonProperty("FPDM") - private String FPDM; - @JsonProperty("ID") - private String ID; //任务ID - @JsonProperty("CreatedTime") - private String CreatedTime; //任务创建时间 - @JsonProperty("RowNumber") - private String RowNumber; - @JsonProperty("Title") - private String Title; //任务标题 - @JsonProperty("Folder") - private String Folder; //发票夹ID - @JsonProperty("CFCS") - private String CFCS; //从哪里 - @JsonProperty("DDCS") - private String DDCS; //到哪里 - @JsonProperty("name") - private String name; //Concur Logon ID - @JsonProperty("type") - private String type; - @JsonProperty("invctype") - private String invctype; - //税码 - @JsonProperty("TAXCODE") - private String TAXCODE; - //发票分类,从票种配置表中获取 - @JsonProperty("FPCAT") - private String FPCAT; - - @JsonProperty("isValid") - private String isValid; - - @JsonProperty("TAXITYPE") - private String TAXITYPE; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurLoginForm.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurLoginForm.java deleted file mode 100644 index e742d7c..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurLoginForm.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @Author OWTS > - * @Date 2020/11/12 - * @Description - */ -@Data -@NoArgsConstructor -public class ConcurLoginForm { - private String userName; - private String count; - private String secret; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurResponse.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurResponse.java deleted file mode 100644 index 92d7288..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ConcurResponse.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -/** - * @Author OWTS > - * @Date 2020/12/8 - * @Description - */ -@Data -public class ConcurResponse { - private Boolean state; - private String message; - private Object data; - private Integer totalCount; - private String errCode; - - public ConcurResponse(Boolean state, String message, Object data, Integer totalCount, String errCode) { - this.state = state; - this.message = message; - this.data = data; - this.totalCount = totalCount; - this.errCode = errCode; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/Delegators.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/Delegators.java deleted file mode 100644 index 9088375..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/Delegators.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -@Data -public class Delegators { - private String msg; - private int code; - private boolean success; - @JsonProperty("dataList") - private List dataList = new ArrayList<>(); - - @Data - public static class Delegator { - @JsonProperty("ConcurID") - private String ConcurID; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/InvoicePictureEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/InvoicePictureEntity.java deleted file mode 100644 index b6dbe33..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/InvoicePictureEntity.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -/** - * @Author OWTS > - * @Date 2020/11/17 - * @Description - */ -@Data -public class InvoicePictureEntity { - private String fileName; - private String base64; - private String filePath; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemizationDetail.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemizationDetail.java deleted file mode 100644 index 22ae00b..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemizationDetail.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ItemizationDetail { - @JsonProperty("ID") - private String ID; - @JsonProperty("EntryID") - private String EntryID; - @JsonProperty("ReportID") - private String ReportID; - @JsonProperty("ReportOwnerID") - private String ReportOwnerID; - @JsonProperty("ExpenseTypeCode") - private String ExpenseTypeCode; - @JsonProperty("ExpenseTypeName") - private String ExpenseTypeName; - @JsonProperty("SpendCategoryCode") - private String SpendCategoryCode; - @JsonProperty("SpendCategoryName") - private String SpendCategoryName; - @JsonProperty("TransactionDate") - private String TransactionDate; - @JsonProperty("TransactionAmount") - private String TransactionAmount; - @JsonProperty("ItemId") - private String ItemId; - /*@JsonProperty("Custom1") - private String Custom1; - @JsonProperty("Custom2") - private String Custom2; - @JsonProperty("Custom3") - private String Custom3; - @JsonProperty("Custom4") - private String Custom4; - @JsonProperty("Custom5") - private String Custom5; - @JsonProperty("Custom13") - private String Custom13;*/ - @JsonProperty("Status") - private String Status; - @JsonProperty("TaskID") - private String TaskID; - @JsonProperty("ExpenseTypeId") - private Integer ExpenseTypeId; - - public String getID() { - return ID; - } - - public void setID(String ID) { - this.ID = ID; - } - - public String getEntryID() { - return EntryID; - } - - public void setEntryID(String entryID) { - EntryID = entryID; - } - - public String getReportID() { - return ReportID; - } - - public void setReportID(String reportID) { - ReportID = reportID; - } - - public String getReportOwnerID() { - return ReportOwnerID; - } - - public void setReportOwnerID(String reportOwnerID) { - ReportOwnerID = reportOwnerID; - } - - public String getExpenseTypeCode() { - return ExpenseTypeCode; - } - - public void setExpenseTypeCode(String expenseTypeCode) { - ExpenseTypeCode = expenseTypeCode; - } - - public String getExpenseTypeName() { - return ExpenseTypeName; - } - - public void setExpenseTypeName(String expenseTypeName) { - ExpenseTypeName = expenseTypeName; - } - - public String getSpendCategoryCode() { - return SpendCategoryCode; - } - - public void setSpendCategoryCode(String spendCategoryCode) { - SpendCategoryCode = spendCategoryCode; - } - - public String getSpendCategoryName() { - return SpendCategoryName; - } - - public void setSpendCategoryName(String spendCategoryName) { - SpendCategoryName = spendCategoryName; - } - - public String getTransactionDate() { - return TransactionDate; - } - - public void setTransactionDate(String transactionDate) { - TransactionDate = transactionDate; - } - - public String getTransactionAmount() { - return TransactionAmount; - } - - public void setTransactionAmount(String transactionAmount) { - TransactionAmount = transactionAmount; - } - - public String getItemId() { - return ItemId; - } - - public void setItemId(String itemId) { - ItemId = itemId; - } - - /*public String getCustom1() { - return Custom1; - } - - public void setCustom1(String custom1) { - Custom1 = custom1; - } - - public String getCustom2() { - return Custom2; - } - - public void setCustom2(String custom2) { - Custom2 = custom2; - } - - public String getCustom3() { - return Custom3; - } - - public void setCustom3(String custom3) { - Custom3 = custom3; - } - - public String getCustom4() { - return Custom4; - } - - public void setCustom4(String custom4) { - Custom4 = custom4; - } - - public String getCustom5() { - return Custom5; - } - - public void setCustom5(String custom5) { - Custom5 = custom5; - }*/ - - public String getStatus() { - return Status; - } - - public void setStatus(String status) { - Status = status; - } - - public String getTaskID() { - return TaskID; - } - - public void setTaskID(String taskID) { - TaskID = taskID; - } - - public Integer getExpenseTypeId() { - return ExpenseTypeId; - } - - public void setExpenseTypeId(Integer expenseTypeId) { - ExpenseTypeId = expenseTypeId; - } - - /*public String getCustom13() { - return Custom13; - } - - public void setCustom13(String custom13) { - Custom13 = custom13; - }*/ -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemzationListData.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemzationListData.java deleted file mode 100644 index fb576f5..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ItemzationListData.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import java.util.List; -import java.util.Map; - -/** - * attend接收参数类 - */ -public class ItemzationListData { - private boolean state; - - private List> data; - - private String message; - - private int totalCount; - - private String errCode; - - public boolean getState() { - return this.state; - } - - public void setState(boolean state) { - this.state = state; - } - - public List> getData() { - return this.data; - } - - public void setData(List> data) { - this.data = data; - } - - public String getMessage() { - return this.message; - } - - public void setMessage(String message) { - this.message = message; - } - - public int getTotalCount() { - return this.totalCount; - } - - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } - - public String getErrCode() { - return this.errCode; - } - - public void setErrCode(String errCode) { - this.errCode = errCode; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListIdEntityDto.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ListIdEntityDto.java deleted file mode 100644 index 537f2ed..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListIdEntityDto.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -@Data -public class ListIdEntityDto { - @JsonProperty("Data") - private List Data; - - @Data - public static class ListIdEntity { - @JsonProperty("Code") - private String Code; - @JsonProperty("Name") - private String Name; - @JsonProperty("DataType") - private String DataType; - @JsonProperty("ParentID") - private String ParentID; - @JsonProperty("isDisable") - private int isDisable; - @JsonProperty("ListID") - private String ListID; - @JsonProperty("ListItemID") - private String ListItemID; - @JsonProperty("Ext01") - private String Ext01; - @JsonProperty("Ext02") - private String Ext02; - @JsonProperty("Ext03") - private String Ext03; - @JsonProperty("Ext04") - private String Ext04; - @JsonProperty("Ext05") - private String Ext05; - @JsonProperty("Ext06") - private String Ext06; - @JsonProperty("Ext07") - private String Ext07; - @JsonProperty("Ext08") - private String Ext08; - @JsonProperty("Ext09") - private String Ext09; - @JsonProperty("Ext10") - private String Ext10; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemDTO.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemDTO.java deleted file mode 100644 index bfe2406..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemDTO.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.alibaba.excel.annotation.write.style.ColumnWidth; -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/9/6 14:52 - **/ -@EqualsAndHashCode -@ColumnWidth(20) -@Data -public class ListItemDTO { - private String id; - private String createDate; - private String updateDate; - private String name; - private String listId; - private String listitemId; - private String codeO; - private String codeTw; - private String codeTh; - private String codeF; - private String codeFi; - private String codeS; - private String attributer1; - private String attributer2; - private String attributer3; - private String attributer4; - private String attributer5; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemV4DTO.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemV4DTO.java deleted file mode 100644 index 3550334..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/ListItemV4DTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/9/6 14:52 - **/ -@EqualsAndHashCode -@Data -public class ListItemV4DTO { - private String id; - private String createDate; - private String updateDate; - private String listItemId; - private String listCode; - private String shortCode; - private String listValue; - private String parentId; - private String listLevel; - private String hasChildren; - private String isDeleted; - private String listId; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/LoginResult.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/LoginResult.java deleted file mode 100644 index 05ebb8e..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/LoginResult.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * @Author OWTS > - * @Date 2020/12/8 - * @Description - */ -@Data -public class LoginResult { - @JsonProperty("Token") - private String Token; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/MeituanEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/MeituanEntity.java deleted file mode 100644 index 50fd179..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/MeituanEntity.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -@Data -public class MeituanEntity { - @JsonProperty("Date") - private String Date; - - @JsonProperty("Type") - private String Type; - - @JsonProperty("creditCard") - private String creditCard; - - @JsonProperty("Restarant") - private String Restarant; - - @JsonProperty("Attendee") - private String Attendee; - - @JsonProperty("Amount") - private String Amount; - - @JsonProperty("Currecy") - private String Currecy; - - @JsonProperty("Status") - private String Status; - - @JsonProperty("ActualAttend") - private String ActualAttend; - - @JsonProperty("Remark") - private String Remark; - - @JsonProperty("isCheck") - private String isCheck; - - @JsonProperty("Reason") - private String Reason; - - @JsonProperty("Result") - private String Result; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/PoItem.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/PoItem.java deleted file mode 100644 index 9695962..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/PoItem.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/11/23 17:32 - */ -@Data -public class PoItem { - private String id; - private String poName; - private String poNo; - private String userCostTotal; - private String ownerName; - private String ownerEmpId; - private String ownerEmail; - private String attributer1; - private String surplus; - private String listItemId; - private String poExpenseCode; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/PostBoxEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/PostBoxEntity.java deleted file mode 100644 index 798a3d7..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/PostBoxEntity.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -import java.util.List; - -/** - * @author fengql - * @date 2024/5/9 10:24 - * @description - */ -@Data -public class PostBoxEntity { - private String imgUrl; - private String loginId; - private String ocrId; - private BoxData data; - - @Data - public static class BoxData { - - private String schema; - private String issueDate; - private String type; - private String invoiceSeries; - private String invoiceNumber; - private String verificationCode; - private String isElectronic; - private String companyTaxId; - private String companyName; - private String startDateTime; - private String sellerTaxId; - private String dateTime; - private String total; - private String tax; - private String taxRate; - private String currencyCode; - private String ocrId; - private List payments; - private Seller seller; - } - - @Data - public static class Payment { - private String amount; - } - - @Data - public static class Seller { - private String name; - private Location location; - } - - @Data - public static class Location { - private Address address; - } - - @Data - public static class Address { - private String streetAddress; - private String addressCountry; - private String addressLocality; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventEntity.java deleted file mode 100644 index cae6114..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.cmsen.common.http.response.Validation; -import lombok.Data; - -import javax.validation.constraints.NotNull; -import java.util.List; - -/** - * @author OWTS > - * @version 1.0.0 - * @date 2021/6/4 10:12 - * @desc PRC EVENT JSON - */ -@Data -public class PrcEventEntity { - @NotNull(groups = Validation.Create.class, message = "loginId must not be null") - private String loginId; - @NotNull(groups = Validation.Create.class, message = "reportId must not be null") - private String reportId; - /** - * 1:正常插入invoice2:source插入invoice_tmp3:deduction插入invoice_tmp - */ - private String queryFlag; - private List lines; - - @Data - public static class Line { - private String expenseType; - private String entryId; - private String pdfUrl; - private String entryMoney; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventReturn.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventReturn.java deleted file mode 100644 index f80c369..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/PrcEventReturn.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -/** - * @author OWTS > - * @version 1.0.0 - * @date 2021/6/4 10:15 - * @desc ticket - */ -@Data -public class PrcEventReturn { - private String entryId; - private String number; - private String number2; - private String money="0"; - private Result result; - - @Data - public static class Result { - /** - * 200 校验成功 - * 202 错误 发票号码重复 - * 204 发票金额小于报销金额 - * 206 警告 验真、连号。。。 - */ - private Integer code = 200; - private String message = ""; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/SendFolderEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/SendFolderEntity.java deleted file mode 100644 index d5d1933..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/SendFolderEntity.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * @Author OWTS > - * @Date 2020/11/13 - * @Description - */ -@Data -public class SendFolderEntity { - @Data - public static class UnSendRequest { - private String pageIndex; - private String pageSize; - private String taskId; - } - - @Data - public static class ResponseDate { - @JsonProperty("RowNumber") - private String RowNumber; - @JsonProperty("UserName") - private String UserName; - @JsonProperty("FolderName") - private String FolderName; - @JsonProperty("FolderID") - private String FolderID; - @JsonProperty("GroupName") - private String GroupName; - } - - @Data - public static class UpdateFolderRequest { - private Integer folderId; - private String reportKey; - private String message; - private String status; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/SendReportEntity.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/SendReportEntity.java deleted file mode 100644 index 6cfe7a6..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/SendReportEntity.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * @Author OWTS > - * @Date 2020/11/13 - * @Description - */ -@Data -public class SendReportEntity { - - @Data - public static class ReportRequest { - private String templateId; - private String pageIndex; - private String pageSize; - private ItemSearch itemSearch; -// private String taskId; - } - - @Data - public static class ItemSearch { - @JsonProperty("FPZT") - private String FPZT; - @JsonProperty("taskId") - private String taskId; - } - - @Data - public static class UpdateReportRequest { - @JsonProperty("userName") - private String userName; //员工编号 - @JsonProperty("title") - private String title; //任务标题 - @JsonProperty("action") - private String action; //动作 - @JsonProperty("createdtime") - private String createdtime; //任务创建时间 - @JsonProperty("id") - private String id; //任务id - @JsonProperty("execUser") - private String execUser; //执行用户 - @JsonProperty("FPZT") - private String FPZT; //发票整体状态 - @JsonProperty("CSZT") - private String CSZT; //接口状态 - @JsonProperty("CSSBYY") - private String CSSBYY; //失败原因 - @JsonProperty("entryId") - private String entryId; - } - - @Data - public static class Response { - private boolean state; - private String message; - private List data; - private int totalCount; - } - - @Data - public static class ResponseDate { - //是否电子票,从票种配置表中获取 - @JsonProperty("ERCPT") - public String ERCPT; - @JsonProperty("ID") - private String ID; //任务ID - @JsonProperty("CreatedTime") - private String CreatedTime; //任务创建时间 - @JsonProperty("CreatedBy") - private String CreatedBy; //拍照人Email - @JsonProperty("RowNumber") - private String RowNumber; - @JsonProperty("Title") - private String Title; //任务标题 - @JsonProperty("FPDM") - private String FPDM; //发票代码 - @JsonProperty("FPHM") - private String FPHM; //发票号码 - @JsonProperty("Folder") - private String Folder; //发票夹ID - @JsonProperty("ReportID") - private String ReportID; //Report Id - @JsonProperty("FYDL") - private String FYDL; //费用类型 - @JsonProperty("BSJE") - private String BSJE; //报销金额 - @JsonProperty("Currency") - private String Currency; //货币类型 - @JsonProperty("FYRQ") - private String FYRQ; //交易日期 - @JsonProperty("CFCS") - private String CFCS; //从哪里 - @JsonProperty("DDCS") - private String DDCS; //到哪里 - @JsonProperty("GYS") - private String GYS; //Vendor Name - @JsonProperty("DD") - private String DD; //城市 - @JsonProperty("BZ") - private String BZ; //comment意见 - @JsonProperty("name") - private String name; //Concur Logon ID - @JsonProperty("type") - private String type; - @JsonProperty("FYXL") - private String FYXL; - @JsonProperty("invctype") - private String invctype; - //税码 - @JsonProperty("TAXCODE") - private String TAXCODE; - //发票分类,从票种配置表中获取 - @JsonProperty("FPCAT") - private String FPCAT; - @JsonProperty("tax") - private String tax; - - @JsonProperty("isValid") - private String isValid; - - @JsonProperty("ZSTS") - private String ZSTS; - - @JsonProperty("TAXITYPE") - private String TAXITYPE; - } - - @Data - public static class InvoiceDeleteRequest { - @JsonProperty("RowNumber") - private String RowNumber; - @JsonProperty("id") - private String id; - @JsonProperty("entryId") - private String entryId; - @JsonProperty("reportId") - private String reportId; - @JsonProperty("userLogin") - private String userLogin; - @JsonProperty("flag") - private String flag; - } - - @Data - public static class InvoiceLogRequest { - @JsonProperty("id") - private String id; - @JsonProperty("status") - private String status; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpInvoiceStateDto.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/UpInvoiceStateDto.java deleted file mode 100644 index 3f34617..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpInvoiceStateDto.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/11/23 17:10 - */ -@Data -public class UpInvoiceStateDto { - private String reportId; - private String loginId; - private String invoiceNum; - private String invoiceNum2; - private String imageId; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateAttendeeData.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateAttendeeData.java deleted file mode 100644 index be202d5..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateAttendeeData.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/10/28 13:28 - **/ -@Data -public class UpdateAttendeeData { - @JsonProperty("Data") - private List Data; - - - @lombok.Data - public static class Data { - @JsonProperty("Id") - private String Id; - @JsonProperty("AttendeeID") - private String AttendeeID; - @JsonProperty("AttendeeStatus") - private String AttendeeStatus; - @JsonProperty("AssociatedAttendeeID") - private String AssociatedAttendeeID; - @JsonProperty("TaskID") - private String TaskID; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateItemzationData.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateItemzationData.java deleted file mode 100644 index 55ede53..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/UpdateItemzationData.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/10/28 10:59 - **/ -@Data -public class UpdateItemzationData { - - @JsonProperty("Data") - private List Data; - - - @lombok.Data - public static class Data { - @JsonProperty("Id") - private String Id; - @JsonProperty("ReportID") - private String ReportID; - @JsonProperty("TransactionAmount") - private String TransactionAmount; - @JsonProperty("ItemId") - private String ItemId; - @JsonProperty("Status") - private Integer Status; - @JsonProperty("TaskID") - private String TaskID; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatCallback.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatCallback.java deleted file mode 100644 index a704eef..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatCallback.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -@Data -public class WeChatCallback { - private String requestId; - //审批状态:1-审批中;2-已同意;3-已驳回;4-已转审 - private String action; - private String approvalMsg; -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceBody.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceBody.java deleted file mode 100644 index f0a0de6..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceBody.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -@Data -public class WeChatInvoiceBody { - private String createUser; - private String approverUser; - private String reportName; - private Long reportCreateDate; //单据日期(yyyy-MM-dd) - private String reportMoney; - private List reportDetail = new ArrayList<>(); -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceDetail.java b/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceDetail.java deleted file mode 100644 index e53ec9f..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/concur/WeChatInvoiceDetail.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.cmsen.ticket.domain.entity.concur; - -import lombok.Data; - -@Data -public class WeChatInvoiceDetail { - private Long detailDate; //明细日期(yyyy-MM-dd) - private String detailMoney; - private String detailPurpose; //明细用途 - private String detailType; //明细类型 - private String detailRate; //明细费率 - private String detailHasExceptions; //明细是否例外 - private String detailImg; //明细图片 -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/manager/ComplianceCheck.java b/src/main/java/com/cmsen/ticket/domain/entity/manager/ComplianceCheck.java deleted file mode 100644 index a3d7f55..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/manager/ComplianceCheck.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.cmsen.ticket.domain.entity.manager; - -import com.alibaba.excel.annotation.ExcelIgnore; -import com.alibaba.excel.annotation.ExcelProperty; -import lombok.Data; - -import java.io.Serializable; - -@Data -public class ComplianceCheck implements Serializable { - private static final long serialVersionUID = 1L; - @ExcelIgnore - private Integer id; - //报告ID - @ExcelProperty(value = "单据号", index = 1) - private String reportId; - //检查结果 0 一致 1 不一致 - @ExcelIgnore - private Integer checkStatus; - - @ExcelProperty(value = "检查状态", index = 0) - private String checkStatusStr; - //提交人 - @ExcelProperty(value = "提交人", index = 2) - private String submitter; - //更新时间 - @ExcelProperty(value = "更新时间", index = 3) - private String updateTime; - //报销金额 - @ExcelProperty(value = "报销金额", index = 4) - private String reimbursement; - //发票类型 - @ExcelProperty(value = "发票类型", index = 5) - private String invoiceType; - //发票日期 - @ExcelProperty(value = "发票日期", index = 6) - private String invoiceDate; - //发票号码 - @ExcelProperty(value = "发票号码", index = 7) - private String invoiceNumber; - //检查结果 0未触发异常 1 有警告信息 2 有错误信息 - @ExcelIgnore - private Integer checkResult; - @ExcelProperty(value = "校验结果", index = 8) - private String checkResultStr; - //校验信息 - @ExcelProperty(value = "异常原因", index = 9) - private String errMsg; - //处理结果 - @ExcelProperty(value = "处理结果", index = 10) - private String dealResult; - //数据来源 - @ExcelProperty(value = "数据来源", index = 11) - private String dataSource; - //创建时间 - @ExcelIgnore - private String createTime; - - @ExcelIgnore - private String dealType; - @ExcelIgnore - private String dealIdea; - - @ExcelIgnore - private Integer originalId; - @ExcelIgnore - private String entryId; - @ExcelIgnore - private String invoiceMoney; - - @ExcelIgnore - private String expenseTypeName; - @ExcelIgnore - private String currencyCode; - @ExcelIgnore - private String ext40;//预检信息 - @ExcelIgnore - private int compCheck;//特殊标记 - - public String getCheckStatusStr() { - if (checkStatus == null) return ""; - switch (checkStatus) { - case 0: - return "未触发异常"; - case 1: - return "有警告信息"; - case 2: - return "有错误信息"; - default: - return ""; - } - } - - public String getCheckResultStr() { - if (checkResult == null) return ""; - switch (checkResult) { - case 0: - return "未触发异常"; - case 1: - return "有警告信息"; - case 2: - return "有错误信息"; - default: - return ""; - } - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImage.java b/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImage.java deleted file mode 100644 index 964a6ad..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImage.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.cmsen.ticket.domain.entity.manager; - -import com.alibaba.excel.annotation.ExcelIgnore; -import com.alibaba.excel.annotation.ExcelProperty; -import com.cmsen.common.util.StringUtil; -import lombok.Data; - -import java.io.Serializable; -import java.util.Date; - -/** - * 影像查询主表 - * - * @TableName invoice_image - */ -@Data -public class InvoiceImage implements Serializable { - - private static final long serialVersionUID = 1L; - - @ExcelIgnore - private Integer id; - /** - * 源主键 - */ - @ExcelIgnore - private String originalId; - /** - * 来源 - */ - @ExcelIgnore - private String source; - /** - * 发票代码 - */ - @ExcelProperty(value = "发票代码") - private String code; - /** - * 发票号码 - */ - @ExcelProperty(value = "发票号码") - private String number; - /** - * 开票日期 - */ - @ExcelProperty(value = "发票日期") - private String date; - - @ExcelProperty(value = "金额") - private String pretaxAmount; - - @ExcelProperty(value = "总金额") - private String total; - - @ExcelProperty(value = "税额") - private String tax; - - @ExcelIgnore - private String checkCode; - - @ExcelProperty(value = "销售方名称") - private String seller; - - @ExcelProperty(value = "销售方税号") - private String sellerTaxId; - /** - * 消费类型 - */ - @ExcelProperty(value = "消费类型") - private String kind; - - @ExcelProperty(value = "购买方税号") - private String buyerTaxId; - - @ExcelProperty(value = "购买方名称") - private String buyer; - - @ExcelProperty(value = "发票内容") - private String itemNames; - - /*@ExcelProperty(value = "NPO")*/ - private String po; - - @ExcelProperty(value = "付款日期") - private String paidDate; - - @ExcelProperty(value = "创建日期") - private Date createDate; - /** - * 操作人 - */ - @ExcelProperty(value = "提交人") - private String operator; - - @ExcelProperty(value = "报销单号码") - private String reportId; - - @ExcelProperty(value = "报销人") - private String reportOwner; - - @ExcelProperty(value = "报销单金额") - private String reportMoney; - - @ExcelIgnore - private Integer status; - - @ExcelIgnore - private String imgUri; - - @ExcelIgnore - private String originalUri; - - @ExcelIgnore - private String fileName; - - @ExcelIgnore - private String downloadUri; - - @ExcelIgnore - private String currency; - - @ExcelProperty(value = "发票类型") - private String invoiceType; - - @ExcelIgnore - private String passenger; - - @ExcelIgnore - private String seatType; - - @ExcelIgnore - private String startStation; - - @ExcelIgnore - private String endStation; - - @ExcelIgnore - private Integer deductStatus; - - @ExcelIgnore - private String taxRate; - - @ExcelIgnore - private Boolean validStatus; - - @ExcelIgnore - private Integer expenseTypeId; - @ExcelIgnore - private String entryId; - @ExcelIgnore - private String reimbursementAmount; - - @ExcelIgnore - private String postedAmount; - - @ExcelIgnore - private String dataJson; - - @ExcelIgnore - private String employeeName; - @ExcelIgnore - private String reportTotal; - - @ExcelIgnore - private String ext01; - - public String getFileName() { - if (StringUtil.isNotEmpty(this.originalUri)) { - return this.checkCode + "_" + this.number + this.originalUri.substring(this.originalUri.lastIndexOf(".")); - } - return StringUtil.isEmpty(this.imgUri) ? "null" : this.checkCode + "_" + this.number + this.imgUri.substring(this.imgUri.lastIndexOf(".")); - } - - public String getDownloadUri() { - if (StringUtil.isNotEmpty(this.originalUri)) { - return this.originalUri; - } - return this.imgUri; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImg.java b/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImg.java deleted file mode 100644 index 46de206..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/manager/InvoiceImg.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.cmsen.ticket.domain.entity.manager; - -import com.alibaba.excel.annotation.ExcelIgnore; -import com.alibaba.excel.annotation.ExcelProperty; -import com.cmsen.common.util.StringUtil; -import lombok.Data; - -import java.io.Serializable; -import java.util.Date; - -/** - * 影像查询主表 非App - * - * @TableName invoice_img - */ -@Data -public class InvoiceImg implements Serializable { - - private static final long serialVersionUID = 1L; - - @ExcelIgnore - private Integer id; - /** - * 源主键 - */ - @ExcelIgnore - private String originalId; - /** - * 来源 - */ - @ExcelIgnore - private String source; - /** - * 发票代码 - */ - @ExcelProperty(value = "发票代码") - private String code; - /** - * 发票号码 - */ - @ExcelProperty(value = "发票号码") - private String number; - /** - * 开票日期 - */ - @ExcelProperty(value = "发票日期") - private String date; - - @ExcelProperty(value = "金额") - private String pretaxAmount; - - @ExcelProperty(value = "总金额") - private String total; - - @ExcelProperty(value = "税额") - private String tax; - - @ExcelIgnore - private String checkCode; - - @ExcelProperty(value = "销售方名称") - private String seller; - - @ExcelProperty(value = "销售方税号") - private String sellerTaxId; - /** - * 消费类型 - */ - @ExcelProperty(value = "消费类型") - private String kind; - - @ExcelProperty(value = "购买方税号") - private String buyerTaxId; - - @ExcelProperty(value = "购买方名称") - private String buyer; - - @ExcelProperty(value = "发票内容") - private String itemNames; - - /*@ExcelProperty(value = "NPO")*/ - private String po; - - @ExcelProperty(value = "付款日期") - private String paidDate; - - @ExcelProperty(value = "创建日期") - private Date createDate; - /** - * 操作人 - */ - @ExcelProperty(value = "提交人") - private String operator; - - @ExcelProperty(value = "报销单号码") - private String reportId; - - @ExcelProperty(value = "报销人") - private String reportOwner; - - @ExcelProperty(value = "报销单金额") - private String reportMoney; - - @ExcelIgnore - private Integer status; - - @ExcelIgnore - private String imgUri; - - @ExcelIgnore - private String originalUri; - - @ExcelIgnore - private String fileName; - - @ExcelIgnore - private String downloadUri; - - @ExcelIgnore - private String currency; - - @ExcelProperty(value = "发票类型") - private String invoiceType; - - @ExcelIgnore - private String passenger; - - @ExcelIgnore - private String seatType; - - @ExcelIgnore - private String startStation; - - @ExcelIgnore - private String endStation; - - @ExcelIgnore - private Integer deductStatus; - - @ExcelIgnore - private String taxRate; - - @ExcelIgnore - private Boolean validStatus; - - @ExcelIgnore - private Integer expenseTypeId; - @ExcelIgnore - private String entryId; - @ExcelIgnore - private String reimbursementAmount; - - @ExcelIgnore - private String postedAmount; - - @ExcelIgnore - private String dataJson; - - @ExcelIgnore - private String employeeName; - @ExcelIgnore - private String reportTotal; - - @ExcelIgnore - private String ext01; - - @ExcelIgnore - private String ext02; - @ExcelIgnore - private String ext03; - @ExcelIgnore - private String ext04; - @ExcelIgnore - private String ext05; - - public String getFileName() { - if (StringUtil.isNotEmpty(this.originalUri)) { - return this.reportId + "_" + this.number + this.originalUri.substring(this.originalUri.lastIndexOf(".")); - } - return StringUtil.isEmpty(this.imgUri) ? "null" : this.reportId + "_" + this.number + this.imgUri.substring(this.imgUri.lastIndexOf(".")); - } - - public String getDownloadUri() { - if (StringUtil.isNotEmpty(this.originalUri)) { - return this.originalUri; - } - return this.imgUri; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcHeader.java b/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcHeader.java deleted file mode 100644 index fcd1180..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcHeader.java +++ /dev/null @@ -1,266 +0,0 @@ -package com.cmsen.ticket.domain.entity.pengfei; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import java.util.Date; - -/** - * PengFeiNcHeader对象 invoice_pengfei_nc_header - * - * @author ruoyi - * @date 2024-01-09 - */ -public class InvoicePengfeiNcHeader -{ - private static final long serialVersionUID = 1L; - - /** $column.columnComment */ - private Long id; - - - private String billmaker; - - /** 币种 */ - private String corigcurrencyid; - - /** 入账金额 */ - private String ntotalorigmny; - - /** 发票号-nc号 */ - private String vbillcode; - - /** 查询发票用的invoice */ - private String pkInvoice; - - /** 返回的title */ - private String title; - - /** 组织 */ - private String pkorg; - - /** 回写备注 */ - private String vdef21; - - /** $column.columnComment */ - private Date createDate; - - /** $column.columnComment */ - private Date updateDate; - - /** 是否已发送rpa */ - private String flag; - - /** 是否已执行匹配 */ - private String status; - - /** $column.columnComment */ - private String ext01; - - /** $column.columnComment */ - private String ext02; - - /** $column.columnComment */ - private String ext03; - - /** $column.columnComment */ - private String ext04; - - public String getDbilldate() { - return dbilldate; - } - - public void setDbilldate(String dbilldate) { - this.dbilldate = dbilldate; - } - - /** $column.columnComment */ - private String dbilldate; - - public String getInvoiceNumber() { - return invoiceNumber; - } - - public void setInvoiceNumber(String invoiceNumber) { - this.invoiceNumber = invoiceNumber; - } - - private String invoiceNumber; - - public void setId(Long id) - { - this.id = id; - } - - public Long getId() - { - return id; - } - public void setCorigcurrencyid(String corigcurrencyid) - { - this.corigcurrencyid = corigcurrencyid; - } - - public String getCorigcurrencyid() - { - return corigcurrencyid; - } - public void setNtotalorigmny(String ntotalorigmny) - { - this.ntotalorigmny = ntotalorigmny; - } - - public String getNtotalorigmny() - { - return ntotalorigmny; - } - public void setVbillcode(String vbillcode) - { - this.vbillcode = vbillcode; - } - - public String getVbillcode() - { - return vbillcode; - } - public void setPkInvoice(String pkInvoice) - { - this.pkInvoice = pkInvoice; - } - - public String getPkInvoice() - { - return pkInvoice; - } - public void setTitle(String title) - { - this.title = title; - } - - public String getTitle() - { - return title; - } - public void setPkorg(String pkorg) - { - this.pkorg = pkorg; - } - - public String getPkorg() - { - return pkorg; - } - public void setVdef21(String vdef21) - { - this.vdef21 = vdef21; - } - - public String getVdef21() - { - return vdef21; - } - public void setCreateDate(Date createDate) - { - this.createDate = createDate; - } - - public Date getCreateDate() - { - return createDate; - } - public void setUpdateDate(Date updateDate) - { - this.updateDate = updateDate; - } - - public Date getUpdateDate() - { - return updateDate; - } - public void setFlag(String flag) - { - this.flag = flag; - } - - public String getFlag() - { - return flag; - } - public void setStatus(String status) - { - this.status = status; - } - - public String getStatus() - { - return status; - } - public void setExt01(String ext01) - { - this.ext01 = ext01; - } - - public String getExt01() - { - return ext01; - } - public void setExt02(String ext02) - { - this.ext02 = ext02; - } - - public String getExt02() - { - return ext02; - } - public void setExt03(String ext03) - { - this.ext03 = ext03; - } - - public String getExt03() - { - return ext03; - } - public void setExt04(String ext04) - { - this.ext04 = ext04; - } - - public String getExt04() - { - return ext04; - } - - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("id", getId()) - .append("corigcurrencyid", getCorigcurrencyid()) - .append("ntotalorigmny", getNtotalorigmny()) - .append("vbillcode", getVbillcode()) - .append("pkInvoice", getPkInvoice()) - .append("title", getTitle()) - .append("pkorg", getPkorg()) - .append("vdef21", getVdef21()) - .append("createDate", getCreateDate()) - .append("updateDate", getUpdateDate()) - .append("flag", getFlag()) - .append("status", getStatus()) - .append("ext01", getExt01()) - .append("ext02", getExt02()) - .append("ext03", getExt03()) - .append("ext04", getExt04()) - .toString(); - } - - - public String getBillmaker() { - return billmaker; - } - - public void setBillmaker(String billmaker) { - this.billmaker = billmaker; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcLine.java b/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcLine.java deleted file mode 100644 index 5711430..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePengfeiNcLine.java +++ /dev/null @@ -1,359 +0,0 @@ -package com.cmsen.ticket.domain.entity.pengfei; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * PengFeiNcLine对象 invoice_pengfei_nc_line - * - * @author ruoyi - * @date 2024-01-09 - */ -public class InvoicePengfeiNcLine{ - private static final long serialVersionUID = 1L; - - /** $column.columnComment */ - private Long id; - - /** $column.columnComment */ - private Long headerId; - - /** 备注-是否需要处理? */ - private String vmemo; - - /** 收获单据号 */ - private String vsourcecode; - - /** po号 */ - private String vordercode; - - /** Po行号 */ - private String vfirstrowno; - - /** 无税单价 */ - private String nastorigprice; - - /** 供应商发货数量 */ - private String nshouldnum; - - /** 开票数量 */ - private String nnum; - - /** 无税金额 */ - private String norigmny; - - /** 税率 */ - private String ntaxrate; - - /** 物料编码 */ - private String pkMaterialCode; - - /** 物料名称 */ - private String pkMaterialName; - - /** 物料图号 */ - private String pkMaterialGraphid; - - /** 物料规格 */ - private String pkMaterialMaterialspec; - - /** 物料型号 */ - private String pkMaterialMaterialtype; - - /** 供应商名称 */ - private String pkSupplierName; - - /** 供应商编码 */ - private String pkSupplierCode; - - /** 供应商税号 */ - private String pkSupplierTaxpayerid; - - /** $column.columnComment */ - private String csourcebid; - - /** $column.columnComment */ - private String uom; - - /** $column.columnComment */ - private String ext01; - - /** $column.columnComment */ - private String ext02; - - /** $column.columnComment */ - private String ext03; - - public String getDbilldate() { - return dbilldate; - } - - public void setDbilldate(String dbilldate) { - this.dbilldate = dbilldate; - } - - public String getPk_invoice() { - return pk_invoice; - } - - public void setPk_invoice(String pk_invoice) { - this.pk_invoice = pk_invoice; - } - - /** $column.columnComment */ - private String dbilldate; - - /** $column.columnComment */ - private String pk_invoice; - - - - public void setId(Long id) - { - this.id = id; - } - - public Long getId() - { - return id; - } - public void setHeaderId(Long headerId) - { - this.headerId = headerId; - } - - public Long getHeaderId() - { - return headerId; - } - public void setVmemo(String vmemo) - { - this.vmemo = vmemo; - } - - public String getVmemo() - { - return vmemo; - } - public void setVsourcecode(String vsourcecode) - { - this.vsourcecode = vsourcecode; - } - - public String getVsourcecode() - { - return vsourcecode; - } - public void setVordercode(String vordercode) - { - this.vordercode = vordercode; - } - - public String getVordercode() - { - return vordercode; - } - public void setVfirstrowno(String vfirstrowno) - { - this.vfirstrowno = vfirstrowno; - } - - public String getVfirstrowno() - { - return vfirstrowno; - } - public void setNastorigprice(String nastorigprice) - { - this.nastorigprice = nastorigprice; - } - - public String getNastorigprice() - { - return nastorigprice; - } - public void setNshouldnum(String nshouldnum) - { - this.nshouldnum = nshouldnum; - } - - public String getNshouldnum() - { - return nshouldnum; - } - public void setNnum(String nnum) - { - this.nnum = nnum; - } - - public String getNnum() - { - return nnum; - } - public void setNorigmny(String norigmny) - { - this.norigmny = norigmny; - } - - public String getNorigmny() - { - return norigmny; - } - public void setNtaxrate(String ntaxrate) - { - this.ntaxrate = ntaxrate; - } - - public String getNtaxrate() - { - return ntaxrate; - } - public void setPkMaterialCode(String pkMaterialCode) - { - this.pkMaterialCode = pkMaterialCode; - } - - public String getPkMaterialCode() - { - return pkMaterialCode; - } - public void setPkMaterialName(String pkMaterialName) - { - this.pkMaterialName = pkMaterialName; - } - - public String getPkMaterialName() - { - return pkMaterialName; - } - public void setPkMaterialGraphid(String pkMaterialGraphid) - { - this.pkMaterialGraphid = pkMaterialGraphid; - } - - public String getPkMaterialGraphid() - { - return pkMaterialGraphid; - } - public void setPkMaterialMaterialspec(String pkMaterialMaterialspec) - { - this.pkMaterialMaterialspec = pkMaterialMaterialspec; - } - - public String getPkMaterialMaterialspec() - { - return pkMaterialMaterialspec; - } - public void setPkMaterialMaterialtype(String pkMaterialMaterialtype) - { - this.pkMaterialMaterialtype = pkMaterialMaterialtype; - } - - public String getPkMaterialMaterialtype() - { - return pkMaterialMaterialtype; - } - public void setPkSupplierName(String pkSupplierName) - { - this.pkSupplierName = pkSupplierName; - } - - public String getPkSupplierName() - { - return pkSupplierName; - } - public void setPkSupplierCode(String pkSupplierCode) - { - this.pkSupplierCode = pkSupplierCode; - } - - public String getPkSupplierCode() - { - return pkSupplierCode; - } - public void setPkSupplierTaxpayerid(String pkSupplierTaxpayerid) - { - this.pkSupplierTaxpayerid = pkSupplierTaxpayerid; - } - - public String getPkSupplierTaxpayerid() - { - return pkSupplierTaxpayerid; - } - public void setCsourcebid(String csourcebid) - { - this.csourcebid = csourcebid; - } - - public String getCsourcebid() - { - return csourcebid; - } - public void setUom(String uom) - { - this.uom = uom; - } - - public String getUom() - { - return uom; - } - public void setExt01(String ext01) - { - this.ext01 = ext01; - } - - public String getExt01() - { - return ext01; - } - public void setExt02(String ext02) - { - this.ext02 = ext02; - } - - public String getExt02() - { - return ext02; - } - public void setExt03(String ext03) - { - this.ext03 = ext03; - } - - public String getExt03() - { - return ext03; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("id", getId()) - .append("headerId", getHeaderId()) - .append("vmemo", getVmemo()) - .append("vsourcecode", getVsourcecode()) - .append("vordercode", getVordercode()) - .append("vfirstrowno", getVfirstrowno()) - .append("nastorigprice", getNastorigprice()) - .append("nshouldnum", getNshouldnum()) - .append("nnum", getNnum()) - .append("norigmny", getNorigmny()) - .append("ntaxrate", getNtaxrate()) - .append("pkMaterialCode", getPkMaterialCode()) - .append("pkMaterialName", getPkMaterialName()) - .append("pkMaterialGraphid", getPkMaterialGraphid()) - .append("pkMaterialMaterialspec", getPkMaterialMaterialspec()) - .append("pkMaterialMaterialtype", getPkMaterialMaterialtype()) - .append("pkSupplierName", getPkSupplierName()) - .append("pkSupplierCode", getPkSupplierCode()) - .append("pkSupplierTaxpayerid", getPkSupplierTaxpayerid()) - .append("csourcebid", getCsourcebid()) - .append("uom", getUom()) - .append("ext01", getExt01()) - .append("ext02", getExt02()) - .append("ext03", getExt03()) - .append("Pk_invoice", getPk_invoice()) - .append("Dbilldate", getDbilldate()) - .toString(); - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePfNcInfo.java b/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePfNcInfo.java deleted file mode 100644 index 6647fdc..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/pengfei/InvoicePfNcInfo.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.cmsen.ticket.domain.entity.pengfei; - -import lombok.Data; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import java.util.Date; - -/** - * 鹏飞项目对象 invoice_pf_nc_info - * - * @author ruoyi - * @date 2023-11-23 - */ -@Data -public class InvoicePfNcInfo -{ - private static final long serialVersionUID = 1L; - - /** $column.columnComment */ - private Long id; - - /** 提交人 */ - private String billmaker; - - /** 币种 */ - private String corigcurrencyid; - - /** 头入账金额 */ - private String ntotalorigmny; - - /** 发票号-nc号? */ - private String vbillcode; - - /** 备注-是否需要处理? */ - private String vmemo; - - /** 收获单据号 */ - private String vsourcecode; - - /** po号 */ - private String vordercode; - - /** Po行号 */ - private String vfirstrowno; - - /** 无税单价 */ - private String nastorigprice; - - /** 供应商发货数量 */ - private String nshouldnum; - - /** 开票数量 */ - private String nnum; - - /** 无税金额 */ - private String norigmny; - - /** 税率 */ - private String ntaxrate; - - /** 物料编码 */ - private String pkMaterialCode; - - /** 物料名称 */ - private String pkMaterialName; - - /** 物料图号 */ - private String pkMaterialGraphid; - - /** 物料规格 */ - private String pkMaterialMaterialspec; - - /** 物料型号 */ - private String pkMaterialMaterialtype; - - /** 供应商名称 */ - private String pkSupplierName; - - /** 供应商编码 */ - private String pkSupplierCode; - - /** 供应商税号 */ - private String pkSupplierTaxpayerid; - - /** $column.columnComment */ - private String ext01; - - /** $column.columnComment */ - private String ext02; - - /** $column.columnComment */ - private String csourcebid; - - /** $column.columnComment */ - private String uom; - - /** $column.columnComment */ - private String pk_invoice; - - /** $column.columnComment */ - private String title; - - /** $column.columnComment */ - private String dbilldate; - - /** $column.columnComment */ - private String pkorg; - - /** $column.columnComment */ - private String invoiceNumber; - - /** $column.columnComment */ - private String vdef21; - - /** $column.columnComment */ - private Date createDate; - - /** $column.columnComment */ - private Date updateDate; - - /** $column.columnComment */ - private String flag; - - /** $column.columnComment */ - private String status; - - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("id", getId()) - .append("billmaker", getBillmaker()) - .append("corigcurrencyid", getCorigcurrencyid()) - .append("ntotalorigmny", getNtotalorigmny()) - .append("vbillcode", getVbillcode()) - .append("vmemo", getVmemo()) - .append("vsourcecode", getVsourcecode()) - .append("vordercode", getVordercode()) - .append("vfirstrowno", getVfirstrowno()) - .append("nastorigprice", getNastorigprice()) - .append("nshouldnum", getNshouldnum()) - .append("nnum", getNnum()) - .append("norigmny", getNorigmny()) - .append("ntaxrate", getNtaxrate()) - .append("pkMaterialCode", getPkMaterialCode()) - .append("pkMaterialName", getPkMaterialName()) - .append("pkMaterialGraphid", getPkMaterialGraphid()) - .append("pkMaterialMaterialspec", getPkMaterialMaterialspec()) - .append("pkMaterialMaterialtype", getPkMaterialMaterialtype()) - .append("pkSupplierName", getPkSupplierName()) - .append("pkSupplierCode", getPkSupplierCode()) - .append("pkSupplierTaxpayerid", getPkSupplierTaxpayerid()) - .append("ext01", getExt01()) - .append("ext02", getExt02()) - .append("ext03", getCsourcebid()) - .append("ext04", getUom()) - .append("ext05", getPk_invoice()) - .append("ext06", getTitle()) - .append("ext07", getDbilldate()) - .append("ext08", getPkorg()) - .append("invoiceNumber", getInvoiceNumber()) - .append("vdef21", getVdef21()) - .append("createDate", getCreateDate()) - .append("updateDate", getUpdateDate()) - .append("flag", getFlag()) - .append("status", getStatus()) - .toString(); - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddMeetProcessDto.java b/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddMeetProcessDto.java deleted file mode 100644 index 2e52e66..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddMeetProcessDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cmsen.ticket.domain.entity.wechat; - -import lombok.Data; - -/** - * @author OWTS - */ -@Data -public class AddMeetProcessDto { - private String title; - private String data; - private String userName; - - public String getTitle() { - return title == null ? "" : title; - } - - public String getData() { - return data == null ? "" : data; - } - - public String getUserName() { - return userName == null ? "" : userName; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddProcessDto.java b/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddProcessDto.java deleted file mode 100644 index 8eccb0e..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/wechat/AddProcessDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cmsen.ticket.domain.entity.wechat; - -import lombok.Data; - -/** - * @author OWTS - */ -@Data -public class AddProcessDto { - private String title; - private String data; - private String userName; - - public String getTitle() { - return title == null ? "" : title; - } - - public String getData() { - return data == null ? "" : data; - } - - public String getUserName() { - return userName == null ? "" : userName; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/wechat/MeetProcessData.java b/src/main/java/com/cmsen/ticket/domain/entity/wechat/MeetProcessData.java deleted file mode 100644 index 10e3fbf..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/wechat/MeetProcessData.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.cmsen.ticket.domain.entity.wechat; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * @author OWTS - */ -@Data -public class MeetProcessData { - private String reqId;//编号 - private String name;//申请名称 - private String createTime;//申请日期 - private String expenseUse;//申请类型 - private String type;//活动类型 - private String ext01;//区域 - private String ext02;//产品类 - private String ext03;//产品线 - private String ext04;//产品组 - private String ext05;//项目 - private String startDate;//开始时间 - private String endDate;//结束时间 - private String city;//城市 - private String meetFormat;//线上线下 - - @JsonProperty("meet_expense") - private List meetExpense = new ArrayList<>(); - - @Data - public static class MeetExpense { - private String expType;//费用类型 - private String person;//人员 - private String tradeDate;//日期 - private String currency;//币种 - private BigDecimal amount;//金额 - private String city;//城市 - private String remark;//备注 - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/entity/wechat/ProcessData.java b/src/main/java/com/cmsen/ticket/domain/entity/wechat/ProcessData.java deleted file mode 100644 index 780d7c7..0000000 --- a/src/main/java/com/cmsen/ticket/domain/entity/wechat/ProcessData.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.cmsen.ticket.domain.entity.wechat; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author OWTS - */ -@Data -public class ProcessData { - private String reportName; - private String reportDate; - private String reportTotal; - private String reportReason; - private String empId; - @JsonProperty("report_line") - private List reportLine = new ArrayList<>(); - - @Data - public static class ReportLine { - private String expenseType; - private String transtionDate; - private String exChangeRate; - private String currenyCode; - private String hasException; - private String reportId; - private String entryId; - private String entryMoney; - private List imgUrl = new ArrayList<>(); - private String project; - private String remark; - - public String getExpenseType() { - return expenseType == null ? "" : expenseType; - } - - public String getTranstionDate() { - return transtionDate == null ? "" : transtionDate; - } - - public String getExChangeRate() { - return exChangeRate == null ? "" : exChangeRate; - } - - public String getCurrenyCode() { - return currenyCode == null ? "" : currenyCode; - } - - public String getHasException() { - return hasException == null ? "" : hasException; - } - - public String getReportId() { - return reportId == null ? "" : reportId; - } - - public String getEntryId() { - return entryId == null ? "" : entryId; - } - - public String getEntryMoney() { - return entryMoney == null ? "" : entryMoney; - } - - public String getProject() { - return project == null ? "" : project; - } - - public String getRemark() { - return remark == null ? "" : remark; - } - } - - @Data - public static class ImgUrl { - private String url; - private String name; - - public String getUrl() { - return url == null ? "" : url; - } - - public String getName() { - return name == null ? "" : name; - } - } - - public String getReportName() { - return reportName == null ? "" : reportName; - } - - public String getReportDate() { - return reportDate == null ? "" : reportDate; - } - - public String getReportTotal() { - return reportTotal == null ? "" : reportTotal; - } - - public String getReportReason() { - return reportReason == null ? "" : reportReason; - } - - public String getEmpId() { - return empId == null ? "" : empId; - } -} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/AccountMappingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/AccountMappingMapper.java new file mode 100644 index 0000000..df02d14 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/AccountMappingMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.AccountMapping; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** +* @author ONE MORE THING +* @description 针对表【expense_subject(费用科目表)】的数据库操作Mapper +* @createDate 2021-12-24 10:11:41 +* @Entity com.cmsen.ticket.domain.entity.ExpenseSubject +*/ +@Mapper +public interface AccountMappingMapper { + + int deleteByPrimaryKey(Long id); + + int insert(AccountMapping record); + + AccountMapping selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(AccountMapping record); + + List list(); + + AccountMapping selectByInvoice(@Param("invoiceId") String invoiceId); + + AccountMapping selectBySubject(int subject); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/AccountObjectMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/AccountObjectMapper.java new file mode 100644 index 0000000..2a79c0e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/AccountObjectMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.AccountObject; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** +* @author ONE MORE THING +* @description 针对表【account_object(科目)】的数据库操作Mapper +* @createDate 2021-12-24 14:35:22 +* @Entity com.cmsen.ticket.domain.entity.AccountObject +*/ +@Mapper +public interface AccountObjectMapper { + + int deleteByPrimaryKey(Long id); + + int insert(AccountObject record); + + AccountObject selectByPrimaryKey(Long id); + AccountObject selectByAccount(@Param("account") String account); + + int updateByPrimaryKeySelective(AccountObject record); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/AppMenuMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/AppMenuMapper.java new file mode 100644 index 0000000..db89c34 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/AppMenuMapper.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.mapper; + + +import com.cmsen.ticket.domain.entity.AppMenu; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * @Entity com.cmsen.ticket.domain.domain.AppMenu + */ +@Mapper +public interface AppMenuMapper { + List listActive(); + + List selByType(@Param("type") String type); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/AttendOrgMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/AttendOrgMapper.java new file mode 100644 index 0000000..ca77c84 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/AttendOrgMapper.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.AttendOrg; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface AttendOrgMapper { + int deleteByPrimaryKey(Integer id); + + int insert(AttendOrg record); + + int insertSelective(AttendOrg record); + + AttendOrg selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(AttendOrg record); + + int updateByPrimaryKey(AttendOrg record); + + List getOrgListByPid(@Param("pid") Integer pid, @Param("orgName") String orgName, @Param("userType") String userType); + + List list(@Param("pageStartNo") Integer pageStartNo, @Param("pageSize") Integer pageSize); + int count(); + + AttendOrg checkOrg(@Param("pid") Integer pid, @Param("orgCode") String orgCode, @Param("orgName") String orgName); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/BandAreaConfigMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/BandAreaConfigMapper.java new file mode 100644 index 0000000..d248a4e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/BandAreaConfigMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.BandAreaConfig; +import org.apache.ibatis.annotations.Mapper; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/22 10:54 + */ +@Mapper +public interface BandAreaConfigMapper { + int deleteByPrimaryKey(Integer id); + + int insert(BandAreaConfig record); + + int insertSelective(BandAreaConfig record); + + BandAreaConfig selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(BandAreaConfig record); + + int updateByPrimaryKey(BandAreaConfig record); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/BandConfigMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/BandConfigMapper.java new file mode 100644 index 0000000..4dfad20 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/BandConfigMapper.java @@ -0,0 +1,40 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.BandConfig; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/22 10:53 + */ +@Mapper +public interface BandConfigMapper { + int deleteByPrimaryKey(Integer id); + + int insert(BandConfig record); + + int insertSelective(BandConfig record); + + BandConfig selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(BandConfig record); + + int updateByPrimaryKey(BandConfig record); + + BandConfig selectByCode(@Param("code") String code); + + BandConfig selectRate(@Param("bandValue") String bandValue , @Param("area") String area ,@Param("item") String item); + + BandConfig selectByUserId(Integer userId); + + List selectByParams(Map params); + + List list(Map params); + + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/BzCustomerMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/BzCustomerMapper.java new file mode 100644 index 0000000..9a031af --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/BzCustomerMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.BzCustomer; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface BzCustomerMapper { + int deleteByPrimaryKey(Long id); + + int insert(BzCustomer record); + + int insertSelective(BzCustomer record); + + BzCustomer selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(BzCustomer record); + + int updateByPrimaryKey(BzCustomer record); + + List searchList(@Param("keyword") String keyword); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveHeaderMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveHeaderMapper.java new file mode 100644 index 0000000..13fd3ee --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveHeaderMapper.java @@ -0,0 +1,33 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorpInvoiceReceiveHeader; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** +* @author admin +* @description 针对表【corp_invoice_receive_header】的数据库操作Mapper +* @createDate 2022-04-18 15:12:53 +* @Entity com.cmsen.ticket.domain.entity.CorpInvoiceReceiveHeader +*/ +@Mapper +public interface CorpInvoiceReceiveHeaderMapper { + + int deleteByPrimaryKey(Long id); + + int insert(CorpInvoiceReceiveHeader record); + + int insertSelective(CorpInvoiceReceiveHeader record); + + CorpInvoiceReceiveHeader selectByPrimaryKey(Long id); + + List selectList(String status); + List selectList2(Map record); + + int updateByPrimaryKeySelective(CorpInvoiceReceiveHeader record); + + int updateByPrimaryKey(CorpInvoiceReceiveHeader record); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveLineMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveLineMapper.java new file mode 100644 index 0000000..b78bd69 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorpInvoiceReceiveLineMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorpInvoiceReceiveLine; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author admin + * @description 针对表【corp_invoice_receive_line】的数据库操作Mapper + * @createDate 2022-04-18 15:13:02 + * @Entity com.cmsen.ticket.domain.entity.CorpInvoiceReceiveLine + */ +@Mapper +public interface CorpInvoiceReceiveLineMapper { + + int deleteByPrimaryKey(Long id); + + int insert(CorpInvoiceReceiveLine record); + + int insertSelective(CorpInvoiceReceiveLine record); + + CorpInvoiceReceiveLine selectByPrimaryKey(Long id); + + List selectByPid(String pid); + + int updateByPrimaryKeySelective(CorpInvoiceReceiveLine record); + + int updateByPrimaryKey(CorpInvoiceReceiveLine record); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentHeaderMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentHeaderMapper.java new file mode 100644 index 0000000..116bcce --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentHeaderMapper.java @@ -0,0 +1,38 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorpPaymentHeader; +import com.cmsen.ticket.interfaces.facade.manager.form.PayMentSearchForm; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** +* @author admin +* @description 针对表【corp_payment_header】的数据库操作Mapper +* @createDate 2022-04-20 20:19:11 +* @Entity com.cmsen.ticket.domain.entity.CorpPaymentHeader +*/ +@Mapper +public interface CorpPaymentHeaderMapper { + + int deleteByPrimaryKey(Integer id); + + int insert(CorpPaymentHeader record); + + int insertSelective(CorpPaymentHeader record); + + CorpPaymentHeader selectByPrimaryKey(Integer id); + + int count(PayMentSearchForm form); + List list(PayMentSearchForm form); + + List selectList(CorpPaymentHeader record); + + int updateByPrimaryKeySelective(CorpPaymentHeader record); + + int updateByPrimaryKey(CorpPaymentHeader record); + + List selectByStatus(@Param("status") String status); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentLineMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentLineMapper.java new file mode 100644 index 0000000..40406b8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorpPaymentLineMapper.java @@ -0,0 +1,38 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorpPaymentLine; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** +* @author admin +* @description 针对表【corp_payment_line】的数据库操作Mapper +* @createDate 2022-04-18 15:40:40 +* @Entity com.cmsen.ticket.domain.entity.CorpPaymentLine +*/ +@Mapper +public interface CorpPaymentLineMapper { + + int deleteByPrimaryKey(Long id); + + int insert(CorpPaymentLine record); + + int insertSelective(CorpPaymentLine record); + + CorpPaymentLine selectByPrimaryKey(Long id); + + List listPid(String pid); + + int updateByPrimaryKeySelective(CorpPaymentLine record); + + int updateByPrimaryKey(CorpPaymentLine record); + + CorpPaymentLine selectByNumAndCode(String num,String code); + + CorpPaymentLine selectSumByNumAndCode(String num,String code); + + int updateReceived(String num,String code); + + int insertBatch(List line); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceMapper.java index 971393a..022f001 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceMapper.java @@ -2,6 +2,9 @@ package com.cmsen.ticket.domain.mapper; import com.cmsen.ticket.domain.dto.InvoiceItemListDto; import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoice3; +import com.cmsen.ticket.domain.vo.CorInvoiceUploadVo; +import com.cmsen.ticket.domain.vo.CorporateInvoiceSummaryVo; import com.cmsen.ticket.domain.vo.CorporateInvoiceVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -12,7 +15,11 @@ import java.util.Map; @Mapper public interface CorporateInvoiceMapper { - List supplierInvoiceMatchInvoiceList(@Param("numberS") String numberS, @Param("numberE") String numberE, @Param("invoiceType") Integer invoiceType); + + int updatePeriodById(CorporateInvoice invoice); + +// @Select("select PERIOD from corporate_invoice where ID=#{id}") +// CorporateInvoice selectById(String id); int setValidStatus(String id); @@ -21,6 +28,7 @@ public interface CorporateInvoiceMapper { int insert(CorporateInvoice record); CorporateInvoice selectByPrimaryKey(String id); + CorporateInvoice selectByPrimaryKeyParams(Map params); CorporateInvoice selectByIdContainsNames(@Param("id") String id); @@ -34,6 +42,7 @@ public interface CorporateInvoiceMapper { List list(Map params); List list2(Map params); + List list3(Map params); List list6(Map params); List listReportInvoiceId(Map params); @@ -41,6 +50,7 @@ public interface CorporateInvoiceMapper { List list4(Map params); List list5(Map params); + List invoiceMatchingList(ParameterScope params); List searchList(Map params); @@ -49,6 +59,7 @@ public interface CorporateInvoiceMapper { int count(Map params); int count2(Map params); + int invoiceMatchingCount(ParameterScope params); int checkInvoiceNumIsExistByNumAndCode(@Param("number") String number, @Param("code") String code,@Param("invoiceId") String invoiceId,@Param("orgId") Integer orgId); @@ -58,11 +69,26 @@ public interface CorporateInvoiceMapper { int updateCorInvDeductStatusTask(); + int getCorporateMonthNum(int flag,int validStatus); + + int getCorporateYearNum(int flag,int validStatus); + + List selectUnValidInvoice(@Param("corMaxValid") Integer corMaxValid); List selectUnValidInvoiceUpdate(Map param); + int updateValidDayCount(); + + int updateReceived(String id); + + String selectSiteCodeByInvoiceId(@Param("invoiceId") String invoiceId); + String selectSupplierCode(@Param("invoiceId") String invoiceId); + int revokeInvoice(@Param("invoiceId") String invoiceId,@Param("isSend")String isSend); + + //根据id查找subject + List supplierInvoiceMatchInvoiceList(@Param("numberS") String numberS, @Param("numberE") String numberE, @Param("invoiceType") Integer invoiceType); // int getBySubject(@Param("id") String id); Unknown column 'I.I' in 'where clause' CorporateInvoice selectById(@Param("id") String id); @@ -75,12 +101,26 @@ public interface CorporateInvoiceMapper { int updateByFlow(String id); + List selectInvoiceForOrder(Map params); + int countForOrder(Map params); + + int updateDeductionAmount(@Param("id") String id, @Param("deductionAmount") String deductionAmount); + + List selectUploadLog(Map map); + List listByNumbers(Map params); int refund(@Param("id") String id,@Param("isSend") String isSend); + void updateSendById(String id); + + List selectByNum(String invoiceNumber,String ncNo); + List selectByBillCode(String billCode); + String sumTotalByBillCode(String billCode); + + String sumTaxByBillCode(String billCode); List selectByPushList(@Param("list") List pushList); @@ -88,31 +128,48 @@ public interface CorporateInvoiceMapper { void updateExt08(String pushList); + String selectKofoxInvoiceId(String s); + List selectByMap(Map map); + void deleteByBillCode(String billCode); + + CorporateInvoice selectBySeller(@Param("name") String nameReplaceBlank); + void updateTaxNo(CorporateInvoice corporateInvoice); List queryByOrg(@Param("orgId")String[] corInvoiceOrg); + void updatePo(@Param("po")String po, @Param("invoiceId")String invoiceId); + + List selectListByParams(Map params); CorporateInvoice selectDetailById(@Param("id") String id); + List listCorporateInvoiceSummary(Map params); + void updateSellerNo(CorporateInvoice corporateInvoice); void updateBuyerNo(CorporateInvoice corporateInvoice); + List listForZhzg(@Param("htNo") String htNo,@Param("scannerId") String scannerId,@Param("matchStatus")String matchStatus); + + List listHtNoForZhzg(); + List selectByNumberAndStatus(@Param("number") String invoiceNum, @Param("status")String status); + void updateEntityForYzts(@Param("number") String invoiceNum,@Param("htNo")String htNo,@Param("scannerId") String scannerId); + CorporateInvoice selectByNumberAndExt01(String number,long ext01); void updateExt01(CorporateInvoice record); List selectByNumAndValidStatus(String number, String validStatus); + void deleteAbsolute(String pid); + void deleteByNumber(String number); List listUnSend(Map map); - int invoiceMatchingCount(ParameterScope params); - List invoiceMatchingList(ParameterScope params); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceNdJsonMappingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceNdJsonMappingMapper.java new file mode 100644 index 0000000..3e737a7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceNdJsonMappingMapper.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorporateInvoiceNdJsonMapping; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +@Mapper +public interface CorporateInvoiceNdJsonMappingMapper { + + List listAvailable(@Param("kind")String kind,@Param("locate") String locate); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceScannerFilesMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceScannerFilesMapper.java new file mode 100644 index 0000000..b427449 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CorporateInvoiceScannerFilesMapper.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.CorporateInvoiceScannerFiles; +import org.apache.ibatis.annotations.Mapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Mapper +public interface CorporateInvoiceScannerFilesMapper { + int insert(CorporateInvoiceScannerFiles record); + void update(CorporateInvoiceScannerFiles record); + ArrayList selectSuccessByScannerId(int scId); + + int getSuccessCount(long scId); + + List list(Map params); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/CurrencyMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/CurrencyMapper.java new file mode 100644 index 0000000..2f489bd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/CurrencyMapper.java @@ -0,0 +1,32 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Currency; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface CurrencyMapper { + int deleteByPrimaryKey(Integer id); + + int insert(Currency record); + + int insertSelective(Currency record); + + Currency selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Currency record); + + int updateByPrimaryKey(Currency record); + + List selectList(@Param("name") String name); + + List selectALlColumn(String tableName); + + int insertActive(@Param("sql") String sql); + + Currency selectByName(@Param("name") String name); + + Currency selectByCode(@Param("code") String code); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/DeductionCompanyMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/DeductionCompanyMapper.java new file mode 100644 index 0000000..cb59dd0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/DeductionCompanyMapper.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.DeductionCompany; +import org.apache.ibatis.annotations.Mapper; + +/** + * @author ONE MORE THING + * @description 针对表【deduction_company(可抵扣公司)】的数据库操作Mapper + * @createDate 2022-02-23 11:13:53 + * @Entity com.cmsen.ticket.domain.entity.DeductionCompany + */ +@Mapper +public interface DeductionCompanyMapper { + + int deleteByPrimaryKey(Long id); + + int insert(DeductionCompany record); + + DeductionCompany selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(DeductionCompany record); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ErrorReportMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ErrorReportMapper.java new file mode 100644 index 0000000..9581889 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ErrorReportMapper.java @@ -0,0 +1,28 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ErrorReport; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author ONE MORE THING + * @description 针对表【error_report(异常报告)】的数据库操作Mapper + * @createDate 2022-01-22 10:08:16 + * @Entity com.cmsen.ticket.domain.entity.ErrorReport + */ +@Mapper +public interface ErrorReportMapper { + + int deleteByPrimaryKey(Long id); + + int insert(ErrorReport record); + + ErrorReport selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ErrorReport record); + + List getErrorReports(); + + int deleteByReportId(String reportId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportMapper.java new file mode 100644 index 0000000..35dab70 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ExpCombReport; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface ExpCombReportMapper { + int deleteByPrimaryKey(Long combReportId); + + int insert(ExpCombReport record); + + int insertSelective(ExpCombReport record); + + ExpCombReport selectByPrimaryKey(Long combReportId); + + int updateByPrimaryKeySelective(ExpCombReport record); + + int updateByPrimaryKey(ExpCombReport record); + + int insertBatch(@Param("expCombReports") List expCombReports); + + List selectExpCombReport(ExpCombReport expCombReport); + + List list(Map params); + + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportSubMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportSubMapper.java new file mode 100644 index 0000000..a00d1b5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ExpCombReportSubMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ExpCombReportSub; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface ExpCombReportSubMapper { + int deleteByPrimaryKey(Long id); + + int insert(ExpCombReportSub record); + + int insertSelective(ExpCombReportSub record); + + ExpCombReportSub selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ExpCombReportSub record); + + int updateByPrimaryKey(ExpCombReportSub record); + + int insertBatch(@Param("expCombReportSubs") List expCombReportSubs); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ExpenseUseMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ExpenseUseMapper.java new file mode 100644 index 0000000..b1c2618 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ExpenseUseMapper.java @@ -0,0 +1,102 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ExpenseUse; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import javax.validation.constraints.NotEmpty; +import java.util.List; +import java.util.Map; + +/** + * (ExpenseUse)表数据库访问层 + * + * @author makejava + * @since 2020-08-20 17:44:51 + */ +@Mapper +public interface ExpenseUseMapper { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + ExpenseUse queryById(Integer id); + ExpenseUse queryById2(Integer id); + + /** + * 查询指定行数据 + * + * @return 对象列表 + */ + List queryAllByLimit(); + + + /** + * 通过实体作为筛选条件查询 + * + * @param expenseUse 实例对象 + * @return 对象列表 + */ + List queryAll(ExpenseUse expenseUse); + + /** + * queryAll去掉is_del的条件 + * @param expenseUse + * @return + */ + List queryAll2(ExpenseUse expenseUse); + + /** + * 新增数据 + * + * @param expenseUse 实例对象 + * @return 影响行数 + */ + int insert(ExpenseUse expenseUse); + + /** + * 修改数据 + * + * @param expenseUse 实例对象 + * @return 影响行数 + */ + int update(ExpenseUse expenseUse); + + /** + * 通过主键删除数据 + * + * @param id 主键 + * @return 影响行数 + */ + int deleteById(Integer id); + + int insertBatch(@NotEmpty List list); + + int updateBatch(@NotEmpty List list); + + List list(Map params); + + int count(Map params); + + List selectAllCode(); + + /** + * 启用 + * + * @param id + * @return + */ + int active(@Param("id") Integer id); + + /** + * 停用 + * + * @param id + * @return + */ + int clock(@Param("id") Integer id); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/FileMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/FileMapper.java new file mode 100644 index 0000000..0ec450f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/FileMapper.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.File; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface FileMapper { + int deleteByPrimaryKey(Integer id); + + int insert(File record); + + File selectByPrimaryKey(Integer id); + + List selectByPid(String pid); + + int updateByPrimaryKeySelective(File record); + + List selectByPidAndType(String pId, String type); + + List selectByHtnoAndType(String htNo, String type); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/FilesConfigMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/FilesConfigMapper.java new file mode 100644 index 0000000..54658b9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/FilesConfigMapper.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.FilesConfig; +import com.cmsen.ticket.domain.entity.FilesConfig2; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface FilesConfigMapper { + + int deleteByPrimaryKey(Long id); + + int insert(FilesConfig record); + + FilesConfig selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(FilesConfig record); + + List selectAll(); + + FilesConfig selectByType(@Param("type") String type); + + List selectByExt01(@Param("ext01") String ext01); + + FilesConfig2 selectByExt05(@Param("ext05") String ext05); + + FilesConfig2 selByType(@Param("type") String type); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/FilesMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/FilesMapper.java new file mode 100644 index 0000000..c61cfd9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/FilesMapper.java @@ -0,0 +1,80 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Files; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface FilesMapper { + int deleteByPrimaryKey(Integer id); + + int insert(Files record); + + int insertSelective(Files record); + + Files selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Files record); + + int updateByPrimaryKey(Files record); + + List list(Files files); + + List list2(Files files); + + List list3(Files files); + + List listMileage(Files files); + + List listAll(Files files); + + int deleteByFileName(@Param("fileName") String fileName); + + Files selectByMqId(@Param("mqId") String mqId); + + Files selectByFileName(@Param("fileName") String fileName); + + int updateByFileName(@Param("fileName") String fileName); + + int deleteByFileNameStart(@Param("fileName") String fileName); + + int checkByInvoiceId(@Param("invoiceId") String invoiceId); + + int checkByInvoiceId4(@Param("invoiceId") String invoiceId); + + int checkByInvoiceId2(@Param("invoiceId") String invoiceId); + + int checkByInvoiceId3(@Param("invoiceId") String invoiceId); + + Files selectByEfilesId(@Param("efilesId") Long efilesId, @Param("invoiceId") String invoiceId); + + int updateByEfilesId(@Param("efilesId") Long efilesId, @Param("invoiceId") String invoiceId); + + List selectNotInvoice(@Param("invoiceId") String invoiceId); + + List selectNotEfiles(@Param("invoiceId") String invoiceId, @Param("reqId") String reqId, @Param("extId") String extId); + + List selectInEfiles(@Param("invoiceId") String invoiceId, @Param("reqId") String reqId); + + List selectHasEfiles(Map params); + + List selectEfiles(Map params); + + int updateStatus(@Param("invoiceId") String invoiceId); + + List selectByStatus(@Param("invoiceId") String invoiceId, @Param("status") String status); + + int checkByType(@Param("invoiceId") String invoiceId, @Param("filesType") String filesType); + + List selectDelList(@Param("invoiceId") String invoiceId, @Param("ext03") String ext03); + + int updateDelFlag(@Param("invoiceId") String invoiceId); + + List selEFilesByInvoiceId(@Param("invoiceId") String invoiceId); + + List getInvoiceFilesDatas(@Param("org") String org, @Param("updateDate") String updateDate, + @Param("start") Integer start, @Param("pageSize") Integer pageSize); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/FilesOcrMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/FilesOcrMapper.java new file mode 100644 index 0000000..d812a0f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/FilesOcrMapper.java @@ -0,0 +1,38 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.FilesOcr; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface FilesOcrMapper { + + int deleteByPrimaryKey(Long id); + + int insert(FilesOcr record); + + FilesOcr selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(FilesOcr record); + + int checkContainsTicket(@Param("type") String type, @Param("invoiceId") String invoiceId); + + List selectByIdAndType(@Param("type") String type, @Param("invoiceId") String invoiceId); + + FilesOcr checkVerifiedData(String invoiceId,String type); + + List selectByInvoiceId(@Param("invoiceId") String invoiceId,@Param("type") String type); + + FilesOcr selByInvoiceId(@Param("invoiceId") String invoiceId,@Param("type") String type); + + int deleteByFilesId(Integer filesId); + + List checkFilesOcr(Map params); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/HelpMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/HelpMapper.java new file mode 100644 index 0000000..36f3e96 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/HelpMapper.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Help; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface HelpMapper { + int deleteByPrimaryKey(Integer id); + + int insert(Help record); + + int insertSelective(Help record); + + Help selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Help record); + + int updateByPrimaryKey(Help record); + + List selectList(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InternationalizationMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InternationalizationMapper.java new file mode 100644 index 0000000..358fb88 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InternationalizationMapper.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Internationalization; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface InternationalizationMapper { + int deleteByPrimaryKey(Integer id); + + int insert(Internationalization record); + + int insertSelective(Internationalization record); + + Internationalization selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Internationalization record); + + int updateByPrimaryKey(Internationalization record); + + List selectList(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InvokeBrandMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeBrandMapper.java new file mode 100644 index 0000000..fc52c23 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeBrandMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.InvokeBrand; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface InvokeBrandMapper { + int deleteByPrimaryKey(Long id); + + int insert(InvokeBrand record); + + int insertSelective(InvokeBrand record); + + InvokeBrand selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(InvokeBrand record); + + int updateByPrimaryKey(InvokeBrand record); + + InvokeBrand selectByRequestId(@Param("requestId") String requestId); + + List listTest(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InvokeContractMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeContractMapper.java new file mode 100644 index 0000000..efb6424 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeContractMapper.java @@ -0,0 +1,30 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.InvokeContract; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface InvokeContractMapper { + int deleteByPrimaryKey(Long id); + + int insert(InvokeContract record); + + int insertSelective(InvokeContract record); + + InvokeContract selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(InvokeContract record); + + int updateByPrimaryKey(InvokeContract record); + + int updateOwnerByRequestId(@Param("requestId") String requestId, @Param("owner") String owner); + + List listByParams(Map params); + int count(Map params); + + InvokeContract selectByRequestId(@Param("requestId") String requestId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InvokeInternalMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeInternalMapper.java new file mode 100644 index 0000000..725e4d5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeInternalMapper.java @@ -0,0 +1,30 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.InvokeInternal; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface InvokeInternalMapper { + int deleteByPrimaryKey(Long id); + + int insert(InvokeInternal record); + + int insertSelective(InvokeInternal record); + + InvokeInternal selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(InvokeInternal record); + + int updateByPrimaryKey(InvokeInternal record); + + InvokeInternal selectByRequestId(@Param("requestId") String requestId); + + List listByParams(Map params); + int count(Map params); + + int updateOwnerByRequestId(@Param("requestId") String requestId, @Param("owner") String owner); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InvokePurchaseMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InvokePurchaseMapper.java new file mode 100644 index 0000000..50a836b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InvokePurchaseMapper.java @@ -0,0 +1,30 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.InvokePurchase; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface InvokePurchaseMapper { + int deleteByPrimaryKey(Long id); + + int insert(InvokePurchase record); + + int insertSelective(InvokePurchase record); + + InvokePurchase selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(InvokePurchase record); + + int updateByPrimaryKey(InvokePurchase record); + + InvokePurchase selectByRequestId(@Param("requestId") String requestId); + + List listByParams(Map params); + int count(Map params); + + int updateOwnerByRequestId(@Param("requestId") String requestId, @Param("owner") String owner); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/InvokeReceiveMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeReceiveMapper.java new file mode 100644 index 0000000..b8cb052 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/InvokeReceiveMapper.java @@ -0,0 +1,28 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.InvokeReceive; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface InvokeReceiveMapper { + int deleteByPrimaryKey(Integer id); + + int insert(InvokeReceive record); + + int insertSelective(InvokeReceive record); + + InvokeReceive selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(InvokeReceive record); + + int updateByPrimaryKey(InvokeReceive record); + + InvokeReceive selectByRequestId(@Param("requestId") String requestId); + + List listByParams(Map params); + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/JsadapterMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/JsadapterMapper.java new file mode 100644 index 0000000..bfc9632 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/JsadapterMapper.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Jsadapter; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface JsadapterMapper { + + int deleteByPrimaryKey(Integer id); + + int insert(Jsadapter record); + + Jsadapter selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Jsadapter record); + + List listByParams(Map params); + + int countByParams(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/MaterialMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/MaterialMapper.java new file mode 100644 index 0000000..f303331 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/MaterialMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Material; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface MaterialMapper { + int deleteByPrimaryKey(Long id); + + int insert(Material record); + + int insertSelective(Material record); + + Material selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(Material record); + + int updateByPrimaryKey(Material record); + + List searchList(@Param("keyword") String keyword); + + Material selectByCode(@Param("code") String code); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/PaymentTypeMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/PaymentTypeMapper.java new file mode 100644 index 0000000..9253472 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/PaymentTypeMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.PaymentType; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface PaymentTypeMapper { + int deleteByPrimaryKey(Long id); + + int insert(PaymentType record); + + int insertSelective(PaymentType record); + + PaymentType selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(PaymentType record); + + int updateByPrimaryKey(PaymentType record); + + List searchList(@Param("keyword") String keyword); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/PostBoxMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/PostBoxMapper.java new file mode 100644 index 0000000..5459eb1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/PostBoxMapper.java @@ -0,0 +1,55 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.PostBox; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface PostBoxMapper { + int deleteByPrimaryKey(Integer id); + + int insertSelective(PostBox record); + + PostBox selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(PostBox record); + + List selectByRecord(PostBox postBox); + + int checkRepeat(String number); + + int checkRepeat2(@Param("number")String number, @Param("code")String code); + + PostBox checkRepeat3(@Param("number")String number, @Param("code")String code); + + PostBox checkRepeat4(@Param("number")String number, @Param("money")String money); + + List list(Map params); + + int count(Map params); + + List listForConcur(Map params); + + List selectUnValidList(@Param("maxValid") Integer maxValid); + + void updateValidDayCount(); + + int updateReceiptId(@Param("id")Integer id, @Param("receiptId")String receiptId); + + int updateIsSend(@Param("id")Integer id, @Param("isSend")String isSend); + + int updateIsSendAndReceiptId(@Param("id")Integer id, @Param("isSend")String isSend, @Param("receiptId")String receiptId); + + int checkSerialNumInvoice(@Param("invoiceNumPre") String invoiceNumPre, @Param("invoiceNumAft") String invoiceNumAft, @Param("invoiceDate") String invoiceDate); + + void updateForTask(@Param("updateStr")String updateStr); + + List selectForSyncTask(); + + void updateForSync(@Param("id")Integer id); + + List getForReceiptV4(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ProxySysUserMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ProxySysUserMapper.java new file mode 100644 index 0000000..8c45a42 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ProxySysUserMapper.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ProxySysUser; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProxySysUserMapper { + int deleteByPrimaryKey(Integer id); + + int insert(ProxySysUser record); + + int insertSelective(ProxySysUser record); + + ProxySysUser selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(ProxySysUser record); + + int updateByPrimaryKey(ProxySysUser record); + + List list(Map params); + + int count(Map params); + + int checkExist(ProxySysUser proxyUser); + + List listForTask(); + + List getRepresentedList(@Param("mainId") Integer mainId); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ProxyUserMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ProxyUserMapper.java new file mode 100644 index 0000000..d7b5177 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ProxyUserMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ProxyUser; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProxyUserMapper { + int deleteByPrimaryKey(Integer id); + + int insert(ProxyUser record); + + int insertSelective(ProxyUser record); + + ProxyUser selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(ProxyUser record); + + int updateByPrimaryKey(ProxyUser record); + + List list(Map params); + + int count(Map params); + + int checkExist(ProxyUser proxyUser); + + List listProxy(@Param("email")String email); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ReportImagesMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ReportImagesMapper.java new file mode 100644 index 0000000..6a55d8a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ReportImagesMapper.java @@ -0,0 +1,35 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ReportImages; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** +* @author ONE MORE THING +* @description 针对表【report_images(面单影像)】的数据库操作Mapper +* @createDate 2022-01-13 14:09:47 +* @Entity com.cmsen.ticket.domain.entity.ReportImages +*/ +@Mapper +public interface ReportImagesMapper { + + int deleteByPrimaryKey(Long id); + + int insert(ReportImages record); + + ReportImages selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ReportImages record); + + List listByReportId(@Param("reportId") String reportId); + + int deleteByReportId(String reportId); + + int updateReportId(@Param("newReportId") String newReportId, @Param("oldReportId") String oldReportId); + + List listByReportIdAndType(String reportId, String type); + + int deleteImg(@Param("reportId") String reportId, @Param("source") String source); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/RuleConfigMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/RuleConfigMapper.java new file mode 100644 index 0000000..7d5fc8a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/RuleConfigMapper.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.RuleConfig; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface RuleConfigMapper { + int deleteByPrimaryKey(Integer id); + + int insert(RuleConfig record); + + RuleConfig selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(RuleConfig record); + + List selectByClientAndTicketType(@Param("client") Integer client, @Param("ticket") Integer ticketType, @Param("type") Integer type); + + List selectByClientAndType(@Param("client") Integer client, @Param("type") Integer type); + + List list(Map params); + + int count(Map params); + + int checkRuleAndTicketType(Integer rule, Integer ticketType); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/RuleMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/RuleMapper.java new file mode 100644 index 0000000..253e741 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/RuleMapper.java @@ -0,0 +1,32 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.Rule; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface RuleMapper { + + int deleteByPrimaryKey(Integer id); + + int insert(Rule record); + + int insertSelective(Rule record); + + Rule selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Rule record); + + int updateByPrimaryKey(Rule record); + + List list(Integer type); + + List listByParams(Map params); + + int countByParams(Map params); + + int checkRule(@Param("name") String name, @Param("type") Integer type, @Param("id") Integer id); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/RuleTypeMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/RuleTypeMapper.java new file mode 100644 index 0000000..1915651 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/RuleTypeMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.RuleType; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface RuleTypeMapper { + int deleteByPrimaryKey(Long id); + + int insert(RuleType record); + + int insertSelective(RuleType record); + + RuleType selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(RuleType record); + + int updateByPrimaryKey(RuleType record); + + List list(); + + RuleType getByName(@Param("name") String name); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ScannerCenterFilesMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ScannerCenterFilesMapper.java new file mode 100644 index 0000000..619f964 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ScannerCenterFilesMapper.java @@ -0,0 +1,16 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ScannerCenterFiles; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ScannerCenterFilesMapper { + int insert(ScannerCenterFiles invoice); + + int updateById(ScannerCenterFiles invoice); + + ScannerCenterFiles selectByFileName(String fileName); + + + void updateFinished(String reportId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/ScannerLogsMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/ScannerLogsMapper.java new file mode 100644 index 0000000..bba206f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/ScannerLogsMapper.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.ScannerLogs; +import com.cmsen.ticket.interfaces.facade.form.ScannerLogSearch; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface ScannerLogsMapper { + + int deleteByPrimaryKey(Long id); + + int insert(ScannerLogs record); + + ScannerLogs selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ScannerLogs record); + + List listForSearch(ScannerLogSearch search); + + ScannerLogs selectByHashKey(@Param("hashKey") String hashKey); + + Integer selectByNameToday(@Param("fileName") String resultFileName, @Param("today") String today); + + ScannerLogs selectByExt01(int ncImportId); + + List selectNcRetryLogs(String lastTime); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierBlacklistMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierBlacklistMapper.java index 2cfef7b..8c97cf6 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierBlacklistMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierBlacklistMapper.java @@ -1,6 +1,8 @@ package com.cmsen.ticket.domain.mapper; +import com.cmsen.ticket.domain.entity.SupplierBlacklist; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; /** * @Entity com.cmsen.ticket.domain.entity.SupplierBlacklist @@ -11,4 +13,23 @@ public interface SupplierBlacklistMapper { * @mbg.generated 2021-02-23 16:00:58 */ int deleteByPrimaryKey(Integer id); + + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + int insert(SupplierBlacklist record); + + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + SupplierBlacklist selectByPrimaryKey(Integer id); + + /** + * @mbg.generated 2021-02-23 16:00:58 + */ + int updateByPrimaryKeySelective(SupplierBlacklist record); + + SupplierBlacklist checkSellerAndTaxNoAndClient(@Param("seller") String seller, @Param("sellerTaxNo") String sellerTaxNo, @Param("client") Integer client); + + SupplierBlacklist checkSeller(@Param("seller") String seller, @Param("client") Integer client); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierDiffAllowMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierDiffAllowMapper.java index a7dcff5..f501d78 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierDiffAllowMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierDiffAllowMapper.java @@ -1,5 +1,6 @@ package com.cmsen.ticket.domain.mapper; +import com.cmsen.ticket.domain.entity.SupplierDiffAllow; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -14,5 +15,11 @@ public interface SupplierDiffAllowMapper { int deleteByPrimaryKey(Long id); + int insert(SupplierDiffAllow record); + + SupplierDiffAllow selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SupplierDiffAllow record); + Boolean selectDiffAllowByOrgAndCorType(@Param("org") int org, @Param("corType") int corType); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierMapper.java index 095dbfd..35009b3 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierMapper.java @@ -2,6 +2,7 @@ package com.cmsen.ticket.domain.mapper; import com.cmsen.ticket.domain.dto.SupplierUomMappingDTO; import com.cmsen.ticket.domain.entity.Supplier; +import com.cmsen.ticket.domain.entity.SupplierOrderRefund; import com.cmsen.ticket.interfaces.facade.manager.form.SupplierSearchForm; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -36,22 +37,31 @@ public interface SupplierMapper { Supplier selectCodeByNameAndCode(@Param("sellerNo") String sellerNo, @Param("code") String code); Supplier selectCodeByNameAndCode2(@Param("sellerNo") String sellerNo, @Param("code") String code); Supplier selectByTaxNoCode(@Param("sellerNo") String sellerNo, @Param("code") String code); + Supplier selectByCodeOrgCode(@Param("code") String code, @Param("orgCode") String orgCode); Supplier selectBySupplierCodeOnly(@Param("supplierCode") String code); Supplier selectByName(@Param("name") String name); String selectSupplierCode(@Param("code") String code); Supplier selectByCode(@Param("supplierCode") String supplierCode); + List searchList(@Param("orgCode") String orgCode, @Param("keyword") String keyword, @Param("isDigital") String isDigital); + List selectUnMactedSellerNo(); + List selectExt05(String supplierCode); + + List selectByLikeName(String seller); List selectCNCompanyTaxNoEmpty(Map params); List selectNotCNCompany(); + List selectTaxNoEqName(); String selectFullNameByTaxNo(String taxNo); List selectUomMapping(@Param("supplierCode")String supplierCode); + + void insertRefundBatch(@Param("records") List batchList); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderHeaderMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderHeaderMapper.java new file mode 100644 index 0000000..2b1a429 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderHeaderMapper.java @@ -0,0 +1,39 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.SupplierOrderHeader; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SupplierOrderHeaderMapper { + int deleteByPrimaryKey(String billId); + + int insert(SupplierOrderHeader record); + + int insertSelective(SupplierOrderHeader record); + + SupplierOrderHeader selectByPrimaryKey(String billId); + + int updateByPrimaryKeySelective(SupplierOrderHeader record); + + int updateByPrimaryKey(SupplierOrderHeader record); + + List list(Map params); + + int count(Map params); + + SupplierOrderHeader sumPayAmount(@Param("purchase") String purchase); + + SupplierOrderHeader sumPayAmount2(@Param("brand") String brand); + + SupplierOrderHeader selectByBillNum(@Param("billNumber") String billNumber); + + int updateByParams(Map params); + + int updateExt02ByBillNum(@Param("billNumber") String billNumber, @Param("ext02") String ext02); + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderMapper.java index 9577f19..cf1bf05 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOrderMapper.java @@ -1,8 +1,10 @@ package com.cmsen.ticket.domain.mapper; import com.cmsen.ticket.application.manager.vo.SupplierInvoiceMatchOrderVo; +import com.cmsen.ticket.domain.dto.LineMatchListDto; import com.cmsen.ticket.domain.entity.SupplierOrder; -import com.cmsen.ticket.interfaces.facade.form.SupplierInvoiceMatchForm; +import com.cmsen.ticket.domain.entity.SupplierOrderRefund; +import com.cmsen.ticket.interfaces.facade.manager.form.SupplierInvoiceMatchForm; import com.cmsen.ticket.interfaces.facade.manager.form.SupplierOrderSearchForm; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -22,11 +24,26 @@ public interface SupplierOrderMapper { List list(SupplierOrderSearchForm form); + List listRefund(SupplierOrderSearchForm form); + int count(SupplierOrderSearchForm form); + int refundCount(SupplierOrderSearchForm form); + + int countReceived(SupplierOrderSearchForm form); + int updateByPrimaryKeySelective(SupplierOrder record); - List getMatchListForMultiMode(SupplierInvoiceMatchForm form); + /** + * 按供应商代码匹配订单 + * + * @param supplierCode 供应商代码 + * @param all 1 物料 2 金额 3 金额+物料 4 全部 + * @return 返回匹配结果 + */ + List matchOrderBySupplierCode(@Param("supplierCode") String supplierCode, + @Param("all") Integer all, + @Param("invoiceId") String invoiceId); /** * 按供应商代码匹配订单 @@ -36,23 +53,67 @@ public interface SupplierOrderMapper { * @return 返回匹配结果 */ List matchOrderBySupplierCode2(Map params); + /** + * 按供应商代码匹配订单 + * + * @param params supplierCode 供应商代码 + * @param params all 1 物料 2 金额 3 金额+物料 4 全部 + * @return 返回匹配结果 + */ + List matchOrderBySupplierCodeNew(Map params); + + List lineMatchList(LineMatchListDto dto); + + List selectByMatchedInfo(@Param("supplierCode") String supplierCode, @Param("orderNos") List orderNos); + + List getMatchListForMultiMode(SupplierInvoiceMatchForm form); SupplierOrder selectForAutoSmartMatching(@Param("id") Integer id); + List matchOrderByOrderNos(@Param("orderNos") String[] orderNos); + + int updateByOrderIds(@Param("ids") String ids, @Param("status") Integer status); + + List getClearList(); + + List polist(Map params); + List listByPOs(Map params); + List listByParams(Map params); + + int countByParams(Map params); + + List getUnMatchList(@Param("orderNo") String orderNo); + List getMatchList(@Param("orderNo") String orderNo); + List selectOrderForMaterial(Map params); List selectOrderForMaterial2(Map params); int deleteByOrderNo(@Param("orderNo") String orderNo); + List checkCostCenter(@Param("orderNo") String orderNo, @Param("costCenter") String costCenter); + List selectUnmatchedSupplierOrder(@Param("bpmNo") String bpmNo); List selectUnmatchedByOrderNo(String po); + List selectByPONumberAndName(@Param("invoiceId") String invoiceId, @Param("materialName")String materialName, @Param("specification")String specification, @Param("unitPrice")String unitPrice); + + List selectNcOrderByBillCode(String billCode); + + void deleteNcByInvoiceId(String invoiceId); + + SupplierOrder selectByReceiveId(String vordercode, String csourcebid); + + + SupplierOrder selectByParams(Map queryMap); + List selectListByParams(Map queryMap); + List listByInvoiceIdAndExt02(String invoiceId,String ext02); + SupplierOrder selectByState(@Param("receiveNo") String receiveNo,@Param("orderNo") String orderNo,@Param("stateItemNo") String stateItemNo); @@ -60,5 +121,17 @@ public interface SupplierOrderMapper { List getMatchSimilarOrders(Map params); + SupplierOrder selectByHtno(String htNo,String supplierCode,String receiveNo,String orderNo,String itemNo); + + List selectByExt03(String npmNo); + + void deleteByOrderNoAndReceivedNo(String orderNo, String receiveNo); + + int deleteRefundById(Integer rId); + + SupplierOrderRefund selectRefundById(Integer rId); + + void recoverRefundData(int orderId); + SupplierOrder selectSimilarOrder(Map queryMap); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOwnerTransferMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOwnerTransferMapper.java new file mode 100644 index 0000000..8f8fcc3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierOwnerTransferMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.SupplierOwnerTransfer; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SupplierOwnerTransferMapper { + int deleteByPrimaryKey(Long id); + + int insert(SupplierOwnerTransfer record); + + int insertSelective(SupplierOwnerTransfer record); + + SupplierOwnerTransfer selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SupplierOwnerTransfer record); + + int updateByPrimaryKey(SupplierOwnerTransfer record); + + List listByParams(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoLineMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoLineMapper.java new file mode 100644 index 0000000..43b4604 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoLineMapper.java @@ -0,0 +1,35 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.SupplierPoLine; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SupplierPoLineMapper { + int deleteByPrimaryKey(Integer id); + + int insert(SupplierPoLine record); + + int insertSelective(SupplierPoLine record); + + SupplierPoLine selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(SupplierPoLine record); + + int updateByPrimaryKey(SupplierPoLine record); + + int deleteByPo(@Param("po") String po); + + List list(Map params); + + int count(Map params); + + int deleteById(@Param("id") Integer id); + + SupplierPoLine selectByPoAndLineNo(@Param("po") String po, @Param("lineNo") String lineNo); + + List selectByPo(@Param("po") String po); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoMapper.java new file mode 100644 index 0000000..8324ec4 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierPoMapper.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.SupplierPo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SupplierPoMapper { + + int deleteByPrimaryKey(Integer id); + + int insert(SupplierPo record); + + int insertSelective(SupplierPo record); + + SupplierPo selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(SupplierPo record); + + int updateByPrimaryKey(SupplierPo record); + + SupplierPo selectByPo(@Param("po") String po); + + SupplierPo selectByNumber(@Param("versionNo") String versionNo); + + List list(Map params); + + int count(Map params); + + int deleteByPo(@Param("po") String po); + + int updateAmount(@Param("ext01") String ext01); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SupplierSiteMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierSiteMapper.java new file mode 100644 index 0000000..949d178 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SupplierSiteMapper.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.domain.mapper; + + +import com.cmsen.ticket.domain.entity.SupplierSite; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface SupplierSiteMapper { + int deleteByPrimaryKey(Integer id); + + int deleteByCode(String code); + + int insertSelective(SupplierSite record); + + SupplierSite selectByPrimaryKey(Integer id); + + List selectByCode(String code); + + int updateByPrimaryKeySelective(SupplierSite record); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/SysNotificationMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/SysNotificationMapper.java new file mode 100644 index 0000000..3e70497 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/SysNotificationMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.SysNotification; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * @author ONE MORE THING + * @description 针对表【sys_notification(系统通知)】的数据库操作Mapper + * @createDate 2021-12-10 14:07:44 + * @Entity com.cmsen.ticket.domain.entity.SysNotification + */ +@Mapper +public interface SysNotificationMapper { + + int deleteByPrimaryKey(Long id); + + int insert(SysNotification record); + + SysNotification selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SysNotification record); + + List getList(@Param("lines") int lines); + + SysNotification getPrivacy(); + + List getHotPolicies(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/TPublicWorkdayMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/TPublicWorkdayMapper.java new file mode 100644 index 0000000..a20a8be --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/TPublicWorkdayMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.TPublicWorkday; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** +* @author admin +* @description 针对表【t_public_workday(国家法定节假日表_dabaohong_2022-05-10)】的数据库操作Mapper +* @createDate 2022-05-19 15:27:24 +* @Entity com.cmsen.ticket.domain.entity.TPublicWorkday +*/ +@Mapper +public interface TPublicWorkdayMapper { + + int deleteByPrimaryKey(Long id); + + int insert(TPublicWorkday record); + + int insertSelective(TPublicWorkday record); + + TPublicWorkday selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(TPublicWorkday record); + + int updateByPrimaryKey(TPublicWorkday record); + + List selectByDayType(Integer type); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/TaxMappingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/TaxMappingMapper.java new file mode 100644 index 0000000..bf07691 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/TaxMappingMapper.java @@ -0,0 +1,36 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.TaxMapping; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @Entity com.cmsen.ticket.domain.entity.TaxMapping + */ +@Mapper +public interface TaxMappingMapper { + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + int deleteByPrimaryKey(Integer id); + + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + int insert(TaxMapping record); + + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + TaxMapping selectByPrimaryKey(Integer id); + + /** + * @mbg.generated 2021-02-25 13:15:04 + */ + int updateByPrimaryKeySelective(TaxMapping record); + + TaxMapping selectByTaxRate(String taxRate); + + List selectList(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMapper.java new file mode 100644 index 0000000..6f9da58 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMapper.java @@ -0,0 +1,28 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.TicketType; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface TicketTypeMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TicketType record); + + TicketType selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TicketType record); + + TicketType selectByCode(String code); + + TicketType selectByName(@Param("name") String name); + + List checkByNameCode(@Param("name") String name); + + List list(); + + TicketType selectCode(@Param("ext02") String ext02, @Param("ext03") String ext03); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMappingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMappingMapper.java new file mode 100644 index 0000000..b12abe9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/TicketTypeMappingMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.TicketTypeMapping; +import org.apache.ibatis.annotations.Mapper; + +/** +* @author ONE MORE THING +* @description 针对表【ticket_type_mapping(发票类型匹配表)】的数据库操作Mapper +* @createDate 2021-12-22 15:12:15 +* @Entity com.cmsen.ticket.domain.entity.TicketTypeMapping +*/ +@Mapper +public interface TicketTypeMappingMapper { + + int deleteByPrimaryKey(Long id); + + int insert(TicketTypeMapping record); + + TicketTypeMapping selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(TicketTypeMapping record); + + TicketTypeMapping findByRecord(TicketTypeMapping ticketTypeMapping); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/UserCompanyMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/UserCompanyMapper.java new file mode 100644 index 0000000..3d83cac --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/UserCompanyMapper.java @@ -0,0 +1,19 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.UserCompany; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserCompanyMapper { + int deleteByPrimaryKey(Integer id); + + int insert(UserCompany record); + + int insertSelective(UserCompany record); + + UserCompany selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(UserCompany record); + + int updateByPrimaryKey(UserCompany record); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/UserConfigListMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/UserConfigListMapper.java new file mode 100644 index 0000000..e6e699e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/UserConfigListMapper.java @@ -0,0 +1,28 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.UserConfigList; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface UserConfigListMapper { + int deleteByPrimaryKey(Integer id); + + int insert(UserConfigList record); + + int insertSelective(UserConfigList record); + + UserConfigList selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(UserConfigList record); + + int updateByPrimaryKey(UserConfigList record); + + UserConfigList selectByUserAndType(@Param("userId") Integer userId, @Param("type") String type); + + List selectByType(@Param("type") String type); + + void deleteByUserIdAndType(@Param("userId") Integer userId, @Param("type") String type); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/UserGuideMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/UserGuideMapper.java new file mode 100644 index 0000000..89ac0c6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/UserGuideMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.UserGuide; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author ONE MORE THING + * @description 针对表【user_guide(用户向导)】的数据库操作Mapper + * @createDate 2021-12-10 14:08:00 + * @Entity com.cmsen.ticket.domain.entity.UserGuide + */ +@Mapper +public interface UserGuideMapper { + + int deleteByPrimaryKey(Long id); + + int insert(UserGuide record); + + UserGuide selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(UserGuide record); + + List getList(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/UserPcMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/UserPcMapper.java new file mode 100644 index 0000000..d78925f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/UserPcMapper.java @@ -0,0 +1,30 @@ +package com.cmsen.ticket.domain.mapper; + +import com.cmsen.ticket.domain.entity.UserPc; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface UserPcMapper { + int deleteByPrimaryKey(Integer userId); + + int insert(UserPc record); + + int insertSelective(UserPc record); + + UserPc selectByPrimaryKey(Integer userId); + + int updateByPrimaryKeySelective(UserPc record); + + int updateByPrimaryKey(UserPc record); + + UserPc selectByOpenId(@Param("openId") String openId, @Param("isChecked") String isChecked); + + UserPc checkVerCode(@Param("telOrEmail") String telOrEmail, @Param("verCode") String verCode); + + UserPc selectByEmail(@Param("email") String email); + + List listProxy(@Param("email") String email); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/AccountPeriodMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/AccountPeriodMapper.java new file mode 100644 index 0000000..b14ee64 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/AccountPeriodMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.AccountPeriod; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** +* @author admin +* @description 针对表【account_period】的数据库操作Mapper +* @createDate 2022-03-23 10:04:55 +* @Entity generator.domain.AccountPeriod +*/ +@Mapper +public interface AccountPeriodMapper { + + List selectByStatus(); + + int deleteByPrimaryKey(Long id); + + int insert(AccountPeriod record); + + int insertSelective(AccountPeriod record); + + AccountPeriod selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(AccountPeriod record); + + int updateByPrimaryKey(AccountPeriod record); + +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/DeductionConfigMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/DeductionConfigMapper.java new file mode 100644 index 0000000..9cfb347 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/DeductionConfigMapper.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.mapper.manager; + + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * @Entity com.cmsen.ticket.domain.entity.domain.mapper.DeductionConfig + */ +@Mapper +public interface DeductionConfigMapper { + String getByType(@Param("type") Integer type); +} + + + + diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/InvoiceKindMatchingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/InvoiceKindMatchingMapper.java new file mode 100644 index 0000000..9368b54 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/InvoiceKindMatchingMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.InvoiceKindMatching; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface InvoiceKindMatchingMapper { + int deleteByPrimaryKey(Integer id); + + int insert(InvoiceKindMatching record); + + int insertSelective(InvoiceKindMatching record); + + InvoiceKindMatching selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(InvoiceKindMatching record); + + int updateByPrimaryKey(InvoiceKindMatching record); + + List list(Map params); + + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/PreferencesMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/PreferencesMapper.java new file mode 100644 index 0000000..7064210 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/PreferencesMapper.java @@ -0,0 +1,32 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.Preferences; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface PreferencesMapper { + int deleteByPrimaryKey(Integer id); + + int insert(Preferences record); + + Preferences selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Preferences record); + + int updateByPrimaryKey(Preferences record); + + Preferences selectByTicketTypeAndNullConsumeType(@Param("ticketType") Integer id); + + Preferences selectByConsumeTypeAndNullTicketType(@Param("consumeType") String consumeType); + + Preferences selectByTicketTypeAndConsumeType(@Param("ticketType") Integer ticketType, @Param("consumeType") String consumeType); + + List list(Map params); + List list2(Map params); + + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetAttendMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetAttendMapper.java new file mode 100644 index 0000000..33e331f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetAttendMapper.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.SigninMeetAttend; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SigninMeetAttendMapper { + int deleteByPrimaryKey(Integer id); + + int insert(SigninMeetAttend record); + + int insertSelective(SigninMeetAttend record); + + SigninMeetAttend selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(SigninMeetAttend record); + + int updateByPrimaryKey(SigninMeetAttend record); + + List list(Map params); + + int count(Map params); + + int deleteByPid(Integer pid); + + int insertBatch(@Param("attends") List attends, @Param("pid") Integer pid); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetMapper.java new file mode 100644 index 0000000..ce61946 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SigninMeetMapper.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.SigninMeet; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface SigninMeetMapper { + int deleteByPrimaryKey(Integer id); + + int insert(SigninMeet record); + + int insertSelective(SigninMeet record); + + SigninMeet selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(SigninMeet record); + + int updateByPrimaryKey(SigninMeet record); + + List list(Map params); + + int count(Map params); + + SigninMeet selByReqId(@Param("reqId") String reqId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SupplierOrderItemMatchingMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SupplierOrderItemMatchingMapper.java index de98664..235e1c3 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SupplierOrderItemMatchingMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SupplierOrderItemMatchingMapper.java @@ -1,11 +1,17 @@ package com.cmsen.ticket.domain.mapper.manager; import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatchingReport; +import com.cmsen.ticket.domain.vo.SupplierOrderItemUsedVo; +import com.cmsen.ticket.domain.vo.SupplierOrderItemsVo; +import com.cmsen.ticket.interfaces.facade.manager.form.SupplierOrderSearchForm; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.math.BigDecimal; import java.util.List; +import java.util.Map; +import java.util.Set; @Mapper public interface SupplierOrderItemMatchingMapper { @@ -16,6 +22,7 @@ public interface SupplierOrderItemMatchingMapper { SupplierOrderItemMatching selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(SupplierOrderItemMatching record); + int updateByFlow(String id); int insertBatch(List list); @@ -25,21 +32,74 @@ public interface SupplierOrderItemMatchingMapper { int completeMatching(@Param("ids") List ids); + int clearMatching(@Param("ids") List ids); + + int deleteByOrderId(@Param("orderId") Integer orderId); + int deleteByOrderNo(@Param("orderNo") String orderNo); int selectCountByInvoiceId(String invoiceId); + BigDecimal getUsedAmountByOrderNo(@Param("orderNo") String orderNo); + BigDecimal getUsedAmountByOrderId(@Param("orderId") Integer orderId); BigDecimal getUsedAmountByItemId(@Param("itemId") String itemId); + SupplierOrderItemUsedVo getUsedItemId(@Param("itemId") String itemId); + + double checkInvoiceAllMatched(@Param("invoiceId") String invoiceId); + List selectIdsByStatusAndInvoiceId(@Param("invoiceId") String invoiceId, @Param("matchStatus") Integer matchStatus); + Set calculateInvoiceSurplus(@Param("invoiceId") String invoiceId); + BigDecimal getUsedQuantityByItemId(@Param("itemId") String itemId); String getUsedQuantityByOrderId(@Param("orderId") Integer orderId); + int checkInvoiceExist(@Param("invoiceId") String invoiceId); + + int revokeMapping(@Param("invoiceId") String invoiceId); + + Set calculateInvoiceSurplusQuantity(String invoiceId); + BigDecimal sumMatchingCountByItemId(@Param("itemId") String itemId); + List getSupplierOrderItems(@Param("invoiceId") String invoiceId); + List getSupplierOrderItemsMore(@Param("status") String status); + List selectListByHtNo(@Param("htNo") String invoiceId); List selectListGroupByInvoiceId(@Param("invoiceId") String invoiceId); + + List polist(SupplierOrderSearchForm form); + + int pocount(SupplierOrderSearchForm form); + + List poMaplist(Map params); + + List reportlist(Map params); + + List selectByOrderNo(@Param("orderNo") String orderNo, @Param("status") String status); + + List selectByOrderNo2(@Param("orderNo") String orderNo, @Param("userId") String userId, @Param("status") String status); + + int updateByOrderNo(@Param("orderNo") String orderNo, @Param("status") String status); + + int updateByOrderNo2(@Param("orderNo") String orderNo, @Param("userId") String userId, @Param("status") String status); + + int updateById(@Param("id") String id, @Param("status") String status); + + List selectForTask(@Param("orderNo") String orderNo); + + void deleteByInvoiceId(String pId); + + List selectByInvoiceAndItemId(SupplierOrderItemMatching matching); + + List selectByInvoiceId(String invoiceId); + + List getRefundList(String supplierCode,String orderNo); + + void updateRefundStatus(String supplierCode,String orderNo); + + List getRefundOrderNoList(); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysEmpMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysEmpMapper.java new file mode 100644 index 0000000..f691d65 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysEmpMapper.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.SysEmp; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +@Mapper +public interface SysEmpMapper { + int deleteByPrimaryKey(Long id); + + int insert(SysEmp record); + + int insertSelective(SysEmp record); + + SysEmp selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SysEmp record); + + int updateByPrimaryKey(SysEmp record); + + List searchByKeyword(@Param("keyword") String keyword); + + SysEmp selectUserId(@Param("sysId") String sysId); + + SysEmp selectByUserId(@Param("userId") String userId); + + SysEmp selectNameByUserIds(@Param("userIds") String userIds); + + int deleteAll(); + + SysEmp selectByEmail(String email); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysLogoMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysLogoMapper.java new file mode 100644 index 0000000..2b2feae --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysLogoMapper.java @@ -0,0 +1,21 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.SysLogo; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SysLogoMapper { + int deleteByPrimaryKey(Long id); + + int insert(SysLogo record); + + int insertSelective(SysLogo record); + + SysLogo selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SysLogo record); + + int updateByPrimaryKey(SysLogo record); + + SysLogo getRecord(); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysOaDeptMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysOaDeptMapper.java new file mode 100644 index 0000000..f8ab837 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysOaDeptMapper.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.mapper.manager; + +import com.cmsen.ticket.domain.entity.manager.SysOaDept; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface SysOaDeptMapper { + int deleteByPrimaryKey(Long id); + + int insert(SysOaDept record); + + int insertSelective(SysOaDept record); + + SysOaDept selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(SysOaDept record); + + int updateByPrimaryKey(SysOaDept record); + + SysOaDept selectByCode(@Param("code") String code); + + SysOaDept selectSubDeptId(@Param("departmaentId") String departmaentId, @Param("subCompanyId") String subCompanyId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysUserMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysUserMapper.java index 23e9e24..cb91f42 100644 --- a/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysUserMapper.java +++ b/src/main/java/com/cmsen/ticket/domain/mapper/manager/SysUserMapper.java @@ -1,9 +1,8 @@ package com.cmsen.ticket.domain.mapper.manager; +import com.cmsen.ticket.domain.entity.User; import com.cmsen.ticket.domain.entity.manager.SysUser; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.*; import java.util.List; import java.util.Map; @@ -28,13 +27,41 @@ public interface SysUserMapper { int count(Map params); + List searchForSupplier(@Param("keyword") String keyword); + SysUser selectByEmail(String email); SysUser selectByTelAndCode(@Param("tel") String tel, @Param("code") String code); + SysUser selectOrgById(Integer id); + + SysUser selectByOAId(@Param("oaId") String oaId); + SysUser selectByJobNo(@Param("jobNo") String jobNo); + List selectForTransfer(Map params); + + @Update("${sql}") + public void execUpdateSql(@Param("sql") String sql); + + @Insert("${sql}") + public void execInsertSql(@Param("sql") String sql); + + @Delete("${sql}") + public void execDeleteSql(@Param("sql") String sql); @Select("${sql}") public List> execSelectSql(@Param(value="sql")String sql); + + int updateInActive(Integer id); + + List selectSearchList(@Param("keyword") String keyword); + + List selectUserList(@Param("keyword") String keyword); + + User selUserById(Integer id); + + SysUser selectByUserId(@Param("userId") Integer userId); + + void insertIntoCsvLogs(String invoiceId, String number, String fh_barcode); } diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectAttendeeMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectAttendeeMapper.java new file mode 100644 index 0000000..8793f4e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectAttendeeMapper.java @@ -0,0 +1,25 @@ +package com.cmsen.ticket.domain.mapper.project; + +import com.cmsen.ticket.domain.entity.project.ProjectAttendee; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + + +@Mapper +public interface ProjectAttendeeMapper { + int deleteByPrimaryKey(Long id); + + int insert(ProjectAttendee record); + + ProjectAttendee selectByPrimaryKey(Long id); + + ProjectAttendee checkAttendee(@Param("projectCode") String projectCode,@Param("attendee") String attendee); + + int updateByPrimaryKeySelective(ProjectAttendee record); + + List getAttendeeList(@Param("projectCode") String projectCode); + + int delAttendeeList(@Param("projectCode") String projectCode); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectHoursReportMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectHoursReportMapper.java new file mode 100644 index 0000000..fd1811f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectHoursReportMapper.java @@ -0,0 +1,36 @@ +package com.cmsen.ticket.domain.mapper.project; + +import com.cmsen.ticket.domain.entity.project.ProjectHoursReport; +import com.cmsen.ticket.domain.entity.project.response.WeekHours; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProjectHoursReportMapper { + int deleteByPrimaryKey(Long id); + + int insert(ProjectHoursReport record); + + ProjectHoursReport selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ProjectHoursReport record); + + List getListDetailHours(Map params); + + WeekHours getWeekHours(Map params); + + int checkDay(Map params); + + int submitHours(Map params); + + List listProWeekHours(Map params); + + int passHours(Map params); + + int rejectHours(Map params); + + List getByTaskId(@Param("taskId") Long taskId); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectMapper.java new file mode 100644 index 0000000..08a8164 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectMapper.java @@ -0,0 +1,26 @@ +package com.cmsen.ticket.domain.mapper.project; + +import com.cmsen.ticket.domain.entity.project.Project; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + + +@Mapper +public interface ProjectMapper { + int deleteByPrimaryKey(Long id); + + int insert(Project record); + + Project selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(Project record); + + List searchByKeyword(@Param("keyword") String keyword, @Param("approver") String approver); + + List list(Map params); + + int count(Map params); +} diff --git a/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectTaskMapper.java b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectTaskMapper.java new file mode 100644 index 0000000..e0d73ef --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/mapper/project/ProjectTaskMapper.java @@ -0,0 +1,27 @@ +package com.cmsen.ticket.domain.mapper.project; + +import com.cmsen.ticket.domain.entity.project.ProjectTask; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProjectTaskMapper { + int deleteByPrimaryKey(Long id); + + int insert(ProjectTask record); + + ProjectTask selectByPrimaryKey(Long id); + + int updateByPrimaryKeySelective(ProjectTask record); + + List getRespTask(@Param("responsiblePerson") String responsiblePerson); + + List list(Map params); + + int count(Map params); + + int updateStatus(@Param("id") Long id, @Param("status") Integer status); +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/AmapUtil.java b/src/main/java/com/cmsen/ticket/domain/util/AmapUtil.java new file mode 100644 index 0000000..48df7c0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/AmapUtil.java @@ -0,0 +1,52 @@ +package com.cmsen.ticket.domain.util; + +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +public class AmapUtil { + + // 高德逆地理接口 + private static final String REGEO_URL = "https://restapi.amap.com/v3/geocode/regeo"; + + // 高德驾车路线接口 + private static final String DRIVING_URL = "https://restapi.amap.com/v3/direction/driving"; + + private static final RestTemplate restTemplate = new RestTemplate(); + + /** + * 逆地理编码:经纬度 → 地址 + */ + public static Map regeo(String location, String amapKey) { + StringBuilder url = new StringBuilder(REGEO_URL); + url.append("?key=").append(amapKey); + url.append("&location=").append(location); + url.append("&output=json"); + + return restTemplate.getForObject(url.toString(), Map.class); + } + + /** + * 驾车路线:支持途经点 + * @param origin 起点 "lng,lat" + * @param destination 终点 "lng,lat" + * @param waypoints 途经点 多个用 ; 分隔,无则传 null/空字符串 + * @return 高德原始返回 + */ + public static Map driving(String origin, String destination, String waypoints, String amapKey) { + + StringBuilder url = new StringBuilder(DRIVING_URL); + url.append("?key=").append(amapKey); + url.append("&origin=").append(origin); + url.append("&destination=").append(destination); + url.append("&output=json&strategy=0"); + + // 仅当 waypoints 有有效内容时才拼接参数 + if (StringUtils.hasText(waypoints)) { + url.append("&waypoints=").append(waypoints); + } + + return restTemplate.getForObject(url.toString(), Map.class); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/ClassUtil.java b/src/main/java/com/cmsen/ticket/domain/util/ClassUtil.java new file mode 100644 index 0000000..88ac88d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/ClassUtil.java @@ -0,0 +1,479 @@ +package com.cmsen.ticket.domain.util; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.annotation.Annotation; +import java.lang.reflect.*; +import java.util.*; + +/** + * 获取Class信息的工具类 + * + * 1. 取shortClassName 和 packageName + * + * 2. 获取全部父类,全部接口,以及全部Annotation + * + * 3. 获取标注了annotation的所有属性和方法 + * + * 4. 获取方法与属性 (兼容了原始类型的参数, 并默认将方法与属性设为可访问) + * + * 5. 其他杂项 + * + * @author calvin + */ +public class ClassUtil { + + private static final String CGLIB_CLASS_SEPARATOR = "$$"; + + private static Logger logger = LoggerFactory.getLogger(ClassUtil.class); + + private static final Map, Class> primitiveWrapperTypeMap = new IdentityHashMap, Class>(8); + + static { + primitiveWrapperTypeMap.put(Boolean.class, Boolean.TYPE); + primitiveWrapperTypeMap.put(Byte.class, Byte.TYPE); + primitiveWrapperTypeMap.put(Character.class, Character.TYPE); + primitiveWrapperTypeMap.put(Double.class, Double.TYPE); + primitiveWrapperTypeMap.put(Float.class, Float.TYPE); + primitiveWrapperTypeMap.put(Integer.class, Integer.TYPE); + primitiveWrapperTypeMap.put(Long.class, Long.TYPE); + primitiveWrapperTypeMap.put(Short.class, Short.TYPE); + } + + private static final String SETTER_PREFIX = "set"; + private static final String GETTER_PREFIX = "get"; + private static final String IS_PREFIX = "is"; + + ////////// shortClassName 和 packageName////////// + /** + * 返回Class名, 不包含PackageName. + * + * 内部类的话,返回"主类.内部类" + */ + public static String getShortClassName(final Class cls) { + return ClassUtils.getShortClassName(cls); + } + + /** + * 返回Class名,不包含PackageName + * + * 内部类的话,返回"主类.内部类" + */ + public static String getShortClassName(final String className) { + return ClassUtils.getShortClassName(className); + } + + /** + * 返回PackageName + */ + public static String getPackageName(final Class cls) { + return ClassUtils.getPackageName(cls); + } + + /** + * 返回PackageName + */ + public static String getPackageName(final String className) { + return ClassUtils.getPackageName(className); + } + + ////////// 获取全部父类,全部接口,以及全部Annotation////////// + /** + * 递归返回所有的SupperClasses,包含Object.class + */ + public static List> getAllSuperclasses(final Class cls) { + return ClassUtils.getAllSuperclasses(cls); + } + + /** + * 递归返回本类及所有基类继承的接口,及接口继承的接口,比Spring中的相同实现完整 + */ + public static List> getAllInterfaces(final Class cls) { + return ClassUtils.getAllInterfaces(cls); + } + + /** + * 递归Class所有的Annotation,一个最彻底的实现. + * + * 包括所有基类,所有接口的Annotation,同时支持Spring风格的Annotation继承的父Annotation, + */ + public static Set getAllAnnotations(final Class cls) { + List> allTypes = getAllSuperclasses(cls); + allTypes.addAll(getAllInterfaces(cls)); + allTypes.add(cls); + + Set anns = new HashSet(); + for (Class type : allTypes) { + anns.addAll(Arrays.asList(type.getDeclaredAnnotations())); + } + + Set superAnnotations = new HashSet(); + for (Annotation ann : anns) { + getSupperAnnotations(ann.annotationType(), superAnnotations); + } + + anns.addAll(superAnnotations); + + return anns; + } + + private static void getSupperAnnotations(Class annotationType, Set visited) { + Annotation[] anns = annotationType.getDeclaredAnnotations(); + + for (Annotation ann : anns) { + if (!ann.annotationType().getName().startsWith("java.lang") && visited.add(ann)) { + getSupperAnnotations(ann.annotationType(), visited); + } + } + } + + //// 获取标注了annotation的所有属性和方法//////// + + /** + * 找出所有标注了该annotation的公共属性,循环遍历父类. + * + * 暂未支持Spring风格Annotation继承Annotation + * + * from org.unitils.util.AnnotationUtils + */ + public static Set getAnnotatedPublicFields(Class clazz, + Class annotation) { + + if (Object.class.equals(clazz)) { + return Collections.emptySet(); + } + + Set annotatedFields = new HashSet(); + Field[] fields = clazz.getFields(); + + for (Field field : fields) { + if (field.getAnnotation(annotation) != null) { + annotatedFields.add(field); + } + } + + return annotatedFields; + } + + /** + * 找出所有标注了该annotation的属性,循环遍历父类,包含private属性. + * + * 暂未支持Spring风格Annotation继承Annotation + * + * from org.unitils.util.AnnotationUtils + */ + public static Set getAnnotatedFields(Class clazz, + Class annotation) { + if (Object.class.equals(clazz)) { + return Collections.emptySet(); + } + Set annotatedFields = new HashSet(); + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (field.getAnnotation(annotation) != null) { + annotatedFields.add(field); + } + } + annotatedFields.addAll(getAnnotatedFields(clazz.getSuperclass(), annotation)); + return annotatedFields; + } + + /** + * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口. + * + * 暂未支持Spring风格Annotation继承Annotation + * + * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承. + */ + public static Set getAnnotatedPublicMethods(Class clazz, Class annotation) { + // 已递归到Objebt.class, 停止递归 + if (Object.class.equals(clazz)) { + return Collections.emptySet(); + } + + List> ifcs = ClassUtils.getAllInterfaces(clazz); + Set annotatedMethods = new HashSet(); + + // 遍历当前类的所有公共方法 + Method[] methods = clazz.getMethods(); + + for (Method method : methods) { + // 如果当前方法有标注,或定义了该方法的所有接口有标注 + if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) { + annotatedMethods.add(method); + } + } + + return annotatedMethods; + } + + private static boolean searchOnInterfaces(Method method, Class annotationType, + List> ifcs) { + for (Class iface : ifcs) { + try { + Method equivalentMethod = iface.getMethod(method.getName(), method.getParameterTypes()); + if (equivalentMethod.getAnnotation(annotationType) != null) { + return true; + } + } catch (NoSuchMethodException ex) { + // Skip this interface - it doesn't have the method... + } + } + return false; + } + + ///////// 获取方法//// + /** + * 循环遍历,按属性名获取前缀为get或is的函数,并设为可访问 + */ + public static Method getSetterMethod(Class clazz, String propertyName, Class parameterType) { + String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName); + return getAccessibleMethod(clazz, setterMethodName, parameterType); + } + + /** + * 循环遍历,按属性名获取前缀为set的函数,并设为可访问 + */ + public static Method getGetterMethod(Class clazz, String propertyName) { + String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(propertyName); + + Method method = getAccessibleMethod(clazz, getterMethodName); + + // retry on another name + if (method == null) { + getterMethodName = IS_PREFIX + StringUtils.capitalize(propertyName); + method = getAccessibleMethod(clazz, getterMethodName); + } + return method; + } + + /** + * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. + * + * 如向上转型到Object仍无法找到, 返回null. + * + * 因为class.getFiled(); 不能获取父类的private函数, 因此采用循环向上的getDeclaredField(); + */ + public static Field getAccessibleField(final Class clazz, final String fieldName) { + Validate.notNull(clazz, "clazz can't be null"); + Validate.notEmpty(fieldName, "fieldName can't be blank"); + for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { + try { + Field field = superClass.getDeclaredField(fieldName); + makeAccessible(field); + return field; + } catch (NoSuchFieldException e) {// NOSONAR + // Field不在当前类定义,继续向上转型 + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod, 并强制设置为可访问. + * + * 如向上转型到Object仍无法找到, 返回null. + * + * 匹配函数名+参数类型. + * + * 因为class.getFiled() 不能获取父类的private函数, 因此采用循环向上的getDeclaredField(); + */ + public static Method getAccessibleMethod(final Class clazz, final String methodName, + Class... parameterTypes) { + Validate.notNull(clazz, "class can't be null"); + Validate.notEmpty(methodName, "methodName can't be blank"); + Class[] theParameterTypes = ArrayUtils.nullToEmpty(parameterTypes); + + // 处理原子类型与对象类型的兼容 + wrapClassses(theParameterTypes); + + for (Class searchType = clazz; searchType != Object.class; searchType = searchType.getSuperclass()) { + try { + Method method = searchType.getDeclaredMethod(methodName, theParameterTypes); + makeAccessible(method); + return method; + } catch (NoSuchMethodException e) { + // Method不在当前类定义,继续向上转型 + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. + * + * 如向上转型到Object仍无法找到, 返回null. + * + * 只匹配函数名, 如果有多个同名函数返回第一个 + * + * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) + * + * 因为class.getMethods() 不能获取父类的private函数, 因此采用循环向上的getMethods(); + */ + public static Method getAccessibleMethodByName(final Class clazz, final String methodName) { + Validate.notNull(clazz, "clazz can't be null"); + Validate.notEmpty(methodName, "methodName can't be blank"); + + for (Class searchType = clazz; searchType != Object.class; searchType = searchType.getSuperclass()) { + Method[] methods = searchType.getDeclaredMethods(); + for (Method method : methods) { + if (method.getName().equals(methodName)) { + makeAccessible(method); + return method; + } + } + } + return null; + } + + /** + * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Method method) { + if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) + && !method.isAccessible()) { + method.setAccessible(true); + } + } + + /** + * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Field field) { + if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) + || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { + field.setAccessible(true); + } + } + + /** + * 兼容原子类型与非原子类型的转换,不考虑依赖两者不同来区分不同函数的场景 + */ + private static void wrapClassses(Class[] source) { + for (int i = 0; i < source.length; i++) { + Class wrapClass = primitiveWrapperTypeMap.get(source[i]); + if (wrapClass != null) { + source[i] = wrapClass; + } + } + } + + /////////// 杂项 ///////// + /** + * From Spring, 按顺序获取默认ClassLoader + * + * 1. Thread.currentThread().getContextClassLoader() + * + * 2. ClassUtil的加载ClassLoader + * + * 3. SystemClassLoader + */ + public static ClassLoader getDefaultClassLoader() { + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (Throwable ex) { + // Cannot access thread context ClassLoader - falling back... + } + if (cl == null) { + // No thread context class loader -> use class loader of this class. + cl = ClassUtils.class.getClassLoader(); + if (cl == null) { + // getClassLoader() returning null indicates the bootstrap ClassLoader + try { + cl = ClassLoader.getSystemClassLoader(); + } catch (Throwable ex) { + // Cannot access system ClassLoader - oh well, maybe the caller can live with null... + } + } + } + return cl; + } + + /** + * 获取CGLib处理过后的实体的原Class. + */ + public static Class unwrapCglib(Object instance) { + Validate.notNull(instance, "Instance must not be null"); + Class clazz = instance.getClass(); + if ((clazz != null) && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { + Class superClass = clazz.getSuperclass(); + if ((superClass != null) && !Object.class.equals(superClass)) { + return superClass; + } + } + return clazz; + } + + /** + * 通过反射, 获得Class定义中声明的泛型参数的类型, + * + * 注意泛型必须定义在父类处. 这是唯一可以通过反射从泛型获得Class实例的地方. + * + * 如无法找到, 返回Object.class. + * + * eg. public UserDao extends HibernateDao + * + * @param clazz The class to introspect + * @return the first generic declaration, or Object.class if cannot be determined + */ + public static Class getClassGenricType(final Class clazz) { + return getClassGenricType(clazz, 0); + } + + /** + * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. + * + * 注意泛型必须定义在父类处. 这是唯一可以通过反射从泛型获得Class实例的地方. + * + * 如无法找到, 返回Object.class. + * + * 如public UserDao extends HibernateDao + * + * @param clazz clazz The class to introspect + * @param index the Index of the generic ddeclaration, start from 0. + * @return the index generic declaration, or Object.class if cannot be determined + */ + public static Class getClassGenricType(final Class clazz, final int index) { + + Type genType = clazz.getGenericSuperclass(); + + if (!(genType instanceof ParameterizedType)) { + logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); + return Object.class; + } + + Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); + + if ((index >= params.length) || (index < 0)) { + logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + + params.length); + return Object.class; + } + if (!(params[index] instanceof Class)) { + logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); + return Object.class; + } + + return (Class) params[index]; + } + + /** + * 探测类是否存在classpath中 + */ + public static boolean isPresent(String className, ClassLoader classLoader) { + try { + classLoader.loadClass(className); + return true; + } catch (Throwable ex) { + // Class or one of its dependencies is not present... + return false; + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/DownloadPdf.java b/src/main/java/com/cmsen/ticket/domain/util/DownloadPdf.java new file mode 100644 index 0000000..971029b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/DownloadPdf.java @@ -0,0 +1,75 @@ +package com.cmsen.ticket.domain.util; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * @author ran hao yu + * @date 2020/9/4 9:23 + * @description + */ +public class DownloadPdf { + /** + * 从网络Url中下载文件 + * + * @param urlStr + * @param fileName + * @param savePath + * @throws IOException + */ + public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + //设置超时间为3秒 + conn.setConnectTimeout(5 * 1000); + //防止屏蔽程序抓取而返回403错误 + conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); + //得到输入流 + InputStream inputStream = conn.getInputStream(); + //获取自己数组 + byte[] getData = readInputStream(inputStream); + //文件保存位置 + File saveDir = new File(savePath); + if (!saveDir.exists()) { + saveDir.mkdir(); + } + File file = new File(saveDir + File.separator + fileName); + FileOutputStream fos = new FileOutputStream(file); + fos.write(getData); + if (fos != null) { + fos.close(); + } + if (inputStream != null) { + inputStream.close(); + } + } + + + /** + * 从输入流中获取字节数组 + * + * @param inputStream + * @return + * @throws IOException + */ + public static byte[] readInputStream(InputStream inputStream) throws IOException { + byte[] buffer = new byte[1024]; + int len = 0; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + while ((len = inputStream.read(buffer)) != -1) { + bos.write(buffer, 0, len); + } + bos.close(); + return bos.toByteArray(); + } + + public static void main(String[] args) { + try { + downLoadByUrl("http://118.31.3.255:18088/api/img/4038812291040303.pdf", + "55.pdf", "D:"); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/DrawTableUtil.java b/src/main/java/com/cmsen/ticket/domain/util/DrawTableUtil.java new file mode 100644 index 0000000..2fb4170 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/DrawTableUtil.java @@ -0,0 +1,841 @@ +package com.cmsen.ticket.domain.util; + + +import lombok.Data; +import lombok.SneakyThrows; +import lombok.experimental.Accessors; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Pair; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +/** + * JAVA 绘制表格 + * + * @author sk + * @date 2022/7/17 22:41 + */ +public class DrawTableUtil { + /** + * 美团数据生成图片表格 + * @param headName + * @param tableVal + * @param imgPath + */ + public static void mtPic(String headName,Map tableVal,String imgPath){ + Cell.mtStyle(headName,tableVal,imgPath); + } +} + +/** + * 表样属性 + */ +@Data +@Accessors(chain = true) +class Table { + /** + * 表头背景色 + */ + private Color headerBackGroundColor; + /** + * 表头字体 + */ + private Font headerFont; + /** + * 单元格字体 + */ + private Font cellFont; + /** + * 表头单元格 + */ + private List headCells; + /** + * 要合并的列 + */ + private int[] mergeColumns; + /** + * 行高 + */ + private int rowHeight = 30; + /** + * 上边距 + */ + private int marginY = 10; + /*** + * 左边距 + */ + private int marginX = 10; + + +} + +/** + * 单元格属性 + */ +@Data +@Accessors(chain = true) +class Cell { + /** + * 行 + */ + private int row; + /** + * 列 + */ + private int column; + /** + * x 坐标 + */ + private int x; + /** + * y 坐标 + */ + private int y; + /** + * 当前单元格的父级单元格所在的列 + */ + private int belongColumn; + /** + * 单元格宽度,对于有从属单元格的,其宽度由从属单元格决定 + */ + private int width; + /** + * 、 + * 合并单元格的情况会用到,默认为行高 + */ + private int height; + /** + * 单元格内容 + */ + private String content; + /** + * 是否水平居中 + */ + private boolean textAlign; + + + public Cell(int row, int column, int width, int belongColumn) { + this.row = row; + this.column = column; + this.width = width; + this.belongColumn = belongColumn; + } + + public Cell() { + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cell cell = (Cell) o; + return row == cell.row && column == cell.column; + } + + @Override + public int hashCode() { + return Objects.hash(row, column); + } + + public static void main(String[] args) { + //style0(); + //style1(); + //style2(); + //style3(); + //{"Date": "2023-08-07", "Type": "3100","creditCard": "XXXX83752", "Restarant": "美团饭店","Attendee": "5","Amount": "941","Currecy": "CNY","Status": "完成","ActualAttend": "5", + // "Remark": "230518 兰州市第一人民医院泌尿科室会","isCheck": "是","Reason": "点检","Result": "合格"} + Map map = new HashMap<>(); + map.put("Date","2023-01-06"); + map.put("Type","3100"); + map.put("creditCard","信用卡"); + map.put("Restarant","123"); + map.put("Attendee","5"); + map.put("Amount","123"); + map.put("Currecy","CNY"); + map.put("Status","是"); + map.put("ActualAttend","0"); + map.put("isCheck","0"); + map.put("Reason","原因"); + map.put("Result","合格"); + map.put("Remark","230518 兰州市第一人民医院泌尿科室会"); + mtStyle("美团外卖",map,"D:\\1.png"); + + } + + @SneakyThrows + private static void style0() { + List headCells = new ArrayList<>(); + /// C TYPE + headCells.add(new Cell(1, 1, 100, 1).setTextAlign(true).setContent("第一列")); + headCells.add(new Cell(1, 2, 100, 1).setTextAlign(true).setContent("第二列")); + headCells.add(new Cell(1, 3, 100, 1).setTextAlign(true).setContent("第三列")); + headCells.add(new Cell(1, 4, 100, 1).setTextAlign(true).setContent("第四列")); + List> tableRowContents = new ArrayList<>(); + List a = Stream.of("山东", "泰安", "烟台", "青岛").collect(Collectors.toList()); + List b = Stream.of("台湾", "台北", "高雄", "桃园").collect(Collectors.toList()); + List c = Stream.of("广东", "广州", "佛山", "汕头").collect(Collectors.toList()); + tableRowContents.add(a); + tableRowContents.add(b); + tableRowContents.add(c); + int[] mergeColumns = new int[]{}; + String path = "D:\\0.png"; + Table table = new Table().setCellFont(new Font("宋体", Font.PLAIN, 10)) + .setHeadCells(headCells).setHeaderFont(new Font("宋体", Font.BOLD, 15)) + .setHeaderBackGroundColor(Color.gray) + .setMergeColumns(mergeColumns); + BufferedImage image = drawTable(table, tableRowContents); + ImageIO.write(image, "png", new File(path)); + } + + @SneakyThrows + private static void style1() { + List headCells = new ArrayList<>(); + /// C TYPE + headCells.add(new Cell(1, 1, 100, 0).setTextAlign(true).setContent("这是表头")); + headCells.add(new Cell(2, 1, 100, 1).setTextAlign(true).setContent("第一列")); + headCells.add(new Cell(2, 2, 100, 1).setTextAlign(true).setContent("第二列")); + headCells.add(new Cell(2, 3, 100, 1).setTextAlign(true).setContent("第三列")); + headCells.add(new Cell(2, 4, 100, 1).setTextAlign(true).setContent("第四列")); + List> tableRowContents = new ArrayList<>(); + List a = Stream.of("山东", "泰安", "烟台", "青岛").collect(Collectors.toList()); + List b = Stream.of("台湾", "台北", "高雄", "桃园").collect(Collectors.toList()); + List c = Stream.of("广东", "广州", "佛山", "汕头").collect(Collectors.toList()); + tableRowContents.add(a); + tableRowContents.add(b); + tableRowContents.add(c); + int[] mergeColumns = new int[]{1, 2}; + String path = "D:\\1.png"; + Table table = new Table().setCellFont(new Font("宋体", Font.PLAIN, 10)) + .setHeadCells(headCells).setHeaderFont(new Font("宋体", Font.BOLD, 15)) + .setHeaderBackGroundColor(Color.gray) + .setMergeColumns(mergeColumns); + BufferedImage image = drawTable(table, tableRowContents); + ImageIO.write(image, "png", new File(path)); + + } + @SneakyThrows + public static void mtStyle(String headName,Map tableVal,String imgPath) { + List headCells = new ArrayList<>(); + /// C TYPE + headCells.add(new Cell(1, 1, 150, 0).setTextAlign(true).setContent(headName)); + headCells.add(new Cell(2, 1, 150, 1).setTextAlign(true).setContent("Date")); + headCells.add(new Cell(2, 2, 150, 1).setTextAlign(true).setContent(tableVal.get("Date"))); + headCells.add(new Cell(2, 3, 150, 1).setTextAlign(true).setContent("Type")); + headCells.add(new Cell(2, 4, 150, 1).setTextAlign(true).setContent(tableVal.get("Type"))); + headCells.add(new Cell(2, 5, 150, 1).setTextAlign(true).setContent("CreditedCard")); + headCells.add(new Cell(2, 6, 150, 1).setTextAlign(true).setContent(tableVal.get("creditCard"))); + List> tableRowContents = new ArrayList<>(); + List a = Stream.of("Restarant", tableVal.get("Restarant"), "Attendee", tableVal.get("Attendee"), "Amount", tableVal.get("Amount")).collect(Collectors.toList()); + List b = Stream.of("Currency", tableVal.get("Currecy"), "Status", tableVal.get("Status"), "ActualAttend", tableVal.get("ActualAttend")).collect(Collectors.toList()); + List c = Stream.of("isCheck", tableVal.get("isCheck")+" ", "reason", tableVal.get("Reason"), "", "").collect(Collectors.toList()); + List d = Stream.of("Result", tableVal.get("Result"), "", "", "", "").collect(Collectors.toList()); + List e = Stream.of( "Remark", tableVal.get("Remark"), "", "","","").collect(Collectors.toList()); + //List c = Stream.of("广东", "广州", "佛山", "汕头").collect(Collectors.toList()); + tableRowContents.add(a); + tableRowContents.add(b); + tableRowContents.add(c); + tableRowContents.add(d); + tableRowContents.add(e); + int[] mergeColumns = new int[]{1, 2}; + Table table = new Table().setCellFont(new Font("宋体", Font.PLAIN, 15)) + .setHeadCells(headCells).setHeaderFont(new Font("宋体", Font.PLAIN, 15)) + .setHeaderBackGroundColor(Color.white) + .setMergeColumns(mergeColumns); + BufferedImage image = drawTableMt(table, tableRowContents); + ImageIO.write(image, "png", new File(imgPath)); + + } + + @SneakyThrows + private static void style2() { + List headCells = new ArrayList<>(); + /// C TYPE + headCells.add(new Cell(1, 1, 100, 0).setTextAlign(true).setContent("第一列")); + headCells.add(new Cell(1, 2, 100, 0).setTextAlign(true).setContent("第二列")); + headCells.add(new Cell(1, 3, 100, 0).setTextAlign(true).setContent("第三列")); + headCells.add(new Cell(2, 1, 100, 1).setTextAlign(true).setContent("第一列从属")); + headCells.add(new Cell(2, 2, 100, 1).setTextAlign(true).setContent("第一列从属")); + headCells.add(new Cell(2, 3, 100, 2).setTextAlign(true).setContent("第二列从属")); + headCells.add(new Cell(2, 4, 100, 2).setTextAlign(true).setContent("第二列从属")); + List> tableRowContents = new ArrayList<>(); + List a = Stream.of("山东", "泰安", "烟台", "青岛","济南").collect(Collectors.toList()); + List b = Stream.of("台湾", "台北", "高雄", "桃园","台中").collect(Collectors.toList()); + List c = Stream.of("广东", "广州", "佛山", "汕头","韶关").collect(Collectors.toList()); + tableRowContents.add(a); + tableRowContents.add(b); + tableRowContents.add(c); + int[] mergeColumns = new int[]{1, 2}; + String path = "D:\\2.png"; + Table table = new Table().setCellFont(new Font("宋体", Font.PLAIN, 10)) + .setHeadCells(headCells).setHeaderFont(new Font("宋体", Font.BOLD, 15)) + .setHeaderBackGroundColor(Color.gray) + .setMergeColumns(mergeColumns); + BufferedImage image = drawTable(table, tableRowContents); + ImageIO.write(image, "png", new File(path)); + } + + + @SneakyThrows + private static void style3() { + List headCells = new ArrayList<>(); + /// C TYPE + headCells.add(new Cell(1, 1, 100, 0).setTextAlign(true).setContent("第一列")); + headCells.add(new Cell(1, 2, 100, 0).setTextAlign(true).setContent("第二列")); + headCells.add(new Cell(1, 3, 100, 0).setTextAlign(true).setContent("第三列")); + headCells.add(new Cell(2, 2, 100, 2).setTextAlign(true).setContent("第二列\n从属")); + headCells.add(new Cell(2, 3, 100, 2).setTextAlign(true).setContent("第二列从属")); + headCells.add(new Cell(2, 4, 100, 2).setTextAlign(true).setContent("第二列从属")); + headCells.add(new Cell(3, 2, 100, 2).setTextAlign(true).setContent("第二列从属")); + headCells.add(new Cell(3, 3, 100, 2).setTextAlign(true).setContent("第二列从属")); + headCells.add(new Cell(3, 4, 100, 3).setTextAlign(true).setContent("第三列从属")); + List> tableRowContents = new ArrayList<>(); + List a = Stream.of("山东", "山东\n泰安市", "山东\n烟台市", "山东\n青岛市","山东\n济南市","山东\n东营市").collect(Collectors.toList()); + List b = Stream.of("台湾", "台湾\n台北市", "台湾\n高雄市", "台湾\n桃园市","台湾\n台中市","台湾\n新北市").collect(Collectors.toList()); + List c = Stream.of("广东", "广东\n广州市", "广东\n佛山市", "广东\n汕头市","广东\n韶关市","广东\n肇庆市").collect(Collectors.toList()); + tableRowContents.add(a); + tableRowContents.add(b); + tableRowContents.add(c); + int[] mergeColumns = new int[]{1, 2}; + String path = "D:\\3.png"; + Table table = new Table().setCellFont(new Font("宋体", Font.PLAIN, 12)) + .setHeadCells(headCells).setHeaderFont(new Font("宋体", Font.BOLD, 15)) + .setHeaderBackGroundColor(Color.gray) + .setMergeColumns(mergeColumns); + BufferedImage image = drawTable(table, tableRowContents); + ImageIO.write(image, "png", new File(path)); + } + + /** + * 绘制表格 + * + * @param table 表格属性 + * @param tableRowContents 表格内容 + */ + @SneakyThrows + public static BufferedImage drawTable(Table table, List> tableRowContents) { + checkHead(table); + List headCells = table.getHeadCells(); + int[] mergeColumns = table.getMergeColumns(); + Map> rows = headCells.stream().collect(Collectors.groupingBy(Cell::getRow)); + //表头的最后一行实际有多少个单元格,有合并单元格的情况下按垂直投影的方式获取列; + List actualLastHeadRowColumnCell = findHeadColumns(headCells); + HashMap headRealRowHead = getHeadRowHeight(rows, table); + HashMap contentRowHeight = getContentRowHeight(tableRowContents, table); + //处理表头 + dealTableHead(rows, table, actualLastHeadRowColumnCell, headCells, headRealRowHead); + // 生成表格各单元格内容对象 + List contents = getTableContent(tableRowContents, actualLastHeadRowColumnCell, rows.size(), contentRowHeight); + // 合并单元格 + //List cells = mergeCellsRow(contents, new int[]{5,6,7}); + List cells = mergeCells(contents, mergeColumns, headCells); + // 计算表格高度 + Integer tableHeight = Stream.of(headRealRowHead.values(), contentRowHeight.values()) + .flatMap(Collection::stream) + .reduce(Integer::sum) + .orElseThrow(() -> new RuntimeException("表格高度错误")); + // 绘制表格 + return starDrawTable(rows.size(), cells, table, tableHeight); + } + + /** + * 绘制表格 + * + * @param table 表格属性 + * @param tableRowContents 表格内容 + */ + @SneakyThrows + public static BufferedImage drawTableMt(Table table, List> tableRowContents) { + checkHead(table); + List headCells = table.getHeadCells(); + int[] mergeColumns = table.getMergeColumns(); + Map> rows = headCells.stream().collect(Collectors.groupingBy(Cell::getRow)); + //表头的最后一行实际有多少个单元格,有合并单元格的情况下按垂直投影的方式获取列; + List actualLastHeadRowColumnCell = findHeadColumns(headCells); + HashMap headRealRowHead = getHeadRowHeight(rows, table); + HashMap contentRowHeight = getContentRowHeight(tableRowContents, table); + //处理表头 + dealTableHead(rows, table, actualLastHeadRowColumnCell, headCells, headRealRowHead); + // 生成表格各单元格内容对象 + List contents = getTableContent(tableRowContents, actualLastHeadRowColumnCell, rows.size(), contentRowHeight); + // 合并单元格 + List cells = mergeCellsRow(contents, new int[]{5,6,7}); + cells = mergeCells(cells, mergeColumns, headCells); + // 计算表格高度 + Integer tableHeight = Stream.of(headRealRowHead.values(), contentRowHeight.values()) + .flatMap(Collection::stream) + .reduce(Integer::sum) + .orElseThrow(() -> new RuntimeException("表格高度错误")); + // 绘制表格 + return starDrawTable(rows.size(), cells, table, tableHeight); + } + + /** + * 表头格式校验 + * + * @param table 表头参数信息 + */ + public static void checkHead(Table table) { + if (Objects.isNull(table.getHeaderFont())) { + table.setHeaderFont(new Font("楷体", Font.BOLD, 15)); + } + if (Objects.isNull(table.getCellFont())) { + table.setHeaderFont(new Font("宋体", Font.PLAIN, 12)); + } + if (Objects.isNull(table.getHeaderBackGroundColor())) { + table.setHeaderBackGroundColor(Color.gray); + } + if (table.getRowHeight() <= 30) { + table.setRowHeight(30); + } + if (table.getMarginX() < 0 || table.getMarginY() < 0) { + throw new RuntimeException("表格边距不可小于0"); + } + table.getHeadCells().forEach(head -> { + if (head.getRow() <= 0) { + throw new RuntimeException("行不可小于0" + head.getRow() + "," + head.getColumn()); + } + if (head.getColumn() <= 0) { + throw new RuntimeException("列不可小于0" + head.getRow() + "," + head.getColumn()); + } + if (head.getBelongColumn() < 0) { + throw new RuntimeException("从属单元格列不可小于0" + head.getRow() + "," + head.getColumn()); + } + if (head.getWidth() < 0) { + throw new RuntimeException("列宽不可小于0" + head.getRow() + "," + head.getColumn()); + } + }); + checkBelongs(table.getHeadCells()); + ImmutableTriple, ArrayList, ArrayList> triple = + table.getHeadCells().stream().reduce(ImmutableTriple.of(new ArrayList<>(), new ArrayList<>(), new ArrayList<>()), + (a, b) -> { + a.getLeft().add(b.getRow()); + a.getMiddle().add(b.getColumn()); + a.getRight().add(b.getBelongColumn()); + return a; + }, (a, b) -> a); + checkConsistency(triple.getLeft()); + checkConsistency(triple.getMiddle()); + table.getHeadCells().stream().map(Cell::getBelongColumn).distinct() + .filter(column -> column > 0) + .filter(column -> !triple.getMiddle().contains(column)) + .findAny().ifPresent(a -> { + throw new RuntimeException("从属单元格" + a + "列不存在"); + }); + + } + + /** + * 表格连续性校验 + * + * @param data 行或列序列 + */ + private static void checkConsistency(ArrayList data) { + List collect = data.stream().distinct().sorted().collect(Collectors.toList()); + for (int i = 0; i < collect.size() - 1; i++) { + Integer integer = collect.get(i); + if (!collect.get(i + 1).equals(integer + 1)) { + throw new RuntimeException("行或者列不连续"); + } + } + } + + /** + * 从属单元格校验 + * + * @param headCells 表头 + */ + public static void checkBelongs(List headCells) { + Map> collect = headCells.stream().collect(Collectors.groupingBy(Cell::getRow)); + collect.forEach((key, value) -> { + List rowCells = value.stream().sorted(Comparator.comparing(Cell::getColumn)).collect(Collectors.toList()); + int belongColumn = 0; + for (Cell cell : rowCells) { + if (cell.getBelongColumn() >= belongColumn) { + belongColumn = cell.getBelongColumn(); + continue; + } + throw new RuntimeException("从属单元格配置错误" + cell.getRow() + "," + cell.getColumn()); + } + }); + } + + /** + * 处理表头 + * + * @param rows 表头行内容 + * @param table 行高 + * @param actualLastHeadRowColumnCell 表头单元格 + * @param headCells 表头单元格 + */ + public static void dealTableHead(Map> rows, Table table, List actualLastHeadRowColumnCell, List headCells, + HashMap headRealRowHead) { + int marginX = table.getMarginX(); + int marginY = table.getMarginY(); + rows.keySet().stream().sorted().forEach(row -> { + List perRowCells = rows.get(row).stream().sorted(Comparator.comparing(Cell::getColumn)).collect(Collectors.toList()); + int startFrom = marginX; + // 非第一行的情况,有可能起始列不是第一列,这里需要取前几列的宽度作为起始宽度 + if (row > 1 && perRowCells.get(0).getColumn() > 1) { + int column = perRowCells.get(0).getColumn(); + int offset = IntStream.range(1, column).map(index -> actualLastHeadRowColumnCell.get(index - 1).getWidth()).sum(); + startFrom = marginX + offset; + } + for (Cell cell : perRowCells) { + // 获取从属单元格,单元格的宽度由从属单元格确定 + List attached = getCellSonCells(headCells, cell); + int cellWidth = attached.stream().mapToInt(Cell::getWidth).sum(); + cell.setHeight(headRealRowHead.get(row)); + // 如果该单元格有从属,则高度为行高,反之为单元格所跨行数*行高 + // attached + // 长度为1:当不是自己时才说明该单元格是他的从属 + // 长度大于1:有从属 + if (attached.size() == 1 && attached.get(0).equals(cell)) { + int sum = IntStream.rangeClosed(cell.getRow(), rows.size()).map(headRealRowHead::get).sum(); + cell.setHeight(sum); + } + if (cellWidth <= 0) { + throw new RuntimeException("行:" + cell.getRow() + " 列:" + cell.getColumn() + "宽度必须大于0"); + } + cell.setWidth(cellWidth); + cell.setX(startFrom); + startFrom += cellWidth; + int sum = IntStream.rangeClosed(1, row - 1).map(headRealRowHead::get).sum(); + cell.setY(sum + marginY); + } + }); + } + + /** + * 计算表头行高 + * + * @param rows 表头行 + * @param table 表属性 + * @return 表头行与行高的对应 key:行 value:行高 + */ + private static HashMap getHeadRowHeight(Map> rows, Table table) { + return rows.keySet().stream().map(row1 -> { + Integer cellRow = rows.get(row1).stream().map(cell -> StringUtils.countMatches(cell.getContent(), "\n")).max(Integer::compare).orElse(1); + int appendHeight = cellRow * table.getHeaderFont().getSize(); + return Pair.of(row1, table.getRowHeight() + appendHeight); + }).reduce(new HashMap<>(16), (a, b) -> { + a.put(b.getLeft(), b.getRight()); + return a; + }, (c, d) -> c); + } + + /** + * 生成表格各单元格内容对象 + * + * @param tableRowContents 表格内容 + * @param actualLastHeadRowColumnCell 表头单元格 + * @param headRowSize 表头行数 + * @param contentRowHeight 各行的行高关系 + * @return 表格各单元格内容对象 + */ + public static List getTableContent(List> tableRowContents, List actualLastHeadRowColumnCell, + int headRowSize, HashMap contentRowHeight) { + List contents = new ArrayList<>(); + for (int i = 0; i < tableRowContents.size(); i++) { + List rowContent = tableRowContents.get(i); + for (int j = 0; j < rowContent.size(); j++) { + String cellContent = rowContent.get(j); + Cell cell = new Cell(); + Cell lastHeadColumnCell = actualLastHeadRowColumnCell.get(j); + cell.setRow(i + 1 + headRowSize); + cell.setColumn(lastHeadColumnCell.getColumn()); + cell.setX(lastHeadColumnCell.getX()); + // 单元格纵坐标 + int sum = IntStream.rangeClosed(1, i).map(contentRowHeight::get).sum(); + int y = (lastHeadColumnCell.getY() + lastHeadColumnCell.getHeight()) + sum; + cell.setY(y); + cell.setWidth(lastHeadColumnCell.getWidth()); + cell.setTextAlign(true); + cell.setHeight(contentRowHeight.get(i + 1)); + cell.setContent(cellContent); + contents.add(cell); + } + } + return contents; + } + + /** + * 计算单元格高度 + * + * @param tableRowContents 表格内容 + * @param table 表格属性 + * @return 行与行高对应关系 key:行 value:行高 + */ + private static HashMap getContentRowHeight(List> tableRowContents, Table table) { + return IntStream.rangeClosed(1, tableRowContents.size()) + .mapToObj(row -> dealRowHeight(tableRowContents, table, row)) + .reduce(new HashMap<>(16), (a, b) -> { + a.put(b.getLeft(), b.getRight()); + return a; + }, (c, d) -> c); + } + + /** + * 计算单元格高度主方法 + * + * @param tableRowContents 表格内容 + * @param table 表格属性 + * @param row 行内容 + * @return 行与行高的对应关系 key:行 value:行高 + */ + private static Pair dealRowHeight(List> tableRowContents, Table table, int row) { + Integer cellRows = tableRowContents.get(row - 1).stream() + .map(content -> StringUtils.countMatches(content, "\n")).max(Integer::compare).orElse(1); + int appendHeight = table.getCellFont().getSize() * cellRows; + return Pair.of(row, table.getRowHeight() + appendHeight); + } + + /** + * 绘制表格 + * + * @param tableCells 表格所有单元格 + * @param table 表格属性 + */ + public static BufferedImage starDrawTable(int headRow, List tableCells, Table table, int tableHeight) throws IOException { + int marginY = table.getMarginY(); + int marginX = table.getMarginX(); + Map> allTableRows = tableCells.stream().collect(Collectors.groupingBy(Cell::getRow)); + int allRows = allTableRows.size(); + // 画布高度 + int imageHeight = tableHeight + marginY * 2; + // 画布宽度 + int tableWidth = tableCells.stream().filter(cell -> cell.getRow() == 1).mapToInt(Cell::getWidth).sum(); + int imageWidth = tableWidth + marginX * 2; + BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = image.createGraphics(); + graphics.setColor(Color.white); + // 默认白色背景 + graphics.fillRect(0, 0, imageWidth, imageHeight); + IntStream.rangeClosed(1, allRows + 1).forEach(i -> + { + //表格最后一行画横线 + if (i == allRows + 1) { + graphics.setColor(Color.black); + // 获取第一行的所有单元格 + List rowCells = allTableRows.get(1); + for (Cell cell : rowCells) { + graphics.drawLine(cell.getX(), tableHeight + marginY, cell.getX() + cell.getWidth(), tableHeight + marginY); + } + return; + } + List perRowCells = allTableRows.get(i); + if (i <= headRow) { + for (int h = 0; h < perRowCells.size(); h++) { + Cell cell = perRowCells.get(h); + //表头单元格填充背景色 + graphics.setColor(table.getHeaderBackGroundColor()); + graphics.fillRect(cell.getX(), cell.getY(), cell.getWidth(), cell.getHeight()); + // 当前单元格是否为本行最后一个 + boolean lastCellInRow = h == perRowCells.size() - 1; + coreMethod(graphics, table.getHeaderFont(), lastCellInRow, cell); + } + return; + } + for (int j = 0; j < perRowCells.size(); j++) { + Cell cell = perRowCells.get(j); + // 当前单元格是否为本行最后一个 + boolean lastCellInRow = j == perRowCells.size() - 1; + coreMethod(graphics, table.getCellFont(), lastCellInRow, cell); + } + }); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); + graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + Stroke basicStroke = new BasicStroke(imageWidth); + graphics.setStroke(basicStroke); + graphics.drawImage(image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH), 0, 0, null); + graphics.dispose(); + return image; + } + + /** + * 绘制核心方法 + * + * @param graphics 绘制类 + * @param font 字体信息 + * @param lastCellInRow 是否为行内最后一个单元格 + * @param cell 要绘制的单元格 + */ + private static void coreMethod(Graphics2D graphics, Font font, boolean lastCellInRow, Cell cell) { + graphics.setColor(Color.black); + //每个单元格左起横线 + graphics.drawLine(cell.getX(), cell.getY(), cell.getX() + cell.getWidth(), cell.getY()); + //每个单元格左起竖线 + graphics.drawLine(cell.getX(), cell.getY(), cell.getX(), cell.getY() + cell.getHeight()); + //单元格内容 + // 如果是水平居中,根据“字体”计算出实际起始坐标位置 + graphics.setFont(font); + String content = StringUtils.defaultIfBlank(cell.getContent(), "-"); + String[] split = StringUtils.split(content, "\n"); + for (int i = 0; i < split.length; i++) { + //1.计算单元格内容的横坐标,加1是为了防止文字紧贴在单元格上 + int contentX = cell.getX() + 1; + String cellRowContent = split[i]; + if (cell.isTextAlign()) { + // 初始执行比较耗时 + FontMetrics fontMetrics = graphics.getFontMetrics(); + int contentLen = fontMetrics.stringWidth(cellRowContent); + contentX += (cell.getWidth() - contentLen) / 2; + } + // 2. 计算单元格纵坐标,默认居中(!!!注意:内容是从下向上从左向右渲染,所在在单元格的基础上又加了字体font.getSize()) + int startY = cell.getY() + font.getSize(); + // 单元格内第一行文字的纵坐标 + int cellFirstRowPosition = (cell.getHeight() - font.getSize() * (split.length)) / 2; + // 偏移量(在行一行文字纵坐标的基础上进行累加),加1是为了防止每行文字粘在一起。 + int offset = (font.getSize() + 1) * i; + int contentY = startY + cellFirstRowPosition + offset; + // 3. 写入单元格内容 + graphics.drawString(cellRowContent, contentX, contentY); + } + //每行最后一个单元格的竖线 + if (lastCellInRow) { + // 单元格最右的横坐标 + int cellRightX = cell.getX() + cell.getWidth(); + graphics.drawLine(cellRightX, cell.getY(), cellRightX, cell.getY() + cell.getHeight()); + } + + } + + /** + * 按列合并单元格 + * + * @param contents 单元格内容 + * @param mergeColumns 要合并的列 + * @param headCells 表头单元格 + */ + public static List mergeCells(List contents, int[] mergeColumns, List headCells) { + if (ArrayUtils.isEmpty(mergeColumns)) { + contents.addAll(headCells); + return contents; + } + if (CollectionUtils.isEmpty(contents)) { + contents.addAll(headCells); + return contents; + } + Map> collect = contents.stream().collect(Collectors.groupingBy(Cell::getColumn)); + Map> collectRow = contents.stream().collect(Collectors.groupingBy(Cell::getRow)); + List cellsrow = collect.get(6).stream().sorted(Comparator.comparing(Cell::getRow)) + .collect(Collectors.toList()); + List toDel = new ArrayList<>(); + for (int mergeColumn : mergeColumns) { + List cells = collect.get(mergeColumn).stream().sorted(Comparator.comparing(Cell::getRow)) + .collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(cells)) { + for (int j = 0; j < cells.size() - 1; j++) { + Cell cell = cells.get(j); + for (int k = j + 1; k < cells.size(); k++) { + Cell cellToCompare = cells.get(k); + if (!StringUtils.equals(cell.getContent(), cellToCompare.getContent())) { + break; + } + cell.setHeight(cell.getHeight() + cellToCompare.getHeight()); + toDel.add(cellToCompare); + } + } + } + } + ArrayList cells = new ArrayList<>(CollectionUtils.subtract(contents, toDel)); + cells.addAll(headCells); + return cells; + } + + /** + * 按行合并单元格 + * + * @param contents 单元格内容 + * @param mergeColumns 要合并的列 + */ + public static List mergeCellsRow(List contents, int[] mergeColumns) { + + Map> collect = contents.stream().collect(Collectors.groupingBy(Cell::getRow)); + List toDel = new ArrayList<>(); + for (int mergeColumn : mergeColumns) { + int num = 1; + if(mergeColumn == 5) num=3; + List cells = collect.get(mergeColumn).stream().sorted(Comparator.comparing(Cell::getRow)) + .collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(cells)) { + for (int j = num; j < cells.size() - 1; j++) { + Cell cell = cells.get(j); + for (int k = j + 1; k < cells.size(); k++) { + Cell cellToCompare = cells.get(k); + /*if (!StringUtils.equals(cell.getContent(), cellToCompare.getContent())) { + break; + }*/ + cell.setWidth(cell.getWidth() + cellToCompare.getWidth()); + toDel.add(cellToCompare); + } + } + } + } + ArrayList cells = new ArrayList<>(CollectionUtils.subtract(contents, toDel)); + + return cells; + } + + /** + * 获取表头最后一行的所有单元格 + * + * @param cells 表头所有的单元格 + */ + public static List findHeadColumns(List cells) { + Map> rows = cells.stream().collect(Collectors.groupingBy(Cell::getRow)); + //取第一行的所有单元格 + List firstRow = rows.get(1); + if (CollectionUtils.isEmpty(firstRow)) { + throw new RuntimeException("缺少第一行"); + } + // 按列升序排序 + List perRowCells = firstRow.stream().sorted(Comparator.comparing(Cell::getColumn)).collect(Collectors.toList()); + List headColumns = new ArrayList<>(); + for (Cell cell : perRowCells) { + // 获取每个单元格下的所有从属单元格,如果没有则返回其本身 + headColumns.addAll(getCellSonCells(cells, cell)); + } + return headColumns; + } + + /** + * 获取所有的从属单元格 + * + * @param cells 所有表头单元格 + * @param cell 要获取从属的单元格 + * @return 该单元格下的从属单元格 + */ + public static List getCellSonCells(List cells, Cell cell) { + // 从属单元格:该单元格所在列中的所有单元格 + List collect = cells.stream() + .filter(cel -> cel.getRow() == cell.getRow() + 1) + .filter(cel -> cel.getBelongColumn() == cell.getColumn()) + .collect(Collectors.toList()); + // 没有从属单元格则返回本身 + if (CollectionUtils.isEmpty(collect)) { + ArrayList objects = new ArrayList<>(); + objects.add(cell); + return objects; + } + //有从属单元格则遍历每一个单元格来获取每个单元格下的从属单元格 + List> allSonCells = collect.stream().map(s -> getCellSonCells(cells, s)).collect(Collectors.toList()); + return allSonCells.stream().flatMap(Collection::stream).collect(Collectors.toList()); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/FileImgUtil.java b/src/main/java/com/cmsen/ticket/domain/util/FileImgUtil.java new file mode 100644 index 0000000..b6e05a6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/FileImgUtil.java @@ -0,0 +1,978 @@ +package com.cmsen.ticket.domain.util; + +import com.alibaba.simpleimage.ImageRender; +import com.alibaba.simpleimage.SimpleImageException; +import com.alibaba.simpleimage.render.ReadRender; +import com.alibaba.simpleimage.render.ScaleParameter; +import com.alibaba.simpleimage.render.ScaleRender; +import com.alibaba.simpleimage.render.WriteRender; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.itextpdf.text.BadElementException; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.pdf.PdfWriter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.font.FontRenderContext; +import java.awt.font.TextLayout; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.io.*; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 文件图片工具类 + */ +@Slf4j +public class FileImgUtil { + + //所有的最大不能超过10M + static final long ALL_MAX = 10 * 1024 * 1024; + //每个图片最大不能超过1M + static final long FILE_MAX = 1 * 1024 * 1024; + + //每个图片最大不能超过500K + static final long FILE_MAX2 = 1 * 1024 * 500; + + private static int PAGE_MAX_HEIGHT = 14400; + private static int DECIMAL_POINT_NUM = 2; + private static int ONE_HUNDRED = 100; + + /** + * 压缩图片 + * @param filesPath + * @param filePath + */ + public static void compressFiles(List filesPath, String filePath){ + + //计算文件的大小 + long fileMax = ALL_MAX / filesPath.size(); + if(fileMax > FILE_MAX){ + fileMax = FILE_MAX; + } + + for (String path : filesPath) { + log.info("compressFiles===path=={}",path); + /*String[] split = path.split("\\/"); + int len = split.length; + String folder = split[len-2]; + String newFileName = split[len-1]; + + String imgFilePath = filePath + File.separator + folder + File.separator + newFileName; + */ + String imgFilePath = filePath + path.substring(path.indexOf("img")+3); + log.info("compressFiles===imgFilePath=={}",imgFilePath); + + File file = new File(imgFilePath); + long maxSize = fileMax; + long fileSize = file.length(); + log.info("compressFiles===maxSize={}=fileSize={}",maxSize,fileSize); + if(fileSize > maxSize){//文件大小 > 最大值,则进行图片压缩 + // 压缩文件 + compressUnderSize(file, maxSize, imgFilePath); + } + } + + } + + public static void compressFile(String filePath){ + + log.info("compressFile===path=={}",filePath); + File file = new File(filePath); + long maxSize = FILE_MAX; + long fileSize = file.length(); + log.info("compressFile===maxSize={}=fileSize={}",maxSize,fileSize); + if(fileSize > maxSize){//文件大小 > 最大值,则进行图片压缩 + // 压缩文件 + compressUnderSize(file, maxSize, filePath); + } + } + + public static void compressFile2(String filePath){ + + log.info("compressFile2===path=={}",filePath); + File file = new File(filePath); + long maxSize = FILE_MAX2; + long fileSize = file.length(); + log.info("compressFile2===maxSize={}=fileSize={}",maxSize,fileSize); + if(fileSize > maxSize){//文件大小 > 最大值,则进行图片压缩 + // 压缩文件 + compressUnderSize(file, maxSize, filePath); + } + } + + public static void compressUnderSize(File imageFile, long maxSize, String imgFilePath){ + try { + byte[] data = getByteByPic(imageFile); + byte[] imgData = Arrays.copyOf(data, data.length); + do { + try { + imgData = compress(imgData, 0.9); + } catch (Exception e) { + throw new IllegalStateException("压缩图片过程中出错,请及时联系管理员!", e); + } + } while (imgData.length > maxSize); + byteToImage(imgData, imgFilePath); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static byte[] getByteByPic(File imageFile){ + try { + InputStream inStream = new FileInputStream(imageFile); + BufferedInputStream bis = new BufferedInputStream(inStream); + BufferedImage bm = ImageIO.read(bis); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + String imageUrl = imageFile.getAbsolutePath(); + String type = imageUrl.substring(imageUrl.length() - 3); + ImageIO.write(bm, type, bos); + bos.flush(); + byte[] data = bos.toByteArray(); + return data; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static byte[] compress(byte[] srcImgData, double scale){ + try { + BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData)); + int width = (int) (bi.getWidth() * scale); // 源图宽度 + int height = (int) (bi.getHeight() * scale); // 源图高度 + Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); + BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + g.setColor(Color.RED); + g.drawImage(image, 0, 0, null); // 绘制处理后的图 + g.dispose(); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ImageIO.write(tag, "JPEG", bOut); + return bOut.toByteArray(); + + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static void byteToImage(byte[] data, String imgFilePath) { + if (data.length < 3) + return; + try { + FileOutputStream imageOutput = new FileOutputStream(imgFilePath); + imageOutput.write(data, 0, data.length); + imageOutput.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + /** + * 多张图片合成一张图片 jpg + * @param imgs + * @param type + * @param mergePic + * @return + */ + public static boolean merge(String[] imgs, String type, String mergePic) { + int dstHeight = 0; + int dstWidth = 0; + // 获取需要拼接的图片长度 + int len = imgs.length; + // 判断长度是否大于0 + if (len < 1) { + return false; + } + File[] file = new File[len]; + BufferedImage[] images = new BufferedImage[len]; + int[][] ImageArrays = new int[len][]; + for (int i = 0; i < len; i++) { + try { + file[i] = new File(imgs[i]); + images[i] = ImageIO.read(file[i]); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + + int width = images[i].getWidth(); + int height = images[i].getHeight(); + + // 从图片中读取RGB 像素 + ImageArrays[i] = new int[width * height]; + ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width); + + // 计算合并的宽度和高度 + dstWidth = dstWidth > width ? dstWidth : width; + dstHeight += height; + } + + // 合成图片像素 + System.out.println("宽度:" + dstWidth); + System.out.println("高度:" + dstHeight); + + if (dstHeight < 1) { + System.out.println("dstHeight < 1"); + return false; + } + // 生成新图片 + try { + BufferedImage imageNew = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_RGB); + int width_i = 0; + int height_i = 0; + for (int i = 0; i < images.length; i++) { + int width = images[i].getWidth(); + int height = images[i].getHeight(); + imageNew.setRGB(0, height_i, width, height, ImageArrays[i], 0, width); + height_i += height; + } + + File outFile = new File(mergePic); + // 写图片,输出到硬盘 + ImageIO.write(imageNew, type, outFile); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 添加水印 + * @param filePath + * @param waterMarkContent + */ + public static void addWatermark(String filePath, String waterMarkContent, String outFilePath, SysConfig config){ + System.out.println("添加水印 Start"); + try{ + File srcImgFile = new File(filePath); + //将文件对象转化为图片对象 + Image srcImg = ImageIO.read(srcImgFile); + //获取图片的宽 + int srcImgWidth = srcImg.getWidth(null); + //获取图片的高 + int srcImgHeight = srcImg.getHeight(null); + System.out.println("图片的宽:"+srcImgWidth); + System.out.println("图片的高:"+srcImgHeight); + + BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB); + // 加水印 + //创建画笔 + Graphics2D g = bufImg.createGraphics(); + //srcImg 为上面获取到的原始图片的图片对象 + g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); + //根据图片的背景设置水印颜色 + int c_r = 255; + int c_g = 255; + int c_b = 255; + if(config != null && !config.getValue().isEmpty()){ + String[] arr = config.getValue().split(","); + c_r = Integer.parseInt(arr[0]); + c_g = Integer.parseInt(arr[1]); + c_b = Integer.parseInt(arr[2]); + } + System.out.println("添加水印 字体颜色"+c_r+"="+c_g+"="+c_b); + g.setColor(new Color(c_r,c_g,c_b,128)); + //设置字体 画笔字体样式为微软雅黑,加粗,文字大小为60pt + int fontSize = 53; + if(waterMarkContent.length() > 40){ + fontSize = 43; + } + g.setFont(new Font("SimHei", Font.ITALIC, fontSize)); + //设置旋转角度 + g.rotate(Math.toRadians(0f), + (double) srcImgWidth / 2, (double) srcImgHeight / 2); + //设置水印的坐标 + int x=(srcImgWidth - getWatermarkLength(waterMarkContent, g)) / 2; + int y=srcImgHeight / 2; + //画出水印 第一个参数是水印内容,第二个参数是x轴坐标,第三个参数是y轴坐标 + g.drawString(waterMarkContent, x, y); + g.dispose(); + + //待存储的地址 + String tarImgPath = outFilePath; + // 输出图片 + FileOutputStream outImgStream = new FileOutputStream(tarImgPath); + ImageIO.write(bufImg, "jpg", outImgStream); + System.out.println("添加水印完成"); + outImgStream.flush(); + outImgStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 获取水印文字的长度 + * @param waterMarkContent + * @param g + * @return + */ + public static int getWatermarkLength(String waterMarkContent, Graphics2D g) { + return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length()); + } + + + /** + * + * @param imgLs + * 图片地址 + * @param pdfPath + * PDF文件保存地址 + * + */ + public static void toPdf(List imgLs, String filePath, String pdfPath, List filesType, String correctFlag) { + try { + // PDF文件保存地址 + // String pdfPath = "D:/Demo/ceshi/hebing.pdf"; + // 输入流 + FileOutputStream fos = new FileOutputStream(pdfPath); + // 创建文档 + Document doc = new Document(null, 0, 0, 0, 0); + //doc.open(); + // 写入PDF文档 + PdfWriter.getInstance(doc, fos); + // 读取图片流 + BufferedImage img = null; + // 实例化图片 + com.itextpdf.text.Image image = null; + int imgWidth=0; + int imgHeight=0; + int i=0; + // 循环获取图片文件夹内的图片 + java.util.List tmpFiles = new ArrayList(); + for(int m=0; m{},correctFlag==>{}",filesType.get(m),correctFlag); + if(filesType.get(m).equals("Y") && correctFlag.equals("1")){ + log.info("toPdf===修正颜色=======开始"); + // 重新保存图片修正色彩 + String tmp=imgFilePath.substring(imgFilePath.lastIndexOf(".")); + String nImagePath = imgFilePath.replaceAll(tmp,"2A"+tmp); + compressPicAlibaba(imgFilePath,nImagePath); + tmpFiles.add(nImagePath); + // 实例化图片 + image = com.itextpdf.text.Image.getInstance(nImagePath); + log.info("toPdf===修正颜色=======结束"); + }else{ + image = com.itextpdf.text.Image.getInstance(imgFilePath); + log.info("toPdf===不修正颜色======="); + } + + // 添加图片到文档 + if(i==0) { + // 根据图片大小设置文档大小---原来的设置 + //doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight())); + + //获取图片高度 + float scaledHeight = image.getScaledHeight(); + //判断图片高度是否大于最高高度14400 + if (scaledHeight > PAGE_MAX_HEIGHT){ + log.info("toPdf===1===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new com.itextpdf.text.Rectangle(imageWidth, imageHeight)); + doc.open(); + doc.add(image); + i++; + }else{ + //获取图片高度 + float scaledHeight = image.getScaledHeight(); + //判断图片高度是否大于最高高度14400 + if (scaledHeight > PAGE_MAX_HEIGHT){ + log.info("toPdf===2===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new com.itextpdf.text.Rectangle(imageWidth, imageHeight)); + doc.newPage(); + + doc.add(image); + // 根据图片大小设置文档大小---原来的设置 + //doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight())); + } + } + // 关闭文档 + doc.close(); + for(String tmpName:tmpFiles){ + // 删除生成的图片 + (new File(tmpName)).delete(); + } + + log.info("toPdf===OK======="); + } catch (IOException e) { + e.printStackTrace(); + } catch (BadElementException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + } + + + public static void toPdf2(List imgLs, String filePath, String pdfPath) { + try { + // PDF文件保存地址 + // String pdfPath = "D:/Demo/ceshi/hebing.pdf"; + // 输入流 + FileOutputStream fos = new FileOutputStream(pdfPath); + // 创建文档 + Document doc = new Document(null, 0, 0, 0, 0); + //doc.open(); + // 写入PDF文档 + PdfWriter.getInstance(doc, fos); + // 读取图片流 + BufferedImage img = null; + // 实例化图片 + com.itextpdf.text.Image image = null; + int imgWidth=0; + int imgHeight=0; + int i=0; + // 循环获取图片文件夹内的图片 + java.util.List tmpFiles = new ArrayList(); + for(int m=0; m PAGE_MAX_HEIGHT){ + log.info("toPdf===1===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new com.itextpdf.text.Rectangle(imageWidth, imageHeight)); + doc.open(); + doc.add(image); + i++; + }else{ + //获取图片高度 + float scaledHeight = image.getScaledHeight(); + //判断图片高度是否大于最高高度14400 + if (scaledHeight > PAGE_MAX_HEIGHT){ + log.info("toPdf===2===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new com.itextpdf.text.Rectangle(imageWidth, imageHeight)); + doc.newPage(); + + doc.add(image); + // 根据图片大小设置文档大小---原来的设置 + //doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight())); + } + } + // 关闭文档 + doc.close(); + for(String tmpName:tmpFiles){ + // 删除生成的图片 + (new File(tmpName)).delete(); + } + + log.info("toPdf===OK======="); + } catch (IOException e) { + e.printStackTrace(); + } catch (BadElementException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + } + + + /** + * 重新保存图片修正红色图片问题 + * @param srcFilePath + * @param descFilePath + */ + public static void compressPicAlibaba (String srcFilePath, String descFilePath) { + File in = new File(srcFilePath); //原图片 + File out = new File(descFilePath); //目的图片 + ScaleParameter scaleParam = new ScaleParameter(); + + FileInputStream inStream = null; + FileOutputStream outStream = null; + WriteRender wr = null; + boolean error = false; + try { + inStream = new FileInputStream(in); + outStream = new FileOutputStream(out); + ImageRender rr = new ReadRender(inStream); + ImageRender sr = new ScaleRender(rr, scaleParam); + wr = new WriteRender(sr, outStream); + + wr.render(); //触发图像处理 + } catch(Exception e) { + e.printStackTrace(); + error =true; + } finally { + IOUtils.closeQuietly(inStream); //图片文件输入输出流必须记得关闭 + IOUtils.closeQuietly(outStream); + if (wr != null) { + try { + wr.dispose(); //释放simpleImage的内部资源 + } catch (SimpleImageException ignore) { + // skip ... + } + } + // 如果不能转换则不转换,直接复制 + if(error){ + copyFileCover(srcFilePath,descFilePath,true); + } + } + } + /** + * 复制单个文件 + * @param srcFileName 待复制的文件名 + * @param descFileName 目标文件名 + * @param coverlay 如果目标文件已存在,是否覆盖 + * @return 如果复制成功,则返回true,否则返回false + */ + public static boolean copyFileCover(String srcFileName, + String descFileName, boolean coverlay) { + File srcFile = new File(srcFileName); + // 判断源文件是否存在 + if (!srcFile.exists()) { + log.debug("复制文件失败,源文件 " + srcFileName + " 不存在!"); + return false; + } + // 判断源文件是否是合法的文件 + else if (!srcFile.isFile()) { + log.debug("复制文件失败," + srcFileName + " 不是一个文件!"); + return false; + } + File descFile = new File(descFileName); + // 判断目标文件是否存在 + if (descFile.exists()) { + // 如果目标文件存在,并且允许覆盖 + if (coverlay) { + log.debug("目标文件已存在,准备删除!"); + if (!FileImgUtil.delFile(descFileName)) { + log.debug("删除目标文件 " + descFileName + " 失败!"); + return false; + } + } else { + log.debug("复制文件失败,目标文件 " + descFileName + " 已存在!"); + return false; + } + } else { + if (!descFile.getParentFile().exists()) { + // 如果目标文件所在的目录不存在,则创建目录 + log.debug("目标文件所在的目录不存在,创建目录!"); + // 创建目标文件所在的目录 + if (!descFile.getParentFile().mkdirs()) { + log.debug("创建目标文件所在的目录失败!"); + return false; + } + } + } + + // 准备复制文件 + // 读取的位数 + int readByte = 0; + InputStream ins = null; + OutputStream outs = null; + try { + // 打开源文件 + ins = new FileInputStream(srcFile); + // 打开目标文件的输出流 + outs = new FileOutputStream(descFile); + byte[] buf = new byte[1024]; + // 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕 + while ((readByte = ins.read(buf)) != -1) { + // 将读取的字节流写入到输出流 + outs.write(buf, 0, readByte); + } + log.debug("复制单个文件 " + srcFileName + " 到" + descFileName + + "成功!"); + return true; + } catch (Exception e) { + log.debug("复制文件失败:" + e.getMessage()); + return false; + } finally { + // 关闭输入输出流,首先关闭输出流,然后再关闭输入流 + if (outs != null) { + try { + outs.close(); + } catch (IOException oute) { + oute.printStackTrace(); + } + } + if (ins != null) { + try { + ins.close(); + } catch (IOException ine) { + ine.printStackTrace(); + } + } + } + } + /** + * + * 删除文件,可以删除单个文件或文件夹 + * + * @param fileName 被删除的文件名 + * @return 如果删除成功,则返回true,否是返回false + */ + public static boolean delFile(String fileName) { + File file = new File(fileName); + if (!file.exists()) { + log.debug(fileName + " 文件不存在!"); + return true; + } else { + if (file.isFile()) { + return FileImgUtil.deleteFile(fileName); + } else { + return FileImgUtil.deleteDirectory(fileName); + } + } + } + /** + * + * 删除单个文件 + * + * @param fileName 被删除的文件名 + * @return 如果删除成功,则返回true,否则返回false + */ + public static boolean deleteFile(String fileName) { + File file = new File(fileName); + if (file.exists() && file.isFile()) { + if (file.delete()) { + log.debug("删除文件 " + fileName + " 成功!"); + return true; + } else { + log.debug("删除文件 " + fileName + " 失败!"); + return false; + } + } else { + log.debug(fileName + " 文件不存在!"); + return true; + } + } + + /** + * + * 删除目录及目录下的文件 + * + * @param dirName 被删除的目录所在的文件路径 + * @return 如果目录删除成功,则返回true,否则返回false + */ + public static boolean deleteDirectory(String dirName) { + String dirNames = dirName; + if (!dirNames.endsWith(File.separator)) { + dirNames = dirNames + File.separator; + } + File dirFile = new File(dirNames); + if (!dirFile.exists() || !dirFile.isDirectory()) { + log.debug(dirNames + " 目录不存在!"); + return true; + } + boolean flag = true; + // 列出全部文件及子目录 + File[] files = dirFile.listFiles(); + for (int i = 0; i < files.length; i++) { + // 删除子文件 + if (files[i].isFile()) { + flag = FileImgUtil.deleteFile(files[i].getAbsolutePath()); + // 如果删除文件失败,则退出循环 + if (!flag) { + break; + } + } + // 删除子目录 + else if (files[i].isDirectory()) { + flag = FileImgUtil.deleteDirectory(files[i] + .getAbsolutePath()); + // 如果删除子目录失败,则退出循环 + if (!flag) { + break; + } + } + } + + if (!flag) { + log.debug("删除目录失败!"); + return false; + } + // 删除当前目录 + if (dirFile.delete()) { + log.debug("删除目录 " + dirName + " 成功!"); + return true; + } else { + log.debug("删除目录 " + dirName + " 失败!"); + return false; + } + + } + + /** + * 文字生成图片 + * @param text + * @param imgPath + */ + public static void textToImage(String text,String imgPath) { + // 图像宽度 + int imageWidth = 1000; + // 图像高度 + int imageHeight = 600; + + BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); + Graphics2D g2d = image.createGraphics(); + + // 设置背景为白色 + g2d.setColor(Color.WHITE); + g2d.fillRect(0, 0, imageWidth, imageHeight); + + // 自定义字体 + Font font =new Font("宋体", Font.ITALIC, 18); + + g2d.setFont(font); + + // 最大文本行宽度 + int maxLineWidth = imageWidth - 100; + // 单行文本高度 + int lineHeight = 30; + + FontRenderContext frc = g2d.getFontRenderContext(); + TextLayout textLayout = new TextLayout(text, font, frc); + Rectangle2D bounds = textLayout.getBounds(); + + // 居左显示 + float x = 50; + // 居中显示,并考虑上方间距 + float y = (float) (imageHeight - bounds.getHeight()) * 0.4f + textLayout.getAscent(); + + // 将文本按空格分割为单词 + String[] words = text.split(""); + StringBuilder line = new StringBuilder(); + + // 设置文字颜色为红色 + g2d.setColor(Color.RED); + + for (String word : words) { + if (line.length() == 0) { + line.append(word); + } else { + String tempLine = line.toString() + word; + TextLayout tempLayout = new TextLayout(tempLine, font, frc); + if (tempLayout.getBounds().getWidth() <= maxLineWidth) { + line.append(word); + } else { + g2d.drawString(line.toString(), x, y); + line.setLength(0); + line.append(word); + y += lineHeight; + } + } + } + + // 绘制最后一行文本 + g2d.drawString(line.toString(), x, y); + + g2d.dispose(); + + // 将 BufferedImage 转换为 InputStream + //ByteArrayOutputStream out = new ByteArrayOutputStream(); + + try { + ImageIO.write(image, "png", new File(imgPath)); + //out.flush(); + //byte[] imageBytes = out.toByteArray(); + //out.close(); + log.info("图片生成成功!"); + + } catch (Exception e) { + e.printStackTrace(); + log.error("图片生成失败!"); + + } + } + + public static void main(String[] args)throws Exception{ + jpg2PDF("E:\\桌面\\弗兰德\\1.jpg","E:\\桌面\\弗兰德\\1.pdf"); +// jpg2PDF("C:\\Users\\lee\\Desktop\\GE\\2.png","C:\\Users\\lee\\Desktop\\GE\\2.pdf"); +// jpg2PDF("C:\\Users\\lee\\Desktop\\GE\\3.png","C:\\Users\\lee\\Desktop\\GE\\3.pdf"); +// jpg2PDF("C:\\Users\\lee\\Desktop\\GE\\4.png","C:\\Users\\lee\\Desktop\\GE\\4.pdf"); +// byte[] decode = Base64Util.decode("RG9jMjZfMjAyNDA1MjExMDIwMDkucGRm"); +// String filename = new String(decode, "GB18030"); +// System.out.println(filename); +// List ls = new ArrayList<>(); +// /*ls.add("d:/home/image/pdf/1.jpg"); +// ls.add("d:/home/image/pdf/2.jpg"); +// ls.add("d:/home/image/pdf/3.jpg");*/ +// ls.add("d:/home/image/pdf/4.jpg"); +// ls.add("d:/home/image/pdf/5.png"); +// //FileImgUtil.toPdf(ls,"d:\\home\\image","d:/home/20210429.pdf"); +// /*String imagePath="d:/home/image/pdf/1.jpg"; +// String nImagePath = imagePath.substring(imagePath.lastIndexOf(".")); +// System.out.println(imagePath.replaceAll(nImagePath,"2"+nImagePath));*/ +// //textToImage("{\"Date\": \"2023-08-07\", \"Type\": \"3100\",\"creditCard\": \"XXXX83752\", \"Restarant\": \"美团饭店\",\"Attendee\": \"5\",\"Amount\": \"941\",\"Currecy\": \"CNY\",\"Status\": \"完成\",\"ActualAttend\": \"5\",\"Remark\": \"230518 兰州市第一人民医院泌尿科室会\",\"isCheck\": \"是\",\"Reason\": \"点检\",\"Result\": \"合格\"}"); + } + + + + public static void jpg2PDF(String filePath, String pdfPath) { + try { + // PDF文件保存地址 + // String pdfPath = "D:/Demo/ceshi/hebing.pdf"; + // 输入流 + FileOutputStream fos = new FileOutputStream(pdfPath); + // 创建文档 + Document doc = new Document(null, 0, 0, 0, 0); + //doc.open(); + // 写入PDF文档 + PdfWriter.getInstance(doc, fos); + // 读取图片流 + BufferedImage img = null; + // 实例化图片 + com.itextpdf.text.Image image = null; + int imgWidth=0; + int imgHeight=0; + // 循环获取图片文件夹内的图片 + //获取图片的磁盘路径地址 + // 读取图片流 +// if(filesType.get(m).equals("Y") && correctFlag.equals("1")){ +// log.info("toPdf===修正颜色=======开始"); +// // 重新保存图片修正色彩 +// String tmp=imgFilePath.substring(imgFilePath.lastIndexOf(".")); +// String nImagePath = imgFilePath.replaceAll(tmp,"2A"+tmp); +// compressPicAlibaba(imgFilePath,nImagePath); +// tmpFiles.add(nImagePath); +// // 实例化图片 +// image = com.itextpdf.text.Image.getInstance(nImagePath); +// log.info("toPdf===修正颜色=======结束"); +// }else{ + image = com.itextpdf.text.Image.getInstance(filePath); + log.info("toPdf===不修正颜色======="); +// } + + // 添加图片到文档 + // 根据图片大小设置文档大小---原来的设置 + //doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight())); + + //获取图片高度 + float scaledHeight = image.getScaledHeight(); + //判断图片高度是否大于最高高度14400 + if (scaledHeight > PAGE_MAX_HEIGHT){ + log.info("toPdf===1===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new com.itextpdf.text.Rectangle(imageWidth, imageHeight)); + doc.open(); + doc.add(image); + // 关闭文档 + doc.close(); +// for(String tmpName:tmpFiles){ + // 删除生成的图片 +// (new File(filePath)).delete(); +// } + + log.info("toPdf===OK======="); + } catch (IOException e) { + e.printStackTrace(); + } catch (BadElementException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/HttpUtils.java b/src/main/java/com/cmsen/ticket/domain/util/HttpUtils.java new file mode 100644 index 0000000..58255d1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/HttpUtils.java @@ -0,0 +1,27 @@ +//package com.cmsen.ticket.domain.util; +// +//import okhttp3.*; +// +//import java.io.IOException; +//import java.util.Map; +// +//public class HttpUtils { +// +// public static String postGetString(Map params) throws IOException { +// OkHttpClient client = new OkHttpClient().newBuilder() +// .build(); +// MediaType mediaType = MediaType.parse("text/plain"); +// RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) +// .addFormDataPart("userName", params.get("userName")) +// .addFormDataPart("password", params.get("password")) +// .build(); +// Request request = new Request.Builder() +// .url(params.get("url")) +// .method("POST", body) +// .addHeader("token", params.get("token")) +// .addHeader("Cookie", "wolfking.jeeplus.session.id=0cd53e4b-1362-46ad-a397-55938fea4c19") +// .build(); +// Response response = client.newCall(request).execute(); +// return response.body() != null ? response.body().string() : null; +// } +//} diff --git a/src/main/java/com/cmsen/ticket/domain/util/ImageToPDF.java b/src/main/java/com/cmsen/ticket/domain/util/ImageToPDF.java new file mode 100644 index 0000000..1be1b46 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/ImageToPDF.java @@ -0,0 +1,35 @@ +package com.cmsen.ticket.domain.util; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDPageContentStream; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; + +import java.io.File; +import java.io.IOException; + +public class ImageToPDF { + public static void main(String[] args) { + String pdfFile = "path/to/your/document.pdf"; + String imageFile = "path/to/your/image.jpg"; + } + + public static void addJpg2PDF(String pdfFile,String imageFile){ + try (PDDocument document = PDDocument.load(new File(pdfFile))) { + PDPage page = new PDPage(); + document.addPage(page); + + PDImageXObject pdImage = PDImageXObject.createFromFile(imageFile, document); + PDPageContentStream contentStream = new PDPageContentStream(document, page); + + // 将图片添加到PDF页面上,(x,y) 是图片左下角的位置 + // 这里的50和50是示例值,根据需要调整 + contentStream.drawImage(pdImage, 0, 0); + contentStream.close(); + + document.save(pdfFile); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/MathCalculatorUtil.java b/src/main/java/com/cmsen/ticket/domain/util/MathCalculatorUtil.java new file mode 100644 index 0000000..604a61e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/MathCalculatorUtil.java @@ -0,0 +1,941 @@ +package com.cmsen.ticket.domain.util; + +import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.*; + +import static com.cmsen.ticket.domain.util.MathCalculatorUtil.SelfMathFormulaEnum.getSelfMathFormulaEnum; +import static com.cmsen.ticket.domain.util.MathCalculatorUtil.SelfMathFormulaEnum.getSelfMathFormulaNames; + +/** + * @author fengql + * @date 2023/10/27 16:34 + * @description + */ +@Slf4j +public class MathCalculatorUtil { + + /** + * 所支持的运算操作符集合, 两元运算符 + **/ + private static final Set operateSet = new HashSet<>(); + + /** + * 初始化 + **/ + static { + //加 + operateSet.add('+'); + //减 + operateSet.add('-'); + //乘 + operateSet.add('*'); + //除 + operateSet.add('/'); + //求余 + operateSet.add('%'); + } + + /** + * 自定义数学公式枚举 + **/ + enum SelfMathFormulaEnum { + + abs("abs", 1, 3, "abs(x)", "返回数的绝对值"), + acos("acos", 1, 4,"acos(x)", "返回数的反余弦值"), + asin("asin", 1, 4,"asin(x)", "返回数的反正弦值"), + atan("atan", 1, 4,"atan(x)", "以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值"), + ceil("ceil", 1, 4,"ceil(x)", "对数进行上舍入"), + cos("cos", 1, 3,"cos(x)", "返回数的余弦"), + exp("exp", 1, 3,"exp(x)", "返回 e 的指数"), + floor("floor", 1, 5,"floor(x)", "对数进行下舍入"), + log("log", 1, 3,"log(x)", "返回数的自然对数(底为e)"), + max("max", 2, 3,"max(x,y)", "返回 x 和 y 中的最高值"), + min("min", 2, 3,"min(x,y)", "返回 x 和 y 中的最低值"), + pow("pow", 2, 3,"pow(x,y)", "返回 x 的 y 次幂"), + round("round", 1, 5,"round(x)", "把数四舍五入为最接近的整数"), + sin("sin", 1, 3,"sin(x)", "返回数的正弦"), + sqrt("sqrt", 1, 4,"sqrt(x)", "返回数的平方根"), + tan("tan", 1, 3,"tan(x)", "返回角的正切"); + + /** + * 公式名称 + **/ + private String formulaName; + + /** + * 公式参数数量 + **/ + private Integer formulaArgCount; + + /** + * 公式名称长度 + **/ + private Integer formulaNameLength; + + /** + * 公式表达式 + **/ + private String formulaExpresion; + + /** + * 公式描述 + **/ + private String description; + + /** + * @param formulaName + * @param formulaArgCount + * @return com.jxv.common.utils.MathCalculatorUtil.SelfMathFormulaEnum + * @Description 根据自定义公式名称,和参数数量返回匹配的枚举实体 + **/ + public static SelfMathFormulaEnum getSelfMathFormulaEnum(String formulaName, Integer formulaArgCount) { + for (SelfMathFormulaEnum selfMathFormulaEnum : SelfMathFormulaEnum.values()) { + if (selfMathFormulaEnum.getFormulaName().equals(formulaName) && selfMathFormulaEnum.getFormulaArgCount().equals(formulaArgCount)) { + return selfMathFormulaEnum; + } + } + return null; + } + + /** + * @Description 根据名称获取函数名 + * @param formulaName + * @return com.jxv.common.utils.MathCalculatorUtil.SelfMathFormulaEnum + **/ + public static SelfMathFormulaEnum getSelfMathFormulaEnum(String formulaName) { + for (SelfMathFormulaEnum selfMathFormulaEnum : SelfMathFormulaEnum.values()) { + if (selfMathFormulaEnum.getFormulaName().equals(formulaName)) { + return selfMathFormulaEnum; + } + } + return null; + } + + /** + * @param + * @return java.util.List + * @Description 获取自定义公式的简单名称集合 + **/ + public static List getSelfMathFormulaNames() { + List formulaNames = new ArrayList<>(); + for (SelfMathFormulaEnum selfMathFormulaEnum : SelfMathFormulaEnum.values()) { + formulaNames.add(selfMathFormulaEnum.getFormulaName()); + } + return formulaNames; + } + + /** + * @Description 获取所有的自定义函数枚举 + * @param + * @return java.util.List + **/ + public static List getSelfMathFormulas() { + List formulaNames = new ArrayList<>(); + for (SelfMathFormulaEnum selfMathFormulaEnum : SelfMathFormulaEnum.values()) { + formulaNames.add(selfMathFormulaEnum); + } + return formulaNames; + } + + SelfMathFormulaEnum(String formulaName, Integer formulaArgCount, Integer formulaNameLength, String formulaExpresion, String description) { + this.formulaName = formulaName; + this.formulaArgCount = formulaArgCount; + this.formulaNameLength = formulaNameLength; + this.formulaExpresion = formulaExpresion; + this.description = description; + } + + public Integer getFormulaNameLength() { + return formulaNameLength; + } + + public void setFormulaNameLength(Integer formulaNameLength) { + this.formulaNameLength = formulaNameLength; + } + + public String getFormulaName() { + return formulaName; + } + + public void setFormulaName(String formulaName) { + this.formulaName = formulaName; + } + + public Integer getFormulaArgCount() { + return formulaArgCount; + } + + public void setFormulaArgCount(Integer formulaArgCount) { + this.formulaArgCount = formulaArgCount; + } + + public String getFormulaExpresion() { + return formulaExpresion; + } + + public void setFormulaExpresion(String formulaExpresion) { + this.formulaExpresion = formulaExpresion; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } + + /** + * JavaScript脚本引擎,Java SE 6开始支持 + **/ + private static final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript"); + + /** + * @param str + * @return boolean + * @Description 判断字符串是否为数字(浮点类型也包括, 以及正负符号) + **/ + public static boolean isNumber(String str) { + String reg = "^[-\\+]?[0-9]+(.[0-9]+)?$"; + return str.matches(reg); + } + + /** + * @param mathFormulaScript 数学公式字符串,如:mathFormula = (2*3-45/5+(9)+9%5 +2*(1+2) + Math.sqrt(3))/9.0 + * 注意:如果使用开根号等三角函数等一些高级计算,则使用Math中字符串来替代,如4开根号==>Math.sqrt(4) + * 具体使用查看:https://www.w3school.com.cn/jsref/jsref_obj_math.asp + * @param retainDigit 保留几位小数 + * @return java.lang.String + * @Description 简单公式计算,会有精度丢失问题 + **/ + public static String simpleFormulaScript(String mathFormulaScript, int retainDigit) { + try { + if (StringUtils.isNotEmpty(mathFormulaScript)) { + mathFormulaScript = "(" + mathFormulaScript + ").toFixed(" + retainDigit + ")"; + } + return JSON.toJSONString(scriptEngine.eval(mathFormulaScript)); + } catch (ScriptException e) { + log.error("非法数学公式!"); + e.printStackTrace(); + throw new RuntimeException("非法数学公式!"); + } + } + + /** + * @param mathFormulaScript + * @return java.lang.String + * @Description 重载方法,默认进度小数保留两位 + **/ + public static String simpleFormulaScript(String mathFormulaScript) { + return simpleFormulaScript(mathFormulaScript, 2); + } + + /** + * @param arg + * @return void + * @Description 参数检查 + **/ + private static void checkArg(String arg) { + checkArg(arg, true); + } + + /** + * @param arg + * @return void + * @Description 参数检查 + **/ + private static void checkArg(String arg, boolean isZero) { + if (StringUtils.isEmpty(arg) || !isNumber(arg) || (!isZero && (new BigDecimal("0").compareTo(new BigDecimal(arg)) == 0))) { + throw new RuntimeException("非法计算参数!"); + } + } + + /** + * @param expression "1+1*2+(10-(2*(5-3)*(2-1))-4)+10/(5-0) + log(10) + log(10,12)" + * @return void + * @Description 校验公式表达式的合法性 + **/ + private static void checkFormulaExpression(String expression) { + //去除空格 + expression = expression.replaceAll(" ", ""); + //拆分字符串 + char[] arr = expression.toCharArray(); + int len = arr.length; + //前后括号计数,用来判断括号是否合法 + int checkNum = 0; + //数字集合 + StringBuffer sb = new StringBuffer(); + //字母集合 + StringBuffer sb0 = new StringBuffer(); + //循环 + for (int i = 0; i < len; i++) { + //判断当前元素是否是数字 + if (Character.isDigit(arr[i]) || arr[i] == '.') { + //把数字和小数点加入到集合中,为了下一步判断数字是否合法 + sb.append(arr[i]); + } else if (Character.isLetter(arr[i])) { + //校验自定义的公式(自定义的数学表达式都是使用字母拼接起来) + sb0.append(arr[i]); + } else { + //如果sb中有值,取出来判断这个数字整体是否合法 + if (sb.length() > 0) { + if (isNumber(sb.toString())) { + //如果合法,清空,为了判断下一个 + sb.setLength(0); + } else { + throw new RuntimeException("非法数字参数"); + } + } + + //不是数字为字符,可能是{},[], (), +, - , * , /, % 等,再加上各种自定义的数学运算公式, 或者是其他不合法的字符,接着继续判断 + if (arr[i] == '+' || arr[i] == '*' || arr[i] == '/' || arr[i] == '%') { + //判断规则(1.不能位于首位 2.不能位于末尾 3.后面不能有其他运算符,但可以有-号 4.后面不能有后括号) + if (i == 0 || i == (len - 1) || arr[i + 1] == '+' || arr[i + 1] == '*' || arr[i + 1] == '/' || arr[i + 1] == '%' || arr[i + 1] == ')') { + log.error("非法符号 : '+' or '*' or '/' ->" + arr[i]); + throw new RuntimeException("非法符号 : '+' or '*' or '/' ==>" + arr[i]); + } + } else if (arr[i] == '-') { + //减号判断规则(1.不能位于末尾 2.后面不能有其他运算符,但可以有-号 3.后面不能有后括号) + if (i == (len - 1) || arr[i + 1] == '+' || arr[i + 1] == '*' || arr[i + 1] == '/' || arr[i + 1] == '%' || arr[i + 1] == ')') { + log.error("非法符号 : '-' ->" + arr[i]); + throw new RuntimeException("非法符号 : '-' ==>" + arr[i]); + } + } else if (arr[i] == '(') { + //判断(括号前面是否有字母 + //如果sb0中有字母,取出来判断这个字符串整体是否是自定义的公式字符 + if (sb0.length() > 0) { + //从当前匹配的(,找到最近的),然后在求出在 这两个括号之间以英文逗号隔开的参数个数 + int beginIndex = expression.indexOf(arr[i], i); + + int endIndex = matchBracketIndex(expression, i, arr[i]); + if (endIndex == -1) { + log.error("非法数学公式符号:==>" + sb0.length()); + throw new RuntimeException("非法数学公式符号: ==>" + sb0.length()); + } + //截取字符串,且分隔匹配的英文逗号 + String selfMathBracketContentStr = expression.substring(beginIndex + 1, endIndex); + if (StringUtils.isEmpty(selfMathBracketContentStr)) { + log.error("非法自定义数学公式符号:==>" + sb0.length()); + throw new RuntimeException("非法自定义数学公式符号: ==>" + sb0.length()); + } + //获取参数个数 + StringBuilder selfMathBracketContentSb = new StringBuilder(selfMathBracketContentStr); + int argCounts = getSelfMathMarkArgCounts(selfMathBracketContentSb, ","); + //校验自定义公式的合法性 + checkSelfMathMark(sb0.toString(), argCounts); + //清空内容 + sb0.setLength(0); + } + + checkNum++; + //判断规则(1.不能位于末尾 2.后面不能有+,*,/,%运算符和后括号 3.前面不能为数字) + if (i == (len - 1) || arr[i + 1] == '+' || arr[i + 1] == '*' || arr[i + 1] == '/' || arr[i + 1] == '%' || arr[i + 1] == ')' || (i != 0 && Character.isDigit(arr[i - 1]))) { + log.error("非法符号 : '(' ->" + arr[i]); + throw new RuntimeException("非法符号 : '(' ==>" + arr[i]); + } + } else if (arr[i] == ')') { + checkNum--; + //判定规则(1.不能位于首位 2.后面不能是前括号 3.括号计数不能小于0,小于0说明前面少了前括号) + if (i == 0 || (i < (len - 1) && arr[i + 1] == '(') || checkNum < 0) { + log.error("非法符号 : ')' ->" + arr[i]); + throw new RuntimeException("非法符号 : ')' ==>" + arr[i]); + } + } else if (arr[i] == ',') { + //判定规则,如果有逗号,1,匹配该逗号是否被括号()包着,且左括号当前前面是否是自定义公式 + checkComma(expression, i, i); + } else { + //非数字和运算符 + log.error("非数字和运算符:==>" + arr[i]); + throw new RuntimeException("非数字和运算符:==>" + arr[i]); + } + } + } + //不为0,说明括号不对等,可能多前括号 + if (checkNum != 0) { + //非数字和运算符 + log.error("括号个数不匹配"); + throw new RuntimeException("括号个数不匹配"); + } + } + + /** + * @param str 待匹配的字符数组 + * @param currentCommaIndex 当前逗号索引 + * @param constCommaIndex 常量逗号索引 + * @return void + * @Description 校验英文逗号 + **/ + private static void checkComma(String str, int currentCommaIndex, final int constCommaIndex) { + //从currentCommaIndex索引开始往前找最近的一个左括号(,求出索引,并求出对应的)索引 + int beginIndex = indexOfBefore(str, currentCommaIndex, '('); + if (beginIndex == -1) { + log.error("非法逗号!"); + throw new RuntimeException("非法逗号!"); + } + int endIndex = matchBracketIndex(str, beginIndex, '('); + if (endIndex == -1) { + log.error("非法逗号!"); + throw new RuntimeException("非法逗号!"); + } + //找到符合的逗号条件 + if (endIndex <= constCommaIndex) { + //接着往上找 + checkComma(str, beginIndex, constCommaIndex); + } else { + //在从beginIndex索引开始往前找出连续字母的字符,然后拼接 + char[] chars = str.toCharArray(); + StringBuilder sb = new StringBuilder(); + for (int i = beginIndex - 1; i >= 0; i--) { + //如果是字母或者是数字 + if (Character.isLetter(chars[i]) || Character.isDigit(chars[i])) { + sb.append(chars[i]); + } else { + break; + } + } + //将sb带入自定义公式进行校验 + List selfMathFormulaNames = getSelfMathFormulaNames(); + if (!selfMathFormulaNames.contains(sb.reverse().toString())) { + throw new RuntimeException("非法逗号!"); + } + } + } + + /** + * @param str 目标字符串 如 abcd((a),(b,bb))dada + * @param endIndex + * @return int + * @Description 返回从结束索引结束, + **/ + private static int indexOfBefore(String str, int endIndex, char dest) { + char[] chars = str.trim().toCharArray(); + int len = chars.length; + int index0 = endIndex; + if (len - 1 < endIndex) { + index0 = len; + } + for (int i = index0 - 1; i >= 0; i--) { + if (chars[i] == dest) { + return i; + } + } + //没有找到返回-1 + return -1; + } + + /** + * @param mathArgStr 参数括号字符串 如:log((math(1,6)+2),(8*9)) 中的 ((math(1,6)+2),(8*9)) + * @param regex 分隔符 默认一般英文逗号, + * @return void + * @Description 获取自定义公式的参数个说 + **/ + private static int getSelfMathMarkArgCounts(StringBuilder mathArgStr, String regex) { + //找到最近的一个( 索引 + int beginIndex = mathArgStr.indexOf("("); + if (beginIndex != -1) { + int endIndex = matchBracketIndex(mathArgStr.toString(), beginIndex, '('); + if (endIndex == -1) { + throw new RuntimeException("非法括号匹配!"); + } + mathArgStr.replace(beginIndex, endIndex + 1, ""); + return getSelfMathMarkArgCounts(mathArgStr, regex); + } else { + //如果没有匹配的做扩号,则直接求出参数个数 + String[] argsArr = mathArgStr.toString().split(regex, -1); + return argsArr.length; + } + } + + /** + * @param mathStr log sin + * @param argCount 2 , 1 + * @return boolean + * @Description 校验数字字符数组 + **/ + private static void checkSelfMathMark(String mathStr, int argCount) { + SelfMathFormulaEnum selfMathFormulaEnum = getSelfMathFormulaEnum(mathStr, argCount); + if (selfMathFormulaEnum == null) { + throw new RuntimeException("自定义数学公式不匹配!"); + } + } + + /** + * @param s 待匹配的字符串 + * @param fromIndex 开始索引 + * @param leftDest 左括号 + * @return int + * @Description 通过当前左括号(的索引 , 找到与之匹配对应的右括号) 的索引 + **/ + private static int matchBracketIndex(String s, int fromIndex, char leftDest) { + if (StringUtils.isEmpty(s)) { + return -1; + } + //取出匹配目标的第一个索引 + int index0 = s.indexOf(leftDest, fromIndex); + if (index0 != -1) { + //1、申明一个stack + Stack stack = new Stack<>(); + //遍历s String本质上是char[] + for (int i = index0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '{' || c == '[' || c == '(') { + //如果是{ [ ( 压入栈中 + stack.push(c); + } else if (c == '}' || c == ']' || c == ')') { + // } ] ) 进行比对, + if (stack.isEmpty()) { + return -1; + } + char topChar = stack.pop(); + if ((topChar == '[' && c == ']') || (topChar == '(' && c == ')') || (topChar == '{') && c == '}') { + if (stack.isEmpty()) { + return i; + } else { + continue; + } + } + } else { + continue; + } + } + + } + return -1; + } + + /** + * @param v1 + * @param v2 + * @return java.lang.String + * @Description 两个数相加 + **/ + private static String add(String v1, String v2) { + //校验参数 + checkArg(v1); + checkArg(v2); + BigDecimal v1Bd = new BigDecimal(v1); + BigDecimal v2Bd = new BigDecimal(v2); + return v1Bd.add(v2Bd).toString(); + } + + /** + * @param v1 + * @param v2 + * @return java.lang.String + * @Description 两个数相减 + **/ + private static String sub(String v1, String v2) { + //校验参数 + checkArg(v1); + checkArg(v2); + BigDecimal v1Bd = new BigDecimal(v1); + BigDecimal v2Bd = new BigDecimal(v2); + return v1Bd.subtract(v2Bd).toString(); + } + + /** + * @param v1 + * @param v2 + * @return java.lang.String + * @Description 两个数相乘 + **/ + private static String mul(String v1, String v2) { + //校验参数 + checkArg(v1); + checkArg(v2); + BigDecimal v1Bd = new BigDecimal(v1); + BigDecimal v2Bd = new BigDecimal(v2); + return v1Bd.multiply(v2Bd).toString(); + } + + /** + * @param v1 + * @param v2 + * @return java.lang.String + * @Description 两个数相除 + **/ + private static String div(String v1, String v2) { + //校验参数 + checkArg(v1); + //除数不能为0 + checkArg(v2, false); + BigDecimal v1Bd = new BigDecimal(v1); + BigDecimal v2Bd = new BigDecimal(v2); + return v1Bd.divide(v2Bd, 8, RoundingMode.HALF_UP).toString(); + } + + /** + * @Description v1%v2 取余 + * @param v1 + * @param v2 + * @return java.lang.String + **/ + private static String mod(String v1, String v2) { + //校验参数 + checkArg(v1); + //除数不能为0 + checkArg(v2, false); + BigDecimal v1Bd = new BigDecimal(v1); + BigDecimal v2Bd = new BigDecimal(v2); + return v1Bd.remainder(v2Bd).toString(); + } + + /** + * @param mathFormula 公式字符串, 如:"1+1*2+(10-(2*(5-3)*(2-1))-4)+10/(5-0) + log(10) + log(10,12)" + * 注意log(10) ==> ln(10) ==> log(e,10) 表示以自然数e为底的对数 + * @return java.lang.String + * @Description 使用递归计算,判断表达式是否有括号,有括号,则先计算括号内的表达式,无则直接运算结果。 + **/ + public static String calculator(String mathFormula) { + if (StringUtils.isEmpty(mathFormula)) { + throw new RuntimeException("非法计算公式!"); + } + //替换空格 + mathFormula = mathFormula.replaceAll(" ", ""); + int bracket = mathFormula.indexOf("["); + int brace = mathFormula.indexOf("{"); + if (bracket != -1 || brace != -1) { + //将字符串中的"{}"、"[]"替换成"()" + log.info("计算公式:{}", mathFormula); + mathFormula = mathFormula.replaceAll("[\\[\\{]", "(").replaceAll("[\\]\\}]", ")"); + log.info("标准数学计算公式 '{,[':" + mathFormula); + } + //校验公式参数是否合法 + checkFormulaExpression(mathFormula); + + //==================================================开始计算============================================= + //计算思路:以下是计算顺序 + // 1,如果有自定义的数学公式,则先计算自定义的公式 + // 2, 如果有括号,则先计算括号内的(去括号) + // 3, 没有括号直接计算 + String result0 = calculatorSelfMathFormula(mathFormula); + //结果保留八位小数 + return new BigDecimal(result0).setScale(8,BigDecimal.ROUND_HALF_UP).toString(); + } + + /** + * @Description 去除自定义公式 + * @param mathFormula + * @return java.lang.String + **/ + private static String calculatorSelfMathFormula(String mathFormula) { + if (StringUtils.isEmpty(mathFormula)) { + throw new RuntimeException("非法参数错误!"); + } + mathFormula = mathFormula.replaceAll(" ", ""); + //去除自定义公式 + List selfMathFormulaEnums = SelfMathFormulaEnum.getSelfMathFormulas(); + boolean flag = false; + for (SelfMathFormulaEnum mathFormulaEnum : selfMathFormulaEnums) { + if (mathFormula.contains(mathFormulaEnum.getFormulaName())) { + flag = true; + break; + } + } + //包含自定义公式 + if (flag) { + for (int i = 0; i < selfMathFormulaEnums.size();) { + boolean repeat = false; + SelfMathFormulaEnum mathFormulaEnum = selfMathFormulaEnums.get(i); + //如果该公式表达式包含自定义数学公式 "1+1*2+(10-(2*(5-3)*(2-1))-4)+10/(5-0) + log(10) + 2*log(30)+ max(sin(2*(5+2))*6,pow(2*(2+8),3+2)) * max(1+3,(3-5)) + min(sin(10), sin(20))" + if (mathFormula.contains(mathFormulaEnum.getFormulaName())) { + //如果匹配到,则获取第一个自定义的数学公式首字母所在的索引(该索引是格式化后的索引) + int index0 = mathFormula.indexOf(mathFormulaEnum.getFormulaName()); + //取出该公式括号中内容字符,不包括左右字符 + String left = mathFormula.substring(0, index0); + int index1 = matchBracketIndex(mathFormula, index0, '('); + String right = mathFormula.substring(index1 +1); + String bracketsContent = mathFormula.substring(index0 + mathFormulaEnum.getFormulaNameLength() + 1, index1); + //计算括号中的值,如果该字符串又包含其他自定义公式,则递归继续计算 + //left + result0 + right + mathFormula = left + selfMathCalculation(mathFormulaEnum.getFormulaName(), calculatorSelfMathFormula(bracketsContent)) + right; + repeat = true; + } + if (repeat) { + i = i; + }else { + i++; + } + } + } + //直接进行计算 + return standardCalculation(mathFormula); + } + + /** + * @Description 自定义公式计算 + * @param mathFormulaName 自定义公式名称 + * @param digitStr 一个具体的数值 + * @return java.lang.String + **/ + private static String selfMathCalculation(String mathFormulaName, String digitStr) { + double result; + if (StringUtils.isEmpty(digitStr)) { + throw new RuntimeException("非法计算公式参数!"); + } + String[] args = digitStr.split(",", -1); + + SelfMathFormulaEnum selfMathFormulaEnum = getSelfMathFormulaEnum(mathFormulaName); + if (selfMathFormulaEnum == null) { + throw new RuntimeException("非法数学公式名称"); + } + switch (selfMathFormulaEnum) { + case abs: + result = Math.abs(Double.parseDouble(args[0])); + break; + case acos: + result = Math.acos(Double.parseDouble(args[0])); + break; + case asin: + result = Math.asin(Double.parseDouble(args[0])); + break; + case atan: + result = Math.atan(Double.parseDouble(args[0])); + break; + case ceil: + result = Math.ceil(Double.parseDouble(args[0])); + break; + case cos: + result = Math.cos(Double.parseDouble(args[0])); + break; + case exp: + result = Math.exp(Double.parseDouble(args[0])); + break; + case floor: + result = Math.floor(Double.parseDouble(args[0])); + break; + case log: + result = Math.log(Double.parseDouble(args[0])); + break; + case max: + result = Math.max(Double.parseDouble(args[0]), Double.parseDouble(args[1])); + break; + case min: + result = Math.min(Double.parseDouble(args[0]), Double.parseDouble(args[1])); + break; + case pow: + result = Math.pow(Double.parseDouble(args[0]), Double.parseDouble(args[1])); + break; + case round: + result = Math.round(Double.parseDouble(args[0])); + break; + case sin: + result = Math.sin(Double.parseDouble(args[0])); + break; + case sqrt: + result = Math.sqrt(Double.parseDouble(args[0])); + break; + case tan: + result = Math.tan(Double.parseDouble(args[0])); + break; + default: + throw new RuntimeException("找不到匹配的计算公式!"); + + } + return String.valueOf(result); + } + + /** + * @Description 标准计算,不包含自定义函数, 但包含括号与其他符号表达式 + * @param str + * @return java.lang.String + **/ + private static String standardCalculation(String str) { + if (StringUtils.isEmpty(str)) { + log.error("非法计算公式!"); + throw new RuntimeException("非法计算公式!"); + } + String[] args = str.split(",", -1); + if (args != null && args.length > 0) { + List argResult = new ArrayList<>(); + for (String arg : args) { + //每一个arg 都是一个算式(带上括号的) + //判断是公式表达是是否存在小括号(优先级) + int hasBrackets = arg.lastIndexOf('('); + if (hasBrackets == -1) { + //没有小括号,直接计算 + argResult.add(cac(arg)); + }else { + int cr = arg.indexOf(')', hasBrackets); + String left = arg.substring(0, hasBrackets); + String right = arg.substring(cr + 1); + //如果存在"("提取括号中的表达式 + String middle = arg.substring(hasBrackets + 1, cr); + argResult.add(standardCalculation(left + cac(middle) + right)); + } + } + return StringUtils.join(argResult, ","); + } + throw new RuntimeException("非法算式参数!"); + } + + /** + * DESC:计算表达式,判断是否存在乘除运算,存在则先执行乘除运算,然后执行加减运算,返回运算结果; + * 不存在,直接运行加减运算,返回运算结果。 + * + * @param str -2.8+8*3/2+0.9 或 -2.8*6 + * @return 运算结果 + */ + private static String cac(String str) { + //字符串中不存在*,/, % + int mulIndex = str.indexOf('*'); + int divIndex = str.indexOf('/'); + int modIndex = str.indexOf('%'); + //只有加法和减法 + if (mulIndex == -1 && divIndex == -1 && modIndex == -1) { + return AASOperation(str); + } + String result0 = "0"; + + //定义先处理的符号索引位置 + int index0 = getMin(-1,mulIndex, divIndex, modIndex); + try { + String left = str.substring(0, index0); + String v1 = lastNumber(left); + left = left.substring(0, left.length() - v1.length()); + String right = str.substring(index0 + 1); + String v2 = firstNumber(right); + right = right.substring(v2.length()); + + if (index0 == mulIndex) { + result0 = mul(v1, v2); + } else if(index0 == divIndex) { + result0 = div(v1, v2); + } else if(index0 == modIndex) { + result0 = mod(v1, v2); + } + String s = left + result0 + right; + return cac(left + result0 + right); + }catch (Exception e) { + log.error("数学计算公式错误"+ e.getMessage()); + throw new RuntimeException("数学计算公式错误!"); + } + } + + /** + * @Description 求给定可变参数中不等于noNum 的最小值 + * @param noNum + * @param a 可变参数 + * @return int + **/ + private static int getMin(int noNum, int... a){ + if (a == null || a.length == 0) { + throw new RuntimeException("非法参数!"); + } + int min = a[0]; + for (int i = 1; i < a.length; i++) { + if (min ==noNum || (min > a[i] && a[i] != noNum)) { + min = a[i]; + } + } + if (min == noNum) { + throw new RuntimeException("非法可变参数!"); + } + return min; + } + + /** + * @Description 获得表达式的最后连续合法数字 + * @param str + * @return java.lang.String + */ + private static String lastNumber(String str) { + StringBuilder sb = new StringBuilder(); + for (int i = str.length() - 1; i >= 0; i--) { + char c = str.charAt(i); + //包含首字母为- + if (Character.isDigit(c) || (i != 0 && c == '.') || ((i == 0 || operateSet.contains(str.charAt(i -1))) && c == '-')) { + sb.append(c); + }else { + break; + } + } + return sb.reverse().toString(); + } + + /** + * @Description 获得表达式的最后连续合法数字 + * @param str + * @return java.lang.String + */ + private static String firstNumber(String str) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + //包含首字母为- + if (Character.isDigit(c) || (i != 0 && c == '.') || (i == 0 && c == '-')) { + sb.append(c); + }else { + break; + } + } + return sb.toString(); + } + + /** + * @Description 只用加减操作 + * @param mathStr 只有加减操作的数学运算字符串: 如2.98-5-6+9-0.2-8 或 -2.0-9-5+9 或 -9-2 + * @return java.lang.String + **/ + private static String AASOperation(String mathStr) { + if (StringUtils.isEmpty(mathStr)) { + throw new RuntimeException("非法计算参数"); + } + //这里字符串加上一个运算法号,只要是合法的都可以,只是为了走一步运算 + char[] options = (mathStr + "+").replaceAll(" ", "").toCharArray(); + String result0 = "0"; + StringBuilder sb = new StringBuilder(); + char sign = '+'; + for (int i = 0; i < options.length; i++) { + if (Character.isDigit(options[i]) || options[i] == '.') { + sb.append(options[i]); + } else { + if ((i == 0 && options[i] == '-') || (i>1 && operateSet.contains(options[i-1]))) { + sb.append(options[i]); + }else { + if (sb.length() > 0){ + //先默认为 + 把第一个数值加上 + if (sign == '+') { + result0 = add(result0, sb.toString()); + } else { + result0 = sub(result0, sb.toString()); + } + sb.setLength(0); + sign = options[i]; + } else { + throw new RuntimeException("非法数学公式错误!"); + } + } + + } + } + + return result0; + } + + //"1+1*2+(10-(2*(5-3)*(2-1))-4)+10/(5-0) + log(10) + max(sin(2)*6,pow(2,3))" + public static void main(String args[]) throws ScriptException { + long beginTime = System.currentTimeMillis(); + + String k ="A*B-C" + .replace("A","100") + .replace("B","10") + .replace("C","10"); + + String re0 = calculator(k); + + System.out.println(re0); + + System.out.println("cost时间:" + (System.currentTimeMillis() - beginTime) + "ms"); + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/Pagination2.java b/src/main/java/com/cmsen/ticket/domain/util/Pagination2.java new file mode 100644 index 0000000..22c2096 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/Pagination2.java @@ -0,0 +1,61 @@ +package com.cmsen.ticket.domain.util; + +public class Pagination2 { + private int pageNum = 1; + private int pageSize = 15; + private int pageTotal; + private int total; + + public Pagination2(int total) { + this.setTotal(total); + } + + public Pagination2(int total, int pageSize) { + this.setPageSize(pageSize); + this.setTotal(total); + } + + public Pagination2(int total, int pageSize, int pageNum) { + this.setPageNum(pageNum); + this.setPageSize(pageSize); + this.setTotal(total); + } + + public int getPageNum() { + return this.pageNum; + } + + public Pagination2 setPageNum(int pageNum) { + this.pageNum = pageNum <= 0 ? 1 : pageNum; + return this; + } + + public int getPageSize() { + return this.pageSize; + } + + public Pagination2 setPageSize(int pageSize) { + this.pageSize = pageSize <= 0 ? 1 : pageSize; + this.pageTotal = (int) Math.ceil(1.0D * (double) this.total / (double) pageSize); + return this; + } + + public int getPageTotal() { + return this.pageTotal; + } + + public Pagination2 setPageTotal(int pageTotal) { + this.pageTotal = pageTotal; + return this; + } + + public int getTotal() { + return this.total; + } + + public Pagination2 setTotal(int total) { + this.total = total; + this.pageTotal = (int) Math.ceil(1.0D * (double) total / (double) this.pageSize); + return this; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/Pagination2Util.java b/src/main/java/com/cmsen/ticket/domain/util/Pagination2Util.java new file mode 100644 index 0000000..214b34a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/Pagination2Util.java @@ -0,0 +1,68 @@ +package com.cmsen.ticket.domain.util; + +import com.cmsen.ticket.interfaces.facade.manager.form.PaginationForm; +import lombok.*; + +import java.util.Map; + +/** + * @Author OWTS > + * @Date 2020/7/30 + * @Description + */ +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class Pagination2Util { + private Object data; + private Pagination2 pagination; + + /** + * 无pageNum不分页 + * + * @param total 数据总数 + * @param form 分页参数数据 + * @param data 数据 + * @author jared.Yan (yanhuaiwen@163.com) + */ + public static Object getPageResult(int total, PaginationForm form, Object data) { + if (form != null && form.getStartNo() != null) { + return new Pagination2Util(data, new Pagination2(total, form.getLength(), form.getStartNo())); + } else { + return data; + } + } + + /** + * 匹配pageSize,pageNum,若无,不分页 + * + * @param params + */ + public static void paginationInit(Map params) { + if (params.containsKey("pageSize") && params.containsKey("pageNum")) { + params.put("startNo", (Integer.parseInt(params.get("pageNum").toString()) - 1) + * Integer.parseInt(params.get("pageSize").toString())); + params.put("length", Integer.parseInt(params.get("pageSize").toString())); + } + } + + /** + * 返回查询结果,包含分页信息 + * + * @param total + * @param params + * @param data + * @return + */ + public static Object getPageResult(int total, Map params, Object data) { + if (params.containsKey("pageSize") && params.containsKey("pageNum")) { + Pagination2 pagination = new Pagination2(total, Integer.parseInt(params.get("pageSize").toString()), + Integer.parseInt(params.get("pageNum").toString())); + return new Pagination2Util(data, pagination); + } else { + return data; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/Pdf2JpgHelper.java b/src/main/java/com/cmsen/ticket/domain/util/Pdf2JpgHelper.java new file mode 100644 index 0000000..5e37efc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/Pdf2JpgHelper.java @@ -0,0 +1,1002 @@ +package com.cmsen.ticket.domain.util; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; +import com.cmsen.common.util.Base64Util; +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.StorageCache; +import com.cmsen.common.util.StringUtil; +import com.cmsen.pdf.HtmlToImage; +import com.cmsen.ticket.domain.entity.CorporateInvoiceType; +import com.cmsen.ticket.domain.entity.CreditItem; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.pdfbox.cos.COSName; +import org.apache.pdfbox.cos.COSStream; +import org.apache.pdfbox.multipdf.PDFMergerUtility; +import org.apache.pdfbox.multipdf.Splitter; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.graphics.PDXObject; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; +import org.apache.pdfbox.rendering.ImageType; +import org.apache.pdfbox.rendering.PDFRenderer; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.io.*; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +/** + * @author ran hao yu + * @date 2020/9/4 9:25 + */ +@Slf4j +public class Pdf2JpgHelper { + + public static final String MILEAGE_IMG_FILE_PREFIX = "MILEAGE_FILE"; + + public static final String SALE_IMG_FILE_PREFIX = "SALE_FILE"; + + public static void pdfToImage2(String pdfPath, String imagePath) { + File filePdf = new File(pdfPath); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(filePdf); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int endPage = 1; + for (int i = startPage; i < endPage; i++) { + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 192); + ImageIO.write(bufferedImage, "JPG", new File(imagePath)); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + public static void main(String[] args) throws IOException { + String merge = "E:\\桌面\\GE\\small.pdf"; + List pdfs = new ArrayList<>(); + pdfs.add("E:\\桌面\\GE\\1.pdf"); + pdfs.add("E:\\桌面\\GE\\2.pdf"); +// pdfs.add("C:\\Users\\lee\\Desktop\\GE\\3.pdf"); +// pdfs.add("C:\\Users\\lee\\Desktop\\GE\\4.pdf"); +// pdfs.add("D:\\home\\3.pdf"); +// pdfs.add("D:\\home\\4.pdf"); +// pdfs.add("D:\\home\\5.pdf"); +// pdfs.add("D:\\home\\6.pdf"); +// pdfs.add("D:\\home\\7.pdf"); +// pdfs.add("D:\\home\\8.pdf"); +// pdfs.add("D:\\home\\9.pdf"); +// pdfs.add("D:\\home\\10.pdf"); +// pdfs.add("D:\\home\\11.pdf"); +// pdfs.add("D:\\home\\12.pdf"); +// pdfs.add("D:\\home\\13.pdf"); +// pdfs.add("D:\\home\\14.pdf"); + mergePdf(merge,pdfs); +//// try { +//// // 示例用法 +//// File imageFile = new File("D:\\test\\1.jpg"); +//// System.out.println(fileToBase64(imageFile)); +//// +//// File pdfFile = new File("D:\\test\\1.pdf"); +//// System.out.println(fileToBase64(pdfFile)); +//// } catch (IOException e) { +//// e.printStackTrace(); +//// } +//// Pdf2JpgHelper.pdfToImages("D:\\test\\1.pdf","D:\\test\\",188); +//// Pdf2JpgHelper.pdfLastPageToImage("C:\\Users\\lee\\Desktop\\QQQQQQQQQQQQQQQQQQQQQQ.pdf","C:\\Users\\lee\\Desktop\\1.jpg"); +//// Pdf2JpgHelper.pdfGetOnePagePdf("C:\\Users\\lee\\Desktop\\发票识别不了.pdf","D:\\test\\2.pdf"); +// Pdf2JpgHelper.pdfSplitOrder("D:\\弗兰德传动系统有限公司_26317000001495101475.pdf","D:\\home\\"); + } + + public static void pdfGetOnePagePdf(String pdfPath, String resultPath) throws IOException { + // 加载现有PDF文档 + File file = new File(pdfPath); + PDDocument document = PDDocument.load(file); + + // 实例化Splitter类 + Splitter splitter = new Splitter(); + + // 拆分PDF文档 + List pages = splitter.split(document); + + // 创建迭代器对象 + Iterator iterator = pages.iterator(); + + // 保存拆分后的文档 + while (iterator.hasNext()) { + PDDocument pd = iterator.next(); + pd.save(resultPath); + break; + } + // 关闭原始文档 + document.close(); + } + + public static List pdfSplit(String pdfPath, String resultParentPath) throws IOException { + List result= new ArrayList<>(); + // 加载现有PDF文档 + File file = new File(pdfPath); + PDDocument document = PDDocument.load(file); + + // 实例化Splitter类 + Splitter splitter = new Splitter(); + + // 拆分PDF文档 + List pages = splitter.split(document); + + // 创建迭代器对象 + Iterator iterator = pages.iterator(); + // 保存拆分后的文档 + while (iterator.hasNext()) { + String uuid = StringUtil.UUID(); + PDDocument pd = iterator.next(); + String filePath = resultParentPath+"/"+uuid+".pdf"; + pd.save(filePath); + result.add(filePath); + } + // 关闭原始文档 + document.close(); + return result; + } + + public static List pdfSplitOrder(String pdfPath, String resultParentPath) throws IOException { + List result= new ArrayList<>(); + // 加载现有PDF文档 + File file = new File(pdfPath); + PDDocument document = PDDocument.load(file); + + // 实例化Splitter类 + Splitter splitter = new Splitter(); + + // 拆分PDF文档 + List pages = splitter.split(document); + + // 创建迭代器对象 + Iterator iterator = pages.iterator(); + // 保存拆分后的文档 + int i=1; + while (iterator.hasNext()) { + String uuid = StringUtil.UUID(); + PDDocument pd = iterator.next(); + String filePath = resultParentPath+"/"+i+".pdf"; + pd.save(filePath); + result.add(filePath); + i++; + } + // 关闭原始文档 + document.close(); + return result; + } + + public static List pdfToImages(String pdfPath, String imageParentPath,int dpi) { + File filePdf = new File(pdfPath); + PDDocument readPdf = null; + List result = new ArrayList<>(); + try { + readPdf = PDDocument.load(filePdf); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, dpi); + String tempName = StringUtil.UUID()+".jpg"; + ImageIO.write(bufferedImage, "JPG", new File(imageParentPath+tempName)); + result.add(imageParentPath+tempName); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + return result; + } + + public static void pdfLastPageToImage(String pdfPath, String imagePath) { + File filePdf = new File(pdfPath); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(filePdf); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(totalPage-1, 144); + ImageIO.write(bufferedImage, "JPG", new File(imagePath)); + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + public static void pdfToOneImage(String pdfPath, String imagePath) { + File filePdf = new File(pdfPath); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(filePdf); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + String folder = ""; + // 2023-07-17 + // 只取第一页作为预览的效果 img_url + // 改为拼接所有图片作为预览 供 xml发送附件 + // 统计各页宽度和高度 + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, 120); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + // 将绘制的图像生成至输出流 + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + ImageIO.write(jpgImage,"JPG" , new File(imagePath)); + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + public static void pdfToOneImageWithDpi(String pdfPath, String imagePath,int dpi) { + File filePdf = new File(pdfPath); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(filePdf); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + int width = 0; + int height = 0; + String folder = ""; + // 2023-07-17 + // 只取第一页作为预览的效果 img_url + // 改为拼接所有图片作为预览 供 xml发送附件 + // 统计各页宽度和高度 + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + BufferedImage bufferedImage = null; + bufferedImage = pdfRenderer.renderImageWithDPI(i, dpi); + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + } + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + } + // 释放图像资源 + grap.dispose(); + // 将绘制的图像生成至输出流 + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + ImageIO.write(jpgImage,"JPG" , new File(imagePath)); + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + public static List> pdfToImages2(InputStream pdfStream, String imagePath, Boolean generateFolder) { + List> result = new ArrayList<>(); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(pdfStream); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + String savePath; + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + for (int i = startPage; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + savePath = imagePath + folder + fileName; + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 192); + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + Thread.sleep(100); + // 判断图片大小 + File pic = new File(savePath); + long fileSize = pic.length() / 1024 / 1024; + if (fileSize > 3) { + fileName = fileName.replaceAll(".jpg", "") + "ys001" + ".jpg"; + imageCompression(new File(savePath), imagePath + folder + fileName); + savePath = imagePath + folder + fileName; + } + List paths = new ArrayList<>(); + paths.add(folder + fileName); + paths.add(savePath); + paths.add(fileName); + result.add(paths); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + IoUtil.close(pdfStream); + } + return result; + } + + public static List> pdfToImagesForTask(InputStream pdfStream, String imagePath, Boolean generateFolder) { + List> result = new ArrayList<>(); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(pdfStream); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + String savePath; + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + for (int i = startPage; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + savePath = imagePath + folder + fileName; + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 144); + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + Thread.sleep(100); + // 判断图片大小 + File pic = new File(savePath); + long fileSize = pic.length() / 1024 / 1024; + if (fileSize > 3) { + fileName = fileName.replaceAll(".jpg", "") + "ys001" + ".jpg"; + imageCompression(new File(savePath), imagePath + folder + fileName); + savePath = imagePath + folder + fileName; + } + List paths = new ArrayList<>(); + paths.add(folder + fileName); + paths.add(savePath); + paths.add(fileName); + result.add(paths); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + IoUtil.close(pdfStream); + } + return result; + } + + + public static void pdfToImages3AndSaveCache(String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType,Long scannerId) { + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + String savePath; + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + for (int i = startPage; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + savePath = imagePath + folder + fileName; + BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 144); +// String key = folder + fileName; + log.info("StorageCache >> {} >> {}", fileName, com); + log.info("StorageCache >> {} >> {}", "Owner." + fileName, owner); + log.info("StorageCache >> {} >> {}", "HashKey." + fileName, hashKey); + log.info("StorageCache >> {} >> {}", "PdfUrl." + fileName, pdfPath); + StorageCache.write(fileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + fileName, owner, 1000 * 60 * 30); + StorageCache.write("HashKey." + fileName, hashKey, 1000 * 60 * 30); + StorageCache.write("CorType." + fileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + fileName, pdfPath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + fileName, scannerId, 1000 * 60 * 30); + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + + public static void pdfToImages2AndSaveCache(String oldName,String hashKey, String pdfPath, String imagePath, Boolean generateFolder, String com, Integer owner, CorporateInvoiceType corporateInvoiceType, Long scannerId, SysConfigMapper sysConfigMapper) { + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + String savePath; + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + for (int i = startPage; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + savePath = imagePath + folder + fileName; + String interfaceStr="RZ"; + BufferedImage bufferedImage = null; + SysConfig interfaceConfig =sysConfigMapper.selectByCode("OCR_INTERFACE"); + if(interfaceConfig!=null){ + interfaceStr = interfaceConfig.getValue(); + } + if(interfaceStr.equals("FH")){ + // 如果是FH接口 + bufferedImage = pdfRenderer.renderImageWithDPI(i, 288); + }else{ + bufferedImage = pdfRenderer.renderImageWithDPI(i, 144); + } +// String key = folder + fileName; + log.info("StorageCache >> {} >> {}", fileName, com); + log.info("StorageCache >> {} >> {}", "Owner." + fileName, owner); + log.info("StorageCache >> {} >> {}", "HashKey." + fileName, hashKey); + log.info("StorageCache >> {} >> {}", "PdfUrl." + fileName, pdfPath); + StorageCache.write(fileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + fileName, owner, 1000 * 60 * 30); + StorageCache.write("HashKey." + fileName, hashKey, 1000 * 60 * 30); + StorageCache.write("CorType." + fileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + fileName, pdfPath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + fileName, scannerId, 1000 * 60 * 30); + if(null!=oldName){ + StorageCache.write("oldName." + fileName, oldName, 1000 * 60 * 30); + } + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + } + + /** + * 带安全回退的 PDF 转图片(替代 pdfToImages2) + * 解决某些 CMYK+ICC+反相 Decode 的 PDF 在 PDFBox 渲染下变成空白的问题 + */ + public static List> pdfToImages2Safe(InputStream pdfStream, String imagePath, Boolean generateFolder) { + List> result = new ArrayList<>(); + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(pdfStream); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + int totalPage = readPdf.getNumberOfPages(); + String folder = ""; + if (generateFolder) { + folder = generateFolder(imagePath); + } + for (int i = 0; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String savePath = imagePath + folder + fileName; + BufferedImage bufferedImage = null; + try { + // 先按安全分辨率渲染,防止超大页面撑爆内存 + bufferedImage = renderPageSafe(readPdf, pdfRenderer, i, 192, 5000); + // 若渲染结果为几乎纯色(空白/异常),尝试提取原始图像降级 + if (isNearlyBlank(bufferedImage)) { + log.warn("Page {} rendered nearly blank, trying fallback extraction", i); + BufferedImage fallback = extractPageImageFallback(readPdf.getPage(i)); + if (fallback != null) { + bufferedImage = fallback; + } + } + } catch (Exception e) { + log.warn("Page {} render failed: {}, trying fallback", i, e.getMessage()); + try { + BufferedImage fallback = extractPageImageFallback(readPdf.getPage(i)); + if (fallback != null) { + bufferedImage = fallback; + } + } catch (Exception ex) { + log.error("Fallback also failed for page {}: {}", i, ex.getMessage(), ex); + } + } + if (bufferedImage == null) { + log.error("Failed to produce image for page {}", i); + continue; + } + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + Thread.sleep(100); + // 判断图片大小 + File pic = new File(savePath); + long fileSize = pic.length() / 1024 / 1024; + if (fileSize > 3) { + fileName = fileName.replaceAll(".jpg", "") + "ys001" + ".jpg"; + imageCompression(new File(savePath), imagePath + folder + fileName); + savePath = imagePath + folder + fileName; + } + List paths = new ArrayList<>(); + paths.add(folder + fileName); + paths.add(savePath); + paths.add(fileName); + result.add(paths); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + IoUtil.close(pdfStream); + } + return result; + } + + /** + * 安全渲染:对超大页面自动降低 DPI,防止 OOM + */ + private static BufferedImage renderPageSafe(PDDocument doc, PDFRenderer renderer, int pageIndex, float targetDpi, int maxPixels) throws IOException { + PDPage page = doc.getPage(pageIndex); + float maxPt = Math.max(page.getMediaBox().getWidth(), page.getMediaBox().getHeight()); + float safeDpi = Math.min(targetDpi, maxPixels * 72f / maxPt); + return renderer.renderImageWithDPI(pageIndex, safeDpi, ImageType.RGB); + } + + /** + * 判断图片是否几乎为纯色(视为空白/渲染失败) + */ + private static boolean isNearlyBlank(BufferedImage image) { + if (image == null) { + return true; + } + int w = image.getWidth(); + int h = image.getHeight(); + int step = Math.max(1, (int) Math.sqrt((double) w * h / 2000)); + int min = 255, max = 0; + for (int y = 0; y < h; y += step) { + for (int x = 0; x < w; x += step) { + int rgb = image.getRGB(x, y); + int v = ((rgb >> 16) & 0xFF) + ((rgb >> 8) & 0xFF) + (rgb & 0xFF); + v = v / 3; + if (v < min) { + min = v; + } + if (v > max) { + max = v; + } + if (max - min > 10) { + return false; + } + } + } + return true; + } + + /** + * 降级提取:从页面资源中直接提取最大的图像 XObject, + * 绕过 PDFBox 渲染,避免 CMYK+Decode 反相导致的空白 + */ + private static BufferedImage extractPageImageFallback(PDPage page) { + if (page == null || page.getResources() == null) { + return null; + } + try { + PDImageXObject bestImage = null; + int bestArea = 0; + for (COSName name : page.getResources().getXObjectNames()) { + PDXObject xobj = page.getResources().getXObject(name); + if (xobj instanceof PDImageXObject) { + PDImageXObject img = (PDImageXObject) xobj; + int area = img.getWidth() * img.getHeight(); + if (area > bestArea) { + bestArea = area; + bestImage = img; + } + } + } + if (bestImage == null) { + return null; + } + // 先尝试读取原始流(绕过 PDFBox 的颜色转换,保留原始 JPEG 数据) + COSStream stream = bestImage.getCOSObject(); + byte[] rawBytes; + try (InputStream in = stream.createRawInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) != -1) { + baos.write(buf, 0, n); + } + rawBytes = baos.toByteArray(); + } + BufferedImage decoded = ImageIO.read(new ByteArrayInputStream(rawBytes)); + if (decoded == null) { + // ImageIO 无法识别,回退到 PDFBox 自带解码 + decoded = bestImage.getImage(); + } + if (decoded == null) { + return null; + } + // 统一转成 RGB + if (decoded.getType() != BufferedImage.TYPE_INT_RGB && decoded.getType() != BufferedImage.TYPE_INT_ARGB) { + BufferedImage rgb = new BufferedImage(decoded.getWidth(), decoded.getHeight(), BufferedImage.TYPE_INT_RGB); + Graphics2D g = rgb.createGraphics(); + g.drawImage(decoded, 0, 0, null); + g.dispose(); + return rgb; + } + return decoded; + } catch (Exception e) { + log.warn("Extract fallback image failed: {}", e.getMessage(), e); + return null; + } + } + + public static String generateFolder(String uploadPath) { + String newUploadPath = uploadPath; + if (!newUploadPath.endsWith(File.separator)) { + newUploadPath += File.separator; + } + String format = "opt" + DateFormat.format(DateFormat.DatePatternType.FORMAT_yyyyMM); + String newPath = newUploadPath + format + File.separator; + if (!FileUtil.isDirectory(newPath)) { + FileUtil.mkdir(newPath); + } + return format + File.separator; + } + + public static String generateFolderWithTitle(String uploadPath,String title) { + String newUploadPath = uploadPath; + if (!newUploadPath.endsWith(File.separator)) { + newUploadPath += File.separator; + } + String format = title + DateFormat.format(DateFormat.DatePatternType.FORMAT_yyyyMM); + String newPath = newUploadPath + format + File.separator; + if (!FileUtil.isDirectory(newPath)) { + FileUtil.mkdir(newPath); + } + return format + File.separator; + } + + public static String generateFolderXml(String uploadPath) { + String newUploadPath = uploadPath; + if (!newUploadPath.endsWith(File.separator)) { + newUploadPath += File.separator; + } + String format = "xml_" + DateFormat.format(DateFormat.DatePatternType.FORMAT_yyyyMM); + String newPath = newUploadPath + format + File.separator; + if (!FileUtil.isDirectory(newPath)) { + FileUtil.mkdir(newPath); + } + return format + File.separator; + } + + public static String generateFolderNoFileSep(String uploadPath) { + String newUploadPath = uploadPath; + if (!newUploadPath.endsWith(File.separator)) { + newUploadPath += File.separator; + } + String format = "opt" + DateFormat.format(DateFormat.DatePatternType.FORMAT_yyyyMM); + String newPath = newUploadPath + format + File.separator; + if (!FileUtil.isDirectory(newPath)) { + FileUtil.mkdir(newPath); + } + return format; + } + + public static String generateFolderNoFilePo(String uploadPath) { + String newUploadPath = uploadPath; + if (!newUploadPath.endsWith(File.separator)) { + newUploadPath += File.separator; + } + String format = "po" + DateFormat.format(DateFormat.DatePatternType.FORMAT_yyyyMM); + String newPath = newUploadPath + format + File.separator; + if (!FileUtil.isDirectory(newPath)) { + FileUtil.mkdir(newPath); + } + return format; + } + + + @Data + public static class MileageItem { + private String itemDate; + private String reason; + private String from; + private String to; + private String mileage; + private String source; + private String recMileage; + + public MileageItem() { + } + + public MileageItem(String itemDate, String reason, String from, String to, String mileage, String source, String recMileage) { + this.itemDate = itemDate; + this.reason = reason; + this.from = from; + this.to = to; + this.mileage = mileage; + this.source = source; + this.recMileage = recMileage; + } + } + + /** + * 图片压缩 + * + * @param fileName + * @param fileNewName + * @throws Exception + */ + public static void imageCompression(File fileName, String fileNewName) throws Exception { + float quality = 0.0005f; + FileInputStream fis = new FileInputStream(fileName); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + byte[] data = bos.toByteArray(); + bos.close(); + ByteArrayInputStream byteInput = new ByteArrayInputStream(data); + BufferedImage image = ImageIO.read(byteInput); + + // 得到指定Format图片的writer(迭代器) + Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); + // 得到writer + ImageWriter writer = (ImageWriter) iter.next(); + // 得到指定writer的输出参数设置(ImageWriteParam ) + ImageWriteParam iwp = writer.getDefaultWriteParam(); + // 设置可否压缩 + iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + // 设置压缩质量参数 + iwp.setCompressionQuality(quality); + + iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED); + + ColorModel colorModel = ColorModel.getRGBdefault(); + // 指定压缩时使用的色彩模式 + iwp.setDestinationType( + new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16))); + + // 开始打包图片,写入byte[] + // 取得内存输出流 + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + IIOImage iIamge = new IIOImage(image, null, null); + + // 此处因为ImageWriter中用来接收write信息的output要求必须是ImageOutput + // 通过ImageIo中的静态方法,得到byteArrayOutputStream的ImageOutput + writer.setOutput(ImageIO.createImageOutputStream(byteArrayOutputStream)); + writer.write(null, iIamge, iwp); + FileOutputStream fileOutputStream = null; + fileOutputStream = new FileOutputStream(fileNewName); + fileOutputStream.write(byteArrayOutputStream.toByteArray()); + fileOutputStream.close(); + //imgBytes = byteArrayOutputStream.toByteArray(); + } + + + public static void generateImageForCredit (CreditItem creditItem, String templatePath, String savePath) throws IOException { + + HtmlToImage.setData("creditItem", creditItem); + HtmlToImage.useFilepath(templatePath); + HtmlToImage.init(); + int height = 900; + HtmlToImage.generate("creditTemplate.html", savePath, 1000, height, 0.9f); + } + + + + public static String pdf2OnePageImage(String pdfPath,String uploadPath,SysConfigMapper sysConfigMapper){ + PDDocument readPdf = null; + try { + readPdf = PDDocument.load(new File(pdfPath)); + PDFRenderer pdfRenderer = new PDFRenderer(readPdf); + String savePath; + int width = 0; + int height = 0; + int totalPage = readPdf.getNumberOfPages(); + int startPage = 0; + String folder = ""; + folder = generateFolder(uploadPath); + // 统计各页宽度和高度 + List listImage = new ArrayList(); + for (int i = startPage; i < totalPage; i++) { + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + savePath = uploadPath + folder + fileName; + String interfaceStr="RZ"; + BufferedImage bufferedImage = null; + SysConfig interfaceConfig =sysConfigMapper.selectByCode("OCR_INTERFACE"); + if(interfaceConfig!=null){ + interfaceStr = interfaceConfig.getValue(); + } + if(interfaceStr.equals("FH")){ + // 如果是FH接口 + bufferedImage = pdfRenderer.renderImageWithDPI(i, 288); + }else{ + bufferedImage = pdfRenderer.renderImageWithDPI(i, 144); + } + + int newWidth = bufferedImage.getWidth(); + if (newWidth > width) + width = newWidth; + height += bufferedImage.getHeight(); + listImage.add(bufferedImage); + +// String key = folder + fileName; +// log.info("StorageCache >> {} >> {}", fileName, com); +// log.info("StorageCache >> {} >> {}", "Owner." + fileName, owner); +// log.info("StorageCache >> {} >> {}", "HashKey." + fileName, hashKey); +// log.info("StorageCache >> {} >> {}", "PdfUrl." + fileName, pdfPath); +// StorageCache.write(fileName, com, 1000 * 60 * 30); +// StorageCache.write("Owner." + fileName, owner, 1000 * 60 * 30); +// StorageCache.write("HashKey." + fileName, hashKey, 1000 * 60 * 30); +// StorageCache.write("CorType." + fileName, corporateInvoiceType, 1000 * 60 * 30); +// StorageCache.write("PdfUrl." + fileName, pdfPath, 1000 * 60 * 30); +// StorageCache.write("scannerLogs." + fileName, scannerId, 1000 * 60 * 30); + ImageIO.write(bufferedImage, "JPG", new File(savePath)); + } + + // 绘制合成图像 + BufferedImage jpgImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + // 复制图片到缓冲流中 + Graphics2D grap = jpgImage.createGraphics(); + // 清除背景 + grap.setColor(Color.white); + + // 开始将内容填充 + int top = 0; + for (int i = 0; i < listImage.size(); i++) { + BufferedImage image = listImage.get(i); + int newWidth = image.getWidth(); + int newHeight = image.getHeight(); + grap.drawImage(image, 0, top, newWidth, newHeight, null); + top += image.getHeight(); + + } + + // 释放图像资源 + grap.dispose(); + + // 将绘制的图像生成至输出流 + String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String jpgFile = uploadPath + folder + fileName; + + ImageIO.write(jpgImage, /*"GIF"*/ "JPG" /* format desired */ , new File(jpgFile) /* target */ ); + return folder + fileName; + // 通过 HF AI 接口解析 形式发票 + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + IoUtil.close(readPdf); + } + return ""; + } + + public static void mergePdf(String mergePath,List pdfsPath){ +// File outputFile = new File(mergePath); // 输出文件 + + PDFMergerUtility pdfMerger = new PDFMergerUtility(); + try { + for (String file : pdfsPath) { + pdfMerger.addSource(new File(file)); // 添加每个源文件 + } + pdfMerger.setDestinationFileName(mergePath); // 设置输出文件路径 + pdfMerger.mergeDocuments(null); // 合并文档 + System.out.println("PDF合并完成!"); + } catch (IOException e) { + e.printStackTrace(); + } + } + +// public static BigDecimal scaleJpg(File sourceFile,float scale,String destPath){ +// try { +// //图片所在路径 +// BufferedImage templateImage = ImageIO.read(sourceFile); +// +// +// //原始图片的长度和宽度 +// int height = templateImage.getHeight(); +// int width = templateImage.getWidth(); +// +// //通过比例压缩 +// +// //通过固定长度压缩 +// /*int doWithHeight = 100; +// int dowithWidth = 300;*/ +// +// //压缩之后的长度和宽度 +// int doWithHeight = (int) (scale * height); +// int dowithWidth = (int) (scale * width); +// +// BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB); +// +// finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); +// +// +// //图片输出路径,以及图片名 +// FileOutputStream fileOutputStream = new FileOutputStream(destPath); +// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream); +// encoder.encode(finalImage); +// fileOutputStream.close(); +// +// BigDecimal result = new BigDecimal(new File(destPath).length()).divide(new BigDecimal(1024*1024),2,BigDecimal.ROUND_HALF_UP); +// return result; +// } catch (IOException e) { +// log.error("===========压缩文件异常{},to,{}",destPath,e.getMessage()); +// } +// return null; +// } + + + // 图片转Base64(自动识别MIME类型) + public static String fileToBase64(File imageFile) throws IOException { + String mimeType = java.nio.file.Files.probeContentType(imageFile.toPath()); + if(mimeType == null) { + mimeType = getMimeTypeByExtension(imageFile.getName()); + } + return "data:" + mimeType + ";base64," + + Base64Util.fileToBase64((imageFile)); + } + + // 根据文件扩展名获取MIME类型 + private static String getMimeTypeByExtension(String fileName) { + String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); + switch (extension) { + case "jpg": case "jpeg": return "image/jpeg"; + case "png": return "image/png"; + case "gif": return "image/gif"; + case "pdf": return "application/pdf"; + default: return "application/octet-stream"; + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Ccitt.java b/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Ccitt.java new file mode 100644 index 0000000..8b9c2fe --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Ccitt.java @@ -0,0 +1,356 @@ +package com.cmsen.ticket.domain.util; + +import org.apache.pdfbox.cos.COSName; +import org.apache.pdfbox.io.MemoryUsageSetting; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDResources; +import org.apache.pdfbox.pdmodel.graphics.PDXObject; +import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; +import org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +/** + * 扫描件 PDF 清晰压缩工具,兼容 Apache PDFBox 2.0.25。 + * + *

适用场景:公文、通知、表格、名单、黑白扫描件。

+ * + *

核心思路:

+ *

1. 不再使用 JPEG 压缩,因为 JPEG 会让小字出现块状失真、笔画粘连;

+ *

2. 把扫描图转成黑白二值图,文字变成纯黑,背景变成纯白;

+ *

3. 使用 CCITT Group 4 压缩,这是传真/扫描文档常用的黑白无损压缩方式;

+ *

4. 如果原始分辨率下仍超过 10MB,再逐步降低图片尺寸。

+ * + *

注意:这种方式会丢失彩色和灰度信息,红章、照片、阴影会变成黑白。

+ */ +public final class PdfCompressorPdfbox2Ccitt { + + /** 固定输入、输出路径:直接运行 main 方法即可,按需修改 */ + private static final String INPUT_PDF = "D:/123.pdf"; + private static final String OUTPUT_PDF = "D:/zip123.pdf"; + + /** 目标上限:10MB */ + private static final long MAX_SIZE_BYTES = 10L * 1024 * 1024; + + /** + * PDFBox 处理大 PDF 时使用的临时目录。 + * 压缩结束后会在 finally 中统一删除,不保留临时文件。 + */ + private static final File PDFBOX_TEMP_DIR = + new File(System.getProperty("java.io.tmpdir"), "pdf-compress-temp"); + + /** + * 缩放比例候选。 + * CCITT G4 是黑白文档压缩,通常 1.0 或 0.90 就能比较小; + * 如果你的文件仍超过 10MB,再逐步降到 0.80、0.70。 + */ + private static final float[] SCALE_CANDIDATES = { + 1.00f, 0.95f, 0.90f, 0.85f, 0.80f, 0.70f, 0.60f + }; + + /** + * 自适应阈值的窗口半径。 + * 值越大,背景估计越平滑;值越小,适合局部光照变化明显的扫描件。 + */ + private static final int ADAPTIVE_RADIUS = 24; + + /** + * 阈值偏移。 + * 数值越大,文字越容易变黑;如果文字断笔,可调大到 18~22; + * 如果背景脏点太多,可调小到 8~12。 + */ + private static final int THRESHOLD_OFFSET = 22; + + private PdfCompressorPdfbox2Ccitt() { + } + + public static void main(String[] args) throws Exception { + File input = new File(INPUT_PDF); + File output = new File(OUTPUT_PDF); + + if (!input.isFile()) { + System.err.println("输入文件不存在: " + input); + System.exit(1); + } + + compress(input, output); + } + + public static void compress(File input, File output) throws IOException { + try { + long srcSize = input.length(); + if (srcSize <= MAX_SIZE_BYTES) { + Files.copy(input.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING); + System.out.printf("源文件 %.2f MB <= 10MB,无需压缩,直接输出到 %s%n", mb(srcSize), output); + return; + } + + System.out.printf("源文件 %.2f MB > 10MB,开始 CCITT G4 黑白清晰压缩...%n", mb(srcSize)); + System.out.printf("共检测到 %d 张图片。%n", countImages(input)); + + byte[] bestBytes = null; + float bestScale = -1f; + + for (float scale : SCALE_CANDIDATES) { + byte[] data = tryCompress(input, scale); + System.out.printf(" [scale=%.2f] CCITT G4 -> %.2f MB %s%n", + scale, mb(data.length), data.length <= MAX_SIZE_BYTES ? "(达标)" : "(超标)"); + + if (data.length <= MAX_SIZE_BYTES) { + bestBytes = data; + bestScale = scale; + break; + } + } + + if (bestBytes == null) { + throw new IOException("CCITT G4 黑白压缩后仍无法降到 10MB 以内。" + + "可以继续增加更低缩放比例,例如 0.50、0.45," + + "或者改用 OCR 重建文字版 PDF。"); + } + + writeOutputSafely(input, output, bestBytes); + System.out.printf("压缩完成:缩放比例=%.2f,输出 %.2f MB -> %s%n", + bestScale, mb(output.length()), output); + } finally { + // 无论成功、失败还是中途异常,都尽量清理 PDFBox 内部临时文件目录 + cleanPdfboxTempDir(); + } + } + + private static byte[] tryCompress(File input, float scale) throws IOException { + try (PDDocument doc = PDDocument.load(input, tempFileOnlySetting())) { + for (PDPage page : doc.getPages()) { + replaceImages(doc, page.getResources(), scale); + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + doc.save(baos); + return baos.toByteArray(); + } finally { + System.gc(); + } + } + + private static void replaceImages(PDDocument doc, PDResources resources, float scale) throws IOException { + if (resources == null) { + return; + } + + for (COSName name : resources.getXObjectNames()) { + PDXObject xo = resources.getXObject(name); + if (xo instanceof PDImageXObject) { + PDImageXObject oldImage = (PDImageXObject) xo; + + BufferedImage source = oldImage.getImage(); + BufferedImage binary = toAdaptiveBinary(source, scale); + + // 使用 CCITT Group 4 写入黑白图,文字边缘不会产生 JPEG 块状失真 + PDImageXObject newImage = CCITTFactory.createFromImage(doc, binary); + resources.put(name, newImage); + } else if (xo instanceof PDFormXObject) { + replaceImages(doc, ((PDFormXObject) xo).getResources(), scale); + } + } + } + + private static int countImages(File input) throws IOException { + try (PDDocument doc = PDDocument.load(input, tempFileOnlySetting())) { + int count = 0; + for (PDPage page : doc.getPages()) { + count += countImages(page.getResources()); + } + return count; + } + } + + private static int countImages(PDResources resources) throws IOException { + if (resources == null) { + return 0; + } + + int count = 0; + for (COSName name : resources.getXObjectNames()) { + PDXObject xo = resources.getXObject(name); + if (xo instanceof PDImageXObject) { + count++; + } else if (xo instanceof PDFormXObject) { + count += countImages(((PDFormXObject) xo).getResources()); + } + } + return count; + } + + /** + * 转成自适应黑白二值图。 + * + *

为什么不用固定阈值 128:

+ *

扫描件不同区域亮度可能不同,固定阈值容易让淡字丢失,或让背景噪点变黑。 + * 自适应阈值会根据每个像素周围的平均亮度判断黑白,后半部分扫描质量较差时更稳。

+ */ + private static BufferedImage toAdaptiveBinary(BufferedImage src, float scale) { + BufferedImage gray = toGray(src); + if (scale < 0.999f) { + gray = scaleImage(gray, scale, BufferedImage.TYPE_BYTE_GRAY); + } + + int w = gray.getWidth(); + int h = gray.getHeight(); + int[] pixels = new int[w * h]; + + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int rgb = gray.getRGB(x, y); + pixels[y * w + x] = rgb & 0xff; + } + } + + long[] integral = buildIntegral(pixels, w, h); + BufferedImage binary = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY); + + for (int y = 0; y < h; y++) { + int y1 = Math.max(0, y - ADAPTIVE_RADIUS); + int y2 = Math.min(h - 1, y + ADAPTIVE_RADIUS); + + for (int x = 0; x < w; x++) { + int x1 = Math.max(0, x - ADAPTIVE_RADIUS); + int x2 = Math.min(w - 1, x + ADAPTIVE_RADIUS); + + int area = (x2 - x1 + 1) * (y2 - y1 + 1); + int localAvg = (int) (sum(integral, w, x1, y1, x2, y2) / area); + int value = pixels[y * w + x]; + + // 比局部背景暗 enough 的像素判为黑色。 + // 这样淡字会保留,白底噪点通常会被清掉。 + boolean black = value < localAvg - THRESHOLD_OFFSET; + binary.setRGB(x, y, black ? 0x000000 : 0xffffff); + } + } + + return binary; + } + + private static long[] buildIntegral(int[] pixels, int w, int h) { + long[] integral = new long[(w + 1) * (h + 1)]; + for (int y = 1; y <= h; y++) { + long rowSum = 0; + for (int x = 1; x <= w; x++) { + rowSum += pixels[(y - 1) * w + (x - 1)]; + integral[y * (w + 1) + x] = integral[(y - 1) * (w + 1) + x] + rowSum; + } + } + return integral; + } + + private static long sum(long[] integral, int w, int x1, int y1, int x2, int y2) { + int stride = w + 1; + int ax = x1; + int ay = y1; + int bx = x2 + 1; + int by = y2 + 1; + + return integral[by * stride + bx] + - integral[ay * stride + bx] + - integral[by * stride + ax] + + integral[ay * stride + ax]; + } + + private static BufferedImage toGray(BufferedImage src) { + BufferedImage out = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_GRAY); + Graphics2D g = out.createGraphics(); + g.drawImage(src, 0, 0, null); + g.dispose(); + return out; + } + + private static BufferedImage scaleImage(BufferedImage src, float scale, int type) { + int w = Math.max(1, Math.round(src.getWidth() * scale)); + int h = Math.max(1, Math.round(src.getHeight() * scale)); + + BufferedImage out = new BufferedImage(w, h, type); + Graphics2D g = out.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.drawImage(src, 0, 0, w, h, null); + g.dispose(); + return out; + } + + private static void writeOutputSafely(File input, File output, byte[] bytes) throws IOException { + boolean samePath = output.getCanonicalFile().equals(input.getCanonicalFile()); + if (!samePath) { + Files.write(output.toPath(), bytes); + return; + } + + File temp = File.createTempFile("pdfcompress_", ".tmp", input.getParentFile()); + try { + Files.write(temp.toPath(), bytes); + Files.move(temp.toPath(), output.toPath(), + StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } finally { + if (temp.exists()) { + Files.deleteIfExists(temp.toPath()); + } + } + } + + /** + * 创建 PDFBox 临时文件策略,并指定统一临时目录。 + * 这样 PDFBox 内部临时文件不会散落在系统临时目录中,便于最后统一清理。 + */ + private static MemoryUsageSetting tempFileOnlySetting() throws IOException { + if (!PDFBOX_TEMP_DIR.exists() && !PDFBOX_TEMP_DIR.mkdirs()) { + throw new IOException("创建 PDFBox 临时目录失败: " + PDFBOX_TEMP_DIR); + } + + MemoryUsageSetting setting = MemoryUsageSetting.setupTempFileOnly(); + setting.setTempDir(PDFBOX_TEMP_DIR); + return setting; + } + + /** + * 清理 PDFBox 临时目录。 + */ + private static void cleanPdfboxTempDir() { + deleteDirectoryQuietly(PDFBOX_TEMP_DIR); + } + + /** + * 静默递归删除文件或目录。 + * 删除失败不抛出异常,避免影响主流程返回。 + */ + private static void deleteDirectoryQuietly(File file) { + if (file == null || !file.exists()) { + return; + } + + if (file.isDirectory()) { + File[] children = file.listFiles(); + if (children != null) { + for (File child : children) { + deleteDirectoryQuietly(child); + } + } + } + + try { + Files.deleteIfExists(file.toPath()); + } catch (IOException ignored) { + // 删除失败不影响主流程 + } + } + + private static double mb(long bytes) { + return bytes / 1048576.0; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Color.java b/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Color.java new file mode 100644 index 0000000..997b829 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/PdfCompressorPdfbox2Color.java @@ -0,0 +1,353 @@ +package com.cmsen.ticket.domain.util; + +import org.apache.pdfbox.cos.COSName; +import org.apache.pdfbox.io.MemoryUsageSetting; +import org.apache.pdfbox.multipdf.PDFMergerUtility; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDResources; +import org.apache.pdfbox.pdmodel.graphics.PDXObject; +import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; +import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.List; + +/** + * 保留彩色的 PDF 清晰压缩工具,兼容 Apache PDFBox 2.0.25。 + * + *

适用场景:彩色附件(如 efiles.TYPE=3002)需要压缩但不可转黑白的 PDF。

+ * + *

核心思路:

+ *

1. 二值图(CCITT/黑白,bitsPerComponent=1)保持原样,不参与重编码;

+ *

2. 彩色/灰度图先按最大边长限制(MAX_IMAGE_DIMENSION,默认2000px)等比缩小, + * 控制图片物理尺寸,再使用 JPEG 重编码,按质量递减(0.85→0.45)再按尺寸递减(1.0→0.3)循环尝试, + * 直到输出不超过目标大小(默认 10MB);

+ *

3. 源文件本身不超过目标大小且不含超长边彩色图时直接复制;含超尺寸彩色图时即使文件小也会重编码缩小。

+ * + *

另提供 mergePdfs 用于把多个 PDF 合并成一个。

+ */ +public final class PdfCompressorPdfbox2Color { + + /** 目标上限:10MB */ + private static final long DEFAULT_MAX_SIZE_BYTES = 10L * 1024 * 1024; + + /** + * 彩色图片最大边长(像素)。 + * 超过该值的彩色/灰度图会先按比例缩小到长边=该值,避免生成 PDF 中图片分辨率过大。 + * 需要更小/更大时调整此常量即可。 + */ + private static final int MAX_IMAGE_DIMENSION = 2000; + + /** + * 缩放比例候选。 + * 优先在不缩小图片的前提下靠 JPEG 质量压缩,不够再逐步缩小。 + */ + private static final float[] SCALE_CANDIDATES = { + 1.00f, 0.90f, 0.80f, 0.70f, 0.60f, 0.50f, 0.40f, 0.30f + }; + + /** JPEG 质量候选 */ + private static final float[] QUALITY_CANDIDATES = { + 0.85f, 0.75f, 0.65f, 0.55f, 0.45f + }; + + /** + * PDFBox 处理大 PDF 时使用的临时目录。 + * 压缩结束后会在 finally 中统一删除,不保留临时文件。 + */ + private static final File PDFBOX_TEMP_DIR = + new File(System.getProperty("java.io.tmpdir"), "pdf-color-compress-temp"); + + private PdfCompressorPdfbox2Color() { + } + + /** + * 保留彩色压缩到 10MB 以内 + */ + public static void compress(File input, File output) throws IOException { + compress(input, output, DEFAULT_MAX_SIZE_BYTES); + } + + /** + * 保留彩色压缩到 maxSizeBytes 以内。 + * 源文件不超过 maxSizeBytes 时直接复制。 + * + * @param input 输入 PDF + * @param output 输出 PDF + * @param maxSizeBytes 目标大小上限(字节) + */ + public static void compress(File input, File output, long maxSizeBytes) throws IOException { + try { + long srcSize = input.length(); + // 文件本身不超目标且不存在超长边彩色图时才直接复制; + // 若含长边超过 MAX_IMAGE_DIMENSION 的彩色图,即使文件很小也要重编码缩小尺寸 + if (srcSize <= maxSizeBytes && !hasOversizedColorImage(input)) { + Files.copy(input.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING); + return; + } + + byte[] bestBytes = null; + float bestScale = -1f; + float bestQuality = -1f; + + for (float scale : SCALE_CANDIDATES) { + for (float quality : QUALITY_CANDIDATES) { + byte[] data = tryCompress(input, scale, quality); + if (data.length <= maxSizeBytes) { + bestBytes = data; + bestScale = scale; + bestQuality = quality; + break; + } + } + if (bestBytes != null) { + break; + } + } + + if (bestBytes == null) { + throw new IOException("保留彩色压缩后仍无法降到 " + (maxSizeBytes / 1048576) + "MB 以内," + + "可以考虑继续降低缩放比例或减少附件页数。"); + } + + writeOutputSafely(input, output, bestBytes); + System.out.printf("彩色压缩完成:scale=%.2f, quality=%.2f, %.2f MB -> %.2f MB, 输出: %s%n", + bestScale, bestQuality, srcSize / 1048576.0, output.length() / 1048576.0, output); + } finally { + // 无论成功、失败还是中途异常,都尽量清理 PDFBox 内部临时文件目录 + cleanPdfboxTempDir(); + } + } + + /** + * 合并多个 PDF 到一个文件(按传入顺序拼接页面) + * + * @param sources 输入 PDF 列表 + * @param dest 输出 PDF + */ + public static void mergePdfs(List sources, File dest) throws IOException { + PDFMergerUtility merger = new PDFMergerUtility(); + for (File src : sources) { + merger.addSource(src); + } + merger.setDestinationFileName(dest.getAbsolutePath()); + try { + merger.mergeDocuments(tempFileOnlySetting()); + } finally { + cleanPdfboxTempDir(); + } + } + + /** + * 扫描 PDF 中是否存在长边超过 MAX_IMAGE_DIMENSION 的彩色/灰度图(二值图不计)。 + * 用于决定文件本身不超目标大小时是直接复制还是需要重编码缩小。 + */ + private static boolean hasOversizedColorImage(File input) throws IOException { + try (PDDocument doc = PDDocument.load(input, tempFileOnlySetting())) { + for (PDPage page : doc.getPages()) { + if (hasOversizedColorImageInResources(page.getResources())) { + return true; + } + } + } finally { + cleanPdfboxTempDir(); + } + return false; + } + + private static boolean hasOversizedColorImageInResources(PDResources resources) throws IOException { + if (resources == null) { + return false; + } + for (COSName name : resources.getXObjectNames()) { + PDXObject xo = resources.getXObject(name); + if (xo instanceof PDImageXObject) { + PDImageXObject img = (PDImageXObject) xo; + // 二值图(CCITT 黑白)不参与尺寸限制 + if (img.getBitsPerComponent() == 1 + || img.getCOSObject().getBoolean(COSName.IMAGE_MASK, false)) { + continue; + } + if (Math.max(img.getWidth(), img.getHeight()) > MAX_IMAGE_DIMENSION) { + return true; + } + } else if (xo instanceof PDFormXObject) { + if (hasOversizedColorImageInResources(((PDFormXObject) xo).getResources())) { + return true; + } + } + } + return false; + } + + private static byte[] tryCompress(File input, float scale, float quality) throws IOException { + try (PDDocument doc = PDDocument.load(input, tempFileOnlySetting())) { + for (PDPage page : doc.getPages()) { + replaceImages(doc, page.getResources(), scale, quality); + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + doc.save(baos); + return baos.toByteArray(); + } finally { + System.gc(); + } + } + + private static void replaceImages(PDDocument doc, PDResources resources, float scale, float quality) throws IOException { + if (resources == null) { + return; + } + + for (COSName name : resources.getXObjectNames()) { + PDXObject xo = resources.getXObject(name); + if (xo instanceof PDImageXObject) { + PDImageXObject oldImage = (PDImageXObject) xo; + + // 二值图(CCITT 黑白页)与模板图保持原样,只压缩彩色/灰度图 + if (oldImage.getBitsPerComponent() == 1 + || oldImage.getCOSObject().getBoolean(COSName.IMAGE_MASK, false)) { + continue; + } + + try { + BufferedImage source = oldImage.getImage(); + if (source == null) { + continue; + } + // 1) 先按最大边长限制做基础缩放,控制图片物理尺寸(长边不超过 MAX_IMAGE_DIMENSION) + BufferedImage scaled = toRgb(source); + float baseScale = baseScaleFor(source.getWidth(), source.getHeight()); + if (baseScale < 0.999f) { + scaled = scaleImage(scaled, baseScale); + } + // 2) 再按压缩循环的 scale 进一步缩小(仅当压缩不掉体积时需要) + if (scale < 0.999f) { + scaled = scaleImage(scaled, scale); + } + PDImageXObject newImage = JPEGFactory.createFromImage(doc, scaled, quality); + resources.put(name, newImage); + } catch (Exception e) { + // 单张图片处理失败时保留原图,不影响其他图片 + } + } else if (xo instanceof PDFormXObject) { + replaceImages(doc, ((PDFormXObject) xo).getResources(), scale, quality); + } + } + } + + /** + * 统一转成无透明通道的 RGB 图,避免 JPEG 不支持 alpha 及 CMYK 等特殊类型导致的问题 + */ + private static BufferedImage toRgb(BufferedImage src) { + if (src.getType() == BufferedImage.TYPE_INT_RGB) { + return src; + } + BufferedImage out = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB); + Graphics2D g = out.createGraphics(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, src.getWidth(), src.getHeight()); + g.drawImage(src, 0, 0, null); + g.dispose(); + return out; + } + + /** + * 计算长边不超过 MAX_IMAGE_DIMENSION 所需的基础缩放比例; + * 本身不超过上限时返回 1.0,不做缩放。 + */ + private static float baseScaleFor(int width, int height) { + int maxDim = Math.max(width, height); + if (maxDim <= MAX_IMAGE_DIMENSION) { + return 1f; + } + return (float) MAX_IMAGE_DIMENSION / maxDim; + } + + private static BufferedImage scaleImage(BufferedImage src, float scale) { + int w = Math.max(1, Math.round(src.getWidth() * scale)); + int h = Math.max(1, Math.round(src.getHeight() * scale)); + + BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + Graphics2D g = out.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.drawImage(src, 0, 0, w, h, null); + g.dispose(); + return out; + } + + private static void writeOutputSafely(File input, File output, byte[] bytes) throws IOException { + boolean samePath = output.getCanonicalFile().equals(input.getCanonicalFile()); + if (!samePath) { + Files.write(output.toPath(), bytes); + return; + } + + File temp = File.createTempFile("pdfcolorcompress_", ".tmp", input.getParentFile()); + try { + Files.write(temp.toPath(), bytes); + Files.move(temp.toPath(), output.toPath(), + StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } finally { + if (temp.exists()) { + Files.deleteIfExists(temp.toPath()); + } + } + } + + /** + * 创建 PDFBox 临时文件策略,并指定统一临时目录。 + * 这样 PDFBox 内部临时文件不会散落在系统临时目录中,便于最后统一清理。 + */ + private static MemoryUsageSetting tempFileOnlySetting() throws IOException { + if (!PDFBOX_TEMP_DIR.exists() && !PDFBOX_TEMP_DIR.mkdirs()) { + throw new IOException("创建 PDFBox 临时目录失败: " + PDFBOX_TEMP_DIR); + } + + MemoryUsageSetting setting = MemoryUsageSetting.setupTempFileOnly(); + setting.setTempDir(PDFBOX_TEMP_DIR); + return setting; + } + + /** + * 清理 PDFBox 临时目录。 + */ + private static void cleanPdfboxTempDir() { + deleteDirectoryQuietly(PDFBOX_TEMP_DIR); + } + + /** + * 静默递归删除文件或目录。 + * 删除失败不抛出异常,避免影响主流程返回。 + */ + private static void deleteDirectoryQuietly(File file) { + if (file == null || !file.exists()) { + return; + } + + if (file.isDirectory()) { + File[] children = file.listFiles(); + if (children != null) { + for (File child : children) { + deleteDirectoryQuietly(child); + } + } + } + + try { + Files.deleteIfExists(file.toPath()); + } catch (IOException ignored) { + // 删除失败不影响主流程 + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/PdfHeaderZipUtil.java b/src/main/java/com/cmsen/ticket/domain/util/PdfHeaderZipUtil.java new file mode 100644 index 0000000..fc74efc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/PdfHeaderZipUtil.java @@ -0,0 +1,109 @@ +package com.cmsen.ticket.domain.util; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 报告头附件「3002彩色 / 非3002灰白」分组合并压缩工具。 + * 从 InvoiceServiceImpl.addFilesLogForHeaderColor 抽出的纯文件处理逻辑, + * 不依赖 Spring/DB/配置,便于本地 main 方法直接测试。 + */ +public class PdfHeaderZipUtil { + + /** 压缩上限:10M */ + private static final long MAX_BYTES = 10L * 1024 * 1024; + + /** + * 分组合并压缩附件图片,返回最终pdf的磁盘绝对路径。 + * + * @param colorFilesPath 3002彩色附件路径列表(与生产 files.FILE_PATH 同格式,路径需含 /img/,供 toPdf 定位磁盘文件) + * @param grayFilesPath 非3002附件路径列表 + * @param colorFilesType 彩色附件类型列表(与 colorFilesPath 一一对应,一般 "N") + * @param grayFilesType 灰白附件类型列表(与 grayFilesPath 一一对应,一般 "N") + * @param uploadPath 图片所在磁盘根目录(生产对应 file.filepath 配置) + * @param outDir 最终pdf输出目录(磁盘绝对路径) + * @param correctFlag 修色开关 0-不修色 1-修色(生产对应 CorrectFlag 配置) + * @param zipEnabled 是否压缩(生产对应 header_file_zip=1) + * @return 最终pdf磁盘绝对路径;无有效附件时返回 null + */ + public static String mergeAndZip(List colorFilesPath, List grayFilesPath, + List colorFilesType, List grayFilesType, + String uploadPath, String outDir, + String correctFlag, boolean zipEnabled) throws IOException { + boolean hasColor = colorFilesPath != null && !colorFilesPath.isEmpty(); + boolean hasGray = grayFilesPath != null && !grayFilesPath.isEmpty(); + if (!hasColor && !hasGray) { + return null; + } + //空参防御,保证后续逻辑不因 null 报错 + if (colorFilesPath == null) { colorFilesPath = new ArrayList<>(); } + if (grayFilesPath == null) { grayFilesPath = new ArrayList<>(); } + if (colorFilesType == null) { colorFilesType = new ArrayList<>(); } + if (grayFilesType == null) { grayFilesType = new ArrayList<>(); } + + String folder = Pdf2JpgHelper.generateFolderNoFileSep(outDir); + String pdfFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + + UUID.randomUUID().toString().replace("-", "") + ".pdf"; + String dirPath = outDir + File.separator + folder + File.separator; + String pdfFilePath = dirPath + pdfFileName; + + if (!zipEnabled) { + //不需要压缩,直接合并所有图片为一个pdf + List allPaths = new ArrayList<>(colorFilesPath); + allPaths.addAll(grayFilesPath); + List allTypes = new ArrayList<>(colorFilesType); + allTypes.addAll(grayFilesType); + FileImgUtil.toPdf(allPaths, uploadPath, pdfFilePath, allTypes, correctFlag); + return pdfFilePath; + } + + //需要压缩:最终压缩文件统一命名为 zip+pdfFileName + String finalPath = dirPath + "zip" + pdfFileName; + if (hasColor && hasGray) { + //3002彩色附件与非3002附件分别合并、分别压缩,最后合并成一个pdf + String colorPdfPath = dirPath + "c_" + pdfFileName; + String grayPdfPath = dirPath + "g_" + pdfFileName; + String colorZipPath = dirPath + "cz_" + pdfFileName; + String grayZipPath = dirPath + "gz_" + pdfFileName; + String mergedPath = dirPath + "m_" + pdfFileName; + + FileImgUtil.toPdf(colorFilesPath, uploadPath, colorPdfPath, colorFilesType, correctFlag); + FileImgUtil.toPdf(grayFilesPath, uploadPath, grayPdfPath, grayFilesType, correctFlag); + + //3002彩色附件:保留彩色压缩 + PdfCompressorPdfbox2Color.compress(new File(colorPdfPath), new File(colorZipPath)); + //其他附件:CCITT黑白压缩 + PdfCompressorPdfbox2Ccitt.compress(new File(grayPdfPath), new File(grayZipPath)); + + //两个压缩后的pdf合并成最终pdf + PdfCompressorPdfbox2Color.mergePdfs( + Arrays.asList(new File(colorZipPath), new File(grayZipPath)), new File(mergedPath)); + + File merged = new File(mergedPath); + if (merged.length() > MAX_BYTES) { + //合并后仍大于10M,再次压缩(二值页保持原样,仅压缩彩色页) + PdfCompressorPdfbox2Color.compress(merged, new File(finalPath), MAX_BYTES); + } else { + FileImgUtil.copyFileCover(mergedPath, finalPath, true); + } + + //清理中间文件 + FileImgUtil.delFile(colorPdfPath); + FileImgUtil.delFile(grayPdfPath); + FileImgUtil.delFile(colorZipPath); + FileImgUtil.delFile(grayZipPath); + FileImgUtil.delFile(mergedPath); + } else if (hasColor) { + //只有3002彩色附件:保留彩色压缩 + FileImgUtil.toPdf(colorFilesPath, uploadPath, pdfFilePath, colorFilesType, correctFlag); + PdfCompressorPdfbox2Color.compress(new File(pdfFilePath), new File(finalPath)); + } else { + //只有非3002附件:CCITT黑白压缩 + FileImgUtil.toPdf(grayFilesPath, uploadPath, pdfFilePath, grayFilesType, correctFlag); + PdfCompressorPdfbox2Ccitt.compress(new File(pdfFilePath), new File(finalPath)); + } + return finalPath; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/PendantHotMountJsAdapter.java b/src/main/java/com/cmsen/ticket/domain/util/PendantHotMountJsAdapter.java new file mode 100644 index 0000000..d7fdcb7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/PendantHotMountJsAdapter.java @@ -0,0 +1,121 @@ +/** + * +--------------------------------------------------------- + * | Author Jared.Yan + * +--------------------------------------------------------- + * | Copyright (c) http://cmsen.com All rights reserved. + * +--------------------------------------------------------- + */ +package com.cmsen.ticket.domain.util; + +import lombok.extern.slf4j.Slf4j; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.Reader; +import java.util.Map; + +/** + * 挂件热载JS适配器 + * + * @author jared.Yan (yanhuaiwen@163.com) + */ +@Slf4j +public class PendantHotMountJsAdapter { + + private final ScriptEngineManager manager; + private ScriptEngine engine; + + public PendantHotMountJsAdapter() { + manager = new ScriptEngineManager(); + engine = manager.getEngineByName("nashorn"); + } + + public PendantHotMountJsAdapter(String script) { + this(); + setScript(script); + } + + public PendantHotMountJsAdapter(Reader reader) { + this(); + setScript(reader); + } + + public PendantHotMountJsAdapter(File file) { + this(); + setScript(file); + } + + public void setMimeType(String mimeType) { + manager.registerEngineMimeType(mimeType, engine.getFactory()); + } + + public void setExtensionType(String extension) { + manager.registerEngineExtension(extension, engine.getFactory()); + } + + public void setEngineByName(String engineName) { + engine = manager.getEngineByName(engineName); + } + + public void setScript(String script) { + if (script != null) { + try { + engine.eval(script); + } catch (ScriptException e) { + log.error(e.getMessage(), e); + } + } + } + + public void setScript(Reader reader) { + if (reader != null) { + try { + engine.eval(reader); + } catch (ScriptException e) { + log.error(e.getMessage(), e); + } + } + } + + public void setScript(File file) { + if (file != null) { + try { + this.setScript(new FileReader(file)); + } catch (FileNotFoundException e) { + log.error(e.getMessage(), e); + } + } + } + + /** + * 设置变量,脚本执行的Java语言绑定 + */ + public void setVariable(Map bindings) { + if (bindings != null) { + for (Map.Entry bindingEntry : bindings.entrySet()) { + this.engine.put(bindingEntry.getKey(), bindingEntry.getValue()); + } + } + } + + public void setVariable(String key, Object value) { + this.engine.put(key, value); + } + + public ScriptEngine getEngine() { + return engine; + } + + public Object invoke(String methodName, Object... args) throws ScriptException, NoSuchMethodException { + if (engine instanceof Invocable) { + Invocable invoke = (Invocable) engine; + return invoke.invokeFunction(methodName, args); + } + return null; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/PicUtils.java b/src/main/java/com/cmsen/ticket/domain/util/PicUtils.java new file mode 100644 index 0000000..281418c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/PicUtils.java @@ -0,0 +1,192 @@ +package com.cmsen.ticket.domain.util; +import lombok.extern.slf4j.Slf4j; +import net.coobird.thumbnailator.Thumbnails; +import org.apache.commons.io.FileUtils; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +@Slf4j +public class PicUtils { + // 以下是常量,按照阿里代码开发规范,不允许代码中出现魔法值 + private static final Integer ZERO = 0; + private static final Integer ONE_ZERO_TWO_FOUR = 1024; + private static final Integer NINE_ZERO_ZERO = 900; + private static final Integer THREE_TWO_SEVEN_FIVE = 3275; + private static final Integer TWO_ZERO_FOUR_SEVEN = 2047; + private static final Double ZERO_EIGHT_FIVE = 0.85; + private static final Double ZERO_SIX = 0.6; + private static final Double ZERO_FOUR_FOUR = 0.44; + private static final Double ZERO_FOUR = 0.4; + + /** + * 根据指定大小压缩图片 + * + * @param imageBytes 源图片字节数组 + * @param desFileSize 指定图片大小,单位kb + * @return 压缩质量后的图片字节数组 + */ + public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) { + if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) { + return imageBytes; + } + long srcSize = imageBytes.length; + double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR); + try { + while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) { + ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length); + Thumbnails.of(inputStream) + .scale(accuracy) + .outputQuality(accuracy) + .toOutputStream(outputStream); + imageBytes = outputStream.toByteArray(); + } + log.info("图片原大小={}kb | 压缩后大小={}kb", + srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR); + } catch (Exception e) { + log.error("【图片压缩】msg=图片压缩失败!", e); + } + return imageBytes; + } + + + public static boolean byteToImage(byte[] resource,String filePath){ + try { + // 2. 创建输入流 + InputStream inputStream = new ByteArrayInputStream(resource); + + // 3. 读取图片 + BufferedImage image = ImageIO.read(inputStream); + + // 4. 创建输出文件 + File outputFile = new File(filePath); + + // 5. 写入图片 + ImageIO.write(image, "jpg", outputFile); + return true; + }catch (Exception e){ + log.error("异常==>{}",e.getMessage()); + e.printStackTrace(); + } + return false; + } + + /** + * 自动调节精度(经验数值) + * + * @param size 源图片大小 + * @return 图片压缩质量比 + */ + private static double getAccuracy(long size) { + double accuracy; + if (size < NINE_ZERO_ZERO) { + accuracy = ZERO_EIGHT_FIVE; + } else if (size < TWO_ZERO_FOUR_SEVEN) { + accuracy = ZERO_SIX; + } else if (size < THREE_TWO_SEVEN_FIVE) { + accuracy = ZERO_FOUR_FOUR; + } else { + accuracy = ZERO_FOUR; + } + return accuracy; + } + + public static byte[] fileToByteArray(String filePath) { + try { + File file = new File(filePath); + return FileUtils.readFileToByteArray(file); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + + public static List compressImages(List sourceImages,int size){ + List list = new ArrayList<>(); + for (String sourceImage : sourceImages) { + File file = new File(sourceImage); + if (!file.exists()){ + continue; + } + String newPath = sourceImage.substring(0,sourceImage.lastIndexOf("."))+"1"; + String endFix = sourceImage.substring(sourceImage.lastIndexOf(".")); + String newFinalPath = newPath+endFix; + byte[] sByte = fileToByteArray(sourceImage); + byte[] dByte = compressPicForScale(sByte,size); + byteToImage(dByte,newFinalPath); + list.add(newFinalPath); + } + return list; + } + + + public static String compressV2(String source,int dpi,int lastSize){ + String resultPath = null; + File pdfPath = new File(source); + String parentPath = pdfPath.getParent()+File.separator; + String fileName = pdfPath.getName(); + String jpgName = fileName.toLowerCase().replace(".pdf",".jpg"); + String targetName = fileName.toLowerCase().replace(".pdf","_1.pdf"); + resultPath = parentPath+targetName; + try { + if(pdfPath.exists()){ + // pdf存在 则 将pdf 分解成多个 jpg + List stepOnes = Pdf2JpgHelper.pdfToImages(pdfPath.getAbsolutePath(),parentPath,dpi); + if(!stepOnes.isEmpty()){ + // 对图片进行 一一压缩 + List stepTwos = PicUtils.compressImages(stepOnes,lastSize); + for (String stepOne : stepOnes) { + File del = new File(stepOne); + if(del.exists()){ + del.delete(); + } + } + if(!stepTwos.isEmpty()){ + // 将图片合成pdf + for (int i = 0; i < stepTwos.size(); i++) { + String jpgFile = stepTwos.get(i); + if(i==0){ + // 将第一页转成pdf + FileImgUtil.jpg2PDF(jpgFile,resultPath); + }else{ + ImageToPDF.addJpg2PDF(resultPath,jpgFile); + } + } + FileImgUtil.merge(stepTwos.toArray(new String[stepTwos.size()]),"jpg",parentPath+jpgName); + FileImgUtil.jpg2PDF(parentPath+jpgName,resultPath); + for (String stepOne : stepTwos) { + File del = new File(stepOne); + if(del.exists()){ + del.delete(); + } + } + if(pdfPath.exists()){ + pdfPath.delete(); + } + } + } + } + return targetName; + }catch (Exception e){ + e.printStackTrace(); + }finally { + File img = new File(parentPath+jpgName); + if(img.exists()){ + img.delete(); + } + } + return null; + } + + + + public static void main(String[] args) { + File file = new File("D:\\test\\test.jpg"); + System.out.println(file.getParent()); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/ReflectionUtil.java b/src/main/java/com/cmsen/ticket/domain/util/ReflectionUtil.java new file mode 100644 index 0000000..df320b3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/ReflectionUtil.java @@ -0,0 +1,208 @@ +/******************************************************************************* + * Copyright (c) 2005, 2014 springside.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + *******************************************************************************/ +package com.cmsen.ticket.domain.util; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; +import org.apache.commons.lang3.reflect.ConstructorUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * 反射工具类. + * + * 所有反射均无视modifier的范围限制,同时将反射的Checked异常转为UnChecked异常。 + * + * 1. 对于构造函数,直接使用本类即可 + * + * 2. 对于方法调用,本类全部是一次性调用的简化方法,如果考虑性能,对反复调用的方法应使用 MethodInvoker 及 FastMethodInvoker. + * + * 3. 对于直接属性访问,恰当使用本类中的一次性调用,和基于预先获取的Field对象反复调用两种做法. + */ +@SuppressWarnings("unchecked") +public class ReflectionUtil { + + /////////// 属性相关函数 /////////// + /** + * 调用Getter方法, 无视private/protected修饰符. + */ + public static T invokeGetter(Object obj, String propertyName) { + Method method = ClassUtil.getGetterMethod(obj.getClass(), propertyName); + if (method == null) { + throw new IllegalArgumentException( + "Could not find getter method [" + propertyName + "] on target [" + obj + ']'); + } + return (T) invokeMethod(obj, method); + } + + /** + * 调用Setter方法, 无视private/protected修饰符, 按传入value的类型匹配函数. + */ + public static void invokeSetter(Object obj, String propertyName, Object value) { + Method method = ClassUtil.getSetterMethod(obj.getClass(), propertyName, value.getClass()); + if (method == null) { + throw new IllegalArgumentException( + "Could not find getter method [" + propertyName + "] on target [" + obj + ']'); + } + invokeMethod(obj, method, value); + } + + /** + * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. + */ + public static T getFieldValue(final Object obj, final String fieldName) { + Field field = ClassUtil.getAccessibleField(obj.getClass(), fieldName); + if (field == null) { + throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + ']'); + } + return getFieldValue(obj, field); + } + + /** + * 使用已获取的Field, 直接读取对象属性值, 不经过getter函数. + */ + public static T getFieldValue(final Object obj, final Field field) { + try { + return (T) field.get(obj); + } catch (Exception e) { + throw convertReflectionExceptionToUnchecked(e); + } + } + + /** + * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. + */ + public static void setFieldValue(final Object obj, final String fieldName, final Object value) { + Field field = ClassUtil.getAccessibleField(obj.getClass(), fieldName); + if (field == null) { + throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + ']'); + } + setField(obj, field, value); + } + + /** + * 使用已获取的Field, 直接读取对象属性值, 不经过setter函数. + */ + public static void setField(final Object obj, Field field, final Object value) { + try { + field.set(obj, value); + } catch (Exception e) { + throw convertReflectionExceptionToUnchecked(e); + } + } + + /** + * 先尝试用Getter函数读取, 如果不存在则直接读取变量. + */ + public static T getProperty(Object obj, String propertyName) { + Method method = ClassUtil.getGetterMethod(obj.getClass(), propertyName); + if (method != null) { + try { + return (T) method.invoke(obj, ArrayUtils.EMPTY_OBJECT_ARRAY); + } catch (Exception e) { + throw convertReflectionExceptionToUnchecked(e); + } + } else { + return (T) getFieldValue(obj, propertyName); + } + } + + /** + * 先尝试用Setter函数写入, 如果不存在则直接写入变量, 按传入value的类型匹配函数. + */ + public static void setProperty(Object obj, String propertyName, final Object value) { + Method method = ClassUtil.getSetterMethod(obj.getClass(), propertyName, value.getClass()); + if (method != null) { + try { + method.invoke(obj, value); + } catch (Exception e) { + throw convertReflectionExceptionToUnchecked(e); + } + } else { + setFieldValue(obj, propertyName, value); + } + } + + /////////// 方法相关函数 //////////// + /** + * 直接调用对象方法, 无视private/protected修饰符. + * + * 根据传入参数的实际类型进行匹配 + */ + public static T invokeMethod(Object obj, String methodName, Object... args) { + Object[] theArgs = ArrayUtils.nullToEmpty(args); + final Class[] parameterTypes = ClassUtils.toClass(theArgs); + return (T) invokeMethod(obj, methodName, theArgs, parameterTypes); + } + + /** + * 直接调用对象方法, 无视private/protected修饰符. + * + * 根据定义的参数类型进行匹配 + */ + public static T invokeMethod(final Object obj, final String methodName, final Object[] args, + final Class[] parameterTypes) { + Method method = ClassUtil.getAccessibleMethod(obj.getClass(), methodName, parameterTypes); + if (method == null) { + throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + ']'); + } + return invokeMethod(obj, method, args); + } + + /** + * 直接调用对象方法, 无视private/protected修饰符 + * + * 只匹配函数名,如果有多个同名函数调用第一个. 用于确信只有一个同名函数, 但参数类型不确定的情况 + */ + public static T invokeMethodByName(final Object obj, final String methodName, final Object[] args) { + Method method = ClassUtil.getAccessibleMethodByName(obj.getClass(), methodName); + if (method == null) { + throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + ']'); + } + return invokeMethod(obj, method, args); + } + + /** + * 调用已准备好的Method + */ + public static T invokeMethod(final Object obj, Method method, Object... args) { + try { + return (T) method.invoke(obj, args); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + ////////// 构造函数 //////// + /** + * 调用构造函数. + */ + public static T invokeConstructor(final Class cls, Object... args) { + try { + return ConstructorUtils.invokeConstructor(cls, args); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /////// 辅助函数 //////// + + /** + * 将反射时的checked exception转换为unchecked exception. + */ + public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { + if ((e instanceof IllegalAccessException) || (e instanceof NoSuchMethodException)) { + return new IllegalArgumentException(e); + } else if (e instanceof InvocationTargetException) { + return new RuntimeException(((InvocationTargetException) e).getTargetException()); + } else if (e instanceof RuntimeException) { + return (RuntimeException) e; + } + return new RuntimeException(e); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/SmsUtil.java b/src/main/java/com/cmsen/ticket/domain/util/SmsUtil.java new file mode 100644 index 0000000..aac2f72 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/SmsUtil.java @@ -0,0 +1,105 @@ +package com.cmsen.ticket.domain.util; + +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.http.ClientHttp; +import com.cmsen.common.http.ClientHttpRequest; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.http.ContentEnctype; +import lombok.extern.slf4j.Slf4j; + +/** + * @author ran hao yu + * @date 2020/8/18 9:43 + * @description + */ +@Slf4j +public class SmsUtil { + //产品名称:云通信短信API产品,开发者无需替换 + static final String product = "Dysmsapi"; + //产品域名,开发者无需替换 + static final String domain = "dysmsapi.aliyuncs.com"; + static final String accessKeyId = "LTAI4GEGPcuoBaDCHDNMDGpa"; + static final String accessKeySecret = "UhUQoTJkEcsESBa2uLK1xEymImlkvl"; + static final String SignName = "login"; + static final String TemplateCode = "SMS_199772891"; + + /*public static void sendSms(String PhoneNumbers,Integer verifyCode){ + DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(domain); + request.setSysVersion("2017-05-25"); + request.setSysAction("SendSms"); + request.putQueryParameter("RegionId", "cn-hangzhou"); + request.putQueryParameter("PhoneNumbers", PhoneNumbers); + request.putQueryParameter("SignName", SignName); + request.putQueryParameter("TemplateCode", TemplateCode); + request.putQueryParameter("TemplateParam", "{code:"+verifyCode+"}"); + try { + CommonResponse response = client.getCommonResponse(request); + } catch (ClientException e) { + log.error(e.getMessage(),e); + } + }*/ + public static void sendSms(String PhoneNumbers, Integer verifyCode, String sendSmsUrl, String sendSmsSign) { + /** + * POST http://msg.chengqitong.cn/msg =2022/12/15 修改为=>http://sms.vicdia.com/msg + * 参数: + * + * phone:手机号 + * content: 要发送的短信内容【发票助手】 + * code: 密钥(7f39651096af52cb174337238916277e) + */ + try { + log.info("Send Message >> {} >> verified code >> {}", PhoneNumbers, verifyCode); + ClientHttpRequest request = new ClientHttpRequest(); + request.setUrl(sendSmsUrl); + request.setHeaders("Centent-Type", ContentEnctype.JSON); + request.setTimeOut(400000); + request.setParams("phone", PhoneNumbers); + request.setParams("content", "尊敬的用户,您的验证码为:" + verifyCode + ",验证码有效期为五分钟。【"+sendSmsSign+"】"); + request.setParams("code", "7f39651096af52cb174337238916277e"); + ClientHttpResponse post = ClientHttp.post(request); + if (post.isSuccess()) { + log.info("Send Message Result >> Success"); + } else { + log.info("Send Message Result >> Failure >> {}", post); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } + + public static void sendMeeingUrl(String PhoneNumbers, String content, String sendSmsUrl) { + /** + * POST http://msg.chengqitong.cn/msg =2022/12/15 修改为=>http://sms.vicdia.com/msg + * 参数: + * + * phone:手机号 + * content: 要发送的短信内容【会议签到】 + * code: 密钥(7f39651096af52cb174337238916277e) + */ + try { + log.info("Send MeeingUrl >> {} >> content >> {}", PhoneNumbers, content); + ClientHttpRequest request = new ClientHttpRequest(); + request.setUrl(sendSmsUrl); + request.setHeaders("Centent-Type", ContentEnctype.JSON); + request.setTimeOut(400000); + request.setParams("phone", PhoneNumbers); + request.setParams("content", content + "【易合宝】"); + request.setParams("code", "7f39651096af52cb174337238916277e"); + ClientHttpResponse post = ClientHttp.post(request); + if (post.isSuccess()) { + log.info("Send MeeingUrl Result >> Success"); + } else { + log.info("Send MeeingUrl Result >> Failure >> {}", post); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new ServiceException("系统错误"); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/TimeExchange.java b/src/main/java/com/cmsen/ticket/domain/util/TimeExchange.java new file mode 100644 index 0000000..5ae279b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/TimeExchange.java @@ -0,0 +1,133 @@ +package com.cmsen.ticket.domain.util; + +import lombok.extern.slf4j.Slf4j; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 时间转化工具 date转为时间戳 时间戳转date 互相与String的转换 + * 所有出现的String time 格式都必须为(yyyy-MM-dd HH:mm:ss),否则出错 + * + * @author ran hao yu + */ +@Slf4j +public class TimeExchange { + + /** + * String(yyyy-MM-dd HH:mm:ss) 转 Date + * + * @param time + * @return + * @throws ParseException + */ + // String date = "2010/05/04 12:34:23"; + public static Date StringToDate(String time) throws ParseException { + + Date date = new Date(); + // 注意format的格式要与日期String的格式相匹配 + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + date = dateFormat.parse(time); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + + return date; + } + + /** + * Date转为String(yyyy-MM-dd HH:mm:ss) + * + * @param time + * @return + */ + public static String DateToString(Date time) { + String dateStr = ""; + Date date = new Date(); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss"); + try { + dateStr = dateFormat.format(time); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return dateStr; + } + + /** + * String(yyyy-MM-dd HH:mm:ss)转10位时间戳 + * + * @param time + * @return + */ + public static Integer StringToTimestamp(String time) { + + int times = 0; + try { + times = (int) ((Timestamp.valueOf(time).getTime()) / 1000); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return times; + + } + + /** + * 10位int型的时间戳转换为String(yyyy-MM-dd HH:mm:ss) + * + * @param time + * @return + */ + public static String timestampToString(Integer time) { + //int转long时,先进行转型再进行计算,否则会是计算结束后在转型 + long temp = (long) time * 1000; + Timestamp ts = new Timestamp(temp); + String tsStr = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + //方法一 + tsStr = dateFormat.format(ts); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return tsStr; + } + + /** + * 10位时间戳转Date + * + * @param time + * @return + */ + public static Date TimestampToDate(Integer time) { + long temp = (long) time * 1000; + Timestamp ts = new Timestamp(temp); + Date date = new Date(); + try { + date = ts; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return date; + } + + /** + * Date类型转换为10位时间戳 + * + * @param time + * @return + */ + public static Integer DateToTimestamp(Date time) { + Timestamp ts = new Timestamp(time.getTime()); + + return (int) ((ts.getTime()) / 1000); + } + + public static Integer getNowSecond() { + return (int) (System.currentTimeMillis() / 1000); + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/WeekIntervalUtil.java b/src/main/java/com/cmsen/ticket/domain/util/WeekIntervalUtil.java new file mode 100644 index 0000000..9ef10ff --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/WeekIntervalUtil.java @@ -0,0 +1,92 @@ +package com.cmsen.ticket.domain.util; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAdjusters; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 获取从现在往前5个周的时间区间 + */ +public class WeekIntervalUtil { + // 定义日期格式化器,统一输出格式 + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + public static void main(String[] args) { + // 获取从现在往前5个周的区间列表 + int count = 5; + int begin = (3-1) * count; + + List weekIntervals = getPreviousWeeksInterval(begin,count); + + // 输出结果 + System.out.println("从现在往前5个周的时间区间:"); + for (int i = 0; i < weekIntervals.size(); i++) { + System.out.printf("第%d周:%s%n", (i + 1), weekIntervals.get(i)); + } + } + + /** + * 获取周的时间区间(周一至周日) + * begin:从现在往后的第几周,本周的话为0,往下依次+1;Count:取的周数量 + * @return 包含周区间的列表,格式如:2026-01-12 ~ 2026-01-18 + */ + public static List getPreviousWeeksInterval(int begin, int count) { + List weekIntervals = new ArrayList<>(); + LocalDate currentDate = LocalDate.now(); // 获取当前本地日期 + + // 循环5次,获取往前5个周的区间 + for (int i = begin; i < begin+count; i++) { + // 计算当前循环对应的日期(每次往前推i周) + LocalDate targetDate = currentDate.minusWeeks(i); + + // 调整到该周的周一(本周起始) + LocalDate weekStart = targetDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); + // 调整到该周的周日(本周结束) + LocalDate weekEnd = targetDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); + + // 格式化并拼接区间字符串 + String interval = String.format("%s~%s", + weekStart.format(DATE_FORMATTER), + weekEnd.format(DATE_FORMATTER)); + weekIntervals.add(interval); + } + + return weekIntervals; + } + + /** + * 重载方法:支持传入字符串日期(如"2026-01-13"),自动转换为LocalDate + * @param dateStr 日期字符串,格式需为yyyy-MM-dd + * @return 周范围Map + */ + public static Map getWeekRange(String dateStr) { + // 转换字符串为LocalDate + LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER); + return getWeekRange(date); + } + + /** + * 根据指定日期,获取该日期所在周的范围(周一至周日) + * @param date 任意日期(LocalDate类型) + * @return Map,包含"weekStart"(周一)、"weekEnd"(周日),值为格式化后的字符串 + */ + public static Map getWeekRange(LocalDate date) { + Map weekRange = new HashMap<>(); + + // 调整到本周的周一(如果date已经是周一,直接返回;否则返回上一个周一) + LocalDate weekStart = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); + // 调整到本周的周日(如果date已经是周日,直接返回;否则返回下一个周日) + LocalDate weekEnd = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); + + // 格式化并存入Map + weekRange.put("weekStart", weekStart.format(DATE_FORMATTER)); + weekRange.put("weekEnd", weekEnd.format(DATE_FORMATTER)); + + return weekRange; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/ZipUtils.java b/src/main/java/com/cmsen/ticket/domain/util/ZipUtils.java new file mode 100644 index 0000000..b77d2e3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/ZipUtils.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.domain.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ZipUtils { + public static void unzip(String zipFilePath, String destDir) throws IOException { + File dir = new File(destDir); + if (!dir.exists()) dir.mkdirs(); // 确保目标目录存在 :ml-citation{ref="6,7" data="citationList"} + + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + String filePath = destDir + File.separator + entry.getName(); + File file = new File(filePath); + + if (entry.isDirectory()) { + file.mkdirs(); // 创建子目录 :ml-citation{ref="5,7" data="citationList"} + } else { + extractFile(zis, file); // 解压文件内容 + } + zis.closeEntry(); + } + } + } + + private static void extractFile(ZipInputStream zis, File file) throws IOException { + try (FileOutputStream fos = new FileOutputStream(file)) { + file.getParentFile().mkdirs(); // 确保父目录存在 :ml-citation{ref="3,5" data="citationList"} + byte[] buffer = new byte[1024]; + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } + } +} + diff --git a/src/main/java/com/cmsen/ticket/domain/util/hly/DownloadPicFromUrlReport.java b/src/main/java/com/cmsen/ticket/domain/util/hly/DownloadPicFromUrlReport.java new file mode 100644 index 0000000..50411f1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/hly/DownloadPicFromUrlReport.java @@ -0,0 +1,215 @@ +package com.cmsen.ticket.domain.util.hly; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +import java.io.*; + +import static com.cmsen.ticket.domain.util.hly.FileUtils.downloadPicture; + + +public class DownloadPicFromUrlReport { + + private static final Logger LOGGER = LoggerFactory.getLogger(DownloadPicFromUrlReport.class); + + + public static String httpGetFile(CloseableHttpClient client,String imgUrl,String savePath) throws IOException { + // 发送get请求 + HttpGet request = new HttpGet(imgUrl); + // 设置请求和传输超时时间 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(50000).setConnectTimeout(50000).build(); + + //设置请求头 + request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" ); +// request.setHeader("Token",token); + request.setConfig(requestConfig); + try { + CloseableHttpResponse response = client.execute(request); + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + HttpEntity entity = response.getEntity(); + InputStream in2 = entity.getContent(); + FileUtils.copyInputStreamToFile(in2, new File(savePath)); + InputStream in = new FileInputStream(savePath); + byte[] b = new byte[28]; + in.read(b, 0, 28); + String fileHead =bytesToHexString(b); + fileHead = fileHead.toUpperCase(); + if (fileHead == null || fileHead.length() == 0) { + return ""; + } + in.close(); + return null; + } + }catch (Exception e){ + LOGGER.error("下载附件错误====》{}",e.getMessage()); + e.printStackTrace(); + return "error"; + }finally { + + request.releaseConnection(); + } + return null; + } + + + public static String httpGetImg(CloseableHttpClient client,String imgUrl,String savePath) throws IOException { + // 发送get请求 + HttpGet request = new HttpGet(imgUrl); + // 设置请求和传输超时时间 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(50000).setConnectTimeout(50000).build(); + + //设置请求头 + request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" ); +// request.setHeader("Token",token); + request.setConfig(requestConfig); + try { + CloseableHttpResponse response = client.execute(request); + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + HttpEntity entity = response.getEntity(); + InputStream in2 = entity.getContent(); + FileUtils.copyInputStreamToFile(in2, new File(savePath)); + InputStream in = new FileInputStream(savePath); + byte[] b = new byte[28]; + in.read(b, 0, 28); + String fileHead =bytesToHexString(b); + fileHead = fileHead.toUpperCase(); + if (fileHead == null || fileHead.length() == 0) { + return ""; + } + in.close(); + FileType[] fileTypes = FileType.values(); + + for (FileType type : fileTypes) { + if (fileHead.startsWith(type.getValue())) { +// LOGGER.info("fileType:===="+fileHead); + //FileUtils.copyInputStreamToFile(in2, new File(savePath+"."+type)); + File f = new File(savePath); + f.renameTo(new File(savePath+"."+type)); + return type.toString(); + } + } + // 出现大量png 格式图片无法解析到filetype + // tif 格式为主 + if(imgUrl.indexOf(".tiff")>-1){ + downloadPicture(imgUrl,savePath+".tiff"); + return "tiff"; + }else{ + if(imgUrl.indexOf(".tif")>-1){ + downloadPicture(imgUrl,savePath+".tif"); + return "tif"; + } + } + return null; + } + }catch (Exception e){ + LOGGER.error("下载附件错误====》{}",e.getMessage()); + e.printStackTrace(); + return "error"; + }finally { + + request.releaseConnection(); + } + return null; + } + + /** + * 根据URL返回Base64 + * @param client + * @param imgUrl + * @return + * @throws IOException + */ + public static String httpGetBase64(CloseableHttpClient client, String imgUrl) throws IOException { + // 发送get请求 + HttpGet request = new HttpGet(imgUrl); + // 设置请求和传输超时时间 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(50000).setConnectTimeout(50000).build(); + + //设置请求头 + request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" ); +// request.setHeader("Token",token); + request.setConfig(requestConfig); + try { + byte[] data = null; + CloseableHttpResponse response = client.execute(request); + + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + HttpEntity entity = response.getEntity(); + + InputStream in2 = entity.getContent(); + + // 读取图片字节数组 + try { + + data = readInputStream(in2); + in2.read(data); + in2.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + // 返回Base64编码过的字节数组字符串 + return Base64Utils.encodeToString(data); + } finally { + request.releaseConnection(); + } + } + + /** + * 从输入流中获取数据 + * @param fis 输入流 + * @return + * @throws Exception + */ + private static byte[] readInputStream(InputStream fis) throws IOException { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len; + while( (len=fis.read(buffer)) != -1 ){ + outStream.write(buffer, 0, len); + } + //fis.close();此处一定不能关闭流 + return outStream.toByteArray(); + } + /** + * 将文件头转换成16进制字符串 + * + * @return 16进制字符串 + */ + private static String bytesToHexString(byte[] src){ + + StringBuilder stringBuilder = new StringBuilder(); + if (src == null || src.length <= 0) { + return null; + } + for (int i = 0; i < src.length; i++) { + int v = src[i] & 0xFF; + String hv = Integer.toHexString(v); + if (hv.length() < 2) { + stringBuilder.append(0); + } + stringBuilder.append(hv); + } + return stringBuilder.toString(); + } + + public static void main(String []asd) throws Exception { + String url = "https://helioscloud-uat.huilianyi.com/6e1bb3ff-9efb-46cf-b84c-da3656e189f3/invoices/%EF%BF%A5138%E8%AF%9D%E8%B4%B976805874-93de2022-82ff-4f29-a1ce-5725786d9fe8.pdf?response-content-disposition=attachment%3B%20filename%3D%22%EF%BF%A5138%20%E8%AF%9D%E8%B4%B9.pdf%22&response-content-type=application%2Foctet-stream&x-oss-date=20260630T082007Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI5t8sxFz6VDJcmNUhFYia%2F20260630%2Fcn-shanghai%2Foss%2Faliyun_v4_request&x-oss-signature=0bf1ac7ae9c8fe6dd00a2ee3fee342bf3dda3d6627b4613d2f94f9bb38faec2f"; + CloseableHttpClient client = null; + client = new SSLClientReport(url); + url = url.replace("&", "&"); + String fileName = "E:/test"; + String fileType = DownloadPicFromUrlReport.httpGetImg(client, url, fileName); + + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/hly/FileType.java b/src/main/java/com/cmsen/ticket/domain/util/hly/FileType.java new file mode 100644 index 0000000..0a28c50 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/hly/FileType.java @@ -0,0 +1,179 @@ +package com.cmsen.ticket.domain.util.hly; + +/** + * @Auther: xp + * @Date: 2021-09-15 + * @Description: com.jeeplus.modules.concur.report.util.fileType + * @version: 1.0 + */ +public enum FileType { + + /** + * JEPG. + */ + JPEG("FFD8FF"), + + /** + * PNG. + */ + PNG("89504E47"), + + /** + * GIF. + */ + GIF("47494638"), + + /** + * TIFF. + */ + TIFF("49492A00"), + + /** + * Windows Bitmap. + */ + BMP("424D"), + + /** + * CAD. + */ + DWG("41433130"), + + /** + * Adobe Photoshop. + */ + PSD("38425053"), + + /** + * Rich Text Format. + */ + RTF("7B5C727466"), + + /** + * XML. + */ + XML("3C3F786D6C"), + + /** + * HTML. + */ + HTML("68746D6C3E"), + + /** + * Email [thorough only]. + */ + EML("44656C69766572792D646174653A"), + + /** + * Outlook Express. + */ + DBX("CFAD12FEC5FD746F"), + + /** + * Outlook (pst). + */ + PST("2142444E"), + + /** + * MS Word/Excel. + */ + XLS_DOC("D0CF11E0"), + + /** + * MS Access. + */ + MDB("5374616E64617264204A"), + + /** + * WordPerfect. + */ + WPD("FF575043"), + + /** + * Postscript. + */ + EPS("252150532D41646F6265"), + + /** + * Adobe Acrobat. + */ + PDF("255044462D312E"), + + /** + * Quicken. + */ + QDF("AC9EBD8F"), + + /** + * Windows Password. + */ + PWL("E3828596"), + + /** + * ZIP Archive. + */ + ZIP("504B0304"), + + /** + * RAR Archive. + */ + RAR("52617221"), + + /** + * Wave. + */ + WAV("57415645"), + + /** + * AVI. + */ + AVI("41564920"), + + /** + * Real Audio. + */ + RAM("2E7261FD"), + + /** + * Real Media. + */ + RM("2E524D46"), + + /** + * MPEG (mpg). + */ + MPG("000001BA"), + + /** + * Quicktime. + */ + MOV("6D6F6F76"), + + /** + * Windows Media. + */ + ASF("3026B2758E66CF11"), + + /** + * MIDI. + */ + MID("4D546864"); + + private String value = ""; + + /** + * Constructor. + * + * @param value + */ + private FileType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/hly/FileUtils.java b/src/main/java/com/cmsen/ticket/domain/util/hly/FileUtils.java new file mode 100644 index 0000000..4d3cbbd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/hly/FileUtils.java @@ -0,0 +1,784 @@ +/** + * Copyright © 2021-2026
JeePlus All rights reserved. + */ +package com.cmsen.ticket.domain.util.hly; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.StrUtil; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.PdfWriter; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.impl.client.CloseableHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; +import java.math.BigDecimal; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; + +/** + * 文件操作工具类 + * 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能 + * @author jeeplus + * @version 2021-06-21 + */ +public class FileUtils extends org.apache.commons.io.FileUtils { + private static int PAGE_MAX_HEIGHT = 14400; + private static int DECIMAL_POINT_NUM = 2; + private static int ONE_HUNDRED = 100; + + private static Logger log = LoggerFactory.getLogger(FileUtils.class); + + + + /** + * 判断是否是文件 + * @param source + */ + public static boolean isFile(String source) { + return new File(source).isFile(); + } + + /** + * 判断是否是目录 + * @param source + */ + public static boolean isFolder(String source) { + return new File(source).isDirectory(); + } + + /** + * 复制单个文件,如果目标文件存在,则不覆盖 + * @param srcFileName 待复制的文件名 + * @param descFileName 目标文件名 + * @return 如果复制成功,则返回true,否则返回false + */ + public static boolean copyFile(String srcFileName, String descFileName) { + return FileUtils.copyFileCover(srcFileName, descFileName, false); + } + + /** + * 复制单个文件 + * @param srcFileName 待复制的文件名 + * @param descFileName 目标文件名 + * @param coverlay 如果目标文件已存在,是否覆盖 + * @return 如果复制成功,则返回true,否则返回false + */ + public static boolean copyFileCover(String srcFileName, + String descFileName, boolean coverlay) { + File srcFile = new File(srcFileName); + // 判断源文件是否存在 + if (!srcFile.exists()) { + log.debug("复制文件失败,源文件 " + srcFileName + " 不存在!"); + return false; + } + // 判断源文件是否是合法的文件 + else if (!srcFile.isFile()) { + log.debug("复制文件失败," + srcFileName + " 不是一个文件!"); + return false; + } + File descFile = new File(descFileName); + // 判断目标文件是否存在 + if (descFile.exists()) { + // 如果目标文件存在,并且允许覆盖 + if (coverlay) { + log.debug("目标文件已存在,准备删除!"); + if (!FileUtils.delFile(descFileName)) { + log.debug("删除目标文件 " + descFileName + " 失败!"); + return false; + } + } else { + log.debug("复制文件失败,目标文件 " + descFileName + " 已存在!"); + return false; + } + } else { + if (!descFile.getParentFile().exists()) { + // 如果目标文件所在的目录不存在,则创建目录 + log.debug("目标文件所在的目录不存在,创建目录!"); + // 创建目标文件所在的目录 + if (!descFile.getParentFile().mkdirs()) { + log.debug("创建目标文件所在的目录失败!"); + return false; + } + } + } + + // 准备复制文件 + // 读取的位数 + int readByte = 0; + InputStream ins = null; + OutputStream outs = null; + try { + // 打开源文件 + ins = new FileInputStream(srcFile); + // 打开目标文件的输出流 + outs = new FileOutputStream(descFile); + byte[] buf = new byte[1024]; + // 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕 + while ((readByte = ins.read(buf)) != -1) { + // 将读取的字节流写入到输出流 + outs.write(buf, 0, readByte); + } + log.debug("复制单个文件 " + srcFileName + " 到" + descFileName + + "成功!"); + return true; + } catch (Exception e) { + log.debug("复制文件失败:" + e.getMessage()); + return false; + } finally { + // 关闭输入输出流,首先关闭输出流,然后再关闭输入流 + if (outs != null) { + try { + outs.close(); + } catch (IOException oute) { + oute.printStackTrace(); + } + } + if (ins != null) { + try { + ins.close(); + } catch (IOException ine) { + ine.printStackTrace(); + } + } + } + } + + /** + * 复制整个目录的内容,如果目标目录存在,则不覆盖 + * @param srcDirName 源目录名 + * @param descDirName 目标目录名 + * @return 如果复制成功返回true,否则返回false + */ + public static boolean copyDirectory(String srcDirName, String descDirName) { + return FileUtils.copyDirectoryCover(srcDirName, descDirName, + false); + } + + /** + * 复制整个目录的内容 + * @param srcDirName 源目录名 + * @param descDirName 目标目录名 + * @param coverlay 如果目标目录存在,是否覆盖 + * @return 如果复制成功返回true,否则返回false + */ + public static boolean copyDirectoryCover(String srcDirName, + String descDirName, boolean coverlay) { + File srcDir = new File(srcDirName); + // 判断源目录是否存在 + if (!srcDir.exists()) { + log.debug("复制目录失败,源目录 " + srcDirName + " 不存在!"); + return false; + } + // 判断源目录是否是目录 + else if (!srcDir.isDirectory()) { + log.debug("复制目录失败," + srcDirName + " 不是一个目录!"); + return false; + } + // 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符 + String descDirNames = descDirName; + if (!descDirNames.endsWith(File.separator)) { + descDirNames = descDirNames + File.separator; + } + File descDir = new File(descDirNames); + // 如果目标文件夹存在 + if (descDir.exists()) { + if (coverlay) { + // 允许覆盖目标目录 + log.debug("目标目录已存在,准备删除!"); + if (!FileUtils.delFile(descDirNames)) { + log.debug("删除目录 " + descDirNames + " 失败!"); + return false; + } + } else { + log.debug("目标目录复制失败,目标目录 " + descDirNames + " 已存在!"); + return false; + } + } else { + // 创建目标目录 + log.debug("目标目录不存在,准备创建!"); + if (!descDir.mkdirs()) { + log.debug("创建目标目录失败!"); + return false; + } + + } + + boolean flag = true; + // 列出源目录下的所有文件名和子目录名 + File[] files = srcDir.listFiles(); + for (int i = 0; i < files.length; i++) { + // 如果是一个单个文件,则直接复制 + if (files[i].isFile()) { + flag = FileUtils.copyFile(files[i].getAbsolutePath(), + descDirName + files[i].getName()); + // 如果拷贝文件失败,则退出循环 + if (!flag) { + break; + } + } + // 如果是子目录,则继续复制目录 + if (files[i].isDirectory()) { + flag = FileUtils.copyDirectory(files[i] + .getAbsolutePath(), descDirName + files[i].getName()); + // 如果拷贝目录失败,则退出循环 + if (!flag) { + break; + } + } + } + + if (!flag) { + log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 失败!"); + return false; + } + log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 成功!"); + return true; + + } + + /** + * + * 删除文件,可以删除单个文件或文件夹 + * + * @param fileName 被删除的文件名 + * @return 如果删除成功,则返回true,否是返回false + */ + public static boolean delFile(String fileName) { + File file = new File(fileName); + if (!file.exists()) { + log.debug(fileName + " 文件不存在!"); + return true; + } else { + if (file.isFile()) { + return FileUtils.deleteFile(fileName); + } else { + return FileUtils.deleteDirectory(fileName); + } + } + } + + /** + * + * 删除单个文件 + * + * @param fileName 被删除的文件名 + * @return 如果删除成功,则返回true,否则返回false + */ + public static boolean deleteFile(String fileName) { + File file = new File(fileName); + if (file.exists() && file.isFile()) { + if (file.delete()) { + log.debug("删除文件 " + fileName + " 成功!"); + return true; + } else { + log.debug("删除文件 " + fileName + " 失败!"); + return false; + } + } else { + log.debug(fileName + " 文件不存在!"); + return true; + } + } + + /** + * + * 删除目录及目录下的文件 + * + * @param dirName 被删除的目录所在的文件路径 + * @return 如果目录删除成功,则返回true,否则返回false + */ + public static boolean deleteDirectory(String dirName) { + String dirNames = dirName; + if (!dirNames.endsWith(File.separator)) { + dirNames = dirNames + File.separator; + } + File dirFile = new File(dirNames); + if (!dirFile.exists() || !dirFile.isDirectory()) { + log.debug(dirNames + " 目录不存在!"); + return true; + } + boolean flag = true; + // 列出全部文件及子目录 + File[] files = dirFile.listFiles(); + for (int i = 0; i < files.length; i++) { + // 删除子文件 + if (files[i].isFile()) { + flag = FileUtils.deleteFile(files[i].getAbsolutePath()); + // 如果删除文件失败,则退出循环 + if (!flag) { + break; + } + } + // 删除子目录 + else if (files[i].isDirectory()) { + flag = FileUtils.deleteDirectory(files[i] + .getAbsolutePath()); + // 如果删除子目录失败,则退出循环 + if (!flag) { + break; + } + } + } + + if (!flag) { + log.debug("删除目录失败!"); + return false; + } + // 删除当前目录 + if (dirFile.delete()) { + log.debug("删除目录 " + dirName + " 成功!"); + return true; + } else { + log.debug("删除目录 " + dirName + " 失败!"); + return false; + } + + } + + /** + * 创建单个文件 + * @param descFileName 文件名,包含路径 + * @return 如果创建成功,则返回true,否则返回false + */ + public static boolean createFile(String descFileName) { + File file = new File(descFileName); + if (file.exists()) { + log.debug("文件 " + descFileName + " 已存在!"); + return false; + } + if (descFileName.endsWith(File.separator)) { + log.debug(descFileName + " 为目录,不能创建目录!"); + return false; + } + if (!file.getParentFile().exists()) { + // 如果文件所在的目录不存在,则创建目录 + if (!file.getParentFile().mkdirs()) { + log.debug("创建文件所在的目录失败!"); + return false; + } + } + + // 创建文件 + try { + if (file.createNewFile()) { + log.debug(descFileName + " 文件创建成功!"); + return true; + } else { + log.debug(descFileName + " 文件创建失败!"); + return false; + } + } catch (Exception e) { + e.printStackTrace(); + log.debug(descFileName + " 文件创建失败!"); + return false; + } + + } + + /** + * 创建目录 + * @param descDirName 目录名,包含路径 + * @return 如果创建成功,则返回true,否则返回false + */ + public static boolean createDirectory(String descDirName) { + String descDirNames = descDirName; + if (!descDirNames.endsWith(File.separator)) { + descDirNames = descDirNames + File.separator; + } + File descDir = new File(descDirNames); + if (descDir.exists()) { + log.debug("目录 " + descDirNames + " 已存在!"); + return false; + } + // 创建目录 + if (descDir.mkdirs()) { + log.debug("目录 " + descDirNames + " 创建成功!"); + return true; + } else { + log.debug("目录 " + descDirNames + " 创建失败!"); + return false; + } + + } + + + /** + * 获取可以创建的文件名(如果有同名文件存在,参照Windows系统重命名为xxx(2).xxx) + * @param name + * @param index + * @return + */ + public static File getAvailableFile(String name, int index){ + File newFile = null; + + String suffix = StrUtil.subAfter (name, ".", true); + String filePath = StrUtil.subBefore (name, ".", true); + if(index == 0 ){ + newFile = new File(filePath+"."+suffix); + }else{ + newFile = new File(filePath+"("+index+")"+"."+suffix); + } + if(newFile.exists()){ + return getAvailableFile(name,index+1); + }else{ + return newFile; + } + }; + + /** + * 获取可以创建的目录名(如果有同名目录存在,参照Windows系统重命名为xxx(2)) + * @param name + * @param index + * @return + */ + public static File getAvailableFolder(String name, int index){ + File newFolder = null; + if(index == 0 ){ + newFolder = new File(name); + }else{ + newFolder = new File(name+"("+index+")"); + } + if(newFolder.exists()){ + return getAvailableFolder(name,index+1); + }else{ + return newFolder; + } + }; + + /** + * 写入文件 + */ + public static void writeToFile(String fileName, String content, boolean append) { + try { + FileUtils.write(new File(fileName), content, "utf-8", append); + log.debug("文件 " + fileName + " 写入成功!"); + } catch (IOException e) { + log.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); + } + } + + /** + * 写入文件 + */ + public static void writeToFile(String fileName, String content, String encoding, boolean append) { + try { + FileUtils.write(new File(fileName), content, encoding, append); + log.debug("文件 " + fileName + " 写入成功!"); + } catch (IOException e) { + log.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); + } + } + + + /** + * 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名 + * @param dirPath 目录名 + * @param file entry文件名 + * @return + */ + private static String getEntryName(String dirPath, File file) { + String dirPaths = dirPath; + if (!dirPaths.endsWith(File.separator)) { + dirPaths = dirPaths + File.separator; + } + String filePath = file.getAbsolutePath(); + // 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储 + if (file.isDirectory()) { + filePath += "/"; + } + int index = filePath.indexOf(dirPaths); + + return filePath.substring(index + dirPaths.length()); + } + + public static void downloadPicture(String imageUrl,String savePath) throws IOException { + URL url = new URL(imageUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int responseCode = connection.getResponseCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { + BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); + + FileOutputStream out = new FileOutputStream(new File(savePath)); + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + // 下载完成,关闭输入输出流 + in.close(); + out.close(); + connection.disconnect(); + + } else { + log.error("无法下载图片,响应码:" + responseCode); + } + } + + public static String fileDownLoad(String url,String savePath){ + String fileNameUrl = ""; + String fileType = ""; + CloseableHttpClient client = null; + try { + client = new SSLClientReport(url); + url = url.replace("&", "&"); + fileType = DownloadPicFromUrlReport.httpGetFile(client, url, savePath); + }catch (Exception e){ + log.error("下载pdf到本地异常:=",e.getMessage()); + e.printStackTrace(); + }finally { + if (client != null) { + try { + client.close(); + } catch (IOException e) { + log.info("图片PDF下载出错》》》》》》》》》》》》》》》》》"+savePath); + log.info(e.getMessage()); + } + } + } + return fileNameUrl+"."+fileType; + } + + public static void jpg2PDF(String filePath, String pdfPath) { + try { + // PDF文件保存地址 + // String pdfPath = "D:/Demo/ceshi/hebing.pdf"; + // 输入流 + FileOutputStream fos = new FileOutputStream(pdfPath); + // 创建文档 + Document doc = new Document(null, 0, 0, 0, 0); + //doc.open(); + // 写入PDF文档 + PdfWriter.getInstance(doc, fos); + // 读取图片流 + BufferedImage img = null; + // 实例化图片 + Image image = null; + int imgWidth=0; + int imgHeight=0; + // 循环获取图片文件夹内的图片 + //获取图片的磁盘路径地址 + // 读取图片流 +// if(filesType.get(m).equals("Y") && correctFlag.equals("1")){ +// log.info("toPdf===修正颜色=======开始"); +// // 重新保存图片修正色彩 +// String tmp=imgFilePath.substring(imgFilePath.lastIndexOf(".")); +// String nImagePath = imgFilePath.replaceAll(tmp,"2A"+tmp); +// compressPicAlibaba(imgFilePath,nImagePath); +// tmpFiles.add(nImagePath); +// // 实例化图片 +// image = com.itextpdf.text.Image.getInstance(nImagePath); +// log.info("toPdf===修正颜色=======结束"); +// }else{ + image = Image.getInstance(filePath); + log.info("toPdf===不修正颜色======="); +// } + + // 添加图片到文档 + // 根据图片大小设置文档大小---原来的设置 + //doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight())); + + //获取图片高度 + float scaledHeight = image.getScaledHeight(); + //判断图片高度是否大于最高高度14400 + if (scaledHeight > PAGE_MAX_HEIGHT){ + log.info("toPdf===1===大于最高高度14400===="); + //图片高度除以页面最大高度14400乘以100等于图片缩小比例 + BigDecimal bigDecimal = BigDecimal.valueOf(scaledHeight); + BigDecimal bigDecimal1 = BigDecimal.valueOf(PAGE_MAX_HEIGHT); + BigDecimal divide = bigDecimal1.divide(bigDecimal, DECIMAL_POINT_NUM, BigDecimal.ROUND_DOWN); + BigDecimal multiply = divide.multiply(BigDecimal.valueOf(ONE_HUNDRED)); + //multiply 计算的图片缩放比例 + image.scalePercent(multiply.intValue()); + } + float imageHeight = image.getScaledHeight(); + float imageWidth = image.getScaledWidth(); + //设置页面宽高与图片一致 最大为14400 + doc.setPageSize(new Rectangle(imageWidth, imageHeight)); + doc.open(); + doc.add(image); + // 关闭文档 + doc.close(); +// for(String tmpName:tmpFiles){ + // 删除生成的图片 +// (new File(filePath)).delete(); +// } + + log.info("toPdf===OK======="); + } catch (IOException e) { + e.printStackTrace(); + } catch (BadElementException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + } + + + public static void convertTifToJpg(String inputFilePath, String outputFilePath) throws IOException { + // 读取TIF文件 + BufferedImage bufferedImage = null; + try { + bufferedImage = ImageIO.read(FileUtil.getInputStream(inputFilePath)); + if (bufferedImage == null) { + System.out.println("image read null"); + } else { + System.out.println("read success"); + } + } catch (IOException e) { + e.printStackTrace(); + } + + + // 设置输出格式为JPG + String jpgExtension = "jpg"; + String jpgMimeType = "image/jpeg"; + + // 写入JPG文件 + ImageIO.write(bufferedImage, jpgExtension, new File(outputFilePath)); + } + + + + + public static void main(String asd[]) throws IOException { + String file1 ="E:\\桌面\\GE\\1.png"; + String file2 ="E:\\桌面\\GE\\2.png"; + String file3 ="E:\\桌面\\GE\\3.png"; + String file4 ="E:\\桌面\\GE\\4.png"; + String file5 ="E:\\桌面\\GE\\5.png"; + String file6 ="E:\\桌面\\GE\\6.png"; + String file7 ="E:\\桌面\\GE\\7.png"; + String file8 ="E:\\桌面\\GE\\8.png"; + String file9 ="E:\\桌面\\GE\\9.png"; + String file10 ="E:\\桌面\\GE\\10.png"; +// String file6 ="C:\\Users\\lee\\Desktop\\GE\\6.png"; + java.util.List imgLs = new ArrayList<>(); + imgLs.add(file1); +// imgLs.add(file2); +// imgLs.add(file3); +// imgLs.add(file4); +// imgLs.add(file5); +// imgLs.add(file6); +// imgLs.add(file7); +// imgLs.add(file8); +// imgLs.add(file9); +// imgLs.add(file10); +// convertTifToJpg(file2,"D:\\office\\ttt.jpg"); + toPdf(imgLs,"E:\\桌面\\GE\\1.pdf"); + } + + /** + * + * @param imgLs + * 图片地址 + * @param pdfPath + * PDF文件保存地址 + * + */ + public static void toPdf(java.util.List imgLs, String pdfPath) { + try { + // PDF文件保存地址 + // String pdfPath = "D:/Demo/ceshi/hebing.pdf"; + // 输入流 + FileOutputStream fos = new FileOutputStream(pdfPath); + // 创建文档 + Document doc = new Document(null, 0, 0, 0, 0); + //doc.open(); + // 写入PDF文档 + PdfWriter.getInstance(doc, fos); + // 读取图片流 + BufferedImage img = null; + // 实例化图片 + Image image = null; + int imgWidth=0; + int imgHeight=0; + int i=0; + // 循环获取图片文件夹内的图片 + for (String imagePath : imgLs) { + // System.out.println(file1.getName()); + File f = new File(imagePath); + if(!f.exists()){ + log.warn("文件不存在=============404:"+imagePath); + continue; + } + if(imagePath.indexOf(".tif")>-1){ + log.warn("文件类型是TIF:"+imagePath); + } + // 读取图片流 + img = ImageIO.read(new File(imagePath)); + // 实例化图片 + image = Image.getInstance(imagePath); + // 添加图片到文档 + try { + if(i==0) { + // 根据图片大小设置文档大小 + doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); + doc.open(); + doc.add(image); + i++; + }else{ + doc.add(image); + // 根据图片大小设置文档大小 + doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); + } + }catch (Exception e){ + log.info(imagePath+"文件合并异常"); + e.printStackTrace(); + } + } + // 关闭文档 + doc.close(); + } catch (IOException e) { + e.printStackTrace(); + } catch (BadElementException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + } + + /** + * base64字符串转换成图片 (对字节数组字符串进行Base64解码并生成图片) + * @param imgStr base64字符串 + * @param imgFilePath 指定图片存放路径 (注意:带文件名) + * @return + */ + public static boolean Base64ToImage(String imgStr,String imgFilePath) { + + if (StringUtils.isEmpty(imgStr)) // 图像数据为空 + return false; + + try { + // Base64解码 + byte[] b = Base64Utils.decodeFromString(imgStr); + for (int i = 0; i < b.length; ++i) { + if (b[i] < 0) {// 调整异常数据 + b[i] += 256; + } + } + + OutputStream out = new FileOutputStream(imgFilePath); + out.write(b); + out.flush(); + out.close(); + + return true; + } catch (Exception e) { + return false; + } + + } + + + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/hly/NumberUtil.java b/src/main/java/com/cmsen/ticket/domain/util/hly/NumberUtil.java new file mode 100644 index 0000000..a8fd5a0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/hly/NumberUtil.java @@ -0,0 +1,265 @@ +package com.cmsen.ticket.domain.util.hly; + +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; + +import java.util.Locale; + +/** + * 数字的工具类. + * + * 1.原始类型数字与byte[]的双向转换(via Guava) + * + * 2.判断字符串是否数字, 是否16进制字符串(via Common Lang) + * + * 3.10机制/16进制字符串 与 原始类型数字/数字对象 的双向转换(参考Common Lang自写) + */ +public class NumberUtil { + + ///////////// bytes[] 与原始类型数字转换 /////// + + public static byte[] toBytes(int value) { + return Ints.toByteArray(value); + } + + public static byte[] toBytes(long value) { + return Longs.toByteArray(value); + } + + /** + * from ElasticSearch Numbers + */ + public static byte[] toBytes(double val) { + return toBytes(Double.doubleToRawLongBits(val)); + } + + public static int toInt(byte[] bytes) { + return Ints.fromByteArray(bytes); + } + + public static long toLong(byte[] bytes) { + return Longs.fromByteArray(bytes); + } + + /** + * from ElasticSearch Numbers + */ + public static double toDouble(byte[] bytes) { + return Double.longBitsToDouble(toLong(bytes)); + } + + /////// 判断字符串类型////////// + /** + * 判断字符串是否合法数字 + */ + public static boolean isNumber(String str) { + return NumberUtils.isNumber(str); + } + + /** + * 判断字符串是否16进制 + */ + public static boolean isHexNumber(String value) { + int index = value.startsWith("-") ? 1 : 0; + return value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index); + } + + /////////// 将字符串安全的转化为原始类型数字///////// + + /** + * 将10进制的String安全的转化为int,当str为空或非数字字符串时,返回0 + */ + public static int toInt(String str) { + return NumberUtils.toInt(str, 0); + } + + /** + * 将10进制的String安全的转化为int,当str为空或非数字字符串时,返回default值 + */ + public static int toInt(String str, int defaultValue) { + return NumberUtils.toInt(str, defaultValue); + } + + /** + * 将10进制的String安全的转化为long,当str为空或非数字字符串时,返回0 + */ + public static long toLong(String str) { + return NumberUtils.toLong(str, 0L); + } + + /** + * 将10进制的String安全的转化为long,当str为空或非数字字符串时,返回default值 + */ + public static long toLong(String str, long defaultValue) { + return NumberUtils.toLong(str, defaultValue); + } + + /** + * 将10进制的String安全的转化为double,当str为空或非数字字符串时,返回0 + */ + public static double toDouble(String str) { + return NumberUtils.toDouble(str, 0L); + } + + /** + * 将10进制的String安全的转化为double,当str为空或非数字字符串时,返回default值 + */ + public static double toDouble(String str, double defaultValue) { + return NumberUtils.toDouble(str, defaultValue); + } + + ////////////// 10进制字符串 转换对象类型数字///////////// + /** + * 将10进制的String安全的转化为Integer,当str为空或非数字字符串时,返回null + */ + public static Integer toIntObject(String str) { + return toIntObject(str, null); + } + + /** + * 将10进制的String安全的转化为Integer,当str为空或非数字字符串时,返回default值 + */ + public static Integer toIntObject(String str, Integer defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + try { + return Integer.valueOf(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + * 将10进制的String安全的转化为Long,当str为空或非数字字符串时,返回null + */ + public static Long toLongObject(String str) { + return toLongObject(str, null); + } + + /** + * 将10进制的String安全的转化为Long,当str为空或非数字字符串时,返回default值 + */ + public static Long toLongObject(String str, Long defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + try { + return Long.valueOf(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + * 将10进制的String安全的转化为Double,当str为空或非数字字符串时,返回null + */ + public static Double toDoubleObject(String str) { + return toDoubleObject(str, null); + } + + /** + * 将10进制的String安全的转化为Long,当str为空或非数字字符串时,返回default值 + */ + public static Double toDoubleObject(String str, Double defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + try { + return Double.valueOf(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //////////// 16进制 字符串转换为数字对象////////// + + /** + * 将16进制的String转化为Integer,出错时返回null. + */ + public static Integer hexToIntObject(String str) { + return hexToIntObject(str, null); + } + + /** + * 将16进制的String转化为Integer,出错时返回默认值. + */ + public static Integer hexToIntObject(String str, Integer defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + try { + return Integer.decode(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + * 将16进制的String转化为Long,出错时返回null. + */ + public static Long hexToLongObject(String str) { + return hexToLongObject(str, null); + } + + /** + * 将16进制的String转化为Long,出错时返回默认值. + */ + public static Long hexToLongObject(String str, Long defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + try { + return Long.decode(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /////// toString (定义了原子类型与对象类型的参数,保证不会用错函数) /////// + + public static String toString(int i) { + return Integer.toString(i); + } + + public static String toString(Integer i) { + return i.toString(); + } + + public static String toString(long l) { + return Long.toString(l); + } + + public static String toString(Long l) { + return l.toString(); + } + + public static String toString(double d) { + return Double.toString(d); + } + + public static String toString(Double d) { + return d.toString(); + } + + /** + * 输出格式化为小数后两位的double字符串 + */ + public static String to2DigitString(double d) { + return String.format(Locale.ROOT, "%.2f", d); + } + + /////////// 杂项 /////// + + /** + * 安全的将小于Integer.MAX的long转为int,否则抛出IllegalArgumentException异常 + */ + public static int toInt32(long x) { + if ((int) x == x){ + return (int) x; + } + throw new IllegalArgumentException("Int " + x + " out of range"); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/hly/SSLClientReport.java b/src/main/java/com/cmsen/ticket/domain/util/hly/SSLClientReport.java new file mode 100644 index 0000000..6294fd7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/hly/SSLClientReport.java @@ -0,0 +1,63 @@ +package com.cmsen.ticket.domain.util.hly; + +/** + * @Auther: xp + * @Date: 2020/3/25 + * @Description: com.jeeplus.modules.ocr.util + * @version: 1.0 + */ + +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class SSLClientReport extends DefaultHttpClient { + public SSLClientReport(String url) throws Exception{ + super(); + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + @Override + public void checkServerTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = this.getConnectionManager(); + SchemeRegistry sr = ccm.getSchemeRegistry(); + String regHead=""; + sr.register(new Scheme("https", getPort(url), ssf)); + } + public int getPort(String str){ + //String str ="https://todayocr.sciclonecloud.com/piaoge/api/task/image"; + String domain=str.substring(str.indexOf("//")+2); + String port=domain.substring(domain.indexOf(":")+1); + port = port.substring(0,port.indexOf("/")); + if(port.indexOf(".")>0 || !NumberUtil.isNumber(port)){ + if(str.indexOf("https")>0) { + port = "443"; + }else{ + port = "80"; + + } + } + return Integer.parseInt(port); + + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/Detail.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/Detail.java new file mode 100644 index 0000000..6d74f6d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/Detail.java @@ -0,0 +1,24 @@ +package com.cmsen.ticket.domain.util.invoice; + +import lombok.Data; + +@Data +public class Detail { + private String name; + private String model; + private String unit; + private String count; + private String price; + private String amount; + private String taxRate; + private String taxAmount; + + + @Override + public String toString() { + return "Detail [name=" + name + ", model=" + model + ", unit=" + unit + ", count=" + count + ", price=" + price + + ", amount=" + amount + ", taxRate=" + taxRate + ", taxAmount=" + taxAmount + "]"; + } + +} + diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/ExInvoice.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/ExInvoice.java new file mode 100644 index 0000000..9c81182 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/ExInvoice.java @@ -0,0 +1,50 @@ +package com.cmsen.ticket.domain.util.invoice; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +public class ExInvoice { + private String title; + private String machineNumber; + private String code; + private String number; + private String date; + private String checksum; + private String buyerName; + private String buyerCode; + private String buyerAddress; + private String buyerAccount; + private String password; + private BigDecimal amount; + private BigDecimal taxAmount; + private String totalAmountString; + private BigDecimal totalAmount; + private String sellerName; + private String sellerCode; + private String sellerAddress; + private String sellerAccount; + private String payee; + private String reviewer; + private String drawer; + private String type; + private String extractType;//识别解析类型 + private String fsActive; + private String kind; + private List detailList; + + @Override + public String toString() { + return "Invoice [title=" + title + ", machineNumber=" + machineNumber + ", code=" + code + ", number=" + number + + ", date=" + date + ", checksum=" + checksum + ", buyerName=" + buyerName + ", buyerCode=" + buyerCode + + ", buyerAddress=" + buyerAddress + ", buyerAccount=" + buyerAccount + ", password=" + password + ", amount=" + + amount + ", taxAmount=" + taxAmount + ", totalAmountString=" + totalAmountString + ", totalAmount=" + + totalAmount + ", sellerName=" + sellerName + ", sellerCode=" + sellerCode + ", sellerAddress=" + sellerAddress + + ", sellerAccount=" + sellerAccount + ", payee=" + payee + ", reviewer=" + reviewer + ", drawer=" + drawer + + ", type=" + type + ", detailList=" + detailList + "]"; + } + +} + diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/IdentifyToOCREntity.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/IdentifyToOCREntity.java new file mode 100644 index 0000000..8dcaf2b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/IdentifyToOCREntity.java @@ -0,0 +1,180 @@ +package com.cmsen.ticket.domain.util.invoice; + +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.infrastructure.ocr2.entity.*; +import lombok.extern.slf4j.Slf4j; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * IdentifyToOCREntity + */ +@Slf4j +public class IdentifyToOCREntity { + + public static boolean checkIdentify(IdentifyOcrEntity identifyOcrEntity) { + + IdentifyOcrEntity.Error error = identifyOcrEntity.getError(); + if(error.getCode() != 200){ + return false; + } + IdentifyOcrEntity.JsonData jsonData = identifyOcrEntity.getResult().getJson_data(); + if(StringUtil.isBlank(jsonData.get票据类型())){ + return false; + } + + return true; + } + + public static RuiZhenOCREntity convert(IdentifyOcrEntity entity) { + + List items = new ArrayList<>(); + + IdentifyOcrEntity.JsonData jsonData = entity.getResult().getJson_data(); + + Details details = new Details(){{ + setCode(jsonData.get发票代码()); + setNumber(jsonData.get发票号码()); + setNumberBackup(jsonData.get发票号码()); + setDate(jsonData.get发票日期()); + setPretax_amount("1"); + // 2024 5 8 total Amount 为 null + setTotal(jsonData.get发票金额()); + setTax("0"); + setCheck_code(""); + setSeller(""); + setSeller_tax_id(""); + setBuyer(""); + setBuyer_tax_id(""); + setKind(""); + setMachine_code(""); + setReceiptor(""); + setReviewer(""); + setIssuer(""); + setService_name(""); + setItem_names(jsonData.get票据类型()); + setCode_confirm(jsonData.get发票代码()); + setTitle(""); + setSeller_addr_tel(""); + setItems(items); + }}; + + List identify_results = new ArrayList(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(){{ + setType(jsonData.get票据类型()); + setDetails(details); + }}; + identify_results.add(identifyResults); + + RuiZhenOCREntity.OCRData data = new RuiZhenOCREntity.OCRData(){{ + setResult(1); + setTimestamp((new Date()).getTime()); + setMessage("success"); + setIdentify_results(identify_results); + }}; + + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(){{ + setData(data); + }}; + + RuiZhenOCREntity ruiZhenOCREntity = new RuiZhenOCREntity(){{ + setResult(1); + setResponse(response); + }}; + + return ruiZhenOCREntity; + } + + public static RuiZhenOCREntity reparse(RuiZhenOCREntity ruiZhenOCREntity) { + + RuiZhenOCREntity.IdentifyResults results = ruiZhenOCREntity.getResponse().getData().getIdentify_results().get(0); + Details details = results.getDetails(); + if(StringUtil.isEmpty(details.getItem_names())){//item_names为空 + String item_names = ""; + List items = details.getItems(); + for ( Item item: items) { + item_names += item.getName()+","; + } + if(item_names.length() > 0){ + details.setItem_names(item_names.substring(0, item_names.length()-1)); + log.info("OCR识别后item_names重新赋值=={}",item_names); + } + } + + return ruiZhenOCREntity; + } + + public static boolean checkAbroadIdentify(AbroadEntity abroadEntity) { + + if(abroadEntity == null){ + return false; + } + if(StringUtil.isBlank(abroadEntity.getTicket_type())){ + return false; + } + + return true; + } + + public static RuiZhenOCREntity convert(AbroadEntity entity) { + + List items = new ArrayList<>(); + + Details details = new Details(){{ + setCode(""); + setNumber(entity.getNumber()); + setNumberBackup(entity.getNumber()); + setDate(entity.getDate()); + setPretax_amount("1"); + // 2024 5 8 total Amount 为 null + setTotal(entity.getAmount()); + setTax("0"); + setCheck_code(""); + setSeller(""); + setSeller_tax_id(""); + setBuyer(""); + setBuyer_tax_id(""); + setKind(""); + setMachine_code(""); + setReceiptor(""); + setReviewer(""); + setIssuer(""); + setService_name(""); + setItem_names(entity.getTicket_type()); + setCode_confirm(""); + setTitle(""); + setSeller_addr_tel(""); + setItems(items); + setCity(entity.getCity()); + setCurrency_code(entity.getCurrentcy()); + }}; + + List identify_results = new ArrayList(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(){{ + setType(entity.getTicket_type()); + setDetails(details); + }}; + identify_results.add(identifyResults); + + RuiZhenOCREntity.OCRData data = new RuiZhenOCREntity.OCRData(){{ + setResult(1); + setTimestamp((new Date()).getTime()); + setMessage("success"); + setIdentify_results(identify_results); + }}; + + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(){{ + setData(data); + }}; + + RuiZhenOCREntity ruiZhenOCREntity = new RuiZhenOCREntity(){{ + setResult(1); + setResponse(response); + }}; + + return ruiZhenOCREntity; + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/InvoiceToOCREntity.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/InvoiceToOCREntity.java new file mode 100644 index 0000000..95785d7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/InvoiceToOCREntity.java @@ -0,0 +1,139 @@ +package com.cmsen.ticket.domain.util.invoice; + +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * InvoiceToOCREntity + */ +@Slf4j +public class InvoiceToOCREntity { + + public static boolean checkInvoice(ExInvoice invoice) { + + if(StringUtil.isBlank(invoice.getTitle()) || StringUtil.isBlank(invoice.getDate()) + || StringUtil.isBlank(invoice.getType()) + || StringUtil.isBlank(invoice.getNumber()) || StringUtil.isBlank(invoice.getExtractType()) + || invoice.getExtractType().equals("0") + || (invoice.getNumber().length() < 20 && StringUtil.isBlank(invoice.getCode()) + || null == invoice.getTotalAmount() + || invoice.getTotalAmount().compareTo(new BigDecimal("0"))!=0 + ) + ){ + return false; + } + + List invoiceDetails = invoice.getDetailList(); + for ( Detail invoiceDetail : invoiceDetails) { + if(StringUtil.isBlank(invoiceDetail.getModel()) && StringUtil.isBlank(invoiceDetail.getName())){ + return false; + } + } + + return true; + } + + public static RuiZhenOCREntity convert(ExInvoice invoice) { + + String item_names = ""; + List items = new ArrayList<>(); + List invoiceDetails = invoice.getDetailList(); + for ( Detail invoiceDetail : invoiceDetails) { + String name = StringUtils.isNotBlank(invoiceDetail.getModel()) ? invoiceDetail.getModel() : invoiceDetail.getName(); + Item item = new Item(){{ + setTotal(invoiceDetail.getAmount()); + setName(name); + setSpecification(invoiceDetail.getModel()); + setUnit(invoiceDetail.getUnit()); + setQuantity(StringUtils.isNotBlank(invoiceDetail.getCount()) ? invoiceDetail.getCount() : ""); + setPrice(invoiceDetail.getPrice()); + setTax_rate(invoiceDetail.getTaxRate()); + setTax(invoiceDetail.getTaxAmount()); + }}; + items.add(item); + item_names += name+","; + } + + String finalItem_names = item_names; + Details details = new Details(){{ + setCode(invoice.getCode()); + setNumber(invoice.getNumber()); + setNumberBackup(invoice.getNumber()); + setDate(invoice.getDate()); + setPretax_amount(invoice.getAmount().toString()); + // 2024 5 8 total Amount 为 null + setTotal(invoice.getTotalAmount()==null ? "0" : invoice.getTotalAmount().toString()); + setTax(invoice.getTaxAmount().toString()); + setCheck_code(invoice.getChecksum()); + setSeller(invoice.getSellerName()); + setSeller_tax_id(invoice.getSellerCode()); + setBuyer(invoice.getBuyerName()); + setBuyer_tax_id(invoice.getBuyerCode()); + setKind(invoice.getKind()); + setMachine_code(invoice.getMachineNumber()); + setReceiptor(invoice.getPayee()); + setReviewer(invoice.getReviewer()); + setIssuer(invoice.getDrawer()); + setService_name(""); + setItem_names(finalItem_names.substring(0, finalItem_names.length()-1)); + setCode_confirm(invoice.getCode()); + setTitle(invoice.getTitle()); + setSeller_addr_tel(invoice.getSellerAddress()); + setItems(items); + }}; + + List identify_results = new ArrayList(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(){{ + setType(invoice.getType()); + setDetails(details); + }}; + identify_results.add(identifyResults); + + RuiZhenOCREntity.OCRData data = new RuiZhenOCREntity.OCRData(){{ + setResult(1); + setTimestamp((new Date()).getTime()); + setMessage("success"); + setIdentify_results(identify_results); + }}; + + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(){{ + setData(data); + }}; + + RuiZhenOCREntity ruiZhenOCREntity = new RuiZhenOCREntity(){{ + setResult(1); + setResponse(response); + }}; + + return ruiZhenOCREntity; + } + + public static RuiZhenOCREntity reparse(RuiZhenOCREntity ruiZhenOCREntity) { + + RuiZhenOCREntity.IdentifyResults results = ruiZhenOCREntity.getResponse().getData().getIdentify_results().get(0); + Details details = results.getDetails(); + if(StringUtil.isEmpty(details.getItem_names())){//item_names为空 + String item_names = ""; + List items = details.getItems(); + for ( Item item: items) { + item_names += item.getName()+","; + } + if(item_names.length() > 0){ + details.setItem_names(item_names.substring(0, item_names.length()-1)); + log.info("OCR识别后item_names重新赋值=={}",item_names); + } + } + + return ruiZhenOCREntity; + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/OfdInvoiceExtractor.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/OfdInvoiceExtractor.java new file mode 100644 index 0000000..a63ef60 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/OfdInvoiceExtractor.java @@ -0,0 +1,168 @@ +package com.cmsen.ticket.domain.util.invoice; + +import com.cmsen.common.util.JsonUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.springframework.util.StreamUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * 专用于处理电子发票识别的类 + * + * + */ +@Slf4j +public class OfdInvoiceExtractor { + + public static ExInvoice extract(File file) throws IOException, DocumentException { + log.info("OfdInvoiceExtractor==开始"); + ZipFile zipFile = new ZipFile(file); + ZipEntry entry = zipFile.getEntry("Doc_0/Attachs/original_invoice.xml"); + ZipEntry entry1 = zipFile.getEntry("Doc_0/Pages/Page_0/Content.xml"); + if(entry1==null){ + entry1 = zipFile.getEntry("Doc_0/Content_0.xml"); + } + InputStream input = zipFile.getInputStream(entry); + InputStream input1 = zipFile.getInputStream(entry1); + String body = StreamUtils.copyToString(input, Charset.forName("utf-8")); + String content = StreamUtils.copyToString(input1, Charset.forName("utf-8")); + zipFile.close(); + Document document = DocumentHelper.parseText(body); + Element root = document.getRootElement(); + ExInvoice invoice = new ExInvoice(); + invoice.setMachineNumber(root.elementTextTrim("MachineNo")); + invoice.setCode(root.elementTextTrim("InvoiceCode")); + invoice.setNumber(root.elementTextTrim("InvoiceNo")); + invoice.setDate(root.elementTextTrim("IssueDate")); + invoice.setChecksum(root.elementTextTrim("InvoiceCheckCode")); + invoice.setAmount(new BigDecimal(root.elementTextTrim("TaxExclusiveTotalAmount"))); + String taxAmountStr = root.elementTextTrim("TaxTotalAmount"); + if(taxAmountStr.indexOf("*")!=-1){ + taxAmountStr="0"; + } + invoice.setTaxAmount(new BigDecimal(taxAmountStr)); + int ind = content.indexOf("圆整"); + invoice.setTotalAmountString(content.substring(content.lastIndexOf(">", ind) + 1, ind + 2)); + invoice.setTotalAmount(new BigDecimal(root.elementTextTrim("TaxInclusiveTotalAmount"))); + invoice.setPayee(root.elementTextTrim("Payee")); + invoice.setReviewer(root.elementTextTrim("Checker")); + invoice.setDrawer(root.elementTextTrim("InvoiceClerk")); + int index = content.indexOf(""); + invoice.setTitle(content.substring(content.lastIndexOf(">", index) + 1, index)); + invoice.setType("普通发票"); + if (invoice.getTitle().contains("专用发票")) { + invoice.setType("专用发票"); + } else if (invoice.getTitle().contains("通行费")) { + //invoice.setType("通行费"); + invoice.setKind("通行费"); + } + invoice.setPassword(root.elementText("TaxControlCode")); + Element buyer = root.element("Buyer"); + { + invoice.setBuyerName(buyer.elementTextTrim("BuyerName")); + invoice.setBuyerCode(buyer.elementTextTrim("BuyerTaxID")); + invoice.setBuyerAddress(buyer.elementTextTrim("BuyerAddrTel")); + invoice.setBuyerAccount(buyer.elementTextTrim("BuyerFinancialAccount")); + } + Element seller = root.element("Seller"); + { + invoice.setSellerName(seller.elementTextTrim("SellerName")); + invoice.setSellerCode(seller.elementTextTrim("SellerTaxID")); + invoice.setSellerAddress(seller.elementTextTrim("SellerAddrTel")); + invoice.setSellerAccount(seller.elementTextTrim("SellerFinancialAccount")); + } + Element details = root.element("GoodsInfos"); + { + List detailList = new ArrayList<>(); + List elements = details.elements(); + for (Element element : elements) { + Detail detail = new Detail(); + detail.setName(element.elementTextTrim("Item")); + detail.setAmount(element.elementTextTrim("Amount")); + String taxAmountLineStr = root.elementTextTrim("TaxAmount"); + if(taxAmountLineStr==null || taxAmountLineStr.indexOf("*")!=-1){ + taxAmountLineStr="0"; + } + detail.setTaxAmount(taxAmountLineStr); + String QuantityStr=element.elementTextTrim("Quantity"); + String PriceStr=element.elementTextTrim("Price"); + if(QuantityStr==null ||QuantityStr.length()==0){ + QuantityStr="0"; + } + if(PriceStr==null ||PriceStr.length()==0){ + PriceStr="0"; + } + detail.setCount(QuantityStr); + detail.setPrice(PriceStr); + detail.setUnit(element.elementTextTrim("MeasurementDimension")); + detail.setModel(element.elementTextTrim("Specification")); + String taxStr = element.elementTextTrim("TaxScheme"); + if(taxStr==null || taxStr.equals("免税")){ + taxStr=""; + } + /*detail.setTaxRate( + new BigDecimal(taxStr.replace("%", "")).divide(new BigDecimal(100)));*/ + detail.setTaxRate(taxStr); + detailList.add(detail); + } + invoice.setDetailList(detailList); + + //处理title、type + if(StringUtils.isNotBlank(invoice.getTitle()) && invoice.getTitle().contains("(")){ + invoice.setTitle(invoice.getTitle()+")"); + } + if(StringUtils.isNotBlank(invoice.getTitle()) && invoice.getTitle().contains("(")){ + invoice.setTitle(invoice.getTitle()+")"); + } + if(StringUtils.isNotBlank(invoice.getType()) && invoice.getType().equals("普通发票")){ + if(invoice.getNumber().length() == 20){ + invoice.setType("10108"); + }else{ + invoice.setType("10102"); + } + } + + if(StringUtils.isNotBlank(invoice.getType()) && invoice.getType().equals("专用发票")){ + if(invoice.getNumber().length() == 20){ + invoice.setType("10107"); + }else{ + invoice.setType("10106"); + } + } + } + return invoice; + } + + + public static void main(String[] args)throws Exception{ + + File pdf = new File("D:/home/ofd/03100200041178616852.ofd"); + File pdf2 = new File("D:/home/ofd/OFD普票1.ofd"); + File pdf3 = new File("D:/home/ofd/OFD普票2.ofd"); + File pdf4 = new File("D:/home/ofd/OFD专票1.ofd"); + File pdf5 = new File("D:/home/ofd/OFD专票2.ofd"); + File pdf6 = new File("D:/home/ofd/031001800311_63282833_I8E7A1C8.ofd"); + ExInvoice inv = extract(pdf2); + if(inv == null){ + System.out.println("111111111"); + }else{ + + System.out.println(JsonUtil.toString(InvoiceToOCREntity.convert(inv))); + } + } + + +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/PDFKeyWordPosition.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/PDFKeyWordPosition.java new file mode 100644 index 0000000..984b474 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/PDFKeyWordPosition.java @@ -0,0 +1,120 @@ +package com.cmsen.ticket.domain.util.invoice; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; +import org.apache.pdfbox.text.TextPosition; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PDFKeyWordPosition extends PDFTextStripper { + + private List keywordList; + private Map> positionListMap; + + public PDFKeyWordPosition() throws IOException { + super(); + } + + // 获取坐标信息 + public Map> getCoordinate(List keywordList, PDDocument document) throws IOException { + super.setSortByPosition(true); + this.keywordList = keywordList; + this.positionListMap = new HashMap<>(); + super.setStartPage(1); + super.setEndPage(1); + Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); + super.writeText(document, dummy); + return positionListMap; + } + + @Override + protected void writeString(String string, List textPositions) throws IOException { + for (String keyword : keywordList) { + Integer foundIndex = 0; + List positionList = positionListMap.computeIfAbsent(keyword, k -> new ArrayList<>()); + for (int i = 0; i < textPositions.size(); i++) { + TextPosition textPosition = textPositions.get(i); + String str = textPosition.getUnicode(); + if (0 < str.length() && str.charAt(0) == keyword.charAt(foundIndex)) { + foundIndex++; + int count = foundIndex; + for (int j = foundIndex; j < keyword.length(); j++) { + if (i + j >= textPositions.size()) { + break; + } else { + String s = textPositions.get(i + j).getUnicode(); + if (0 < s.length() && s.charAt(0) == keyword.charAt(j)) { + count++; + } + } + } + if (count == keyword.length()) { + foundIndex = 0; + Position position = new Position(); + position.setX(textPosition.getX()); + position.setY(textPosition.getY()); + positionList.add(position); + positionListMap.put(keyword, positionList); + } + } + } + } + } + +} + +class Position { + public Position() { + } + + public Position(float x, float y) { + super(); + this.x = x; + this.y = y; + } + + float x; + float y; + + /** + * @return the x + */ + public float getX() { + return x; + } + + /** + * @param x + * the x to set + */ + public void setX(float x) { + this.x = x; + } + + /** + * @return the y + */ + public float getY() { + return y; + } + + /** + * @param y + * the y to set + */ + public void setY(float y) { + this.y = y; + } + + @Override + public String toString() { + return "Position [x=" + x + ", y=" + y + "]"; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/util/invoice/PdfInvoiceExtractor.java b/src/main/java/com/cmsen/ticket/domain/util/invoice/PdfInvoiceExtractor.java new file mode 100644 index 0000000..6bf462e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/util/invoice/PdfInvoiceExtractor.java @@ -0,0 +1,480 @@ +package com.cmsen.ticket.domain.util.invoice; + +import com.cmsen.common.util.JsonUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.text.PDFTextStripper; +import org.apache.pdfbox.text.PDFTextStripperByArea; + +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 专用于处理电子发票识别的类 + * + * @author arthurlee + * + */ +@Slf4j +public class PdfInvoiceExtractor { + + public static ExInvoice extract(File file) throws IOException { + log.info("PdfInvoiceExtractor==开始"); + ExInvoice invoice = new ExInvoice(); + PDDocument doc = PDDocument.load(file); + PDPage firstPage = doc.getPage(0); + int pageWidth = Math.round(firstPage.getCropBox().getWidth()); + PDFTextStripper textStripper = new PDFTextStripper(); + textStripper.setSortByPosition(true); + String fullText = textStripper.getText(doc); + String fullText2 = Pattern.compile("\\\\s*|\\t|\\r|\\n").matcher(fullText).replaceAll("").trim(); + log.info("fullText2=={}=={}",fullText2,fullText2.length()); + if(fullText2.equals("\r\n") || fullText2 == null || fullText2.length() == 0) + {return null;} + if (firstPage.getRotation() != 0) { + pageWidth = Math.round(firstPage.getCropBox().getHeight()); + } + String allText = replace(fullText).replaceAll("(", "(").replaceAll(")", ")") + .replaceAll("¥", "¥").replaceAll("发票号码", "\n发票号码"). + replaceAll("售名称","\n售名称").replaceAll("信统一","\n信统一"); + { + String reg = "机器编号:(?\\d{12})|发票代码:(?\\d{12})|发票号码:(?\\d{7,20})|国制(?\\d{8})|:(?\\d{4}年\\d{2}月\\d{2}日)" + + "|校验码:(?\\d{20}|\\S{4,})"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(allText); + while (matcher.find()) { + if (matcher.group("machineNumber") != null) { + invoice.setMachineNumber(matcher.group("machineNumber")); + } else if (matcher.group("code") != null) { + invoice.setCode(matcher.group("code")); + } else if (matcher.group("number") != null) { + invoice.setNumber(matcher.group("number")); + } else if (matcher.group("date") != null) { + invoice.setDate(matcher.group("date")); + } else if (matcher.group("checksum") != null) { + invoice.setChecksum(matcher.group("checksum")); + }else if(invoice.getNumber()==null || invoice.getNumber().equals("")){// 发票特殊情况处理 + if (matcher.group("number2") != null) { + invoice.setNumber(matcher.group("number2")); + } + } + } + } + { + String reg = "合计¥?(?[^ \\f\\n\\r\\t\\v\\*]*)(?:¥?(?\\S*)|\\*+)\\s"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(allText); + if (matcher.find()) { + try { + invoice.setAmount(new BigDecimal(matcher.group("amount"))); + } catch (Exception e) { + } + try { + invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount"))); + } catch (Exception e) { + invoice.setTaxAmount(new BigDecimal(0)); + } + } + } + if (null == invoice.getAmount()) { + String reg = "合\\u0020*计\\u0020*¥?(?[^ ]*)\\u0020+¥?(?:(?\\S*)|\\*+)\\s"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(fullText); + if (matcher.find()) { + try { + invoice.setAmount(new BigDecimal(matcher.group("amount"))); + } catch (Exception e) { + invoice.setAmount(new BigDecimal(0)); + } + try { + invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount"))); + } catch (Exception e) { + invoice.setTaxAmount(new BigDecimal(0)); + } + } + } + { + String reg = "价税合计\\u0028大写\\u0029(?\\S*)\\u0028小写\\u0029¥?(?\\S*)\\s"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(allText); + if (matcher.find()) { + invoice.setTotalAmountString(matcher.group("amountString")); + try { + invoice.setTotalAmount(new BigDecimal(matcher.group("amount"))); + } catch (Exception e) { + invoice.setTotalAmount(new BigDecimal(0)); + } + } + } + { + String reg = "收款人:(?\\S*)复核:(?\\S*)开票人:(?\\S*)销售方"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(allText); + if (matcher.find()) { + invoice.setPayee(matcher.group("payee")); + invoice.setReviewer(matcher.group("reviewer")); + invoice.setDrawer(matcher.group("drawer")); + } + if (allText.indexOf("通行费") > 0 && allText.indexOf("车牌号") > 0) { + invoice.setKind("通行费"); + } + Pattern type00Pattern = Pattern.compile("(?

\\S*)通发票"); + Matcher m00 = type00Pattern.matcher(allText); + if (m00.find()) { + invoice.setTitle(m00.group("p").replaceAll("(?:国|统|一|发|票|监|制)", "") + "通发票"); + if (null == invoice.getType()) { + invoice.setType("普通发票"); + } + } else { + Pattern type01Pattern = Pattern.compile("(?

\\S*)用发票"); + Matcher m01 = type01Pattern.matcher(allText); + if (m01.find()) { + invoice.setTitle(m01.group("p").replaceAll("(?:国|统|一|发|票|监|制)", "") + "用发票"); + if (null == invoice.getType()) { + invoice.setType("专用发票"); + } + } + } + } + PDFKeyWordPosition kwp = new PDFKeyWordPosition(); + Map> positionListMap = kwp + .getCoordinate(Arrays.asList("机器编号", "税率", "价税合计", "合计", "开票日期", "规格型号", "车牌号", "开户行及账号", "密", "码", "区"), doc); + + PDFTextStripperByArea stripper = new PDFTextStripperByArea(); + stripper.setSortByPosition(true); + PDFTextStripperByArea detailStripper = new PDFTextStripperByArea(); + detailStripper.setSortByPosition(true); + { + Position machineNumber; + if (positionListMap.get("机器编号").size() > 0) { + machineNumber = positionListMap.get("机器编号").get(0); + } else { + machineNumber = positionListMap.get("开票日期").get(0); + machineNumber.setY(machineNumber.getY() + 30); + } + Position taxRate = positionListMap.get("税率").get(0); + Position totalAmount = positionListMap.get("价税合计").get(0); + Position amount = positionListMap.get("合计").get(0); + Position model = null; + if (!positionListMap.get("规格型号").isEmpty()) { + model = positionListMap.get("规格型号").get(0); + } else { + model = positionListMap.get("车牌号").get(0); + model.setX(model.getX() - 15); + } + + List account = positionListMap.get("开户行及账号"); + Position buyer; + Position seller; + if (account.size() < 2) { + buyer = new Position(51, 122); + seller = new Position(51, 341); + } else { + buyer = account.get(0); + seller = account.get(1); + } + + int maqX = 370; + List mi = positionListMap.get("密"); + List ma = positionListMap.get("码"); + List qu = positionListMap.get("区"); + for (int i = 0; i < mi.size(); i++) { + float x1 = mi.get(i).getX(); + for (int j = 0; j < ma.size(); j++) { + float x2 = ma.get(j).getX(); + if (Math.abs(x1 - x2) < 5) { + for (int k = 0; k < qu.size(); k++) { + float x3 = qu.get(k).getX(); + if (Math.abs(x2 - x3) < 5) { + maqX = Math.round((x1 + x2 + x3) / 3); + } + } + } + } + } + { + int x = Math.round(model.getX()) - 13; + int y = Math.round(taxRate.getY()) + 5; // 用税率的y坐标作参考 + int h = Math.round(amount.getY()) - Math.round(taxRate.getY()) - 25; // 价税合计的y坐标减去税率的y坐标 + detailStripper.addRegion("detail", new Rectangle(0, y, pageWidth, h)); + stripper.addRegion("detailName", new Rectangle(0, y, x, h)); + // 全电发票位置修改 + /*if(invoice.getNumber().length()==20){ + x=0; + pageWidth+=60; + }*/ + stripper.addRegion("detailPrice", new Rectangle(x, y, pageWidth, h)); + } + { + int x = maqX + 10; + int y = Math.round(machineNumber.getY()) + 10; + int w = pageWidth - maqX - 10; + int h = Math.round(taxRate.getY() - 5) - y; + stripper.addRegion("password", new Rectangle(x, y, w, h)); + } + // 标题 + { + int x = 180; + int y = 30; + int w = 230; + int h = 30; + stripper.addRegion("title", new Rectangle(x, y, w, h)); + } + { + int x = Math.round(buyer.getX()) - 15; // 开户行及账号的x为参考 + int y = Math.round(machineNumber.getY()) + 10; // 机器编号的y坐标为参考 + int w = maqX - x - 5; // 密码区x坐标为参考 + int h = Math.round(buyer.getY()) - y + 20; // 开户行及账号的y坐标为参考 + // 全电发票位置修改 + if(invoice.getNumber().length()==20){ + x=30; + y=35; + w=270; + h=170; + } + stripper.addRegion("buyer", new Rectangle(x, y, w, h)); + } + { + int x = Math.round(seller.getX()) - 15; // 开户行及账号为x参考 + int y = Math.round(totalAmount.getY()) + 10; // 价税合计的y坐标为参考 + + int w = maqX - x - 5; // 密码区的x为参考 + + int h = Math.round(seller.getY()) - y + 20; // 开户行及账号的y为参考 + // 全电发票位置修改 + if(invoice.getNumber().length()==20){ + x=300; + y=90; + w=270; + h=170; + } + stripper.addRegion("seller", new Rectangle(x, y, w, h)); + } + } + stripper.extractRegions(firstPage); + detailStripper.extractRegions(firstPage); + doc.close(); + + invoice.setPassword(StringUtils.trim(stripper.getTextForRegion("password"))); + + String reg = "名称:(?\\S*)|纳税人识别号:(?\\S*)|地址、电话:(?

\\S*)|开户行及账号:(?\\S*)|电子支付标识:(?\\S*)"; + //标题为空重新识别 + { + + String titleStr = replace(stripper.getTextForRegion("title")); + System.out.println("titleStr==="+titleStr); + Pattern type00Pattern = Pattern.compile("(?

\\S*)通发票"); + Matcher m00 = type00Pattern.matcher(titleStr); + if (m00.find()) { + invoice.setTitle(m00.group("p").replaceAll("(?:国|统|一|发|票|监|制)", "") + "通发票"); + if (null == invoice.getType()) { + invoice.setType("普通发票"); + } + } else { + Pattern type01Pattern = Pattern.compile("(?

\\S*)用发票"); + Matcher m01 = type01Pattern.matcher(titleStr); + if (m01.find()) { + invoice.setTitle(m01.group("p").replaceAll("(?:国|统|一|发|票|监|制)", "") + "用发票"); + if (null == invoice.getType()) { + invoice.setType("专用发票"); + } + } + } + } + { + String buyer = replace(stripper.getTextForRegion("buyer")); + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(buyer); + while (matcher.find()) { + if (matcher.group("name") != null) { + invoice.setBuyerName(matcher.group("name")); + } else if (matcher.group("code") != null) { + invoice.setBuyerCode(matcher.group("code")); + } else if (matcher.group("address") != null) { + invoice.setBuyerAddress(matcher.group("address")); + } else if (matcher.group("account") != null) { + invoice.setBuyerAccount(matcher.group("account")); + } else if (matcher.group("account2") != null) { + invoice.setBuyerAccount(matcher.group("account2")); + } + } + } + { + String seller = replace(stripper.getTextForRegion("seller")); + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(seller); + while (matcher.find()) { + if (matcher.group("name") != null) { + invoice.setSellerName(matcher.group("name")); + } else if (matcher.group("code") != null) { + invoice.setSellerCode(matcher.group("code")); + } else if (matcher.group("address") != null) { + invoice.setSellerAddress(matcher.group("address")); + } else if (matcher.group("account") != null) { + invoice.setSellerAccount(matcher.group("account")); + } + } + } + { + List skipList = new ArrayList<>(); + List detailList = new ArrayList<>(); + String[] detailPriceStringArray = stripper.getTextForRegion("detailPrice").replaceAll(" ", " ").replaceAll(" ", " ") + .replaceAll("\r", "").split("\\n"); + // 全电发票位置修改 + if(invoice.getNumber().length()==20){ + detailPriceStringArray = detailStripper.getTextForRegion("detail").replaceAll(" ", " ").replaceAll(" ", " ") + .replaceAll("\r", "").split("\\n"); + } + for (String detailString : detailPriceStringArray) { + Detail detail = new Detail(); + detail.setName(""); + String[] itemArray = StringUtils.split(detailString, " "); + if (2 == itemArray.length) { + detail.setAmount(itemArray[0]); + detail.setTaxAmount(itemArray[1]); + detailList.add(detail); + } else if (2 < itemArray.length) { + detail.setAmount(itemArray[itemArray.length - 3]); + String taxRate = itemArray[itemArray.length - 2]; + if (taxRate.indexOf("免税") > 0 || taxRate.indexOf("不征税") > 0 || taxRate.indexOf("出口零税率") > 0 + || taxRate.indexOf("普通零税率") > 0 || taxRate.indexOf("%") < 0) { + detail.setTaxRate(""); + detail.setTaxAmount("0"); + } else { + /*BigDecimal rate = new BigDecimal(Integer.parseInt(taxRate.replaceAll("%", ""))); + detail.setTaxRate(rate.divide(new BigDecimal(100)));*/ + detail.setTaxRate(taxRate); + detail.setTaxAmount(itemArray[itemArray.length - 1]); + } + for (int j = 0; j < itemArray.length - 3; j++) { + if (itemArray[j].matches("^(-?\\d+)(\\.\\d+)?$")) { + if (null == detail.getCount()) { + detail.setCount(itemArray[j]); + } else { + detail.setPrice(itemArray[j]); + } + } else { + if (itemArray.length >= j + 1 && !itemArray[j + 1].matches("^(-?\\d+)(\\.\\d+)?$")) { + detail.setUnit(itemArray[j + 1]); + detail.setModel(itemArray[j]); + j++; + } else if (itemArray[j].length() > 2) { + detail.setModel(itemArray[j]); + } else { + detail.setUnit(itemArray[j]); + } + } + } + detailList.add(detail); + } else { + skipList.add(detailString); + } + } + + String[] detailNameStringArray = stripper.getTextForRegion("detailName").replaceAll(" ", " ").replaceAll(" ", " ") + .replaceAll("\r", "").split("\\n"); + String[] detailStringArray = replace(detailStripper.getTextForRegion("detail")).replaceAll("\r", "").split("\\n"); + int i = 0, j = 0, h = 0, m = 0; + Detail lastDetail = null; + for (String detailString : detailStringArray) { + if (m < detailNameStringArray.length) { + if (detailString.matches("\\S+\\d*(%|免税|不征税|出口零税率|普通零税率)\\S*") + && !detailString.matches("^ *\\d*(%|免税|不征税|出口零税率|普通零税率)\\S*") + && detailString.matches("\\S+\\d+%[\\-\\d]+\\S*") + || detailStringArray.length > i + 1 + && detailStringArray[i + 1].matches("^ *\\d*(%|免税|不征税|出口零税率|普通零税率)\\S*")) { + if (j < detailList.size()) { + lastDetail = detailList.get(j); + lastDetail.setName(detailNameStringArray[m]); + } + j++; + } else if (null != lastDetail && StringUtils.isNotBlank(detailNameStringArray[m])) { + if (skipList.size() > h) { + String skip = skipList.get(h); + if (detailString.endsWith(skip)) { + if (detailString.equals(skip)) { + m--; + } else { + lastDetail.setName(lastDetail.getName() + detailNameStringArray[m]); + } + lastDetail.setModel(lastDetail.getModel() + skip); + h++; + } else { + lastDetail.setName(lastDetail.getName() + detailNameStringArray[m]); + } + } else { + lastDetail.setName(lastDetail.getName() + detailNameStringArray[m]); + } + } + } + i++; + m++; + } + invoice.setDetailList(detailList); + + //处理title、type + if(StringUtils.isNotBlank(invoice.getTitle()) && invoice.getTitle().contains("(")){ + invoice.setTitle(invoice.getTitle()+")"); + } + if(StringUtils.isNotBlank(invoice.getTitle()) && invoice.getTitle().contains("(")){ + invoice.setTitle(invoice.getTitle()+")"); + } + if(StringUtils.isNotBlank(invoice.getType()) && invoice.getType().equals("普通发票")){ + if(invoice.getNumber().length() == 20){ + invoice.setType("10108"); + }else{ + invoice.setType("10102"); + } + } + + if(StringUtils.isNotBlank(invoice.getType()) && invoice.getType().equals("专用发票")){ + if(invoice.getNumber().length() == 20){ + invoice.setType("10107"); + }else{ + invoice.setType("10106"); + } + } + + } + return invoice; + + } + + public static String replace(String str) { + return str.replaceAll(" ", "").replaceAll(" ", "").replaceAll(":", ":").replaceAll(" ", ""); + } + public static void main(String[] args)throws Exception{ + + File pdf = new File("D:/home/pdf/PDF普票1.pdf"); + File pdf11 = new File("D:/home/pdf/20221001084042f09ef655fd1149fca3a94d6eec8211b7.pdf"); + File pdf12 = new File("D:/home/pdf/20211025180937ff206f8389534344adcb5f9e4c86055b.pdf"); + File pdf2 = new File("D:/home/pdf/PDF普票2.pdf"); + File pdf3 = new File("D:/home/pdf/PDF专票1.pdf"); + File pdf4 = new File("D:/home/pdf/PDF专票2.pdf"); + File pdf5 = new File("D:/home/pdf/全电发票专票1.pdf"); + File pdf6 = new File("D:/home/pdf/全电发票专票2.pdf"); + File pdf7 = new File("D:/home/pdf/全电普票1.pdf"); + File pdf8 = new File("D:/home/pdf/全电普票2.pdf"); + File pdf9 = new File("D:/home/pdf/12.pdf"); + ExInvoice inv = extract(pdf2); + if(inv == null){ + System.out.println("111111111"); + }else{ + System.out.println(inv.getType()); + System.out.println(JsonUtil.toString(inv)); + System.out.println(JsonUtil.toString(InvoiceToOCREntity.convert(inv))); + } + + } + +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/AIMaterialVO.java b/src/main/java/com/cmsen/ticket/domain/vo/AIMaterialVO.java index 10b536a..30b0e7a 100644 --- a/src/main/java/com/cmsen/ticket/domain/vo/AIMaterialVO.java +++ b/src/main/java/com/cmsen/ticket/domain/vo/AIMaterialVO.java @@ -5,7 +5,6 @@ import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; - @Data @AllArgsConstructor @NoArgsConstructor diff --git a/src/main/java/com/cmsen/ticket/domain/vo/AccountMappingVo.java b/src/main/java/com/cmsen/ticket/domain/vo/AccountMappingVo.java new file mode 100644 index 0000000..0c095e5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/AccountMappingVo.java @@ -0,0 +1,13 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.Data; + +@Data +public class AccountMappingVo { + + private String accountType; + + private String account; + + private String amount; // corprateInvoice pretax_amount +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/BaozunInvoiceVo.java b/src/main/java/com/cmsen/ticket/domain/vo/BaozunInvoiceVo.java new file mode 100644 index 0000000..f17016a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/BaozunInvoiceVo.java @@ -0,0 +1,88 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class BaozunInvoiceVo { + + private int status; + private String errorCode; + private String errorMessage; + private int currentPage; + private int totalPage; + private List data; + @Data + @AllArgsConstructor + @NoArgsConstructor + public class DataInfo { + private String vendorCode; + private String oaNumber; + private String appleremark; + private String settlementType; + private BigDecimal prePayTotalAmount; + private List invoiceList; + private String costCenter; + private String createTime; + private List poList; + } + @Data + @AllArgsConstructor + @NoArgsConstructor + public class BaozunInvoiceInfo { + private String invoiceCode; + private String invoiceNumber; + private String invoiceUrl; + private String invoiceType; + } + @Data + @AllArgsConstructor + @NoArgsConstructor + public class BaoznPoInfo { + private String poNumber; + private BigDecimal prePayAmount; + } + + //{ + // "status": 1, + // "errorCode": "", + // " errorMessage ": "", + // "currentPage": 1, + // "totalPage": 52, + // "data": [ + // { + // "vendorCode": "123123", + // "oaNumber": "dhfljlgsjkdjk", + // "appleremark":"Apple", + // "settlementType":"1", + // "prePayTotalAmount": 12312.23, + // "invoiceList": [ + // { + // "invoiceCode": "", + // "invoiceNumber": "12312341412412", + // "invoiceUrl": "http://example.pdf", + // "invoiceType": "电子发票(增值税专用发票)" + // } + // ], + // "costCenter": "成本中心", + // "createTime": "2024-10-14 10:00:00", + // "poList": [ + // { + // "poNumber": "PORO202408241111", + // "prePayAmount": 122321.43 + // }, + // { + // "poNumber": "PORO202408241112", + // "prePayAmount": 122321.43 + // } + // ] + // } + //] + //} +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/CorInvoiceUploadVo.java b/src/main/java/com/cmsen/ticket/domain/vo/CorInvoiceUploadVo.java new file mode 100644 index 0000000..fe63aeb --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/CorInvoiceUploadVo.java @@ -0,0 +1,61 @@ +package com.cmsen.ticket.domain.vo; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +@Data +public class CorInvoiceUploadVo { + + // 文件上传日期 + @ExcelProperty(value = "文件上传日期",index = 0,order = 0) + private String uploadDate; + + // 文件名 + @ExcelProperty(value = "文件名",index = 1,order = 1) + private String fileName; + + + // 电子票or 纸质票 + @ExcelIgnore + private String ticketType; + + @ExcelProperty(value = "发票类型",index = 2,order = 2) + private String ticketTypeName; + + // 发票状态 异常 待处理 + @ExcelIgnore + private String invoiceStatus; + + public String getInvoicesStatusName() { + if("0".equals(invoiceStatus)){ + return "待处理"; + } + if("1".equals(invoiceStatus)){ + return "已完成"; + } + return "异常"; + } + + @ExcelProperty(value = "发票状态",index = 3,order = 3) + private String invoicesStatusName; + + // 发票号码 + @ExcelProperty(value = "发票号码",index = 4,order = 4) + private String invoiceNumber; + + // 发票标签码 电子形式发票没有标签编码 纸质发票有唯一的标签编码 + @ExcelProperty(value = "发票标签码",index = 5,order = 5) + private String invoiceTagCode; + + // 上传者 + @ExcelProperty(value = "上传者",index = 6,order = 6) + private String uploader; + + public String getTicketTypeName() { + if("10101".equals(ticketType)||"10100".equals(ticketType)){ + return "纸质票"; + } + return "电子票"; + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceSummaryVo.java b/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceSummaryVo.java new file mode 100644 index 0000000..8743fd9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceSummaryVo.java @@ -0,0 +1,33 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CorporateInvoiceSummaryVo implements Serializable { + + private String costCenter; + + private String orgName; + + private int assertTotal; + + private String assertAmount; + + private int assertRefundTotal; + + private String assertRefundAmount; + + private int serviceTotal; + + private String serviceAmount; + + private int serviceRefundTotal; + + private String serviceRefundAmount; +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceVo.java b/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceVo.java index 726f900..c5bda04 100644 --- a/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceVo.java +++ b/src/main/java/com/cmsen/ticket/domain/vo/CorporateInvoiceVo.java @@ -2,6 +2,8 @@ package com.cmsen.ticket.domain.vo; import lombok.Data; +import java.util.List; + @Data public class CorporateInvoiceVo { @@ -37,6 +39,7 @@ public class CorporateInvoiceVo { private String code; private String number; private String depName; + private List accountcombine; // select buyer,name,type,ledger,companyid,code from sys_user,sys_org ,corporate_invoice,account_mapping where // sys_user.id =corporateInvoice.owner and corporateInvoice.org_id = sys_org.id and corporateInvoice.subject = account_mapping.id diff --git a/src/main/java/com/cmsen/ticket/domain/vo/DeductionsDiDi.java b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsDiDi.java new file mode 100644 index 0000000..59ef67e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsDiDi.java @@ -0,0 +1,86 @@ +package com.cmsen.ticket.domain.vo; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class DeductionsDiDi { + @ExcelProperty("发票状态") + private String invoiceStatus; + @ExcelIgnore + private Integer invoiceStatusCode; + @ExcelProperty("发票类型") + private String invoiceType; + @ExcelProperty("发票号码") + private String invoiceNumber; + @ExcelProperty("发票代码") + private String invoiceCode; + @ExcelProperty("销售方") + private String seller; + @ExcelProperty("销售方税号") + private String sellerCode; + @ExcelProperty("购买方") + private String buyer; + @ExcelProperty("购买方税号") + private String buyerCode; + @ExcelProperty("发票日期") + private String invoiceDate; + @ExcelProperty("总额") + private String total; + @ExcelProperty("税额") + private String tax; + @ExcelProperty("抵扣税额") + private String deTax; + @ExcelProperty("Report ID") + private String reportId; + + @ExcelIgnore + private String loginId; + + @ExcelIgnore + private String taxRate; + @ExcelIgnore + private String postedAmount; + @ExcelIgnore + private Integer id; + @ExcelIgnore + private String attributer1; + + //税额 = 报销金额 - (报销金额/(1+税率)) + + //抵扣税额 = (报销金额/发票金额)* 总税额 + public String getDeTax() { + try { + BigDecimal postAmountNum = new BigDecimal(postedAmount); + BigDecimal taxMoney = new BigDecimal(tax); + BigDecimal invoiceMoney = new BigDecimal(total).add(taxMoney); + if (invoiceMoney.compareTo(postAmountNum) < 0) { + return taxMoney.toString(); + } + return postAmountNum.divide(invoiceMoney, 4, BigDecimal.ROUND_HALF_UP).multiply(taxMoney).toString(); + } catch (Exception e) { + return null; + } + } + + public String getInvoiceStatus() { + if (invoiceStatusCode == null) { + return null; + } + switch (this.invoiceStatusCode) { + case 0: + return "未抵扣"; + case 1: + return "发送抵扣"; + case 2: + return "确认抵扣"; + case 3: + return "抵扣失败"; + default: + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/DeductionsSearch.java b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsSearch.java new file mode 100644 index 0000000..141ae18 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsSearch.java @@ -0,0 +1,20 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.Data; + +@Data +public class DeductionsSearch { + private Integer type; //1增专 2 火车票 3 滴滴 4供应商发票 + private String start; //2020-10-10 + private String end; //2020-10-12 + // New filed added + private Integer deductType; //1待抵扣 2可抵扣 3已抵扣 + + private Integer pageNo; + + private Integer pageSize; + + private String reportId; + private String reportKey; + private String readFlag; +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/DeductionsTrain.java b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsTrain.java new file mode 100644 index 0000000..e3f89b6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsTrain.java @@ -0,0 +1,73 @@ +package com.cmsen.ticket.domain.vo; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.cmsen.common.util.StringUtil; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class DeductionsTrain { + @ExcelProperty("发票状态") + private String invoiceStatus; + @ExcelIgnore + private Integer invoiceStatusCode; + @ExcelProperty("发票类型") + private String invoiceType; + @ExcelProperty("发票号码") + private String invoiceNumber; + @ExcelProperty("乘客") + private String passenger; + @ExcelProperty("座位等级") + private String seatType; + @ExcelProperty("日期") + private String invoiceDate; + @ExcelProperty("出发站") + private String startStation; + @ExcelProperty("到达站") + private String endStation; + @ExcelProperty("总额") + private String total; + @ExcelProperty("抵扣税额") + private String deTax; + @ExcelProperty("Report ID") + private String reportId; + @ExcelIgnore + private String loginId; + @ExcelIgnore + private String attributer1; + + @ExcelIgnore + private Integer id; + + public String getDeTax() { + if (StringUtil.isNotEmpty(total)) { + try { + BigDecimal totalNum = new BigDecimal(total); + return totalNum.subtract(totalNum.divide(new BigDecimal("1.09"), 2, 4)).toString(); + } catch (Exception e) { + return deTax; + } + } + return deTax; + } + + public String getInvoiceStatus() { + if (invoiceStatusCode == null) { + return null; + } + switch (this.invoiceStatusCode) { + case 0: + return "未抵扣"; + case 1: + return "发送抵扣"; + case 2: + return "确认抵扣"; + case 3: + return "抵扣失败"; + default: + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/DeductionsVAT.java b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsVAT.java new file mode 100644 index 0000000..052d4bb --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/DeductionsVAT.java @@ -0,0 +1,142 @@ +package com.cmsen.ticket.domain.vo; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.cmsen.common.util.StringUtil; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class DeductionsVAT { + private Integer id; + @ExcelProperty(value = "发票状态", order = 12) + private String invoiceStatus; + @ExcelIgnore + private Integer invoiceStatusCode; + @ExcelProperty(value = "发票类型", order = 11) + private String invoiceType; + @ExcelProperty(value = "发票号码", order = 1) + private String invoiceNumber; + @ExcelProperty(value = "发票代码", order = 0) + private String invoiceCode; + @ExcelProperty(value = "销售方", order = 8) + private String seller; + @ExcelProperty(value = "销售方税号", order = 9) + private String sellerCode; + @ExcelProperty(value = "购方名称", order = 2) + private String buyer; + @ExcelProperty(value = "购买方税号", order = 10) + private String buyerCode; + @ExcelProperty(value = "发票日期", order = 5) + private String invoiceDate; + @ExcelProperty(value = "不含税金额", order = 3) + private String total; + @ExcelProperty(value = "税额", order = 4) + private String tax; + // @ExcelProperty("抵扣税额") + @ExcelIgnore + private String deTax; + @ExcelProperty(value = "Report ID", order = 13) + private String reportId; + + @ExcelProperty(value = "备注", order = 6) + private String remark; + + @ExcelProperty(value = "公司代码", order = 7) + private String comCode; + + @ExcelIgnore + private String paidDate; + + @ExcelIgnore + private String taxRate; + @ExcelIgnore + private String postedAmount; + + @ExcelIgnore + private String loginId; + @ExcelIgnore + private String reportKey; + + @ExcelIgnore + private String attributer1; + @ExcelProperty(value = "发票识别状态", order = 13) + private String readFlag; + private String readFlagStr; + @ExcelProperty(value = "Concur费用类型", order = 14) + private String expenseTypeName; + @ExcelIgnore + @ExcelProperty(value = "验真状态", order = 15) + private String validStatus; + private String validStatusStr; + @ExcelProperty(value = "审批日期", order = 15) + private String reportDate; + @ExcelProperty(value = "EntryId", order = 15) + private String reportEntryId; + + public String getRemark() { + return "VAThotel" + (StringUtil.isBlank(paidDate) ? "" : (paidDate.substring(2, 4) + paidDate.substring(5, 7))); + } + + //抵扣税额 = (报销金额/发票金额)* 总税额 + public String getDeTax() { + try { + BigDecimal postAmountNum = new BigDecimal(postedAmount); + BigDecimal taxMoney = new BigDecimal(tax); + BigDecimal invoiceMoney = new BigDecimal(total).add(taxMoney); + if (invoiceMoney.compareTo(postAmountNum) < 0) { + return taxMoney.toString(); + } + return postAmountNum.divide(invoiceMoney, 4, BigDecimal.ROUND_HALF_UP).multiply(taxMoney).toString(); + } catch (Exception e) { + return null; + } + } + + public String getInvoiceStatus() { + if (invoiceStatusCode == null) { + return null; + } + switch (this.invoiceStatusCode) { + case 0: + return "未抵扣"; + case 1: + return "发送抵扣"; + case 2: + return "确认抵扣"; + case 3: + return "抵扣失败"; + default: + return null; + } + } + public String getReadFlagStr() { + if (readFlag == null || readFlag.equals("")) { + return "未识别"; + } + switch (Integer.parseInt(this.readFlag)) { + case 1: + return "已识别"; + case 2: + return "识别错误"; + case 3: + return "未识别"; + default: + return "未识别"; + } + } + public String getValidStatusStr() { + if (validStatus == null) { + return null; + } + switch (Integer.parseInt(this.validStatus)) { + case 0: + return "未验真"; + case 1: + return "已验真"; + default: + return null; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/EntryImageVO.java b/src/main/java/com/cmsen/ticket/domain/vo/EntryImageVO.java new file mode 100644 index 0000000..cfff83e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/EntryImageVO.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.domain.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author OWTS + */ +@NoArgsConstructor +@Data +public class EntryImageVO { + @JsonProperty("msg") + private String msg; + @JsonProperty("code") + private Integer code; + @JsonProperty("imageId") + private String imageId; + @JsonProperty("data") + private String data; + @JsonProperty("success") + private Boolean success; +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/FileVo.java b/src/main/java/com/cmsen/ticket/domain/vo/FileVo.java new file mode 100644 index 0000000..289b41e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/FileVo.java @@ -0,0 +1,20 @@ +package com.cmsen.ticket.domain.vo; + +import com.cmsen.common.util.Base64Util; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FileVo { + + private String fileName; + + private String filePath; + + public String parseBase64Url() { + return "data:application/pdf;base64,"+Base64Util.fileToBase64(filePath); + } +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/InvoiceImagesUrlVo.java b/src/main/java/com/cmsen/ticket/domain/vo/InvoiceImagesUrlVo.java new file mode 100644 index 0000000..b2f8ae1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/InvoiceImagesUrlVo.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.Data; + +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/9/10 16:00 + **/ +@Data +public class InvoiceImagesUrlVo { + private String id; + private String url; + private List urls; +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/MultiInvExprotEntity.java b/src/main/java/com/cmsen/ticket/domain/vo/MultiInvExprotEntity.java new file mode 100644 index 0000000..e0533e2 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/MultiInvExprotEntity.java @@ -0,0 +1,35 @@ +package com.cmsen.ticket.domain.vo; + +/* + * @author OWTS + * @date 2021/4/25 + * @desc + */ + +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +/** + * 员工姓名,员工ID,报告ID,entry ID,金额,发票号码,费用类型 + */ +@Data +public class MultiInvExprotEntity { + @ExcelProperty(value = "员工姓名") + private String name; + @ExcelProperty(value = "员工ID") + private String employeeId; + @ExcelProperty(value = "报告ID") + private String reportId; + @ExcelProperty(value = "ENTRY_ID") + private String entryId; + @ExcelProperty(value = "费用类型") + private String expensetype; + @ExcelProperty(value = "发票类型") + private String type; + @ExcelProperty(value = "发票号码") + private String number; + @ExcelProperty(value = "金额") + private String total; + @ExcelProperty(value = "验证状态") + private String custom7; +} diff --git a/src/main/java/com/cmsen/ticket/domain/vo/SupplierOrderItemUsedVo.java b/src/main/java/com/cmsen/ticket/domain/vo/SupplierOrderItemUsedVo.java new file mode 100644 index 0000000..313605e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/domain/vo/SupplierOrderItemUsedVo.java @@ -0,0 +1,14 @@ +package com.cmsen.ticket.domain.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class SupplierOrderItemUsedVo { + + private BigDecimal usedAmount; + + private String usedQuantity; + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/config/JacksonConfig.java b/src/main/java/com/cmsen/ticket/infrastructure/config/JacksonConfig.java new file mode 100644 index 0000000..53e890a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/config/JacksonConfig.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.infrastructure.config; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; + +import java.io.IOException; + +/** + * 处理 jackson 返回的null值 + */ +@Configuration +public class JacksonConfig { + + @Bean + @Primary + @ConditionalOnMissingBean(ObjectMapper.class) + public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { + ObjectMapper objectMapper = builder.createXmlMapper(false).build(); + objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() { + @Override + public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeString(""); + } + }); + return objectMapper; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/config/RedisConfig.java b/src/main/java/com/cmsen/ticket/infrastructure/config/RedisConfig.java new file mode 100644 index 0000000..907534f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/config/RedisConfig.java @@ -0,0 +1,58 @@ +///* +// * +--------------------------------------------------------- +// * | Author Jared.Yan +// * +--------------------------------------------------------- +// * | Copyright (c) http://cmsen.com All rights reserved. +// * +--------------------------------------------------------- +// */ +//package com.cmsen.ticket.infrastructure.config; +// +//import com.fasterxml.jackson.annotation.JsonAutoDetect; +//import com.fasterxml.jackson.annotation.JsonTypeInfo; +//import com.fasterxml.jackson.annotation.PropertyAccessor; +//import com.fasterxml.jackson.databind.DeserializationFeature; +//import com.fasterxml.jackson.databind.MapperFeature; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.fasterxml.jackson.databind.SerializationFeature; +//import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +//import org.springframework.cache.annotation.CachingConfigurerSupport; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.data.redis.connection.RedisConnectionFactory; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +//import org.springframework.data.redis.serializer.StringRedisSerializer; +// +///** +// * Redis配置 +// */ +//@Configuration +//public class RedisConfig extends CachingConfigurerSupport { +// +// private static final ObjectMapper mapper = new ObjectMapper(); +// +// static { +// mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); +// mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); +// mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); +// mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); +// mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); +// mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); +// } +// +// @Bean +// public RedisTemplate redisTemplate(RedisConnectionFactory factory) { +// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); +// jackson2JsonRedisSerializer.setObjectMapper(mapper); +// RedisTemplate template = new RedisTemplate<>(); +// StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); +// template.setConnectionFactory(factory); +// template.setKeySerializer(stringRedisSerializer); +// template.setHashKeySerializer(stringRedisSerializer); +// template.setValueSerializer(jackson2JsonRedisSerializer); +// template.setHashValueSerializer(jackson2JsonRedisSerializer); +// template.afterPropertiesSet(); +// return template; +// } +// +//} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/config/TokenSecurityFilterConfig.java b/src/main/java/com/cmsen/ticket/infrastructure/config/TokenSecurityFilterConfig.java index f33b68d..23556b3 100644 --- a/src/main/java/com/cmsen/ticket/infrastructure/config/TokenSecurityFilterConfig.java +++ b/src/main/java/com/cmsen/ticket/infrastructure/config/TokenSecurityFilterConfig.java @@ -9,7 +9,6 @@ package com.cmsen.ticket.infrastructure.config; import com.cmsen.common.util.StorageCache; import com.cmsen.common.util.StringUtil; -import com.cmsen.ticket.domain.entity.concur.ConcurConfigEntity; import com.cmsenframework.security.RequestContextMap; import com.cmsenframework.security.RequestSecurityPolicy; import com.cmsenframework.security.TokenSecurityFilter; @@ -46,9 +45,6 @@ import java.util.stream.Collectors; @Component public class TokenSecurityFilterConfig extends TokenSecurityFilter { - @Resource - private ConcurConfigEntity concurConfig; - // 使用你logback配置的命名logger,输出到OUTER_HTTP_MONITOR文件 private static final Logger accessLogger = LoggerFactory.getLogger("innerHttpMonitor"); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @@ -98,8 +94,7 @@ public class TokenSecurityFilterConfig extends TokenSecurityFilter { try{ // 开放回送地址访问给定接口 String header = request.getHeader("Authorization"); - if (!StringUtil.isEmpty(header) && header.length() > 20 && header.startsWith("Bearer ") - && header.substring("Bearer ".length()).equalsIgnoreCase(concurConfig.getConcurLoginInfo().getToken())) { + if (!StringUtil.isEmpty(header) && header.length() > 20 && header.startsWith("Bearer ")) { if (RequestSecurityPolicy.getAuthentication() == null) { RequestSecurityPolicy.setSecurityContext(new UserDetail() {{ setPermissions(RequestContextMap.get().values() diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/GetAppTokenFeign.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/GetAppTokenFeign.java new file mode 100644 index 0000000..9c85eb0 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/GetAppTokenFeign.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayApiCode; +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayApiToken; +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayCodeGen; +import com.cmsen.ticket.infrastructure.ocr2.entity.R; +import com.dtflys.forest.annotation.Get; +import com.dtflys.forest.annotation.JSONBody; +import com.dtflys.forest.annotation.Post; +import com.dtflys.forest.annotation.Var; + +public interface GetAppTokenFeign { + + /** + * 通过appKey获取Code + * @param appKey 应用标识 + * @return R 包含code为验证码的对象 + */ + @Get(url = "http://s2s-admin-ui-gateway-uat.pengfeijituan.com/api/gateway/token/generateCodeByAppKey?appKey={appKey}") + R getAppCodeByAppKey(@Var("appKey") String appKey); + + /** + * 通过appKey和服务名称和验证码和code获取token + * @param gatewayCodeGen 包含appKey、serviceName、validCode、code的对象 + * @return R 获取到的token对象,包含token为获取到的唯一标识码 + */ + @Post("http://s2s-admin-ui-gateway-uat.pengfeijituan.com/api/gateway/token/generateToken") + R getAppTokenByAppKeyAndAppCode(@JSONBody GatewayCodeGen gatewayCodeGen); +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/HHOCRService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/HHOCRService.java new file mode 100644 index 0000000..d88875a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/HHOCRService.java @@ -0,0 +1,484 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.ClientHttpRequest; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.http.ClientHttps; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.ticket.domain.entity.TicketType; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Flight; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; + + +/** + * @author OWTS + * @date 2020/10/11 15:26 + * @description + */ +@Component +@Slf4j +public class HHOCRService { + + @Resource + private SupplierMaterialUomMapper supplierMaterialUomMapper; + + @Resource + private SupplierMapper supplierMapper; + + @Resource + private SmarttaxService smarttaxService; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private CorporateInvoiceNdJsonMappingMapper corporateInvoiceNdJsonMappingMapper; + @Resource + private SysUserMapper sysUserMapper; + private String verify_invoice_interface_str; + + @PostConstruct + public void init() { + SysConfig verify_invoice_interface = sysConfigMapper.selectByCode("VERIFY_INVOICE_INTERFACE"); + verify_invoice_interface_str = verify_invoice_interface.getValue(); + log.info("verify_invoice_interface_is_rz >> {}", verify_invoice_interface_str); + } + + private static final List needVerifyCodes = new ArrayList() {{ + add("10101"); + add("10100"); + add("10102"); + add("10103"); + add("10104"); + add("10105"); + add("10107"); + add("10106");//新增 2022/11/11 + add("10108");//新增 2022/11/11 + }}; + private static final List qrCodeTypes = new ArrayList() {{ + add("10101"); + add("10100"); + add("10102"); + }}; + @Value("${spring.ccintocr.app_key}") + private String appKey; + @Value("${spring.ccintocr.app_secret}") + private String appSecret; + + public RuiZhenOCREntity billsCrop(String imgViewPath) { + log.info("HH OCR Result>>>>start>>>>"); + + String Url = "https://api.textin.com/ai/service/v1/bill_recognize_v2"; + SysConfig conf = sysConfigMapper.selectByCode("HH_OCR_URL"); + if(conf != null && !conf.getValue().isEmpty()){ + Url = conf.getValue(); + } + + ClientHttpResponse response = ClientHttps.post( + new ClientHttpRequest() + .setUrl(Url+"?crop_complete_image=1") + .setHeaders("x-ti-app-id",sysConfigMapper.selectByCode("x-ti-app-id").getValue()) + .setHeaders("x-ti-secret-code",sysConfigMapper.selectByCode("x-ti-secret-code").getValue()) + .setHeaders("Content-Type", ContentEnctype.TEXT) + .setParams(imgViewPath) + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202408/20240812154905da3db88570ec45279632c8679b7e9023.jpg")//增值税普通发票 + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202412/20241215195233682a400ee7bd4d3db77388f6e416e1da.jpg")//增值税专用发票 + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202506/202506061527208530bf24022249eca41eeff6dc00fd97.jpg")//增值税电子普通发票 + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202407/202407311709302cf8138935714d9b8ce19cc25edb4162.jpg")//增值税电子专用发票 + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202505/20250519122430c4a7bcc8c8ac4394880d5a819bf3b73e.jpg")//电子火车票 + //.setParams("https://fp.connectconcur.com:10244/api/img/opt202504/202504181448092194befb9df64fb1aff4c543758791b8.jpg")//航空运输电子客票行程单 + ); + log.info("HH OCR Result>>" + response); + + //进行结果的解析 + return responseToOCREntity(response.toString()); + } + + /** + * 转换Base64图片为二进制流 + * @param base64Str 包含前缀的完整Base64字符串 + * @return 图片二进制字节数组 + * @throws IllegalArgumentException 当Base64格式非法时抛出 + */ + public byte[] convertToBinary(String base64Str) { + try { + String pureBase64 = base64Str.replaceFirst("^data:image/\\w+;base64,", ""); + return Base64.getDecoder().decode(pureBase64); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Base64解码失败: " + e.getMessage()); + } + } + + /** + * 接口结果解析成RuiZhenOCREntity + * @param response + * @return + */ + public RuiZhenOCREntity responseToOCREntity(String response) { + RuiZhenOCREntity ruiZhenOCREntity = new RuiZhenOCREntity(); + RuiZhenOCREntity.Response response1= new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData= new RuiZhenOCREntity.OCRData(); + + JSONObject res = JSONObject.parseObject(response); + if(null != res.getInteger("code") && res.getInteger("code") == 200){ + ruiZhenOCREntity.setResult(res.getInteger("code")); + + List resultsList = new ArrayList<>(Collections.emptyList()); + JSONArray pages = res.getJSONArray("pages"); + for (int i = 0; i< pages.size(); i++){ + + JSONObject page = pages.getJSONObject(i); + JSONArray objectList = page.getJSONObject("result").getJSONArray("object_list"); + for (int j = 0; j< objectList.size(); j++){ + //定义每张票的对象 + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + + JSONObject object = objectList.getJSONObject(j); + String type = object.getString("type"); + String invoiceType = ""; + log.info("responseToOCREntity=====type=={}",type); + identifyResults.setImage(object.getString("image")); + + Details details = new Details(); + details.setKind(object.getString("kind_description")); + + StringBuilder itemNames = new StringBuilder(); + if(type.equals("vat_invoice")){//增值税发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "vat_invoice_total_cover_tax_digits" : details.setTotal(value.substring(1).replaceAll(" ","")); break; + case "vat_invoice_daima" : details.setCode(value); break; + case "vat_invoice_haoma" : details.setNumber(value); details.setNumberBackup(value); break; + case "vat_invoice_total" : details.setPretax_amount(value.substring(1).replaceAll(" ",""));break; + case "vat_invoice_issue_date" : details.setDate(value);break; + case "vat_invoice_correct_code" : details.setCheck_code(value);break; + case "vat_invoice_tax_total" : details.setTax(value.substring(1).replaceAll(" ",""));break; + case "vat_invoice_payer_name" : details.setBuyer(value);break; + case "title" : details.setTitle(value);break; + case "vat_invoice_machine_no" : details.setMachine_code(value);break; + case "vat_invoice_review" : details.setReviewer(value);break; + case "vat_invoice_drawer" : details.setIssuer(value);break; + case "vat_invoice_payee" : details.setReceiptor(value);break; + case "vat_invoice_payer_addr_tell" : details.setBuyer_addr_tel(value);break; + case "vat_invoice_payer_bank_account" : details.setBuyer_bank_account(value);break; + case "vat_invoice_rate_payer_id" : details.setBuyer_tax_id(value);break; + case "vat_invoice_seller_name" : details.setSeller(value);break; + case "vat_invoice_seller_addr_tell" : details.setSeller_addr_tel(value);break; + case "vat_invoice_seller_bank_account" : details.setSeller_bank_account(value);break; + case "vat_invoice_seller_id" : details.setSeller_tax_id(value);break; + case "invoice_type" : invoiceType = value;break; + default: break; + } + } + List items = new ArrayList<>(); + //得到明细信息(行输出) + JSONArray productList = object.getJSONArray("product_list"); + for (int m = 0; m< productList.size(); m++){ + Item item = new Item(); + JSONArray products = JSONObject.parseArray(productList.get(m).toString()); + for (int n = 0; n< products.size(); n++){ + JSONObject product = products.getJSONObject(n); + String value = product.getString("value"); + switch (product.getString("key")){ + case "vat_invoice_product_name": item.setName(value); + itemNames.append(value).append(";");break; + case "vat_invoice_price": item.setTotal(value);break; + case "vat_invoice_tax": item.setTax(value);break; + case "vat_invoice_tax_rate": item.setTax_rate(value);break; + case "vat_invoice_unit_price": item.setPrice(value);break; + case "vat_invoice_quantity": item.setQuantity(value);break; + case "vat_invoice_unit": item.setUnit(value);break; + case "vat_invoice_specification": item.setSpecification(value);break; + default:break; + } + } + items.add(item); + } + details.setItems(items); + }else if(type.equals("vat_digital_invoice")){//数电票(增值税普通/专用发票) + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "title" : details.setTitle(value);break; + case "vat_invoice_number" : details.setNumber(value); details.setNumberBackup(value); break; + case "vat_invoice_issue_date" : details.setDate(value);break; + case "vat_invoice_payer_name" : details.setBuyer(value);break; + case "vat_invoice_rate_payer_id" : details.setBuyer_tax_id(value);break; + case "vat_invoice_seller_name" : details.setSeller(value);break; + case "vat_invoice_seller_id" : details.setSeller_tax_id(value);break; + case "vat_invoice_total" : details.setPretax_amount(value.substring(1).replaceAll(" ",""));break; + case "vat_invoice_tax_total" : details.setTax(value.substring(1).replaceAll(" ",""));break; + case "vat_invoice_total_cover_tax_digits" : details.setTotal(value.substring(1).replaceAll(" ","")); break; + case "vat_invoice_drawer" : details.setIssuer(value);break; + case "invoice_type" : invoiceType = value;break; + default: break; + } + } + List items = new ArrayList<>(); + //得到明细信息(行输出) + JSONArray productList = object.getJSONArray("product_list"); + for (int m = 0; m< productList.size(); m++){ + Item item = new Item(); + JSONArray products = JSONObject.parseArray(productList.get(m).toString()); + for (int n = 0; n< products.size(); n++){ + JSONObject product = products.getJSONObject(n); + String value = product.getString("value"); + switch (product.getString("key")){ + case "vat_invoice_product_name": item.setName(value); + itemNames.append(value).append(";");break; + case "vat_invoice_specification": item.setSpecification(value);break; + case "vat_invoice_tax": item.setTax(value);break; + case "vat_invoice_tax_rate": item.setTax_rate(value);break; + case "vat_invoice_price": item.setTotal(value);break; + case "vat_invoice_unit_price": item.setPrice(value);break; + case "vat_invoice_quantity": item.setQuantity(value);break; + case "vat_invoice_unit": item.setUnit(value);break; + default:break; + } + } + items.add(item); + } + details.setItems(items); + }else if(type.equals("railway_digital_ticket")){//电子火车票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "number" : details.setNumber(value); details.setNumberBackup(value);break; + case "pretax_amount" : details.setPretax_amount(value);break; + case "tax" : details.setTax(value);break; + case "tax_rate" : details.setTax_rate(value);break; + case "departure_station" : details.setStation_geton(value);break; + case "train_number" : details.setTrain_number(value);break; + case "arrival_station" : details.setStation_getoff(value);break; + case "dateonly_of_departure_date" : details.setDate(value);break; + case "price" : details.setTotal(value);break; + case "timeonly_of_departure_date" : details.setTime(value);break; + case "passenger_name" : details.setName(value);break; + case "class" : details.setSeat(value);break; + case "ticket_id" : details.setSerial_number(value);break; + case "passenger_id" : details.setUser_id(value); break; + case "buyer" : details.setBuyer(value); break; + case "buyer_tax_id" : details.setBuyer_tax_id(value); break; + case "date_of_issue" : details.setDate_of_issue(value); break; + case "invoice_item" : if(!value.equals("退票费") && !value.equals("改签费") ){details.setType_of_business("售");}break; + case "issuing_status" : details.setTicket_content(value); break; + default: break; + } + } + details.setType_of_business(object.getString("type_description")); + + }else if(type.equals("flight_digital_ticket")){//数电票(航空运输电子客票行程单) + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "e_ticket_no" : details.setNumber(value); details.setNumberBackup(value);break; + case "issued_date" : details.setDate(value);break; + case "total" : details.setTotal(value);break; + case "tax" : details.setTax(value); + case "check_code" : details.setCheck_code(value);break; + case "buyer" : details.setBuyer(value);break; + case "id_no" : details.setUser_id(value); break; + case "passenger_name" : details.setUser_name(value);break; + case "agentcode" : details.setAgentcode(value);break; + case "issued_by" : details.setIssue_by(value);break; + case "fare" : details.setFare(value);break; + case "fuel_surcharge" : details.setFuel_surcharge(value);break; + case "civil_aviation_fund" : details.setCaac_development_fund(value);break; + case "insurance" : details.setInsurance(value);break; + case "international_flag" : details.setInternational_flag(value);break; + case "tax_rate" : details.setTax_rate(value);break; + case "invoice_number" : details.setReceipt_number(value);break; + default: break; + } + } + details.setTitle(object.getString("type_description")); + + List flights = new ArrayList<>(); + //得到航线信息 + JSONArray flightList = object.getJSONArray("flight_data_list"); + for (int m = 0; m< flightList.size(); m++){ + Flight flightB = new Flight(); + JSONArray flightArr = JSONObject.parseArray(flightList.get(m).toString()); + for (int n = 0; n< flightArr.size(); n++){ + JSONObject flight = flightArr.getJSONObject(n); + String value = flight.getString("value"); + switch (flight.getString("key")){ + case "from": flightB.setFrom(value);break; + case "to": flightB.setTo(value);break; + case "carrier": flightB.setCarrier(value);break; + case "flight_number": flightB.setFlight_number(value);break; + case "seat_class": flightB.setSeat(value);break; + case "date": flightB.setDate(value);break; + case "time": flightB.setTime(value);break; + default:break; + } + } + flights.add(flightB); + } + details.setFlights(flights); + }else if(type.equals("taxi_ticket")){//出租车发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "invoice_code" : details.setCode(value); break; + case "invoice_no" : details.setNumber(value);details.setNumberBackup(value);break; + case "date" : details.setDate(value.substring(0,10));break; + case "sum" : details.setTotal(value);details.setFare(value);break; + case "location" : details.setPlace(value);details.setProvince(value.substring(0,3));details.setCity(value.substring(3));break; + case "boarding_time" : details.setTime_geton(value);break; + case "landing_time" : details.setTime_getoff(value);break; + case "mileage" : details.setMileage(value);break; + case "taxi_no" : details.setLicense_plate(value);break; + default: break; + } + } + }else if(type.equals("quota_invoice")){//定额发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "quota_invoice_code" : details.setCode(value); break; + case "quota_invoice_number" : details.setNumber(value);details.setNumberBackup(value);break; + case "amount_digits" : details.setTotal(value);details.setFare(value);break; + case "location" : details.setProvince(value);break; + case "title" : details.setTitle(value);break; + default: break; + } + } + }else if(type.equals("vehicle_toll")){//过路过桥费发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "toll_code" : details.setCode(value); break; + case "toll_number" : details.setNumber(value);details.setNumberBackup(value);break; + case "money" : details.setTotal(value);break; + case "entrance" : details.setEntrance(value);break; + case "exit" : details.setExit(value);break; + case "title" : details.setTitle(value);break; + default: break; + } + } + }else if(type.equals("highway_passenger_invoice")){//公路客运发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "invoice_code" : details.setCode(value); break; + case "invoice_number" : details.setNumber(value);details.setNumberBackup(value);break; + case "money" : details.setTotal(value);break; + case "date" : details.setDate(value);break; + case "time" : details.setTime(value);break; + case "departure" : details.setStation_geton(value);break; + case "arrival" : details.setStation_getoff(value);break; + case "passenger_id" : details.setUser_id(value);break; + case "passenger_name" : details.setUser_name(value);break; + case "title" : details.setTitle(value);break; + case "bus_number" : details.setTrain_number(value);break; + default: break; + } + } + }else if(type.equals("shipping_invoice")){//船运客票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "invoice_code" : details.setCode(value); break; + case "invoice_number" : details.setNumber(value);details.setNumberBackup(value);break; + case "money" : details.setTotal(value);break; + case "date" : details.setDate(value);break; + case "time" : details.setTime(value);break; + case "departure" : details.setStation_geton(value);break; + case "arrival" : details.setStation_getoff(value);break; + case "passenger_id" : details.setUser_id(value);break; + case "passenger_name" : details.setUser_name(value);break; + default: break; + } + } + }else if(type.equals("general_machine_invoice")){//机打发票 + JSONArray itemList = object.getJSONArray("item_list"); + for (int k = 0; k< itemList.size(); k++){ + JSONObject item = itemList.getJSONObject(k); + String value = item.getString("value"); + switch (item.getString("key")){ + case "title" : details.setTitle(value); break; + case "invoice_code" : details.setCode(value); break; + case "invoice_number" : details.setNumber(value);details.setNumberBackup(value);break; + case "seller" : details.setSeller(value);break; + case "seller_tax_id" : details.setSeller_tax_id(value);break; + case "buyer" : details.setBuyer(value);break; + case "buyer_tax_id" : details.setBuyer_tax_id(value);break; + case "total" : details.setTotal(value);break; + case "date" : details.setDate(value);break; + case "time" : details.setTime(value);break; + default: break; + } + } + } + + details.setItem_names(itemNames.toString()); + + //判断electronic_mark + if(object.getString("type_description").contains("数电票") || invoiceType.contains("电子")){ + details.setElectronic_mark("1"); + } + identifyResults.setDetails(details); + + //undo 得到type + TicketType ticketType = ticketTypeMapper.selectCode(type,invoiceType); + identifyResults.setType(ticketType != null ? ticketType.getCode() : ""); + + resultsList.add(identifyResults); + + } + + } + ocrData.setIdentify_results(resultsList); + response1.setData(ocrData); + ruiZhenOCREntity.setResponse(response1); + log.info("responseToOCREntity==ruiZhenOCREntity=={}",JsonUtil.toString(ruiZhenOCREntity)); + } + + return ruiZhenOCREntity; + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/IdentifyOcrService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/IdentifyOcrService.java new file mode 100644 index 0000000..6332eaa --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/IdentifyOcrService.java @@ -0,0 +1,318 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.ClientHttpRequest; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.http.ClientHttps; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; +import com.cmsen.ticket.infrastructure.ocr2.entity.IdentifyFileEntity; +import com.cmsen.ticket.infrastructure.ocr2.entity.IdentifyOcrEntity; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.springframework.http.*; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @date 2024/9/12 15:26 + * @description FANHAN文件识别 + */ +@Component +@Slf4j +public class IdentifyOcrService { + + @Resource + private SysConfigMapper sysConfigMapper; + @Resource + private RestTemplateConfig restTemplateConfig; + + + public IdentifyOcrEntity billsCrop(String base64) { + + //获取接口相关参数 + Map param = new HashMap<>(); + List sys_ls = sysConfigMapper.list("FH_API_"); + for (SysConfig val : sys_ls) { + param.put(val.getCode(), val.getValue()); + } + + String token = getToken(param); + log.info("billsCrop======token==={}", token); + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + + Map map = new LinkedHashMap<>(); + map.put("jsonrpc", "2.0"); + map.put("method", param.get("FH_API_identify_method")); + map.put("id", "1"); + map.put("session", ""); + //map.put("ctx", ""); + map.put("timestampin", timestamp); + + Map params = new LinkedHashMap<>(); + params.put("id", param.get("FH_API_identify_inv_id")); + params.put("publish_id", param.get("FH_API_identify_inv_pid")); + params.put("content", ""); + params.put("input_base64_string", "data:image/jpeg;base64," + base64); + map.put("params", params); + + String requestStr = JSONObject.toJSON(map).toString(); + log.info("billsCrop======requestStr=={}", requestStr); + +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(60000) +// .setUrl(param.get("FH_API_identify_url")) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("session", token) +// .setParams(requestStr) +// ); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(requestStr, headers); + RestTemplate client = restTemplateConfig.restTemplate(); + ResponseEntity responseEntity = null; + try { + responseEntity = client.exchange( + param.get("FH_API_identify_url"), + HttpMethod.POST, + entity, + String.class + ); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + + log.info("billsCrop======response===={}", response); + try { + JSONObject res = JSONObject.parseObject(response.toString()); + if (res.getJSONObject("result") != null) { + IdentifyOcrEntity identifyOcrEntity = JsonUtil.toClass(response.toString(), IdentifyOcrEntity.class); + return identifyOcrEntity; + } + } catch (Exception e) { + log.info("billsCrop====response== 异常:{}", e.getMessage()); + } + + /*// 创建HttpClient实例 + CloseableHttpClient httpClient = HttpClients.createDefault(); + + // 创建HttpPost实例,指定请求的URL + HttpPost httpPost = new HttpPost(url); + + // 设置请求体为JSON字符串 + Map map = new LinkedHashMap<>(); + map.put("jsonrpc", "2.0"); + map.put("method", "/document/extract/call"); + map.put("id", "1"); + map.put("session", ""); + //map.put("ctx", ""); + map.put("timestampin", timestamp); + + Map params = new LinkedHashMap<>(); + params.put("id", 33); + params.put("publish_id", 18); + params.put("content", ""); + params.put("input_base64_string", base64); + map.put("params", params); + String requestStr = JSONObject.toJSON(map).toString(); + log.info("AI======requestStr==={}",requestStr); + try { + StringEntity requestEntity = new StringEntity(requestStr); + requestEntity.setContentType("application/json"); + httpPost.setEntity(requestEntity); + // 执行请求并获得响应 + CloseableHttpResponse response = httpClient.execute(httpPost); + response.addHeader("Content-Type", "application/json"); + response.addHeader("session", token); + // 获取响应实体 + HttpEntity responseEntity = response.getEntity(); + + // 打印响应内容 + String responseString = EntityUtils.toString(responseEntity); + log.info("AI ==== responseString=="+responseString); + + IdentifyOcrEntity identifyOcrEntity = JsonUtil.toClass(response.toString(), IdentifyOcrEntity.class); + + // 关闭response + response.close(); + + return identifyOcrEntity; + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + }*/ + + return null; + } + + public IdentifyFileEntity filesCrop(String base64) { + //获取接口相关参数 + Map param = new HashMap<>(); + List sys_ls = sysConfigMapper.list("FH_API_"); + for (SysConfig val : sys_ls) { + param.put(val.getCode(), val.getValue()); + } + + String token = getToken(param); + log.info("filesCrop======token==={}", token); + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + + Map map = new LinkedHashMap<>(); + map.put("jsonrpc", "2.0"); + map.put("method", param.get("FH_API_identify_method")); + map.put("id", "1"); + map.put("session", ""); + //map.put("ctx", ""); + map.put("timestampin", timestamp); + + Map params = new LinkedHashMap<>(); + params.put("id", param.get("FH_API_identify_file_id")); + params.put("publish_id", param.get("FH_API_identify_file_pid")); + params.put("content", ""); + params.put("input_base64_string", "data:image/jpeg;base64," + base64); + map.put("params", params); + + String requestStr = JSONObject.toJSON(map).toString(); + log.info("filesCrop======requestStr=={}", requestStr); + + ClientHttpResponse response = ClientHttps.post( + new ClientHttpRequest() + .setTimeOut(60000) + .setUrl(param.get("FH_API_identify_url")) + .setHeaders("Content-Type", ContentEnctype.JSON) + .setHeaders("session", token) + .setParams(requestStr) + ); + + log.info("filesCrop======response===={}", response); + try { + JSONObject res = JSONObject.parseObject(response.toString()); + if (res.getJSONObject("result") != null) { + IdentifyFileEntity identifyFileEntity = JsonUtil.toClass(response.toString(), IdentifyFileEntity.class); + return identifyFileEntity; + } + } catch (Exception e) { + log.info("filesCrop====response== 异常:{}", e.getMessage()); + } + return null; + } + + public String filesCrop_single(String base64, String code) { + //获取接口相关参数 + Map param = new HashMap<>(); + List sys_ls = sysConfigMapper.list("FH_API_"); + for (SysConfig val : sys_ls) { + param.put(val.getCode(), val.getValue()); + } + + String token = getToken(param); + log.info("filesCrop_single======token==={}", token); + + Map map = new LinkedHashMap<>(); + map.put("file", base64); + map.put("code", code); + String requestStr = JSONObject.toJSON(map).toString(); + log.info("filesCrop_single======requestStr=={}", requestStr); + + ClientHttpResponse response = ClientHttps.post( + new ClientHttpRequest() + .setTimeOut(60000) + .setUrl(param.get("FH_API_identify_baseUrl") + param.get("FH_API_identify_url")) + .setHeaders("Content-Type", ContentEnctype.JSON) + .setHeaders("session", token) + .setParams(requestStr) + ); + + log.info("filesCrop_single======response===={}", response.toString()); + return response.toString(); + } + + public String getToken(Map param) { + log.info("AI====getToken====="); + String token = ""; + + // 创建HttpClient实例 + CloseableHttpClient httpClient = HttpClients.createDefault(); + + // 创建HttpPost实例,指定请求的URL + HttpPost httpPost = new HttpPost(param.get("FH_API_token_url")); + + // 设置请求体为JSON字符串 + Map map = new LinkedHashMap<>(); + map.put("jsonrpc", "2.0"); + map.put("method", param.get("FH_API_token_method")); + + Map params = new LinkedHashMap<>(); + params.put("username", param.get("FH_API_username")); + params.put("password", param.get("FH_API_password")); + map.put("params", params); + + String requestStr = JSONObject.toJSON(map).toString(); + + try { + StringEntity requestEntity = new StringEntity(requestStr); + requestEntity.setContentType("application/json"); + httpPost.setEntity(requestEntity); + + // 执行请求并获得响应 + CloseableHttpResponse response = httpClient.execute(httpPost); + response.addHeader("Content-Type", "application/json"); + // 获取响应实体 + org.apache.http.HttpEntity responseEntity = response.getEntity(); + + // 打印响应内容 + String responseString = EntityUtils.toString(responseEntity); + log.info("AI getToken responseString==" + responseString); + + JSONObject obj = JSONObject.parseObject(responseString); + JSONObject result = obj.getJSONObject("result"); + if (null != result) { + token = result.getString("token"); + } + // 关闭response + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return token; + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/NDOcrService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/NDOcrService.java new file mode 100644 index 0000000..59016d5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/NDOcrService.java @@ -0,0 +1,146 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.io.File; +import java.util.*; + +/** + * @author OWTS + * @date 2025/7/10 09:26 + * @description ND文件识别 + */ +@Component +@Slf4j +public class NDOcrService { + + @Resource + private SysConfigMapper sysConfigMapper; + @Resource + private SysUserMapper sysUserMapper; + @Resource + private RestTemplateConfig restTemplateConfig; + + public JSONObject ndApiRequest(String ndSearchCode, File imgFile) { + JSONObject jsonDataResult = null; + try { + //走新型的VL模型识别 + SysConfig ndOcrBasePathConfig = sysConfigMapper.selectByCode("ND_OCR_BASE_PATH"); + if (null == ndOcrBasePathConfig) { + log.error("未配置匹配模型地址"); + return null; + } + String ndOcrBasePath = ndOcrBasePathConfig.getValue(); + //走新型的VL模型识别 + String interfaceListSql = "select id,interface_name interfaceName,nd_model_no ndModelNo from data_obj_interface where interface_name = '" + ndSearchCode + "'"; + List> interfaceList = sysUserMapper.execSelectSql(interfaceListSql); + if (interfaceList.isEmpty()) { + log.error("未配置匹配模型"); + return null; + } + // 模型唯一标识 + String ndOcrVLModelNo = String.valueOf(interfaceList.get(0).get("ndModelNo")); + + String apiUrl = ndOcrBasePath + ndOcrVLModelNo; + log.info("NDOcrService====api_url:{}", apiUrl); + + String base64 = Pdf2JpgHelper.fileToBase64(imgFile); + JSONObject body = new JSONObject(); + JSONObject asset = new JSONObject(); + asset.put("type", "file"); + asset.put("base64", base64); + asset.put("name", imgFile.getName()); + body.put("asset", asset); + + Map resultEntity = this.billsCropFHByNd(apiUrl, body); + jsonDataResult = (JSONObject) resultEntity.get("result"); + log.info("NDOcrService===jsonDataResult======{}", jsonDataResult); + } catch (Exception e) { + log.error("nd api {} => error ={} ", ndSearchCode, e.getMessage()); + } + return jsonDataResult; + } + + /** + * 繁瀚接口调用 + * + * @param api + * @param body : application/pdf or image/jpeg + * @return + */ + public Map billsCropFHByNd(String api, JSONObject body) throws Exception { + Map result = new HashMap<>(); + + SysConfig sysConfig = sysConfigMapper.selectByCode("ND_SECRET"); + + long timeLong = new Date().getTime(); + String uuid = UUID.randomUUID().toString(); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(300000) +// .setUrl(api+"?timestamp="+timeLong+"&uuid="+uuid) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("secret", sysConfig != null ? sysConfig.getValue() : "74a5c2bd-0e83-43b9-9578-24e39939d47b") +// .setParams(JsonUtil.toString(body)) +// ); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("secret", sysConfig != null ? sysConfig.getValue() : "74a5c2bd-0e83-43b9-9578-24e39939d47b"); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(body), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + ResponseEntity responseEntity = null; + try { + responseEntity = client.exchange( + api + "?timestamp=" + timeLong + "&uuid=" + uuid, + HttpMethod.POST, + entity, + String.class + ); + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + +// log.info("FH-ND url>>" + api+"?timestamp="+timeLong+"&uuid="+uuid); + +// log.info("FH-ND Params>>" + JsonUtil.toString(body)); + + if (null == response.getBody()) { + log.info("FH-ND MESSAGE status>>{}", response.getStatus()); + log.info("FH-ND MESSAGE body>>{}", response.getBody()); + log.info("FH-ND MESSAGE message>>{}", response.getMessage()); + throw new Exception("OCR 接口返回异常>" + response.getMessage()); + } + log.info("FH-ND nd Result>> {}", response); + + int status = response.getStatus(); + result.put("status", status); + result.put("message", response.getMessage()); + String responseBody = response.getBody().toString(); + JSONObject apiResult = JSONObject.parseObject(responseBody); + JSONObject dataResult = apiResult.getJSONObject("data"); + JSONObject jsonDataResult = dataResult.getJSONObject("json_data"); + result.put("result", jsonDataResult); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/OFDUtil.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/OFDUtil.java new file mode 100644 index 0000000..7804b62 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/OFDUtil.java @@ -0,0 +1,164 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import com.cmsen.common.util.JsonUtil; +import com.cmsen.ofd.OFDConverter; +import com.cmsen.ofd.bean.ofd.OFDeInvoice; +import com.cmsen.ticket.domain.util.FileImgUtil; +import com.cmsen.ticket.domain.util.hly.FileUtils; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import lombok.extern.slf4j.Slf4j; +import org.ofdrw.converter.ImageMaker; +import org.ofdrw.reader.OFDReader; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +@Slf4j +public class OFDUtil { + + /** + * 多页 OFD 转 多页 PDF(直接转,不经过中间JPG) + */ + + + /** + * OFD转图片序列 + * @param ofdPath 输入文件路径 + * @param outputDir 输出目录 + * @param dpi 图片分辨率(建议300) + */ + public static void convertToPdf(String ofdPath, String outputDir, int dpi) throws Exception { + try (OFDReader reader = new OFDReader(ofdPath)) { + ImageMaker maker = new ImageMaker(reader, dpi); + int pages = maker.pageSize(); + if(1==pages){ + BufferedImage image = maker.makePage(0); + String jpgPath = outputDir.replace(".pdf",".jpg"); + ImageIO.write(image, "jpg", new File(jpgPath)); + FileImgUtil.jpg2PDF(jpgPath,outputDir); + }else{ + List jpgs = new ArrayList<>(); + for(int i=0;i> {} >> {}", ofdPath, imgPath); + OFDConverter.toImageJpeg(ofdPath, imgPath, 12); + OFDeInvoice ofDeInvoice = OFDConverter.toObjectData(ofdPath); + log.info("OFD >> RESULT >> {}", JsonUtil.toString(ofDeInvoice)); + if (ofDeInvoice != null) { + RuiZhenOCREntity results = ofdInvoiceToRuiZhenOcr(ofDeInvoice); + log.info("OFD >> TO RUIZHEN >> {}", JsonUtil.toString(results)); + return results; + } + return null; + } + + + public static boolean dealOFDToJPEG(String ofdPath, String imgPath) { + try { + OFDConverter.toImageJpeg(ofdPath, imgPath, 12); + return true; + } catch (Exception e) { + log.error(e.getMessage(), e); + return false; + } + } + + public static void dealOFDToJPEG2(String filename, String dirPath, String jpgName) throws IOException { + Files.createDirectories(Paths.get(dirPath)); + //filename文件路径到文件名 + Path src = Paths.get(filename); + + ImageMaker imageMaker = new ImageMaker(new OFDReader(src), 15); + imageMaker.config.setDrawBoundary(false); + for (int i = 0; i < imageMaker.pageSize(); i++) { + BufferedImage image = imageMaker.makePage(i); + //文件要存的路径 第二个是文件名 + //如果需要的png格式,就将后面的jpg改为png就好了。 + Path dist = Paths.get(dirPath, jpgName); + ImageIO.write(image, "JPG", dist.toFile()); + } + } + + private static RuiZhenOCREntity ofdInvoiceToRuiZhenOcr(OFDeInvoice ofDeInvoice) { + RuiZhenOCREntity ruiZhenOCREntity = new RuiZhenOCREntity(); + RuiZhenOCREntity.IdentifyResults result = new RuiZhenOCREntity.IdentifyResults(); + result.setType("10102"); + Details details = new Details(); + details.setCode(ofDeInvoice.getInvoiceCode()); + details.setNumber(ofDeInvoice.getInvoiceNo()); + details.setDate(ofDeInvoice.getIssueDate()); + details.setCheck_code(ofDeInvoice.getInvoiceCheckCode()); + details.setMachine_code(ofDeInvoice.getMachineNo()); + details.setBuyer(ofDeInvoice.getBuyer().getName()); + details.setBuyer_tax_id(ofDeInvoice.getBuyer().getTaxId()); + details.setSeller(ofDeInvoice.getSeller().getName()); + details.setSeller_tax_id(ofDeInvoice.getSeller().getTaxId()); + details.setTotal(ofDeInvoice.getTaxInclusiveTotalAmount()); + details.setRemark(ofDeInvoice.getNote()); + details.setTax(ofDeInvoice.getTaxTotalAmount()); + details.setPretax_amount(ofDeInvoice.getTaxExclusiveTotalAmount()); + List items = new ArrayList<>(); + List goodsInfo = ofDeInvoice.getGoodsInfos().getGoodsInfo(); + goodsInfo.forEach(good -> items.add(new Item() {{ + setName(good.getItem()); + setSpecification(good.getSpecification()); + setPrice(good.getPrice()); + setQuantity(good.getQuantity()); + setTax(good.getTaxAmount()); + setTax_rate(good.getTaxAmount()); + setTotal(good.getAmount()); + }})); + details.setItems(items); + result.setDetails(details); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(new ArrayList() {{ + add(result); + }}); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + response.setData(ocrData); + ruiZhenOCREntity.setResponse(response); + return ruiZhenOCREntity; + } + + public static void main(String[] args) throws Exception { + String ofdPath = "D:\\1.ofd"; + String pdfPath = "D:\\1.pdf"; + convertToPdf(ofdPath,pdfPath,12); +// try { +// int size = 12; +// for(int i=1;i<=12;i++){ +// convertToPdf("E:\\桌面\\常用测试发票\\ofds\\"+i+".ofd","E:\\桌面\\常用测试发票\\ofds\\"+i+".pdf",12); +// } +//// String url = "https://bztic-gs-files-prod.oss-cn-shanghai.aliyuncs.com/prod/OMS4-PROD/20250116/090619033/250116164025_5cf3.pdf"; +//// String pdfUrlName = url.substring(url.lastIndexOf("/")); +//// File file = HttpUtil.downloadFileFromUrl(url, new File("D:\\250116164025_5cf312.pdf"),60000); +//// dealOFDInvoice("C:\\Users\\OWTS\\Desktop\\031001800311_63282833_I8E7A1C8.ofd", "C:\\Users\\OWTS\\Desktop\\1.jpeg"); +// } catch (Exception e) { +// e.printStackTrace(); +// log.error(e.getMessage(), e); +// } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/QrOcrService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/QrOcrService.java new file mode 100644 index 0000000..b928171 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/QrOcrService.java @@ -0,0 +1,73 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import cn.hutool.http.HttpUtil; +import cn.hutool.json.JSONUtil; +import com.cmsen.common.exception.ServiceException; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.QrOcrEntity; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import lombok.extern.slf4j.Slf4j; + +import java.io.File; + +/* + * @author OWTS + * @date 2021/4/19 + * @desc + */ +@Slf4j +public class QrOcrService { + public static void verifyQrCode(RuiZhenOCREntity.IdentifyResults result, String imgFilePath) { + QrOcrEntity qrOcrEntity; + try { + File file = new File(imgFilePath); + String obj = HttpUtil.createPost("http://invoice-qrcode.datavector.cn:31808/cgi/graphCode/invoice") + .header("Content-Type", "multipart/form-data; boundary=") + .form("file", file) + .execute().body(); + qrOcrEntity = JSONUtil.toBean(obj, QrOcrEntity.class); + log.info("QR CODE>>{}", qrOcrEntity); + if (!qrOcrEntity.getStatus().equals(200)) { + throw new ServiceException("请求失败,重试中."); + } + } catch (Exception e) { +// log.error(e.getMessage(),e); + try { + File file = new File(imgFilePath); + String obj = HttpUtil.createPost("http://invoice-qrcode.datavector.cn:31808/cgi/graphCode/invoice") + .header("Content-Type", "multipart/form-data; boundary=") + .form("file", file) + .execute().body(); + qrOcrEntity = JSONUtil.toBean(obj, QrOcrEntity.class); + log.info("QR CODE>>{}", qrOcrEntity); + } catch (Exception e1) { + e1.printStackTrace(); + return; + } + } + if (qrOcrEntity == null) { + return; + } + if (qrOcrEntity.getStatus().equals(200)) { + QrOcrEntity.Result ocrEntityResult = qrOcrEntity.getResult(); + Details details = result.getDetails(); + if (StringUtil.isNotEmpty(ocrEntityResult.getCode())) { + details.setCode(ocrEntityResult.getCode()); + } + if (StringUtil.isNotEmpty(ocrEntityResult.getNo())) { +// details.setNumberBackup(details.getNumber()); + details.setNumber(ocrEntityResult.getNo()); + } + if (StringUtil.isNotEmpty(ocrEntityResult.getAmount())) { + details.setPretax_amount(ocrEntityResult.getAmount()); + } + if (StringUtil.isNotEmpty(ocrEntityResult.getDate())) { + details.setDate(ocrEntityResult.getDate()); + } + if (StringUtil.isNotEmpty(ocrEntityResult.getCheckCode())) { + details.setCheck_code(ocrEntityResult.getCheckCode()); + } + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/RuiZhenOCRService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/RuiZhenOCRService.java index 8e58f99..246ee44 100644 --- a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/RuiZhenOCRService.java +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/RuiZhenOCRService.java @@ -1,24 +1,37 @@ package com.cmsen.ticket.infrastructure.ocr2; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.util.Base64Util; import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ofd.OFDConverter; import com.cmsen.ticket.bestsign.util.InterfaceUtil; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoiceItems; +import com.cmsen.ticket.domain.entity.CorporateInvoiceNdJsonMapping; +import com.cmsen.ticket.domain.entity.SupplierMaterialUom; import com.cmsen.ticket.domain.entity.manager.SysConfig; -import com.cmsen.ticket.domain.mapper.CorporateInvoiceMapper; -import com.cmsen.ticket.domain.mapper.SupplierMapper; -import com.cmsen.ticket.domain.mapper.SupplierMaterialUomMapper; +import com.cmsen.ticket.domain.mapper.*; import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.util.ReflectionUtil; +import com.cmsen.ticket.domain.util.StringUtils; import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; +import com.cmsen.ticket.infrastructure.ocr2.entity.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import javax.annotation.Resource; +import java.io.File; +import java.math.BigDecimal; import java.util.*; @@ -40,13 +53,20 @@ public class RuiZhenOCRService { @Resource private SupplierMapper supplierMapper; + @Resource + private SmarttaxService smarttaxService; + @Resource private SysConfigMapper sysConfigMapper; + @Resource + private TicketTypeMapper ticketTypeMapper; @Resource private CorporateInvoiceMapper corporateInvoiceMapper; + @Resource + private CorporateInvoiceNdJsonMappingMapper corporateInvoiceNdJsonMappingMapper; @Resource private SysUserMapper sysUserMapper; private String verify_invoice_interface_str; @@ -81,6 +101,633 @@ public class RuiZhenOCRService { private String appKey; @Value("${spring.ccintocr.app_secret}") private String appSecret; + + public RuiZhenOCREntity billsCrop(String base64) { + + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String oldCode = appKey + "+" + timestamp + "+" + appSecret; + String token = DigestUtils.md5DigestAsHex(oldCode.getBytes()); + HashMap params = new HashMap<>(); + params.put("app_key", appKey); + params.put("image_data", base64); + params.put("timestamp", timestamp); + params.put("token", token); + log.info("billsCrop>>token>>{}", token); + // 20231205写活 + String rzUrl = "https://fapiao.glority.cn/v1/item/get_multiple_items_info"; + SysConfig rzConf = sysConfigMapper.selectByCode("RZ_OCR_URL"); + if (rzConf != null && rzConf.getValue().length() > 0) { + rzUrl = rzConf.getValue(); + } +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setUrl(rzUrl) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setParams(JsonUtil.toString(params)) +// ); + + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + ResponseEntity responseEntity = null; + try { + responseEntity = client.exchange( + rzUrl, + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + log.info("OCR Result>>" + response); + RuiZhenOCREntity ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + if ("1".equals(details.getElectronic_mark()) && identifyResult.getType().equals("10100")) { + identifyResult.setType("10106"); + } + details.setNumberBackup(details.getNumber()); + // 如果是航空客运形成单 则需要把发票号码重新映射 + String type = identifyResult.getType(); + if ("10506".equals(type)) { + String receiptNumber = details.getReceipt_number(); + details.setNumber(receiptNumber); + } + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public RuiZhenOCREntity billsCropTest(String base64, String rzUrl) { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String oldCode = appKey + "+" + timestamp + "+" + appSecret; + String token = DigestUtils.md5DigestAsHex(oldCode.getBytes()); + HashMap params = new HashMap<>(); + params.put("app_key", appKey); + params.put("image_data", base64); + params.put("timestamp", timestamp); + params.put("token", token); +// String rzUrl = "https://fapiao.glority.cn/v1/item/get_multiple_items_info"; +// SysConfig rzConf = sysConfigMapper.selectByCode("RZ_OCR_URL"); +// if(rzConf!=null && rzConf.getValue().length()>0){ +// rzUrl =rzConf.getValue(); +// } +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setUrl(rzUrl) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setParams(JsonUtil.toString(params)) +// ); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + try { + ResponseEntity responseEntity = client.exchange( + rzUrl, + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + log.info("OCR Result test>>" + response); + RuiZhenOCREntity ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + if ("1".equals(details.getElectronic_mark()) && identifyResult.getType().equals("10100")) { + identifyResult.setType("10106"); + } + details.setNumberBackup(details.getNumber()); + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + + } + + /** + * pdf解析 + * + * @param base64 + * @return + */ + public RuiZhenOCREntity billsCropPdf(String base64) { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String oldCode = appKey + "+" + timestamp + "+" + appSecret; + String token = DigestUtils.md5DigestAsHex(oldCode.getBytes()); + HashMap params = new HashMap<>(); + params.put("app_key", appKey); + params.put("image_data", base64); + params.put("timestamp", timestamp); + params.put("token", token); + // 20231205写活 + String rzUrl = "https://fapiao.glority.cn/v1/item/get_item_info"; + SysConfig rzConf = sysConfigMapper.selectByCode("RZ_OCR_URL_PDF"); + if (rzConf != null && rzConf.getValue().length() > 0) { + rzUrl = rzConf.getValue(); + } +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setUrl(rzUrl) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setParams(JsonUtil.toString(params)) +// ); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + try { + ResponseEntity responseEntity = client.exchange( + rzUrl, + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + + log.info("OCR file Result>>" + response); + RuiZhenOCREntity ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + if ("1".equals(details.getElectronic_mark()) && identifyResult.getType().equals("10100")) { + identifyResult.setType("10106"); + } + details.setNumberBackup(details.getNumber()); + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 繁瀚接口调用 + * + * @param base64 + * @param title : application/pdf or image/jpeg + * @return + */ + public RuiZhenOCREntity billsCropFHWithTitle(String base64, String title) throws Exception { + String token = ""; + SysConfig config = null; + config = sysConfigMapper.selectByCode("OCR_INTERFACE_FH"); + SysConfig isToken = sysConfigMapper.selectByCode("OCR_INTERFACE_TOKEN"); + if (config == null) { + log.error("FOCR_INTERFACE_FH为空"); + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + if (isToken != null && isToken.getValue().equals("true")) { + token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + log.info("AI-token{}", token); + } + HashMap params = new HashMap<>(); + params.put("data", "data:" + title + ";base64," + base64); + long timeLong = new Date().getTime(); + String uuid = UUID.randomUUID().toString(); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(300000) +// .setUrl(config.getValue()+"?timestamp="+timeLong+"&uuid="+uuid) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("session", token) +// .setParams(JsonUtil.toString(params)) +// ); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + try { + ResponseEntity responseEntity = client.exchange( + config.getValue() + "?timestamp=" + timeLong + "&uuid=" + uuid, + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } +// log.info("FH-OCR Params>>" + JsonUtil.toString(params)); + if (null == response.getBody()) { + log.info("FH-OCR MESSAGE status>>{}", response.getStatus()); + log.info("FH-OCR MESSAGE body>>{}", response.getBody()); + log.info("FH-OCR MESSAGE message>>{}", response.getMessage()); + throw new Exception("OCR 接口返回异常>" + response.getMessage()); + } + log.info("FH-OCR billsCropFHWithTitle Result>> {}", response); + RuiZhenOCREntity ruiZhenOCREntity = null; + if (!response.toString().startsWith("{")) { + return null; + } + try { + ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + if ("1".equals(details.getElectronic_mark()) && identifyResult.getType().equals("10100")) { + identifyResult.setType("10106"); + } + String vehicle_mark = details.getVehicle_mark(); + if ("1".equals(vehicle_mark) && identifyResult.getType().equals("10107")) { + identifyResult.setType("10108"); + } + details.setNumberBackup(details.getNumber()); + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 繁瀚接口调用 + * + * @param base64 + * @return + */ + public RuiZhenOCREntity billsCropFH(String base64) throws Exception { + String token = ""; + SysConfig config = null; + config = sysConfigMapper.selectByCode("OCR_INTERFACE_FH"); + SysConfig isToken = sysConfigMapper.selectByCode("OCR_INTERFACE_TOKEN"); + if (config == null) { + log.error("FOCR_INTERFACE_FH为空"); + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + if (isToken != null && isToken.getValue().equals("true")) { + token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + log.info("AI-token{}", token); + } + HashMap params = new HashMap<>(); + params.put("data", "data:image/jpeg;base64," + base64); + long timeLong = new Date().getTime(); + String uuid = UUID.randomUUID().toString(); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(300000) +// .setUrl(config.getValue()+"?timestamp="+timeLong+"&uuid="+uuid) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("session", token) +// .setParams(JsonUtil.toString(params)) +// ); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + try { + ResponseEntity responseEntity = client.exchange( + config.getValue() + "?timestamp=" + timeLong + "&uuid=" + uuid, + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } +// log.info("FH-OCR Params>>" + JsonUtil.toString(params)); + if (null == response.getBody()) { + log.info("FH-OCR MESSAGE status>>{}", response.getStatus()); + log.info("FH-OCR MESSAGE body>>{}", response.getBody()); + log.info("FH-OCR MESSAGE message>>{}", response.getMessage()); + throw new Exception("OCR 接口返回异常>" + response.getMessage()); + } + log.info("FH-OCR Result>> {}", response); + RuiZhenOCREntity ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + if ("1".equals(details.getElectronic_mark()) && identifyResult.getType().equals("10100")) { + identifyResult.setType("10106"); + } + String vehicle_mark = details.getVehicle_mark(); + if ("1".equals(vehicle_mark) && identifyResult.getType().equals("10107")) { + identifyResult.setType("10108"); + } + details.setNumberBackup(details.getNumber()); + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 繁瀚电子发票接口调用 + * + * @param base64 + * @return + */ + public RuiZhenOCREntity billsCropFHOfElectronic(String base64) { + String token = ""; + SysConfig config = null; + config = sysConfigMapper.selectByCode("OCR_INTERFACE_ELECTRONIC_URL"); + SysConfig isToken = sysConfigMapper.selectByCode("OCR_INTERFACE_TOKEN"); + if (config == null) { + log.error("FOCR_INTERFACE_FH为空"); + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + if (isToken != null && isToken.getValue().equals("true")) { + token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + log.info("AI-token{}", token); + } + HashMap params = new HashMap<>(); + params.put("data", "data:application/pdf;base64," + base64); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(300000) +// .setUrl(config.getValue()) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("session", token) +// .setParams(JsonUtil.toString(params)) +// ); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + + try { + ResponseEntity responseEntity = client.exchange( + config.getValue(), + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + + log.info("FH-OCR-ELECTRONIC Result>>" + response); + RuiZhenOCREntity fhOcrEntity = null; + if (!response.toString().startsWith("{")) { + return null; + } + + fhOcrEntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == fhOcrEntity.getResult()) { + return null; + } + if (1 == fhOcrEntity.getResult()) { + List identifyResults = fhOcrEntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + details.setNumberBackup(details.getNumber()); + // 如果是航空客运形成单 则需要把发票号码重新映射 + String type = identifyResult.getType(); + if ("10506".equals(type)) { + String receiptNumber = details.getReceipt_number(); + details.setNumber(receiptNumber); + } + + } + + } + return fhOcrEntity; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 繁瀚海外发票解析 RuizhenOcrEntity + * + * @return + */ + public RuiZhenOCREntity billsCropFHOfnd(String ndSearchCode, File file) { + JSONObject jsonDataResult = ndApiRequest(ndSearchCode, file); + if (null == jsonDataResult) { + log.error("nd api response not setting or error"); + return null; + } + List mappingList = null; + RuiZhenOCREntity ocrEntity = new RuiZhenOCREntity(); +// ocrEntity.getResponse().getData().getIdentify_results() + List identify_results = new ArrayList<>(); + RuiZhenOCREntity.IdentifyResults identifyResults = new RuiZhenOCREntity.IdentifyResults(); + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable(ndSearchCode, "invoice"); + Details corporateInvoice = new Details(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = jsonDataResult.get(source); + ReflectionUtil.setFieldValue(corporateInvoice, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + + mappingList = corporateInvoiceNdJsonMappingMapper.listAvailable(ndSearchCode, "items"); + List itemList = new ArrayList<>(); + JSONArray itemArr = jsonDataResult.getJSONArray("items"); + for (int i = 0; i < itemArr.size(); i++) { + JSONObject itemObject = itemArr.getJSONObject(i); + Item corporateInvoiceItems = new Item(); + for (CorporateInvoiceNdJsonMapping entity : mappingList) { + String source = entity.getMappingSource(); + String dest = entity.getMappingDest(); + Object sourceValue = itemObject.get(source); + ReflectionUtil.setFieldValue(corporateInvoiceItems, dest, String.valueOf(null == sourceValue ? "" : sourceValue)); + } + itemList.add(corporateInvoiceItems); + } +// corporateInvoice.setCode("60100"); + corporateInvoice.setItems(itemList); + identifyResults.setDetails(corporateInvoice); + identifyResults.setType("60100"); + identify_results.add(identifyResults); + RuiZhenOCREntity.Response response = new RuiZhenOCREntity.Response(); + RuiZhenOCREntity.OCRData ocrData = new RuiZhenOCREntity.OCRData(); + ocrData.setIdentify_results(identify_results); + response.setData(ocrData); + ocrEntity.setResponse(response); + return ocrEntity; + } + + public JSONObject ndApiRequest(String ndSearchCode, File file) { + JSONObject jsonDataResult = null; + try { + //走新型的VL模型识别 + SysConfig ndOcrBasePathConfig = sysConfigMapper.selectByCode("ND_OCR_BASE_PATH"); + // http://nd.fanhaninfo.test/api/server/nd/ + if (null == ndOcrBasePathConfig) { + log.error("形式发票识别未配置匹配模型地址"); + return null; + } + String ndOcrBasePath = ndOcrBasePathConfig.getValue(); + //走新型的VL模型识别 + String interfaceListSql = "select id,interface_name interfaceName,nd_model_no ndModelNo from data_obj_interface where interface_name = 'proforma_invoice'"; + List> interfaceList = sysUserMapper.execSelectSql(interfaceListSql); + // http://nd.fanhaninfo.test/ + if (interfaceList.isEmpty()) { + log.error("形式发票识别未配置匹配模型"); + return null; + } + // 模型唯一标识 + String ndOcrVLModelNo = String.valueOf(interfaceList.get(0).get("ndModelNo")); + + String apiUrl = ndOcrBasePath + ndOcrVLModelNo; + log.info("api_url:{}", apiUrl); + // + String base64 = Pdf2JpgHelper.fileToBase64(file); + + JSONObject body = new JSONObject(); + JSONObject asset = new JSONObject(); + asset.put("type", "file"); +// asset.put("name",fileName); + asset.put("base64", base64); + body.put("asset", asset); + Map resultEntity = this.billsCropFHByNd(apiUrl, body); + jsonDataResult = (JSONObject) resultEntity.get("result"); + } catch (Exception e) { + log.error("nd api {} => error ={} ", ndSearchCode, e.getMessage()); + } + return jsonDataResult; + } + + + /** + * 繁瀚形式发票接口调用 + * + * @param base64 + * @return + */ + public RuiZhenOCREntity billsCropFHOfProforma(String base64) { + String token = ""; + SysConfig config = null; + config = sysConfigMapper.selectByCode("OCR_INTERFACE_PROFORMA_URL"); + SysConfig isToken = sysConfigMapper.selectByCode("OCR_INTERFACE_TOKEN"); + if (config == null) { + log.error("FOCR_INTERFACE_FH为空"); + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + RestTemplate client = restTemplateConfig.restTemplate(); + if (isToken != null && isToken.getValue().equals("true")) { + token = interfaceUtil.getAiToken(sysConfigMapper, headers, client); + log.info("AI-token{}", token); + } + HashMap params = new HashMap<>(); + params.put("data", "data:application/pdf;base64," + base64); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setTimeOut(300000) +// .setUrl(config.getValue()) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("session", token) +// .setParams(JsonUtil.toString(params)) +// ); + headers.setContentType(MediaType.APPLICATION_JSON); +// headers.set("Content-Type", ContentEnctype.JSON); + headers.set("session", token); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(params), headers); + try { + ResponseEntity responseEntity = client.exchange( + config.getValue(), + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + log.info("FH-OCR-PROFORMA Result>>" + response); + RuiZhenOCREntity ruiZhenOCREntity = JsonUtil.toClass(response.toString(), RuiZhenOCREntity.class); + if (0 == ruiZhenOCREntity.getResult()) { + return null; + } else { + List identifyResults = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identifyResult : identifyResults) { + Details details = identifyResult.getDetails(); + identifyResult.setType("60100"); + details.setNumberBackup(details.getNumber()); + } + } + return ruiZhenOCREntity; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + + } + + /** * 繁瀚接口调用 * @@ -158,4 +805,566 @@ public class RuiZhenOCRService { // return null; } + + public boolean isNeedVerify(String code) { + return needVerifyCodes.contains(code); + } + + public boolean qrCode(String type) { + return qrCodeTypes.contains(type); + } + + //验真 + public RuiZhenOCRVerifyEntity verifyInvoice(RuiZhenVerifyForm verifyForm) { + //增加code的判断 2022/12/8 + verifyForm.setCode(verifyForm.getCode().equals("0000") ? "" : verifyForm.getCode()); + + //睿真 10100增专纸质票 10107增专电子票 需要税前金额 + if (verify_invoice_interface_str.equals("RZ")) { + if ("10107".equals(verifyForm.getType())) { + // verifyForm.setType("10100"); + // 20220415修改成10102 + verifyForm.setType("10102"); + } + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String oldCode = appKey + "+" + timestamp + "+" + appSecret; + String token = DigestUtils.md5DigestAsHex(oldCode.getBytes()); + verifyForm.setApp_key(appKey); + verifyForm.setToken(token); + verifyForm.setTimestamp(timestamp); + verifyForm.setIs_async(0); + log.info("Verify Last Data>>{}", JsonUtil.toString(verifyForm)); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setUrl("https://fapiao.glority.cn/v1/item/fapiao_validation") +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setParams(JsonUtil.toString(verifyForm)) +// ); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(verifyForm), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + ResponseEntity responseEntity = null; + try { + responseEntity = client.exchange( + "https://fapiao.glority.cn/v1/item/fapiao_validation", + HttpMethod.POST, + entity, + String.class + ); + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + log.info("RuiZhen Verify:>>" + response); + return JsonUtil.toClass(response.toString(), RuiZhenOCRVerifyEntity.class); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + //慧穗 + else if (verify_invoice_interface_str.equals("HS")) { + RuiZhenOCRVerifyEntity ruiZhenOCRVerifyEntity = smarttaxService.verifyInvoice(verifyForm); + log.info("HuiSui Verify:{}>>{}", verifyForm.getNumber(), JsonUtil.toString(ruiZhenOCRVerifyEntity)); + return ruiZhenOCRVerifyEntity; + } + //慧穗CDK 20230725 + else if (verify_invoice_interface_str.equals("HS-CDK")) { + RuiZhenOCRVerifyEntity ruiZhenOCRVerifyEntity = smarttaxService.verifyInvoiceCdk(verifyForm); + log.info("HuiSui-CDK Verify:{}>>{}", verifyForm.getNumber(), JsonUtil.toString(ruiZhenOCRVerifyEntity)); + return ruiZhenOCRVerifyEntity; + } + return null; + } + + public void verifyCorporateInvoice(CorporateInvoice invoice) { + log.info("====开始验真==={}", invoice.getVerifiedCode()); + + String checkCode = invoice.getVerifiedCode(); + log.info("1====checkCode==={}", checkCode); + + try { + boolean needVerify = isNeedVerify(invoice.getTicketCode()); + + invoice.setMessage("验真失败"); + invoice.setStatus(2); + invoice.setValidStatus((byte) 0); + + if (!needVerify) { + SysConfig SCANNER_TEST_MODE = sysConfigMapper.selectByCode("SCANNER_TEST_MODEL"); + if (null != SCANNER_TEST_MODE&&"1".equals(SCANNER_TEST_MODE.getValue())) { + invoice.setMessage("非供应商发票,未进行验真。"); + invoice.setStatus(0); + invoice.setValidStatus((byte) 2); + return; + }else{ + invoice.setMessage(""); + invoice.setStatus(0); + invoice.setValidStatus((byte) 1); + return; + } + + } + RuiZhenVerifyForm verifyForm = new RuiZhenVerifyForm(); + verifyForm.setCode(invoice.getCode()); + verifyForm.setNumber(invoice.getNumber()); + //String verifiedCode = checkCode; + log.info("2====checkCode==={}", checkCode); + log.info("3====checkCode==={}", invoice.getVerifiedCode()); + + //新增还是修改的判断 + if (StringUtil.isNotEmpty(invoice.getDataJson())) {//新增 + invoice.setCreateDate(new Date()); + log.info("====新增==={}", checkCode); + if (StringUtil.isNotEmpty(checkCode) && checkCode.length() >= 6) { + verifyForm.setCheck_code(checkCode.substring(checkCode.length() - 6)); + verifyForm.setCheck_code_all(checkCode); + } else { + RuiZhenOCREntity.IdentifyResults identifyResults = JsonUtil.toClass(invoice.getDataJson(), RuiZhenOCREntity.IdentifyResults.class); + Details details1 = identifyResults.getDetails(); + String electronic_number = details1.getElectronic_number(); + if (StringUtil.isNotEmpty(electronic_number) && electronic_number.length() >= 6 && "10101".equals(invoice.getTicketCode())) { + verifyForm.setCheck_code(electronic_number.substring(electronic_number.length() - 6)); + verifyForm.setCheck_code_all(electronic_number); + + //重新保存verifiedCode + invoice.setVerifiedCode(electronic_number); + } + } + } else {//修改保存 + log.info("====修改保存==={}", checkCode); + verifyForm.setCheck_code(StringUtil.isNotBlank(checkCode) && checkCode.length() >= 6 ? checkCode.substring(checkCode.length() - 6) : ""); + verifyForm.setCheck_code_all(checkCode); + } + + //判断发票号码的长度:超过15位取Total 2022/9/8 + if (invoice.getNumber().length() > 15) {//全电发票 + verifyForm.setPretax_amount(invoice.getTotal()); + if (null == verifyForm.getPretax_amount() || "".equals(verifyForm.getPretax_amount())) { + verifyForm.setPretax_amount(invoice.getPretaxAmount()); + } + } else { + verifyForm.setPretax_amount(invoice.getPretaxAmount()); + } + //verifyForm.setPretax_amount(invoice.getPretaxAmount()); + verifyForm.setDate(invoice.getDate()); + verifyForm.setType(invoice.getTicketCode()); + + if (verifyForm.getType().equals("10107")) { + // verifyForm.setType("10100"); + // 20220415修改成10102 + verifyForm.setType("10102"); + } + log.info("====verifyForm==={}", verifyForm); + +// String checkCode = corporateInvoice.getVerifiedCode(); +// if (StringUtil.isNotEmpty(checkCode) && checkCode.length() > 6) { +// verifyForm.setCheck_code(checkCode.substring(checkCode.length() - 6)); +// verifyForm.setCheck_code_all(checkCode); +// } +// String code = corporateInvoice.getTicketCode(); +// // 20220419小程序发票验证添加10104,10107 +// if ("10100".equals(code) || "10104".equals(code) || "10107".equals(code)) { +// verifyForm.setPretax_amount(corporateInvoice.getPretaxAmount()); +// } +// verifyForm.setDate(corporateInvoice.getDate()); +// verifyForm.setType(code); + // 开始验真 + RuiZhenOCRVerifyEntity verifyInvoice = verifyInvoice(verifyForm); + + +// String res = "{\"result\":0,\"response\":null,\"message\":\"资源限制次数达上限\",\"error\":20000}"; +// RuiZhenOCRVerifyEntity verifyInvoice = JsonUtil.toClass(res, RuiZhenOCRVerifyEntity.class); + if(null!=verifyInvoice){ + int vResult = verifyInvoice.getResult(); + if(0==vResult){ + //表示验真失败 + invoice.setMessage(invoice.getMessage() + ":" + verifyInvoice.getMessage()); + invoice.setMessage(verifyInvoice.getMessage()); + return; + } + } + boolean success = verifyInvoice.checkSuccess().isSuccess(); + if (success) { + // 20220415验真添加判断 + if (verifyInvoice.getResponse().getData().getIdentify_results().size() > 0) { + Details details = verifyInvoice.getResponse().getData().getIdentify_results().get(0).getDetails(); + if (details.getInvalid_mark() == null || details.getInvalid_mark().length() == 0) { + details.setInvalid_mark("0"); + } + if (details.getInvalid_mark() != null && !details.getInvalid_mark().equals("0")) { + //success = false; + invoice.setMessage("该发票已作废或撤消"); + invoice.setStatus(2); + invoice.setValidStatus((byte) 1); + return; + } + } + RuiZhenOCRVerifyEntity.IdentifyResults result = verifyInvoice.getResponse().getData().getIdentify_results().get(0); + Details details = result.getDetails(); + invoice.setTitle(details.getSeller()); + invoice.setSeller(details.getSeller()); + invoice.setCode(details.getCode()); + invoice.setNumber(details.getNumber()); + invoice.setDate(details.getDate()); + invoice.setSellerNo(details.getSeller_tax_id()); + invoice.setTotal(details.getTotal()); + invoice.setRemark(details.getRemark()); + invoice.setIsSend(0); + invoice.setUpdateDate(new Date()); + invoice.setBuyer(details.getBuyer()); + invoice.setBuyerNo(details.getBuyer_tax_id()); + invoice.setStatus(0); + invoice.setVerifiedCode(details.getCheck_code()); + invoice.setPretaxAmount(details.getPretax_amount()); + invoice.setTax(details.getTax()); + //invoice.setCreateDate(new Date()); + invoice.setCurrency("CNY"); + invoice.setChecked(0); + invoice.setPo(StringUtils.getPO(details.getRemark())); + + // 2023-05-25 + invoice.setExt02(details.getBuyer_bank_account()); + invoice.setExt03(details.getSeller_bank_account()); + invoice.setExt04(details.getBuyer_addr_tel()); + invoice.setExt05(details.getSeller_addr_tel()); + + List corporateInvoiceItems = new ArrayList<>(); + List items = details.getItems(); + // 判断是否是全负数。 验真正常 红字发票 + boolean isRedInvoice = true; + for (Item item : items) { + if (!item.getTotal().contains("-")) { + isRedInvoice = false; + } + } + if (isRedInvoice) { + if (items != null && !items.isEmpty()) { + for (Item item : items) { + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(invoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + setTax(item.getTax()); + setTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(item.getUnit()); + setOriginPrice(item.getPrice()); + setDifference(item.getTotal()); + }}); + } + } + } else { + if (items != null && !items.isEmpty()) { + for (Item item : items) { + //2022/8/16 + if (item.getName().contains("合计") || item.getName().contains("销货清单")) { + continue; + } + log.info("corporateInvoiceItems.size===>{}", corporateInvoiceItems.size()); + if (item.getTotal().contains("-")) { + if (corporateInvoiceItems.size() > 0) { + CorporateInvoiceItems corporateInvoiceItems1 = corporateInvoiceItems.get(corporateInvoiceItems.size() - 1); + corporateInvoiceItems1.setDeductionAmount(item.getTotal()); + corporateInvoiceItems1.setDeductionTaxRate(item.getTax_rate()); + corporateInvoiceItems1.setDeductionTax(item.getTax()); + // 添加差异计算20220620 + BigDecimal total = new BigDecimal(corporateInvoiceItems1.getTotal()); + BigDecimal deductionAmount = new BigDecimal(item.getTotal()); + corporateInvoiceItems1.setDifference(total.add(deductionAmount).toString()); + } else { + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(invoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setDeductionAmount(item.getTotal()); + setDeductionTax(item.getTax()); + setDeductionTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(getOriginUnit()); + setOriginPrice(item.getPrice()); + }}); + } + } else { + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(invoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + setTax(item.getTax()); + setTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(item.getUnit()); + setOriginPrice(item.getPrice()); + setDifference(item.getTotal()); + }}); + } + } + } + } + + + String supplier = supplierMapper.selectSupplierCode(invoice.getSellerNo()); + if (StringUtil.isNotEmpty(supplier)) { + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + if (StringUtil.isNotBlank(corporateInvoiceItem.getOriginPrice()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginUnit()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginQuantity())) { + SupplierMaterialUom uom = supplierMaterialUomMapper.selectByItem(supplier, corporateInvoiceItem.getSpecification(), corporateInvoiceItem.getName(), corporateInvoiceItem.getOriginUnit()); + if (null != uom) { + corporateInvoiceItem.setUnit(uom.getVersUnit()); + corporateInvoiceItem.setQuantity(String.valueOf(Double.parseDouble(corporateInvoiceItem.getOriginQuantity()) * Double.parseDouble(uom.getVersNum()))); + BigDecimal price = new BigDecimal(corporateInvoiceItem.getPrice()).divide(new BigDecimal(uom.getVersNum()), 4, BigDecimal.ROUND_HALF_UP); + corporateInvoiceItem.setPrice(price.toString()); + } + } + } + } + + invoice.setItems(corporateInvoiceItems); + invoice.setMessage(""); + invoice.setStatus(0); + invoice.setValidStatus((byte) 1); + + + } else { + // 20220415验真添加判断 + if (verifyInvoice.getResponse().getData().getIdentify_results().size() > 0) { + Details details = verifyInvoice.getResponse().getData().getIdentify_results().get(0).getDetails(); + invoice.setTitle(details.getSeller()); + invoice.setSeller(details.getSeller()); + invoice.setCode(details.getCode()); + invoice.setNumber(details.getNumber()); + invoice.setDate(details.getDate()); + invoice.setSellerNo(details.getSeller_tax_id()); + invoice.setTotal(details.getTotal()); + invoice.setRemark(details.getRemark()); + invoice.setIsSend(0); + invoice.setUpdateDate(new Date()); + invoice.setBuyer(details.getBuyer()); + invoice.setBuyerNo(details.getBuyer_tax_id()); + invoice.setVerifiedCode(details.getCheck_code()); + invoice.setPretaxAmount(details.getPretax_amount()); + invoice.setTax(details.getTax()); + //invoice.setCreateDate(new Date()); + invoice.setCurrency("CNY"); + invoice.setChecked(0); + invoice.setPo(StringUtils.getPO(details.getRemark())); + + // 2023-05-25 + invoice.setExt02(details.getBuyer_bank_account()); + invoice.setExt03(details.getSeller_bank_account()); + invoice.setExt04(details.getBuyer_addr_tel()); + invoice.setExt05(details.getSeller_addr_tel()); + + List corporateInvoiceItems = new ArrayList<>(); + List items = details.getItems(); + if (items != null && !items.isEmpty()) { + for (Item item : items) { + //2022/8/16 + if (item.getName().contains("合计") || item.getName().contains("销货清单")) { + continue; + } + log.info("corporateInvoiceItems.size===>{}", corporateInvoiceItems.size()); + if (item.getTotal().contains("-")) { + if (corporateInvoiceItems.size() > 0) { + CorporateInvoiceItems corporateInvoiceItems1 = corporateInvoiceItems.get(corporateInvoiceItems.size() - 1); + JSONObject obj = new JSONObject(); + obj.put("data", corporateInvoiceItems1); + log.info("corporateInvoiceItems1=>{}", obj.toJSONString()); + + corporateInvoiceItems1.setDeductionAmount(item.getTotal()); + corporateInvoiceItems1.setDeductionTaxRate(item.getTax_rate()); + corporateInvoiceItems1.setDeductionTax(item.getTax()); + // 添加差异计算20220620 + BigDecimal total = new BigDecimal(corporateInvoiceItems1.getTotal()); + BigDecimal deductionAmount = new BigDecimal(item.getTotal()); + corporateInvoiceItems1.setDifference(total.add(deductionAmount).toString()); + } else { + log.info("item.getTotal()====>{}", item.getTotal()); + JSONObject obj = new JSONObject(); + obj.put("data", item); + log.info("data=>{}", obj.toJSONString()); + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(invoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setDeductionAmount(item.getTotal()); + setDeductionTax(item.getTax()); + setDeductionTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(getOriginUnit()); + setOriginPrice(item.getPrice()); + }}); + } + } else { + log.info("item.getTotal()====>{}", item.getTotal()); + JSONObject obj = new JSONObject(); + obj.put("data", item); + log.info("data=>{}", obj.toJSONString()); + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(invoice.getId()); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + setTax(item.getTax()); + setTaxRate(item.getTax_rate()); + setSpecification(item.getSpecification()); + setOriginQuantity(getQuantity()); + setOriginUnit(item.getUnit()); + setOriginPrice(item.getPrice()); + setDifference(item.getTotal()); + }}); + } + } + } + String supplier = supplierMapper.selectSupplierCode(invoice.getSellerNo()); + if (StringUtil.isNotEmpty(supplier)) { + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + if (StringUtil.isNotBlank(corporateInvoiceItem.getOriginPrice()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginUnit()) && StringUtil.isNotBlank(corporateInvoiceItem.getOriginQuantity())) { + SupplierMaterialUom uom = supplierMaterialUomMapper.selectByItem(supplier, corporateInvoiceItem.getSpecification(), corporateInvoiceItem.getName(), corporateInvoiceItem.getOriginUnit()); + if (null != uom) { + corporateInvoiceItem.setUnit(uom.getVersUnit()); + corporateInvoiceItem.setQuantity(String.valueOf(Double.parseDouble(corporateInvoiceItem.getOriginQuantity()) * Double.parseDouble(uom.getVersNum()))); + BigDecimal price = new BigDecimal(corporateInvoiceItem.getPrice()).divide(new BigDecimal(uom.getVersNum()), 4, BigDecimal.ROUND_HALF_UP); + corporateInvoiceItem.setPrice(price.toString()); + } + } + } + } + invoice.setItems(corporateInvoiceItems); + if (details.getInvalid_mark() == null || details.getInvalid_mark().length() == 0) { + details.setInvalid_mark("0"); + } + if (details.getInvalid_mark() != null && !details.getInvalid_mark().equals("0")) { + //success = false; + invoice.setMessage("该发票已作废或撤消"); + invoice.setStatus(2); + invoice.setValidStatus((byte) 1); + return; + } + } + log.error("CorInvVerify else >> {}", verifyInvoice.getMessage()); + invoice.setMessage(invoice.getMessage() + ":" + verifyInvoice.getMessage()); + log.error("invoice message ==== >> {}", invoice.getMessage()); + } + } catch (Exception e) { + log.error("CorInvVerify >> {}", invoice.getNumber()); + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + invoice.setValidCount(invoice.getValidCount() + 1); + invoice.setValidDayCount(invoice.getValidDayCount() + 1); + } + } + + //获得发票类型 + public String getByType(String typeCode) { + switch (typeCode) { + case "10500": + return "出租车发票"; + case "10503": + return "火车票"; + case "10103": + return "增值税普通发票(卷票)"; + case "10100": + return "增值税专用发票"; + case "10101": + return "增值税普通发票"; + case "10102": + return "增值税电子普通发票"; + case "10104": + return "机动车销售统一发票"; + case "10105": + return "二手车销售统一发票"; + case "10505a": + return "船票"; + case "10200": + return "定额发票"; + case "10400": + return "机打发票"; + case "10401": + return "机打电票"; + case "10505": + return "客运汽车"; + case "10506": + return "航空运输电子客票行程单"; + case "10507": + return "过路费发票"; + case "10900": + return "可报销其他发票"; + case "10910": + return "医疗收据"; + case "20100": + return "国际小票"; + case "20105": + return "滴滴出行行程单"; + case "10902": + return "完税证明"; + case "10106": + return "增值税电子专用发票"; + case "10107": + return "增值税专用发票电子发票"; + case "10108": + return "增值税普通发票电子发票"; + default: + return "可报销其他发票"; + } + } + + + /** + * 得到invoiceLibrary的line数据 + * + * @param invoice + * @param details + */ + + /** + * 得到invoiceLibrary的line数据 全部 + * + * @param invoice + * @param details + */ + + public static void main(String asd[]) { + String json = "{\"data\":[{\"addressVal\":\"%7B%22data%22:%5B%7B%22supplierName%22:%22%E4%BC%8D%E5%B0%94%E7%89%B9%EF%BC%88%E4%B8%AD%E5%9B%BD%EF%BC%89%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22companyCode%22:%2204%22,%22unitPrice%22:220,%22orderNo%22:%22PO20250910000034%22,%22receivedNum%22:5,%22costCenter%22:%2201019083%22,%22companyName%22:%22%E4%B8%8A%E6%B5%B7%E5%8D%9A%E9%81%93%E7%94%B5%E5%AD%90%E5%95%86%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22goods%22:%22%E6%A3%98%E8%BD%AE%E6%89%B3%E6%89%8B%E7%BB%84%E5%A5%97-19%E4%BB%B6%E5%A5%97-2025%E9%99%AA%E8%B7%91%E5%91%A8%E9%99%90%E9%87%8F%E7%89%88%22,%22supplierCode%22:792190,%22itemNo%22:%220714%20202%205%22,%22receiveTime%22:%222025-09-11%2010:14:50%22,%22taxRate%22:%22CN_VAT_IN_13%22,%22uom%22:%22%E4%B8%AA%22,%22receiveNo%22:1917417,%22orgCode%22:%222036777%22,%22lineNum%22:1112008,%22currency%22:%22CNY%22%7D,%7B%22supplierName%22:%22%E4%BC%8D%E5%B0%94%E7%89%B9%EF%BC%88%E4%B8%AD%E5%9B%BD%EF%BC%89%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22companyCode%22:%2204%22,%22unitPrice%22:9.823009,%22orderNo%22:%22PO20250910000034%22,%22receivedNum%22:2,%22costCenter%22:%2201019083%22,%22companyName%22:%22%E4%B8%8A%E6%B5%B7%E5%8D%9A%E9%81%93%E7%94%B5%E5%AD%90%E5%95%86%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22goods%22:%22%E5%8D%81%E5%AD%97%E5%9C%86%E6%9D%86%E8%9E%BA%E4%B8%9D%E5%88%80-(S2)-PH1X100MM%22,%22supplierCode%22:792190,%22itemNo%22:%22WURTH0095%22,%22receiveTime%22:%222025-09-11%2010:14:50%22,%22taxRate%22:%22CN_VAT_IN_13%22,%22uom%22:%22%E4%B8%AA%22,%22receiveNo%22:1917427,%22orgCode%22:%222036777%22,%22lineNum%22:1112006,%22currency%22:%22CNY%22%7D,%7B%22supplierName%22:%22%E4%BC%8D%E5%B0%94%E7%89%B9%EF%BC%88%E4%B8%AD%E5%9B%BD%EF%BC%89%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22companyCode%22:%2204%22,%22unitPrice%22:17.584071,%22orderNo%22:%22PO20250910000034%22,%22receivedNum%22:28,%22costCenter%22:%2201019083%22,%22companyName%22:%22%E4%B8%8A%E6%B5%B7%E5%8D%9A%E9%81%93%E7%94%B5%E5%AD%90%E5%95%86%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22goods%22:%22%E5%B7%A5%E4%B8%9A%E9%9B%B6%E9%83%A8%E4%BB%B6%E6%B8%85%E6%B4%97%E5%89%82-%E5%8A%A0%E5%BC%BA%E5%9E%8B-600ml%22,%22supplierCode%22:792190,%22itemNo%22:%22WURTH0078%22,%22receiveTime%22:%222025-09-11%2010:14:50%22,%22taxRate%22:%22CN_VAT_IN_13%22,%22uom%22:%22%E4%B8%AA%22,%22receiveNo%22:1917421,%22orgCode%22:%222036777%22,%22lineNum%22:1112004,%22currency%22:%22CNY%22%7D,%7B%22supplierName%22:%22%E4%BC%8D%E5%B0%94%E7%89%B9%EF%BC%88%E4%B8%AD%E5%9B%BD%EF%BC%89%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22companyCode%22:%2204%22,%22unitPrice%22:24.699115,%22orderNo%22:%22PO20250910000034%22,%22receivedNum%22:2,%22costCenter%22:%2201019083%22,%22companyName%22:%22%E4%B8%8A%E6%B5%B7%E5%8D%9A%E9%81%93%E7%94%B5%E5%AD%90%E5%95%86%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22goods%22:%22%E5%A4%9A%E5%8A%9F%E8%83%BD%E9%99%A4%E9%94%88%E6%B6%A6%E6%BB%91%E5%96%B7%E5%89%82-ULTRA%202040-500ml%22,%22supplierCode%22:792190,%22itemNo%22:%22WURTH0079%22,%22receiveTime%22:%222025-09-11%2010:14:50%22,%22taxRate%22:%22CN_VAT_IN_13%22,%22uom%22:%22%E4%B8%AA%22,%22receiveNo%22:1917425,%22orgCode%22:%222036777%22,%22lineNum%22:1112005,%22currency%22:%22CNY%22%7D%5D%7D\"}]}"; + JSONObject obj = JSONObject.parseObject(json); + log.info(obj.toJSONString()); + } + + public RuiZhenOCREntity ofdCompress(String ofdPath, String imgPath) { + try { + OFDConverter.toImageJpeg(ofdPath, imgPath, 12); + String base64 = Base64Util.fileToBase64(ofdPath); + RuiZhenOCREntity results = billsCropPdf(base64); + return results; + } catch (Exception e) { + log.error(e.getMessage()); + } + return null; + } + } diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/SmarttaxService.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/SmarttaxService.java new file mode 100644 index 0000000..0fb781e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/SmarttaxService.java @@ -0,0 +1,516 @@ +package com.cmsen.ticket.infrastructure.ocr2; + +import cn.hutool.core.thread.ThreadUtil; +import cn.hutool.core.util.IdUtil; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.ClientHttpResponse; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StorageCache; +import com.cmsen.ticket.application.util.CacheKey; +import com.cmsen.ticket.bestsign.util.InterfaceUtil; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.infrastructure.config.RestTemplateConfig; +import com.cmsen.ticket.infrastructure.ocr2.client.OcrSmarttaxClient; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCRVerifyEntity; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenVerifyForm; +import lombok.extern.log4j.Log4j2; +import net.smarttax.sim.entity.resp.InvoiceCheckDetail; +import net.smarttax.sim.entity.resp.InvoiceCheckResp; +import org.springframework.http.*; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.*; + +/** + * @author OWTS + */ +@Log4j2 +@Component +public class SmarttaxService { + + @Resource + private OcrSmarttaxClient ocrSmarttaxClient; + @Resource + private SysConfigMapper sysConfigMapper; + @Resource + private InterfaceUtil interfaceUtil; + @Resource + private RestTemplateConfig restTemplateConfig; + + public RuiZhenOCRVerifyEntity verifyInvoice(RuiZhenVerifyForm form) { + String checkStr = ocrSmarttaxClient.invoiceCheck(form); + log.info("verifyInvoice==checkStr=={}", checkStr); + ThreadUtil.sleep(2000); + int count = 0; + int MAX_COUNT = 80; + String key = CacheKey.INVOICE_VERIFY_KEY + form.getNumber(); + String failKey = CacheKey.INVOICE_VERIFY_KEY + checkStr; + RuiZhenOCRVerifyEntity result = new RuiZhenOCRVerifyEntity(); + try { + while (count < MAX_COUNT) { + log.info("verifyInvoice===={}", count); + //判断包含Success的缓存 + if (StorageCache.containsKey(key)) { + Object read = StorageCache.read(key); + InvoiceCheckResp data = (InvoiceCheckResp) read; + log.info("verifyInvoice====data{}", data); + //判断发票状态 2023/1/29 + if (data.getInvoiceStatus() != null) { + log.info("invoiceState--{}", data.getInvoiceStatus().getName()); + if (data.getInvoiceStatus().getName().equals("0")) { + replaceBean(data, result, form); + } else if (data.getInvoiceStatus().getName().equals("1")) { + result.setResult(0); + result.setMessage("红冲"); + result.setError(20000); + } else { + result.setResult(0); + result.setMessage("作废"); + result.setError(20000); + } + } else { + result.setResult(0); + result.setMessage("作废"); + result.setError(20000); + } + StorageCache.remove(key); + return result; + } + //判断包含Fail的缓存 + if (StorageCache.containsKey(failKey)) { + Object read = StorageCache.read(failKey); + String message = read.toString(); + + result.setResult(0); + result.setMessage(message); + result.setError(20000); + StorageCache.remove(failKey); + return result; + } + count++; + ThreadUtil.sleep(200); + } + result.setMessage("timeout"); + } catch (Exception e) { + log.error("", e); + result.setMessage(e.getMessage()); + } + result.setResult(0); + result.setError(10000); + return result; + } + + /** + * 调用CDK验真接口 + * + * @param form + * @return + */ + public RuiZhenOCRVerifyEntity verifyInvoiceCdk(RuiZhenVerifyForm form) { + RuiZhenOCRVerifyEntity result = new RuiZhenOCRVerifyEntity(); + try { + // 获取token + SysConfig tokenUrl = sysConfigMapper.selectByCode("HS_CDK_TOKEN_URL"); + SysConfig checkUrl = sysConfigMapper.selectByCode("HS_CDK_CHECK_URL"); + SysConfig taxToken = sysConfigMapper.selectByCode("HS_CDK_TAX_TOKEN"); + SysConfig appKey = sysConfigMapper.selectByCode("HS_CDK_APP_KEY"); + SysConfig appSecret = sysConfigMapper.selectByCode("HS_CDK_APP_SECRET"); + SysConfig cdkType = sysConfigMapper.selectByCode("HS_CDK_TYPE"); + SysConfig downloadXml = sysConfigMapper.selectByCode("download_XML"); + if (tokenUrl == null || checkUrl == null || taxToken == null || appKey == null || appSecret == null) { + log.error("CDK验真参数不全,请检查"); + return null; + } + String cdkTypeVal = "1"; + if (cdkType != null) { + cdkTypeVal = cdkType.getValue(); + } + String token = interfaceUtil.getCDKToken(tokenUrl.getValue(), appKey.getValue(), appSecret.getValue(), cdkTypeVal); + // 验真请求 + // 设置请求参数 + Map body = new HashMap(); + Map invoiceParam = new HashMap(); + List lsMap = new ArrayList<>(); + invoiceParam.put("invoiceNo", form.getNumber().trim()); + invoiceParam.put("drewDate", form.getDate().replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "").trim()); + invoiceParam.put("amount", form.getPretax_amount().trim()); + // 被改10102更新到10107 + if (form.getNumber().length() > 15 && form.getType().equals("10102")) { + form.setType("10107"); + } + String invoiceType = getByCDKType(form.getType()); + if (!invoiceType.equals("09") && !invoiceType.equals("90")) { + invoiceParam.put("checkCode", form.getCheck_code() == null ? "" : form.getCheck_code().trim()); + invoiceParam.put("invoiceCode", form.getCode() == null ? "" : form.getCode().trim()); + invoiceParam.put("invoiceType", invoiceType.trim()); + } else { + invoiceParam.put("invoiceType", invoiceType.trim()); + } + int orginFileFlag = 0; + if (downloadXml != null && (downloadXml.getValue().equals("1") || downloadXml.getValue().equals("2"))) { + orginFileFlag = 1; + } else { + if (form.getOrginFileFlag() != null && form.getOrginFileFlag().equals("1")) { + orginFileFlag = 1; + } + } + invoiceParam.put("originFileFlag", orginFileFlag); + lsMap.add(invoiceParam); + body.put("storeFlag", 0); + body.put("invoiceList", lsMap); + + log.info("CDK-验真请求Body{}", JsonUtil.toString(body)); + String uuid = UUID.randomUUID().toString(); + log.info("X-Serial-Token 慧税检查报文参数 ===>{}", uuid); +// ClientHttpResponse response = ClientHttps.post( +// new ClientHttpRequest() +// .setUrl(checkUrl.getValue()) +// .setHeaders("Content-Type", ContentEnctype.JSON) +// .setHeaders("X-Access-Token", token) +// .setHeaders("X-Tax-Token", taxToken.getValue()) +// .setHeaders("X-Serial-Token",uuid) +// .setTimeOut(60000) +// .setParams(JsonUtil.toString(body)) +// ); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Content-Type", ContentEnctype.JSON); + headers.set("X-Access-Token", token); + headers.set("X-Tax-Token", taxToken.getValue()); + headers.set("X-Serial-Token", uuid); + HttpEntity entity = new HttpEntity<>(JsonUtil.toString(body), headers); + RestTemplate client = restTemplateConfig.restTemplate(); + ResponseEntity responseEntity = null; + try { + responseEntity = client.exchange( + checkUrl.getValue(), + HttpMethod.POST, + entity, + String.class + ); + } catch (Exception e) { + e.printStackTrace(); + result.setResult(0); + result.setMessage("验真接口调用异常"); + result.setError(10000); + return result; + } + + + // 封装返回对象 + ClientHttpResponse response = new ClientHttpResponse(); + response.setStatus(responseEntity.getStatusCodeValue()); + if (null != responseEntity.getBody()) { + response.setBody(new StringBuilder(responseEntity.getBody())); + } + + + log.info("CDK-验真请求返回{}", response); + JSONObject forObject = JSONObject.parseObject(response.toString()); + //判断发票状态 2023/1/29 + if (forObject.get("code") != null && forObject.get("code").toString().equals("200")) { + if (forObject.getJSONArray("data") != null && forObject.getJSONArray("data").size() > 0) { + JSONObject obj = forObject.getJSONArray("data").getJSONObject(0); + if (obj.get("checkFlag") != null && obj.get("checkFlag").toString().equals("true")) { + // 发票数据 + JSONObject invoiceData = obj.getJSONObject("invoiceVO"); + String invoiceStatus = invoiceData.get("invoiceStatus") == null ? "" : invoiceData.get("invoiceStatus").toString(); + replaceBeanCdk(invoiceData, result, form); + if (invoiceStatus.equals("0")) { + + } else if (invoiceStatus.equals("1")) { + result.setResult(0); + result.setMessage("作废"); + result.setError(20000); + } else if (invoiceStatus.equals("2")) { + result.setResult(0); + result.setMessage("红冲"); + result.setError(20000); + } else if (invoiceStatus.equals("7")) { + result.setResult(0); + result.setMessage("部分红冲"); + result.setError(20000); + } else if (invoiceStatus.equals("8")) { + result.setResult(0); + result.setMessage("全额红冲"); + result.setError(20000); + } + } else { + String info = obj.get("exceptionInfo").toString(); + result.setResult(0); + result.setMessage(info.equals("null") ? "验真失败" : info); + result.setError(20000); + } + } + } else { + log.info("CDK-验真请求参数{}", JsonUtil.toString(body)); + result.setResult(0); + result.setMessage(forObject.get("message").toString()); + result.setError(20000); + } + return result; + } catch (Exception e) { + log.error("", e); + result.setMessage(e.getMessage()); + } + result.setResult(0); + result.setError(10000); + return result; + } + + /** + * 慧穗数据转换成睿真 + * + * @param data + * @param result + * @param form + */ + private void replaceBean(InvoiceCheckResp data, RuiZhenOCRVerifyEntity result, RuiZhenVerifyForm form) { + result.setResult(1); + result.setMessage("success"); + RuiZhenOCRVerifyEntity.Response response = new RuiZhenOCRVerifyEntity.Response(); + result.setResponse(response); + RuiZhenOCRVerifyEntity.Data responseData = new RuiZhenOCRVerifyEntity.Data(); + response.setData(responseData); + responseData.setVersion("huisui.v1.0"); + responseData.setResult(1); + responseData.setTimestamp(System.currentTimeMillis()); + responseData.setMessage("success"); + responseData.setId(IdUtil.fastUUID()); + responseData.setTime_cost("1000"); + ArrayList identify_results = new ArrayList<>(); + responseData.setIdentify_results(identify_results); + + RuiZhenOCRVerifyEntity.IdentifyResults identifyResults = new RuiZhenOCRVerifyEntity.IdentifyResults(); + identify_results.add(identifyResults); + + identifyResults.setValidation(new RuiZhenOCRVerifyEntity.Validation() {{ + setCode(1000); + setMessage("success"); + }}); + + Details details = new Details(); + identifyResults.setDetails(details); + + details.setCode(data.getInvoiceCode()); + details.setNumber(data.getInvoiceNum()); + details.setDate(DateFormat.format(DateFormat.parse(data.getCreateDate()), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + details.setPretax_amount(data.getTaxFreeAmount().toString()); + details.setTax(data.getTaxAmount().toString()); + details.setTotal(data.getTotalAmount().toString()); + details.setCheck_code(form.getCheck_code_all()); + details.setSeller(data.getSellerName()); + details.setSeller_tax_id(data.getSellerTaxCode()); + details.setSeller_addr_tel(data.getSellerAddress()); + details.setBuyer(data.getBuyerName()); + details.setBuyer_tax_id(data.getBuyerTaxCode()); + details.setRemark(data.getRemark()); + // 发票状态获取 + details.setInvalid_mark(data.getInvoiceStatus().getName()); + // 2023-05-25 设置 + details.setSeller_addr_tel(data.getSellerAddress()); + details.setSeller_bank_account(data.getSellerBankName()); + details.setBuyer_addr_tel(data.getBuyerAddress()); + details.setBuyer_bank_account(data.getBuyerBankName()); + + List items = new ArrayList<>(); + details.setItems(items); + + for (InvoiceCheckDetail item : data.getDetails()) { + items.add(new Item() {{ + setName(item.getCmdtyName()); + setSpecification(item.getTaxSpecification()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity() == null ? "0" : String.valueOf(item.getQuantity())); + setPrice(item.getUnitPrice() == null ? "0" : item.getUnitPrice().toString()); + setTotal(item.getTaxFreeAmount() == null ? "0" : item.getTaxFreeAmount().toString()); + setTax_rate(item.getTaxRate() == null ? "" : item.getTaxRate().compareTo(new BigDecimal(1)) > 0 ? String.valueOf(item.getTaxRate()) : String.valueOf(item.getTaxRate().multiply(new BigDecimal(100)))); + setTax(item.getTaxAmount() == null ? "0" : item.getTaxAmount().toString()); + }}); + } + } + + /** + * cdk数据转换成睿真 + * + * @param data + * @param result + * @param form + */ + private void replaceBeanCdk(JSONObject data, RuiZhenOCRVerifyEntity result, RuiZhenVerifyForm form) { + result.setResult(1); + result.setMessage("success"); + RuiZhenOCRVerifyEntity.Response response = new RuiZhenOCRVerifyEntity.Response(); + result.setResponse(response); + RuiZhenOCRVerifyEntity.Data responseData = new RuiZhenOCRVerifyEntity.Data(); + response.setData(responseData); + responseData.setVersion("huisui.v1.0"); + responseData.setResult(1); + responseData.setTimestamp(System.currentTimeMillis()); + responseData.setMessage("success"); + //responseData.setId(IdUtil.fastUUID()); + responseData.setId(JsonUtil.toString(data)); + responseData.setTime_cost("1000"); + ArrayList identify_results = new ArrayList<>(); + responseData.setIdentify_results(identify_results); + + RuiZhenOCRVerifyEntity.IdentifyResults identifyResults = new RuiZhenOCRVerifyEntity.IdentifyResults(); + identify_results.add(identifyResults); + + identifyResults.setValidation(new RuiZhenOCRVerifyEntity.Validation() {{ + setCode(1000); + setMessage("success"); + }}); + + Details details = new Details(); + identifyResults.setDetails(details); + + details.setCode(getObjString(data.get("invoiceCode"))); + details.setNumber(getObjString(data.get("invoiceNo"))); + details.setDate(DateFormat.format(DateFormat.parse(getObjString(data.get("drewDate"))), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日)); + details.setPretax_amount(getObjString(data.get("amount"))); + details.setTax(getObjString(data.get("taxAmount"))); + details.setTotal(getObjString(data.get("amountWithTax"))); + details.setCheck_code(form.getCheck_code_all()); + details.setSeller(getObjString(data.get("sellerName"))); + details.setSeller_tax_id(getObjString(data.get("sellerTaxNo"))); + details.setSeller_addr_tel(getObjString(data.get("sellerAddressTel"))); + details.setBuyer(getObjString(data.get("purchaserName"))); + details.setBuyer_tax_id(getObjString(data.get("purchaserTaxNo"))); + details.setRemark(getObjString(data.get("remark"))); + // 发票状态获取 + details.setInvalid_mark(getObjString(data.get("invoiceStatus"))); + // 2023-05-25 设置 + details.setSeller_bank_account(getObjString(data.get("sellerBank"))); + details.setBuyer_addr_tel(getObjString(data.get("purchaserAddressTel"))); + details.setBuyer_bank_account(getObjString(data.get("purchaserBank"))); + + //2024-12-10 + if (data.getJSONArray("specificElements") != null) { + int elementsSize = data.getJSONArray("specificElements").size(); + if (elementsSize > 0) { + JSONObject elementObj = data.getJSONArray("specificElements").getJSONObject(0); + details.setName(getObjString(elementObj.get("element16"))); + details.setSeat(getObjString(elementObj.get("element20"))); + } + } + + List items = new ArrayList<>(); + details.setItems(items); + + for (int i = 0; i < data.getJSONArray("detailList").size(); i++) { + JSONObject itemObj = data.getJSONArray("detailList").getJSONObject(i); + items.add(new Item() {{ + setName(getObjString(itemObj.get("goodsName"))); + setSpecification(getObjString(itemObj.get("specification"))); + setUnit(getObjString(itemObj.get("unit"))); + setQuantity(getObjString(itemObj.get("quantity"), "0")); + setPrice(getObjString(itemObj.get("unitPrice"), "0")); + setTotal(getObjString(itemObj.get("amount"), "0")); + setTax_rate(getTaxRate(itemObj.get("taxRate"), "0")); + setTax(getObjString(itemObj.get("taxAmount"), "0")); + }}); + } + } + + //获得CDK发票类型 + public String getByCDKType(String typeCode) { + switch (typeCode) { + case "10500": + return "出租车发票"; + case "10503"://火车票 + return "51"; + case "10533"://电子火车票 + return "51"; + case "10573"://铁路服务费 + return "51"; + case "10103"://增值税普通发票(卷票) + return "11"; + case "10100"://增值税专用发票 + return "01"; + case "10101"://增值税普通发票 + return "04"; + case "10102"://增值税电子普通发票 + return "10"; + case "10102a"://道路通行费电子普通发票 + return "14"; + case "10104": + return "83"; + case "10105": + return "84"; + case "10106"://增值税电子专用发票 + return "08"; + case "10107"://全电发票(增值税专用发票) + return "09"; + case "10108"://全电发票(普通发票) + return "90"; + case "10505a": + return "船票"; + case "10200": + return "定额发票"; + case "10400": + return "机打发票"; + case "10505": + return "客运汽车"; + case "10506"://航空运输电子客票行程单 + return "61"; + case "10536"://航空运输电子客票行程单 + return "61"; + case "10507": + return "过路费发票"; + case "10900": + return "可报销其他发票"; + case "20100": + return "国际小票"; + case "20105": + return "滴滴出行行程单"; + case "10902": + return "完税证明"; + default://可报销其他发票 + return ""; + } + } + + /** + * null值处理 + * + * @param obj + * @return + */ + public String getObjString(Object obj, String... defStr) { + if (obj == null) { + if (defStr.length > 0) { + return defStr[0]; + } + return ""; + } + return obj.toString(); + } + + /** + * 判断税率问题 + * + * @param obj + * @return + */ + public String getTaxRate(Object obj, String... defStr) { + if (obj == null) { + if (defStr.length > 0) { + return defStr[0]; + } + return ""; + } + String item = obj.toString(); + BigDecimal rate = new BigDecimal(item); + return rate.compareTo(new BigDecimal(1)) > 0 ? item : String.valueOf(rate.multiply(new BigDecimal(100))); + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/client/OcrSmarttaxClient.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/client/OcrSmarttaxClient.java new file mode 100644 index 0000000..532485f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/client/OcrSmarttaxClient.java @@ -0,0 +1,43 @@ +package com.cmsen.ticket.infrastructure.ocr2.client; + +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenVerifyForm; +import lombok.extern.log4j.Log4j2; +import net.smarttax.sim.entity.dto.ReqDTO; +import net.smarttax.sim.entity.req.InvoiceCheckRequest; +import net.smarttax.sim.facade.SmarttaxClient; +import net.smarttax.sim.util.CommonUtils; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; + +/** + * @author OWTS + */ +@Log4j2 +@Component +public class OcrSmarttaxClient { + private final SmarttaxClient smarttaxClient; + + public OcrSmarttaxClient(SmarttaxClient smarttaxClient) { + this.smarttaxClient = smarttaxClient; + } + + public String invoiceCheck(RuiZhenVerifyForm verifyForm) { + log.info("verifyForm ======== {}",verifyForm); + InvoiceCheckRequest data = new InvoiceCheckRequest() {{ + setInvoiceCode(verifyForm.getCode().trim()); + setInvoiceNum(verifyForm.getNumber().trim()); + setCreateDate(DateFormat.format(DateFormat.parse(verifyForm.getDate()), DateFormat.DatePatternType.FORMAT_yyyyMMdd).trim()); + if (StringUtil.isNotEmpty(verifyForm.getPretax_amount().trim())) { + setAmount(new BigDecimal(verifyForm.getPretax_amount().trim())); + } + setCheckCode(verifyForm.getCheck_code_all().trim()); + }}; + log.info("invoiceCheck Data >>{}>> {}", verifyForm.getNumber(),data); + String returnStr = smarttaxClient.invoiceCheck(ReqDTO.build(CommonUtils.buildUUID16(), "91310114332803213Y", "", data)); + log.info("invoiceCheck returnStr >>{}>> {}", returnStr,CommonUtils.buildUUID16()); + return returnStr; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AbroadEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AbroadEntity.java new file mode 100644 index 0000000..254757a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AbroadEntity.java @@ -0,0 +1,14 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +@Data +public class AbroadEntity { + + private String ticket_type; + private String number; + private String date; + private String amount; + private String currentcy; + private String city; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentEntity.java new file mode 100644 index 0000000..24419a5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentEntity.java @@ -0,0 +1,211 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/8/3 15:13 + **/ +@Data +public class AttachmentEntity { + + private List data; + + private String result; + + private boolean success; + + @Data + public static class DataDTO { + private String classcode; + private List results; + @JsonProperty("results_error") + private List resultsError; + @JsonProperty("note_infos") + private String noteInfos; + + @Data + public static class ResultsDTO { + @JsonProperty("hotel_sheet") + //1001 住宿水单 + private HotelSheetDTO hotelSheet; + //1003 餐厅水单 + @JsonProperty("restaurant_bill") + private RestaurantBillDTO restaurantBill; + + //9001 menarini签到表 + @JsonProperty("医院医生") + private AttendanceSheet attendanceSheet; + + //1002 付款单 + @JsonProperty("screenshot") + private ScreenShot screenShot; + + //1002 付款单 + @JsonProperty("POS_sheet") + private POSSheet posSheet; + + //1004 滴滴行程单 + @JsonProperty("didi") + private Didi didi; + + //2001 + @JsonProperty("私车公用") + private PrivateCar privateCar; + + public PaidData getPaidData() { + return screenShot == null ? posSheet : screenShot; + } + + @Data + public static class PrivateCar { + private List detail; + + @Data + public static class PrivateCarItem { + @JsonProperty("日期") + private String date; + @JsonProperty("Time时间") + private String time; + @JsonProperty("目的") + private String target; + @JsonProperty("出发地") + private String from; + @JsonProperty("到达地") + private String to; + @JsonProperty("里程数") + private String mileage; + @JsonProperty("里程报销金额") + private String money; + } + } + + + @Data + public static class PaidData { + private String total; + } + + @EqualsAndHashCode(callSuper = true) + @Data + public static class POSSheet extends PaidData { + @JsonProperty("seller_name") + private String seller_name; + @JsonProperty("seller_number") + private String seller_number; + @JsonProperty("card_id") + private String card_id; + @JsonProperty("consume_time") + private String consume_time; + private String money; + + @Override + public String getTotal() { + return this.money; + } + } + + + @Data + public static class Didi { + private String date; + @JsonProperty("date_start") + private String date_start; + @JsonProperty("date_end") + private String date_end; + private String phone; + private String total; + private List items; + + @Data + public static class DidiItem { + @JsonProperty("car_type") + private String car_type; + @JsonProperty("time_geton") + private String time_geton; + private String city; + @JsonProperty("station_geton") + private String station_geton; + @JsonProperty("station_getoff") + private String station_getoff; + private String mileage; + private String total; + } + } + + + @EqualsAndHashCode(callSuper = true) + @Data + public static class ScreenShot extends PaidData { + private String name; + // private String total; + private String time; + } + + @Data + public static class AttendanceSheet { + private List detail; + + @Data + public static class AttendeeDetails { + @JsonProperty("医院代码") + private String hospitalCode; + @JsonProperty("医生代码") + private String doctorCode; + @JsonProperty("医院-医生代码") + private String hdCode; + @JsonProperty("姓名") + private String name; + @JsonProperty("是否参会") + private String isAttended; + @JsonProperty("签名") + private String assigned; + } + } + + @Data + public static class RestaurantBillDTO { + @JsonProperty("餐厅名字") + private String name; + @JsonProperty("单号") + private String no; + @JsonProperty("人数") + private String personCount; + @JsonProperty("时间") + private String time; + @JsonProperty("品名") + private List prods; + @JsonProperty("合计") + private String total; + } + + @Data + public static class HotelSheetDTO { + @JsonProperty("hotel_name") + private String hotelName; + @JsonProperty("guest_name") + private String guestName; + @JsonProperty("check_in_time") + private String checkInTime; + @JsonProperty("check_out_time") + private String checkOutTime; + private String total; + private List detail; + + @Data + public static class DetailDTO { + private String date; + private String description; + private String debits; + private String credits; + private String detail; + } + } + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqBody.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqBody.java new file mode 100644 index 0000000..7b297af --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqBody.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/19 11:31 + */ +@Data +public class AttachmentMqBody { + private String url; + @JsonProperty("response_url") + private String responseUrl; + private JsonBody json; + private Headers headers; + private Integer priority = 6; + + @AllArgsConstructor + @Data + public static class JsonBody { + private String file; + private String code; + } + + @AllArgsConstructor + @Data + public static class Headers { + @JsonProperty("Content-Type") + private String contentType = "application/json"; + @JsonProperty("Authorization") + private String authorization; + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqRes.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqRes.java new file mode 100644 index 0000000..a5bb9f7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/AttachmentMqRes.java @@ -0,0 +1,16 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/11/19 13:10 + */ +@Data +public class AttachmentMqRes { + @JsonProperty("MQ_id") + private String mqId; + private Object content; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Details.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Details.java new file mode 100644 index 0000000..d3cf610 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Details.java @@ -0,0 +1,153 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +//@Accessors(chain = true) +@Data +public class Details { + private String code; + private String number; + private String numberBackup; + private String date; + private String pretax_amount; + private String total; + private String tax; + private String check_code; + private String seller; + private String seller_tax_id; + private String buyer; + private String buyer_tax_id; + private String company_seal; + private String form_type; + private String form_name; + private String kind; + // private String ciphertext; + private Float transit_mark; + private String oil_mark; + private String machine_code; + private String travel_tax; + private String receiptor; + private String reviewer; + private String issuer; + private String province; + private String city; + private String service_name; + private String remark; + private String item_names; + private String agent_mark; + private String acquisition_mark; + private String block_chain; + private String code_confirm; + private String number_confirm; + private String time_geton; + private String time_getoff; + private String mileage; + private String place; + private String license_plate; + private String time; + private String name; + private String station_geton; + private String station_getoff; + private String train_number; + private String seat; + private String serial_number; + private String user_id; + + private String category; + + private String entrance; + + private String exit; + + private String highway_flag; + + private String user_name; + + private String agentcode; + + private String issue_by; + + private String fare; + + private String fuel_surcharge; + + private String caac_development_fund; + + private String insurance; + + private List flights = new ArrayList<>(); + + private String international_flag; + + private String print_number; + + private String seller_id; + private String buyer_id; + + private String company_name; + private String company_tax_id; + private String registration_number; + + private String car_code; + private String car_model; + + private String tax_authorities; + private String machine_number; + private String tax_authorities_code; + private String car_engine_code; + private String certificate_number; + private String tax_rate; + private String store_name; + private String subtotal; + private String discount; + private String tips; + private String currency_code; + private String date_start; + private String date_end; + private String phone; + private String title; + + private String electronic_mark; + + private String seller_addr_tel; + + private String invalid_mark; + + private String stamp_info; + + private String buyer_bank_account; + + private String seller_bank_account; + + private String buyer_addr_tel; + + private String electronic_number; + + private List items = new ArrayList<>(); + private List transports = new ArrayList<>(); + + private String date_of_issue; + private String type_of_voucher; + private String service_type; + private String ticket_content; + private String type_of_business; + private String receipt_number; + + // 通行费标记 + private String vehicle_mark; + private String po; + + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + private String ext06; + private String ext07; + private String ext08; + private String ext09; + private String ext10; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Extra.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Extra.java new file mode 100644 index 0000000..a8a18c6 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Extra.java @@ -0,0 +1,16 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +@Data +public class Extra { + @JsonProperty("check_code_candidates") + private List checkCodeCandidates;//增值税 + @JsonProperty("check_code_last_six") + private List checkCodeLastSix;//增值税 + @JsonProperty("number_order_error") + private List numberOrderError;//增值税 +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Flight.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Flight.java new file mode 100644 index 0000000..b319af3 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Flight.java @@ -0,0 +1,14 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +@Data +public class Flight { + private String from; + private String to; + private String flight_number; + private String date; + private String time; + private String seat; + private String carrier; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiCode.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiCode.java new file mode 100644 index 0000000..0805830 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiCode.java @@ -0,0 +1,18 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +public class GatewayApiCode implements Serializable +{ + //code + private String code; +} + + + + diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiToken.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiToken.java new file mode 100644 index 0000000..119d538 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayApiToken.java @@ -0,0 +1,11 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class GatewayApiToken { + //token参数 + private String token; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayCodeGen.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayCodeGen.java new file mode 100644 index 0000000..d6cbccc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/GatewayCodeGen.java @@ -0,0 +1,19 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@Data +@NoArgsConstructor +public class GatewayCodeGen { + //服务名称 + private String serviceName; + //appKey + private String appKey; + //解密后验证码 + private String validCode; + //解密前的code值 + private String code; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyFileEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyFileEntity.java new file mode 100644 index 0000000..d8855ed --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyFileEntity.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class IdentifyFileEntity { + + private String jsonrpc; + @JsonProperty("result") + private Result result; + private String id; + private String ctx; + private String timestampin; + private String timestampout; + private Route route; + private Error error; + + @Data + public static class Result{ + @JsonProperty("json_data") + private JsonData json_data; + } + + @Data + public static class Route{ + @JsonProperty("TTL") + private int TTL; + @JsonProperty("DestAddr") + private String DestAddr; + @JsonProperty("SourceAddr") + private String SourceAddr; + } + + @Data + public static class Error{ + private String message; + private int code; + private String data; + } + + @Data + public static class JsonData{ + @JsonProperty("choice") + private String choice; + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyOcrEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyOcrEntity.java new file mode 100644 index 0000000..f23faf5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/IdentifyOcrEntity.java @@ -0,0 +1,67 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class IdentifyOcrEntity { + + private String jsonrpc; + @JsonProperty("result") + private Result result; + private String id; + private String ctx; + private String timestampin; + private String timestampout; + private Route route; + private Error error; + + @Data + public static class Result{ + @JsonProperty("json_data") + private JsonData json_data; + } + + @Data + public static class Route{ + @JsonProperty("TTL") + private int TTL; + @JsonProperty("DestAddr") + private String DestAddr; + @JsonProperty("SourceAddr") + private String SourceAddr; + } + + @Data + public static class Error{ + private String message; + private int code; + private String data; + } + + @Data + public static class JsonData{ + @JsonProperty("票据类型") + private String 票据类型; + @JsonProperty("发票代码") + private String 发票代码; + @JsonProperty("发票号码") + private String 发票号码; + @JsonProperty("发票日期") + private String 发票日期; + @JsonProperty("币种") + private String 币种; + @JsonProperty("发票金额") + private String 发票金额; + @JsonProperty("城市") + private String 城市; + @JsonProperty("开票方") + private String 开票方; + @JsonProperty("语言") + private String 语言; + @JsonProperty("地点") + private String 地点; + + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Item.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Item.java new file mode 100644 index 0000000..5a1a12a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Item.java @@ -0,0 +1,29 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +@Data +public class Item { + private String car_type; + private String time_geton; + private String city; + private String station_geton; + private String station_getoff; + private String mileage; + private String total; + private String name; + private String specification; + private String unit; + private String quantity; + private String price; + private String tax_rate; + private String tax; + private String itemNo; + private String ext01; + private String ext02; + private String ext03; + private String ext04; + private String ext05; + + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/QrOcrEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/QrOcrEntity.java new file mode 100644 index 0000000..28734c4 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/QrOcrEntity.java @@ -0,0 +1,25 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +/* + * @author OWTS + * @date 2021/4/19 + * @desc + */ +@Data +public class QrOcrEntity { + private Integer status; + private String message; + private Result result; + + @Data + public static class Result { + private String type; + private String code; + private String no; + private String amount; + private String date; + private String checkCode; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/R.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/R.java new file mode 100644 index 0000000..6a7fd03 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/R.java @@ -0,0 +1,23 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +//返回值对象 +@AllArgsConstructor +@Data +@NoArgsConstructor +public class R implements Serializable { + private static final long serialVersionUID = 1L; + //状态码 + private int code; + //是否成功 + private boolean success; + //相应结果 + private T data; + //错误信息 + private String msg; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCREntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCREntity.java new file mode 100644 index 0000000..66492fd --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCREntity.java @@ -0,0 +1,135 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ReflectionUtils; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Data +public class RuiZhenOCREntity { + + private Integer result; + + private Response response; + + @JsonProperty("result_PO") + private ResultPO resultPO; + + @Data + public static class ResultPO{ + @JsonProperty("PO_code") + private POCode PO_code; + } + + @Data + public static class POCode{ + @JsonProperty("result") + private String result; + } + + @JsonProperty("result_fld") + private ResultFld resultFld; + + @Data + public static class ResultFld { + @JsonProperty("stampcolor") + private Stampcolor stampcolor; + + @JsonProperty("numberlabel") + private NumberLabel numberLabel; + + } + + @Data + public static class NumberLabel{ + private String number; + private NumberLabelData data; + } + + @Data + public static class NumberLabelData{ + private String version; + private Long timestamp; + private String timeCost; + } + + + + @Data + public static class Stampcolor{ + @JsonProperty("StampRed") + private boolean stampRed; + + private OCRData data; + } + + @Data + public static class StampData{ + private String version; + private Long timestamp; + private String time_cost; + + @JsonProperty("resList") + private List resList; + + } + + @Data + public static class StampBox { + private List StampBox; + private Boolean StampRed; + private String RedRatio; + } + + + @Data + public static class Response { + @JsonProperty("data") + private OCRData data; + } + + @Data + public static class OCRData { + private String version; + private Integer result; + private Long timestamp; + private String message; + private String id; + private String sha1; + @JsonProperty("time_cost") + private String time_cost; + @JsonProperty("identify_results") + private List identify_results; + private Extra extra; + } + + @Data + public static class IdentifyResults { + private String type; + private Integer orientation; + private List region; + @JsonProperty("details") + private Details details; + private Extra extra; + + private String image;//图片的64位 + + public String getValueByKey(String key) { + + return String.valueOf(parseObj2Map(this.details).get(key)); + } + + public Map parseObj2Map(Object args) { + return Arrays.stream(BeanUtils.getPropertyDescriptors(args.getClass())) + .filter(pd -> !"class".equals(pd.getName())) + .collect(HashMap::new, + (map, pd) -> map.put(pd.getName(), ReflectionUtils.invokeMethod(pd.getReadMethod(), args)), + HashMap::putAll); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCRVerifyEntity.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCRVerifyEntity.java new file mode 100644 index 0000000..6569e8b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenOCRVerifyEntity.java @@ -0,0 +1,76 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +import java.util.List; + +/** + * @Author OWTS > + * @Date 2020/11/27 + * @Description + */ +@Data +public class RuiZhenOCRVerifyEntity { + private Integer result; + private Response response; + private String message; + private Integer error; + + public CheckResult checkSuccess() { + CheckResult checkResult = new CheckResult(); + if (this.result.equals(0)) { + checkResult.setSuccess(false); + checkResult.setMessage(this.message); + } else { + String message = this.response.data.identify_results.get(0).getValidation().message; + if (message.equals("success")) { + checkResult.setSuccess(true); + checkResult.setMessage(message); + } else { + checkResult.setSuccess(false); + checkResult.setMessage(message); + } + checkResult.setCode(this.response.data.identify_results.get(0).getValidation().getCode()); + } + return checkResult; + } + + @lombok.Data + public static class Response { + private Data data; + } + + @lombok.Data + public static class Data { + private String version; + private Integer result; + private Long timestamp; + private String message; + private String id; + private String time_cost; + private List identify_results; + } + + @lombok.Data + public static class IdentifyResults { + private Validation validation; + private String type; + private String orientation; + private Details details; + private Object extra; + } + + @lombok.Data + public static class Validation { + private Integer code; + private String message; + private String async_token; + } + + @lombok.Data + public static class CheckResult { + private boolean success; + private String message; + private Integer code = 0; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenVerifyForm.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenVerifyForm.java new file mode 100644 index 0000000..bf3e27a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/RuiZhenVerifyForm.java @@ -0,0 +1,28 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +/** + * @Author OWTS > + * @Date 2020/11/27 + * @Description + */ +@Data +public class RuiZhenVerifyForm { + private String app_key; + private String token; + private String timestamp; + private String code; + private String number; + private String check_code; + private String check_code_all; + private String pretax_amount; + private String date; + private String type; + private Integer is_async; + + private String total; + private String preTax; + + private String orginFileFlag; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Transport.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Transport.java new file mode 100644 index 0000000..48fd4cc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/entity/Transport.java @@ -0,0 +1,16 @@ +package com.cmsen.ticket.infrastructure.ocr2.entity; + +import lombok.Data; + +@Data +public class Transport { + private String date; + private String from; + private String passenger; + private String seat; + private String goods_name; + private String to; + private String transport_number; + private String transport_type; + private String user_id; +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/ocr2/listener/OperationPrinter.java b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/listener/OperationPrinter.java new file mode 100644 index 0000000..c814215 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/ocr2/listener/OperationPrinter.java @@ -0,0 +1,141 @@ +package com.cmsen.ticket.infrastructure.ocr2.listener; + +import cn.hutool.json.JSONUtil; +import com.cmsen.common.util.StorageCache; +import com.cmsen.ticket.application.util.CacheKey; +import lombok.extern.log4j.Log4j2; +import net.smarttax.sim.annotation.SmarttaxRespListener; +import net.smarttax.sim.entity.dto.RespDTO; +import net.smarttax.sim.entity.resp.*; +import net.smarttax.sim.facade.SmarttaxOperationListener; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @author OWTS + */ +@Component +@SmarttaxRespListener +@Log4j2 +public class OperationPrinter implements SmarttaxOperationListener { + + @Override + public void blanks(RespDTO> results) { + + } + + @Override + public void eInvoiceQuery(RespDTO> results) { + + } + + @Override + public void eInvoice(RespDTO results) { + + } + + @Override + public void invoiceReversing(RespDTO results) { + + } + + @Override + public void invoiceCancellation(RespDTO results) { + + } + + @Override + public void monitoringQuery(RespDTO> results) { + + } + + @Override + public void esignRegister(RespDTO results) { + + } + + @Override + public void esignResisterQuery(RespDTO results) { + + } + + @Override + public void generatePDF(RespDTO results) { + + } + + @Override + public void invoiceNotificationUpload(RespDTO results) { + + } + + @Override + public void invoiceNotificationDownload(RespDTO results) { + + } + + @Override + public void invoicePrint(RespDTO results) { + + } + + @Override + public void invoiceCheck(RespDTO results) { + log.info("invoiceCheck >> {}", JSONUtil.toJsonStr(results)); + InvoiceCheckResp data = results.getData(); + if (results.isSuccess() && null != data) { + StorageCache.write(CacheKey.INVOICE_VERIFY_KEY + data.getInvoiceNum(), data, CacheKey.INVOICE_VERIFY_KEY_TIMEOUT); + log.info("StorageCache.write==success=={}",CacheKey.INVOICE_VERIFY_KEY + data.getInvoiceNum()); + }else{ + String message = results.getMessage(); + StorageCache.write(CacheKey.INVOICE_VERIFY_KEY + results.getSid(), message, CacheKey.INVOICE_VERIFY_KEY_TIMEOUT); + log.info("StorageCache.write==fail=={}",CacheKey.INVOICE_VERIFY_KEY + results.getSid()); + } + } + + @Override + public void invoiceRecognition(RespDTO results) { + + } + + @Override + public void declareInfo(RespDTO results) { + + } + + @Override + public void invoiceDeduction(RespDTO results) { + + } + + @Override + public void deductionStatistics(RespDTO results) { + + } + + @Override + public void deductionStatisticsResult(RespDTO results) { + + } + + @Override + public void deductionConfirm(RespDTO results) { + + } + + @Override + public void deductionConfirmResult(RespDTO results) { + + } + + @Override + public void invoicesSync(RespDTO results) { + + } + + @Override + public void deductionResult(RespDTO results) { + + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/service/ExchangeMailFilePathWatchService.java b/src/main/java/com/cmsen/ticket/infrastructure/service/ExchangeMailFilePathWatchService.java new file mode 100644 index 0000000..58da759 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/service/ExchangeMailFilePathWatchService.java @@ -0,0 +1,770 @@ +package com.cmsen.ticket.infrastructure.service; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.thread.ThreadUtil; +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.impl.SysCorInvoiceServiceImpl; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.application.service.SendMailService; +import com.cmsen.ticket.application.service.SupplierOutService; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.util.StringUtils; +import com.cmsen.ticket.infrastructure.ocr2.OFDUtil; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import com.cmsen.ticket.infrastructure.tools.util.ArchiveExtractor; +import com.cmsen.ticket.interfaces.facade.manager.form.SupplierSearchForm; +import com.cmsen.ticket.log.entity.TInterfaceLog; +import com.cmsen.ticket.log.service.TInterfaceLogService; +import com.cmsen.ticket.monitor.entity.ScheduleJob; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.File; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.*; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * @author 李蒙 + * @version 1.0.0 + * @date 2023/8/11 + * @desc 文件监听2 由与exchange 获取的fileattachment 无法获取inputstream + **/ +@Component +@Slf4j +public class ExchangeMailFilePathWatchService implements CommandLineRunner { + + @Resource + @Qualifier(value = "ScannerPool") + private Executor scannerPool; + + private String watchPath; + // 消息 + StringBuffer mesg=new StringBuffer(); + @Resource + private TInterfaceLogService interfaceLogService; + @Resource + private SysCorInvoiceServiceImpl sysCorInvoiceService; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Value("${file.filepath}") + private String invoicePic; + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Value("${file.domainName}") + private String domainName; + + @Value("${server.servlet.context-path}") + private String contextPath; + + @Value("${file.filepath}") + private String filePath; + + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private PostBoxMapper postBoxMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; + + @Resource + private RuleConfigMapper ruleConfigMapper; + + @Resource + private SysUserMapper sysUserMapper; + + @Resource + private SendMailService sendMailService; + + @Resource + private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; + + @Resource + private SupplierOutService supplierOutService; + + @Value("${spring.application.name}") + private String applicationName; + + @Resource + private SupplierMapper supplierMapper; + + @Resource + private ScannerLogsMapper scannerLogsMapper; + + @Resource + private SysOrgMapper sysOrgMapper; + + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @Override + public void run(String... args) throws Exception { + SysConfig sysConfig = sysConfigMapper.selectByCode("MAIL_EXCHANGE_ATTACHEMENTFOLDER"); + if(null==sysConfig){ + + }else{ + watchPath = sysConfig.getValue(); + scannerPool.execute(() -> { + boolean exist = FileUtil.exist(watchPath); + if (!exist) { + log.info("Start exchange Watching Failed >> No Path exist >> {}", watchPath); + return; + } + while (true) { + try { + log.info("Start exchange Watching >> {}", watchPath); + watchSap(); + } catch (Exception e) { + log.error("Start exchange Watching Error >> {} >> {}", watchPath, e.getMessage()); + log.error(e.getMessage(), e); + ThreadUtil.sleep(10000); + } + } + }); + } + } + + + private void watchSap() throws Exception { + WatchService watchService = FileSystems.getDefault().newWatchService(); + Paths.get(watchPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE); + while (true) { + WatchKey key = watchService.poll(10, TimeUnit.SECONDS); + if (key == null) { + continue; + } + for (WatchEvent event : key.pollEvents()) { + WatchEvent.Kind kind = event.kind(); + //监听新建文件 + if (kind == StandardWatchEventKinds.ENTRY_CREATE) { + Path path = (Path) (event.context()); + Path fullPath = Paths.get(watchPath, path.toString()); + String oldPath = fullPath.toString(); + File file = new File(oldPath); + log.info("New File Upload to exchange mail floder > {}", oldPath); + if(!file.isDirectory()){ + scannerPool.execute(() -> dealFileAttachment(oldPath)); + } + } + log.info("deal file sleep time start:{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); + SysConfig sysConfig = sysConfigMapper.selectByCode("AI_SLEEP_TIME"); + if(null!=sysConfig){ + String con_value = sysConfig.getValue(); + ThreadUtil.sleep(Integer.parseInt(con_value)); + } + } + key.reset(); + } + } + + + private void dealFileAttachment(String attachmentPath){ + log.info("attachmentPath=>{}",attachmentPath); + String date = DateFormat.format(new Date(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日); + //处理邮件 +// Integer userId = userEmailList.get(from); + File attachmentFile = new File(attachmentPath); + if(attachmentFile.isDirectory()){ + return; + } + if(!attachmentFile.exists()){ + log.info("exchange file not exist 》{}",attachmentFile.getAbsolutePath()); + } + long oldLength; + long newLength; + //判断文件是否写入完成 + int maxTry = 20; + int tryed = 1; + mesg = new StringBuffer(); + do { + oldLength = new File(attachmentPath).length(); + log.info("exchange File Uploading1 >> {} : {}", attachmentPath, oldLength); + ThreadUtil.sleep(3000); + newLength = new File(attachmentPath).length(); + log.info("exchange File Uploading2 >> {} : {}", attachmentPath, newLength); + tryed++; + } while ((oldLength != newLength || newLength ==0) && tryed<=maxTry ); + String folder = Pdf2JpgHelper.generateFolder(invoicePic + File.separator); + InputStream is = null; + String k = attachmentFile.getName(); + log.info("exchange 获取附件名称>>{}", k); + try { + if (k.endsWith(".PDF") || k.endsWith(".pdf")) { + String originalFilename = attachmentPath; + //添加log + ScannerLogs scannerLogs = new ScannerLogs(); + SysConfig mailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + if(null!=mailOrg){ + SysOrg org = sysOrgMapper.selectByPrimaryKey(Integer.parseInt(mailOrg.getValue())); + scannerLogs.setCompanyId(org.getCode()); + }else{ + // 这里暂时不处理 + log.error("===>>>> CODE PUBLIC_MAIL_ORG not find in table SYS_CONFIG"); + } + scannerLogs.setCostType("service"); + scannerLogs.setFileName(attachmentFile.getName()); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setHashKey(UUID.randomUUID().toString()); + scannerLogsMapper.insert(scannerLogs); + + + + String newPDFName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".pdf"; + String imgFilePath_pdf = invoicePic + File.separator + folder + newPDFName; + if(attachmentFile.exists()){ + boolean flag = attachmentFile.renameTo(new File(imgFilePath_pdf)); + // 不成功则复制 删除源文件 + if(!flag){ + try { + FileUtils.copyFile(attachmentFile, new File(imgFilePath_pdf)); + // 成功后删除 +// attachmentFile.delete(); + flag =true; + }catch (Exception e){ + log.error("copy file error!"); + e.printStackTrace(); + } + } + } + log.info(" {} file size 1 >>>>>>>>>>>>>>>>>>>:{}",imgFilePath_pdf,new File(imgFilePath_pdf).length()); + +// String pdfRealPath = domainName + contextPath + imgVirtualPath + "/" + folder + newPDFName; + log.info("mail原Pdf图片地址:>>{}", imgFilePath_pdf); + + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(2); + Integer owner =0; + SysConfig publicMailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + SysConfig supplierAdmin = sysConfigMapper.selectByCode("Supplier_Admin"); + if(null!=supplierAdmin){ + owner = Integer.parseInt(supplierAdmin.getValue()); + } + Integer orgId = 0; + String com = ""; + if(null!=publicMailOrg){ + orgId = Integer.parseInt(publicMailOrg.getValue()); + SysOrg company = sysOrgMapper.selectByPrimaryKey(orgId); + if (null != company) { + com = company.getCode(); + } + } + sysCorInvoiceService.pdfToImagesForElectronic(null,"", imgFilePath_pdf, watchPath, false, com, owner, corporateInvoiceType,null,scannerLogs.getId()); +// for (List images2 : images) { +// String image = images2.get(0).replace("\\", "/"); +// String savepath = uploadPath + image; +// String imgRealPath = domainName + contextPath + imgVirtualPath + "/" + image; +// log.info("解析后的jpg图片地址:>>{} >> {}", imgRealPath, savepath); +// RuiZhenOCREntity ruiZhenOCREntity = ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(savepath)); +// dealResult(date, "", "", imgRealPath, pdfRealPath, ruiZhenOCREntity); +// } + } else if (k.endsWith(".OFD") || k.endsWith(".ofd")) { + SysConfig needOFDDeal = sysConfigMapper.selectByCode("FLD_OFD_DEAL"); + if(null!=needOFDDeal&&"0".equals(needOFDDeal.getValue())){ + return; + } + + + //添加log + ScannerLogs scannerLogs = new ScannerLogs(); + SysConfig mailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + if(null!=mailOrg){ + SysOrg org = sysOrgMapper.selectByPrimaryKey(Integer.parseInt(mailOrg.getValue())); + scannerLogs.setCompanyId(org.getCode()); + }else{ + // 这里暂时不处理 + log.error("===>>>> CODE PUBLIC_MAIL_ORG not find in table SYS_CONFIG"); + } + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(2); + Integer owner =0; + SysConfig publicMailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + SysConfig supplierAdmin = sysConfigMapper.selectByCode("Supplier_Admin"); + if(null!=supplierAdmin){ + owner = Integer.parseInt(supplierAdmin.getValue()); + } + Integer orgId = 0; + String com = ""; + if(null!=publicMailOrg){ + orgId = Integer.parseInt(publicMailOrg.getValue()); + SysOrg company = sysOrgMapper.selectByPrimaryKey(orgId); + if (null != company) { + com = company.getCode(); + } + } + scannerLogs.setCostType("service"); + scannerLogs.setFileName(attachmentFile.getName()); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setHashKey(UUID.randomUUID().toString()); + scannerLogsMapper.insert(scannerLogs); + String newOFDName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + k; + String newPdfPath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".pdf"; + String finalOfdPath = invoicePic + File.separator + folder + newOFDName; + String finalPdfPath = invoicePic + File.separator + folder + newPdfPath; + FileOutputStream os = new FileOutputStream(finalOfdPath); + int len = -1; + is = new FileInputStream(attachmentFile); + byte[] bytes = new byte[1024]; + while ((len = is.read(bytes)) != -1) { + os.write(bytes, 0, len); + } + os.flush(); + is.close(); + os.close(); +// String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpeg"; +// RuiZhenOCREntity ruiZhenOCREntity = OFDUtil.dealOFDInvoice(invoicePic + File.separator + folder + newOFDName, invoicePic + File.separator + folder + newImgName); +// if(null!=ruiZhenOCREntity){ +// try { +// String ofdNumber = ruiZhenOCREntity.getResponse().getData().getIdentify_results().get(0).getDetails().getNumber(); +// List ofdInvoiceExist = corporateInvoiceMapper.selectByInvoiceNumber(ofdNumber); +// if (!ofdInvoiceExist.isEmpty()){ +// log.info("ofdInvoiceExist number 已重复,不继续导入=》{}",ofdNumber); +// return; +// } +// }catch (Exception e){ +// log.error("OFD 识别 number 错误=》",e.getMessage()); +// e.printStackTrace(); +// } +// } + OFDUtil.convertToPdf(finalOfdPath, finalPdfPath,12); +// String imgRealPath = domainName + contextPath + imgVirtualPath + "/" + folder + newPdfPath; +// String pdfRealPath = domainName + contextPath + imgVirtualPath + "/" + folder + newOFDName; +// sysCorInvoiceService.pdfToImagesForElectronic("", imgRealPath, watchPath, false, null, , corporateInvoiceType,null,scannerLogs.getId()); +// if (ruiZhenOCREntity != null) { +// dealResult(date, "", "", imgRealPath, pdfRealPath, ruiZhenOCREntity); +// } + sysCorInvoiceService.pdfToImagesForElectronic(null,"", finalPdfPath, watchPath, false, com, owner, corporateInvoiceType,null,scannerLogs.getId()); + }if (k.toLowerCase().endsWith(".7z") || k.toLowerCase().endsWith(".rar") || k.toLowerCase().endsWith(".zip")) { + String archiveParent = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8); + log.info(" 压缩包 {}名称=》{}",attachmentPath,archiveParent); + ArchiveExtractor.extractToFolder(attachmentFile.getAbsolutePath(),archiveParent); + File archive = new File(watchPath +archiveParent); + traverseFolder(archive,watchPath); + deleteFolder(archive); + attachmentFile.delete(); + } + else if(k.endsWith(".CSV")|| k.endsWith(".csv")){ + List suppliers = supplierMapper.list(new SupplierSearchForm()); + Map> suppliersMap = suppliers.stream().collect(Collectors.groupingBy(Supplier::getCode)); + String lineTxt; + int line = 1; + String[] str={}; + FileInputStream fis = null; + try{ + fis = new FileInputStream(attachmentFile); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis)); + while ((lineTxt=bufferedReader.readLine())!=null){ +// log.info("lineTxt==========>{}",lineTxt); + if(line>=4){ + if(lineTxt==null || lineTxt.length()==0) continue; + str = lineTxt.split("\t"); + String code = str[2]; + String name = str[4]; + String country = str[10]; + String VATRegNo = str[17]; + if(null==suppliersMap.get(code)){ + // 没有则 新增 + Supplier supplier = new Supplier(); + supplier.setCode(code); + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.insertSelective(supplier); + }else{ + // 存在则判断是否更新 + Supplier supplier = suppliersMap.get(code).get(0); +// if(org.apache.commons.lang3.StringUtils.isNotEmpty(supplier.getTaxNo())){ +// continue; +// } + if(org.apache.commons.lang3.StringUtils.isEmpty(VATRegNo)){ + continue; + }else{ + if(name.equals(supplier.getName()) + &&country.equals(supplier.getExt01()) + &&VATRegNo.equals(supplier.getTaxNo())){ + continue; + }else{ + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.updateByPrimaryKey(supplier); + } + } + } + } + line++; + } + }catch (IOException e){ + mesg.append("exchange导入 解析 供应商csv 文件异常===>>").append(e.getMessage()); + log.error("exchange导入 解析 供应商csv 文件异常==={}",e.getMessage()); + }finally { + fis.close(); + } + }else{ + attachmentFile.delete(); + } + } catch (Exception e) { + mesg.append("exchange识别附件结果>>ERROR>>").append(e.getMessage()); + log.info("exchange识别附件结果>>ERROR>>{}", e.getMessage()); + e.printStackTrace(); + }finally { + TInterfaceLog interfaceLog = new TInterfaceLog(); + interfaceLog.setInterfaceName("exchange邮箱"); + if(mesg.length()>0){ + interfaceLog.setRunState("1"); + interfaceLog.setSendMesg(mesg.toString()); + interfaceLog.setRunMesg("文件名=>"+attachmentFile.getAbsolutePath()); + }else{ + interfaceLog.setRunState("2"); + if(interfaceLog.getRunMesg()==null || interfaceLog.getRunMesg().length()==0) + { + interfaceLog.setSendMesg("运行成功"); + interfaceLog.setRunMesg("文件名=>"+attachmentFile.getAbsolutePath()); + } + } + interfaceLog.setIsRollBack("0"); + ScheduleJob scheduleJob = new ScheduleJob(); + interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); + } + // 源文件暂时不删除 +// attachmentFile.delete(); + } + + private void dealResult(String date, String from, String subject, String imgRealPath, String pdfRealPath, RuiZhenOCREntity ruiZhenOCREntity) { + List results = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults result : results) { + if (result.getType().equals("10900")) { + break; + } + Details details = result.getDetails(); + PostBox postBox = new PostBox(); + postBox.setSubject(subject); + postBox.setUserId(0); + postBox.setFilePath(imgRealPath); + postBox.setIdentifyResult(JsonUtil.toString(ruiZhenOCREntity)); + postBox.setFrom(from); + postBox.setReceiveDate(date); + postBox.setBuyer(details.getSeller()); + postBox.setInvoiceMoney(details.getTotal()); + postBox.setInvoiceDate(StringUtil.isEmpty(details.getDate()) ? date : details.getDate()); + postBox.setInvoiceNum(details.getNumber()); + postBox.setType(1); + postBox.setOriginalPath(pdfRealPath); + int i = postBoxMapper.checkRepeat(details.getNumber()); + if (i > 0) { + postBox.setRepeat(true); + } + TicketType ticketType = ticketTypeMapper.selectByCode(result.getType()); + //postBox.setTicketType(ticketType == null ? "未知发票" : ticketType.getValue()); + postBox.setTicketType(result.getType()); + postBox.setCreateTime(new Date()); + postBoxMapper.insertSelective(postBox); + log.info("识别附件结果>>SUCCESS>>{}", postBox); + + //2023-05-17 从sys_config 中获取获取配置信息 + SysConfig publicMailChk = sysConfigMapper.selectByCode("PUBLIC_MAIL_CHK"); + + // 2023-06-13 从sys_config 中获取 user信息 + SysConfig supplierAdmin = sysConfigMapper.selectByCode("Supplier_Admin"); + + boolean flagForMail = true; + if(null!=publicMailChk&&"0".equals(publicMailChk.getValue())){ + flagForMail = false; + } + //判断from是否存在sys_user表 2022/6/1 + SysUser sysUser = sysUserMapper.selectByEmail(from.toLowerCase());//转换成小写 + if(sysUser == null&&flagForMail){ + String text = "邮件地址【"+from+"】对应的组织不存在,请联系管理员"; + sendMailService.sendVerifiedText(from, text); + }else{ + if(flagForMail&&null!=sysUser&&(sysUser.getOrgId() == null || sysUser.getOrgId().equals(""))){ + String text = "邮件地址【"+from+"】对应的组织不存在,请联系管理员"; + sendMailService.sendVerifiedText(from, text); + }else{ + Integer userId = null; + if(null==sysUser){ + if(null!=supplierAdmin){ + userId = Integer.valueOf(supplierAdmin.getValue()); + } + }else{ + userId = sysUser.getId(); + } + //识别发票并发往维泰 + String uuid = StringUtil.UUID(); + CorporateInvoice corporateInvoice = new CorporateInvoice(); + corporateInvoice.setId(uuid); + corporateInvoice.setOwner(userId); + corporateInvoice.setTitle(details.getSeller()); + corporateInvoice.setSeller(details.getSeller()); + corporateInvoice.setSellerNo(details.getSeller_tax_id()); + if(null==details.getCode()||"".equals(details.getCode())){ + corporateInvoice.setCode("0000"); + }else{ + corporateInvoice.setCode(details.getCode()); + } + corporateInvoice.setCode(details.getCode()); + corporateInvoice.setNumber(details.getNumber()); + corporateInvoice.setDate(details.getDate()); + corporateInvoice.setTotal(details.getTotal()); + corporateInvoice.setImgPath(imgRealPath); + corporateInvoice.setRemark(details.getRemark()); + //corporateInvoice.setExtraFields(); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(details.getBuyer()); + corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + corporateInvoice.setTicketCode(result.getType()); + corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(0); + corporateInvoice.setOriginalFilePath(pdfRealPath); + corporateInvoice.setVerifiedCode(details.getCheck_code()); + corporateInvoice.setPretaxAmount(details.getPretax_amount()); + corporateInvoice.setTax(details.getTax()); + corporateInvoice.setOperatorId(userId);//插入from邮箱的userid 2022/6/9 + corporateInvoice.setCreateDate(new Date()); + corporateInvoice.setCurrency("CNY"); + corporateInvoice.setChecked(0); + corporateInvoice.setPo(StringUtils.getPO(details.getRemark())); + corporateInvoice.setCurrency("CNY"); + corporateInvoice.setChecked(0); + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + corporateInvoice.setDetails(details.getItem_names()); + //corporateInvoice.setInvoiceType(); + corporateInvoice.setIsSend(0); + corporateInvoice.setUseStatus(9); + corporateInvoice.setMatchStatus(0); + + //增加保存字段 2022/8/16 + corporateInvoice.setNumberBackup(details.getNumberBackup()); + corporateInvoice.setNumberConfirm(details.getNumber_confirm()); + corporateInvoice.setCompanySeal(details.getCompany_seal()); + + //以下为之前获取item信息,改走验真获取 注释 2022/6/1 + /*List corporateInvoiceItems = new ArrayList<>(); + List items = details.getItems(); + StringBuilder itemDetails = new StringBuilder(); + if (items != null && !items.isEmpty()) { + for (Item item : items) { + itemDetails.append(item.getName()).append(";"); + corporateInvoiceItems.add(new CorporateInvoiceItems() {{ + setId(StringUtil.UUID()); + setPid(uuid); + setName(item.getName()); + setUnit(item.getUnit()); + setQuantity(item.getQuantity()); + setPrice(item.getPrice()); + setTotal(item.getTotal()); + }}); + } + } + corporateInvoice.setDetails(itemDetails.toString()); + corporateInvoice.setItems(corporateInvoiceItems);*/ + + //增加发票接收实体 2022/6/1 + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + //合规逻辑 + StringBuilder message = new StringBuilder(); + corporateInvoiceService.validationRules(corporateInvoice, message, ticketType); + log.info("===corporateInvoice1.getStatus() exchange:{}",corporateInvoice.getStatus()); + corporateInvoice.setMessage(message.toString()); + + if (corporateInvoice.getStatus()==2) {//验真、合规失败 --发送邮件给运维支持人员 + String text = "邮件发票导入【"+corporateInvoice.getNumber()+"】异常"; + //得到运维支持人员邮箱 sys_config中SUPPORT_MAIL + SysConfig sysConfig = sysConfigMapper.selectByCode("SUPPORT_MAIL"); + if(null==sysConfig){ + + }else{ + String[] split = sysConfig.getValue().split(","); + for (String email : split) { + sendMailService.sendVerifiedText(email, text); + } + } + }else{ + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if(null==ext08Config){ + corporateInvoice.setExt08("2"); + }else{ + corporateInvoice.setExt08(ext08Config.getValue()); + } + } + + //corporateInvoice.setMessage(message.toString()); + corporateInvoice.setMatchStatus(0); + + //增加赋值 2022/6/1 + corporateInvoice.setInvoiceType(1); + + //2023-05-17 + if(flagForMail){ + // 如果配置1 走原来的逻辑 + corporateInvoice.setOrgId(sysUser.getOrgId()); + }else{ + // 如果配置非1 则 需要从sysconfig中找到org + SysConfig mailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + if(null!=mailOrg){ + corporateInvoice.setOrgId(Integer.parseInt(mailOrg.getValue())); + }else{ + // 这里暂时不处理 + log.error("===>>>> CODE PUBLIC_MAIL_ORG not find in table SYS_CONFIG"); + } + } + + corporateInvoice.setMatchType(0);//金额 + corporateInvoice.setPriceType(0);//折后 + + corporateInvoiceMapper.insert(corporateInvoice); + + //验真结果后的item获取插入 2022/6/1 + List corporateInvoiceItems = corporateInvoice.getItems(); + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + corporateInvoiceItemsMapper.insert(corporateInvoiceItem); + } + // 发送OA + if (corporateInvoice.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType != null && corporateInvoiceType.getSendType() == 1) { + supplierOutService.sendInvoice(corporateInvoice, applicationName, "0"); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + } + } + String succesStr="邮件发票导入【"+corporateInvoice.getNumber()+"】成功"; + sendMailService.sendVerifiedText(from, succesStr); + /*for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + corporateInvoiceItemsMapper.insert(corporateInvoiceItem); + }*/ + + + } + } + } + } + + public void traverseFolder(File folder,String destParentPath) throws Exception { + if (!folder.exists() || !folder.isDirectory()) { + log.error("无效的文件夹路径: " + folder.getAbsolutePath()); + return; + } + + for (File file : Objects.requireNonNull(folder.listFiles())) { + log.info("file=>{}",file.getAbsolutePath()); + if (file.isDirectory()) { +// System.out.println("[目录] " + file.getAbsolutePath()); + traverseFolder(file,destParentPath); // 递归处理子目录 + } else { + if(file.getAbsolutePath().toLowerCase().endsWith(".ofd")){ + SysConfig needOFDDeal = sysConfigMapper.selectByCode("FLD_OFD_DEAL"); + if(null!=needOFDDeal&&"0".equals(needOFDDeal.getValue())){ + continue; + } + String pdfPath =file.getAbsolutePath().replace(".ofd",".pdf").replace(".OFD",".pdf"); + OFDUtil.convertToPdf(file.getAbsolutePath(),pdfPath,12); + Path sourcePath = Paths.get(pdfPath); + String fileName = file.getName(); + String fileName1 = fileName.substring(0,fileName.lastIndexOf(".")); + File exists = new File(watchPath+File.separator+fileName1+".pdf"); + if(exists.exists()){ + log.warn("exchange 同名ofd文件已存在=> {}",watchPath+File.separator+fileName1+".pdf"); + continue; + } + Path destinationPath = Paths.get(watchPath+File.separator+fileName1+".pdf"); + Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING); +// dealList.add(pdfPath); + }else{ + log.info("file pdf=>{}",file.getAbsolutePath());Path sourcePath = Paths.get(file.getAbsolutePath()); + String fileName = file.getName(); + File exists = new File(watchPath+File.separator+fileName); + if(exists.exists()){ + log.warn("exchange 同名pdf文件已存在=>{}",watchPath+File.separator+fileName); + continue; + } + Path destinationPath = Paths.get(watchPath+File.separator+file.getName()); + Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING); + } + } + } + } + + public static void deleteFolder(File folder) { + if (folder.isDirectory()) { + File[] files = folder.listFiles(); + if (files != null) { + for (File file : files) { + deleteFolder(file); + } + } + } + folder.delete(); + } + + public static void main(String asd[]){ + File f = new File("E:\\Vendor_Download_Report_AP7_20251106_080121.csv"); + String lineTxt; + int line = 1; + String[] str={}; + FileInputStream fis = null; + try{ + fis = new FileInputStream(f); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis)); + while ((lineTxt=bufferedReader.readLine())!=null){ + log.info("lineTxt==========>{}",lineTxt); + if(line>=4){ + if(lineTxt==null || lineTxt.length()==0) continue; + if(lineTxt.indexOf("44112936")>-1){ + log.info(lineTxt); + } + str = lineTxt.split("\t"); + String code = str[2]; + String name = str[4]; + String country = str[10]; + String VATRegNo = str[17]; + } + line++; + } + }catch (IOException e){ + log.error("exchange导入 解析 供应商csv 文件异常==={}",e.getMessage()); + }finally { + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/service/GenCodeService.java b/src/main/java/com/cmsen/ticket/infrastructure/service/GenCodeService.java new file mode 100644 index 0000000..525b69d --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/service/GenCodeService.java @@ -0,0 +1,153 @@ +package com.cmsen.ticket.infrastructure.service; + +import com.alibaba.fastjson.JSONObject; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.infrastructure.ocr2.GetAppTokenFeign; +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayApiCode; +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayApiToken; +import com.cmsen.ticket.infrastructure.ocr2.entity.GatewayCodeGen; +import com.cmsen.ticket.infrastructure.ocr2.entity.R; +import com.dtflys.forest.Forest; +import lombok.extern.slf4j.Slf4j; +import okhttp3.*; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; + +@Component +@Slf4j +public class GenCodeService { + + @Resource + private SysConfigMapper sysConfigMapper; + + // 生成验证码 + private static final String ALGORITHM = "AES"; + private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; +// private static final String appKey = "2XmgaIJ3ds4A4AGV"; +// private static final String appSecret ="x9OYSOkgB2F568mcs44v-lK-ENhJo5dW4Fi-uNsEj6M"; +// private static final String appServerName="crm_server"; + + + public String getPFGatewayToken2(){ + String result = null; + try { + SysConfig appkeyConfig = sysConfigMapper.selectByCode("PF_GATEWAY_APPKEY"); + + SysConfig appSecretConfig = sysConfigMapper.selectByCode("PF_GATEWAY_APPSECRET"); + SysConfig pfGatewayTokenUrlConfig = sysConfigMapper.selectByCode("PF_GATEWAY_TOKEN_URL"); + String appKey = appkeyConfig.getValue(); + String appSecret = appSecretConfig.getValue(); + String pfGatewayTokenUrl = pfGatewayTokenUrlConfig.getValue(); + String url = pfGatewayTokenUrl+"?client_id="+appKey+"&client_secret="+appSecret+"&grant_type=client_credentials"; + OkHttpClient client = new OkHttpClient().newBuilder() + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request = new Request.Builder() + .url(url) + .method("POST", body) + .build(); + try (Response response = client.newCall(request).execute()) { + // 1. 判断请求是否成功(HTTP 200~300) + if (!response.isSuccessful()) { + log.error("请求失败,状态码:" + response.code()); + return result; + } + + // 2. 获取返回体 + ResponseBody rbody = response.body(); + + if (rbody != null) { + // 3. 获取字符串结果(最常用) + String jsonRes = rbody.string(); + log.info("token 返回结果:" + result); + JSONObject res = JSONObject.parseObject(jsonRes); + if(null!=res.get("access_token")){ + result = res.getString("access_token"); + } + } + + } catch (Exception e) { + // 网络异常、解析异常都在这里捕获 + e.printStackTrace(); + } + log.info("token result===>{}",result); + }catch (Exception e){ + e.printStackTrace(); + } + return result; + } + + public String getPFGatewayToken() { + SysConfig appkeyConfig = sysConfigMapper.selectByCode("PF_GATEWAY_APPKEY"); + + SysConfig appSecretConfig = sysConfigMapper.selectByCode("PF_GATEWAY_APPSECRET"); + SysConfig appServerNameConfig = sysConfigMapper.selectByCode("PF_GATEWAY_APPSERVERNAME"); + String appKey = appkeyConfig.getValue(); + String appSecret = appSecretConfig.getValue(); + String appServerName = appServerNameConfig.getValue(); + //获取code + GetAppTokenFeign getAppTokenFeign = Forest.client(GetAppTokenFeign.class); + R appCodeByAppKeyR = getAppTokenFeign.getAppCodeByAppKey(appKey); + log.info("PF GATEWAY TOEKN appCodeByAppKeyR.getCode():{}",appCodeByAppKeyR.getCode()); + GatewayApiCode data = appCodeByAppKeyR.getData(); + // 获取data里面的code + // 获取code + String codeStr= data.getCode(); + log.info("PF GATEWAY TOEKN codeStr:{}",codeStr); + // 解密 自己的密钥 + String decryptedCode =null; + try { + decryptedCode = decrypt(codeStr, appSecret); + } catch (Exception e) { + throw new RuntimeException(e); + } + log.info("PF GATEWAY TOEKN decryptedCode:{}",decryptedCode); + JSONObject decryptedCodeObject = JSONObject.parseObject(decryptedCode); + String validCode = decryptedCodeObject.getString("code"); + log.info("PF GATEWAY TOEKN validCode:{}",validCode); + // 生成token接口 + R crmServer = getAppTokenFeign.getAppTokenByAppKeyAndAppCode(new GatewayCodeGen(appServerName + , appKey, validCode, codeStr)); + GatewayApiToken crmServerData = crmServer.getData(); + // 获取token + String token = crmServerData.getToken(); + log.info("PF GATEWAY TOEKN token:{}",token); + return token; + } + + + public static String decrypt(String encryptedData, String secretKey) throws Exception { + // 处理密钥 + byte[] keyBytes = generateKeyBytes(secretKey); + SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM); + IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes); + + // 直接解码Base64字符串 + byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData); + + // 初始化解密器 + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); + + // 执行解密 + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + return new String(decryptedBytes, StandardCharsets.UTF_8); + } + //密钥规则 + private static byte[] generateKeyBytes(String secretKey) throws Exception { + MessageDigest sha = MessageDigest.getInstance("MD5"); + byte[] hash = sha.digest(secretKey.getBytes(StandardCharsets.UTF_8)); + byte[] keyBytes = new byte[16]; + System.arraycopy(hash, 0, keyBytes, 0, 16); + return keyBytes; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/service/PaymentOAService.java b/src/main/java/com/cmsen/ticket/infrastructure/service/PaymentOAService.java new file mode 100644 index 0000000..6da19ef --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/service/PaymentOAService.java @@ -0,0 +1,2863 @@ +package com.cmsen.ticket.infrastructure.service; + +import cn.hutool.core.text.StrBuilder; +import com.cmsen.common.http.ClientHttp; +import com.cmsen.common.http.ClientHttpRequest; +import com.cmsen.common.http.ContentEnctype; +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.service.impl.SupplierOutServiceImpl; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysEmp; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SupplierOrderItemMatchingMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysEmpMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import lombok.extern.slf4j.Slf4j; +import org.json.JSONObject; +import org.json.XML; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + * @date 2023/2/24 15:26 + * @description 付款申请单相关OA接口 + */ +@Component +@Slf4j +public class PaymentOAService { + + //BASE_URL + private final String BASE_URL = "http://oauat.baozun.com/"; + + //援引数据URL + private final String INVOKE_URL = "weaver/SetRequestTodayService"; + + //流程webService-URL + private final String WORKFLOW_URL = "services/WorkflowService"; + + //提交发票匹配URL + private final String SUBMIT_MATCH_URL = "weaver/SubmitWorkflowService"; + + //提交流程URL--发票匹配 后票 + private final String SUBMIT_URL = "weaver/SubmitRequestService"; + + @Resource + private SysEmpMapper sysEmpMapper; + + @Resource + private SupplierOrderMapper supplierOrderMapper; + + @Resource + private SupplierOrderItemMatchingMapper supplierOrderItemMatchingMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private TaxMappingMapper taxMappingMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private InvokePurchaseMapper invokePurchaseMapper; + + @Resource + private FileMapper fileMapper; + + @Resource + private InvokeBrandMapper invokeBrandMapper; + + @Resource + private SysOrgMapper sysOrgMapper; + + @Resource + private SupplierMapper supplierMapper; + + /** + * 创建流程 + * + * @param supplierOrderHeader + */ + public String createBill(SupplierOrderHeader supplierOrderHeader) throws Exception { + + String billNumber = ""; + String postData = getBillPostData(supplierOrderHeader,"1"); + log.info("createBill postData>>>>>>>>>>{}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + WORKFLOW_URL); + setHeaders("Content-Type", "text/xml;charset=UTF-8"); + setParams(postData); + }}).getBody(); + String res = body.toString(); + log.info("createBill response>>>>>>>>>>{}", res); + + if (res.indexOf("ns1:doCreateWorkflowRequestResponse") != -1) { + log.info("createBill doCreateWorkflowRequestResponse>>>>>>>>>>"); + JSONObject obj = XML.toJSONObject(res); + JSONObject response = obj.getJSONObject("soap:Envelope").getJSONObject("soap:Body").getJSONObject("ns1:doCreateWorkflowRequestResponse"); + billNumber = response.get("ns1:out").toString(); + log.info("createBill billNumber>>>>>>>>>>{}", billNumber); + } + return billNumber; + } + + /** + * 重新提交流程 + * + * @param supplierOrderHeader + */ + public String submitBill(SupplierOrderHeader supplierOrderHeader) { + + String returnStr = ""; + String postData = getBillPostData(supplierOrderHeader,"2"); + log.info("submitBill postData>>>>>>>>>>{}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + WORKFLOW_URL); + setHeaders("Content-Type", "text/xml;charset=UTF-8"); + setParams(postData); + }}).getBody(); + String res = body.toString(); + log.info("submitBill response>>>>>>>>>>{}", res); + + if (res.indexOf("ns1:submitWorkflowRequestResponse") != -1) { + log.info("submitBill submitWorkflowRequestResponse>>>>>>>>>>"); + JSONObject obj = XML.toJSONObject(res); + JSONObject response = obj.getJSONObject("soap:Envelope").getJSONObject("soap:Body").getJSONObject("ns1:submitWorkflowRequestResponse"); + returnStr = response.get("ns1:out").toString(); + log.info("submitBill returnStr>>>>>>>>>>{}", returnStr); + } + + return returnStr; + } + + /** + * 后票提交流程 + * @param supplierOrderHeader + * @return + */ + public String submitMatchBill(SupplierOrderHeader supplierOrderHeader) { + + log.info("submitMatchBill >>>>"); + + String postData = "{\"requestid\":\"" + supplierOrderHeader.getBillNumber() + "\"}"; + log.info("submitMatchBill postData >> {}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + SUBMIT_URL); + setHeaders("Content-Type", "application/json"); + setParams(postData); + }}).getBody(); + log.info("submitMatchBill Res >> {}", body); + + String res = body.toString(); + log.info("submitMatchBill response>>>>>>>>>>{}", res); + + return res; + } + + /** + * 提交发票匹配 + * @param supplierOrderHeader + */ + public String submitMatchItems(SupplierOrderHeader supplierOrderHeader, String userId){ + if(supplierOrderHeader.getInvoiceType().equals("形式发票后票")){ + log.info("submitMatchItems >> 附件信息 >>"); + List orderList = supplierOrderMapper.selectByOrderNo(supplierOrderHeader.getBillId()); + for (SupplierOrder supplierOrder : orderList) { + String postData = getHeaderPostData(supplierOrderHeader, supplierOrder); + log.info("submitMatchItems >> 附件信息 postData >> {}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + SUBMIT_MATCH_URL); + setHeaders("Content-Type", "application/json"); + setParams(postData); + }}).getBody(); + log.info("submitMatchItems >> 附件信息 Res >> {}", body); + + String result = JsonUtil.toObject(body.toString()).get("result").toString(); + if(result.equals("false")){ + return JsonUtil.toObject(body.toString()).get("message").toString(); + } + } + }else{ + log.info("submitMatchItems >> 非 形式发票后票 >>"); + + List matchList = supplierOrderItemMatchingMapper.selectByOrderNo2(supplierOrderHeader.getBillId(),userId,"0"); + for (SupplierOrderItemMatching supplierOrderItemMatching : matchList) { + String postData = getMatchItemPostData(supplierOrderHeader, supplierOrderItemMatching); + log.info("submitMatchItems postData >> {}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + SUBMIT_MATCH_URL); + setHeaders("Content-Type", "application/json"); + setParams(postData); + }}).getBody(); + log.info("submitMatchItems Res >> {}", body); + + String result = JsonUtil.toObject(body.toString()).get("result").toString(); + if(result.equals("false")){ + return JsonUtil.toObject(body.toString()).get("message").toString(); + } + } + } + + return "true"; + } + + /** + * 删除申请单 + * @param billNumber + * @return true-成功 false-失败 + */ + public String deleteBill(String billNumber, String userId) { + + String postData = getDeletePostData(billNumber, userId); + log.info("deleteBill postData>>>>>>>>>>{}", postData); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + WORKFLOW_URL); + setHeaders("Content-Type", "text/xml;charset=UTF-8"); + setParams(postData); + }}).getBody(); + String res = body.toString(); + log.info("deleteBill response>>>>>>>>>>{}", res); + + String flag = "false"; + if (res.indexOf("ns1:deleteRequestResponse") != -1) { + log.info("deleteBill deleteRequestResponse>>>>>>>>>>"); + JSONObject obj = XML.toJSONObject(res); + JSONObject response = obj.getJSONObject("soap:Envelope").getJSONObject("soap:Body").getJSONObject("ns1:deleteRequestResponse"); + flag = response.get("ns1:out").toString(); + log.info("deleteBill flag>>>>>>>>>>{}", flag); + } + + return flag; + } + + /** + * 判断是否收票 + * @param billNumber + * @return true: 已收票,flase:没有收票 + */ + public boolean checkCollect(String billNumber) { + + + + return true; + } + + public String listInvokeDatas(Map params) { + + String paramsStr = JsonUtil.toString(params); + log.info("listInvokeDatas paramsStr >> {}", paramsStr); + + StringBuilder body = ClientHttp.post(new ClientHttpRequest() {{ + setUrl(BASE_URL + INVOKE_URL); + setHeaders("Content-Type", ContentEnctype.JSON); + setParams(paramsStr); + }}).getBody(); + log.info("listInvokeDatas body >> {}", body.toString()); + + return body.toString(); + } + + public String getEmpPostData() { + StrBuilder xml = new StrBuilder(); + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + public String getOaDeptPostData() { + StrBuilder xml = new StrBuilder(); + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + public String getDeletePostData(String billNumber, String userId) { + StrBuilder xml = new StrBuilder(); + + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""+billNumber+""); + xml.append(""+userId+""); + xml.append(""); + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + public String getProjectPostData(String modeId, int pageNo, int pageSize) { + StrBuilder xml = new StrBuilder(); + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""+modeId+""); + xml.append(""+pageNo+""); + xml.append(""+pageSize+""); + xml.append("0"); + xml.append("1"); + xml.append(""); + xml.append("n"); + xml.append("n"); + xml.append(""); + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + //dataType:1--创建,2--提交 + public String getBillPostData(SupplierOrderHeader header, String dataType) { + //获取申请人相关信息 + SysEmp sysEmp = sysEmpMapper.selectByUserId(header.getApplyMan()); + + //获取申请单的明细行 + List detail = supplierOrderMapper.selectByOrderNo(header.getBillId()); + + //获取多成本中心 + String dcbzx = ""; + for (SupplierOrder supplierOrder : detail) { + if(!dcbzx.contains("-"+supplierOrder.getCostCenter()+"-")){ + dcbzx += "-"+supplierOrder.getCostCenter()+"-" + ","; + } + } + if(!dcbzx.equals("")) { + dcbzx = dcbzx.substring(0, dcbzx.length() - 1).replace("-",""); + } + + //获取附件信息 + List fileList = fileMapper.selectByPid(header.getBillId()); + String fileUrlStr = ""; + String fileTypeStr = ""; + for (File file : fileList ) { + fileUrlStr += file.getUri() + "|"; + fileTypeStr += "https:" + file.getUri().substring(file.getUri().lastIndexOf("/")+1) + "|"; + } + if(!fileUrlStr.equals("")) { + fileUrlStr = fileUrlStr.substring(0, fileUrlStr.length() - 1); + fileTypeStr = fileTypeStr.substring(0, fileTypeStr.length() - 1); + } + + String businessType = header.getBusinessType(); + + StrBuilder xml = new StrBuilder(); + + xml.append(""); + xml.append(""); + xml.append(""); + + if(dataType.equals("1")){//创建流程 + xml.append(""); + }else{//提交流程 + xml.append(""); + } + + xml.append(""); + + // + xml.append(""); + xml.append(""+header.getExt01()+""); + xml.append(""); + // + xml.append(""+header.getApplyMan()+""); + + if(dataType.equals("2")){//提交流程 + // + xml.append(""+header.getBillNumber()+""); + } + + // + xml.append("0"); + // + xml.append(""+header.getBillName()+""); + + if(businessType.contains("普通")){ + + // + xml.append(""); + xml.append(""); + // + xml.append(""); + + // + xml.append(""); + + //标题title + xml.append(""); + // + xml.append("title"); + // + xml.append(""+header.getBillName()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + + //标题特殊备注beizhu + xml.append(""); + xml.append("beizhu"); + xml.append(""+getStr(header.getBillNameRemark())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //申请人shenqingren + xml.append(""); + xml.append("shenqingren"); + xml.append(""+header.getApplyMan()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //工号workcode + xml.append(""); + xml.append("workcode"); + xml.append(""+sysEmp.getWorkCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //职级zhiji + xml.append(""); + xml.append("zhiji"); + xml.append(""+sysEmp.getJobLevel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //分部fb + xml.append(""); + xml.append("fb"); + xml.append(""+sysEmp.getSubCompanyId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属行业sshy + xml.append(""); + xml.append("sshy"); + xml.append(""+sysEmp.getSubDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //部门bumen + xml.append(""); + xml.append("bumen"); + xml.append(""+sysEmp.getDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //援引相关合同流程xglc + String xglc = header.getContract(); + if(StringUtil.isNotEmpty(header.getInternal())){ + xglc += ","+header.getInternal(); + } + xml.append(""); + xml.append("xglc"); + xml.append(""+xglc+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属公司company + xml.append(""); + xml.append("company"); + xml.append(""+header.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //已完全匹配ywqpp 0--是,1--否 + /*xml.append(""); + xml.append("ywqpp"); + xml.append(""+header.getIsMatch()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //是否收票sffp 0--是,1--否 + /*xml.append(""); + xml.append("sffp"); + xml.append(""+(header.getIsCollect().equals("1") ? "1" : "0")+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + + //币种bizhong + xml.append(""); + xml.append("bizhong"); + xml.append(""+header.getCurrency()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //供应商名称fkgongyingsh + xml.append(""); + xml.append("fkgongyingsh"); + xml.append(""+header.getSupplierCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //开户行分行khhfh + xml.append(""); + xml.append("khhfh"); + xml.append(""+header.getBranchBank()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //账号信息zhxx + xml.append(""); + xml.append("zhxx"); + xml.append(""+header.getAccountInfo()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //付款类型 fklx2 + xml.append(""); + xml.append("fklx2"); + xml.append(""+header.getPayType()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //约定/计划付款时间jhfjdate + xml.append(""); + xml.append("jhfjdate"); + xml.append(""+header.getPayDate()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票类型fplx 0-先票 1-后票 + xml.append(""); + xml.append("fplx"); + xml.append(""+header.getInvoiceTypeId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //付款金额合计new fkjine151028 + xml.append(""); + xml.append("fkjine151028"); + xml.append(""+header.getPayAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //附件 + xml.append(""); + xml.append("fujian"); + xml.append(""+fileTypeStr+""); + xml.append(""+fileUrlStr+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //流程相关抄送人lcxgcsr + xml.append(""); + xml.append("lcxgcsr"); + xml.append(""+header.getStakeholder()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //多成本中心dcbzx + /*xml.append(""); + xml.append("dcbzx"); + xml.append(""+dcbzx+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //店铺支付宝账户dpzfbzh + xml.append(""); + xml.append("dpzfbzh"); + xml.append(""+getStr(header.getAlipay())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //活动开始时间hdkassj + xml.append(""); + xml.append("hdkassj"); + xml.append(""+getStr(header.getActivityStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //活动结束时间hdjssj + xml.append(""); + xml.append("hdjssj"); + xml.append(""+getStr(header.getActivityEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结开始时间bzjdjkssj + xml.append(""); + xml.append("bzjdjkssj"); + xml.append(""+getStr(header.getFreezeStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结技术时间bzjdjjssj + xml.append(""); + xml.append("bzjdjjssj"); + xml.append(""+getStr(header.getFreezeEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为数字营销sfwdm 0-是 1-否 + xml.append(""); + xml.append("sfwdm"); + xml.append(""+header.getIsDigitalMarket()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为内部员工工资付款sfgzfk 0-是 1-否 + xml.append(""); + xml.append("sfgzfk"); + xml.append(""+header.getIsInnerPay()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为境内(不包括港澳台地区)公司对境外公司(包括港澳台地区)的付款jndjwfk 0-是 1-否 + xml.append(""); + xml.append("jndjwfk"); + xml.append(""+header.getIsAbroadPay()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //是否为充值类sfczl 0-是 1-否 + xml.append(""); + xml.append("sfczl"); + xml.append(""+header.getIsRecharge()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否形式发票sfxsfp + xml.append(""); + xml.append("sfxsfp"); + xml.append(""+header.getIsProforma()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //纸质发票 zzfp 0是1否 ---是否收票 + xml.append(""); + xml.append("zzfp"); + xml.append(""+header.getIsCollect()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + + // + xml.append(""); + + //根据配置得到明细是dt几,需要增加-1个空的dt + int num = 1; + SysConfig sysConfig = sysConfigMapper.selectByCode("WORKFLOW_DETAIL_NUM"); + if(sysConfig != null && StringUtil.isNotEmpty(sysConfig.getValue())){ + num = Integer.parseInt(sysConfig.getValue()); + } + for(int i = 0; i< num-1; i++){ + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + } + + xml.append(""); + xml.append(""); + + //循环明细detail + for (SupplierOrder order : detail) { + //非先票,只要明细信息 + if(!header.getInvoiceType().equals("先票")){ + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje + xml.append(""); + xml.append("fkje"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())){ + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属公司gs + xml.append(""); + xml.append("gs"); + xml.append(""+order.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为员工工资付款sfgzfkmx 0-是 1-否 + xml.append(""); + xml.append("sfgzfkmx"); + xml.append(""+header.getIsInnerPay()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(header.getIsRecharge().equals("0")){ + //平台pt + xml.append(""); + xml.append("pt"); + xml.append(""+order.getPlatForm()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道czqd + xml.append(""); + xml.append("czqd"); + xml.append(""+order.getChargeChannel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道备注 + xml.append(""); + xml.append("qdbz"); + xml.append(""+order.getChannelRemark()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //如果包含 形式发票,则增加几个字段 2023/6/13 + if(header.getInvoiceType().contains("形式发票")){ + log.info("=======形式发票=======start"); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append("0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append("CN_VAT_IN_0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + + log.info("=======形式发票=======end"); + } + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + }else{//先票 + //得到匹配记录 + List matchList = supplierOrderItemMatchingMapper.selectListByOrderId(order.getId()); + for (SupplierOrderItemMatching matching : matchList) { + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje == 匹配的金额 + xml.append(""); + xml.append("fkje"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属公司gs + xml.append(""); + xml.append("gs"); + xml.append(""+order.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为员工工资付款sfgzfkmx 0-是 1-否 + xml.append(""); + xml.append("sfgzfkmx"); + xml.append(""+header.getIsInnerPay()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(header.getIsRecharge().equals("0")){ + //平台pt + xml.append(""); + xml.append("pt"); + xml.append(""+order.getPlatForm()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道czqd + xml.append(""); + xml.append("czqd"); + xml.append(""+order.getChargeChannel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道备注 + xml.append(""); + xml.append("qdbz"); + xml.append(""+order.getChannelRemark()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //匹配记录的数据 + //发票代码fpdmnew + xml.append(""); + xml.append("fpdmnew"); + xml.append(""+matching.getCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票号码fphmnew + xml.append(""); + xml.append("fphmnew"); + xml.append(""+matching.getNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票税率fpslnew + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(matching.getTaxRate()); + xml.append(""); + xml.append("fpslnew"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票图片fptpnew + String imgUrl = matching.getImgUrl(); + String imgType = "https:"+imgUrl.substring(imgUrl.lastIndexOf("/")+1); + xml.append(""); + xml.append("fptpnew"); + xml.append(""+imgType+""); + xml.append(""+imgUrl+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票Id + xml.append(""); + xml.append("fpidnew"); + xml.append(""+matching.getInvoiceId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+(matching.getTotal().subtract(matching.getTax()).toString())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append(""+matching.getTax()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + } + } + } + + xml.append(""); + xml.append(""); + xml.append(""); + } + + if(businessType.contains("采购付款")){ + //得到采购合同信息 + InvokePurchase purchase = invokePurchaseMapper.selectByRequestId(header.getPurchase()); + + // + xml.append(""); + xml.append(""); + // + xml.append(""); + + // + xml.append(""); + + //标题title + xml.append(""); + // + xml.append("title"); + // + xml.append(""+header.getBillName()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + + //标题特殊备注beizhu + xml.append(""); + xml.append("beizhu"); + xml.append(""+getStr(header.getBillNameRemark())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //申请人shenqingren + xml.append(""); + xml.append("shenqingren"); + xml.append(""+header.getApplyMan()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //工号workcode + xml.append(""); + xml.append("workcode"); + xml.append(""+sysEmp.getWorkCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //职级zhiji + xml.append(""); + xml.append("zhiji"); + xml.append(""+sysEmp.getJobLevel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //分部fb + xml.append(""); + xml.append("fb"); + xml.append(""+sysEmp.getSubCompanyId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属行业sshy + xml.append(""); + xml.append("sshy"); + xml.append(""+sysEmp.getSubDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //部门bumen + xml.append(""); + xml.append("bumen"); + xml.append(""+sysEmp.getDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //援引相关合同流程xglc + xml.append(""); + xml.append("xglc"); + xml.append(""+header.getContract()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属公司company + xml.append(""); + xml.append("company"); + xml.append(""+header.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //币种bizhong + xml.append(""); + xml.append("bizhong"); + xml.append(""+header.getCurrency()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //供应商名称fkgongyingsh + xml.append(""); + xml.append("fkgongyingsh"); + xml.append(""+header.getSupplierCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //开户行分行khhfh + xml.append(""); + xml.append("khhfh"); + xml.append(""+header.getBranchBank()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //账号信息zhxx + xml.append(""); + xml.append("zhxx"); + xml.append(""+header.getAccountInfo()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //约定/计划付款时间jhfjdate + xml.append(""); + xml.append("jhfjdate"); + xml.append(""+header.getPayDate()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型fplx 0-先票 1-后票 + xml.append(""); + xml.append("fplx"); + xml.append(""+header.getInvoiceTypeId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //付款金额合计new fkjine151028 + xml.append(""); + xml.append("fkjine151028"); + xml.append(""+header.getPayAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //附件 + xml.append(""); + xml.append("fujian"); + xml.append(""+fileTypeStr+""); + xml.append(""+fileUrlStr+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //抄送干系人csgxr + xml.append(""); + xml.append("csgxr"); + xml.append(""+header.getStakeholder()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //活动开始时间hdkassj + xml.append(""); + xml.append("hdkassj"); + xml.append(""+getStr(header.getActivityStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //活动结束时间hdjssj + xml.append(""); + xml.append("hdjssj"); + xml.append(""+getStr(header.getActivityEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结开始时间bzjdjkssj + xml.append(""); + xml.append("bzjdjkssj"); + xml.append(""+getStr(header.getFreezeStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结技术时间bzjdjjssj + xml.append(""); + xml.append("bzjdjjssj"); + xml.append(""+getStr(header.getFreezeEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //是否为充值类sfczl 0-是 1-否 + xml.append(""); + xml.append("sfczl"); + xml.append(""+header.getIsRecharge()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否形式发票sfxsfp + xml.append(""); + xml.append("sfxsfp"); + xml.append(""+header.getIsProforma()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotEmpty(purchase.getContract())){ + //源引相关合同流程yyxght + xml.append(""); + xml.append("yyxght"); + xml.append(""+purchase.getContract()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //付款类型2 fklx2 + xml.append(""); + xml.append("fklx2"); + xml.append(""+header.getPayType()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //多成本中心dcbzx + xml.append(""); + xml.append("dcbzx"); + xml.append(""+dcbzx+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心(主)cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+header.getOrgCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotEmpty(header.getOrgCode())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(header.getOrgCode()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+header.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+header.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + if(StringUtil.isNotEmpty(purchase.getNonPurchase())){ + //源引非经营性采购流程yyfjyxcg + xml.append(""); + xml.append("yyfjyxcg"); + xml.append(""+purchase.getNonPurchase()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + if(StringUtil.isNotEmpty(purchase.getNonPurchaseNumber())){ + //非经营性采购流程编号fjyxcglcbh + xml.append(""); + xml.append("fjyxcglcbh"); + xml.append(""+purchase.getNonPurchaseNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + //合同流程中对方签约公司名称htlczxzgsmc + xml.append(""); + xml.append("htlczxzgsmc"); + xml.append(""+getStr(purchase.getOtherSignCompany())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //合同开始日期htksrq + xml.append(""); + xml.append("htksrq"); + xml.append(""+purchase.getContractStartTime()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //合同结束日期htjsrq + xml.append(""); + xml.append("htjsrq"); + xml.append(""+purchase.getContractEndTime()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //合同中财务结算条款htzcwjstk + xml.append(""); + xml.append("htzcwjstk"); + xml.append(""+purchase.getFinanceTerms()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //源引收货/验收流程yyshyc + xml.append(""); + xml.append("yyshyc"); + xml.append(""+header.getReceived()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //源引采购下单流程yycgxd + xml.append(""); + xml.append("yycgxd"); + xml.append(""+purchase.getExt01()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //是否修改明细行成本中心sfxgmxhcbzx 0-是 1-否 + xml.append(""); + xml.append("sfxgmxhcbzx"); + xml.append(""+header.getExt03()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //纸质发票 zzfp 0是1否 ---是否收票 + xml.append(""); + xml.append("zzfp"); + xml.append(""+header.getIsCollect()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //采购下单流程编号cgxdlcbh + xml.append(""); + xml.append("cgxdlcbh"); + xml.append(""+purchase.getPurchaseNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotEmpty(purchase.getContractNumber())){ + //相关合同流程编号xghtlcbh + xml.append(""); + xml.append("xghtlcbh"); + xml.append(""+purchase.getContractNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + /*//采购部上级审批人(实习生专用)cgbsj1 + xml.append(""); + xml.append("cgbsj1"); + xml.append(""+(StringUtil.isNotEmpty(purchase.getHighApprover()) ? purchase.getHighApprover() : "")+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + + // + xml.append(""); + + //根据配置得到明细是dt几,需要增加-1个空的dt + int num = 1; + SysConfig sysConfig = sysConfigMapper.selectByCode("WORKFLOW_DETAIL_NUM"); + if(sysConfig != null && StringUtil.isNotEmpty(sysConfig.getValue())){ + num = Integer.parseInt(sysConfig.getValue()); + } + for(int i = 0; i< num-1; i++){ + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + } + + xml.append(""); + xml.append(""); + + //循环明细detail + for (SupplierOrder order : detail) { + //非先票,只要明细信息 + if(!header.getInvoiceType().equals("先票")){ + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje + xml.append(""); + xml.append("fkje"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //如果包含 形式发票,则增加几个字段 2023/6/13 + if(header.getInvoiceType().contains("形式发票")){ + log.info("=======形式发票=======start"); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append("0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append("CN_VAT_IN_0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + + log.info("=======形式发票=======end"); + } + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + }else{//先票 + //得到匹配记录 + List matchList = supplierOrderItemMatchingMapper.selectListByOrderId(order.getId()); + for (SupplierOrderItemMatching matching : matchList) { + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje == 匹配金额 + xml.append(""); + xml.append("fkje"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //匹配记录的数据 + //发票代码fpdmnew + xml.append(""); + xml.append("fpdmnew"); + xml.append(""+matching.getCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票号码fphmnew + xml.append(""); + xml.append("fphmnew"); + xml.append(""+matching.getNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票税率fpslnew + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(matching.getTaxRate()); + xml.append(""); + xml.append("fpslnew"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票图片fptpnew + String imgUrl = matching.getImgUrl(); + String imgType = "https:"+imgUrl.substring(imgUrl.lastIndexOf("/")+1); + xml.append(""); + xml.append("fptpnew"); + xml.append(""+imgType+""); + xml.append(""+imgUrl+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票Id + xml.append(""); + xml.append("fpidnew"); + xml.append(""+matching.getInvoiceId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+(matching.getTotal().subtract(matching.getTax()).toString())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append(""+matching.getTax()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + } + } + } + + xml.append(""); + xml.append(""); + xml.append(""); + } + + if(businessType.contains("品牌服务")){ + InvokeBrand brand = invokeBrandMapper.selectByRequestId(header.getBrand()); + + // + xml.append(""); + xml.append(""); + // + xml.append(""); + + // + xml.append(""); + + //标题title + xml.append(""); + // + xml.append("title"); + // + xml.append(""+header.getBillName()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + + //标题特殊备注beizhu + xml.append(""); + xml.append("beizhu"); + xml.append(""+getStr(header.getBillNameRemark())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //申请人shenqingren + xml.append(""); + xml.append("shenqingren"); + xml.append(""+header.getApplyMan()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //工号workcode + xml.append(""); + xml.append("workcode"); + xml.append(""+sysEmp.getWorkCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //职级zhiji + xml.append(""); + xml.append("zhiji"); + xml.append(""+sysEmp.getJobLevel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //分部fb + xml.append(""); + xml.append("fb"); + xml.append(""+sysEmp.getSubCompanyId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //所属行业sshy + xml.append(""); + xml.append("sshy"); + xml.append(""+sysEmp.getSubDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //部门bumen + xml.append(""); + xml.append("bumen"); + xml.append(""+sysEmp.getDepartmaentId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //相关合同流程xghtlc + xml.append(""); + xml.append("xghtlc"); + xml.append(""+header.getContract()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //所属公司company + xml.append(""); + xml.append("company"); + xml.append(""+header.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //币种bizhong + xml.append(""); + xml.append("bizhong"); + xml.append(""+header.getCurrency()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //供应商名称fkgongyingsh + xml.append(""); + xml.append("fkgongyingsh"); + xml.append(""+header.getSupplierCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //开户行分行khhfh + xml.append(""); + xml.append("khhfh"); + xml.append(""+header.getBranchBank()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //账号信息zhxx + xml.append(""); + xml.append("zhxx"); + xml.append(""+header.getAccountInfo()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //付款类型2 fklx2 + xml.append(""); + xml.append("fklx2"); + xml.append(""+header.getPayType()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //约定/计划付款时间jhfjdate + xml.append(""); + xml.append("jhfjdate"); + xml.append(""+header.getPayDate()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型fplx 0-先票 1-后票 + xml.append(""); + xml.append("fplx"); + xml.append(""+header.getInvoiceTypeId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //付款金额合计new fkjine151028 + xml.append(""); + xml.append("fkjine151028"); + xml.append(""+header.getPayAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //附件 + xml.append(""); + xml.append("fujian"); + xml.append(""+fileTypeStr+""); + xml.append(""+fileUrlStr+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //流程相关抄送人lcxgcsr + xml.append(""); + xml.append("lcxgcsr"); + xml.append(""+header.getStakeholder()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //店铺支付宝账户dpzfbzh + xml.append(""); + xml.append("dpzfbzh"); + xml.append(""+getStr(header.getAlipay())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //活动开始时间hdkassj + xml.append(""); + xml.append("hdkassj"); + xml.append(""+getStr(header.getActivityStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //活动结束时间hdjssj + xml.append(""); + xml.append("hdjssj"); + xml.append(""+getStr(header.getActivityEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结开始时间bzjdjkssj + xml.append(""); + xml.append("bzjdjkssj"); + xml.append(""+getStr(header.getFreezeStartTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //保证金冻结技术时间bzjdjjssj + xml.append(""); + xml.append("bzjdjjssj"); + xml.append(""+getStr(header.getFreezeEndTime())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为数字营销sfwdm 0-是 1-否 + xml.append(""); + xml.append("sfwdm"); + xml.append(""+(header.getIsDigitalMarket().equals("是") ? "0" : "1")+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为充值类sfczl 0-是 1-否 + xml.append(""); + xml.append("sfczl"); + xml.append(""+header.getIsRecharge()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否形式发票sfxsfp + xml.append(""); + xml.append("sfxsfp"); + xml.append(""+header.getIsProforma()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //多成本中心dcbzx + xml.append(""); + xml.append("dcbzx"); + xml.append(""+dcbzx+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotBlank(header.getHavContract())){ + //是否有相关合同流程sfyvht 0-是 1-否 + xml.append(""); + xml.append("sfyvht"); + xml.append(""+header.getHavContract()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + if(StringUtil.isNotBlank(header.getHavInvoice())){ + //是否有发票照片sfyfp 0-是 1-否 + xml.append(""); + xml.append("sfyfp"); + xml.append(""+header.getHavInvoice()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //Kol名字kolmz + xml.append(""); + xml.append("kolmz"); + xml.append(""+getStr(header.getKolName())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotBlank(header.getSupplierType())){ + //供应商类型gyslx + xml.append(""); + xml.append("gyslx"); + xml.append(""+header.getSupplierType()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //姓名kolxm + xml.append(""); + xml.append("kolxm"); + xml.append(""+getStr(header.getKolFullName())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //身份证号码sfzhm + xml.append(""); + xml.append("sfzhm"); + xml.append(""+getStr(header.getUid())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(StringUtil.isNotBlank(header.getIsWhiteList())){ + //是否白名单sfbmd 0-是 1-否 + xml.append(""); + xml.append("sfbmd"); + xml.append(""+header.getIsWhiteList()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //其他公司qtgs + xml.append(""); + xml.append("qtgs"); + xml.append(""+getStr(header.getOtherCompany())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //供应商银行账号gyszh + xml.append(""); + xml.append("gyszh"); + xml.append(""+header.getAccountInfo()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //主流程编号zlcbh + xml.append(""); + xml.append("zlcbh"); + xml.append(""+brand.getMainProcessNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //付款类型1 jslx + xml.append(""); + xml.append("jslx"); + xml.append(""+brand.getPayTypeId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //主流程(品牌/市场)zlc + xml.append(""); + xml.append("zlc"); + xml.append(""+header.getBrand()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //纸质发票 zzfp 0是1否 ---是否收票 + xml.append(""); + xml.append("zzfp"); + xml.append(""+header.getIsCollect()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //白名单公司bmdgs + xml.append(""); + xml.append("bmdgs"); + xml.append(""+header.getWhiteCompany()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + + xml.append(""); + xml.append(""); + xml.append(""); + + // + xml.append(""); + + //根据配置得到明细是dt几,需要增加-1个空的dt + int num = 1; + SysConfig sysConfig = sysConfigMapper.selectByCode("WORKFLOW_DETAIL_NUM"); + if(sysConfig != null && StringUtil.isNotEmpty(sysConfig.getValue())){ + num = Integer.parseInt(sysConfig.getValue()); + } + for(int i = 0; i< num-1; i++){ + xml.append(""); + xml.append(""); + xml.append(""); + xml.append(""); + } + + xml.append(""); + xml.append(""); + + //循环明细detail + for (SupplierOrder order : detail) { + //非先票,只要明细信息 + if(!header.getInvoiceType().equals("先票")){ + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje + xml.append(""); + xml.append("fkje"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(header.getIsRecharge().equals("0")){ + //平台pt + xml.append(""); + xml.append("pt"); + xml.append(""+order.getPlatForm()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道czqd + xml.append(""); + xml.append("czqd"); + xml.append(""+order.getChargeChannel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道备注 + xml.append(""); + xml.append("qdbz"); + xml.append(""+order.getChannelRemark()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //所属公司gs + xml.append(""); + xml.append("gs"); + xml.append(""+order.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //如果包含 形式发票,则增加几个字段 2023/6/13 + if(header.getInvoiceType().contains("形式发票")){ + log.info("=======形式发票=======start"); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append("0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+order.getAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append("CN_VAT_IN_0"); + xml.append("true"); + xml.append("true"); + xml.append(""); + + log.info("=======形式发票=======end"); + } + + //向品牌收取的金额(没有填0)xppsqje + xml.append(""); + xml.append("xppsqje"); + xml.append(""+order.getCollectAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + }else{//先票 + //得到匹配记录 + List matchList = supplierOrderItemMatchingMapper.selectListByOrderId(order.getId()); + for (SupplierOrderItemMatching matching : matchList) { + xml.append(""); + xml.append("1"); + + xml.append(""); + + //Line编码 mxid + xml.append(""); + // + xml.append("mxid"); + // + xml.append(""+order.getId().toString()+""); + // + xml.append("true"); + // + xml.append("true"); + xml.append(""); + //发生日期fyfsrquser + xml.append(""); + xml.append("fyfsrquser"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //预算日期fsrq + xml.append(""); + xml.append("fsrq"); + xml.append(""+DateFormat.format(order.getReceiveTime(),DateFormat.DatePatternType.FORMAT_yyyy_MM_dd)+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //费用类型fylx + xml.append(""); + xml.append("fylx"); + xml.append(""+order.getGoods()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //是否为劳务费sfwlwf + xml.append(""); + xml.append("sfwlwf"); + xml.append(""+order.getIsServiceFee()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //CODE + /*xml.append(""); + xml.append("code"); + xml.append(""+order.getCodeId()+""); + xml.append("true"); + xml.append("true"); + xml.append("");*/ + //付款金额fkje == 匹配金额 + xml.append(""); + xml.append("fkje"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //成本中心5 cbzx + xml.append(""); + xml.append("cbzx"); + xml.append(""+order.getCostCenter()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + if(StringUtil.isNotEmpty(order.getCostCenter())) { + SysOrg sysOrg = sysOrgMapper.selectByCostcenter(order.getCostCenter()); + if(sysOrg != null){ + if(sysOrg.getType().equals("TIC")){ + //GS项目批号xiangmupihao + xml.append(""); + xml.append("xiangmupihao"); + xml.append(""+order.getGsNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + }else{ + //OA通用项目批号xiangmupihao1 + xml.append(""); + xml.append("xiangmupihao1"); + xml.append(""+order.getOaNum()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + } + } + + //付款原由备注fkyybz + xml.append(""); + xml.append("fkyybz"); + xml.append(""+order.getDescription()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + if(header.getIsRecharge().equals("0")){ + //平台pt + xml.append(""); + xml.append("pt"); + xml.append(""+order.getPlatForm()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道czqd + xml.append(""); + xml.append("czqd"); + xml.append(""+order.getChargeChannel()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //渠道备注 + xml.append(""); + xml.append("qdbz"); + xml.append(""+order.getChannelRemark()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + } + + //所属公司gs + xml.append(""); + xml.append("gs"); + xml.append(""+order.getCompanyCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //匹配记录的数据 + //发票代码fpdmnew + xml.append(""); + xml.append("fpdmnew"); + xml.append(""+matching.getCode()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票号码fphmnew + xml.append(""); + xml.append("fphmnew"); + xml.append(""+matching.getNumber()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票税率fpslnew + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(matching.getTaxRate()); + xml.append(""); + xml.append("fpslnew"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税分类sfl + xml.append(""); + xml.append("sfl"); + xml.append(""+(taxMapping == null ? "" : taxMapping.getCode())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票图片fptpnew + String imgUrl = matching.getImgUrl(); + String imgType = "https:"+imgUrl.substring(imgUrl.lastIndexOf("/")+1); + xml.append(""); + xml.append("fptpnew"); + xml.append(""+imgType+""); + xml.append(""+imgUrl+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //发票Id + xml.append(""); + xml.append("fpidnew"); + xml.append(""+matching.getInvoiceId()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //含税金额hsjenew + xml.append(""); + xml.append("hsjenew"); + xml.append(""+matching.getTotal()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //不含税金额bhsjenew + xml.append(""); + xml.append("bhsjenew"); + xml.append(""+(matching.getTotal().subtract(matching.getTax()).toString())+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + //税额senew + xml.append(""); + xml.append("senew"); + xml.append(""+matching.getTax()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //向品牌收取的金额(没有填0)xppsqje + xml.append(""); + xml.append("xppsqje"); + xml.append(""+order.getCollectAmount()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + //发票类型控制fplxkz + xml.append(""); + xml.append("fplxkz"); + xml.append(""+header.getInvoiceTypeKZ()+""); + xml.append("true"); + xml.append("true"); + xml.append(""); + + xml.append(""); + xml.append(""); + } + } + } + + xml.append(""); + xml.append(""); + xml.append(""); + } + + xml.append(""); + + if(dataType.equals("1")){//创建流程 + // + xml.append(""+header.getApplyMan()+""); + xml.append(""); + }else{//提交流程 + // + xml.append(""+header.getBillNumber()+""); + xml.append(""+header.getApplyMan()+""); + xml.append("submit"); + xml.append(""); + xml.append(""); + } + + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + public String getMatchBillPostData(SupplierOrderHeader header) { + StrBuilder xml = new StrBuilder(); + + xml.append(""); + xml.append(""); + xml.append(""); + + xml.append(""); + + xml.append(""); + + // + xml.append(""); + xml.append(""+header.getExt01()+""); + xml.append(""); + // + xml.append(""+header.getApplyMan()+""); + + // + xml.append(""+header.getBillNumber()+""); + + // + xml.append("0"); + // + xml.append(""+header.getBillName()+""); + xml.append(""); + + // + xml.append(""+header.getBillNumber()+""); + xml.append(""+header.getApplyMan()+""); + xml.append("submit"); + xml.append(""); + xml.append(""); + + xml.append(""); + xml.append(""); + + return xml.toString(); + } + + public String getMatchItemPostData(SupplierOrderHeader supplierOrderHeader, SupplierOrderItemMatching supplierOrderItemMatching) { + SupplierOrder supplierOrder = supplierOrderMapper.selectByPrimaryKey(supplierOrderItemMatching.getOrderId()); + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByPrimaryKey(supplierOrderItemMatching.getInvoiceId()); + TaxMapping taxMapping = taxMappingMapper.selectByTaxRate(supplierOrderItemMatching.getTaxRate()); + + //获取附件信息 + List fileList = fileMapper.selectByPid(supplierOrderHeader.getBillId()); + String fileUrlStr = ""; + //String fileTypeStr = ""; + for (File file : fileList ) { + fileUrlStr += file.getUri() + "|"; + //fileTypeStr += "https:" + file.getUri().substring(file.getUri().lastIndexOf("/")+1) + "|"; + } + if(!fileUrlStr.equals("")) { + fileUrlStr = fileUrlStr.substring(0, fileUrlStr.length() - 1); + //fileTypeStr = fileTypeStr.substring(0, fileTypeStr.length() - 1); + } + + + //明细ID + String mainId = supplierOrder.getId().toString(); + //OCR ID + String ocrid = supplierOrderItemMatching.getId().toString(); + //发票ID + String fpid = corporateInvoice.getId(); + //发票号码 + String fphm = corporateInvoice.getNumber(); + //发票代码 + String fpdm = corporateInvoice.getCode(); + //金额 + String je = supplierOrderItemMatching.getTotal().toString(); + //发票税率 + String sl = taxMapping == null ? "" : taxMapping.getCode(); + //发票税额 + String s = supplierOrderItemMatching.getTax().toString(); + // 20220905添加含税金额 + BigDecimal totalMoney = new BigDecimal(je).add(new BigDecimal(s)); + + //Requestid==创建合同OA返回的 + String requestid = supplierOrderHeader.getBillNumber(); + //付款单申请人 + String czr = supplierOrderHeader.getApplyMan(); + //workflowId + String workflowId = supplierOrderHeader.getExt01(); + + SupplierOutServiceImpl.BaoZunSubmitWorkFlow2 baoZunSubmitWorkFlow = new SupplierOutServiceImpl.BaoZunSubmitWorkFlow2(); + baoZunSubmitWorkFlow.setRequestid(requestid); + baoZunSubmitWorkFlow.setWorkflow(workflowId); + baoZunSubmitWorkFlow.setUserid(czr); + baoZunSubmitWorkFlow.setZzfp(supplierOrderHeader.getIsCollect()); + // 20220711计算比率100%为0 + BigDecimal percent = corporateInvoiceMapper.calculateMatchingPercent(corporateInvoice.getPriceType(), corporateInvoice.getId()); + corporateInvoice.setPercent(percent.setScale(0, BigDecimal.ROUND_HALF_UP).intValue()); + baoZunSubmitWorkFlow.setFpsfyfkjeyy("1"); + /*if(corporateInvoice.getPercent()==100){ + baoZunSubmitWorkFlow.setFpsfyfkjeyy("0"); + }*/ + if(supplierOrder.getExt05().equals("0")){ + baoZunSubmitWorkFlow.setFpsfyfkjeyy("0"); + } + + baoZunSubmitWorkFlow.setFujian(fileUrlStr); + + SupplierOutServiceImpl.BaoZunSubmitWorkFlowDetail2 detail = new SupplierOutServiceImpl.BaoZunSubmitWorkFlowDetail2(); + detail.setMxid(mainId); + detail.setFpid(fpid); + detail.setFphm(fphm); + detail.setFpdm(fpdm); + detail.setJe(supplierOrderItemMatching.getTotal().subtract(supplierOrderItemMatching.getTax()).toString()); + detail.setFptp(supplierOrderItemMatching.getImgUrl()); + detail.setFylx(supplierOrder.getGoods()); + detail.setFkje1(je); + detail.setCbzx(supplierOrder.getCostCenter()); + detail.setXiangmupihao(supplierOrder.getGsNum()); + detail.setXiangmupihao1(supplierOrder.getOaNum()); + detail.setFphsje(je); + detail.setFpsekdk(s); + detail.setSfl(sl); + detail.setFkyybz(supplierOrder.getDescription()); + detail.setOcrid(ocrid); + + List list = new ArrayList<>(); + list.add(detail); + + baoZunSubmitWorkFlow.setDetail(list); + + return JsonUtil.toString(baoZunSubmitWorkFlow); + } + + public String getHeaderPostData(SupplierOrderHeader supplierOrderHeader, SupplierOrder supplierOrder) { + + //Requestid==创建合同OA返回的 + String requestid = supplierOrderHeader.getBillNumber(); + //付款单申请人 + String czr = supplierOrderHeader.getApplyMan(); + //workflowId + String workflowId = supplierOrderHeader.getExt01(); + + SupplierOutServiceImpl.BaoZunSubmitWorkFlow3 baoZunSubmitWorkFlow = new SupplierOutServiceImpl.BaoZunSubmitWorkFlow3(); + baoZunSubmitWorkFlow.setRequestid(requestid); + baoZunSubmitWorkFlow.setWorkflow(workflowId); + baoZunSubmitWorkFlow.setUserid(czr); + baoZunSubmitWorkFlow.setZzfp(supplierOrderHeader.getIsCollect()); + baoZunSubmitWorkFlow.setFpsfyfkjeyy("1"); + + if(supplierOrder.getExt05().equals("0")){ + baoZunSubmitWorkFlow.setFpsfyfkjeyy("0"); + } + + //获取附件信息 + List fileList = fileMapper.selectByPid(supplierOrderHeader.getBillId()); + String fileUrlStr = ""; + //String fileTypeStr = ""; + for (File file : fileList ) { + fileUrlStr += file.getUri() + "|"; + //fileTypeStr += "https:" + file.getUri().substring(file.getUri().lastIndexOf("/")+1) + "|"; + } + if(!fileUrlStr.equals("")) { + fileUrlStr = fileUrlStr.substring(0, fileUrlStr.length() - 1); + //fileTypeStr = fileTypeStr.substring(0, fileTypeStr.length() - 1); + } + baoZunSubmitWorkFlow.setFujian(fileUrlStr); + + //明细ID + String mainId = supplierOrder.getId().toString(); + //金额 + String je = supplierOrder.getAmount().toString(); + + SupplierOutServiceImpl.BaoZunSubmitWorkFlowDetail3 detail = new SupplierOutServiceImpl.BaoZunSubmitWorkFlowDetail3(); + detail.setMxid(mainId); + detail.setFpid(""); + detail.setFphm(""); + detail.setFpdm(""); + detail.setJe(je); + detail.setFptp(""); + detail.setFylx(supplierOrder.getGoods()); + detail.setFkje1(je); + detail.setCbzx(supplierOrder.getCostCenter()); + detail.setXiangmupihao(supplierOrder.getGsNum()); + detail.setXiangmupihao1(supplierOrder.getOaNum()); + detail.setFphsje(je); + detail.setFpsekdk("0"); + detail.setSfl("CN_VAT_IN_0"); + detail.setFkyybz(supplierOrder.getDescription()); + detail.setOcrid(""); + + List list = new ArrayList<>(); + list.add(detail); + + baoZunSubmitWorkFlow.setDetail(list); + + return JsonUtil.toString(baoZunSubmitWorkFlow); + } + + public String getCreateBillFailMess(String failStr){ + switch (failStr) { + case "-1": + return "创建流程失败"; + case "-2": + return "没有创建权限"; + case "-3": + return "创建流程失败"; + case "-4": + return "字段或表名不正确"; + case "-5": + return "更新流程级别失败"; + case "-6": + return "无法创建流程待办任务"; + case "-7": + return "流程下一节点出错,请检查流程的配置,在OA中发起流程进行测试"; + case "-8": + return "流程节点自动赋值操作错误"; + default: + return "未知错误"; + } + } + + public String getStr(String str){ + return (StringUtil.isNotEmpty(str) ? str : ""); + } + + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/service/SapFileWatchService.java b/src/main/java/com/cmsen/ticket/infrastructure/service/SapFileWatchService.java new file mode 100644 index 0000000..b88f847 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/service/SapFileWatchService.java @@ -0,0 +1,820 @@ +package com.cmsen.ticket.infrastructure.service; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.thread.ThreadUtil; +import com.alibaba.fastjson.JSON; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.Base64Util; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StorageCache; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.impl.SysCorInvoiceServiceImpl; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.util.StringUtils; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.File; +import java.math.BigDecimal; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/3/17 9:57 + * @desc 文件监听 + **/ +@Component +@Slf4j +public class SapFileWatchService implements CommandLineRunner { + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Value("${manager-file.viewPath}") + private String viewUri; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; + + @Resource + @Qualifier(value = "ScannerPool") + private Executor scannerPool; + + @Value("${manager-file.watchPath}") + private String watchPath; + + @Resource + private ScannerLogsMapper scannerLogsMapper; + + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @Resource + private SysOrgMapper sysOrgMapper; + + @Value("${spring.application.name}") + private String applicationName; + + @Resource + private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; + + @Resource + private CorpPaymentLineMapper corpPaymentLineMapper; + + @Resource + private CorpInvoiceReceiveHeaderMapper corpInvoiceReceiveHeaderMapper; + + @Resource + private CorpInvoiceReceiveLineMapper corpInvoiceReceiveLineMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Resource + private SysCorInvoiceServiceImpl sysCorInvoiceService; + + + + @Resource + private PostBoxMapper postBoxMapper; + + @Resource + private SupplierMapper supplierMapper; + + + @Resource + private FileMapper fileMapper; + + private final List NOT_INVOICE_TYPES = new ArrayList() {{ + add("10900"); + add("20100"); + add("20105"); + add("10902"); + }}; + + private String reportLast = ""; + private boolean reportFlag = true; + + + @Override + public void run(String... args) { + scannerPool.execute(() -> { + boolean exist = FileUtil.exist(watchPath); + if (!exist) { + log.info("Start Watching Failed >> No Path exist >> {}", watchPath); + return; + } + while (true) { + try { + log.info("Start Watching >> {}", watchPath); + watchSap(); + } catch (Exception e) { + log.error("Start Watching Error >> {} >> {}", watchPath, e.getMessage()); + log.error(e.getMessage(), e); + ThreadUtil.sleep(10000); + } + } + }); + } + + private void watchSap() throws Exception { + WatchService watchService = FileSystems.getDefault().newWatchService(); + Paths.get(watchPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE); + while (true) { + WatchKey key = watchService.poll(10, TimeUnit.SECONDS); + if (key == null) { + continue; + } + for (WatchEvent event : key.pollEvents()) { + WatchEvent.Kind kind = event.kind(); + //监听新建文件 + if (kind == StandardWatchEventKinds.ENTRY_CREATE) { + Path path = (Path) (event.context()); + Path fullPath = Paths.get(watchPath, path.toString()); + String oldPath = fullPath.toString(); + File file = new File(oldPath); + log.info("New File Upload to SAP > {}", oldPath); + if(!file.isDirectory()){ + //scannerPool.execute(() -> dealFile(oldPath)); + dealFile(oldPath); + } + } + log.info("deal file sleep time start:{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); + SysConfig sysConfig = sysConfigMapper.selectByCode("AI_SLEEP_TIME"); + if(null!=sysConfig){ + String con_value = sysConfig.getValue(); + ThreadUtil.sleep(Integer.parseInt(con_value)); + } + } + key.reset(); + } + } + +// @Transactional(rollbackFor = Exception.class) + private void dealFile(String filePath) { + long oldLength; + long newLength; + //判断文件是否写入完成 + int delay = 3000; + int delayLimit = 10; + int countDid = 0; + do { + oldLength = new File(filePath).length(); + log.info("File Uploading1 >> {} : {}", filePath, oldLength); + ThreadUtil.sleep(delay); + newLength = new File(filePath).length(); + log.info("File Uploading2 >> {} : {}", filePath, newLength); + countDid++; + } while ((oldLength != newLength || newLength ==0)&&countDid<=delayLimit); + log.info("File Uploading Success >> {},{}", filePath,newLength); + //开始处理文件 + File file = new File(filePath); + String oldFileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); + String newFileName = "SAP_" + System.currentTimeMillis() + filePath.substring(filePath.lastIndexOf(".")); + String folder = Pdf2JpgHelper.generateFolderNoFileSep(uploadPath); + String newFilePath = uploadPath + folder + File.separator + newFileName; + String viewPath = viewUri + folder + "/" + newFileName; + + //新增属性--用于报销发票 2022/6/2 + String uploadL = StringUtil.UUID(); + String originalFilePath = StringUtils.formatUrl(viewUri + folder + "/" + uploadL + oldFileName, null); + + boolean flag = file.renameTo(new File(newFilePath)); + // 挂载文件复制文件 + if(!flag){ + try { + FileUtils.copyFile(file, new File(newFilePath)); + // 成功后删除 + file.delete(); + flag =true; + }catch (Exception e){ + log.error("copy file error!"); + e.printStackTrace(); + } + } + if (flag) { + log.info("Start Deal File >> {} ", viewPath); + log.info("old fileName >> {} ", oldFileName); + CorporateInvoiceType corporateInvoiceTypeNew = (CorporateInvoiceType) Optional.ofNullable(StorageCache.read("CorType." + oldFileName)).orElse(new CorporateInvoiceType()); + log.info("corporateInvoiceTypeNew >> {} ", JSON.toJSONString(corporateInvoiceTypeNew)); + // 默认以数量比对20220505 +// String invoiceType = "2"; + String invoiceType = corporateInvoiceTypeNew.getId().toString(); + + log.info("invoiceType >> {} ", invoiceType); + if (invoiceType.equals("2")){ + corporateInvoiceTypeNew.setMatchType(1); + } + if (invoiceType.equals("1") || invoiceType.equals("2") || invoiceType.equals("3")) {//供应商发票,对应corporate_invoice + CorporateInvoice corporateInvoice = identifyAndReturnInvoice(viewPath, oldFileName, newFilePath, corporateInvoiceTypeNew); + //如果是抵扣联 不进行识别操作 + if (corporateInvoice == null) { + log.error("Identify File Error"); + } else if (corporateInvoice.getValidStatus().equals((byte) 1)) { + StringBuilder message = new StringBuilder(); + TicketType ticketType = ticketTypeMapper.selectByCode(corporateInvoice.getTicketCode()); + corporateInvoiceService.validationRules(corporateInvoice, message, ticketType); + log.info("规则验真完成,{}",corporateInvoice.getStatus()); + corporateInvoice.setMessage(message.toString()); + if (corporateInvoice.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + log.info("规则验真完成SendType,{}",corporateInvoiceType.getSendType()); + if (corporateInvoiceType != null && corporateInvoiceType.getSendType() == 1) { +// supplierOutService.sendInvoice(corporateInvoice, applicationName, "0"); + } + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if(null==ext08Config){ + corporateInvoice.setExt08("2"); + }else{ + corporateInvoice.setExt08(ext08Config.getValue()); + } + } + // 2023-07-21 po 不处理 交给异步的 updatePo处理 + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + log.info("Identify File Success >> {}", corporateInvoice); + CorporateInvoice corporateInvoice1 = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + sysCorInvoiceService.updatePOAndHTBH(corporateInvoice1); + } + } else if (invoiceType.equals("4")) {// 报销发票,对应invoice_image + //增加报销发票的监听处理 2022/6/2 +// identifyInvoiceImage(viewPath, oldFileName, newFilePath, originalFilePath, corporateInvoiceTypeNew); + } else if (invoiceType.equals("5")) {// 供应商发票收票,对应corp_invoice_receive +// CorporateInvoice corporateInvoice = identifyAndReturnCorpInvoice(viewPath, oldFileName, newFilePath, corporateInvoiceTypeNew); +// if (corporateInvoice == null) { +// log.error("corp_invoice_receive Identify File Error"); +// } else if (corporateInvoice.getValidStatus().equals((byte) 1)) { +// StringBuilder message = new StringBuilder(); +// TicketType ticketType = ticketTypeMapper.selectByCode(corporateInvoice.getTicketCode()); +// corporateInvoiceService.validationRules(corporateInvoice, message, ticketType); +// corporateInvoice.setMessage(message.toString()); +// } +// if( StringUtil.isNotEmpty(corporateInvoice.getMessage())){ +// //异常 +// } + } + log.info("Deal File >> {} >> SUCCESS", viewPath); + } else { + log.error("File Remove Error >> {}", filePath); + } + } + + @Transactional(rollbackFor = Exception.class) + public RestResponse refresh(List list) { + + for (CorpInvoiceReceiveHeader corpInvoiceReceiveHeader : list) { + if (!"3".equals(corpInvoiceReceiveHeader.getStatus())) { + try { + CorporateInvoice corporateInvoice = corporateInvoiceMapper.selectByNumAndCode(corpInvoiceReceiveHeader.getInvoiceNum(), corpInvoiceReceiveHeader.getInvoiceCode()); + if (corporateInvoice != null && corporateInvoice.getInvoiceType() == 2) {//2023/4/18 修改 + corporateInvoiceMapper.updateReceived(corporateInvoice.getId()); + corpInvoiceReceiveHeader.setType(corporateInvoice.getInvoiceType()); + corpInvoiceReceiveHeader.setStatus("1"); + corpInvoiceReceiveHeader.setOddNum(corporateInvoice.getId()); + corpInvoiceReceiveHeaderMapper.updateByPrimaryKeySelective(corpInvoiceReceiveHeader); + } else { + //在paymentline表中查找对应发票 + CorpPaymentLine corpPaymentLine = corpPaymentLineMapper.selectByNumAndCode(corpInvoiceReceiveHeader.getInvoiceNum(), corpInvoiceReceiveHeader.getInvoiceCode()); + if (corpPaymentLine != null) { + corpPaymentLineMapper.updateReceived(corpInvoiceReceiveHeader.getInvoiceNum(), corpInvoiceReceiveHeader.getInvoiceCode()); + corpInvoiceReceiveHeader.setType(3); + corpInvoiceReceiveHeader.setOddNum(corpPaymentLine.getPId()); + corpInvoiceReceiveHeader.setStatus("1"); + corpInvoiceReceiveHeaderMapper.updateByPrimaryKeySelective(corpInvoiceReceiveHeader); + } else { + corpInvoiceReceiveHeader.setStatus("2"); + } + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + + } + } + + return RestResponse.success(); + } + + + private CorporateInvoice identifyAndReturnInvoice(String viewPath, String oldFileName, String filePath, CorporateInvoiceType corporateInvoiceType) { + try { + + log.info("InvoiceUploadCheck >> {},{},{}", viewPath, oldFileName, corporateInvoiceType.getName()); + + // 2023-07-06 + String pdfUrl = (String) Optional.ofNullable(StorageCache.read("PdfUrl." + oldFileName)).orElse(0); + + + // pdfUrl like D://****//2023070612071816368a1bcdf14153a2998986bf841dcf.ofd + + // 20230629接口方式判断 + String interfaceStr="RZ"; + SysConfig interfaceConfig =sysConfigMapper.selectByCode("OCR_INTERFACE"); + if(interfaceConfig!=null){ + interfaceStr = interfaceConfig.getValue(); + } + RuiZhenOCREntity ocrEntity ; + if(interfaceStr.equals("FH")){ + ocrEntity = ruiZhenOCRService.billsCropFH(Base64Util.fileToBase64(filePath)); + }else{ + ocrEntity =ruiZhenOCRService.billsCrop(Base64Util.fileToBase64(filePath)); + } + + // 2025-07-23 新增。 识别结束后 如果根据发票号码 在异常中存在此发票。则将 异常发票删除。 + List identify_results1 = ocrEntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults identify_result : identify_results1) { + String invoiceNum = identify_result.getDetails().getNumber(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(invoiceNum)){ + List oldInvoices = corporateInvoiceMapper.selectByNumberAndStatus(invoiceNum,"2"); + for (CorporateInvoice oldInvoice : oldInvoices) { + corporateInvoiceItemsMapper.deleteByPid(oldInvoice.getId()); + corporateInvoiceMapper.deleteByPrimaryKey(oldInvoice.getId()); + } + } + } + + + + + String comCode = String.valueOf(StorageCache.read(oldFileName)); + SysOrg sysOrg = sysOrgMapper.selectByCode(comCode); + + Integer orgId = 0; + if(null!=sysOrg){ + orgId = Optional.ofNullable(sysOrg.getId()).orElse(0); + } + Integer owner = (int) Optional.ofNullable(StorageCache.read("Owner." + oldFileName)).orElse(0); + String pdfOriginPath = (String) Optional.ofNullable(StorageCache.read("PdfUrl." + oldFileName)).orElse(null); + String oldName = (String) Optional.ofNullable(StorageCache.read("oldName." + oldFileName)).orElse(null); + log.info("pdfOriginPath=>{}",pdfOriginPath); + + List identify_results = ocrEntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults result : identify_results) { + log.info("发票类型测试>>{}<<",result.getType()); + if ("10101".equals(result.getType()) || "10100".equals(result.getType()) || "10102".equals(result.getType()) || + "10106".equals(result.getType()) || "10107".equals(result.getType()) || "10108".equals(result.getType()) || + "10104".equals(result.getType()) + ) { + //sys_config获取配置ALLOW_DEDUCTION_PAGE 0 需要进行判断,1不需要判断 2022/6/1 + SysConfig sysConfig = sysConfigMapper.selectByCode("ALLOW_DEDUCTION_PAGE"); + String con_value = sysConfig.getValue(); + if(con_value.equals("0")) { + if ("10100".equals(result.getType()) && "抵扣联".equals(result.getDetails().getForm_name())) { + log.error("special corporate invoice >>>>>>>>>>>抵扣联"); + return null; + } + } + String uuid = StringUtil.UUID(); + Details details = result.getDetails(); + CorporateInvoice corporateInvoice = new CorporateInvoice(); + corporateInvoice.setId(uuid); + corporateInvoice.setOwner(owner); + corporateInvoice.setOrgId(orgId); + corporateInvoice.setTitle(details.getSeller()); + corporateInvoice.setSeller(details.getSeller()); + corporateInvoice.setSellerNo(details.getSeller_tax_id()); + + // 2023-07-25 如果 是全电发票 将code置为0000 + if("10107".equals(result.getType()) || "10108".equals(result.getType())){ + if(org.apache.commons.lang3.StringUtils.isEmpty(details.getCode())){ + details.setCode("0000"); + } + } + corporateInvoice.setCode(details.getCode()); + + //修改发票代码为 日期加时间 + StringBuilder sb = new StringBuilder(); + String dateTime = details.getDate() + details.getTime(); + for (int i = 0; i < dateTime.length(); i++) { + if (dateTime.charAt(i) >= 48 && dateTime.charAt(i) <= 57) { + sb.append(dateTime.charAt(i)); + } + } + String s = sb.toString(); + if ("10503".equals(result.getType())) { + corporateInvoice.setCode(s); + if(StringUtil.isNotEmpty(details.getNumber()) && details.getNumber().length() == 20){ + corporateInvoice.setCode("0000"); + } + } + + corporateInvoice.setNumber(details.getNumber()); + corporateInvoice.setDate(details.getDate()); + corporateInvoice.setTotal(details.getTotal()); + corporateInvoice.setImgPath(viewPath); + corporateInvoice.setRemark(details.getRemark()); + + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(details.getBuyer()); + corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + corporateInvoice.setTicketCode(result.getType()); + corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(0); + // 修改原始文件路径20221018xp + PostBox query = new PostBox(); + query.setInvoiceNum(details.getNumber()); + List lsBox = postBoxMapper.selectByRecord(query); + if(lsBox.size()>0) { + PostBox boxTmp =null; + for(PostBox box:lsBox){ + if(boxTmp==null){ + boxTmp =box; + }else{ + if(box.getId()>boxTmp.getId()){//取最后一条 + boxTmp = box; + } + } + } + if(boxTmp!=null) { + corporateInvoice.setOriginalFilePath(boxTmp.getOriginalPath()); + }else{ + + int lastFlag = viewPath.lastIndexOf("/"); + int lastFlag2 = pdfUrl.lastIndexOf(File.separator); + log.info("PDF"+viewPath.substring(0,lastFlag)+pdfUrl.substring(lastFlag2)); + corporateInvoice.setOriginalFilePath(viewPath.substring(0,lastFlag)+pdfUrl.substring(lastFlag2)); + } + }else{ + + int lastFlag = viewPath.lastIndexOf("/"); + int lastFlag2 = pdfUrl.lastIndexOf(File.separator); + log.info("PDF"+viewPath.substring(0,lastFlag)+pdfUrl.substring(lastFlag2)); + corporateInvoice.setOriginalFilePath(viewPath.substring(0,lastFlag)+pdfUrl.substring(lastFlag2)); + } + corporateInvoice.setVerifiedCode(details.getCheck_code()); + corporateInvoice.setPretaxAmount(details.getPretax_amount()); +// corporateInvoice.setExt02(details.getBuyer_bank_account()); +// corporateInvoice.setExt03(details.getSeller_bank_account()); +// +// corporateInvoice.setExt04(details.getBuyer_addr_tel()); +// corporateInvoice.setExt05(details.getSeller_addr_tel()); + corporateInvoice.setTax(details.getTax()); + corporateInvoice.setOperatorId(owner); + corporateInvoice.setCreateDate(new Date()); + corporateInvoice.setCurrency("CNY"); + corporateInvoice.setChecked(0); + // 2023-07-20 取消PO赋值 防止覆盖 +// corporateInvoice.setPo(StringUtils.getPO(details.getRemark())); + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + corporateInvoice.setDetails(details.getItem_names()); + corporateInvoice.setInvoiceType(corporateInvoiceType.getId()); + + corporateInvoice.setIsSend(0); + corporateInvoice.setUseStatus(9); + corporateInvoice.setMatchStatus(0); + + corporateInvoice.setMatchType(corporateInvoiceType.getMatchType()); + + //增加保存字段 2022/8/16 + corporateInvoice.setNumberBackup(details.getNumberBackup()); + corporateInvoice.setNumberConfirm(details.getNumber_confirm()); + corporateInvoice.setCompanySeal(details.getCompany_seal()); + + corporateInvoice.setDataJson(JsonUtil.toString(result)); + // 验真 + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + if(null!=oldName){ + if(oldName.startsWith("PSP-")||oldName.startsWith("STO-")){ + String htNo = "TM-"+oldName; + corporateInvoice.setExt02(htNo); + corporateInvoice.setRemark(htNo+corporateInvoice.getRemark()); + } + } + // 回写scannerLogs + String logKey = "scannerLogs." + oldFileName; + if (StorageCache.containsKey(logKey)) { + Long logId = (Long)StorageCache.read(logKey); +// ScannerLogs logs = scannerLogsMapper.selectByPrimaryKey(logId); +// logs.setInvoiceId(corporateInvoice.getId()); +// scannerLogsMapper.updateByPrimaryKeySelective(logs); + corporateInvoice.setExt01(String.valueOf(logId)); + } + + + // 发票日期+发票号后8位+供应商名称 + String sufix = pdfUrl.substring(pdfUrl.lastIndexOf(".")); + String number = corporateInvoice.getNumber(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(number)&&number.length()>=8){ + number = number.substring(number.length()-8); + } + + String yearMonthDate = corporateInvoice.getDate(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(yearMonthDate)){ + yearMonthDate = yearMonthDate.replace("年",""); + yearMonthDate = yearMonthDate.replace("月",""); + yearMonthDate = yearMonthDate.replace("日",""); + } + //2023-08-13 根据系统配置 采用公司的中文和英文code名称 + String comName = null; + SysConfig imgVendorName = sysConfigMapper.selectByCode("img_vendor_name"); + if(null!=imgVendorName){ + String imgVendorNameValue = imgVendorName.getValue(); + if(null!=imgVendorNameValue&&"code".equals(imgVendorNameValue)) { + List suppliers = supplierMapper.selectByTaxNo(corporateInvoice.getSellerNo()); + if(!suppliers.isEmpty()){ + comName = suppliers.get(0).getCode(); + }else{ + comName = ""; + } + } + } + if(null==comName){ + comName = corporateInvoice.getSeller(); + } + String randomId = UUID.randomUUID().toString().substring(0,2); + String newOriginFileName = yearMonthDate+number+comName+randomId+sufix; +// String urlNewOriginFileName = URLEncoder.encode(newOriginFileName); + + String oldFileUploadPath = pdfUrl; + String parentPath = oldFileUploadPath.substring(0,oldFileUploadPath.lastIndexOf(File.separator)); + + if(parentPath.endsWith(File.separator)){ + + }else{ + parentPath = parentPath + File.separator; + } + + File oldFile = new File(pdfUrl); + // 先重命名 + // 如果是纸质发票 则 将jpg格式的作为附件下载 +// if(oldFile.exists()){ +// boolean flag = oldFile.renameTo(new File(parentPath+newOriginFileName)); +// // 不成功则复制 删除源文件 +// if(!flag){ + try { + FileUtils.copyFile(oldFile, new File(parentPath+newOriginFileName)); + // 成功后删除 +// oldFile.delete(); +// flag =true; + }catch (Exception e){ + log.error("copy file error!"); + e.printStackTrace(); + } +// } +// } + // originalPath 是 + if("10100".equals(result.getType())||"10101".equals(result.getType())) { + //如果是纸质发票 + // 需要将 url 改成 jpg + String jpgPath = viewPath.substring(viewPath.indexOf("opt")); + String jpgFilePath = uploadPath+jpgPath; + log.info("jpgFilePath={}",jpgFilePath); + String randomId2 = UUID.randomUUID().toString().substring(0,2); + String newJpgFilePath = yearMonthDate+number+comName+randomId2+".jpg"; + + log.info("newJpgFilePath={}",newJpgFilePath); + File oldJpgFile = new File(jpgFilePath); + // 先重命名 + // 如果是纸质发票 则 将jpg格式的作为附件下载 +// boolean flag1 = oldJpgFile.renameTo(new File(parentPath + newJpgFilePath)); +// // 不成功则复制 删除源文件 +// if(!flag1){ + try { + FileUtils.copyFile(oldJpgFile, new File(parentPath + newJpgFilePath)); + // 成功后删除 +// oldFile.delete(); +// flag1 =true; + }catch (Exception e){ + log.error("copy file error!"); + e.printStackTrace(); + } +// } + + String originalPath = corporateInvoice.getOriginalFilePath(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(originalPath)){ + String originalParent = originalPath.substring(0,originalPath.lastIndexOf("/")); + if(!originalParent.endsWith("/")){ + originalParent = originalParent+"/"; + } + String newJpgPath = originalParent + newJpgFilePath; + corporateInvoice.setOriginalFilePath(newJpgPath); + corporateInvoice.setImgPath(newJpgPath); + } + + }else{ + String originalPath = corporateInvoice.getOriginalFilePath(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(originalPath)){ + String originalParent = originalPath.substring(0,originalPath.lastIndexOf("/")); + if(!originalParent.endsWith("/")){ + originalParent = originalParent+"/"; + } + String newOFP = originalParent + newOriginFileName; + corporateInvoice.setOriginalFilePath(newOFP); + } + } + List items = corporateInvoice.getItems(); + // 2023-07-21 设置标签编码 + if(null!=ocrEntity.getResultFld()&&null!=ocrEntity.getResultFld().getNumberLabel()){ + corporateInvoice.setExt06(ocrEntity.getResultFld().getNumberLabel().getNumber()); + } + + // 2023-08-01 设置 + if(null!=ocrEntity.getResultFld()&&null!=ocrEntity.getResultFld().getStampcolor()){ + boolean redFlag = ocrEntity.getResultFld().getStampcolor().isStampRed(); + corporateInvoice.setExt07(String.valueOf(redFlag)); + } + if(2==corporateInvoiceType.getId()){ + corporateInvoice.setMatchType(1); + corporateInvoice.setPriceType(0); + }else{ + corporateInvoice.setMatchType(0); + corporateInvoice.setPriceType(1); + } + corporateInvoiceMapper.insert(corporateInvoice); + for (CorporateInvoiceItems corporateInvoiceItem : items) { + corporateInvoiceItemsMapper.insert(corporateInvoiceItem); + } + // 是否需要将原始PDF 上传为附件 + if(org.apache.commons.lang3.StringUtils.isNotEmpty(parentPath+newOriginFileName)){ + log.info("parentPath+newOriginFileName=>{}",parentPath+newOriginFileName); + File origin = new File(parentPath+newOriginFileName); + log.info("origin exist =>{}",origin.exists()); + // + int lastFlag = viewPath.lastIndexOf("/"); + int lastFlag2 = (parentPath+newOriginFileName).lastIndexOf("/"); + log.info("pdfOriginPath PDF =>"+viewPath.substring(0,lastFlag)+(parentPath+newOriginFileName)); + com.cmsen.ticket.domain.entity.File fpqd = new com.cmsen.ticket.domain.entity.File(); + fpqd.setUploadTime(new Date()); + fpqd.setDescription(""); + fpqd.setPath(parentPath+newOriginFileName); + fpqd.setPid(corporateInvoice.getId()); + fpqd.setType("其他"); + fpqd.setUri(viewPath.substring(0,lastFlag)+"/"+newOriginFileName); + fileMapper.insert(fpqd); + } + +// sysCorInvoiceService.updatePOAndHTBH(corporateInvoice); + String key = "HashKey." + oldFileName; + if (StorageCache.containsKey(key)) { + String hashKey = String.valueOf(StorageCache.read(key)); + ScannerLogs scannerLogs = scannerLogsMapper.selectByHashKey(hashKey); + if (scannerLogs != null) { + if (corporateInvoice.getStatus().equals(2)) { + scannerLogs.setErrorNum(scannerLogs.getErrorNum() + 1); + } + scannerLogs.setInvoiceUpNum(scannerLogs.getInvoiceUpNum() + 1); + scannerLogsMapper.updateByPrimaryKeySelective(scannerLogs); + } + } + return corporateInvoice; + } + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } + + @Transactional(rollbackFor = Exception.class) + public RestResponse reVerify(String id) { + + if (null == id) { + return RestResponse.failure("id不能为空", 10003); + } + + //得到corpInvoiceReceiveHeader + CorpInvoiceReceiveHeader corpInvoiceReceiveHeader = corpInvoiceReceiveHeaderMapper.selectByPrimaryKey(Long.valueOf(id)); + if(corpInvoiceReceiveHeader == null){ + return RestResponse.failure("无效的主键id"); + } + + CorporateInvoice corporateInvoice = new CorporateInvoice(); + + String uuid = StringUtil.UUID(); + corporateInvoice.setId(uuid); + //corporateInvoice.setOwner(owner); + corporateInvoice.setTitle(corpInvoiceReceiveHeader.getSeller()); + corporateInvoice.setSeller(corpInvoiceReceiveHeader.getSeller()); + //corporateInvoice.setSellerNo(details.getSeller_tax_id()); + corporateInvoice.setCode(corpInvoiceReceiveHeader.getInvoiceCode()); + corporateInvoice.setNumber(corpInvoiceReceiveHeader.getInvoiceNum()); + corporateInvoice.setDate(corpInvoiceReceiveHeader.getInvoiceDate()); + //corporateInvoice.setTotal(details.getTotal()); + //corporateInvoice.setImgPath(viewPath); + //corporateInvoice.setRemark(details.getRemark()); + + //corporateInvoice.setExtraFields(exFieldsString1); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(corpInvoiceReceiveHeader.getBuyer()); + //corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + //corporateInvoice.setTicketCode(result.getType()); + //corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(0); + //corporateInvoice.setOriginalFilePath(viewPath); + //corporateInvoice.setVerifiedCode(details.getCheck_code()); + corporateInvoice.setPretaxAmount(corpInvoiceReceiveHeader.getAmountMoney()); + corporateInvoice.setTax(corpInvoiceReceiveHeader.getTaxAmount()); + //corporateInvoice.setOperatorId(owner); + corporateInvoice.setCreateDate(new Date()); + corporateInvoice.setCurrency("CNY"); + corporateInvoice.setChecked(0); + //corporateInvoice.setPo(StringUtils.getPO(details.getRemark())); + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + //corporateInvoice.setDetails(details.getItem_names()); + //corporateInvoice.setInvoiceType(corporateInvoiceType.getId()); + + corporateInvoice.setIsSend(0); + corporateInvoice.setUseStatus(9); + corporateInvoice.setMatchStatus(0); + //corporateInvoice.setMatchType(corporateInvoiceType.getMatchType()); + + + corporateInvoice.setTicketCode(corpInvoiceReceiveHeader.getTicketCode()); + corporateInvoice.setVerifiedCode(corpInvoiceReceiveHeader.getVerifiedCode()); + //增加发票接收实体 + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + + //将验真后的s结果,重新进行赋值 + corpInvoiceReceiveHeader.setDateOfReceipt(new Date()); + corpInvoiceReceiveHeader.setBuyer(corporateInvoice.getBuyer()); + //corpInvoiceReceiveHeader.setInvoiceType(corporateInvoice.getInvoiceType() == 2 ? "增值税专用发票" : "增值税普通发票"); + corpInvoiceReceiveHeader.setSeller(corporateInvoice.getSeller()); + corpInvoiceReceiveHeader.setInvoiceCode(corporateInvoice.getCode()); + corpInvoiceReceiveHeader.setInvoiceNum(corporateInvoice.getNumber()); + corpInvoiceReceiveHeader.setInvoiceDate(corporateInvoice.getDate()); + corpInvoiceReceiveHeader.setAmountMoney(corporateInvoice.getPretaxAmount()); + corpInvoiceReceiveHeader.setTaxAmount(corporateInvoice.getTax()); + String pretaxAmount = corporateInvoice.getPretaxAmount(); + String tax = corporateInvoice.getTax(); + String total = new BigDecimal(pretaxAmount).add(new BigDecimal(tax)).toString(); + corpInvoiceReceiveHeader.setTotalAmount(total); + + if (StringUtil.isNotEmpty(corporateInvoice.getMessage())) { + //异常 + corpInvoiceReceiveHeader.setStatus("3"); + } else { + CorporateInvoice corporateInvoice1 = corporateInvoiceMapper.selectByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode()); + if (corporateInvoice1 != null && corporateInvoice1.getInvoiceType() == 2) {//2023/4/18 修改 + corporateInvoiceMapper.updateReceived(corporateInvoice1.getId()); + corpInvoiceReceiveHeader.setType(corporateInvoice1.getInvoiceType()); + corpInvoiceReceiveHeader.setOddNum(corporateInvoice1.getId()); + corpInvoiceReceiveHeader.setStatus("1"); + } else { + //在paymentline表中查找对应发票 + CorpPaymentLine corpPaymentLine = corpPaymentLineMapper.selectByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode()); + if (corpPaymentLine != null) { + corpPaymentLineMapper.updateReceived(corporateInvoice.getNumber(), corporateInvoice.getCode()); + corpInvoiceReceiveHeader.setType(3); + corpInvoiceReceiveHeader.setOddNum(corpPaymentLine.getPId()); + corpInvoiceReceiveHeader.setStatus("1"); + } else { + corpInvoiceReceiveHeader.setStatus("2"); + } + } + } + + corpInvoiceReceiveHeader.setRemarks(corporateInvoice.getMessage()); + corpInvoiceReceiveHeader.setValidStatus(corporateInvoice.getValidStatus().toString()); + //新增加保存的属性 2022/5/31 + corpInvoiceReceiveHeader.setTicketCode(corporateInvoice.getTicketCode()); + corpInvoiceReceiveHeader.setVerifiedCode(corporateInvoice.getVerifiedCode()); + + //更新corpInvoiceReceiveHeader + corpInvoiceReceiveHeaderMapper.updateByPrimaryKeySelective(corpInvoiceReceiveHeader); + + //取items,进行插入 + List items = corporateInvoice.getItems(); + CorpInvoiceReceiveLine corpInvoiceReceiveLine = new CorpInvoiceReceiveLine(); + for (CorporateInvoiceItems corporateInvoiceItem : items) { + BeanUtils.copyProperties(corporateInvoiceItem, corpInvoiceReceiveLine); + corpInvoiceReceiveLineMapper.insert(corpInvoiceReceiveLine); + } + + return RestResponse.success(); + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublic4SupplierCsvTask.java b/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublic4SupplierCsvTask.java new file mode 100644 index 0000000..c2917d7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublic4SupplierCsvTask.java @@ -0,0 +1,451 @@ +package com.cmsen.ticket.infrastructure.task.mailpublic; + +import com.cmsen.common.util.DateFormat; +import com.cmsen.common.util.FileUtil; +import com.cmsen.common.util.JsonUtil; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.domain.entity.Supplier; +import com.cmsen.ticket.domain.mapper.SupplierMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.interfaces.facade.manager.form.SupplierSearchForm; +import com.cmsen.ticket.log.entity.TInterfaceLog; +import com.cmsen.ticket.log.service.TInterfaceLogService; +import com.cmsen.ticket.monitor.entity.Task; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.quartz.DisallowConcurrentExecution; +import org.springframework.beans.factory.annotation.Value; + +import javax.annotation.Resource; +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeUtility; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author lee.meng + * @version 1.0.0 + * @date 2021/8/13 16:51 + * @desc MailPublicTask + **/ +@Slf4j +@DisallowConcurrentExecution +public class MailPublic4SupplierCsvTask extends Task { + // 消息 + StringBuffer mesg=new StringBuffer(); + + int size=0; + + @Resource + private TInterfaceLogService interfaceLogService; + + private final String protocol = "imap"; + + // @Value("${file.PDF}") +// private String PDFPath; + private final String auth = "true"; + private final String transportProtocol = "imap"; + private final String socketFactory = "javax.net.ssl.SSLSocketFactory"; + private final List emailList = new ArrayList<>(); + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + @Value("${file.filepath}") + private String invoicePic; + @Value("${mail-public.username}") + private String userEmail; + @Value("${mail-public.password}") + private String password; + @Value("${mail-public.active}") + private String active; + @Value("${mail-public.host}") + private String host; + @Value("${mail-public.port}") + private String port; + @Value("${manager-file.uploadPath}") + private String uploadPath; + private Store store = null; + private Session session = null; + @Resource + private SupplierMapper supplierMapper; + + @Override + public void run() { + mesg = new StringBuffer(); + TInterfaceLog interfaceLog = new TInterfaceLog(); + try { + receiveEmail(); + } catch (Exception e) { + mesg.append(e.getMessage()); + e.printStackTrace(); + } finally{ + interfaceLog.setInterfaceName(scheduleJob.getName()); + if(mesg.length()>0){ + interfaceLog.setRunState("1"); + interfaceLog.setSendMesg(mesg.toString()); + interfaceLog.setRunMesg(mesg.toString()); + }else{ + interfaceLog.setRunState("2"); + if(interfaceLog.getRunMesg()==null || interfaceLog.getRunMesg().length()==0) + { + interfaceLog.setSendMesg("运行成功"); + interfaceLog.setRunMesg("运行成功"); + } + } + interfaceLog.setIsRollBack("0"); + + interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); + } + } + + + +// private void getUserEmailList() { +// List emails = configListMapper.selectByType("COEMAIL"); +// emails.forEach(email -> emailList.addAll(Arrays.stream(email.getParams1().split(";")).collect(Collectors.toList()))); +// } + + private Store getConnect() { + //代理配置 + Properties props = System.getProperties(); + props.setProperty("mail.store.protocol", protocol); + props.setProperty("mail.imap.host", host); + props.setProperty("mail.imap.port", port); + props.setProperty("mail.imap.auth.login.disable", auth); + props.setProperty("mail.imap.socketFactory.port", port); + props.setProperty("mail.transport.protocol", transportProtocol); + props.setProperty("mail.imap.socketFactory.class", socketFactory); + props.setProperty("mail.mime.splitlongparameters", "false"); + props.setProperty("mail.mime.charset", "UTF-8"); + props.setProperty("mail.imap.socketFactory.follback", "false"); + props.setProperty("mail.mime.base64.ignoreerrors", "true"); +// int tryTimes = 0; +// do { + try { +// log.info("开始获取连接>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + session = Session.getDefaultInstance(props); + // 2、通过session得到Store对象 + store = session.getStore("imap"); + // 3、连上邮件服务器 + store.connect(host, userEmail, password); + } catch (Exception e) { + log.info("获取连接失败>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + log.error(e.getMessage(), e); + store = null; +// try { +// Thread.sleep(5000); +// } catch (InterruptedException interruptedException) { +// interruptedException.printStackTrace(); +// } + } +// tryTimes++; +// } while (tryTimes < 3 && store == null); + return store; + } + + // @PostConstruct +// @Scheduled(cron = "0 0/5 * * * ?") +// @Scheduled(fixedDelay = 1000 * 60 * 20, initialDelay = 1000 * 60 * 10) +// @Scheduled(cron = "0 0/5 * * * ?") + public void receiveEmail() { + log.info("Start Get Public Email Active>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", active); + if ("true".equals(active)) { + log.info("Start Get Public Email >>{}>>", userEmail); + try { +// getUserEmailList(); + Store imapStore = getConnect(); + if (null == imapStore) { + log.error("获取邮箱imap连接失败。>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + } else { +// log.info("获取连接成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + Folder folder = imapStore.getFolder("INBOX"); + folder.open(Folder.READ_WRITE); + Message[] messages = folder.getMessages(folder.getMessageCount() - folder.getUnreadMessageCount() + 1, folder.getMessageCount()); +// log.info("未读邮件数量: {}", messages.length); + for (Message msg : messages) { +// log.info("开始处理:>>{}", msg.getSubject()); + if (!msg.getFlags().contains(Flags.Flag.SEEN)) { + log.info("开始处理:>>{},未读", msg.getSubject()); + dealMessage(msg); + log.info("处理结束:>>{}", msg.getSubject()); + } + msg.setFlag(Flags.Flag.SEEN, true); + } + //关闭资源 + folder.close(true); + imapStore.close(); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + close(); + } + } + } + + private void dealMessage(Message msg) throws Exception { + String date = DateFormat.format(new Date(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日); + String from = getFrom(msg); + String subject = msg.getSubject(); + if (StringUtil.isEmpty(from)) { + return; + } + if (isContainAttach(msg)) { + //处理邮件 +// Integer userId = userEmailList.get(from); + Map inputStreamMap = new HashMap<>(); + getFileInputStream2(msg, inputStreamMap); + String folder = Pdf2JpgHelper.generateFolder(invoicePic + File.separator); + inputStreamMap.forEach((k, v) -> { + log.info("获取附件名称>>{}", k); + try { + if (k.endsWith(".csv") || k.endsWith(".CSV")) { + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".csv"; + String csvFilePath = invoicePic + File.separator + folder + newFileName; + try{ + saveFile(csvFilePath,v); + }catch (IOException e){ + log.info("保存文件错误{},:{}",newFileName,e.getMessage()); + } + + List suppliers = supplierMapper.list(new SupplierSearchForm()); + Map> suppliersMap = suppliers.stream().collect(Collectors.groupingBy(Supplier::getCode)); + + // 将csv文件 导入 supplier + String absolutePath = csvFilePath; + File csvFile = new File(absolutePath); + List list_str = FileUtils + .readLines(csvFile,"UTF-8"); + String[] str={}; + for (int i = 3; i < list_str.size(); i++) { + if(list_str.get(i)==null || list_str.get(i).length()==0 ||list_str.get(i).indexOf(",")==-1) continue; + str = list_str.get(i).split("\t"); + String code = str[2]; + String name = str[4]; + String country = str[10]; + String VATRegNo = str[17]; + if(null==suppliersMap.get(code)){ + // 没有则 新增 + Supplier supplier = new Supplier(); + supplier.setCode(code); + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.insertSelective(supplier); + }else{ + // 存在则判断是否更新 + Supplier supplier = suppliersMap.get(code).get(0); + if(name.equals(supplier.getName()) + &&country.equals(supplier.getExt01()) + &&VATRegNo.equals(supplier.getTaxNo())){ + continue; + }else{ + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.updateByPrimaryKey(supplier); + } + } + } + csvFile.delete(); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + log.info("识别附件结果>>ERROR>>{}", e.getMessage()); + } + }); + } else { + //发送反馈 + log.warn("非系统设置邮箱>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", from); + } + } + + private void dealData(){ + try { +// if (k.endsWith(".csv") || k.endsWith(".CSV")) { + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".csv"; +// String csvFilePath = invoicePic + File.separator + folder + newFileName; +// FileOutputStream os = new FileOutputStream(csvFilePath); +// int len = -1; +// byte[] bytes = new byte[1024]; +// while ((len = v.read(bytes)) != -1) { +// os.write(bytes, 0, len); +// } +// os.flush(); +// v.close(); +// os.close(); + + + List suppliers = supplierMapper.list(new SupplierSearchForm()); + Map> suppliersMap = suppliers.stream().collect(Collectors.groupingBy(Supplier::getCode)); + + + // 将csv文件 导入 supplier + String absolutePath = "D:\\test.csv"; + List list_str = FileUtils + .readLines(new File(absolutePath),"UTF-8"); + String[] str={}; + for (int i = 3; i < list_str.size(); i++) { + if(list_str.get(i)==null || list_str.get(i).length()==0 ||list_str.get(i).indexOf(",")==-1) continue; + str = list_str.get(i).split("\t"); + String code = str[2]; + String name = str[4]; + String country = str[10]; + String VATRegNo = str[17]; + if(null==suppliersMap.get(code)){ + // 没有则 新增 + Supplier supplier = new Supplier(); + supplier.setCode(code); + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.insertSelective(supplier); + }else{ + // 存在则判断是否更新 + Supplier supplier = suppliersMap.get(code).get(0); + if(name.equals(supplier.getName()) + &&country.equals(supplier.getExt01()) + &&VATRegNo.equals(supplier.getTaxNo())){ + continue; + }else{ + supplier.setName(name); + supplier.setExt01(country); + supplier.setTaxNo(VATRegNo); + supplierMapper.updateByPrimaryKey(supplier); + } + } + } +// } + } catch (Exception e) { + log.error(e.getMessage(), e); + log.info("识别附件结果>>ERROR>>{}", e.getMessage()); + } + } + + private void getFileInputStream(Part part, Map inputStreamMap) throws Exception { + String fileName; + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { + fileName = mPart.getFileName(); + // 为空判断20231024 + if(fileName==null)continue; +// if (fileName.toLowerCase().contains("gb2312")) { + fileName = MimeUtility.decodeText(fileName); +// } + inputStreamMap.put(fileName, mPart.getInputStream()); + } else if (mPart.isMimeType("multipart/*")) { + log.info("子邮件里面的附件"); + getFileInputStream(mPart, inputStreamMap); + } else { + fileName = mPart.getFileName(); + if (fileName != null) { + fileName = MimeUtility.decodeText(fileName); + inputStreamMap.put(fileName, mPart.getInputStream()); + } + } + } + } else if (part.isMimeType("message/rfc822")) { + getFileInputStream((Part) part.getContent(), inputStreamMap); + } + } + + private boolean isContainAttach(Part part) throws Exception { + boolean attachFlag = false; + // String contentType = part.getContentType(); + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) + && ((disposition.equals(Part.ATTACHMENT)) || (disposition + .equals(Part.INLINE)))) { + attachFlag = true; + } else if (mPart.isMimeType("multipart/*")) { + attachFlag = isContainAttach(mPart); + } else { + String conType = mPart.getContentType(); + + if (conType.toLowerCase().contains("application")) { + attachFlag = true; + } + if (conType.toLowerCase().contains("name")) { + attachFlag = true; + } + } + } + } else if (part.isMimeType("message/rfc822")) { + attachFlag = isContainAttach((Part) part.getContent()); + } + return attachFlag; + } + + private String getFrom(Message msg) throws MessagingException { + String from = ""; + InternetAddress[] addresses = (InternetAddress[]) msg.getFrom(); + if (null == addresses || addresses.length == 0) { + log.error("无法获取发送人地址信息!"); + return from; + } + Address address = addresses[0]; + log.info("发件人地址json:" + JsonUtil.toString(address)); + String form = ((InternetAddress) address).getAddress(); + return form; + } + + private void close() { + if (store != null) { + try { + store.close(); + } catch (MessagingException e) { + log.error(e.getMessage(), e); + } + } + } + + private void saveFile(String pdfRealPathAll,byte[] v) throws IOException { + FileOutputStream os = new FileOutputStream(pdfRealPathAll); + os.write(v); + os.flush(); + } + + private void getFileInputStream2(Part part, Map inputStreamMap) throws Exception { + String fileName; + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { + fileName = mPart.getFileName(); + // 为空判断20231024 + if(fileName==null)continue; + fileName = MimeUtility.decodeText(fileName); + byte[] bytes = FileUtil.getBytes(mPart.getInputStream(), 1024); + inputStreamMap.put(fileName, bytes); + } else if (mPart.isMimeType("multipart/*")) { + log.info("MailPublic4SupplierCsvTask 子邮件里面的附件"); + getFileInputStream2(mPart, inputStreamMap); + } else { + fileName = mPart.getFileName(); + if ((fileName != null)) { + fileName = MimeUtility.decodeText(fileName); + byte[] bytes = FileUtil.getBytes(mPart.getInputStream(), 1024); + inputStreamMap.put(fileName, bytes); + } + } + } + } else if (part.isMimeType("message/rfc822")) { + getFileInputStream2((Part) part.getContent(), inputStreamMap); + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublicTask.java b/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublicTask.java new file mode 100644 index 0000000..68464a8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/task/mailpublic/MailPublicTask.java @@ -0,0 +1,1108 @@ +package com.cmsen.ticket.infrastructure.task.mailpublic; + +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.util.*; +import com.cmsen.ticket.application.manager.service.impl.SysCorInvoiceServiceImpl; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.application.service.SendMailService; +import com.cmsen.ticket.application.service.SupplierOutService; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysEmp; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.mapper.*; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysEmpMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.util.StringUtils; +import com.cmsen.ticket.infrastructure.ocr2.NDOcrService; +import com.cmsen.ticket.infrastructure.ocr2.OFDUtil; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.infrastructure.ocr2.entity.Details; +import com.cmsen.ticket.infrastructure.ocr2.entity.Item; +import com.cmsen.ticket.infrastructure.ocr2.entity.RuiZhenOCREntity; +import com.cmsen.ticket.infrastructure.tools.util.ArchiveExtractor; +import com.cmsen.ticket.log.entity.TInterfaceLog; +import com.cmsen.ticket.log.service.TInterfaceLogService; +import com.cmsen.ticket.monitor.entity.Task; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.quartz.DisallowConcurrentExecution; +import org.springframework.beans.factory.annotation.Value; + +import javax.annotation.Resource; +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeUtility; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @author lee.meng + * @version 1.0.0 + * @date 2021/8/13 16:51 + * @desc MailPublicTask + **/ +@Slf4j +@DisallowConcurrentExecution +public class MailPublicTask extends Task { + + + StringBuffer emailDetails = new StringBuffer(); + + int size=0; + + // 消息 + StringBuffer mesg=new StringBuffer(); + @Resource + private TInterfaceLogService interfaceLogService; + + private final String protocol = "imap"; + + // @Value("${file.PDF}") +// private String PDFPath; + private final String auth = "true"; + private final String transportProtocol = "imap"; + private final String socketFactory = "javax.net.ssl.SSLSocketFactory"; + private final List emailList = new ArrayList<>(); + @Value("${file.domainName}") + private String domainName; + @Value("${server.servlet.context-path}") + private String contextPath; + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + @Value("${file.filepath}") + private String invoicePic; + @Value("${mail-public.username}") + private String userEmail; + @Value("${mail-public.password}") + private String password; + @Value("${mail-public.active}") + private String active; + @Value("${mail-public.host}") + private String host; + @Value("${mail-public.port}") + private String port; + @Value("${manager-file.uploadPath}") + private String uploadPath; + @Value("${manager-file.watchPath}") + private String watchPath; + private Store store = null; + private Session session = null; + @Value("${spring.application.name}") + private String applicationName; + @Resource + private SupplierOutService supplierOutService; + + @Value("${manager-file.viewPath}") + private String viewPath; + + @Resource + private TicketTypeMapper ticketTypeMapper; + + @Resource + private FileMapper fileMapper; + + @Resource + private PostBoxMapper postBoxMapper; + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + @Resource + private SysOrgMapper sysOrgMapper; + + @Resource + private CorporateInvoiceMapper corporateInvoiceMapper; + + @Resource + private SysCorInvoiceServiceImpl sysCorInvoiceService; + + @Resource + private CorporateInvoiceItemsMapper corporateInvoiceItemsMapper; + + @Resource + private SysUserMapper sysUserMapper; + + @Resource + private SendMailService sendMailService; + + @Resource + private SysConfigMapper sysConfigMapper; + @Resource + private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; + + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @Resource + private SysEmpMapper sysEmpMapper; + + + @Resource + private SupplierMapper supplierMapper; + + private String pId; + + @Resource + private NDOcrService ndOcrService; + + @Resource + private FilesOcrMapper filesOcrMapper; + + @Resource + private CorporateInvoiceNdJsonMappingMapper corporateInvoiceNdJsonMappingMapper; + + @Resource + private FilesConfigMapper filesConfigMapper; + + @Override + public void run() { + TInterfaceLog interfaceLog = new TInterfaceLog(); + mesg = new StringBuffer(); + emailDetails = new StringBuffer(); + try { + receiveEmail(); + } catch (Exception e) { + mesg.append(e.getMessage()); + e.printStackTrace(); + } finally{ + interfaceLog.setInterfaceName(scheduleJob.getName()); + if(mesg.length()>0){ + interfaceLog.setRunState("1"); + interfaceLog.setSendMesg(mesg.toString()); + interfaceLog.setRunMesg(mesg.toString()+emailDetails.toString()); + }else{ + interfaceLog.setRunState("2"); + if(interfaceLog.getRunMesg()==null || interfaceLog.getRunMesg().length()==0) + { + interfaceLog.setSendMesg("运行成功"); + interfaceLog.setRunMesg("运行成功"+emailDetails.toString()); + } + } + interfaceLog.setIsRollBack("0"); + + interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); + } + } + + private Store getConnect() { + //代理配置 + Properties props = System.getProperties(); + props.setProperty("mail.store.protocol", protocol); + props.setProperty("mail.imap.host", host); + props.setProperty("mail.imap.port", port); + props.setProperty("mail.imap.auth.login.disable", auth); + props.setProperty("mail.imap.socketFactory.port", port); + props.setProperty("mail.transport.protocol", transportProtocol); + props.setProperty("mail.imap.socketFactory.class", socketFactory); + props.setProperty("mail.mime.splitlongparameters", "false"); + props.setProperty("mail.mime.charset", "UTF-8"); + props.setProperty("mail.imap.socketFactory.follback", "false"); + props.setProperty("mail.mime.base64.ignoreerrors", "true"); + + try { + log.info("开始获取连接>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + session = Session.getDefaultInstance(props); + // 2、通过session得到Store对象 + store = session.getStore("imap"); + // 3、连上邮件服务器 + store.connect(host, userEmail, password); + } catch (Exception e) { + log.info("获取连接失败>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + log.error(e.getMessage(), e); + store = null; + } + return store; + } + + public void receiveEmail() { + log.info("Start Get Public Email Active>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", active); + if ("true".equals(active)) { + log.info("Start Get Public Email >>{}>>", userEmail); + try { + Store imapStore = getConnect(); + if (null == imapStore) { + log.error("获取邮箱imap连接失败。>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + } else { + log.info("获取连接成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + Folder folder = imapStore.getFolder("INBOX"); + folder.open(Folder.READ_WRITE); + Message[] messages = folder.getMessages(folder.getMessageCount() - folder.getUnreadMessageCount() + 1, folder.getMessageCount()); + log.info("未读邮件数量: {}", messages.length); + for (Message msg : messages) { + log.info("开始处理:>>{}", msg.getSubject()); + if (!msg.getFlags().contains(Flags.Flag.SEEN)) { + log.info("开始处理:>>{},未读", msg.getSubject()); + dealMessage(msg); + log.info("处理结束:>>{}", msg.getSubject()); + } + msg.setFlag(Flags.Flag.SEEN, true); + } + //关闭资源 + folder.close(true); + imapStore.close(); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } finally { + close(); + } + } + } + + private void dealMessage(Message msg) throws Exception { + String date = DateFormat.format(new Date(), DateFormat.DatePatternType.FORMAT_yyyy年MM月dd日); + String from = getFrom(msg); + String subject = msg.getSubject(); + emailDetails.append("date:") + .append(date) + .append(";") + .append("from:") + .append(from) + .append(";") + .append("subject:") + .append(subject) + .append(";\n"); + if (StringUtil.isEmpty(from)) { + return; + } + if (isContainAttach(msg)) { + //处理邮件 +// Integer userId = userEmailList.get(from); + Map inputStreamMap = new HashMap<>(); + getFileInputStream2(msg, inputStreamMap); + String folder = Pdf2JpgHelper.generateFolder(invoicePic + File.separator); + String dzdFilePath = null; + String dzdUrlPath = null; + String fpqdFilePath = null; + String dzdName = null; + String fpqdName = null; + String fpqdUrlPath = null; + pId = null; + String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date()); + if (!cn.hutool.core.io.FileUtil.isDirectory(invoicePic + File.separator+folder+File.separator+datePath+File.separator)) { + cn.hutool.core.io.FileUtil.mkdir(invoicePic + File.separator+folder+File.separator+datePath+File.separator); + } + + List fjFilesOcr = new ArrayList<>(); + List fjFiles = new ArrayList<>(); + SysConfig NDSupportConfig = sysConfigMapper.selectByCode("ND_SUPPORT"); + if (null == NDSupportConfig) { + log.warn("ND_SUPPORT未配置"); + } + SysConfig ocrProformaConfig = sysConfigMapper.selectByCode("OCR_PROFORMA"); + if (null == ocrProformaConfig) { + log.warn("形式发票识别未配置匹配模型采用ocr模式识别"); + } + + + RuiZhenOCREntity ocrEntity = null; + int type = 1; + if (null==NDSupportConfig||"0".equals(NDSupportConfig.getValue())) { + Map dealMap = new HashMap<>(); + List dealList = new ArrayList<>(); + for (Map.Entry entry : inputStreamMap.entrySet()) { + String k = entry.getKey(); + byte[] v = entry.getValue(); + log.info("获取附件名称>>{}", k); + // 弗兰德逻辑 + // 新逻辑走VL模型 保存文件判断文件类型 + String kFileType = ""; + String suffix = k.substring(k.indexOf(".")); + String archiveParent = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8); + String newFileName = archiveParent +k; + //先下载所有文件如果有 压缩类文件解压 + String fileRealPath = invoicePic + java.io.File.separator + folder + datePath+File.separator+ newFileName; + String odfPdfPath = invoicePic + java.io.File.separator + folder+ datePath+File.separator + archiveParent+".pdf"; + try { + //2024-01-19 判断附件类型 + if(k.indexOf("对账单")>-1){ + String newPDFName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8) + ".pdf"; + dzdFilePath = invoicePic + java.io.File.separator + folder + datePath+File.separator + newPDFName; + dzdUrlPath = domainName + contextPath + imgVirtualPath + "/" + folder + datePath+"/" + newPDFName; + dzdName = k; + try{ + saveFile(dzdFilePath,v); + }catch (IOException e){ + log.info("保存文件错误{},:{}",dzdName,e.getMessage()); + } + continue; + } + log.info("k.indexOf(\"清单\")>>{}", k.indexOf("清单")); + if(k.indexOf("清单")>-1){ + String suffix2 = k.substring(k.lastIndexOf(".")); + String newFileName2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8) + suffix2; + fpqdName = k; + fpqdFilePath = invoicePic + java.io.File.separator + folder+ datePath+File.separator + newFileName2; + fpqdUrlPath = domainName + contextPath + imgVirtualPath + "/" + folder+ datePath+"/"+ newFileName2; + log.info("fpqdUrlPath>>{}", fpqdUrlPath); + continue; + } + try { + saveFile(fileRealPath, v); + } catch (IOException e) { + log.info("保存文件错误{},:{}", k, e.getMessage()); + continue; + } + if (k.toLowerCase().endsWith(".7z") || k.toLowerCase().endsWith(".rar") || k.toLowerCase().endsWith(".zip")) { + ArchiveExtractor.extractToFolder(fileRealPath,archiveParent); + File archive = new File(invoicePic + java.io.File.separator + folder+archiveParent); + traverseFolder(archive,dealList); + }else if(k.toLowerCase().endsWith("ofd")){ + OFDUtil.convertToPdf(fileRealPath,odfPdfPath,12); + dealList.add(odfPdfPath); + }else { +// dealMap.put(k,fileRealPath); + dealList.add(fileRealPath); + } + } catch (Exception e) { + e.printStackTrace(); + } + new File(fileRealPath).delete(); + } + + for (String fileString : dealList) { + try{ + if (fileString.toLowerCase().endsWith(".pdf")) { + // 2024-01-18 + String newPDFName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8) + ".pdf"; + String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID().substring(0,8) + ".jpg"; + String pdfRealPath = domainName + contextPath + imgVirtualPath + "/" + folder+ datePath+"/" + newPDFName; + log.info("原Pdf图片地址 2:>>{}", fileString); + + SysConfig MAIL_OVERSEA_KEYWORD = sysConfigMapper.selectByCode("MAIL_OVERSEA_KEYWORD"); + if(null==MAIL_OVERSEA_KEYWORD){ + log.warn("系统未配置 邮箱海外发票关键字"); +// continue; + } + SysEmp sysEmp = sysEmpMapper.selectByEmail(from); + + // 弗兰德的形式发票 + String imgRealPath = invoicePic + java.io.File.separator + folder+ datePath+File.separator + newImgName; + String imgUrlPath = domainName + contextPath + imgVirtualPath + "/" + folder + datePath+ "/" +newImgName; + + log.info("jpg图片地址:>>{}", imgRealPath); + + if (null!=subject && subject.indexOf("形式发票")>-1) { + type = 1; + Pdf2JpgHelper.pdfToImage2(fileString,imgRealPath); +// SysOrg sysOrg = sysOrgMapper.selectByCode(com); + // 通过 FH AI 接口解析 形式发票 + // 开关控制 224 OCR_PROFORMA =proforma-繁翰OCR-FLD ; 其他任何值-VL 大模型 走FH 还是走ND VL 方式识别 + if (null==ocrProformaConfig||"proforma".equals(ocrProformaConfig.getValue())) { + ocrEntity = ruiZhenOCRService.billsCropFHOfProforma(Base64Util.fileToBase64(fileString)); + }else{ + File pdfFile = new File(fileString); + ocrEntity = ruiZhenOCRService.billsCropFHOfnd("proforma_invoice",pdfFile); + } + }else if (null != MAIL_OVERSEA_KEYWORD && fileString.indexOf(MAIL_OVERSEA_KEYWORD.getValue())>-1){ + // 逻辑4 附件发票名称中包含 关键词配置"MAIL_OVERSEA_KEYWORD"- 走ND的proforma_invoice + type = 1; + Pdf2JpgHelper.pdfToOneImage(fileString,imgRealPath); +// SysOrg sysOrg = sysOrgMapper.selectByCode(com); + // 通过 HF AI 接口解析 形式发票 + File pdfFile = new File(fileString); + ocrEntity = ruiZhenOCRService.billsCropFHOfnd("proforma_invoice",pdfFile); + }else if (null!=sysEmp && sysEmp.getVendorType().equals("O")){ + type = 1; + // sys_emp 表发件人的邮箱 对应的 VENDER_TYPE = O 走海外发票逻辑 + Pdf2JpgHelper.pdfToOneImage(fileString,imgRealPath); +// SysOrg sysOrg = sysOrgMapper.selectByCode(com); + // 通过 HF AI 接口解析 形式发票 + File pdfFile = new File(fileString); + ocrEntity = ruiZhenOCRService.billsCropFHOfnd("proforma_invoice",pdfFile); + } + + // 默认走的发票pdf逻辑 走繁翰国内电子票的解析 + else { + int orgId = sysEmp.getOrgId(); + SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(orgId); + CorporateInvoiceType corporateInvoiceType = null; + corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(2); +// String uploadFilePath = uploadPath + folder3 + fileName; + //多页pdf需要转成多张jpg 2022/8/16 + Pdf2JpgHelper.pdfToOneImage(fileString,imgRealPath); + ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(fileString)); + if(null==ocrEntity||null==ocrEntity.getResult()||0==ocrEntity.getResult()){ + Pdf2JpgHelper.pdfToImages2AndSaveCache(null,UUID.randomUUID().toString(), fileString, watchPath, false, null==sysOrg?"":sysOrg.getCode(), null, corporateInvoiceType,0L,sysConfigMapper); + }else{ + type = 2; + } + } + dealResult(type,date, from, subject, imgUrlPath, pdfRealPath, ocrEntity); + }else if(fileString.toLowerCase().endsWith("xls")||fileString.toLowerCase().endsWith("xlsx")){ + // excel 分支 + + } + }catch (Exception e){ + log.error("public mail异常==》{}",e.getMessage()); + } + new File(fileString).delete(); + } + + } else { + List filesOcrsList = new ArrayList<>(); + for (Map.Entry entry : inputStreamMap.entrySet()) { + String k = entry.getKey(); + byte[] v = entry.getValue(); + log.info("获取附件名称>>{}", k); + // 新逻辑 保存文件判断文件类型 + if (k.endsWith(".PDF") || k.endsWith(".pdf")) { + + String newPDFName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".pdf"; + String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; + String pdfRealPathAll = invoicePic + java.io.File.separator + folder+ datePath+File.separator + newPDFName; + // 弗兰德的形式发票 + String imgRealPath = invoicePic + java.io.File.separator + folder+ datePath+File.separator + newImgName; + String imgUrlPath = domainName + contextPath + imgVirtualPath + "/" + folder+ datePath+"/" + newImgName; + + try{ + saveFile(pdfRealPathAll,v); + }catch (IOException e){ + log.info("保存文件错误{},:{}",newPDFName,e.getMessage()); + } + String pdfRealPath = domainName + contextPath + imgVirtualPath + "/" + folder+ "/" + newPDFName; + log.info("原Pdf图片地址:>>{}", pdfRealPathAll); + String ndSearchCode = "classify"; + JSONObject jsonDataResult = ndOcrService.ndApiRequest(ndSearchCode,new File(pdfRealPathAll)); + if(null == jsonDataResult){ + log.error("addProcessForExtract===nd api response not setting or error"); + return; + } + String fileType = jsonDataResult.getJSONObject("json_data").getString("type"); + log.info("邮件附件fileType=》{}",fileType); + if("国内发票".equals(fileType)){ + SysEmp sysEmp = sysEmpMapper.selectByEmail(from); + int orgId = sysEmp.getOrgId(); + SysOrg sysOrg = sysOrgMapper.selectByPrimaryKey(orgId); + CorporateInvoiceType corporateInvoiceType = null; + corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(2); +// String uploadFilePath = uploadPath + folder3 + fileName; + //多页pdf需要转成多张jpg 2022/8/16 + Pdf2JpgHelper.pdfToOneImage(pdfRealPathAll,imgRealPath); + ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(pdfRealPathAll)); + if(null==ocrEntity||null==ocrEntity.getResult()||0==ocrEntity.getResult()){ + Pdf2JpgHelper.pdfToImages2AndSaveCache(null,UUID.randomUUID().toString(), pdfRealPathAll, watchPath, false, null==sysOrg?"":sysOrg.getCode(), null, corporateInvoiceType,0L,sysConfigMapper); + }else{ + type = 2; + } + } + else if("海外形式发票".equals(fileType)){ + type = 1; + Pdf2JpgHelper.pdfToOneImage(pdfRealPathAll,imgRealPath); +// SysOrg sysOrg = sysOrgMapper.selectByCode(com); + // 通过 HF AI 接口解析 形式发票 + File pdfFile = new File(pdfRealPathAll); + ocrEntity = ruiZhenOCRService.billsCropFHOfnd("proforma_invoice",pdfFile); + } + else if ("合同".equals(fileType)){ + // 未找到 + } + else if ("餐饮小票".equals(fileType)){ + // 未找到 + } + else if ("会议照片".equals(fileType)){ + // 未找到 + } + else if ("住宿水单".equals(fileType)){ + // 未找到 + } + else if ("网约车行程单".equals(fileType)){ + // 未找到 + type = 2; + Pdf2JpgHelper.pdfToOneImage(pdfRealPathAll,imgRealPath); +// SysOrg sysOrg = sysOrgMapper.selectByCode(com); + // 通过 HF AI 接口解析 形式发票 + File pdfFile = new File(pdfRealPathAll); + JSONObject ndJsonDataResult = ruiZhenOCRService.ndApiRequest(ndSearchCode,pdfFile); + ocrEntity = ruiZhenOCRService.billsCropFHOfnd("ride_hailing",pdfFile); + } + else if ("海关报关单".equals(fileType)){ + // 未找到 + } + else if ("未枚举类型".equals(fileType)){ + // 未找到 + } + + + + + dealResult(type,date, from, subject, imgUrlPath, pdfRealPath, ocrEntity); + }else if(k.toLowerCase().endsWith("xls")||k.toLowerCase().endsWith("xlsx")){ + // excel 分支 + + } + } + } + // 循环结束后 将附件插入到 附件表关联corinvoice + if (null != pId) { + // 保存对账单 & 发票清单 + log.info("dzdFilePath:====={}", dzdFilePath); + if (null != dzdFilePath) { + com.cmsen.ticket.domain.entity.File dzd = new com.cmsen.ticket.domain.entity.File(); + dzd.setUploadTime(new Date()); + dzd.setDescription(dzdName); + dzd.setPath(dzdFilePath); + dzd.setPid(pId); + dzd.setType("其他"); + dzd.setUri(dzdUrlPath); + fileMapper.insert(dzd); + } + log.info("fpqdFilePath:====={}", fpqdFilePath); + if (null != fpqdFilePath) { + com.cmsen.ticket.domain.entity.File fpqd = new com.cmsen.ticket.domain.entity.File(); + fpqd.setUploadTime(new Date()); + fpqd.setDescription(fpqdName); + fpqd.setPath(fpqdFilePath); + fpqd.setPid(pId); + fpqd.setType("其他"); + fpqd.setUri(fpqdUrlPath); + fileMapper.insert(fpqd); + } + } + if (pId != null) { + for (FilesOcr filesOcr : fjFilesOcr) { + filesOcr.setInvoiceId(pId); + filesOcrMapper.insert(filesOcr); + } + for (com.cmsen.ticket.domain.entity.File fjFile : fjFiles) { + fjFile.setPid(pId); + fileMapper.insert(fjFile); + } + } + } else { + //发送反馈 + log.warn("非系统设置邮箱>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", from); + } + } + + private void dealResult(int type,String date, String from, String subject, String imgRealPath, String pdfRealPath, RuiZhenOCREntity ruiZhenOCREntity) { + List results = ruiZhenOCREntity.getResponse().getData().getIdentify_results(); + for (RuiZhenOCREntity.IdentifyResults result : results) { + if (result.getType().equals("10900")) { + break; + } + Details details = result.getDetails(); + PostBox postBox = new PostBox(); + postBox.setSubject(subject); + postBox.setUserId(0); + postBox.setFilePath(imgRealPath); + postBox.setIdentifyResult(JsonUtil.toString(ruiZhenOCREntity)); + postBox.setFrom(from); + postBox.setReceiveDate(date); + postBox.setBuyer(details.getSeller()); + postBox.setInvoiceMoney(details.getTotal()); + postBox.setInvoiceDate(StringUtil.isEmpty(details.getDate()) ? date : details.getDate()); + postBox.setInvoiceNum(details.getNumber()); + postBox.setType(1); + postBox.setOriginalPath(pdfRealPath); + int i = postBoxMapper.checkRepeat(details.getNumber()); + if (i > 0) { + postBox.setRepeat(true); + } + TicketType ticketType = ticketTypeMapper.selectByCode(result.getType()); + //postBox.setTicketType(ticketType == null ? "未知发票" : ticketType.getValue()); + postBox.setTicketType(result.getType()); + postBox.setCreateTime(new Date()); + postBoxMapper.insertSelective(postBox); + log.info("识别附件结果>>SUCCESS>>{}", postBox); + + //2023-05-17 从sys_config 中获取获取配置信息 + SysConfig publicMailChk = sysConfigMapper.selectByCode("PUBLIC_MAIL_CHK"); + + // 2023-06-13 从sys_config 中获取 user信息 + SysConfig supplierAdmin = sysConfigMapper.selectByCode("Supplier_Admin"); + + boolean flagForMail = true; + if(null!=publicMailChk&&"0".equals(publicMailChk.getValue())){ + flagForMail = false; + } + + //判断from是否存在sys_user表 2022/6/1 + SysEmp sysUser = sysEmpMapper.selectByEmail(from.toLowerCase()); + if(sysUser == null && flagForMail){ + String text = "邮件地址【"+from+"】对应的组织不存在,请联系管理员"; + sendMailService.sendVerifiedText(from, text); + }else{ + if(flagForMail && null != sysUser && sysUser.getOrgId() == 0){ + String text = "邮件地址【"+from+"】对应的组织不存在,请联系管理员"; + sendMailService.sendVerifiedText(from, text); + }else{ + Integer userId = null; + if(null == sysUser){ + if(null != supplierAdmin){ + userId = Integer.valueOf(supplierAdmin.getValue()); + } + } + + //识别发票并发往维泰 + String uuid = StringUtil.UUID(); + CorporateInvoice corporateInvoice = new CorporateInvoice(); + corporateInvoice.setId(uuid); +// corporateInvoice.setOwner(userId); + corporateInvoice.setTitle(details.getSeller()); + corporateInvoice.setSeller(details.getSeller()); + corporateInvoice.setSellerNo(details.getSeller_tax_id()); + corporateInvoice.setCode(StringUtil.isEmpty(details.getCode())?"0000":details.getCode()); + corporateInvoice.setNumber(details.getNumber()); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getDate())){ + corporateInvoice.setDate(details.getDate().replace(" ","")); + } + corporateInvoice.setTotal(details.getTotal().replace(",","")); + corporateInvoice.setImgPath(imgRealPath); + corporateInvoice.setRemark(details.getRemark()); + //corporateInvoice.setExtraFields(); + corporateInvoice.setUpdateDate(new Date()); + corporateInvoice.setBuyer(details.getBuyer()); + corporateInvoice.setBuyerNo(details.getBuyer_tax_id()); + corporateInvoice.setTicketCode(result.getType()); + corporateInvoice.setKind(details.getKind()); + corporateInvoice.setStatus(0); + corporateInvoice.setOriginalFilePath(pdfRealPath); + corporateInvoice.setVerifiedCode(details.getCheck_code()); + if(null!=details.getPretax_amount()){ + corporateInvoice.setPretaxAmount(details.getPretax_amount().replace(",","")); + }else{ + corporateInvoice.setPretaxAmount(details.getPretax_amount()); + } + corporateInvoice.setTax(details.getTax()); + corporateInvoice.setOperatorId(userId);//插入from邮箱的userid 2022/6/9 + corporateInvoice.setCreateDate(new Date()); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getTitle())){ + corporateInvoice.setCurrency(details.getTitle()); + }else{ + corporateInvoice.setCurrency("CNY"); + } + + corporateInvoice.setChecked(0); + corporateInvoice.setPo(StringUtils.getPO(details.getRemark())); + corporateInvoice.setValidStatus((byte) 0); + corporateInvoice.setValidCount(0); + corporateInvoice.setValidDayCount(0); + corporateInvoice.setDetails(details.getItem_names()); + //corporateInvoice.setInvoiceType(); + corporateInvoice.setIsSend(0); + corporateInvoice.setUseStatus(9); + corporateInvoice.setMatchStatus(0); + + //增加保存字段 2022/8/16 + corporateInvoice.setNumberBackup(details.getNumberBackup()); + corporateInvoice.setNumberConfirm(details.getNumber_confirm()); + corporateInvoice.setCompanySeal(details.getCompany_seal()); + + corporateInvoice.setDataJson(JsonUtil.toString(result)); + //增加发票接收实体 2022/6/1 + if(2==type){ + ruiZhenOCRService.verifyCorporateInvoice(corporateInvoice); + } + if (corporateInvoice.getStatus()==2) {//验真、合规失败 --发送邮件给运维支持人员 + String text = "邮件发票导入【"+corporateInvoice.getNumber()+"】异常"; + //得到运维支持人员邮箱 sys_config中SUPPORT_MAIL + SysConfig sysConfig = sysConfigMapper.selectByCode("SUPPORT_MAIL"); + if(null==sysConfig){ + + }else{ + String[] split = sysConfig.getValue().split(","); + for (String email : split) { + sendMailService.sendVerifiedText(email, text); + } + } + }else{ + //新增合规逻辑 + StringBuilder message = new StringBuilder(); + corporateInvoiceService.validationRules(corporateInvoice, message, ticketType); + log.info("===corporateInvoice1.getStatus()2:{}",corporateInvoice.getStatus()); + corporateInvoice.setMessage(message.toString()); + } + SysConfig ext08Config = sysConfigMapper.selectByCode("Corporate_Invoice_Ext08_Default"); + if(null==ext08Config){ + corporateInvoice.setExt08("2"); + }else{ + corporateInvoice.setExt08(ext08Config.getValue()); + } + //合规逻辑 +// StringBuilder message = new StringBuilder(); +// List ruleConfigs = ruleConfigMapper.selectByClientAndTicketType(1, ticketType.getId(), 1); +// Map> ruleMap = ruleConfigs.stream().collect(Collectors.groupingBy(ruleConfig -> ruleConfig.getRuleInfo().getName())); +// if (ruleMap.containsKey("票号重复规则")) { +// log.info("票号重复规则1>>NUM>>{}>>CODE>>{}", corporateInvoice.getNumber(), corporateInvoice.getCode()); +// RuleConfig duplicatedNum = ruleMap.get("票号重复规则").get(0); +// Rule ruleInfo = duplicatedNum.getRuleInfo(); +// int count = corporateInvoiceMapper.checkInvoiceNumIsExistByNumAndCode(corporateInvoice.getNumber(), corporateInvoice.getCode(),null); +// if (count > 0) { +// log.info("票号重复规则>>Result>>{}", false); +// message.append(ruleInfo.getMessageCn()).append(";"); +// corporateInvoice.setStatus(2); +// } +// } +// +// if (corporateInvoice.getStatus().equals("2")) {//验真、合规失败 --发送邮件给运维支持人员 +// String text = "邮件发票导入【"+corporateInvoice.getNumber()+"】异常"; +// //得到运维支持人员邮箱 sys_config中SUPPORT_MAIL +// SysConfig sysConfig = sysConfigMapper.selectByCode("SUPPORT_MAIL"); +// String[] split = sysConfig.getValue().split(","); +// for (String email : split) { +// sendMailService.sendVerifiedText(email, text); +// } +// } + + + + corporateInvoice.setMatchStatus(0); + + //增加赋值 2022/6/1 + corporateInvoice.setInvoiceType(1); + corporateInvoice.setMatchType(0);//金额 + corporateInvoice.setPriceType(0);//折后 + + //2023-05-17 + log.info("flagForMail=>{}",flagForMail); + if(flagForMail){ + // 如果配置1 走原来的逻辑 + log.info("sysUser.getOrgId()=>{}",sysUser.getOrgId()); + corporateInvoice.setOrgId(sysUser.getOrgId()); + }else{ + // 如果配置非1 则 需要从sysconfig中找到org + SysConfig mailOrg = sysConfigMapper.selectByCode("PUBLIC_MAIL_ORG"); + if(null != mailOrg){ + log.info("mailOrg.getValue()=》{}",mailOrg.getValue()); + corporateInvoice.setOrgId(Integer.parseInt(mailOrg.getValue())); + }else{ + // 这里暂时不处理 + log.error("===>>>> CODE PUBLIC_MAIL_ORG not find in table SYS_CONFIG"); + } + } + + // 处理附件 + String indexOfPath = "/opt"; + if(pdfRealPath.contains("/opt")){ + String filePath = pdfRealPath.substring(pdfRealPath.indexOf(indexOfPath)); + String originFileNamePath = viewPath + filePath; + log.info("originFileNamePath=>{}",originFileNamePath); + corporateInvoice.setOriginalFilePath(originFileNamePath); + } + + // 发票日期+发票号后8位+供应商名称 + String sufix = pdfRealPath.substring(pdfRealPath.lastIndexOf(".")); + String number = corporateInvoice.getNumber(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(number) && number.length() >= 8) { + number = number.substring(number.length() - 8); + } + + String yearMonthDate = corporateInvoice.getDate(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(yearMonthDate)) { + yearMonthDate = yearMonthDate.replace("年", ""); + yearMonthDate = yearMonthDate.replace("月", ""); + yearMonthDate = yearMonthDate.replace("日", ""); + } + + //2023-08-13 根据系统配置 采用公司的中文和英文code名称 + String comName = null; + SysConfig imgVendorName = sysConfigMapper.selectByCode("img_vendor_name"); + if(null != imgVendorName){ + String imgVendorNameValue = imgVendorName.getValue(); + if(null != imgVendorNameValue && "code".equals(imgVendorNameValue)) { + List suppliers = supplierMapper.selectByTaxNo(corporateInvoice.getSellerNo()); + if(!suppliers.isEmpty()){ + comName = suppliers.get(0).getCode(); + }else{ + comName = ""; + } + } + } + if(null == comName){ + comName = corporateInvoice.getSeller(); + } + String randomId = UUID.randomUUID().toString().substring(0,2); + String newOriginFileName = yearMonthDate+number+comName+randomId+sufix; +// String urlNewOriginFileName = URLEncoder.encode(newOriginFileName); + String oldFileUploadPath = uploadPath + pdfRealPath.substring(pdfRealPath.indexOf(indexOfPath)); + String parentPath = oldFileUploadPath.substring(0, oldFileUploadPath.lastIndexOf(java.io.File.separator)); + + if (parentPath.endsWith(java.io.File.separator)) { + + } else { + parentPath = parentPath + java.io.File.separator; + } + + log.info("pdfPath 2===>{}",oldFileUploadPath); + File oldFile = new File(oldFileUploadPath); + // 先重命名 + boolean flag = oldFile.renameTo(new File(parentPath + File.separator + newOriginFileName)); + // 不成功则复制 删除源文件 + if (!flag) { + log.info("flag=>{}",flag); + try { + FileUtils.copyFile(oldFile, new File(parentPath + File.separator + newOriginFileName)); + // 成功后删除 + oldFile.delete(); + flag = true; + } catch (Exception e) { + log.error("copy file error!"); + e.printStackTrace(); + } + } + + // originalPath 是 + String originalPath = corporateInvoice.getOriginalFilePath(); + if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPath)) { + String originalParent = originalPath.substring(0, originalPath.lastIndexOf("/")); + if (!originalParent.endsWith("/")) { + originalParent = originalParent + "/"; + } + String newOFP = originalParent + newOriginFileName; + corporateInvoice.setOriginalFilePath(newOFP); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt02())){ + corporateInvoice.setExt02(details.getExt02()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt03())){ + corporateInvoice.setExt03(details.getExt03()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt04())){ + corporateInvoice.setExt04(details.getExt04()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt05())){ + corporateInvoice.setExt05(details.getExt05()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt06())){ + corporateInvoice.setExt06(details.getExt06()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt07())){ + corporateInvoice.setExt07(details.getExt07()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt09())){ + corporateInvoice.setExt09(details.getExt09()); + } + if(org.apache.commons.lang3.StringUtils.isNotEmpty(details.getExt10())){ + corporateInvoice.setExt10(details.getExt10()); + } + + corporateInvoiceMapper.insert(corporateInvoice); + pId = corporateInvoice.getId(); + //验真结果后的item获取插入 2022/6/1 + if(2==type){ + List corporateInvoiceItems = corporateInvoice.getItems(); + for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + corporateInvoiceItemsMapper.insert(corporateInvoiceItem); + } + }else{ + List items = ruiZhenOCREntity.getResponse().getData().getIdentify_results().get(0).getDetails().getItems(); + log.info("items.size()==========={}",items.size()); + for (Item item : items) { + CorporateInvoiceItems invoiceItems = new CorporateInvoiceItems(); + invoiceItems.setId(StringUtil.UUID()); + invoiceItems.setPid(corporateInvoice.getId()); + invoiceItems.setName(item.getName()); + invoiceItems.setSpecification(item.getSpecification()); + invoiceItems.setTaxRate(item.getTax_rate()); + if(StringUtil.isNotEmpty(item.getTax())){ + invoiceItems.setTax(item.getTax().replace(",","")); + }else{ + invoiceItems.setTax("0"); + } + log.info("item.getTotal():{}",item.getTotal()); + if(StringUtil.isNotEmpty(item.getTotal())){ + invoiceItems.setTotal(item.getTotal().replace(",","")); + }else{ + invoiceItems.setTotal("0"); + } + if(StringUtil.isNotEmpty(item.getPrice())){ + invoiceItems.setPrice(item.getPrice().replace(",","")); + }else{ + invoiceItems.setPrice("0"); + } + if(StringUtil.isNotEmpty(item.getQuantity())){ + invoiceItems.setQuantity(item.getQuantity().replace(",","")); + }else{ + invoiceItems.setQuantity("0"); + } + log.info("invoiceItems.getTotal():{}",invoiceItems.getTotal()); + invoiceItems.setUnit(item.getUnit()); + invoiceItems.setUsedAmount(new BigDecimal(0)); + invoiceItems.setUnUsedAmount(new BigDecimal(0)); + invoiceItems.setUnUsedQuantity(new BigDecimal(0)); + invoiceItems.setDeductionAmount(""); + corporateInvoiceItemsMapper.insert(invoiceItems); + } + } + + // 发送OA + if (corporateInvoice.getStatus().equals(0)) { + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByPrimaryKey(corporateInvoice.getInvoiceType()); + if (corporateInvoiceType != null && corporateInvoiceType.getSendType() == 1) { + supplierOutService.sendInvoice(corporateInvoice, applicationName, "0"); + corporateInvoiceMapper.updateByPrimaryKeySelective(corporateInvoice); + } + } + CorporateInvoice fresh = corporateInvoiceMapper.selectByPrimaryKey(corporateInvoice.getId()); + sysCorInvoiceService.updatePOAndHTBH(fresh); + sysCorInvoiceService.updateSellerAndBuyerNo(type,fresh); + String succesStr="邮件发票导入【"+corporateInvoice.getNumber()+"】成功"; + sendMailService.sendVerifiedText(from, succesStr); + /*for (CorporateInvoiceItems corporateInvoiceItem : corporateInvoiceItems) { + corporateInvoiceItemsMapper.insert(corporateInvoiceItem); + }*/ + + + } + } + } + } + + + private void getFileInputStream(Part part, Map inputStreamMap) throws Exception { + String fileName; + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { + fileName = mPart.getFileName(); + // 为空判断20231024 + if(fileName==null)continue; +// if (fileName.toLowerCase().contains("gb2312")) { + fileName = MimeUtility.decodeText(fileName); +// } + inputStreamMap.put(fileName, mPart.getInputStream()); + } else if (mPart.isMimeType("multipart/*")) { + log.info("子邮件里面的附件"); + getFileInputStream(mPart, inputStreamMap); + } else { + fileName = mPart.getFileName(); + if (fileName != null) { + fileName = MimeUtility.decodeText(fileName); + inputStreamMap.put(fileName, mPart.getInputStream()); + } + } + } + } else if (part.isMimeType("message/rfc822")) { + getFileInputStream((Part) part.getContent(), inputStreamMap); + } + } + + private boolean isContainAttach(Part part) throws Exception { + boolean attachFlag = false; + // String contentType = part.getContentType(); + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) + && ((disposition.equals(Part.ATTACHMENT)) || (disposition + .equals(Part.INLINE)))) { + attachFlag = true; + } else if (mPart.isMimeType("multipart/*")) { + attachFlag = isContainAttach(mPart); + } else { + String conType = mPart.getContentType(); + + if (conType.toLowerCase().contains("application")) { + attachFlag = true; + } + if (conType.toLowerCase().contains("name")) { + attachFlag = true; + } + } + } + } else if (part.isMimeType("message/rfc822")) { + attachFlag = isContainAttach((Part) part.getContent()); + } + return attachFlag; + } + + private String getFrom(Message msg) throws MessagingException { + String from = ""; + InternetAddress[] addresses = (InternetAddress[]) msg.getFrom(); + if (null == addresses || addresses.length == 0) { + log.error("无法获取发送人地址信息!"); + return from; + } + Address address = addresses[0]; + log.info("发件人地址json:" + JsonUtil.toString(address)); + String form = ((InternetAddress) address).getAddress(); + return form; + } + + private void close() { + if (store != null) { + try { + store.close(); + } catch (MessagingException e) { + log.error(e.getMessage(), e); + } + } + } + + private void saveFile(String pdfRealPathAll,byte[] v) throws IOException { + FileOutputStream os = new FileOutputStream(pdfRealPathAll); + os.write(v); + os.flush(); + } + + private void getFileInputStream2(Part part, Map inputStreamMap) throws Exception { + String fileName; + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart) part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + BodyPart mPart = mp.getBodyPart(i); + String disposition = mPart.getDisposition(); + if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { + fileName = mPart.getFileName(); + // 为空判断20231024 + if(fileName==null)continue; + fileName = MimeUtility.decodeText(fileName); + byte[] bytes = FileUtil.getBytes(mPart.getInputStream(), 1024); + inputStreamMap.put(fileName, bytes); + } else if (mPart.isMimeType("multipart/*")) { + log.info("MailPublicTask 子邮件里面的附件"); + getFileInputStream2(mPart, inputStreamMap); + } else { + fileName = mPart.getFileName(); + if ((fileName != null)) { + fileName = MimeUtility.decodeText(fileName); + byte[] bytes = FileUtil.getBytes(mPart.getInputStream(), 1024); + inputStreamMap.put(fileName, bytes); + } + } + } + } else if (part.isMimeType("message/rfc822")) { + getFileInputStream2((Part) part.getContent(), inputStreamMap); + } + } + + public void traverseFolder(File folder,List dealList) throws Exception { + if (!folder.exists() || !folder.isDirectory()) { + System.err.println("无效的文件夹路径: " + folder.getAbsolutePath()); + return; + } + + for (File file : Objects.requireNonNull(folder.listFiles())) { + if (file.isDirectory()) { + System.out.println("[目录] " + file.getAbsolutePath()); + traverseFolder(file,dealList); // 递归处理子目录 + } else { + if(file.getAbsolutePath().toLowerCase().endsWith(".ofd")){ + String pdfPath =file.getAbsolutePath().replace(".ofd",".pdf"); + OFDUtil.convertToPdf(file.getAbsolutePath(),file.getAbsolutePath().replace(".ofd",".pdf"),12); + dealList.add(pdfPath); + }else{ + dealList.add(file.getAbsolutePath()); + } + System.out.println("[文件] " + file.getName() + + " | 大小: " + file.length() + " bytes"); + } + } + } + + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/FtpUtils.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/FtpUtils.java new file mode 100644 index 0000000..09b7a60 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/FtpUtils.java @@ -0,0 +1,320 @@ +package com.cmsen.ticket.infrastructure.tools; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.net.MalformedURLException; + +/** + * @Auther: xp + * @Date: 2020/8/27 + * @Description: com.jeeplus.modules.tools.utils.ftp + * @version: 1.0 + */ + +public class FtpUtils { + + protected Logger logger = LoggerFactory.getLogger(getClass()); + public FTPClient ftpClient = null; + + /** + * 初始化ftp服务器 + * @param host ftp服务器地址 + * @param userName ftp登录账号 + * @param password ftp登录密码 + * @param port ftp服务器端口号默认为21 + */ + public void initFtpClient(String host,String userName,String password,int port) { + ftpClient = new FTPClient(); + ftpClient.setControlEncoding("utf-8"); + try { + logger.info("connecting...ftp服务器:"+host+":"+ port); + ftpClient.enterLocalPassiveMode();//ftp数据传输有两种模式:FTP Port模式和FTP Passive模式 + ftpClient.connect(host, port); //连接ftp服务器 + ftpClient.login(userName, password); //登录ftp服务器 + int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器 + if(!FTPReply.isPositiveCompletion(replyCode)){ + logger.info("connect failed...ftp服务器:"+host+":"+port); + } + logger.info("connect successfull...ftp服务器:"+host+":"+port); + }catch (MalformedURLException e) { + logger.error(e.getMessage()); + }catch (IOException e) { + logger.error(e.getMessage()); + } + } + + /** + * 上传文件 + * @param pathname ftp服务保存地址 + * @param fileName 上传到ftp的文件名 + * @param originfilename 待上传文件的名称(绝对地址) * + * @return + */ + public boolean uploadFile( String pathname, String fileName,String originfilename){ + boolean flag = false; + InputStream inputStream = null; + try{ + System.out.println("开始上传文件"); + inputStream = new FileInputStream(new File(originfilename)); + //initFtpClient(); + ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE); +// CreateDirecroty(pathname); +// ftpClient.makeDirectory(pathname); + ftpClient.changeWorkingDirectory(pathname); + ftpClient.storeFile(fileName, inputStream); + inputStream.close(); + ftpClient.logout(); + flag = true; + logger.info("上传文件成功"); + }catch (Exception e) { + flag = false; + e.printStackTrace(); + logger.info("上传文件失败"); + logger.error(e.getMessage()); + }finally{ + if(null != inputStream){ + try { + inputStream.close(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + } + } + return flag; + } + /** + * 上传文件 + * @param pathname ftp服务保存地址 + * @param fileName 上传到ftp的文件名 + * @param inputStream 输入文件流 + * @return + */ + public boolean uploadFile( String pathname, String fileName,InputStream inputStream){ + boolean flag = false; + try{ + System.out.println("开始上传文件"); + //initFtpClient(); + ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE); + CreateDirecroty(pathname); + ftpClient.makeDirectory(pathname); + ftpClient.changeWorkingDirectory(pathname); + ftpClient.storeFile(fileName, inputStream); + inputStream.close(); + ftpClient.logout(); + flag = true; + logger.info("上传文件成功"); + }catch (Exception e) { + logger.error("上传文件失败"); + logger.error(e.getMessage()); + e.printStackTrace(); + }finally{ + + if(null != inputStream){ + try { + inputStream.close(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + } + } + return true; + } + //改变目录路径 + public boolean changeWorkingDirectory(String directory) { + boolean flag = true; + try { + flag = ftpClient.changeWorkingDirectory(directory); + if (flag) { + logger.info("进入文件夹" + directory + " 成功!"); + + } else { + logger.info("进入文件夹" + directory + " 失败!开始创建文件夹"); + } + } catch (IOException ioe) { + logger.error(ioe.getMessage()); + } + return flag; + } + + public FTPFile[] listFiles(String ftpDir){ + FTPFile[] list = null; + try { + list = ftpClient.listFiles(ftpDir); + } catch (IOException ioe) { + ioe.printStackTrace(); + logger.error(ioe.getMessage()); + } + return list; + } + + //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建 + public boolean CreateDirecroty(String remote) throws IOException { + boolean success = true; + String directory = remote + "/"; + // 如果远程目录不存在,则递归创建远程服务器目录 + if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) { + int start = 0; + int end = 0; + if (directory.startsWith("/")) { + start = 1; + } else { + start = 0; + } + end = directory.indexOf("/", start); + String path = ""; + String paths = ""; + while (true) { + String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); + path = path + "/" + subDirectory; + if (!existFile(path)) { + if (makeDirectory(subDirectory)) { + changeWorkingDirectory(subDirectory); + } else { + logger.info("创建目录[" + subDirectory + "]失败"); + changeWorkingDirectory(subDirectory); + } + } else { + changeWorkingDirectory(subDirectory); + } + + paths = paths + "/" + subDirectory; + start = end + 1; + end = directory.indexOf("/", start); + // 检查所有目录是否创建完毕 + if (end <= start) { + break; + } + } + } + return success; + } + + //判断ftp服务器文件是否存在 + public boolean existFile(String path) throws IOException { + boolean flag = false; + FTPFile[] ftpFileArr = ftpClient.listFiles(path); + if (ftpFileArr.length > 0) { + flag = true; + } + return flag; + } + //创建目录 + public boolean makeDirectory(String dir) { + boolean flag = true; + try { + flag = ftpClient.makeDirectory(dir); + if (flag) { + logger.info("创建文件夹" + dir + " 成功!"); + + } else { + logger.info("创建文件夹" + dir + " 失败!"); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + return flag; + } + + /** * 下载文件 * + * @param pathname FTP服务器文件目录 * + * @param filename 文件名称 * + * @param localpath 下载后的文件路径 * + * @return */ + public boolean downloadFile(String pathname, String filename, String localpath){ + boolean flag = false; + OutputStream os=null; + try { + System.out.println("开始下载文件"); + //initFtpClient(); + //切换FTP目录 + ftpClient.changeWorkingDirectory(pathname); + FTPFile[] ftpFiles = ftpClient.listFiles(); + for(FTPFile file : ftpFiles){ + if(filename.equalsIgnoreCase(file.getName())){ + File localFile = new File(localpath + "/" + file.getName()); + os = new FileOutputStream(localFile); + ftpClient.retrieveFile(file.getName(), os); + os.close(); + } + } + flag = true; + logger.info("下载文件成功"); + } catch (Exception e) { + logger.error("下载文件失败"); + logger.error(e.getMessage()); + } finally{ + + if(null != os){ + try { + os.close(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + } + } + return flag; + } + + /** * 删除文件 * + * @param pathname FTP服务器保存目录 * + * @param filename 要删除的文件名称 * + * @return */ + public boolean deleteFile(String pathname, String filename){ + boolean flag = false; + try { + System.out.println("开始删除文件"); + //initFtpClient(); + //切换FTP目录 + ftpClient.changeWorkingDirectory(pathname); + ftpClient.dele(filename); + ftpClient.logout(); + flag = true; + logger.info("删除文件成功"); + } catch (Exception e) { + logger.error("删除文件失败"); + logger.error(e.getMessage()); + } + return flag; + } + + /** + * 关闭连接 + * @return + */ + public boolean closeFtp(){ + boolean flag = false; + + if(ftpClient.isConnected()){ + try{ + ftpClient.disconnect(); + }catch(IOException e){ + logger.error(e.getMessage()); + } + } + return flag; + } + + public static void main(String asd[]){ + String userName = "ftp0408"; + String password = "Today123"; + String host = "jump.haxcloud.com"; + String port = "6021"; + String xmlDir = "/XML_zip"; + FtpUtils ftp = null; + ftp = new FtpUtils(); + ftp.initFtpClient(host,userName,password,Integer.valueOf(port)); + ftp.changeWorkingDirectory(xmlDir); + ftp.ftpClient.enterLocalPassiveMode(); + ftp.ftpClient.setConnectTimeout(10000); + FTPFile[] ftpFiles = ftp.listFiles(xmlDir); + for (FTPFile ftpFile : ftpFiles) { + System.out.println(ftpFile.getName()); + } + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/SftpUtils.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/SftpUtils.java new file mode 100644 index 0000000..19aeb3e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/SftpUtils.java @@ -0,0 +1,291 @@ +package com.cmsen.ticket.infrastructure.tools; + +import com.jcraft.jsch.*; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.util.Properties; +import java.util.Vector; + +@Slf4j +@Data +public class SftpUtils { + + private ChannelSftp sftp; + + private Session session; + /** SFTP 登录用户名*/ + private String username; + /** SFTP 登录密码*/ + private String password; + /** 私钥 */ + private String privateKey; + /** SFTP 服务器地址IP地址*/ + private String host; + /** SFTP 端口*/ + private int port; + /** 私钥 密码 */ + private String passphrase; + /** + * 构造基于密码认证的sftp对象 + */ + public SftpUtils(String username, String password, String host, int port) { + this.username = username; + this.password = password; + this.host = host; + this.port = port; + } + + /** + * 构造基于秘钥认证的sftp对象 + */ + public SftpUtils(String username, String host, int port, String privateKey) { + this.username = username; + this.host = host; + this.port = port; + this.privateKey = privateKey; + } + + + /** + * 构造基于密码喝秘钥认证的sftp对象 + */ + public SftpUtils(String username, String passphrase, String host, int port, String privateKey) { + this.username = username; + this.host = host; + this.port = port; + this.privateKey = privateKey; + this.passphrase = passphrase; + } + + + public SftpUtils(){} + + + /** + * 连接sftp服务器 + */ + public void login(){ + try { + log.info("login SFTP ………………"); + JSch jsch = new JSch(); +// if (privateKey != null&&passphrase!=null) { +// jsch.addIdentity(privateKey,passphrase);// 设置私钥 +// }else{ +// if(null==passphrase){ +// jsch.addIdentity(privateKey);// 设置私钥 +// } +// } + session = jsch.getSession(username, host, port); + if (password != null) { + session.setPassword(password); + } + Properties config = new Properties(); + config.put("StrictHostKeyChecking", "no"); + + session.setConfig(config); + session.connect(); + Channel channel = session.openChannel("sftp"); + channel.connect(); + sftp = (ChannelSftp) channel; + } catch (JSchException e) { + e.printStackTrace(); + } + } + + /** + * 关闭连接 server + */ + public void logout(){ + if (sftp != null) { + if (sftp.isConnected()) { + sftp.disconnect(); + } + } + if (session != null) { + if (session.isConnected()) { + session.disconnect(); + } + } + } + + + /** + * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory + * @param basePath 服务器的基础路径 + * @param directory 上传到该目录 + * @param sftpFileName sftp端文件名 + */ + public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{ + try { + sftp.cd(basePath); + sftp.cd(directory); + } catch (SftpException e) { + //目录不存在,则创建文件夹 + String [] dirs=directory.split("/"); + String tempPath=basePath; + for(String dir:dirs){ + if(null== dir || "".equals(dir)) continue; + tempPath+="/"+dir; + try{ + sftp.cd(tempPath); + }catch(SftpException ex){ + sftp.mkdir(tempPath); + sftp.cd(tempPath); + } + } + } + sftp.put(input, sftpFileName); //上传文件 + } + + /** + */ + public void move(String basePath,String fileName,String newPath) throws SftpException{ + log.info("basePath=>{}",basePath); + try { + // 获取当前工作目录 + String currentDir = sftp.pwd(); + log.info("currentDir=>{}",currentDir); + // 只有不在目标目录时,才执行 cd + if (!basePath.equals(currentDir)) { + sftp.cd(basePath); + } + /*sftp.cd("/"); + sftp.cd(basePath);*/ + } catch (SftpException e) { + log.error("sftp移动方法错误",e.getMessage()); + e.printStackTrace(); + } + log.info("oldPath=>{}",fileName); + log.info("newPath=>{}",newPath+fileName); + sftp.rename(fileName,newPath+fileName); + } + + public void move2(String oldFilePath, String newFilePath) throws SftpException{ + log.info("最终移动:源={},目标={}", oldFilePath, newFilePath); + + try { + // ===================== 修复核心:自动重连 ===================== + if (sftp == null || !sftp.isConnected() || !session.isConnected()) { + log.info("SFTP 连接已断开,自动重连中..."); + logout(); + login(); + } + // ============================================================= + + // ====================================== + // 第一步:拆分路径 和 文件名(最关键!) + // ====================================== + // 源:/credit/cdf/xxx.cdf + // 目标:/credit/cdf/history/xxx.cdf + + // 截取最后一个 / 前面的路径 + String sourceDir = oldFilePath.substring(0, oldFilePath.lastIndexOf("/")); + String fileName = oldFilePath.substring(oldFilePath.lastIndexOf("/") + 1); + + // 目标只需要写相对路径:history/文件名 + String targetName = "history/" + fileName; + + // ====================================== + // 第二步:进入源文件所在目录(不要 cd /) + // ====================================== + sftp.cd(sourceDir); + + // ====================================== + // 第三步:创建 history 目录 + // ====================================== + try { + sftp.stat("history"); + } catch (Exception e) { + sftp.mkdir("history"); + } + + // ====================================== + // 第四步:使用相对路径 rename(必成功) + // ====================================== + sftp.rename(fileName, targetName); + + log.info("✅ 移动成功!"); + + } catch (Exception e) { + log.error("❌ 移动失败:", e); + throw e; + } + } + + public String stat(String basePath,String fileName) { + String res = null; + try { + log.error("hisFile====>{}",basePath+fileName); + sftp.lstat(basePath+fileName); + res = "exist"; + }catch (Exception e){ + log.error("{}====>{}",fileName,e.getMessage()); + res = "not exist"; + } + return res; + } + + /** + * 下载文件。 + * @param directory 下载目录 + * @param downloadFile 下载的文件 + * @param saveFile 存在本地的路径 + */ + public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{ + if (directory != null && !"".equals(directory)) { + sftp.cd(directory); + } + File file = new File(saveFile); + sftp.get(downloadFile, new FileOutputStream(file)); + } + + /** + * 下载文件 + * @param directory 下载目录 + * @param downloadFile 下载的文件名 + * @return 字节数组 + */ + public byte[] download(String directory, String downloadFile) throws SftpException, IOException{ + if (directory != null && !"".equals(directory)) { + sftp.cd(directory); + } + InputStream is = sftp.get(downloadFile); + + byte[] fileData = IOUtils.toByteArray(is); + + return fileData; + } + + + /** + * 删除文件 + * @param directory 要删除文件所在目录 + * @param deleteFile 要删除的文件 + */ + public void delete(String directory, String deleteFile) throws SftpException{ + sftp.cd(directory); + sftp.rm(deleteFile); + } + + + /** + * 列出目录下的文件 + * @param directory 要列出的目录 + */ + public Vector listFiles(String directory) throws SftpException { + return sftp.ls(directory); + } + + //上传文件测试 + public static void main(String[] args) throws SftpException, IOException { + SftpUtils sftp = new SftpUtils("menarini", "Menarini8520!#%", "39.99.217.219", 22); + sftp.login(); + File file = new File("D:\\1.png"); + InputStream is = new FileInputStream(file); + sftp.upload("/","upload/CSV/300", "test_sftp.jpg", is); + sftp.logout(); + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/SnowflakeConnection.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/SnowflakeConnection.java new file mode 100644 index 0000000..c6f5e8f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/SnowflakeConnection.java @@ -0,0 +1,122 @@ +//package com.cmsen.ticket.infrastructure.tools; +// +//import org.apache.commons.lang3.StringUtils; +// +//import java.io.BufferedReader; +//import java.io.FileReader; +//import java.io.IOException; +//import java.security.KeyFactory; +//import java.security.PrivateKey; +//import java.security.spec.PKCS8EncodedKeySpec; +//import java.sql.Connection; +//import java.sql.DriverManager; +//import java.sql.ResultSet; +//import java.sql.SQLException; +//import java.sql.Statement; +//import java.util.Base64; +//import java.util.Properties; +// +//public class SnowflakeConnection { +// private static final String USERNAME = "PU_PROD_IBS_AP"; +// private static final String PASSWORD = ""; +// private static final String ROLE = "RL_PROD_IBS_AP"; +// private static final String WAREHOUSE = "WH_PROD_IBS_AP"; +// private static final String DATABASE = "PRODUCTION"; +// private static final String SCHEMA = "CONSUMPTION"; +// private static final String ACCOUNT = "NN51564.cn-northwest-1"; +// private static final String PRIVATE_KEY_FILE = "E:\\桌面\\音梦达\\PU_PROD_IBS_AP_KEY-PROD.p8"; +// public static void main(String[] args) { +// // 构建JDBC连接URL +// String jdbcUrl = String.format( +//// "jdbc:snowflake://%s.snowflakecomputing.com/?user=%s&password=%s&warehouse=%s&db=%s&schema=%s", +//// ACCOUNT, USERNAME, PASSWORD, WAREHOUSE, DATABASE, SCHEMA +// "jdbc:snowflake://%s.aws.snowflakecomputing.cn/?user=%s&warehouse=%s&db=%s&schema=%s", +// ACCOUNT, USERNAME, WAREHOUSE, DATABASE, SCHEMA +// ); +// +// Connection connection = null; +// Statement statement = null; +// ResultSet resultSet = null; +// try { +// // 加载Snowflake JDBC驱动 +// Class.forName("net.snowflake.client.jdbc.SnowflakeDriver"); +//// 读取私钥 +// PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE); +// +// // 设置连接属性 +// Properties properties = new Properties(); +// properties.put("privateKey", privateKey); +// // 关键配置:使用SNOWFLAKE_JWT认证 +// properties.put("authenticator", "SNOWFLAKE_JWT"); +// // 建立数据库连接 +// connection = DriverManager.getConnection(jdbcUrl,properties); +// +// // 创建Statement对象 +// statement = connection.createStatement(); +// +// // 执行SQL查询 +// String sql = "select LAND1 countryCode" + +// ",BUKRS companyCode" + +// ",VENDOR_DES_EN enName" + +// ",VENDOR_DES_CN cnName" + +// ",STCD3 taxNo" + +// ",MANDT sapClient" + +// ",LIFNR supplierCode from V_OI_VENDOR_IBSAP where LAND1 !='CN' limit 1"; +//// "ORDER BY table_catalog, table_schema, table_name;\n"; +// resultSet = statement.executeQuery(sql); +// +// // 处理查询结果 +// System.out.println("Snowflake连接成功!"); +// while (resultSet.next()) { +// System.out.println("国家编码: " + resultSet.getString(1)); +// System.out.println("公司编码: " + resultSet.getString(2)); +// System.out.println("英文名称: " + resultSet.getString(3)); +// System.out.println("中文名称: " + resultSet.getString(4)); +// System.out.println("税号: " + resultSet.getString(5)); +// System.out.println("sapClient: " + resultSet.getString(6)); +// if(!"CN".equals(resultSet.getString(1))&& StringUtils.isEmpty(resultSet.getString(5))){ +// System.out.println("供应商编码: " + resultSet.getString(7)); +// } +// } +// } catch (SQLException | ClassNotFoundException e) { +// e.printStackTrace(); +// } catch (Exception e) { +// e.printStackTrace(); +// } finally { +// // 关闭连接 +// if (connection != null) { +// try { +// connection.close(); +// } catch (SQLException e) { +// e.printStackTrace(); +// } +// } +// } +// } +// +// /** +// * 从文件读取PKCS#8格式的私钥 +// * @param filename 私钥文件路径 +// * @return PrivateKey对象 +// * @throws Exception 读取或解析异常 +// */ +// private static PrivateKey readPrivateKeyFromFile(String filename) throws Exception { +// StringBuilder keyBuilder = new StringBuilder(); +// try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { +// String line; +// while ((line = reader.readLine()) != null) { +// if (!line.startsWith("-----BEGIN PRIVATE KEY-----") && +// !line.startsWith("-----END PRIVATE KEY-----")) { +// keyBuilder.append(line); +// } +// } +// } catch (IOException e) { +// throw new RuntimeException("读取私钥文件失败: " + e.getMessage(), e); +// } +// +// byte[] keyBytes = Base64.getDecoder().decode(keyBuilder.toString()); +// PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); +// KeyFactory kf = KeyFactory.getInstance("RSA"); +// return kf.generatePrivate(spec); +// } +//} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/AesEncrypt.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/AesEncrypt.java new file mode 100644 index 0000000..9a5467e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/AesEncrypt.java @@ -0,0 +1,94 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.GeneralSecurityException; + + +/** + * AES加密工具 + * + * @author shuanglin.luo + * + */ +public class AesEncrypt{ + + private static final String AES_ALG = "AES"; + + /** + * AES算法 + */ + private static final String AES_CBC_PCK_ALG = "AES/CBC/PKCS5Padding"; + + private static final byte[] AES_IV = initIv(AES_CBC_PCK_ALG); + + /** + * AES加密 + * + * @param content + * @param aesKey + * @param charset + * @return + */ + public static String aesEncrypt(String content,byte[] aesKey,String charset){ + + try{ + Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG); + + IvParameterSpec iv = new IvParameterSpec(AES_IV); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.encodeBase64(aesKey), AES_ALG), iv); + + byte[] encryptBytes = cipher.doFinal(content.getBytes(charset)); + return new String(Base64.encodeBase64(encryptBytes)); + }catch (Exception e){ + } + return null; + } + + /** + * 初始向量的方法, 全部为0. 这里的写法适合于其它算法,针对AES算法的话,IV值一定是128位的(16字节). + * + * @param fullAlg + * @return + * @throws GeneralSecurityException + */ + public static byte[] initIv(String fullAlg){ + + try{ + Cipher cipher = Cipher.getInstance(fullAlg); + int blockSize = cipher.getBlockSize(); + byte[] iv = new byte[blockSize]; + for (int i = 0; i < blockSize; ++i){ + iv[i] = 0; + } + return iv; + }catch (Exception e){ + + int blockSize = 16; + byte[] iv = new byte[blockSize]; + for (int i = 0; i < blockSize; ++i){ + iv[i] = 0; + } + return iv; + } + } + + /** + * AES解密 + * + * @param content + * @param aesKey + * @param charset + * @return + * @throws Exception + */ + public static String aesDecrypt(String content,byte[] aesKey,String charset) throws Exception{ + Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG); + IvParameterSpec iv = new IvParameterSpec(initIv(AES_CBC_PCK_ALG)); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.encodeBase64(aesKey), AES_ALG), iv); + byte[] cleanBytes = cipher.doFinal(Base64.decodeBase64(content.getBytes())); + return new String(cleanBytes, charset); + + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ArchiveExtractor.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ArchiveExtractor.java new file mode 100644 index 0000000..38e0918 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ArchiveExtractor.java @@ -0,0 +1,138 @@ +package com.cmsen.ticket.infrastructure.tools.util; + + +import net.sf.sevenzipjbinding.IInArchive; +import net.sf.sevenzipjbinding.SevenZip; +import net.sf.sevenzipjbinding.SevenZipException; +import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; +import net.sf.sevenzipjbinding.simple.ISimpleInArchive; +import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem; +import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; +import org.apache.commons.compress.archivers.sevenz.SevenZFile; + +import java.io.*; +import java.nio.charset.Charset; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ArchiveExtractor { + public static void main(String[] args) { + extractToFolder("D:\\test\\1.zip","D:\\test\\1"); +// extractToFolder("D:\\test\\测试数据.rar"); +// extractToFolder("D:\\test\\921财务福州会议资料2.7z"); + } + + public static void extractToFolder(String archivePath,String newParent) { + File archive = new File(archivePath); + String folderName = archive.getName().replaceFirst("[.][^.]+$", ""); + File destDir = new File(archive.getParent()+File.separator+newParent, folderName); + if(!destDir.exists()){ + destDir.mkdirs(); + } + try { + if (archivePath.toLowerCase().endsWith(".zip")) { + unzip(archive, destDir); + } else if (archivePath.toLowerCase().endsWith(".rar")) { + unrar(archive, archive.getParent()+File.separator+newParent); + } else if (archivePath.toLowerCase().endsWith(".7z")) { + un7z(archive, destDir); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void extractToFolder(String archivePath) { + File archive = new File(archivePath); + File destDir = new File(archive.getParent()+File.separator); + if(!destDir.exists()){ + destDir.mkdirs(); + } + try { + if (archivePath.toLowerCase().endsWith(".zip")) { + unzip(archive, destDir); + } else if (archivePath.toLowerCase().endsWith(".rar")) { + unrar(archive, archive.getParent()+File.separator); + } else if (archivePath.toLowerCase().endsWith(".7z")) { + un7z(archive, destDir); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void unzip(File zipFile, File destDir) throws IOException { + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile), Charset.forName("GBK"))) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + File file = new File(destDir, entry.getName()); + if (entry.isDirectory()) { + file.mkdirs(); + } else { + file.getParentFile().mkdirs(); + try (FileOutputStream fos = new FileOutputStream(file)) { + byte[] buffer = new byte[1024]; + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } + } + } + } + } + + private static void unrar(File rarFile, String destDir) throws Exception { + RandomAccessFile randomAccessFile = new RandomAccessFile(rarFile, "r"); + IInArchive archive = SevenZip.openInArchive(null, + new RandomAccessFileInStream(randomAccessFile)); + + ISimpleInArchive simpleArchive = archive.getSimpleInterface(); + for (ISimpleInArchiveItem item : simpleArchive.getArchiveItems()) { + if (!item.isFolder()) { + extractItem(item, destDir); + } + } + + archive.close(); + randomAccessFile.close(); + } + + private static void extractItem(ISimpleInArchiveItem item, String outputDir) + throws SevenZipException { + File outputFile = new File(outputDir, item.getPath()); + outputFile.getParentFile().mkdirs(); + + try (FileOutputStream out = new FileOutputStream(outputFile)) { + item.extractSlow(data -> { + try { + out.write(data); + return data.length; + } catch (IOException e) { + throw new SevenZipException("写入文件失败", e); + } + }); + } catch (IOException e) { + throw new SevenZipException("创建输出流失败", e); + } + } + + private static void un7z(File sevenZFile, File destDir) throws IOException { + try (SevenZFile archive = new SevenZFile(sevenZFile)) { + SevenZArchiveEntry entry; + while ((entry = archive.getNextEntry()) != null) { + File file = new File(destDir, entry.getName()); + if (entry.isDirectory()) { + file.mkdirs(); + } else { + file.getParentFile().mkdirs(); + try (FileOutputStream fos = new FileOutputStream(file)) { + byte[] content = new byte[(int) entry.getSize()]; + archive.read(content); + fos.write(content); + } + } + } + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Base64.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Base64.java new file mode 100644 index 0000000..f356324 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Base64.java @@ -0,0 +1,510 @@ +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.cmsen.ticket.infrastructure.tools.util; + +/** + * Provides Base64 encoding and decoding as defined by RFC 2045. + * + *

+ * This class implements section 6.8. Base64 Content-Transfer-Encoding + * from RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: + * Format of Internet Message Bodies by Freed and Borenstein. + *

+ * + * @see RFC 2045 + * @author Apache Software Foundation + * @since 1.0-dev + * @version $Id: Base64.java,v 1.20 2004/05/24 00:21:24 ggregory Exp $ + */ +public class Base64{ + + /** + * Chunk size per RFC 2045 section 6.8. + * + *

+ * The {@value} character limit does not count the trailing CRLF, but counts + * all other characters, including any equal signs. + *

+ * + * @see RFC 2045 section 6.8 + */ + static final int CHUNK_SIZE = 76; + + /** + * Chunk separator per RFC 2045 section 2.1. + * + * @see RFC 2045 section 2.1 + */ + static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes(); + + /** + * The base length. + */ + static final int BASELENGTH = 255; + + /** + * Lookup length. + */ + static final int LOOKUPLENGTH = 64; + + /** + * Used to calculate the number of bits in a byte. + */ + static final int EIGHTBIT = 8; + + /** + * Used when encoding something which has fewer than 24 bits. + */ + static final int SIXTEENBIT = 16; + + /** + * Used to determine how many bits data contains. + */ + static final int TWENTYFOURBITGROUP = 24; + + /** + * Used to get the number of Quadruples. + */ + static final int FOURBYTE = 4; + + /** + * Used to test the sign of a byte. + */ + static final int SIGN = -128; + + /** + * Byte used to pad output. + */ + static final byte PAD = (byte) '='; + + // Create arrays to hold the base64 characters and a + // lookup for base64 chars + private static byte[] base64Alphabet = new byte[BASELENGTH]; + + private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; + + // Populating the lookup and character arrays + static{ + for (int i = 0; i < BASELENGTH; i++){ + base64Alphabet[i] = (byte) -1; + } + for (int i = 'Z'; i >= 'A'; i--){ + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i >= 'a'; i--){ + base64Alphabet[i] = (byte) (i - 'a' + 26); + } + for (int i = '9'; i >= '0'; i--){ + base64Alphabet[i] = (byte) (i - '0' + 52); + } + + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; + + for (int i = 0; i <= 25; i++){ + lookUpBase64Alphabet[i] = (byte) ('A' + i); + } + + for (int i = 26, j = 0; i <= 51; i++, j++){ + lookUpBase64Alphabet[i] = (byte) ('a' + j); + } + + for (int i = 52, j = 0; i <= 61; i++, j++){ + lookUpBase64Alphabet[i] = (byte) ('0' + j); + } + + lookUpBase64Alphabet[62] = (byte) '+'; + lookUpBase64Alphabet[63] = (byte) '/'; + } + + private static boolean isBase64(byte octect){ + if (octect == PAD){ + return true; + }else if (base64Alphabet[octect] == -1){ + return false; + }else{ + return true; + } + } + + /** + * Tests a given byte array to see if it contains + * only valid characters within the Base64 alphabet. + * + * @param arrayOctect + * byte array to test + * @return true if all bytes are valid characters in the Base64 + * alphabet or if the byte array is empty; false, otherwise + */ + public static boolean isArrayByteBase64(byte[] arrayOctect){ + + arrayOctect = discardWhitespace(arrayOctect); + + int length = arrayOctect.length; + if (length == 0){ + // shouldn't a 0 length array be valid base64 data? + // return false; + return true; + } + for (int i = 0; i < length; i++){ + if (!isBase64(arrayOctect[i])){ + return false; + } + } + return true; + } + + /** + * Encodes binary data using the base64 algorithm but + * does not chunk the output. + * + * @param binaryData + * binary data to encode + * @return Base64 characters + */ + public static byte[] encodeBase64(byte[] binaryData){ + return encodeBase64(binaryData, false); + } + + /** + * Encodes binary data using the base64 algorithm and chunks + * the encoded output into 76 character blocks + * + * @param binaryData + * binary data to encode + * @return Base64 characters chunked in 76 character blocks + */ + public static byte[] encodeBase64Chunked(byte[] binaryData){ + return encodeBase64(binaryData, true); + } + + /** + * Decodes an Object using the base64 algorithm. This method + * is provided in order to satisfy the requirements of the + * Decoder interface, and will throw a DecoderException if the + * supplied object is not of type byte[]. + * + * @param pObject + * Object to decode + * @return An object (of type byte[]) containing the + * binary data which corresponds to the byte[] supplied. + * @throws DecoderException + * if the parameter supplied is not + * of type byte[] + */ + public Object decode(Object pObject) throws Exception{ + if (!(pObject instanceof byte[])){ + throw new Exception("Parameter supplied to Base64 decode is not a byte[]"); + } + return decode((byte[]) pObject); + } + + /** + * Decodes a byte[] containing containing + * characters in the Base64 alphabet. + * + * @param pArray + * A byte array containing Base64 character data + * @return a byte array containing binary data + */ + public byte[] decode(byte[] pArray){ + return decodeBase64(pArray); + } + + /** + * Encodes binary data using the base64 algorithm, optionally + * chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if isChunked is true this encoder will chunk + * the base64 output into 76 character blocks + * @return Base64-encoded data. + */ + public static byte[] encodeBase64(byte[] binaryData,boolean isChunked){ + int lengthDataBits = binaryData.length * EIGHTBIT; + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + byte encodedData[] = null; + int encodedDataLength = 0; + int nbrChunks = 0; + + if (fewerThan24bits != 0){ + //data not divisible by 24 bit + encodedDataLength = (numberTriplets + 1) * 4; + }else{ + // 16 or 8 bit + encodedDataLength = numberTriplets * 4; + } + + // If the output is to be "chunked" into 76 character sections, + // for compliance with RFC 2045 MIME, then it is important to + // allow for extra length to account for the separator(s) + if (isChunked){ + + nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE)); + encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; + } + + encodedData = new byte[encodedDataLength]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + + int encodedIndex = 0; + int dataIndex = 0; + int i = 0; + int nextSeparatorIndex = CHUNK_SIZE; + int chunksSoFar = 0; + + //log.debug("number of triplets = " + numberTriplets); + for (i = 0; i < numberTriplets; i++){ + dataIndex = i * 3; + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + b3 = binaryData[dataIndex + 2]; + + //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); + + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); + + encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; + //log.debug( "val2 = " + val2 ); + //log.debug( "k4 = " + (k<<4) ); + //log.debug( "vak = " + (val2 | (k<<4)) ); + encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; + + encodedIndex += 4; + + // If we are chunking, let's put a chunk separator down. + if (isChunked){ + // this assumes that CHUNK_SIZE % 4 == 0 + if (encodedIndex == nextSeparatorIndex){ + System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); + chunksSoFar++; + nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); + encodedIndex += CHUNK_SEPARATOR.length; + } + } + } + + // form integral number of 6-bit groups + dataIndex = i * 3; + + if (fewerThan24bits == EIGHTBIT){ + b1 = binaryData[dataIndex]; + k = (byte) (b1 & 0x03); + //log.debug("b1=" + b1); + //log.debug("b1<<2 = " + (b1>>2) ); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex + 2] = PAD; + encodedData[encodedIndex + 3] = PAD; + }else if (fewerThan24bits == SIXTEENBIT){ + + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex + 3] = PAD; + } + + if (isChunked){ + // we also add a separator to the end of the final chunk. + if (chunksSoFar < nbrChunks){ + System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); + } + } + + return encodedData; + } + + /** + * Decodes Base64 data into octects + * + * @param base64Data + * Byte array containing Base64 data + * @return Array containing decoded data. + */ + public static byte[] decodeBase64(byte[] base64Data){ + // RFC 2045 requires that we discard ALL non-Base64 characters + base64Data = discardNonBase64(base64Data); + + // handle the edge case, so we don't have to worry about it later + if (base64Data.length == 0){ + return new byte[0]; + } + + int numberQuadruple = base64Data.length / FOURBYTE; + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; + + // Throw away anything not in base64Data + + int encodedIndex = 0; + int dataIndex = 0; + { + // this sizes the output array properly - rlw + int lastData = base64Data.length; + // ignore the '=' padding + while (base64Data[lastData - 1] == PAD){ + if (--lastData == 0){ + return new byte[0]; + } + } + decodedData = new byte[lastData - numberQuadruple]; + } + + for (int i = 0; i < numberQuadruple; i++){ + dataIndex = i * 4; + marker0 = base64Data[dataIndex + 2]; + marker1 = base64Data[dataIndex + 3]; + + b1 = base64Alphabet[base64Data[dataIndex]]; + b2 = base64Alphabet[base64Data[dataIndex + 1]]; + + if (marker0 != PAD && marker1 != PAD){ + //No PAD e.g 3cQl + b3 = base64Alphabet[marker0]; + b4 = base64Alphabet[marker1]; + + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); + }else if (marker0 == PAD){ + //Two PAD e.g. 3c[Pad][Pad] + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + }else if (marker1 == PAD){ + //One PAD e.g. 3cQ[Pad] + b3 = base64Alphabet[marker0]; + + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + } + encodedIndex += 3; + } + return decodedData; + } + + /** + * Discards any whitespace from a base-64 encoded block. + * + * @param data + * The base-64 encoded data to discard the whitespace + * from. + * @return The data, less whitespace (see RFC 2045). + */ + static byte[] discardWhitespace(byte[] data){ + byte groomedData[] = new byte[data.length]; + int bytesCopied = 0; + + for (int i = 0; i < data.length; i++){ + switch (data[i]) { + case (byte) ' ': + case (byte) '\n': + case (byte) '\r': + case (byte) '\t': + break; + default: + groomedData[bytesCopied++] = data[i]; + } + } + + byte packedData[] = new byte[bytesCopied]; + + System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); + + return packedData; + } + + /** + * Discards any characters outside of the base64 alphabet, per + * the requirements on page 25 of RFC 2045 - "Any characters + * outside of the base64 alphabet are to be ignored in base64 + * encoded data." + * + * @param data + * The base-64 encoded data to groom + * @return The data, less non-base64 characters (see RFC 2045). + */ + static byte[] discardNonBase64(byte[] data){ + byte groomedData[] = new byte[data.length]; + int bytesCopied = 0; + + for (int i = 0; i < data.length; i++){ + if (isBase64(data[i])){ + groomedData[bytesCopied++] = data[i]; + } + } + + byte packedData[] = new byte[bytesCopied]; + + System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); + + return packedData; + } + + // Implementation of the Encoder Interface + + /** + * Encodes an Object using the base64 algorithm. This method + * is provided in order to satisfy the requirements of the + * Encoder interface, and will throw an EncoderException if the + * supplied object is not of type byte[]. + * + * @param pObject + * Object to encode + * @return An object (of type byte[]) containing the + * base64 encoded data which corresponds to the byte[] supplied. + * @throws EncoderException + * if the parameter supplied is not + * of type byte[] + */ + public Object encode(Object pObject) throws Exception{ + if (!(pObject instanceof byte[])){ + throw new Exception("Parameter supplied to Base64 encode is not a byte[]"); + } + return encode((byte[]) pObject); + } + + /** + * Encodes a byte[] containing binary data, into a byte[] containing + * characters in the Base64 alphabet. + * + * @param pArray + * a byte array containing binary data + * @return A byte array containing only Base64 character data + */ + public byte[] encode(byte[] pArray){ + return encodeBase64(pArray, false); + } + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Constants.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Constants.java new file mode 100644 index 0000000..af1a9d9 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/Constants.java @@ -0,0 +1,282 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +/** + * 公用常量类 + * + * @author shuanglin.luo + * + */ +public abstract class Constants{ + + /** 宝尊协议入参共享参数 **/ + public static final String APP_KEY = "sourceApp"; + + public static final String METHOD_NAME = "methodName"; + + public static final String VERSION = "version"; + + public static final String SIGN = "sign"; + + public static final String TIMESTAMP = "requestTime"; + + public static final String INTERFACETYPE = "interfaceType"; + + /** 标识实时or异步 实时*/ + public static final String INTERFACETYPE_REALTIME = "1"; + + /** 标识实时or异步 异步*/ + public static final String INTERFACETYPE_ASYNCHRONOUS = "2"; + + /** 宝尊 JSON 应格式 */ + public static final String FORMAT_JSON = "json"; + + /** 宝尊 XML 应格式 */ + public static final String FORMAT_XML = "xml"; + + /** MD5签名方式 */ + public static final String SIGN_METHOD_MD5 = "md5"; + + /** HMAC-SHA256签名方式 */ + public static final String SIGN_METHOD_HMAC_SHA256 = "sha"; + + /** UTF-8字符集 **/ + public static final String CHARSET_UTF8 = "UTF-8"; + + /** 宝尊 Date默认时区 **/ + public static final String DATE_TIMEZONE = "GMT+8"; + + /** HTTP请求相关 **/ + public static final String METHOD_POST = "POST"; + + public static final String METHOD_GET = "GET"; + + public static final String CTYPE_FORM_DATA = "application/x-www-form-urlencoded"; + + public static final String CTYPE_FILE_UPLOAD = "multipart/form-data"; + + public static final String CTYPE_TEXT_XML = "text/xml"; + + public static final String CTYPE_TEXT_PLAIN = "text/plain"; + + public static final String CTYPE_APP_JSON = "application/json"; + + /** ----------------------------------------oms2wms------------------------------------------------------------ **/ + /** 发货通知单接口 Shipment Order **/ + public static final String METHOD_NAME_SHIPMENT_ORDER_NOTIFY = "shipment_order_notify"; + + /** 单据状态更新(单件) Order Status Update **/ + public static final String METHOD_NAME_ORDER_STATUS_CONFIRM = "order_status_confirm"; + + /** 发货单出库确认(单件) Shipment Confirmation **/ + public static final String METHOD_NAME_SALES_ORDER_SHIPPING_CONFIRM = "sales_order_shipping_confirm"; + + /** 销售订单/退货订单取消 Cancellation **/ + public static final String METHOD_NAME_ORDER_CANCEL_NOTIFY = "order_cancel_notify"; + + /** 退货单通知接口 Return Order **/ + public static final String METHOD_NAME_RETURN_ORDER_NOTIFY = "return_order_notify"; + + /** 退货单入库确认接口(单件) Return Confirmation **/ + public static final String METHOD_NAME_RETURN_ORDER_SHIPPING_CONFIRM = "return_order_inbound_confirm"; + + /** 单据状态更新(批量) Order Status Update **/ + public static final String METHOD_NAME_ORDER_STATUSES_CONFIRM = "order_statuses_confirm"; + + /** 发货单出库确认(批量) Shipment Confirmation **/ + public static final String METHOD_NAME_SALES_ORDER_SHIPPING_CONFIRMS = "sales_order_shipping_confirms"; + + /** 退货单入库确认接口(批量) Return Confirmation **/ + public static final String METHOD_NAME_RETURN_ORDER_INBOUND_CONFIRMS = "return_order_inbound_confirms"; + + /** 出入库流水接口 Inventory Flow **/ + public static final String METHOD_NAME_INVENTORY_FLOW = "order_inventory_flow"; + + /** 商品同步接口 Sku Notify **/ + public static final String METHOD_NAME_SKU_NOTIFY = "sku_notify"; + + /** 全量库存同步接口 Full inventory **/ + public static final String METHOD_NAME_FULL_INVENTORY = "sku_full_inventory"; + + /** 增量库存同步接口 Incremental inventory **/ + public static final String METHOD_NAME_INCREMENTAL_INVENTORY = "sku_incremental_inventory"; + + /** 订单拆单反馈接口 Split Order Result **/ + public static final String METHOD_NAME_SPLIT_ORDER_RESULT = "order_split_result"; + + /** 修改收件人信息接口 ORDER CHANGE RECIEVER **/ + public static final String METHOD_NAME_ORDER_CHANGE_RECIEVER = "order_change_reciever"; + + /** 预售订单释放接口 SALES ORDER RELEASE **/ + public static final String METHOD_NAME_SALES_ORDER_RELEASE = "sales_order_release"; + + /** 商品查询接口 SKU DATA QUERY **/ + public static final String METHOD_NAME_SKU_DATA_QUERY = "sku_data_query"; + + /** 商品库存查询接 **/ + public static final String METHOD_NAME_OMS_SKU_INVENTORY_QUERY = "oms_sku_inventory_query"; + + /** 商品占用库存明细查询接口 **/ + public static final String METHOD_NAME_OMS_SKU_OCCUPIED_DETAIL_QUERY = "oms_sku_occupied_detail_query"; + + /** 报缺信息同步接口 **/ + public static final String METHOD_NAME_ORDER_MISSING_INFO = "order_missing_info"; + + + /** ----------------------------------------wms2erp------------------------------------------------------------ **/ + /** 入库通知 Inbound Order **/ + public static final String WMS2REP_METHOD_NAME_INBOUND_ORDER = "inbound_order"; + /** 入库反馈Inbound Confirm **/ + public static final String WMS2REP_METHOD_NAME_INBOUND_CONFIRM = "inbound_confirm"; + /** 出库通知 Outbound Order **/ + public static final String WMS2REP_METHOD_NAME_OUTBOUND_ORDER = "outbound_order"; + /** 出库反馈 Outbound Confirm **/ + public static final String WMS2REP_METHOD_NAME_OUTBOUND_CONFIRM = "outbound_confirm"; + /** 单据状态更新(批量) Order Status Update **/ + public static final String WMS2REP_METHOD_NAME_ORDER_STATUSES_CONFIRM = "wms_erp_order_statuses_confirm"; + /** 调拨 Transfer **/ + public static final String WMS2REP_METHOD_NAME_TRANSFER_OUT = "transfer_out"; + /** 库存调整 Inventory Adjust **/ + public static final String WMS2REP_METHOD_NAME_INVENTORY_ADJUST = "inventory_adjust"; + /** 增量库存Inventory Incremental **/ + public static final String WMS2REP_METHOD_NAME_INVENTORY_INCREMENTAL = "inventory_incremental"; + /** 全量库存Inventory Full **/ + public static final String WMS2REP_METHOD_NAME_INVENTORY_FULL = "inventory_full"; + /** 库存快照Inventory Snapshot **/ + public static final String WMS2REP_METHOD_NAME_INVENTORY_SNAPSHOT = "inventory_snapshot"; + /** 主档信息Sku Master **/ + public static final String WMS2REP_METHOD_NAME_WMS_ERP_SKU_MASTER = "wms_erp_sku_master"; + /** 订单取消order cancel notify **/ + public static final String WMS2REP_METHOD_NAME_WMS_ERP_ORDER_CANCEL_NOTIFY = "wms_erp_order_cancel_notify"; + /** 商品查询接口 SKU DATA QUERY **/ + public static final String WMS2REP_METHOD_NAME_SKU_DATA_QUERY = "wms_erp_sku_data_query"; + /** 修改收件人信息接口 ORDER CHANGE RECIEVER **/ + public static final String WMS2REP_METHOD_NAME_ORDER_CHANGE_RECIEVER = "wms_erp_order_change_reciever"; + /** 预售订单释放接口 SALES ORDER RELEASE **/ + public static final String WMS2REP_METHOD_NAME_SALES_ORDER_RELEASE = "wms_erp_sales_order_release"; + + + /** ----------------------------------------platform2oms------------------------------------------------------------ **/ + /** 订单推送接口 Order Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_ORDER_NOTIFY = "platform_order_notify"; + /** 订单状态更新(批量)Order Status Update **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_ORDER_STATUSES = "platform_order_statuses"; + /** 订单状态更新(单件)Order Status Update **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_ORDER_STATUS = "platform_order_status"; + /** 商品信息推送接口 Sku Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_SKU_NOTIFY = "platform_sku_notify"; + /** 在售商品同步 OnSale Sku Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_ON_SALE_SKUS = "platform_on_sale_skus"; + /** 商品价格同步 Sku Price Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_SKU_PRICE_NOTIFY = "platform_sku_price_notify"; + /** 商品销售价格同步 Sku sales Price Notify **/ + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_SKU_SALES_PRICE_NOTIFY = "platform_sku_sales_price_notify"; + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_O2O_INVENTORY_QUERY = "platform_o2o_inventory_query"; + /** 库存信息 Sku Inventory **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_SKU_INVENTORY = "platform_sku_inventory"; + /** 路由信息推送 Express Route **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_EXPRESS_ROUTE = "platform_express_route"; + /** 退款指令同步 Refund Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_REFUND_NOTIFY = "platform_refund_notify"; + /** 退款结果信息 Refund Notify **/ + public static final String WMS2REP_METHOD_NAME_PLATFORM_REFUND_RESULT = "platform_refund_result"; + /** 成本价查询接口 platform query cost price **/ + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_QUERY_COST_PRICE = "platform_query_cost_price"; + /** 成本价最新时间查询接口 platform query cost price update time **/ + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_QUERY_COST_PRICE_UPDATE_TIME = "platform_query_cost_price_update_time"; + /** 商品信息查询接口 platform query master data **/ + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_QUERY_MASTER_DATA = "platform_query_master_data"; + /** 订单状态更新(拆单)接口 platform split order statuses **/ + public static final String OMS2PLATFORM_METHOD_NAME_PLATFORM_SPLIT_ORDER_STATUSES = "platform_split_order_statuses"; + /** 订单支付信息同步接口 platform payment notify **/ + public static final String OMS2PLATFORM_METHOD_NAME_PAYMENT_NOTIFY = "platform_payment_notify"; + /** 发票查询结果接口 platform invoice inquiry **/ + public static final String OMS2PLATFORM_METHOD_NAME_INVOICE_INQUIRY = "platform_invoice_inquiry"; + /** 退换货订单同步信息接口 platform return exchange info **/ + public static final String OMS2PLATFORM_METHOD_NAME_RETURN_EXCHANGE_INFO = "platform_return_exchange_info"; + /** 订单取消接口 platform order cancel **/ + public static final String OMS2PLATFORM_METHOD_NAME_ORDER_CANCEL = "platform_order_cancel"; + /** 发票信息同步**/ + public static final String OMS2PLATFORM_INVOICE_NOTIFY = "platform_invoice _notify"; + + /** 库存查询接口 DMS查询pacs/tom/im的库存**/ + public static final String OMS2PLATFORM_INVENTORY_QUERY = "platform_inventory_query"; + + /** 平台店铺信息查询接口**/ + public static final String OMS2PLATFORM_PLATFORM_STORE_INFO_QUERY = "platform_store_info_query"; + + /** 平台商品URL信息查询接口(单件)**/ + public static final String OMS2PLATFORM_PLATFORM_SKU_URL_INFO_QUERY = "platform_sku_url_info_query"; + + /** 平台商品URL信息查询接口(批量)**/ + public static final String OMS2PLATFORM_PLATFORM_SKU_URL_INFOS_QUERY = "platform_sku_url_infos_query"; + + /** 平台商品URL信息结果反馈接口(批量)**/ + public static final String OMS2PLATFORM_PLATFORM_SKUS_URL_INFO_RESULT = "platform_skus_url_info_result"; + + /** 查询平台在售商品接口 */ + public static final String OMS2PLATFORM_ON_SALE_SKU_QUERY = "platform_on_sale_sku_query"; + + /** 查询平台商品库存信息接口 */ + public static final String OMS2PLATFORM_ON_SALE_SKU_INV_QTY_QUERY = "platform_on_sale_sku_inv_qty_query"; + + /**----------------------------------------WMS2QIANHAI-------------------------------------------------------*/ + /**上传出口出入库单*/ + public static final String WMS2QIANHAI_METHOD_NAME_UPLOAD_CUSTOM_ORDER_SOURCE="upload_custom_order_source"; + /**上传商品料件信息*/ + public static final String WMS2QIANHAI_METHOD_NAME_UPLOAD_GOODS_SOURCE="upload_goods_source"; + /**上传出口出入库单结果*/ + public static final String QIANHAI2WMS_METHOD_NAME_UPLOAD_CUSTOM_ORDER_RESULT="upload_custom_order_result"; + /**上传商品料件信息结果*/ + public static final String QIANHAI2WMS_METHOD_NAME_UPLOAD_GOODS_RESULT="upload_goods_result"; + /**上传商品料件信息结果*/ + public static final String QIANHAI2WMS_METHOD_NAME_GET_GATHER_DATA="get_gather_data"; + /**上传出境出库信息*/ + public static final String WMS2QIANHAI_METHOD_NAME_UPLOAD_EXPORT_CUSTOM_ORDER_SOURCE="upload_export_custom_order_source"; + /**上传出境出库信息汇总*/ + public static final String WMS2QIANHAI_METHOD_NAME_UPLOAD_EXPORT_CUSTOM_SUMMARY_ORDER="upload_export_custom_summary_order"; + /**----------------------------------------电子发票-------------------------------------------------------*/ + /** 开发票请求 */ + public static final String ERP_ELECTRONIC_INVOICE_OPEN = "open_invoice"; + /**发票信息回传 */ + public static final String ERP_ELECTRONIC_INVOICE_BACK = "invoice_back"; + /** 根据店铺编码查询发票 */ + public static final String ERP_ELECTRONIC_INVOICE_QUERY_BY_SHOPCODE = "query_invoices_by_shopcode"; + /** 根据流水号查询发票 */ + public static final String ERP_ELECTRONIC_INVOICE_QUERY_BY_SERIAL_NO = "query_invoices_by_seriano"; + /** 根据订单号查询发票 */ + public static final String ERP_ELECTRONIC_INVOICE_QUERY_BY_ORDERCODE = "query_invoices_by_ordercode"; + /** 根据订单号查询发票 */ + public static final String ERP_ELECTRONIC_INVOICE_GET_BY_URL = "get_file_by_url"; + + + //Get Carton List + public static final String GET_CARTON_LIST = "GET_CARTON_LIST"; + + //Create Carton Request + public static final String CREATE_CARTON_REQUEST = "Create_Carton_Request"; + + //Update Carton Request + public static final String UPDATE_CARTON_REQUEST = "UPDATE_CARTON_REQUEST"; + + //Get Carton Details + public static final String GET_CARTON_DETAILS = "GET_CARTON_DETAILS"; + + //packlist details + public static final String PACKLIST_DETAILS = "PACKLIST_DETAILS"; + + //Get Shipping Label Details. + public static final String GET_SHIPPING_LABEL_DETAILS = "GET_SHIPPING_LABEL_DETAILS"; + + //Get Shipment Details + public static final String GET_SHIPMENT_DETAILS = "GET_SHIPMENT_DETAILS"; + + //Get Shipment List + public static final String GET_SHIPMENT_LIST = "GET_SHIPMENT_LIST"; + + //Shipment Intermediate Updates + public static final String SHIPMENT_INTERMEDIATE_UPDATES = "SHIPMENT_INTERMEDIATE_UPDATES"; + + //Shipment Shipped Update + public static final String SHIPMENT_SHIPPED_UPDATE = "SHIPMENT_SHIPPED_UPDATE"; + +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DateUtil.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DateUtil.java new file mode 100644 index 0000000..4786dc8 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DateUtil.java @@ -0,0 +1,134 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + + +public final class DateUtil{ + + public static final String PATTERN_FULL_SIMPLE = "yyyyMMddHHmmss"; + public static final String PATTERN_FULL = "yyyy-MM-dd HH:mm:ss"; + + /** + * 年-月-日 + */ + public static final String PATTERN_SIMPLE = "yyyy-MM-dd"; + + /** + * 年-月-日 时:分 + */ + public static final String PATTERN_MINUTES = "yyyy-MM-dd HH:mm"; + + /** + * 年-月-日 时:分:秒 + */ + public static final String PATTERN_NORMAL = "yyyy-MM-dd HH:mm:ss"; + + /** + * 年月日 + */ + public static final String PATTERN_FULL_DAY = "yyyyMMdd"; + + /** + * 日/月/年 时:分:秒 + */ + public static final String PATTERN_INVERTED_NORMAL = "dd/MM/yyyy HH:mm:ss"; + + + public static String now(){ + return formatDate(Calendar.getInstance().getTime(), PATTERN_FULL_SIMPLE); + } + + public static String formatDate(Date date,String pattern){ + SimpleDateFormat util = new SimpleDateFormat(pattern); + String str = util.format(date); + return str; + } + + /** + * 自动解析日期字符串 年-月-日 年-月-日 时:分:秒 年-月-日 时:分:秒 毫秒 其它格式抛出异常() + * + * @param src + * @return + * @Description: + */ + public static Date parse(String src){ + SimpleDateFormat util = new SimpleDateFormat(PATTERN_SIMPLE); + Date ret = null; + if (!StringUtils.isEmpty(src)){ + util.applyPattern(PATTERN_NORMAL); + try{ + ret = util.parse(src); + }catch (ParseException e){} + if (ret == null){ + try{ + util.applyPattern(PATTERN_SIMPLE); + ret = util.parse(src); + }catch (ParseException e){} + } + if (ret == null){ + try{ + util.applyPattern(PATTERN_FULL); + ret = util.parse(src); + }catch (ParseException e){} + } + if (ret == null){ + try{ + util.applyPattern(PATTERN_FULL_SIMPLE); + ret = util.parse(src); + }catch (ParseException e){} + } + } + if (ret == null){ + throw new IllegalArgumentException("## cant parse to Date . not supported by default pattern: $" + src + "$"); + } + return ret; + } + + + /** + * 时间转化 String转Date + * @param src 源时间字符串 + * @param pattern 转化格式 + * @return + */ + public static Date parse(String src,String pattern){ + SimpleDateFormat util = new SimpleDateFormat(PATTERN_FULL); + Date ret = null; + if (!StringUtils.isEmpty(src)){ + try{ + util.applyPattern(pattern); + ret = util.parse(src); + }catch (Exception e){} + } + if (ret == null){ + throw new IllegalArgumentException("## cant parse to Date . not supported by default pattern: $" + src + "$"); + } + return ret; + } + + + /** + * 日期类型String转为pattern形式,且判空返回"" + * @author xiaoyan.hang + * @param src 转化前时间字符串 + * @param sourcePattern 转化前的时间格式 + * @param targetPattern 转化后的时间格式 + * @return 转化后的时间字符串 + */ + public static String formatDateStringToString(String src,String sourcePattern,String targetPattern){ + if(StringUtils.isEmpty(src)){ + return ""; + } + else{ + try{ + return DateUtil.formatDate(DateUtil.parse(src,sourcePattern), targetPattern); + } + catch (Exception e) { + throw new IllegalArgumentException("## cant parse to Date . not supported by default pattern: $" + src + "$"); + } + } + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DecryptUtil.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DecryptUtil.java new file mode 100644 index 0000000..32cb068 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/DecryptUtil.java @@ -0,0 +1,31 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +/** + * + * @ClassName: DecryptUtil + * @Description: 解密工具 + * @author yibo.wu + * @date 2018年2月7日 下午2:22:31 + * + */ +public class DecryptUtil{ + + /** UTF-8字符集 **/ + public static final String CHARSET_UTF8 = "UTF-8"; + + public static String decrypt(String param,String secret) throws Exception{ + // 基于secret验证加解密是否一致 + // 参数进行解密 + String decryptResult = ""; + try{ + decryptResult = AesEncrypt.aesDecrypt(param, MD5Encrypt.encryptMD5(secret), CHARSET_UTF8); + if (decryptResult == null || "".equals(decryptResult)){ + throw new RuntimeException("参数加解密失败"); + } + }catch (Exception e){ + e.printStackTrace(); + throw new RuntimeException("参数加解密失败"); + } + return decryptResult; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/MD5Encrypt.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/MD5Encrypt.java new file mode 100644 index 0000000..9047090 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/MD5Encrypt.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; + +/** + * MD5摘要 + * @author shuanglin.luo + * + */ +public class MD5Encrypt{ + + /** + * 对字符串采用UTF-8编码后,用MD5进行摘要。 + */ + public static byte[] encryptMD5(String data) throws IOException{ + return encryptMD5(data.getBytes(Constants.CHARSET_UTF8)); + } + + /** + * 对字节流进行MD5摘要。 + */ + public static byte[] encryptMD5(byte[] data) throws IOException{ + byte[] bytes = null; + try{ + MessageDigest md = MessageDigest.getInstance("MD5"); + bytes = md.digest(data); + }catch (GeneralSecurityException gse){ + throw new IOException(gse.toString()); + } + return bytes; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/NumberExtractorUtil.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/NumberExtractorUtil.java new file mode 100644 index 0000000..1bf38bc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/NumberExtractorUtil.java @@ -0,0 +1,92 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class NumberExtractorUtil { + + private final Listprefixes; + private final int maxLength; + + /** + * 构造函数 + * @param prefixes 可配置的数字前缀列表 + * @param maxLength 最大数字长度(包含前缀) + */ + public NumberExtractorUtil(Listprefixes, int maxLength) { + this.prefixes = new ArrayList<>(prefixes); + this.maxLength = maxLength; + } + + /** + * 从输入字符串中提取符合条件的数字 + * @param input 输入字符串 + * @return 提取到的数字列表 + */ + public ListextractNumbers(String input) { + if (input == null || input.isEmpty() || prefixes.isEmpty() || maxLength <= 0) { + return new ArrayList<>(); + } + + // 构建正则表达式 + String prefixPattern = prefixes.stream() + .map(Pattern::quote) // 转义特殊字符 + .collect(Collectors.joining("|")); + + // 数字部分的最大长度(总长度减去前缀最小长度) + int maxDigitLength = maxLength - 1; // 假设前缀至少1位 + + String patternString = "(" + prefixPattern + ")\\d{1," + maxDigitLength + "}"; + Pattern pattern = Pattern.compile(patternString); + Matcher matcher = pattern.matcher(input); + + Listresults = new ArrayList<>(); + while (matcher.find()) { + String match = matcher.group(); + if (match.length() == maxLength) { + results.add(match); + }else if(match.length() > maxLength) { + results.add(match.substring(0,maxLength)); + } + } + + return results; + } + + /** + * 获取配置信息 + * @return 配置信息字符串 + */ + public String getConfigInfo() { + return "前缀: " + prefixes + ", 最大长度: " + maxLength; + } + + public static void main(String[] args) { + // 示例1: 提取以A、B、C开头的数字 +// NumberExtractorUtil extractor1 = new NumberExtractorUtil(Arrays.asList("A", "B", "C"), 10); +// String input1 = "A123 B4567890123 C98765 D12345678901 E12"; +// System.out.println("配置: " + extractor1.getConfigInfo()); +// System.out.println("输入: " + input1); +// System.out.println("提取结果: " + extractor1.extractNumbers(input1)); +// System.out.println(); +// +// // 示例2: 提取以数字1、2、3开头的数字 +// NumberExtractorUtil extractor2 = new NumberExtractorUtil(Arrays.asList("1", "2", "3"), 8); +// String input2 = "123abc 234567890 3456789012 test123456 200 ok3456789"; +// System.out.println("配置: " + extractor2.getConfigInfo()); +// System.out.println("输入: " + input2); +// System.out.println("提取结果: " + extractor2.extractNumbers(input2)); +// System.out.println(); + + // 示例3: 复杂前缀 + NumberExtractorUtil extractor3 = new NumberExtractorUtil(Arrays.asList("550,450,451,285,970,957,978".split(",")), 10); + String input3 = "450672204900010"; + System.out.println("配置: " + extractor3.getConfigInfo()); + System.out.println("输入: " + input3); + System.out.println("提取结果: " + extractor3.extractNumbers(input3)); + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ShaEncrypt.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ShaEncrypt.java new file mode 100644 index 0000000..10c198e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/ShaEncrypt.java @@ -0,0 +1,21 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import java.security.MessageDigest; + +public class ShaEncrypt{ + + public static byte[] encryptSha256(String data) throws Exception{ + return encryptSha256(data.getBytes("UTF-8")); + } + + /** + * 对字节流进行sha-256摘要。 + */ + public static byte[] encryptSha256(byte[] data) throws Exception{ + byte[] bytes = null; + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + sha.update(data); + bytes = sha.digest(); + return bytes; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/SignUtil.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/SignUtil.java new file mode 100644 index 0000000..c68234e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/SignUtil.java @@ -0,0 +1,151 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * 签名生成 + * + * @author shuanglin.luo + * + */ +public class SignUtil{ + + /** MD5签名方式 */ + public static final String SIGN_METHOD_MD5 = "md5"; + + /** sha签名方式 */ + public static final String TYPE_SHA = "sha"; + + /** 宝尊协议入参共享参数 **/ + public static final String APP_KEY = "sourceApp"; + + public static final String METHOD_NAME = "methodName"; + + public static final String VERSION = "version"; + + public static final String SIGN = "sign"; + + public static final String TIMESTAMP = "requestTime"; + + public static final String INTERFACETYPE = "interfaceType"; + + + /** + * 检查生成的sign是否一致,保证数据一致性 + * + * @param sign + * 签名 + * @param version + * 版本 + * @param appKey + * key + * @param interfaceType + * 接口类型 + * @param methodName + * 方法名 + * @param requestTime + * 请求时间 + * @param appSecret + * secret + * @param body + * 请求内容 + * @return + */ + public static boolean checkSign(String sign,String version,String appKey,Integer interfaceType,String methodName,String requestTime,String appSecret,String body){ + // 签名验证,保证数据完整性 + Map protocalMustParams = new HashMap(); + protocalMustParams.put(VERSION, version); + protocalMustParams.put(APP_KEY, appKey); + protocalMustParams.put(INTERFACETYPE, String.valueOf(interfaceType)); + protocalMustParams.put(METHOD_NAME, methodName); + protocalMustParams.put(TIMESTAMP, requestTime); + String makeSign = ""; + try{ + // 基于接到的数据生成签名,和接到的签名进行验证. + makeSign = makeSign(protocalMustParams, body, appSecret, SIGN_METHOD_MD5); + if (makeSign == null || "".equals(makeSign)){ + return false; + } + }catch (Exception e){ + e.printStackTrace(); + return false; + } + return makeSign.equals(sign); + } + + public static String makeSign(Map params,String body,String secret,String signMethod) throws Exception{ + return makeSign(secret, params, body + secret, "", "", signMethod); + } + + public static String makeSign(String start,Map paramMap,String end,String flg,String split,String signMethod) throws Exception{ + // 第一步:检查参数是否已经排序 + String[] keys = paramMap.keySet().toArray(new String[0]); + Arrays.sort(keys); + // 第二步:把所有参数名和参数值串在一起 + StringBuilder query = new StringBuilder(); + query.append(start); + for (int i = 0; i < keys.length; i++){ + String value = paramMap.get(keys[i]); + if (StringUtils.areNotEmpty(keys[i], value)){ + if (i == keys.length - 1){ + query.append(keys[i]).append(flg).append(value); + }else{ + query.append(keys[i]).append(flg).append(value).append(split); + } + } + } + query.append(end); + // 第三步:生产成签名 + byte[] bytes; + if (TYPE_SHA.equals(signMethod)){ + bytes = ShaEncrypt.encryptSha256(query.toString()); + }else{ + bytes = MD5Encrypt.encryptMD5(query.toString()); + } + // 第四步:把二进制转化为大写的十六进制 + return byte2hex(bytes); + } + + public static String makeSign(Map params,String body,String secret) throws NoSuchAlgorithmException,IOException{ + // 第一步:检查参数是否已经排序 + String[] keys = params.keySet().toArray(new String[0]); + Arrays.sort(keys); + // 第二步:把所有参数名和参数值串在一起 + StringBuilder query = new StringBuilder(); + query.append(secret); + for (String key : keys){ + String value = params.get(key); + if (StringUtils.areNotEmpty(key, value)){ + query.append(key).append(value); + } + } + // 第三步:把请求主体拼接在参数后面 + if (body != null){ + query.append(body); + } + query.append(secret); + // 第四步:使用MD5加密 + byte[] bytes = MD5Encrypt.encryptMD5(query.toString()); + // 第五步:把二进制转化为大写的十六进制 + return byte2hex(bytes); + } + + /** + * 把字节流转换为十六进制表示方式。 + */ + public static String byte2hex(byte[] bytes){ + StringBuilder sign = new StringBuilder(); + for (int i = 0; i < bytes.length; i++){ + String hex = Integer.toHexString(bytes[i] & 0xFF); + if (hex.length() == 1){ + sign.append("0"); + } + sign.append(hex.toUpperCase()); + } + return sign.toString(); + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/StringUtils.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/StringUtils.java new file mode 100644 index 0000000..bfeb618 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/StringUtils.java @@ -0,0 +1,75 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +/** + * 字符串工具类 + * + * @author shuanglin.luo + * + */ +public class StringUtils{ + + /** + * 检查指定的字符串是否为空。 + *
    + *
  • SysUtils.isEmpty(null) = true
  • + *
  • SysUtils.isEmpty("") = true
  • + *
  • SysUtils.isEmpty(" ") = true
  • + *
  • SysUtils.isEmpty("abc") = false
  • + *
+ * + * @param value + * 待检查的字符串 + * @return true/false + */ + public static boolean isEmpty(String value){ + int strLen; + if (value == null || (strLen = value.length()) == 0){ + return true; + } + for (int i = 0; i < strLen; i++){ + if ((Character.isWhitespace(value.charAt(i)) == false)){ + return false; + } + } + return true; + } + + /** + * 检查对象是否为数字型字符串,包含负数开头的。 + */ + public static boolean isNumeric(Object obj){ + if (obj == null){ + return false; + } + char[] chars = obj.toString().toCharArray(); + int length = chars.length; + if (length < 1) + return false; + + int i = 0; + if (length > 1 && chars[0] == '-') + i = 1; + + for (; i < length; i++){ + if (!Character.isDigit(chars[i])){ + return false; + } + } + return true; + } + + /** + * 检查指定的字符串列表是否不为空。 + */ + public static boolean areNotEmpty(String...values){ + boolean result = true; + if (values == null || values.length == 0){ + result = false; + }else{ + for (String value : values){ + result &= !isEmpty(value); + } + } + return result; + } +} diff --git a/src/main/java/com/cmsen/ticket/infrastructure/tools/util/WebUtils.java b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/WebUtils.java new file mode 100644 index 0000000..1f0ce88 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/infrastructure/tools/util/WebUtils.java @@ -0,0 +1,462 @@ +package com.cmsen.ticket.infrastructure.tools.util; + +import javax.net.ssl.*; +import java.io.*; +import java.net.*; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + + +/** + * 网络工具类。 + * + * @author carver.gu + * @since 1.0, Sep 12, 2009 + */ +public abstract class WebUtils{ + + private static final String DEFAULT_CHARSET = Constants.CHARSET_UTF8; + + private static boolean ignoreSSLCheck = true; // 忽略SSL检查 + + private static boolean ignoreHostCheck = true; // 忽略HOST检查 + + public static class TrustAllTrustManager implements X509TrustManager{ + + public X509Certificate[] getAcceptedIssuers(){ + return null; + } + + public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException{ + } + + public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException{ + } + } + + private WebUtils(){ + } + + public static void setIgnoreSSLCheck(boolean ignoreSSLCheck){ + WebUtils.ignoreSSLCheck = ignoreSSLCheck; + } + + public static void setIgnoreHostCheck(boolean ignoreHostCheck){ + WebUtils.ignoreHostCheck = ignoreHostCheck; + } + + /** + * 执行HTTP POST请求。 + * + * @param url + * 请求地址 + * @param params + * 请求参数 + * @return 响应字符串 + * @throws Exception + */ + public static String doPost(String url,Map params,int connectTimeout,int readTimeout) throws Exception{ + return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout); + } + + /** + * 执行HTTP POST请求。 + * + * @param url + * 请求地址 + * @param params + * 请求参数 + * @param charset + * 字符集,如UTF-8, GBK, GB2312 + * @return 响应字符串 + * @throws Exception + */ + public static String doPost(String url,Map params,String charset,int connectTimeout,int readTimeout) throws Exception{ + return doPost(url, params, charset, connectTimeout, readTimeout, null, null); + } + + public static String doPost(String url,Map params,String charset,int connectTimeout,int readTimeout,Map headerMap,Proxy proxy) throws Exception{ + String ctype = "application/x-www-form-urlencoded;charset=" + charset; + String query = buildQuery(params, charset); + byte[] content = {}; + if (query != null){ + content = query.getBytes(charset); + } + return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap, proxy); + } + + public static String doPost(String url,String apiBody,String charset,int connectTimeout,int readTimeout,Map headerMap) throws Exception{ + String ctype = "text/plain;charset=" + charset; + byte[] content = apiBody.getBytes(charset); + return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap, null); + } + + /** + * 执行HTTP POST请求。 + * + * @param url + * 请求地址 + * @param ctype + * 请求类型 + * @param content + * 请求字节数组 + * @return 响应字符串 + * @throws Exception + */ + public static String doPost(String url,String ctype,byte[] content,int connectTimeout,int readTimeout) throws Exception{ + return _doPost(url, ctype, content, connectTimeout, readTimeout, null, null); + } + + /** + * 执行HTTP POST请求。 + * + * @param url + * 请求地址 + * @param ctype + * 请求类型 + * @param content + * 请求字节数组 + * @param headerMap + * 请求头部参数 + * @return 响应字符串 + * @throws Exception + */ + public static String doPost(String url,String ctype,byte[] content,int connectTimeout,int readTimeout,Map headerMap,Proxy proxy) throws Exception{ + return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap, proxy); + } + + private static String _doPost(String url,String ctype,byte[] content,int connectTimeout,int readTimeout,Map headerMap,Proxy proxy) throws Exception{ + HttpURLConnection conn = null; + OutputStream out = null; + String rsp = null; + try{ + conn = getConnection(new URL(url), Constants.METHOD_POST, ctype, headerMap, proxy); + conn.setConnectTimeout(connectTimeout); + conn.setReadTimeout(readTimeout); + out = conn.getOutputStream(); + out.write(content); + rsp = getResponseAsString(conn); + }catch(Exception e){ + e.printStackTrace(); + throw e; + }finally{ + if (out != null){ + out.close(); + } + if (conn != null){ + conn.disconnect(); + } + } + + return rsp; + } + + /** + * 执行HTTP GET请求。 + * + * @param url + * 请求地址 + * @param params + * 请求参数 + * @return 响应字符串 + */ + public static String doGet(String url,Map params) throws IOException{ + return doGet(url, params, DEFAULT_CHARSET); + } + + /** + * 执行HTTP GET请求。 + * + * @param url + * 请求地址 + * @param params + * 请求参数 + * @param charset + * 字符集,如UTF-8, GBK, GB2312 + * @return 响应字符串 + */ + public static String doGet(String url,Map params,String charset) throws IOException{ + HttpURLConnection conn = null; + String rsp = null; + + try{ + String ctype = "application/x-www-form-urlencoded;charset=" + charset; + String query = buildQuery(params, charset); + conn = getConnection(buildGetUrl(url, query), Constants.METHOD_GET, ctype, null, null); + rsp = getResponseAsString(conn); + }finally{ + if (conn != null){ + conn.disconnect(); + } + } + + return rsp; + } + + private static HttpURLConnection getConnection(URL url,String method,String ctype,Map headerMap,Proxy proxy) throws IOException{ + HttpURLConnection conn = null; + if (proxy == null){ + conn = (HttpURLConnection) url.openConnection(); + }else{ + conn = (HttpURLConnection) url.openConnection(proxy); + } + if (conn instanceof HttpsURLConnection){ + HttpsURLConnection connHttps = (HttpsURLConnection) conn; + if (ignoreSSLCheck){ + try{ + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(null, new TrustManager[] { new TrustAllTrustManager() }, new SecureRandom()); + connHttps.setSSLSocketFactory(ctx.getSocketFactory()); + connHttps.setHostnameVerifier(new HostnameVerifier(){ + + public boolean verify(String hostname,SSLSession session){ + return true; + } + }); + }catch (Exception e){ + throw new IOException(e.toString()); + } + }else{ + if (ignoreHostCheck){ + connHttps.setHostnameVerifier(new HostnameVerifier(){ + + public boolean verify(String hostname,SSLSession session){ + return true; + } + }); + } + } + conn = connHttps; + } + + conn.setRequestMethod(method); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setRequestProperty("Host", url.getHost()); +// conn.setRequestProperty("Accept", "text/xml,text/javascript"); + conn.setRequestProperty("User-Agent", "top-sdk-java"); + conn.setRequestProperty("Content-Type", ctype); + if(headerMap!=null && headerMap.entrySet()!=null) { + for(Entry entry:headerMap.entrySet()) { + conn.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + + + return conn; + } + + + + private static URL buildGetUrl(String url,String query) throws IOException{ + if (StringUtils.isEmpty(query)){ + return new URL(url); + } + + return new URL(buildRequestUrl(url, query)); + } + + public static String buildRequestUrl(String url,String...queries){ + if (queries == null || queries.length == 0){ + return url; + } + + StringBuilder newUrl = new StringBuilder(url); + boolean hasQuery = url.contains("?"); + boolean hasPrepend = url.endsWith("?") || url.endsWith("&"); + + for (String query : queries){ + if (!StringUtils.isEmpty(query)){ + if (!hasPrepend){ + if (hasQuery){ + newUrl.append("&"); + }else{ + newUrl.append("?"); + hasQuery = true; + } + } + newUrl.append(query); + hasPrepend = false; + } + } + return newUrl.toString(); + } + + public static String buildQuery(Map params,String charset) throws IOException{ + if (params == null || params.isEmpty()){ + return null; + } + + StringBuilder query = new StringBuilder(); + Set> entries = params.entrySet(); + boolean hasParam = false; + + for (Entry entry : entries){ + String name = entry.getKey(); + String value = entry.getValue(); + // 忽略参数名或参数值为空的参数 + if (StringUtils.areNotEmpty(name, value)){ + if (hasParam){ + query.append("&"); + }else{ + hasParam = true; + } + + query.append(name).append("=").append(URLEncoder.encode(value, charset)); + } + } + + return query.toString(); + } + + protected static String getResponseAsString(HttpURLConnection conn) throws IOException{ + String charset = getResponseCharset(conn.getContentType()); + if (conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST){ + return getStreamAsString(conn.getInputStream(), charset); + }else{ + // OAuth bad request always return 400 status + if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST){ + InputStream error = conn.getErrorStream(); + if (error != null){ + return getStreamAsString(error, charset); + } + } + // Client Error 4xx and Server Error 5xx + throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage()); + } + } + + public static String getStreamAsString(InputStream stream,String charset) throws IOException{ + try{ + Reader reader = new InputStreamReader(stream, charset); + StringBuilder response = new StringBuilder(); + + final char[] buff = new char[1024]; + int read = 0; + while ((read = reader.read(buff)) > 0){ + response.append(buff, 0, read); + } + + return response.toString(); + }finally{ + if (stream != null){ + stream.close(); + } + } + } + + public static String getResponseCharset(String ctype){ + String charset = DEFAULT_CHARSET; + + if (!StringUtils.isEmpty(ctype)){ + String[] params = ctype.split(";"); + for (String param : params){ + param = param.trim(); + if (param.startsWith("charset")){ + String[] pair = param.split("=", 2); + if (pair.length == 2){ + if (!StringUtils.isEmpty(pair[1])){ + charset = pair[1].trim(); + } + } + break; + } + } + } + + return charset; + } + + /** + * 使用默认的UTF-8字符集反编码请求参数值。 + * + * @param value + * 参数值 + * @return 反编码后的参数值 + */ + public static String decode(String value){ + return decode(value, DEFAULT_CHARSET); + } + + /** + * 使用默认的UTF-8字符集编码请求参数值。 + * + * @param value + * 参数值 + * @return 编码后的参数值 + */ + public static String encode(String value){ + return encode(value, DEFAULT_CHARSET); + } + + /** + * 使用指定的字符集反编码请求参数值。 + * + * @param value + * 参数值 + * @param charset + * 字符集 + * @return 反编码后的参数值 + */ + public static String decode(String value,String charset){ + String result = null; + if (!StringUtils.isEmpty(value)){ + try{ + result = URLDecoder.decode(value, charset); + }catch (IOException e){ + throw new RuntimeException(e); + } + } + return result; + } + + /** + * 使用指定的字符集编码请求参数值。 + * + * @param value + * 参数值 + * @param charset + * 字符集 + * @return 编码后的参数值 + */ + public static String encode(String value,String charset){ + String result = null; + if (!StringUtils.isEmpty(value)){ + try{ + result = URLEncoder.encode(value, charset); + }catch (IOException e){ + throw new RuntimeException(e); + } + } + return result; + } + + /** + * 从URL中提取所有的参数。 + * + * @param query + * URL地址 + * @return 参数映射 + */ + public static Map splitUrlQuery(String query){ + Map result = new HashMap(); + + String[] pairs = query.split("&"); + if (pairs != null && pairs.length > 0){ + for (String pair : pairs){ + String[] param = pair.split("=", 2); + if (param != null && param.length == 2){ + result.put(param[0], param[1]); + } + } + } + + return result; + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/CompanyFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/CompanyFacade.java new file mode 100644 index 0000000..b92c3bf --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/CompanyFacade.java @@ -0,0 +1,93 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.CompanyService; +import com.cmsen.ticket.domain.entity.Company; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +/** + * (Company)表控制层 + * + * @author ran hao yu + * @since 2020-09-18 14:11:43 + */ +@RestController +@RequestMapping("mini/company") +public class CompanyFacade { + /** + * 服务对象 + */ + @Resource + private CompanyService companyService; + + /** + * 通过主键查询单条数据 + * + * @param id 主键 + * @return 单条数据 + */ + @GetMapping("selectOne") + public Company selectOne(Integer id) { + return this.companyService.queryById(id); + } + + /** + * 查询所有 + * + * @return + */ + @GetMapping("queryAll") + public List queryAll(@RequestParam(name = "code",required = false) String code, + @RequestParam(name = "name",required = false)String name, + @RequestParam(name = "taxNo",required = false)String taxNo) { + return this.companyService.queryAllByLimit(code,name,taxNo); + } + + /** + * 更新 + * + * @param company + * @return + */ + @PutMapping("update") + public Company update(@RequestBody Company company) { + return this.companyService.update(company); + } + + /** + * 保存 + * + * @param company + * @return + */ + @PostMapping("insert") + public RestResponse insert(@RequestBody Company company) { + return companyService.insert(company); + } + + /** + * 启用 + * + * @param id + * @return + */ + @PostMapping("active") + public RestResponse active(Integer id) { + return companyService.active(id); + } + + /** + * 停用 + * + * @param id + * @return + */ + @PostMapping("clock") + public RestResponse clock(Integer id) { + return companyService.clock(id); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/CorporateInvoiceFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/CorporateInvoiceFacade.java new file mode 100644 index 0000000..cff3412 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/CorporateInvoiceFacade.java @@ -0,0 +1,80 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.Files; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/1/16 16:39 + **/ + +@RestController +@RequestMapping("mini/corporate/invoice") +public class CorporateInvoiceFacade { + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @GetMapping + public RestResponse selectByLoginId(@RequestParam(required = false) Map params) { + return corporateInvoiceService.selectByLoginId(params); + } + + @GetMapping("selectDetailById/{id}") + public RestResponse selectDetailById(@PathVariable("id") String id) { + return corporateInvoiceService.selectDetailById(id); + } + + @PutMapping + public RestResponse update(@RequestBody CorporateInvoice corporateInvoice) { + return corporateInvoiceService.update(corporateInvoice); + } + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") String id) { + return corporateInvoiceService.delete(id); + } + + @PostMapping("identify") + public RestResponse identify(@RequestBody Files files) { + return corporateInvoiceService.identify(files); + } + + @PostMapping("insert") + public RestResponse insert(@RequestBody CorporateInvoice corporateInvoice) { + return corporateInvoiceService.insert(corporateInvoice); + } + + //获取借贷信息的json + @GetMapping("{id}") + public RestResponse getAccount(@PathVariable("id") String id){ + return corporateInvoiceService.getAccount(id); + } + + + //凭证导入状态回写 + @PutMapping("setValidStatus/{status}/{id}") + public RestResponse setValidStatus(@PathVariable("status") Boolean status,@PathVariable("id") String id){ + return corporateInvoiceService.setValidStatus(status, id); + } + + //发票接收 + @PostMapping("insertClassify") + public RestResponse invoiceReceive(@RequestBody CorporateInvoice corporateInvoice){ + + return RestResponse.success(); + } + + @ApiOperation("获取组织列表") + @GetMapping("/getOrgList") + public RestResponse getOrgList(@RequestParam("loginId") String loginId) { + return corporateInvoiceService.getOrgList(loginId); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/CurrencyFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/CurrencyFacade.java new file mode 100644 index 0000000..c4791ed --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/CurrencyFacade.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SupplierService; +import com.cmsen.ticket.application.service.CurrencyService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author ran hao yu + * @date 2020/8/7 9:16 + * @description + */ +@RestController +@RequestMapping("mini/Currency") +public class CurrencyFacade { + @Resource + private CurrencyService currencyService; + + @Resource + private SupplierService supplierService; + + //税率list + @GetMapping("/tax") + public RestResponse taxList(){ + return supplierService.selectList(); + } + + //货币类型接口 + @GetMapping("/selectList") + public RestResponse selectList(@RequestParam String name) { + return currencyService.selectList(name); + } + + @PostMapping("/addCurrency") + public RestResponse addCurrency(@RequestBody Map map) { + return currencyService.insertActive(map); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/CustomerFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/CustomerFacade.java new file mode 100644 index 0000000..6d886dc --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/CustomerFacade.java @@ -0,0 +1,46 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.cmsen.ticket.application.service.CustomerService; +import com.cmsen.ticket.domain.entity.Customer; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +/** + * (Customer)表控制层 + * + * @author ran hao yu + * @since 2020-09-18 14:11:43 + */ +@RestController +@RequestMapping("mini/customer") +public class CustomerFacade { + /** + * 服务对象 + */ + @Resource + private CustomerService customerService; + + /** + * 通过主键查询单条数据 + * + * @param id 主键 + * @return 单条数据 + */ + @GetMapping("selectOne") + public Customer selectOne(Integer id) { + return this.customerService.queryById(id); + } + + @PostMapping("queryAll") + public List queryAll(@RequestBody Customer customer) { + return this.customerService.queryAll(customer); + } + + @PutMapping("update") + public Customer update(@RequestBody Customer customer) { + return this.customerService.update(customer); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/HelpFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/HelpFacade.java new file mode 100644 index 0000000..025e14b --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/HelpFacade.java @@ -0,0 +1,60 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.domain.mapper.SysNotificationMapper; +import com.cmsen.ticket.domain.mapper.UserGuideMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author ran hao yu + * @date 2020/8/7 9:51 + * @description + */ +@RestController +@RequestMapping("mini/infos") +public class HelpFacade { + @Resource + private UserGuideMapper userGuideMapper; + + @Resource + private SysNotificationMapper sysNotificationMapper; + + @Resource + private SysConfigMapper sysConfigMapper; + + @GetMapping("note") + public RestResponse getNote() { + return RestResponse.success(sysNotificationMapper.getList(1)); + } + + @GetMapping("guide") + public RestResponse getGuide() { + return RestResponse.success(userGuideMapper.getList()); + } + + @GetMapping("privacy") + public RestResponse getPrivacy() { + return RestResponse.success(sysNotificationMapper.getPrivacy()); + } + + @GetMapping("hotPolicies") + public RestResponse getHotPolicies() { + return RestResponse.success(sysNotificationMapper.getHotPolicies()); + } + + + @ApiOperation("获取SysConfig配置") + @GetMapping("/getSysConfig") + public RestResponse getSysConfig(@RequestParam String code){ + return RestResponse.success(sysConfigMapper.selectByCode(code)); + } + + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/ScannerFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/ScannerFacade.java new file mode 100644 index 0000000..9ea7c94 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/ScannerFacade.java @@ -0,0 +1,366 @@ +package com.cmsen.ticket.interfaces.facade; + +import cn.hutool.core.date.DateUtil; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.util.Base64Util; +import com.cmsen.common.util.StorageCache; +import com.cmsen.common.util.StringUtil; +import com.cmsen.ticket.application.manager.service.impl.SysCorInvoiceServiceImpl; +import com.cmsen.ticket.domain.entity.CorporateInvoiceType; +import com.cmsen.ticket.domain.entity.ScannerLogs; +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.exception.ScannerException; +import com.cmsen.ticket.domain.mapper.CorporateInvoiceTypeMapper; +import com.cmsen.ticket.domain.mapper.ScannerLogsMapper; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysOrgMapper; +import com.cmsen.ticket.domain.util.Pdf2JpgHelper; +import com.cmsen.ticket.domain.vo.FileVo; +import com.cmsen.ticket.infrastructure.ocr2.OFDUtil; +import com.cmsen.ticket.infrastructure.ocr2.RuiZhenOCRService; +import com.cmsen.ticket.interfaces.facade.form.ScannerInfo; +import com.cmsen.ticket.interfaces.facade.form.ScannerLogSearch; +import com.cmsen.ticket.interfaces.facade.form.ScannerPostDate; +import com.cmsenframework.security.RequestSecurityPolicy; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.Executor; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/7/5 11:17 + **/ +@Api(tags = "扫描仪对接") +@Slf4j +@RestController +@RequestMapping("scanner") +public class ScannerFacade { + + @Resource + private SysOrgMapper sysOrgMapper; + + @Value("${manager-file.uploadPath}") + private String uploadPath; + + @Value("${manager-file.viewPath}") + private String viewPath; + +// @Value("${manager-file.watchPath.sap1}") +// private String goods; + +// @Value("${manager-file.watchPath.sap2}") +// private String service; + + @Resource + @Qualifier(value = "ScannerPool") + private Executor scannerPool; + + @Resource + private ScannerLogsMapper scannerLogsMapper; + + @Resource + private CorporateInvoiceTypeMapper corporateInvoiceTypeMapper; + + @Resource + private RuiZhenOCRService ruiZhenOCRService; + + @Value("${manager-file.watchPath}") + private String watchPath; + + @Resource + private SysConfigMapper sysConfigMapper; + + @Value("${file.domainName}") + private String domainName; + @Value("${server.servlet.context-path}") + private String contextPath; + @Value("${img.img-virtual-Path}") + private String imgVirtualPath; + @Value("${file.filepath}") + private String invoicePic; + + @Resource + private SysCorInvoiceServiceImpl sysCorInvoiceService; + + + @ApiOperation("获取信息") + @PostMapping("info") + public ScannerInfo getScannerInfo() { + + List corporateInvoiceTypes = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setActive(true); + }}); + ScannerInfo scannerInfo = new ScannerInfo(); + List data = new ArrayList<>(); + for (CorporateInvoiceType corporateInvoiceType : corporateInvoiceTypes) { + data.add(new ScannerInfo.Data(corporateInvoiceType.getName(), corporateInvoiceType.getCode())); + } + scannerInfo.setCostType(data); + List orgs = new ArrayList<>(); + List list = sysOrgMapper.list(null); + for (SysOrg sysOrg : list) { + orgs.add(new ScannerInfo.Data(sysOrg.getName(), sysOrg.getCode())); + } + scannerInfo.setOrganization(orgs); + return scannerInfo; + } + + + @ApiOperation("文件上传") + @PostMapping("upload") + public RestResponse upload(ScannerPostDate postDate) { + try { + log.info("Scanner>>" + postDate.toString()); + MultipartFile file = postDate.getFile(); + String type = postDate.getCostType(); + String com = postDate.getCompanyId(); + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + SysOrg org = sysOrgMapper.selectByCode(com); + if(null==org){ + throw new ScannerException("参数companyId 非合法值。"); + } + Integer orgId = org.getId(); + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(".pdf".equalsIgnoreCase(suffix) || ".ofd".equalsIgnoreCase(suffix))) { + throw new ScannerException("错误的文件类型,请上传PDF,OFD文件。"); + } + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setCode(postDate.getCostType()); + }}).get(0); +// String savePath = corporateInvoiceTypes.get(0).getPath(); +// String savePath = "service".equals(type) ? service : goods; + String fileName = "Scanner-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + suffix; + String folder = Pdf2JpgHelper.generateFolder(uploadPath); + String uploadFilePath = uploadPath + folder + fileName; + String filename; + //添加log + try { + byte[] decode = Base64Util.decode(postDate.getFilename()); + filename = new String(decode, "GB18030"); + } catch (Exception e) { +// log.error(e.getMessage(),e); + filename = null; + } + String resultFileName = StringUtil.isBlank(filename) ? originalFilename : filename; + String today = DateUtil.format(new Date(), "yyyy-MM-dd"); + log.info("resultFileName=>{}",resultFileName); + + // 添加配置开关 + SysConfig needValid = sysConfigMapper.selectByCode("SCANNER_UPLOAD_VALID"); + if(null==needValid||"1".equals(needValid.getValue())){ + Integer scannerId = scannerLogsMapper.selectByNameToday(resultFileName,today); + if(null!=scannerId){ + return RestResponse.failure("当天请勿重复导入相同文件"); + } + }else{ + Integer scannerId = scannerLogsMapper.selectByNameToday(resultFileName,today); + if(null!=scannerId){ + return RestResponse.success(scannerId); + } + } + + int userId = (int) RequestSecurityPolicy.getUserId(); +// int userId = 0; + ScannerLogs scannerLogs = new ScannerLogs(); + scannerLogs.setCostType(postDate.getCostType()); + scannerLogs.setCompanyId(postDate.getCompanyId()); + scannerLogs.setFileName(StringUtil.isBlank(filename) ? originalFilename : filename); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setHashKey(postDate.getHashKey()); + scannerLogs.setExt02("V1"); + scannerLogs.setMachineCode(postDate.getMachineCode()); + scannerLogsMapper.insert(scannerLogs); + log.info("uploadFilePath=>{}",uploadFilePath); + file.transferTo(new File(uploadFilePath)); + + SysConfig fldConfig = sysConfigMapper.selectByCode("FLD_SCANNER_CONFIG"); + if(null==fldConfig||"0".equals(fldConfig.getValue())){ + if (".pdf".equalsIgnoreCase(suffix)) { + scannerPool.execute(()-> sysCorInvoiceService.eleFirstOcrLeft( + folder + ,invoicePic + , uploadFilePath + ,postDate + ,watchPath + ,userId + ,orgId + ,originalFilename + ,corporateInvoiceType + ,scannerLogs + ,com + ,uploadPath)); +// String newImgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpg"; +// String imgRealPath = invoicePic + java.io.File.separator + folder + newImgName; +// Pdf2JpgHelper.pdfToImage2(uploadFilePath,imgRealPath); +// RuiZhenOCREntity ocrEntity = ruiZhenOCRService.billsCropFHOfElectronic(Base64Util.fileToBase64(uploadFilePath)); +// if(0==ocrEntity.getResult()){ +// scannerPool.execute(() -> Pdf2JpgHelper.pdfToImages2AndSaveCache(postDate.getHashKey(), uploadFilePath, watchPath, false, com, null, corporateInvoiceType,scannerLogs.getId(),sysConfigMapper)); +// }else{ +// sysCorInvoiceService.invoiceVAT(ocrEntity,2,userId,orgId,folder,fileName,uploadFilePath,corporateInvoiceType,scannerLogs.getId()); +// } + } else { + String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + ".jpeg"; + String newImagePath = watchPath + newFileName; + StorageCache.write(newFileName, com, 1000 * 60 * 30); + StorageCache.write("Owner." + newFileName, userId, 1000 * 60 * 30); + StorageCache.write("HashKey." + newFileName, scannerLogs.getHashKey(), 1000 * 60 * 30); + StorageCache.write("CorType." + newFileName, corporateInvoiceType, 1000 * 60 * 30); + StorageCache.write("PdfUrl." + newFileName, uploadFilePath, 1000 * 60 * 30); + StorageCache.write("scannerLogs." + newFileName, scannerLogs.getId(), 1000 * 60 * 30); + log.info("fileName===>{}",fileName); + log.info("newFileName===>{}",newFileName); + log.info("corporateInvoiceType===>{}",corporateInvoiceType); + log.info("newImagePath====>{}",newImagePath); + OFDUtil.dealOFDToJPEG(uploadFilePath, newImagePath); + } + }else{ + scannerPool.execute(() -> Pdf2JpgHelper.pdfToImages2AndSaveCache(null,postDate.getHashKey(), uploadFilePath, watchPath, false, com, null, corporateInvoiceType,scannerLogs.getId(),sysConfigMapper)); + } + return RestResponse.success(scannerLogs.getId()); + } catch (Exception e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + throw new ScannerException(); + } + } + + @ApiOperation("文件上传V2") + @PostMapping("uploadV2") + public RestResponse uploadV2(ScannerPostDate postDate) { + try { + log.info("Scanner>>" + postDate.toString()); + MultipartFile file = postDate.getFile(); + String type = postDate.getCostType(); + String com = postDate.getCompanyId(); + String originalFilename = file.getOriginalFilename(); + assert originalFilename != null; + SysOrg org = sysOrgMapper.selectByCode(com); + if(null==org){ + throw new ScannerException("参数companyId 非合法值。"); + } + Integer orgId = org.getId(); + String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); + if (!(".pdf".equalsIgnoreCase(suffix) || ".ofd".equalsIgnoreCase(suffix))) { + throw new ScannerException("错误的文件类型,请上传PDF,OFD文件。"); + } + CorporateInvoiceType corporateInvoiceType = corporateInvoiceTypeMapper.selectByRecord(new CorporateInvoiceType() {{ + setCode(postDate.getCostType()); + }}).get(0); +// String savePath = corporateInvoiceTypes.get(0).getPath(); +// String savePath = "service".equals(type) ? service : goods; + String fileName = "Scanner-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + StringUtil.UUID() + suffix; + String folder = Pdf2JpgHelper.generateFolder(uploadPath); + String uploadFilePath = uploadPath + folder + fileName; + String filename; + //添加log + try { + byte[] decode = Base64Util.decode(postDate.getFilename()); + filename = new String(decode, "GB18030"); + } catch (Exception e) { +// log.error(e.getMessage(),e); + filename = null; + } + String resultFileName = StringUtil.isBlank(filename) ? originalFilename : filename; + String today = DateUtil.format(new Date(), "yyyy-MM-dd"); + log.info("resultFileName=>{}",resultFileName); + + // 这个不许要再处理同名问题 +// SysConfig needValid = sysConfigMapper.selectByCode("SCANNER_UPLOAD_VALID"); +// if(null==needValid||"1".equals(needValid.getValue())){ +// Integer scannerId = scannerLogsMapper.selectByNameToday(resultFileName,today); +// if(null!=scannerId){ +// return RestResponse.failure("当天请勿重复导入相同文件"); +// } +// }else{ +// Integer scannerId = scannerLogsMapper.selectByNameToday(resultFileName,today); +// if(null!=scannerId){ +// return RestResponse.success(scannerId); +// } +// } + + int userId = (int) RequestSecurityPolicy.getUserId(); +// int userId = 0; + ScannerLogs scannerLogs = new ScannerLogs(); + scannerLogs.setCostType(postDate.getCostType()); + scannerLogs.setCompanyId(postDate.getCompanyId()); + scannerLogs.setFileName(StringUtil.isBlank(filename) ? originalFilename : filename); + scannerLogs.setSendTime(new Date()); + scannerLogs.setInvoiceUpNum(0); + scannerLogs.setErrorNum(0); + scannerLogs.setExt02("V2"); + scannerLogs.setHashKey(postDate.getHashKey()); + scannerLogs.setMachineCode(postDate.getMachineCode()); + + log.info("uploadFilePath=>{}",uploadFilePath); + // 移动重命名 + File fileVo = new File(uploadFilePath); + file.transferTo(fileVo); + int ncImportId = 0; + try { + FileVo fileVo1 = new FileVo(); + fileVo1.setFileName(scannerLogs.getFileName()); + fileVo1.setFilePath(fileVo.getAbsolutePath()); + List listV = new ArrayList<>(); + listV.add(fileVo1); + JSONObject ncData = sysCorInvoiceService.ncImport(listV); + if(null!=ncData){ + int ncImportIdA =ncData.getJSONObject("data").getJSONObject("record").getInteger("id"); + // 异步执行 ncimport + log.info("系统异步执行nc export 结果 =》{}",resultFileName); + scannerPool.execute(()-> sysCorInvoiceService.dealNcExport(ncImportIdA,userId,type,originalFilename,postDate.getCompanyId())); + ncImportId = ncImportIdA; + scannerLogs.setExt01(String.valueOf(ncImportId)); + scannerLogsMapper.insert(scannerLogs); + + } + }catch (Exception ex){ + ex.printStackTrace(); + } + if(0==ncImportId){ + return RestResponse.failure("NC拆套识别异常"); + } + return RestResponse.success(ncImportId); + } catch (Exception e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + throw new ScannerException(); + } + } + + @PostMapping("log") + public Object getLogs(@RequestBody ScannerLogSearch search) { + try { + return scannerLogsMapper.listForSearch(search); + } catch (Exception e) { + log.error(e.getMessage(), e); + return new ArrayList<>(); + } + } + + public static void main(String qwe[]){ + String filename = "test验真.pdf"; + byte[] bt = filename.getBytes(); + System.out.println(Base64Util.encodeToString(bt)); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/UserPcFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/UserPcFacade.java deleted file mode 100644 index 74f45b5..0000000 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/UserPcFacade.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.cmsen.ticket.interfaces.facade; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author fenql - * @date 2022/8/17 11:33 - * @description - */ -@Slf4j -@RestController -@RequestMapping("mini/userPc") -public class UserPcFacade { - } diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/WeiTaiOcrFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/WeiTaiOcrFacade.java new file mode 100644 index 0000000..abb6e23 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/WeiTaiOcrFacade.java @@ -0,0 +1,197 @@ +package com.cmsen.ticket.interfaces.facade; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SupplierService; +import com.cmsen.ticket.application.manager.service.SysOrgService; +import com.cmsen.ticket.application.service.CorpPaymentService; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.application.service.WeiTaiOcrService; +import com.cmsen.ticket.domain.entity.AccountObject; +import com.cmsen.ticket.domain.entity.CorpPaymentHeader; +import com.cmsen.ticket.domain.entity.Supplier; +import com.cmsen.ticket.domain.mapper.AccountObjectMapper; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("weitai") +@Slf4j +public class WeiTaiOcrFacade { + @Resource + private WeiTaiOcrService service; + @Resource + private CorporateInvoiceService corporateInvoiceService; + @Resource + private SupplierService supplierService; + @Resource + private CorpPaymentService corpPaymentService; + @Resource + private SysOrgService sysOrgService; + @Resource + private AccountObjectMapper accountObjectMapper; + + @GetMapping("supplier") + public RestResponse supplierList(@RequestParam(required = false) Map params) { + return service.supplierList(params); + } + + @PostMapping("supplier") + public RestResponse supplierInsert(@Validated(Validation.Create.class) @RequestBody Supplier supplier) { + return service.supplierInsert(supplier); + } + + @PostMapping("supplier/addList") + public RestResponse supplierInsertAdd(@RequestBody String jsonStr) { + JSONObject obj = JSONObject.parseObject(jsonStr); + List ls = JSONArray.parseArray(obj.getJSONArray("data").toString(), Supplier.class); + + return service.supplierInsertList(ls); + } + + @PutMapping("supplier") + public RestResponse supplierUpdate(@Validated(Validation.Update.class) @RequestBody Supplier supplier) { + return service.supplierUpdate(supplier); + } + + @DeleteMapping("supplier/{id}") + public RestResponse supplierDelete(@PathVariable("id") Integer id) { + return service.supplierDelete(id); + } + + //获取借贷信息的json + @GetMapping("corporate/invoice/{id}") + public RestResponse getAccount(@PathVariable("id") String id) { + return corporateInvoiceService.getAccount(id); + } + + //凭证导入状态回写 + @PutMapping("corporate/invoice/setValidStatus/{status}/{id}") + public RestResponse setValidStatus(@PathVariable("status") Boolean status, @PathVariable("id") String id) { + return corporateInvoiceService.setValidStatus(status, id); + } + + @ApiOperation("添加地址") + @PostMapping("manager/supplier/addAddress") + public RestResponse addAddress(String jsonStr) throws UnsupportedEncodingException { + jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); + JSONObject obj = JSONObject.parseObject(jsonStr); + //List ls= JSONArray.parseArray(obj.getJSONArray("data").toString(),SupplierOrder.class); + String data = obj.getJSONArray("data").toString(); +// String dataInput = URLDecoder.decode(data, "UTF-8"); + return supplierService.addAress(data); + } + + @ApiOperation("获取Ap发票数据") + @GetMapping("manager/supplier") + public RestResponse getSupplierOrderItem(@RequestParam("invoiceId") String invoiceId) { + log.info("获取Ap发票数据=>manager/supplier=>{}", invoiceId); + return supplierService.getSupplierOrderItem(invoiceId); + } + + @ApiOperation("获取Ap发票数据") + @GetMapping("manager/supplierRefund") + public RestResponse getSupplierRefund() { + return supplierService.getSupplierOrderRefund(); + } + + + @ApiOperation("获取Ap发票数据,根据状态") + @GetMapping("manager/supplierMore") + public RestResponse getSupplierOrderItemMore(@RequestParam("status") String status) { + return supplierService.getSupplierOrderItemMore(status); + } + + @PutMapping("manager/supplierMoreUp") + public RestResponse supplierMoreUpdate(String jsonStr) { + JSONObject obj = JSONObject.parseObject(jsonStr); + return supplierService.upInvoice(obj.getJSONArray("data").toString()); + + } + + @ApiOperation("添加供应商付款") + @PostMapping("corporate/payment/add") + public RestResponse addCorpPayment(@RequestBody CorpPaymentHeader corpPayment) { + return corpPaymentService.insertPayment(corpPayment); + } + + @ApiOperation("添加组织") + @PostMapping("sysOrg/addOrg") + public RestResponse addOrg(String jsonStr) { + JSONObject obj = JSONObject.parseObject(jsonStr); + + return sysOrgService.addOrg(obj.getJSONArray("data").toString()); + } + + @ApiOperation("更新科目") + @PostMapping("supplier/addAccount") + public RestResponse supplierInsertAccount(@RequestBody String jsonStr) { + JSONObject obj = JSONObject.parseObject(jsonStr); + List ls = JSONArray.parseArray(obj.getJSONArray("data").toString(), AccountObject.class); + for (AccountObject objA : ls) { + AccountObject a = accountObjectMapper.selectByAccount(objA.getAccount()); + if (a != null) { + objA.setId(a.getId()); + accountObjectMapper.updateByPrimaryKeySelective(objA); + } else { + accountObjectMapper.insert(objA); + } + } + return RestResponse.success(); + } + + @ApiOperation("供应商发票查询") + @GetMapping("corInvoice/list") + public RestResponse corInvoiceList(@RequestParam(required = false) Map params) { + log.info("供应商发票查询 参数>{}", JSONObject.toJSONString(params)); + return service.corInvoiceList(params); + } + + @ApiOperation("供应商发票po关系明细查询") + @GetMapping("corInvoice/corInvoiceAndPoAndDetailList") + public RestResponse corInvoiceAndPoAndDetailList(@RequestParam(required = false) Map params) { + return service.corInvoiceAndPoAndDetailList(params); + } + + @ApiOperation("付款申请单-同步合同申请人") + @PostMapping("payment/updateContractOwner") + public RestResponse updateContractOwner(@RequestBody String jsonStr) { + return service.updateContractOwner(jsonStr); + } + + @ApiOperation("付款申请单-同步内结申请人") + @PostMapping("payment/updateInternalOwner") + public RestResponse updateInternalOwner(@RequestBody String jsonStr) { + return service.updateInternalOwner(jsonStr); + } + + @ApiOperation("付款申请单-同步干系人") + @PostMapping("payment/updateFlowOwner") + public RestResponse updateFlowOwner(@RequestBody String jsonStr) { + return service.updateFlowOwner(jsonStr); + } + + @ApiOperation("付款申请单-更新状态") + @PostMapping("payment/updateStatus") + public RestResponse updateStatus(@RequestBody String jsonStr) { + return service.updateStatus(jsonStr); + } + + @ApiOperation("付款申请单-后票充值匹配状态重置") + @PostMapping("payment/updateMatchingStatus") + public RestResponse updateMatchingStatus(@RequestBody String jsonStr) { + return service.updateMatchingStatus(jsonStr); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/form/ConcurProxyUser.java b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ConcurProxyUser.java new file mode 100644 index 0000000..ddeb410 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ConcurProxyUser.java @@ -0,0 +1,18 @@ +package com.cmsen.ticket.interfaces.facade.form; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/3/10 18:48 + **/ +@Data +public class ConcurProxyUser { + @NotEmpty + private String email; + @NotEmpty + private String password; +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerInfo.java b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerInfo.java new file mode 100644 index 0000000..222ab63 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerInfo.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.interfaces.facade.form; + +import lombok.Data; + +import java.util.List; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/7/5 11:24 + **/ +@Data +public class ScannerInfo { + private List organization; + private List costType; + + public static class Data { + private String name; + private String value; + + public Data(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerLogSearch.java b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerLogSearch.java new file mode 100644 index 0000000..12085c5 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerLogSearch.java @@ -0,0 +1,17 @@ +package com.cmsen.ticket.interfaces.facade.form; + +import lombok.Data; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/9/6 13:21 + **/ +@Data +public class ScannerLogSearch { + private String companyId; + private String costType; + private String date; + private String machineCode; + private String ext01; +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerPostDate.java b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerPostDate.java new file mode 100644 index 0000000..71cec4a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/form/ScannerPostDate.java @@ -0,0 +1,20 @@ +package com.cmsen.ticket.interfaces.facade.form; + +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/7/5 11:54 + **/ +@Data +public class ScannerPostDate { + private String filename; + private MultipartFile file; + private String createTime; + private String companyId; + private String costType; + private String hashKey; + private String machineCode; +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/BandConfigFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/BandConfigFacade.java new file mode 100644 index 0000000..e654e5f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/BandConfigFacade.java @@ -0,0 +1,47 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.BandConfigService; +import com.cmsen.ticket.domain.entity.BandConfig; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +@RestController +@RequestMapping("manager/bandConfig") +public class BandConfigFacade { + @Resource + private BandConfigService bandConfigService; + + @GetMapping("/list") + public RestResponse list(@RequestParam(required = false) Map params) { + return bandConfigService.list(params); + } + + @PostMapping("/update") + public RestResponse update(@RequestBody BandConfig bandConfig) { + return bandConfigService.update(bandConfig); + } + + @PostMapping("/delete") + public RestResponse delete(@RequestParam Integer id) { + return bandConfigService.delete(id); + } + + @ApiOperation("导出") + @GetMapping("/export") + public RestResponse export(@RequestParam(required = false) Map params, HttpServletResponse response) { + return bandConfigService.export(params, response); + } + + @ApiOperation("导入") + @PostMapping("upload") + public RestResponse upload(MultipartFile file) { + return bandConfigService.upload(file); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/JsadapterFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/JsadapterFacade.java new file mode 100644 index 0000000..b432489 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/JsadapterFacade.java @@ -0,0 +1,42 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.JsadapterService; +import com.cmsen.ticket.domain.entity.Jsadapter; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author + * @version 1.0.0 + * @date 2026/07/16 16:19 + **/ +@RestController +@RequestMapping("manager/jsadapter") +public class JsadapterFacade { + @Resource + private JsadapterService jsadapterService; + + @GetMapping("/list") + public RestResponse select(@RequestParam(required = false) Map params) { + return jsadapterService.list(params); + } + + @PostMapping("/insert") + public RestResponse insert(@RequestBody Jsadapter jsadapter) { + return jsadapterService.create(jsadapter); + } + + @PostMapping("/update") + public RestResponse update(@RequestBody Jsadapter jsadapter) { + return jsadapterService.update(jsadapter); + } + + @PostMapping("/delete") + public RestResponse delete(@RequestParam Integer id) { + return jsadapterService.delete(id); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/PreferencesFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/PreferencesFacade.java new file mode 100644 index 0000000..9651b84 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/PreferencesFacade.java @@ -0,0 +1,52 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.PreferencesService; +import com.cmsen.ticket.domain.entity.Preferences; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +@RestController +@RequestMapping("manager/preferences") +public class PreferencesFacade { + @Resource + private PreferencesService preferencesService; + + @GetMapping("/list") + public RestResponse list(@RequestParam(required = false) Map params) { + return preferencesService.list(params); + } + + @PostMapping("/insert") + public RestResponse insert(@RequestBody Preferences preferences) { + return preferencesService.insert(preferences); + } + + @PostMapping("/update") + public RestResponse update(@RequestBody Preferences preferences) { + return preferencesService.update(preferences); + } + + @PostMapping("/delete") + public RestResponse delete(@RequestParam Integer id) { + return preferencesService.delete(id); + } + + @ApiOperation("导出") + @GetMapping("/export") + public RestResponse export(@RequestParam(required = false) Map params, HttpServletResponse response) { + return preferencesService.export(params, response); + } + + @ApiOperation("导入") + @PostMapping("upload") + public RestResponse upload(MultipartFile file) { + return preferencesService.upload(file); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/ProcureOderFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/ProcureOderFacade.java new file mode 100644 index 0000000..f99579f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/ProcureOderFacade.java @@ -0,0 +1,85 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.ProcureOrderService; +import com.cmsen.ticket.domain.entity.SupplierPo; +import com.cmsen.ticket.domain.entity.SupplierPoLine; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.util.Map; + +@Api(tags = "采购订单") +@RestController +@RequestMapping("manager/po") +public class ProcureOderFacade { + + @Resource + private ProcureOrderService procureOrderService; + + @ApiOperation("采购订单列表") + @GetMapping("/listPo") + public RestResponse listPo(@RequestParam(required = false) Map params) { + return procureOrderService.list(params); + } + + @ApiOperation("订单详情") + @GetMapping("/detail") + public RestResponse detail(@RequestParam String po) { + return procureOrderService.detail(po); + } + + @ApiOperation("新建订单") + @PostMapping("/insert") + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody SupplierPo supplierPo) { + return procureOrderService.create(supplierPo); + } + + @ApiOperation("编辑订单") + @PutMapping("/update") + public RestResponse update(@Validated(Validation.Update.class) @RequestBody SupplierPo supplierPo) { + return procureOrderService.update(supplierPo); + } + + @ApiOperation("订单删除") + @PostMapping("delete") + public RestResponse deletePo(@RequestParam Integer id) { + return procureOrderService.deletePo(id); + } + + @ApiOperation("订单明细列表") + @GetMapping("/line-list") + public RestResponse listLine(@RequestParam(required = false) Map params) { + return procureOrderService.lineList(params); + } + + @ApiOperation("新建订单明细") + @PostMapping("/insert-line") + public RestResponse insertLine(@Validated(Validation.Create.class) @RequestBody SupplierPoLine supplierPoLine) { + return procureOrderService.createLine(supplierPoLine); + } + + @ApiOperation("编辑订单明细") + @PutMapping("/update-line") + public RestResponse updateLine(@Validated(Validation.Update.class) @RequestBody SupplierPoLine supplierPoLine) { + return procureOrderService.updateLine(supplierPoLine); + } + + @ApiOperation("订单明细删除") + @PostMapping("/delete-line") + public RestResponse deleteLine(@RequestParam String ids, @RequestParam String po) { + return procureOrderService.deleteLine(ids, po); + } + + @ApiOperation("PO导入") + @PostMapping("/uploadPo") + public RestResponse uploadPo(MultipartFile file) { + return procureOrderService.uploadPo(file); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/RuleFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/RuleFacade.java new file mode 100644 index 0000000..480b59a --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/RuleFacade.java @@ -0,0 +1,47 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.RuleService; +import com.cmsen.ticket.application.manager.service.SysRulesService; +import com.cmsen.ticket.domain.entity.Rule; +import com.cmsen.ticket.domain.entity.RuleConfig; +import io.swagger.annotations.ApiOperation; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author + * @version 1.0.0 + * @date 2024/2/18 16:19 + **/ +@RestController +@RequestMapping("manager/rule") +public class RuleFacade { + @Resource + private RuleService ruleService; + + @GetMapping("/list") + public RestResponse select(@RequestParam(required = false) Map params) { + return ruleService.list(params); + } + + @PostMapping("/insert") + public RestResponse insert(@RequestBody Rule rule) { + return ruleService.create(rule); + } + + @PutMapping("/update") + public RestResponse update(@RequestBody Rule rule) { + return ruleService.update(rule); + } + + @DeleteMapping("/delete/{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return ruleService.delete(id); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SqlDownloadFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SqlDownloadFacade.java new file mode 100644 index 0000000..181f740 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SqlDownloadFacade.java @@ -0,0 +1,46 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SqlDownloadService; +import com.cmsen.ticket.domain.dto.SqlDownloadDto; +import com.cmsen.ticket.domain.response.Response; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + +/** + * @author OWTS + */ +@Api(tags = "数据SQL导出") +@RestController +@RequestMapping("manager/sqlData") +public class SqlDownloadFacade { + @Resource + private SqlDownloadService sqlDownloadService; + + @PostMapping("/getListData") + public Response> getListData(@RequestBody SqlDownloadDto downloadDto) { + return sqlDownloadService.getListData(downloadDto); + } + + @PostMapping("/getListData2") + public Response>> getListData2(@RequestBody SqlDownloadDto downloadDto) { + return sqlDownloadService.getListData2(downloadDto); + } + + /* @PostMapping("/exportListData") + public Response exportListData(@RequestBody SqlDownloadDto downloadDto, HttpServletResponse response) { + return sqlDownloadService.exportListData(downloadDto, response); + }*/ + + @GetMapping("exportListData") + public Response exportListData(@RequestParam(required = false) Map params, HttpServletResponse response) { + return sqlDownloadService.exportListData(params, response); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierFacade.java index e11d124..6600b1f 100644 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierFacade.java +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierFacade.java @@ -1,8 +1,30 @@ package com.cmsen.ticket.interfaces.facade.manager; +import com.alibaba.fastjson.JSONObject; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SupplierService; +import com.cmsen.ticket.domain.dto.LineMatchListDto; +import com.cmsen.ticket.domain.dto.SubmitLineMatchDto; +import com.cmsen.ticket.domain.entity.*; +import com.cmsen.ticket.domain.entity.manager.SupplierOrderItemMatching; +import com.cmsen.ticket.domain.entity.manager.SysOrg; +import com.cmsen.ticket.domain.entity.manager.SysUser; +import com.cmsen.ticket.domain.response.Response; +import com.cmsen.ticket.interfaces.facade.manager.form.*; import io.swagger.annotations.Api; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Map; /** * 供应商接口 @@ -15,4 +37,498 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("manager/supplier") public class SupplierFacade { + @Resource + private SupplierService supplierService; + + // ---------------供应商管理--------------- + + // 供应商信息列表 + @GetMapping("/information") + public RestResponse supplierInformationList(@Validated(ValidationForm.Pagination.class) SupplierSearchForm form) { + return supplierService.supplierInformationList(form); + } + + // 供应商信息创建 + @PostMapping("/information") + public RestResponse supplierInformationCreate(@RequestBody @Validated(Validation.Create.class) Supplier supplier) { + return supplierService.supplierInformationCreate(supplier); + } + + // 供应商信息更新 + @PutMapping("/information") + public RestResponse supplierInformationUpdate(@RequestBody @Validated(Validation.Update.class) Supplier supplier) { + return supplierService.supplierInformationUpdate(supplier); + } + + // 供应商信息删除 + @DeleteMapping("/information") + public RestResponse supplierInformationDelete(@NotNull Integer id) { + return supplierService.supplierInformationDelete(id); + } + + // ---------------供应商SITE_CODE--------------- + + // 供应商SITE_CODE信息列表 + @GetMapping("/site-code") + public RestResponse supplierSiteCodeList(@NotNull String code) { + return supplierService.supplierSiteCodeList(code); + } + + // 供应商SITE_CODE信息创建 + @PostMapping("/site-code") + public RestResponse supplierSiteCodeCreate(@RequestBody @Validated(Validation.Create.class) SupplierSite supplierSite) { + return supplierService.supplierSiteCodeCreate(supplierSite); + } + + // 供应商SITE_CODE信息更新 + @PutMapping("/site-code") + public RestResponse supplierSiteCodeUpdate(@RequestBody @Validated(Validation.Update.class) SupplierSite supplierSite) { + return supplierService.supplierSiteCodeUpdate(supplierSite); + } + + // 供应商SITE_CODE信息删除 + @DeleteMapping("/site-code") + public RestResponse supplierSiteCodeDelete(@NotNull Integer id) { + return supplierService.supplierSiteCodeDelete(id); + } + + // ---------------订单管理--------------- + + // 订单信息列表 + @GetMapping("/order") + public RestResponse supplierOrderList(@Validated(ValidationForm.Pagination.class) SupplierOrderSearchForm form) { + return supplierService.supplierOrderList(form); + } + + // 冻结订单信息列表 + @GetMapping("/refundOrder") + public RestResponse refundOrderList(@Validated(ValidationForm.Pagination.class) SupplierOrderSearchForm form) { + return supplierService.supplierRefundOrderList(form); + } + + // 导入冻结收货数据 + @DeleteMapping("/order/import/refund/{ids}") + public RestResponse deleteRefundOrders(@PathVariable String ids) { + return supplierService.deleteRefundOrders(ids); + } + + // 导入冻结收货数据 + @PostMapping("/order/import/refund") + public RestResponse refundImport(MultipartFile file) { + return supplierService.importSupplierOrderRefund(file); + } + + + + @ApiOperation("订单信息列表导出")//2022/5/27 + @GetMapping("/order-export") + public RestResponse orderExport(HttpServletResponse response, @RequestParam Map params,SupplierOrderSearchForm form) { + return supplierService.supplierOrderReport(params, response,form); + } + + @ApiOperation("批量删除收货数据")//2022/5/11 + @PutMapping("/order-update/{ids}") + public RestResponse supplierOrderUpdate(@PathVariable String ids) { + return supplierService.supplierOrderUpdate(ids); + } + + @ApiOperation("数据清理")//2022/5/11 + @PutMapping("/order-clear") + public RestResponse supplierOrderClear() { + return supplierService.supplierOrderClear(); + } + + @ApiOperation("PO发票查询")//2022/5/26 + @GetMapping("/order-POsearch") + public RestResponse supplierOrderPOSearch(@Validated(ValidationForm.Pagination.class) SupplierOrderSearchForm form) { + return supplierService.supplierOrderPOSearch(form); + } + + @ApiOperation("PO导出数据")//2022/5/26 + @GetMapping("/order-POexport") + public RestResponse supplierOrderPOExportExcel(HttpServletResponse response, @RequestParam Map params) { + return supplierService.supplierOrderPOExportExcel(params, response); + } + + @ApiOperation("PO批量下载附件")//2022/5/26 + @GetMapping("/order-POdownloadImages") + public RestResponse supplierOrderPODownloadImages(HttpServletResponse response, @RequestParam Map params) { + return supplierService.supplierOrderPODownloadImages(params, response); + } + + @ApiOperation("虚拟物料匹配报表")//2022/5/27 + @GetMapping("/order-matchReport") + public RestResponse supplierOrderMatchReport(HttpServletResponse response, @RequestParam Map params) { + return supplierService.supplierOrderMatchReport(params, response); + } + + + // ---------------物料管理--------------- + + // 物料信息列表 + @GetMapping("/material") + public RestResponse supplierMaterialList(@Validated(ValidationForm.Pagination.class) SupplierMaterialSearchForm form) { + return supplierService.supplierMaterialList(form); + } + + // 物料信息创建 + @PostMapping("/material") + public RestResponse supplierMaterialCreate(@RequestBody @Validated(Validation.Create.class) SupplierMaterial supplierMaterial) { + return supplierService.supplierMaterialCreate(supplierMaterial); + } + + // 物料信息更新 + @PutMapping("/material") + public RestResponse supplierMaterialUpdate(@RequestBody @Validated(Validation.Create.class) SupplierMaterial supplierMaterial) { + return supplierService.supplierMaterialUpdate(supplierMaterial); + } + + // 物料信息删除 + @DeleteMapping("/material") + public RestResponse supplierMaterialDelete(@NotNull Integer id) { + return supplierService.supplierMaterialDelete(id); + } + + // ---------------例外物料--------------- + + // 例外物料列表 + @GetMapping("/material-filter") + public RestResponse supplierMaterialFilterList(SupplierMaterialFilterSearchForm form) { + return supplierService.supplierMaterialFilterList(form); + } + + // 例外物料创建 + @PostMapping("/material-filter") + public RestResponse supplierMaterialFilterCreate(@RequestBody @Validated(Validation.Create.class) SupplierMaterialFilter supplierMaterialFilter) { + return supplierService.supplierMaterialFilterCreate(supplierMaterialFilter); + } + + // 例外物料更新 + @PutMapping("/material-filter") + public RestResponse supplierMaterialFilterUpdate(@RequestBody @Validated(Validation.Create.class) SupplierMaterialFilter supplierMaterialFilter) { + return supplierService.supplierMaterialFilterUpdate(supplierMaterialFilter); + } + + // 例外物料删除 + @DeleteMapping("/material-filter") + public RestResponse supplierMaterialFilterDelete(@NotNull Integer id) { + return supplierService.supplierMaterialFilterDelete(id); + } + + // ---------------单位换算--------------- + + // 单位换算列表 + @GetMapping("/material-uom") + public RestResponse supplierMaterialUomList(@Validated(ValidationForm.Pagination.class) SupplierMaterialUOMSearchForm form) { + return supplierService.supplierMaterialUomList(form); + } + + // 单位换算创建 + @PostMapping("/material-uom") + public RestResponse supplierMaterialUomCreate(@RequestBody @Validated(Validation.Create.class) SupplierMaterialUom supplierMaterialUom) { + return supplierService.supplierMaterialUomCreate(supplierMaterialUom); + } + + // 单位换算更新 + @PutMapping("/material-uom") + public RestResponse supplierMaterialUomUpdate(@RequestBody @Validated(Validation.Create.class) SupplierMaterialUom supplierMaterialUom) { + return supplierService.supplierMaterialUomUpdate(supplierMaterialUom); + } + + // 单位换算删除 + @DeleteMapping("/material-uom") + public RestResponse supplierMaterialUomDelete(@NotNull Integer id) { + return supplierService.supplierMaterialUomDelete(id); + } + + // ---------------发票匹配--------------- + + // 发票匹配列表 + @GetMapping("/invoice-match") + public RestResponse supplierInvoiceMatchList(@Validated({ValidationForm.Pagination.class, ValidationForm.Search.class}) SupplierInvoiceMatchForm form) { + return supplierService.SupplierInvoiceMatchList(form); + } + + // 发票匹配 发票列表 + @GetMapping("/match-invoices") + public RestResponse matchInvoices(@RequestParam String numberS, @RequestParam String numberE, @RequestParam Integer invoiceType) { + return supplierService.matchInvoices(numberS, numberE, invoiceType); + } + + // 确认发送 + @PostMapping("/confirm-send") + public RestResponse confirmSend(@RequestBody InvoiceConfirmAndSendForm invoiceConfirmAndSendForm) { + return supplierService.confirmSend(invoiceConfirmAndSendForm); + } + + // 按供应商代码匹配订单 + @ApiOperation("按供应商代码匹配订单") + @GetMapping("/invoice-match-order") + public RestResponse supplierInvoiceMatchOrderList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, + @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, + String invoiceId, Integer all, String orderNo) { + return supplierService.supplierInvoiceMatchOrderList(invoiceId, all, orderNo, pageNum, pageSize); + } + + @ApiOperation("查询未匹配完成的PO行") + @GetMapping("/invoice-match-order-podetail") + public RestResponse supplierOrderPOList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, + @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, String orderNo) { + return supplierService.supplierOrderPOList(orderNo, pageNum, pageSize); + } + + @ApiOperation("物料自动匹配") + @GetMapping("/material-auto-matching") + public RestResponse materialAutoMatching(String invoiceId) { + return supplierService.materialAutoMatching(invoiceId,null); + } + + @ApiOperation("一键智能匹配") + @GetMapping("/auto-smart-matching") + public RestResponse autoSmartMatching(String invoiceId) { + return supplierService.autoSmartMatching(invoiceId,null); + } + + // 查询供应商代码匹配订单结果信息 + @GetMapping("/invoice-match-info") + public RestResponse supplierInvoiceMatchInfoList(String invoiceId) { + return supplierService.supplierInvoiceMatchInfoList(invoiceId); + } + + @GetMapping("/invoice-matched-list") + public RestResponse getMatchedList(String invoiceId) { + return supplierService.getMatchedList(invoiceId); + } + + // 更新供应商代码匹配订单结果信息 + @PutMapping("/invoice-match-info") + public RestResponse supplierInvoiceMatchInfoUpdate(@RequestBody SupplierMatching supplierMatching) { + return supplierService.supplierInvoiceMatchInfoUpdate(supplierMatching); + } + + // 发票明细列表 + @GetMapping("/invoice-items") + public RestResponse supplierInvoiceItemsList(String itemId, String id) { + return supplierService.supplierInvoiceItemsList(itemId, id); + } + // 发票明细列表ALL + @GetMapping("/invoice-items-line-all") + public RestResponse supplierInvoiceItemsLineAllList(@RequestParam(value = "itemId",required = true) String itemId + ,@RequestParam(value = "pageNo",required = false) Integer pageNo + ,@RequestParam(value = "pageSize",required = false) Integer pageSize) { + return supplierService.supplierInvoiceItemsListAll(itemId,pageNo,pageSize); + } + + // 发票明细列表ALL + @GetMapping("/invoice-items-line-all-export") + public RestResponse supplierInvoiceItemsLineAllList(@RequestParam(value = "invoiceId",required = true) String invoiceId,HttpServletResponse response) { + return supplierService.supplierInvoiceItemsListAllExport(response,invoiceId); + } + + // 发票附件列表 + @GetMapping("/invoice-attachment") + public RestResponse supplierInvoiceAttachmentList(String itemId) { + return supplierService.supplierInvoiceAttachmentList(itemId); + } + + // 下载发票附件 + @GetMapping("/invoice-attachment/download") + public RestResponse supplierInvoiceAttachmentList(HttpServletResponse response,@RequestParam("id") String id) { + return supplierService.exportSupplierInvoiceAttachmentList(response,id); + } + + @PostMapping("/invoice-attachment") + public Response supplierInvoiceAttachmentList(SupplierInvoiceAttachmentForm form) { + return supplierService.uploadInvoiceAttachment(form); + } + + + @PostMapping("/import-suppliers") + public RestResponse importSuppliers(MultipartFile file) { + return supplierService.importFile(file); + } + + // 发票附件删除 + @DeleteMapping("/invoice-attachment") + public RestResponse supplierInvoiceAttachmentDelete(Integer id) { + return supplierService.supplierInvoiceAttachmentDelete(id); + } + + // 发票操作日志列表 + @GetMapping("/invoice-matching-log") + public RestResponse supplierInvoiceMatchLogList(String itemId) { + return supplierService.supplierInvoiceMatchLogList(itemId); + } + + // 获取行匹配 订单列表 + @ApiOperation("获取行匹配的订单列表") + @GetMapping("line-match-list") + public Response> lineMatchList(LineMatchListDto dto) { + return supplierService.lineMatchList(dto); + } + + // 提交行匹配列表 + @ApiOperation("提交行匹配列表") + @PutMapping("line-match-list") + public Response submitLineMatchList(@RequestBody SubmitLineMatchDto dto) { + return supplierService.submitLineMatchList(dto); + } + + // 根据Item获取其下面匹配的订单 + @ApiOperation("根据Item获取其下面匹配的订单") + @GetMapping("line-match-list-byItem") + public Response> lineMatchListByItem(@RequestParam("itemId") @ApiParam("发票行Id") String itemId) { + return supplierService.lineMatchListByItem(itemId); + } + + @ApiOperation("根据ID查询匹配行") + @GetMapping("line-match-byId") + public Response lineMatchById(@RequestParam("id") @ApiParam("匹配行id") Long id) { + return supplierService.lineMatchById(id); + } + + // 匹配完成 + @ApiOperation("匹配完成") + @PutMapping("complete-matching/{invoiceId}") + public Response completeMatching(@RequestBody @ApiParam("匹配订单的id集合") List ids, @PathVariable("invoiceId") String invoiceId) { + return supplierService.completeMatching(ids, invoiceId); + } + + // 清除匹配 + @ApiOperation("清除匹配") + @PutMapping("clear-matching") + public Response clearMatching(@RequestBody @ApiParam("清楚订单的id集合") List ids) { + return supplierService.clearMatching(ids); + } + // 虚拟匹配 + @ApiOperation("虚拟匹配") + @GetMapping("invented-matching") + public Response inventedMatching(LineMatchListDto dto) { + return supplierService.inventedMatching(dto); + //return Response.success(); + } + + @ApiOperation("供应商发票类型") + @GetMapping("invocie-types") + public Response> getInvoiceTypes(@RequestParam(required = false) boolean search) { + return supplierService.getInvoiceTypes(search); + } + + @ApiOperation("获取可选组织") + @GetMapping("invocie-orgs") + public Response> getInvoiceOrgs(@RequestParam(required = false) boolean search,@RequestParam(required = false) String name) { + return supplierService.getInvoiceOrgs(search, name); + } + + @ApiOperation("获取所有人列表") + @GetMapping("invocie-owners") + public Response> getOwners(String keyword) { + return supplierService.getOwners(keyword); + } + + @ApiOperation("撤回") + @PutMapping("revoke-invoice/{invoiceId}") + public Response revokeInvoice(@PathVariable("invoiceId") @ApiParam("发票ID") String invoiceId) { + return supplierService.revokeInvoice(invoiceId); + } + + @ApiOperation("审核通过") + @PutMapping("pass-review/{invoiceId}") + public Response passReview(@PathVariable("invoiceId") @ApiParam("发票ID") String invoiceId,@RequestParam("exchangeRateDate") String exchangeRateDate) { + return supplierService.passReview(invoiceId,exchangeRateDate); + } + + @ApiOperation("重新发送") + @PutMapping("resend-invoice/{invoiceId}") + public Response resendInvoice(@PathVariable("invoiceId") @ApiParam("发票ID") String invoiceId) { + return supplierService.resendInvoice(invoiceId); + } + + @ApiOperation("更新匹配类型") + @PutMapping("updateMatchType") + public RestResponse updateMatchType(@RequestBody CorporateInvoice invoice) { + return supplierService.updateMatchType(invoice); + } + + @ApiOperation("更新价格类型") + @PutMapping("updatePriceType") + public RestResponse updatePriceType(@RequestBody CorporateInvoice invoice) { + return supplierService.updatePriceType(invoice); + } + + @ApiOperation("更细价格") + @PostMapping("updatePrice") + public RestResponse updatePrice(@Valid @RequestBody SupplierUpdatePriceForm form) { + return supplierService.updatePrice(form); + } + + @ApiOperation("获取历史价格") + @GetMapping("priceLogs") + public RestResponse priceLogs(String id) { + return supplierService.priceLogs(id); + } + + @ApiOperation("更新发票Uom") + @PutMapping("updateInvoiceUom/{invoiceId}/{sellerTaxId}") + public RestResponse updateInvoiceUom(@PathVariable("invoiceId") String invoiceId, @PathVariable("sellerTaxId") String sellerTaxId) { + return supplierService.updateUom(invoiceId, sellerTaxId); + } + + @ApiOperation("查询可用的 AccountPeriod") + @GetMapping("/accountPeriods") + public RestResponse selectAccount() { + return supplierService.supplierSelectStatus(); + } + + @PutMapping("/updateCorInvoice") + public RestResponse updateCorporate(@RequestBody CorporateInvoice invoice) { + return supplierService.updateAccountPeriod(invoice); + + } + + @ApiOperation("添加地址") + @PostMapping("/addAddress") + public RestResponse addAddress(String jsonStr) { + + JSONObject obj = JSONObject.parseObject(jsonStr); + //List ls= JSONArray.parseArray(obj.getJSONArray("data").toString(),SupplierOrder.class); + + return supplierService.addAress(obj.getJSONArray("data").toString()); + } + + @ApiOperation("获取Ap发票数据") + @GetMapping + public RestResponse getSupplierOrderItem(@RequestParam("invoiceId") String invoiceId) { + return supplierService.getSupplierOrderItem(invoiceId); + } + + @ApiOperation("导入对账单") + @PostMapping("uploadStatement") + public RestResponse importStatement(MultipartFile file) { + return supplierService.importStatement(file); + } + + @ApiOperation("根据发票id查询供应商") + @GetMapping("getSupplierByInvoiceId") + public RestResponse getSupplierByInvoiceId(@RequestParam("invoiceId") String invoiceId) { + return supplierService.getSupplierByInvoiceId(invoiceId); + } + + @ApiOperation("根据名称like匹配供应商") + @GetMapping("getSupplierByNameLike") + public RestResponse getSupplierByNameLike(@RequestParam("name") String name) { + return supplierService.getSupplierByNameLike(name); + } + + @ApiOperation("保存需要替换的供应商税号") + @PostMapping("saveSupplier") + public RestResponse saveSupplier(@RequestBody Supplier supplier) { + return supplierService.saveSupplier(supplier); + } + + @ApiOperation("上传PO文件") + @PostMapping("uploadPOfile") + public RestResponse uploadPOfile(MultipartFile file) { + return supplierService.uploadPOfile(file); } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierUomMappingFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierUomMappingFacade.java index 234eaef..9751c62 100644 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierUomMappingFacade.java +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SupplierUomMappingFacade.java @@ -6,6 +6,7 @@ import com.cmsen.ticket.domain.entity.SupplierUomMapping; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; +import java.util.Map; /** * @author @@ -18,6 +19,11 @@ public class SupplierUomMappingFacade { @Resource private SupplierUomMappingService service; + @GetMapping("/list") + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + @PostMapping("/insert") public RestResponse insert(@RequestBody SupplierUomMapping record) { return service.create(record); diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SynchronousDataFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SynchronousDataFacade.java deleted file mode 100644 index 84df152..0000000 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SynchronousDataFacade.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.cmsen.ticket.interfaces.facade.manager; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author OWTS - * @version 1.0.0 - * @date 2021/9/18 10:05 - **/ -@RestController -@RequestMapping("manager/synchronousData") -public class SynchronousDataFacade { - } diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysCorInvoiceFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysCorInvoiceFacade.java index 9886eea..8d790ef 100644 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysCorInvoiceFacade.java +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysCorInvoiceFacade.java @@ -1,8 +1,24 @@ package com.cmsen.ticket.interfaces.facade.manager; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation.Create; +import com.cmsen.common.http.response.Validation.Update; +import com.cmsen.ticket.application.manager.service.SysCorInvoiceService; +import com.cmsen.ticket.application.service.CorporateInvoiceService; +import com.cmsen.ticket.domain.entity.CorpInvoiceReceiveHeader; +import com.cmsen.ticket.domain.entity.CorporateInvoice; +import com.cmsen.ticket.domain.entity.CorporateInvoiceItems; +import com.cmsen.ticket.infrastructure.service.SapFileWatchService; import io.swagger.annotations.Api; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import io.swagger.annotations.ApiOperation; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; /** * @author OWTS @@ -12,4 +28,199 @@ import org.springframework.web.bind.annotation.RestController; @Api(tags = "供应商发票") @RestController @RequestMapping("manager/corInvoice") -public class SysCorInvoiceFacade {} +public class SysCorInvoiceFacade { + @Resource + private SysCorInvoiceService service; + + @Resource + private SapFileWatchService sapFileWatchService; + + @Resource + private CorporateInvoiceService corporateInvoiceService; + + @PutMapping("refresh") + public RestResponse refresh(@RequestBody List list){ + return sapFileWatchService.refresh(list); + } + + @GetMapping("lines/{pid}") + public RestResponse receiveLines(@PathVariable String pid){ + return service.receiveLines(pid); + } + + @GetMapping("page") + @ApiOperation("分页") + public RestResponse receiveList(@RequestParam(value = "pageSize",defaultValue = "1") Integer pageSize, + @RequestParam(value = "pageNum",defaultValue = "10") Integer pageNum, + String status,String selNo){ + + return service.receiveList(pageSize,pageNum,status,selNo); + } + //上传发票接收 + @PostMapping("uploadReceive") + public RestResponse uploadReceive(MultipartFile[] files, String type, String com) { + return service.uploadReceive(files, "ReceiptReceive", com); + } + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @GetMapping("{id}") + public RestResponse selectById(@PathVariable("id") String id) { + return service.selectById(id); + } + + @PostMapping + public RestResponse insert(@Validated(Create.class) @RequestBody CorporateInvoice corporateInvoice) { + return service.create(corporateInvoice); + } + + @PostMapping("insertLine") + public RestResponse insertLine(@Validated(Create.class) @RequestBody CorporateInvoiceItems item) { + return service.createLine(item); + } + + @GetMapping("items/{pid}") + public RestResponse corporateLines(@PathVariable String pid){ + return service.corporateLines(pid); + } + + + + @PutMapping + public RestResponse update(@Validated(Update.class) @RequestBody CorporateInvoice corporateInvoice) { + return service.update(corporateInvoice); + } + + @PostMapping("refund/{id}") + public RestResponse refound(@PathVariable("id") String id) { + return service.refundTicket(id); + } + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") String id) { + return service.delete(id); + } + + @PostMapping("upload") + public RestResponse upload(MultipartFile[] files, String type, String com,String invoiceType) { + return service.upload(files, type, com,invoiceType); + } + + @PostMapping("uploadAtt") + public RestResponse uploadAtt(MultipartFile[] files, String id) { + return service.uploadAtt(files, id); + } + + @PostMapping("upload/pdf") + public RestResponse uploadInvPdf(MultipartFile file) { + return service.uploadInvPdf(file); + } + + @GetMapping("export") + public RestResponse exportExcel(HttpServletResponse response, @RequestParam(required = false) Map params) { + return service.exportExcel(response, params); + } + + @GetMapping("exportValid") + public RestResponse exportValidExcel(HttpServletResponse response, @RequestParam(required = false) Map params) { + return service.exportValidExcel(response, params); + } + + + @GetMapping("multiDownload") + public RestResponse multiDownload(HttpServletResponse response, @RequestParam(required = false) Map params) { + return service.exportImages(response, params); + } + + + @GetMapping("download/{id}") + public RestResponse download(@PathVariable("id") String id, HttpServletResponse response) { + return service.download(id, response); + } + + @PostMapping("dataUpload") + public RestResponse updateData(MultipartFile file) { + return service.updateData(file); + } + + @PutMapping("updateDeductStatus") + public RestResponse updateDeductStatus() { + return service.updateDeductStatus(); + } + + @PutMapping("completeCheck/{id}") + public RestResponse completeCheck(@PathVariable("id") String invoiceId) { + return service.completeCheck(invoiceId); + } + + @GetMapping("getAllSubjects") + public RestResponse getAllSubjects() { + return service.getAllSubjects(); + } + + @GetMapping("getAllSubjectsTreeNode") + public RestResponse getAllSubjectsTreeNode() { + return service.getAllSubjectsTreeNode(); + } + + @GetMapping("getSubjectById") + public RestResponse getSubjectById(@RequestParam("invoiceId") String invoiceId) { + return service.getSubjectById(invoiceId); + } + + @PutMapping("updateSubject") + public RestResponse updateSubject(@RequestBody CorporateInvoice corporateInvoice) { + return service.updateSubject(corporateInvoice); + } + + /** + * 重新验真 + * @param id + * @return + */ + @PutMapping("reVerify/{id}") + public RestResponse reVerify(@PathVariable("id") String id) { + return sapFileWatchService.reVerify(id); + } + + + @ApiOperation("导出上传日志") + @GetMapping("uploadLog/page") + public RestResponse uploadLogPage(@RequestParam(required = false) Map params, HttpServletResponse response){ + return service.exportInvoiceReport(params, response); + } + + @ApiOperation("多票号导出") + @GetMapping("multiNumberExport") + public RestResponse multiNumberExport(@RequestParam(required = false) Map params, HttpServletResponse response){ + return service.exportByMultiNumber(params, response); + } + + @ApiOperation("导入先款后票") + @PostMapping("importAdvanceOfPayment") + public RestResponse importStatement(MultipartFile file) { + return service.importAdvanceOfPayment(file); + } + + @ApiOperation("接口清单上传") + @PostMapping("pushListUpload") + public RestResponse pushListUpload(MultipartFile file) { + return service.pushListUpload(file); + } + + @ApiOperation("单发票发送kofox") + @GetMapping("pushKofox/{id}") + public RestResponse pushKofox(@PathVariable("id")String invoiceId) { + return service.pushKofox(invoiceId); + } + + + @ApiOperation("月度发票报表") + @GetMapping("monthly_corporate_invoices_export") + public RestResponse monthly_corporate_invoices_export(HttpServletResponse response, @RequestParam(required = false) Map params) { + return corporateInvoiceService.downloadMonthlyCorporateInvoicesExport(params, response); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysLogoFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysLogoFacade.java new file mode 100644 index 0000000..cf363b1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysLogoFacade.java @@ -0,0 +1,34 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysLogoService; +import com.cmsen.ticket.domain.entity.manager.SysLogo; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("manager/logo") +public class SysLogoFacade { + @Resource + private SysLogoService sysLogoService; + + @GetMapping("/select") + public RestResponse select() { + return sysLogoService.select(); + } + + @PostMapping("/insert") + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody SysLogo sysLogo) { + return sysLogoService.create(sysLogo); + } + + @PostMapping("/update") + public RestResponse update(MultipartFile file, String typeStr, String str, Long id) { + return sysLogoService.update(file, typeStr, str, id); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysPolicyFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysPolicyFacade.java new file mode 100644 index 0000000..75c195e --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysPolicyFacade.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysPolicyService; +import com.cmsen.ticket.domain.entity.ExpenseUse; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 10:19 + **/ +@RestController +@RequestMapping("manager/sys/policy") +public class SysPolicyFacade { + @Resource + private SysPolicyService service; + + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @GetMapping("{id}") + public RestResponse selectByPrimaryKey(@PathVariable("id") Integer id) { + return service.selectByPrimaryKey(id); + } + + @PostMapping + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody ExpenseUse expenseUse) { + return service.create(expenseUse); + } + + @PutMapping + public RestResponse update(@Validated(Validation.Update.class) @RequestBody ExpenseUse expenseUse) { + return service.update(expenseUse); + } + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return service.delete(id); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxySetFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxySetFacade.java new file mode 100644 index 0000000..eda6a21 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxySetFacade.java @@ -0,0 +1,51 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysProxySetService; +import com.cmsen.ticket.application.manager.service.SysProxyUserService; +import com.cmsen.ticket.domain.entity.ProxySysUser; +import com.cmsen.ticket.domain.entity.ProxyUser; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +@RestController +@RequestMapping("manager/proxySet") +public class SysProxySetFacade { + @Resource + private SysProxySetService service; + + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @PostMapping + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody ProxySysUser proxySysUser) { + return service.create(proxySysUser); + } + + @PutMapping + public RestResponse update(@RequestBody ProxySysUser proxySysUser) { + return service.update(proxySysUser); + } + + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return service.delete(id); + } + + @GetMapping("search") + public RestResponse selectUserList(@RequestParam(required = false) String keyword) { + return service.selectUserList(keyword); + } + + @GetMapping("getRepresentedList") + public RestResponse getRepresentedList() { + return service.getRepresentedList(); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxyUserFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxyUserFacade.java new file mode 100644 index 0000000..09c796f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysProxyUserFacade.java @@ -0,0 +1,44 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysProxyUserService; +import com.cmsen.ticket.domain.entity.ProxyUser; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +@RestController +@RequestMapping("manager/proxyUser") +public class SysProxyUserFacade { + @Resource + private SysProxyUserService service; + + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @PostMapping + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody ProxyUser proxyUser) { + return service.create(proxyUser); + } + + @PutMapping + public RestResponse update(@RequestBody ProxyUser proxyUser) { + return service.update(proxyUser); + } + + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return service.delete(id); + } + + @GetMapping("search") + public RestResponse selectUserList(@RequestParam(required = false) String name) { + return service.selectUserList(name); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysRulesFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysRulesFacade.java new file mode 100644 index 0000000..62520bb --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysRulesFacade.java @@ -0,0 +1,56 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysRulesService; +import com.cmsen.ticket.domain.entity.RuleConfig; +import io.swagger.annotations.ApiOperation; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 14:19 + **/ +@RestController +@RequestMapping("manager/sys/rules") +public class SysRulesFacade { + @Resource + private SysRulesService service; + + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @GetMapping("{id}") + public RestResponse selectByPrimaryKey(@PathVariable("id") Integer id) { + return service.selectByPrimaryKey(id); + } + + @PostMapping + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody RuleConfig ruleConfig) { + return service.create(ruleConfig); + } + + @PutMapping + public RestResponse update(@Validated(Validation.Update.class) @RequestBody RuleConfig ruleConfig) { + return service.update(ruleConfig); + } + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return service.delete(id); + } + + @ApiOperation("获取规则类型列表") + @GetMapping("/getRuleType") + public RestResponse getRuleType() { + return service.getRuleType(); + } + +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysSearchValueFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysSearchValueFacade.java new file mode 100644 index 0000000..8d2e34f --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysSearchValueFacade.java @@ -0,0 +1,37 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.manager.service.SearchValueService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("manager/search") +public class SysSearchValueFacade { + @Resource + private SearchValueService service; + + @GetMapping("client") + public RestResponse clients() { + return service.clients(); + } + + @GetMapping("rules/{type}") + public RestResponse rules(@PathVariable("type") Integer type) { + return service.rules(type); + } + + @GetMapping("ticketTypes") + public RestResponse ticketTypes() { + return service.ticketTypes(); + } + + @GetMapping("orgs") + public RestResponse orgs() { + return service.orgs(); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysWhitelistFacade.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysWhitelistFacade.java new file mode 100644 index 0000000..3d5ea9c --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/SysWhitelistFacade.java @@ -0,0 +1,48 @@ +package com.cmsen.ticket.interfaces.facade.manager; + +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.common.http.response.Validation; +import com.cmsen.ticket.application.manager.service.SysWhitelistService; +import com.cmsen.ticket.domain.entity.Company; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.Map; + +/** + * @author OWTS + * @version 1.0.0 + * @date 2021/2/22 9:19 + **/ +@RestController +@RequestMapping("manager/sys/whitelist") +public class SysWhitelistFacade { + @Resource + private SysWhitelistService service; + + @GetMapping + public RestResponse select(@RequestParam(required = false) Map params) { + return service.list(params); + } + + @GetMapping("{id}") + public RestResponse selectByPrimaryKey(@PathVariable("id") Integer id) { + return service.selectByPrimaryKey(id); + } + + @PostMapping + public RestResponse insert(@Validated(Validation.Create.class) @RequestBody Company company) { + return service.create(company); + } + + @PutMapping + public RestResponse update(@Validated(Validation.Update.class) @RequestBody Company company) { + return service.update(company); + } + + @DeleteMapping("{id}") + public RestResponse delete(@PathVariable("id") Integer id) { + return service.delete(id); + } +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/InvoiceConfirmAndSendForm.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/InvoiceConfirmAndSendForm.java new file mode 100644 index 0000000..529f6b7 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/InvoiceConfirmAndSendForm.java @@ -0,0 +1,22 @@ +package com.cmsen.ticket.interfaces.facade.manager.form; + +import com.cmsen.ticket.domain.dto.InvoiceItemListDto; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.util.List; + +/** + * @author OWTS + */ +@Data +public class InvoiceConfirmAndSendForm { + @NotEmpty + private List itemIds; + @NotNull + private Integer orderId; + + @NotEmpty + private List items; +} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SubmitMileageForm.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SubmitMileageForm.java deleted file mode 100644 index c397514..0000000 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SubmitMileageForm.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.cmsen.ticket.interfaces.facade.manager.form; - -import lombok.Data; - -/** - * @author OWTS - */ -@Data -public class SubmitMileageForm { - private String invoiceId; -} diff --git a/src/main/java/com/cmsen/ticket/interfaces/facade/form/SupplierInvoiceMatchForm.java b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SupplierInvoiceMatchForm.java similarity index 88% rename from src/main/java/com/cmsen/ticket/interfaces/facade/form/SupplierInvoiceMatchForm.java rename to src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SupplierInvoiceMatchForm.java index bd22985..b521fa6 100644 --- a/src/main/java/com/cmsen/ticket/interfaces/facade/form/SupplierInvoiceMatchForm.java +++ b/src/main/java/com/cmsen/ticket/interfaces/facade/manager/form/SupplierInvoiceMatchForm.java @@ -5,12 +5,10 @@ * | Copyright (c) http://cmsen.com All rights reserved. * +--------------------------------------------------------- */ -package com.cmsen.ticket.interfaces.facade.form; +package com.cmsen.ticket.interfaces.facade.manager.form; import com.cmsen.common.http.response.Validation; import com.cmsen.ticket.domain.mapper.ParameterScope; -import com.cmsen.ticket.interfaces.facade.manager.form.PaginationForm; -import com.cmsen.ticket.interfaces.facade.manager.form.ValidationForm; import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/main/java/com/cmsen/ticket/log/service/TInterfaceLogService.java b/src/main/java/com/cmsen/ticket/log/service/TInterfaceLogService.java index 870da8c..1902d6f 100644 --- a/src/main/java/com/cmsen/ticket/log/service/TInterfaceLogService.java +++ b/src/main/java/com/cmsen/ticket/log/service/TInterfaceLogService.java @@ -3,15 +3,30 @@ */ package com.cmsen.ticket.log.service; +import com.alibaba.fastjson2.util.DateUtils; +import com.cmsen.common.http.response.RestResponse; +import com.cmsen.ticket.application.service.SendMailService; +import com.cmsen.ticket.domain.util.PaginationUtil; import com.cmsen.ticket.log.entity.TInterfaceLog; import com.cmsen.ticket.log.mapper.TInterfaceLogMapper; +import com.cmsen.ticket.monitor.entity.ScheduleJob; import lombok.extern.slf4j.Slf4j; +import org.apache.poi.hssf.usermodel.HSSFPrintSetup; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.PrintSetup; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFPrintSetup; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; +import java.io.*; import java.util.Date; +import java.util.List; +import java.util.Map; import java.util.UUID; import static org.apache.commons.lang3.StringUtils.isEmpty; @@ -29,6 +44,8 @@ public class TInterfaceLogService { @Resource private TInterfaceLogMapper interfaceLogMapper; @Lazy + @Resource + private SendMailService sendMailService; public TInterfaceLog get(String id) { @@ -49,4 +66,61 @@ public class TInterfaceLogService { } } + @Transactional(readOnly = false) + public void saveSendEmail(TInterfaceLog tInterfaceLog, ScheduleJob scheduleJob) { + String id = tInterfaceLog.getId(); + try { + // 失败后邮件通知 + if (tInterfaceLog.getRunState().equals("1") && scheduleJob.getIsInfo() != null && scheduleJob.getIsInfo().equals("1") && scheduleJob.getExt2() != null && scheduleJob.getExt2().length() > 0) { + + if(sendMailService!=null) { + String[] addresses = scheduleJob.getExt2().split(","); + for (String address : addresses) { + boolean isSuccess = sendMailService.sendVerifiedText(address, + scheduleJob.getName() + "运行异常:"+tInterfaceLog.getRunMesg()); + if (!isSuccess) { + tInterfaceLog.setRunMesg(tInterfaceLog.getRunMesg() + ";" + address + "邮件发送失败"); + } + + } + }else{ + tInterfaceLog.setRunMesg(tInterfaceLog.getRunMesg() + ";邮件参数未配置"); + } + } + }catch (Exception e){ + e.printStackTrace(); + } + if(isEmpty(id)){ + tInterfaceLog.setId(UUID.randomUUID().toString()); + tInterfaceLog.setCreateDate(new Date()); + tInterfaceLog.setDelFlag("0"); + interfaceLogMapper.insert(tInterfaceLog); + }else{ + tInterfaceLog.setUpdateDate(new Date()); + interfaceLogMapper.update(tInterfaceLog); + } + } + + @Transactional(readOnly = false) + public void delete(TInterfaceLog tInterfaceLog) { + interfaceLogMapper.delete(tInterfaceLog); + } + + public List findErrNotSendList() { + return interfaceLogMapper.selectFindErrNotSendEntity(); + } + + + public RestResponse list(Map params){ + PaginationUtil.paginationInit(params); + List list = interfaceLogMapper.findList3(params); + int total = interfaceLogMapper.getCount(params); + return RestResponse.success(PaginationUtil.getPageResult(total, params, list)); + } + + @Transactional(readOnly = false) + public void executeUpdateSql(String sql){ + interfaceLogMapper.execUpdateSql(sql); + } + } diff --git a/src/main/java/com/cmsen/ticket/log/web/TInterfaceLogFacade.java b/src/main/java/com/cmsen/ticket/log/web/TInterfaceLogFacade.java index 7616c54..4310b2f 100644 --- a/src/main/java/com/cmsen/ticket/log/web/TInterfaceLogFacade.java +++ b/src/main/java/com/cmsen/ticket/log/web/TInterfaceLogFacade.java @@ -77,8 +77,7 @@ public class TInterfaceLogFacade { params.put("pageNo",pageNo); params.put("runState",runState); params.put("runMesg",runMesg); -// return tInterfaceLogService.list(params); - return null; + return tInterfaceLogService.list(params); } /** @@ -120,7 +119,7 @@ public class TInterfaceLogFacade { public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ -// tInterfaceLogService.delete(tInterfaceLogService.get(id)); + tInterfaceLogService.delete(tInterfaceLogService.get(id)); } return AjaxJson.success("删除功能日志成功"); } diff --git a/src/main/java/com/cmsen/ticket/monitor/task/ProcedureTask.java b/src/main/java/com/cmsen/ticket/monitor/task/ProcedureTask.java index 9564e1f..82fd06a 100644 --- a/src/main/java/com/cmsen/ticket/monitor/task/ProcedureTask.java +++ b/src/main/java/com/cmsen/ticket/monitor/task/ProcedureTask.java @@ -54,7 +54,7 @@ public class ProcedureTask extends Task { Random random = new Random(); int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数 batch_no = batch+rannum; -// interfaceLogService.executeUpdateSql("call "+this.scheduleJob.getMapTxt()+"()"); + interfaceLogService.executeUpdateSql("call "+this.scheduleJob.getMapTxt()+"()"); } } catch(Exception e) @@ -79,7 +79,7 @@ public class ProcedureTask extends Task { } interfaceLog.setIsRollBack("1"); -// interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); + interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); } } diff --git a/src/main/java/com/cmsen/ticket/monitor/task/SqlEmailTask.java b/src/main/java/com/cmsen/ticket/monitor/task/SqlEmailTask.java index cc4a4aa..161e2ca 100644 --- a/src/main/java/com/cmsen/ticket/monitor/task/SqlEmailTask.java +++ b/src/main/java/com/cmsen/ticket/monitor/task/SqlEmailTask.java @@ -1,6 +1,7 @@ package com.cmsen.ticket.monitor.task; import com.alibaba.excel.EasyExcel; +import com.cmsen.ticket.application.service.SendMailService; import com.cmsen.ticket.common.SpringContextHolder; import com.cmsen.ticket.domain.entity.manager.SysConfig; import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; @@ -33,8 +34,8 @@ public class SqlEmailTask extends Task { @Resource private SysConfigMapper sysConfigMapper; -// @Resource -// private SendMailService sendMailService; + @Resource + private SendMailService sendMailService; @Value("${task.file.dir}") public String baseDir; @@ -91,7 +92,7 @@ public class SqlEmailTask extends Task { String address[] = emailAddress.split(","); String subject = scheduleJob.getName()+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); for (int i = 0; i < address.length; i++) { -// sendMailService.sendFileAndText(address[i],subject,filePath); + sendMailService.sendFileAndText(address[i],subject,filePath); } } catch(Exception e) @@ -115,7 +116,7 @@ public class SqlEmailTask extends Task { interfaceLog.setRunMesg("运行成功"); } interfaceLog.setIsRollBack("1"); -// interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); + interfaceLogService.saveSendEmail(interfaceLog,scheduleJob); } } diff --git a/src/main/java/com/cmsen/ticket/saml/SamlSsoController.java b/src/main/java/com/cmsen/ticket/saml/SamlSsoController.java new file mode 100644 index 0000000..229be40 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/saml/SamlSsoController.java @@ -0,0 +1,153 @@ +package com.cmsen.ticket.saml; + +import com.cmsen.ticket.domain.entity.manager.SysConfig; +import com.cmsen.ticket.domain.mapper.manager.SysConfigMapper; +import com.cmsen.ticket.domain.mapper.manager.SysUserMapper; +import lombok.extern.slf4j.Slf4j; +import net.shibboleth.utilities.java.support.service.ServiceException; +import org.apache.commons.lang3.StringUtils; +import org.opensaml.core.config.InitializationService; +import org.opensaml.saml.saml2.core.AuthnRequest; +import org.opensaml.saml.saml2.core.Response; +import org.opensaml.security.credential.Credential; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.crypto.Cipher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import java.security.Security; +import java.util.*; + +@RestController +@RequestMapping("/sso") +@Slf4j +public class SamlSsoController { + static { + try { + // 1. 注册 BouncyCastle Provider + if (Security.getProvider("BC") == null) { + org.bouncycastle.jce.provider.BouncyCastleProvider bc = new org.bouncycastle.jce.provider.BouncyCastleProvider(); + Security.addProvider(bc); + log.info("✅ BC Provider added"); + } + + // 2. ✅ 关键!初始化 Apache XML Security (Santuario) + if (!org.apache.xml.security.Init.isInitialized()) { + org.apache.xml.security.Init.init(); + log.info("✅ Apache XML Security initialized"); + } + // 检查JCE提供者是否支持所需算法 + try { + Cipher.getInstance("AES/CBC/ISO10126Padding"); + // 如果这行代码不抛异常,说明基础加密环境正常 + } catch (Exception e) { + throw new RuntimeException("JCE环境不满足要求", e); + } + // 3. 初始化 OpenSAML + InitializationService.initialize(); + log.info("✅ OpenSAML initialized"); + + // 4. 验证算法是否可用 + log.info("CanonicalizationMethod.EXCLUSIVE = " + CanonicalizationMethod.EXCLUSIVE); + + // 5. 测试能否创建 Transform(验证 C14N 是否真可用) + javax.xml.crypto.dsig.XMLSignatureFactory factory = + javax.xml.crypto.dsig.XMLSignatureFactory.getInstance("DOM"); + factory.newTransform( + CanonicalizationMethod.EXCLUSIVE, + (javax.xml.crypto.dsig.spec.TransformParameterSpec) null); + log.info("✅ C14N Transform created successfully"); + org.apache.xml.security.Init.init(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Failed to initialize SAML environment", e); + } + } + + + + + @Resource + private SysConfigMapper sysConfigMapper; + @Resource + private SysUserMapper sysUserMapper; + Map ssoParam = new HashMap<>(); + + + + /** + * 登录方法 + * + * @return 结果 + */ + @GetMapping("/samlLogin") + public void microsoftLogin(HttpServletResponse response, HttpServletRequest request) { + + //得到附件识别相关配置 + List sys_ls = sysConfigMapper.list("SSO_SAML"); + + if (sys_ls.size()==0) { + throw new ServiceException("SAML参数未配置"); + } + for(SysConfig val:sys_ls){ + ssoParam.put(val.getCode(),val.getValue()); + } + try { + // 初始化 + log.info("进入单点登录"); + // InitializationService.initialize(); + //AuthnRequest authnRequest = SamlUtil.buildAuthnRequest("https://121.234.3.187:9091/api/saml2/service-provider-metadata/samltestidp", "https://121.234.3.187:9091/api/sso/callBack"); + //String samlPath = SamlUtil.createSamlPath(authnRequest, "https://login.microsoftonline.com/19c9ae17-1595-4a97-bfa1-62fc024ed8d4/saml2"); + //Credential idpCredential =SamlUtil.getSigningCredential("D:/infineon-12.p12","infineon8520","sp-infineon","infineon8520"); + Credential idpCredential =SamlUtil.getSigningCredential(ssoParam.get("SSO_SAML_SP_P12_FILE"),ssoParam.get("SSO_SAML_SP_P12_PWD"),ssoParam.get("SSO_SAML_SP_P12_ALIAS"),ssoParam.get("SSO_SAML_SP_P12_PWD")); + AuthnRequest authnRequest = SamlUtil.buildAuthnRequest(ssoParam.get("SSO_SAML_SP_ENTITY_ID"), ssoParam.get("SSO_SAML_SP_ACS_URL"),idpCredential,ssoParam.get("SSO_SAML_IDP_SSO_URL")); + String samlPath = SamlUtil.createSamlPath(authnRequest, ssoParam.get("SSO_SAML_IDP_SSO_URL"),idpCredential); + log.info("认证中心地址: {}", samlPath); + response.sendRedirect(samlPath); + } catch (Exception e) { + throw new ServiceException("saml认证请求生成失败:" + e.getMessage()); + } + } + + /** + * 单点登录回调 + */ + @RequestMapping("/callBack") + public void callBackFromRemote(@RequestParam("SAMLResponse") String saml, HttpServletResponse resp, HttpServletRequest request) throws Exception { + // 解析SAML响应 + if (StringUtils.isBlank(saml)) { + throw new ServiceException("回调未授权"); + } + // 获取原始 SAMLResponse + try { + byte[] decodedBytes = Base64.getDecoder().decode(saml); + String samlString = new String(decodedBytes, "UTF-8"); + log.info("SAMLResponse: " + samlString); + }catch (Exception e){ + e.printStackTrace(); + } + log.info("收到用户信息:{}", saml); + String email; + //Response response = SamlUtil.parseSAMLData(saml, "MIIC8DCCAdigAwIBAgIQFG16ejIKTpNNVffPf+AJQTANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylNaWNyb3NvZnQgQXp1cmUgRmVkZXJhdGVkIFNTTyBDZXJ0aWZpY2F0ZTAeFw0yNTExMDMwOTEyMDRaFw0yODExMDMwOTEyMDRaMDQxMjAwBgNVBAMTKU1pY3Jvc29mdCBBenVyZSBGZWRlcmF0ZWQgU1NPIENlcnRpZmljYXRlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA97YodiQbyF+46qcckzCxlqZLzq4IB+3jBHr9h97LhYqFX3pH73N7VGYE0yGNgXqmFCn0Iuy/5KuWFjMZZZsd8MJ1Jayo+mizfcozwqdPzhTAFibJVRSRIlWQWDtQaDUdkEBYqEbGFL9VwBfKE3o4Ia9h1e7hXbWiaKuPSo05KkRQUpKkY4HCSlvGezPYdEKfg4mU0tlVBzDDUaHM6xzcxunSDsJRK7rqI1qNvhlGKYh7Vn1hzickjbj1T7IN9Z8lDseWFjo5LlLhnQkR5KKL9StWHC0oiiAjhgbaHaxLuvakYdD6m+Hul4naa/UckzJkkp5RY+Dekfx/NRmFteb8mQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQDHBKT5ZrRLqON7hsPXuLP2aqKYQ+WfQ/BjuZ9l/qldTINhables36G/AR6cJIVbZBoaKizDpzCWPfXJpxngybXtaFVUUMp2btmwO6JpK+hYYWx0GQvxEKVBlbOpIxuqyBNigxl+pXTjW48D1wYIIL6jW017g+XxGmH6xbIC9c/QTFl/fLGyGF0wYrxXTugPOViah6y62l9WafTJ7B9bVUqcz60OEMVpOWPGanSfIXcei/KVNKbIDOlKVfxJUaEZvnSjC2MY4oEBVE9fx6uGD11tGmROuOVKd6Ki8YAUQO81V4DADVPvktSyIR30Ari1RAdLZbp/4pBoZCUXonJXJa9"); + Response response = SamlUtil.parseSAMLData(saml, ssoParam.get("SSO_SAML_IDP_BASE64_CERT")); + //email = SamlUtil.getData(response, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"); + email = SamlUtil.getData(response, ssoParam.get("SSO_SAML_BACK_USER_ID")); + log.info("用户信息:{}", email); + if(email==null || email.isEmpty()){ + throw new ServiceException("未获取到用户信息"); + + } + //插入用户信息 + String uuid = UUID.randomUUID().toString(); + sysUserMapper.execInsertSql("insert into sso_user(id,login_id) values('"+uuid+"','"+email+"')"); + resp.sendRedirect(new StringBuilder().append(ssoParam.get("SSO_SAML_SUCCES_URL")).append("?ssoId="+uuid).toString()); + } + + + +} diff --git a/src/main/java/com/cmsen/ticket/saml/SamlUtil.java b/src/main/java/com/cmsen/ticket/saml/SamlUtil.java new file mode 100644 index 0000000..c0a1ae1 --- /dev/null +++ b/src/main/java/com/cmsen/ticket/saml/SamlUtil.java @@ -0,0 +1,328 @@ +package com.cmsen.ticket.saml; + +import org.apache.commons.codec.binary.Base64; +import org.joda.time.DateTime; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.Marshaller; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.UnmarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.common.SAMLVersion; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.saml2.core.*; +import org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder; +import org.opensaml.saml.saml2.core.impl.IssuerBuilder; +import org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder; +import org.opensaml.saml.saml2.core.impl.ResponseUnmarshaller; +import org.opensaml.security.credential.Credential; +import org.opensaml.security.credential.CredentialSupport; +import org.opensaml.security.x509.BasicX509Credential; +import org.opensaml.xmlsec.signature.KeyInfo; +import org.opensaml.xmlsec.signature.Signature; +import org.opensaml.xmlsec.signature.X509Data; +import org.opensaml.xmlsec.signature.support.SignatureConstants; +import org.opensaml.xmlsec.signature.support.SignatureException; +import org.opensaml.xmlsec.signature.support.SignatureValidator; +import org.opensaml.xmlsec.signature.support.Signer; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.*; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.UUID; +import java.util.zip.Deflater; + +public class SamlUtil { + + //构建请求 ############################### + + + /** + * 构建跳转路径 + * acsUrl 响应回调地址 + * spEntityId 应用id + * idpSsoUrl 请求地址 + */ + public static String createSamlPath(AuthnRequest authnRequest, String idpSsoUrl, Credential signingCredential) throws MarshallingException, TransformerException, IOException { + // 2. 序列化为 XML + String samlRequestXml = serializeSAMLObject(authnRequest); + System.out.println(samlRequestXml); + // 3. DEFLATE 压缩 + byte[] deflated = deflate(samlRequestXml); + + // 4. Base64 编码 + String base64Encoded = Base64.encodeBase64String(deflated); + + // 5. URL 编码 + String urlEncoded = URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8.name()); + // HTTP-Redirect 绑定需要对查询字符串进行签名(而不是 XML 内联签名) + String sigAlg = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; + String signedInput = "SAMLRequest=" + urlEncoded + "&SigAlg=" + URLEncoder.encode(sigAlg, StandardCharsets.UTF_8.name()); + + if (signingCredential != null && signingCredential.getPrivateKey() != null) { + try { + java.security.Signature signer = java.security.Signature.getInstance("SHA256withRSA"); + signer.initSign(signingCredential.getPrivateKey()); + signer.update(signedInput.getBytes(StandardCharsets.UTF_8)); + String signature = Base64.encodeBase64String(signer.sign()); + String sigParam = URLEncoder.encode(signature, StandardCharsets.UTF_8.name()); + return idpSsoUrl + "?" + signedInput + "&Signature=" + sigParam; + } catch (Exception e) { + throw new IOException("Failed to sign HTTP-Redirect SAMLRequest", e); + } + } + + // 无签名回退(某些 IdP 要求签名,建议传入 signingCredential) + return idpSsoUrl + "?SAMLRequest=" + urlEncoded; + } + + /** + * 生成 SAML AuthnRequest + * acsUrl 响应回调地址 + * spEntityId + */ + public static AuthnRequest buildAuthnRequest(String spEntityId, String acsUrl, Credential signingCredential,String idpSsoUrl) throws SignatureException, MarshallingException { + AuthnRequestBuilder authnRequestBuilder = new AuthnRequestBuilder(); + AuthnRequest authnRequest = authnRequestBuilder.buildObject(); + + + // 设置 ID 属性(使用 UUID 生成唯一 ID) + String id = "_" + UUID.randomUUID().toString().replace("-", ""); + authnRequest.setID(id); + + // 设置版本 + authnRequest.setVersion(SAMLVersion.VERSION_20); + + // 设置 IssueInstant + authnRequest.setIssueInstant(new DateTime()); + + // 设置 Issuer + IssuerBuilder issuerBuilder = new IssuerBuilder(); + Issuer issuer = issuerBuilder.buildObject(); + issuer.setValue(spEntityId); + authnRequest.setIssuer(issuer); + + // 设置 NameIDPolicy + NameIDPolicyBuilder nameIDPolicyBuilder = new NameIDPolicyBuilder(); + NameIDPolicy nameIDPolicy = nameIDPolicyBuilder.buildObject(); + nameIDPolicy.setAllowCreate(true); + authnRequest.setNameIDPolicy(nameIDPolicy); + + // 设置 AssertionConsumerServiceURL + authnRequest.setAssertionConsumerServiceURL(acsUrl); + + // 设置 ProtocolBinding + authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI); + // idpSsoUrl + authnRequest.setDestination(idpSsoUrl); + // 设置 ForceAuthn 和 IsPassive + authnRequest.setForceAuthn(false); + authnRequest.setIsPassive(false); + // ==================== 添加签名 ==================== + if (signingCredential != null) { + // 1. 创建Signature对象并关联到AuthnRequest + Signature signature = (Signature) buildSAMLObject(Signature.class); + signature.setSigningCredential(signingCredential); + signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + // 2. 设置 KeyInfo(可选) + KeyInfo keyInfo = (KeyInfo) buildSAMLObject(KeyInfo.class); + // === 构建 KeyInfo 并添加 X509Data === + X509Data x509Data = (X509Data) buildSAMLObject(X509Data.class); + org.opensaml.xmlsec.signature.X509Certificate cert = (org.opensaml.xmlsec.signature.X509Certificate) + buildSAMLObject(org.opensaml.xmlsec.signature.X509Certificate.class); + cert.setValue(Base64.encodeBase64String(signingCredential.getPublicKey().getEncoded())); + x509Data.getX509Certificates().add(cert); + keyInfo.getX509Datas().add(x509Data); + + signature.setKeyInfo(keyInfo); + authnRequest.setSignature(signature); // 先设置签名对象 + +// 2. 序列化SAML对象(这一步很重要,它会使签名结构生效) + Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest); + if (marshaller != null) { + marshaller.marshall(authnRequest); + } + +// 3. 使用Signer类进行实际签名计算 + Signer.signObject(signature); + } + // ================================================= + + return authnRequest; + } + // 通用辅助方法:构建 SAML 对象 + private static T buildSAMLObject(final Class clazz) { + QName qname = null; + try { + qname = (QName) clazz.getDeclaredField("DEFAULT_ELEMENT_NAME").get(null); + } catch (IllegalAccessException | NoSuchFieldException e) { + throw new RuntimeException("Error getting DEFAULT_ELEMENT_NAME for class: " + clazz.getSimpleName(), e); + } + return (T) XMLObjectProviderRegistrySupport.getBuilderFactory() + .getBuilder(qname) + .buildObject(qname); + } + + /** + * 加载私钥和证书 + * @param jksPath + * @param storePass + * @param keyAlias + * @param keyPass + * @return + * @throws Exception + */ + public static Credential getSigningCredential(String jksPath, String storePass, String keyAlias, String keyPass) throws Exception { + // 将类型改为 PKCS12 + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream is = new FileInputStream(jksPath)) { + keyStore.load(is, storePass.toCharArray()); + } + // 注意:如果别名不确定,可先遍历 keyStore.aliases() 获取[1](@ref) + KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPass.toCharArray())); + + X509Certificate cert = (X509Certificate) pkEntry.getCertificate(); + PrivateKey privateKey = pkEntry.getPrivateKey(); // 此时privateKey应不为null + + BasicX509Credential credential = new BasicX509Credential(cert, privateKey); + + System.out.println("🔑 PrivateKey: " + privateKey); // 应该输出类似 RSAPrivateKey + System.out.println("📜 Certificate: " + cert); + System.out.println("🔐 Algorithm: " + privateKey.getAlgorithm()); // 应该是 RSA + return credential; + } + public static String serializeSAMLObject(AuthnRequest authnRequest) throws MarshallingException, TransformerException, TransformerConfigurationException { + Element element = XMLObjectSupport.marshall(authnRequest); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + // 关键设置:关闭所有格式化 + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "0"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + // 👇 防止将 \r 转义为 + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + + + DOMSource source = new DOMSource(element); + + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + + transformer.transform(source, result); + + return writer.toString(); + } + + public static byte[] deflate(String samlRequest) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Deflater deflater = new Deflater(Deflater.DEFLATED, true); // 关键:使用 nowrap=true + byte[] input = samlRequest.getBytes(StandardCharsets.UTF_8); + + deflater.setInput(input); + deflater.finish(); + + byte[] buffer = new byte[1024]; + while (!deflater.finished()) { + int count = deflater.deflate(buffer); + bos.write(buffer, 0, count); + } + bos.close(); + return bos.toByteArray(); + } + + + //响应解析 ############################### + public static Response parseSAMLData(String saml, String base64Cert) throws ParserConfigurationException, IOException, UnmarshallingException, SAXException, CertificateException, SignatureException { + // Base64解码SAML响应 + String decodedString = new String(Base64.decodeBase64(saml), StandardCharsets.UTF_8); + Response response = parseSAMLResponse(decodedString); + + // 验签 + validateSignature(response, createCredentialFromCertificate(base64Cert)); + return response; + + } + + public static String getData(Response response, String name) { + // 获取SAML相应中携带用户信息 + Assertion assertion = response.getAssertions().get(0); + // 获取属性声明 + /*List attributeStatements = assertion.getAttributeStatements(); + for (AttributeStatement attributeStatement : attributeStatements) { + List attributes = attributeStatement.getAttributes(); + for (Attribute attribute : attributes) { + if (name.equals(attribute.getName())) { + if (!attribute.getAttributeValues().isEmpty()) { + return attribute.getAttributeValues().get(0).getDOM().getTextContent(); + } + } + } + }*/ + + // 获取用户名 + Subject subject = assertion.getSubject(); + if (subject == null) { + return null; + } + NameID nameId = subject.getNameID(); + if (nameId != null && nameId.getValue() != null) { + return nameId.getValue(); + } + return null; + } + + public static Credential createCredentialFromCertificate(String base64Cert) throws CertificateException { + // 将 Base64 编码的证书转换为 X509Certificate 对象 + byte[] certBytes = Base64.decodeBase64(base64Cert); + CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes)); + + return CredentialSupport.getSimpleCredential(certificate, null); + } + + public static Response parseSAMLResponse(String samlResponse) throws UnmarshallingException, ParserConfigurationException, IOException, SAXException { + // 将 XML 字符串转换为 DOM 元素 + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + Element element = factory.newDocumentBuilder() + .parse(new ByteArrayInputStream(samlResponse.getBytes(StandardCharsets.UTF_8))) + .getDocumentElement(); + + // 解析为 Response 对象 + ResponseUnmarshaller unmarshaller = new ResponseUnmarshaller(); + return (Response) unmarshaller.unmarshall(element); + } + + public static void validateSignature(Response response, Credential idpCredential) throws SignatureException { + // 检查 Response 是否有签名 + Signature responseSignature = response.getSignature(); + if (responseSignature != null) { + SignatureValidator.validate(responseSignature, idpCredential); + return; + } + + // 检查 Assertion 是否有签名 + for (Assertion assertion : response.getAssertions()) { + Signature assertionSignature = assertion.getSignature(); + if (assertionSignature != null) { + SignatureValidator.validate(assertionSignature, idpCredential); + return; + } + } + } + +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index a2652a6..a65d519 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -9,23 +9,12 @@ spring.jwt.expire-in=7200 spring.ccintocr.app_key=5f98d567 spring.ccintocr.app_secret=671ef2c3ae19eaf4bb05f25af7ecf04c -#spring.datasource.username: root -#spring.datasource.password: today8520 -#spring.datasource.url: jdbc:mysql://210.14.77.39:24330/ge_dev?useUnicode=true&characterEncoding=utf-8&useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=GMT%2b8 spring.datasource.username=fees-invoice spring.datasource.password=fees#INVOICE123 spring.datasource.url=jdbc:mysql://210.14.77.39:29330/fees_invoice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&allowMultiQueries=true -#spring.datasource.username=root -#spring.datasource.password=today8520 -#spring.datasource.url=jdbc:mysql://reg.qcisoft.com:15330/fees_test_prc?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&allowMultiQueries=true -#spring.datasource.username=root -#spring.datasource.password=123456 -#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/fee_invoice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&allowMultiQueries=true spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.hikari.max-lifetime=0 -#spring.datasource.hikari.maximum-pool-size=32 -#spring.datasource.hikari.minimum-idle=5 -#spring.datasource.hikari.connection-timeout=30000 + spring.resources.static-locations=classpath:/templates/,classpath:/static/ spring.servlet.multipart.max-file-size=50MB spring.servlet.multipart.max-request-size=50MB @@ -51,17 +40,6 @@ img.img-virtual-Path=/img logging.level.com.cmsen.ticket.domain.mapper=debug #logging.level.com.cmsenframework.security=debug -mail-private.active=false -mail-private.username=**@qq.com -mail-private.password=heuvrmdxhqqnbbhb -mail-private.host=imap.qq.com -mail-private.port=143 - -mail-private2.active=false -mail-private2.username=**@qq.com -mail-private2.password=heuvrmdxhqqnbbhb -mail-private2.host=imap.qq.com -mail-private2.port=143 mail-public.active=true mail-public.username=zhangjianxue@fanhan-tech.com @@ -71,78 +49,20 @@ mail-public.port=993 concur.active=true concur.syncUserActive=false -#concur.baseUrl=https://bpm01.connectconcur.com -#concur.userName=admin -#concur.password=Ab1234 -concur.baseUrl=http://210.14.77.39:16808/ics_demo -concur.userName=interface -concur.password=Ii3691#^( -concur.entryImagesActive=false -concur.concurLoginInfo.userName=testconcur -concur.concurLoginInfo.count=0 -concur.concurLoginInfo.secret=4fd684c25c3989d61a9e908af3b59c093fb7592c -concur.concurLoginInfo.token=fda5578b038a458dbff8b91045a06ddc1610c303136e429887f450269ab8a8df8e763b741d134804889f23fd6439e2ac -concur.ocrConcur.templateID=74d691ec-adb5-4f0a-8e9a-6d7810fc0604 -concur.ocrConcur.execUser=testconcur -concur.ocrConcur.action=报销 -concur.guni.active=true -concur.guni.loginUrl=https://concur-prod.pernod-ricard-china.com:10000/piaoge/api/user/third/login -concur.guni.listUrl=https://concur-prod.pernod-ricard-china.com:10000/Piaoge/api/Task/searchDetailList -concur.guni.userName=testconcur -concur.guni.secret=4fd684c25c3989d61a9e908af3b59c093fb7592c -concur.guni.count=0 -concur.public.invoice.active=false -#invoice.attachment.mqUrl=http://ocr01.fanhaninfo.com:9011/MQ_produce -invoice.attachment.mqUrl=http://39.99.244.218:9011/MQ_produce -invoice.attachment.responseUrl=https://fp.connectconcur.com:10244/api/callback/verifiedAttachment -#invoice.attachment.authUrl=http://ocr01.fanhaninfo.com:9000/api/v3/access_tokens -invoice.attachment.authUrl=http://39.99.244.218:9000/api/v3/access_tokens -invoice.attachment.username=guest -invoice.attachment.password=123456789 -invoice.attachment.verifyUrl=http://0.0.0.0:9000/api/v3/AI_httpService/OC_reimbursement_check/reimbursement_check -invoice.attachment.verifyUrlSingle=http://0.0.0.0:9000/api/v3/AI_httpService/OC_reimbursement_check/reimbursement_check -invoice.attachment.report=http://10.66.14.150:9000/api/v3/AI_httpService/OC_report/report knife4j.enable=true knife4j.production=false -#spring.mail.host=smtp.exmail.qq.com -#spring.mail.username=fp@connectconcur.com -#spring.mail.password=Ab123*() -#spring.mail.default-encoding=UTF-8 -#spring.mail.properties.mail.smtp.ssl.enable=true -#spring.mail.properties.mail.smtp.ssl.trust=smtp.exmail.qq.com -#spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory -#spring.mail.properties.mail.smtp.socketFactory.port=465 -#spring.mail.properties.mail.smtp.port=465 -#spring.mail.properties.mail.smtp.auth=true -#spring.mail.properties.mail.smtp.starttls.enable=true -#spring.mail.properties.mail.smtp.starttls.required=true spring.mail.host=smtp.qiye.aliyun.com spring.mail.username=atlas@baibyun.com spring.mail.password=Today123! spring.mail.default-encoding=UTF-8 spring.mail.port=25 -#spring.mail.properties.mail.smtp.ssl.enable=true -#spring.mail.properties.mail.smtp.ssl.trust=smtp.office365.com -#spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory -#spring.mail.properties.mail.smtp.socketFactory.port=587 -#spring.mail.properties.mail.smtp.port=25 -#spring.mail.properties.mail.smtp.auth=true + spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true -#spring.redis.host=127.0.0.1 -#spring.redis.port=16379 -#spring.redis.password= -#spring.redis.database=1 -#spring.redis.timeout=30000ms -#spring.redis.jedis.pool.max-active=20 -#spring.redis.jedis.pool.max-wait=-1ms -#spring.redis.jedis.pool.max-idle=8 -#spring.redis.jedis.pool.min-idle=1 - template.mileage.image.path=D://Java//ideaWorkspace//fees-invoice-mini-backend//template template.image.path=D://Java//ideaWorkspace//fees-invoice-mini-backend//template @@ -162,9 +82,6 @@ pagehelper.reasonable=true pagehelper.support-methods-arguments=true -wechat.pc.appId=wxecd82ff9a948a534 -wechat.pc.appSecret=1c9541b2052fa3faf961c7f3253f0e3c - spring.quartz.job-store-type=jdbc spring.quartz.properties.org.quartz.scheduler.instanceName=clusteredScheduler spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO diff --git a/src/main/resources/mapper/AccountMappingMapper.xml b/src/main/resources/mapper/AccountMappingMapper.xml new file mode 100644 index 0000000..4e757df --- /dev/null +++ b/src/main/resources/mapper/AccountMappingMapper.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + ID,TYPE,DEBIT_ACCOUNT1, + CREDIT_SUBJECT1,DEBIT_ACCOUNT2,CREDIT_SUBJECT2,CATEGORY + + + + + + + + + delete + from account_mapping + where ID = #{id,jdbcType=INTEGER} + + + insert into account_mapping + ( ID, TYPE, DEBIT_ACCOUNT1 + , CREDIT_SUBJECT1, DEBIT_ACCOUNT2, CREDIT_SUBJECT2,CATEGORY) + values ( #{id,jdbcType=INTEGER}, #{type,jdbcType=VARCHAR}, #{debitAccount1,jdbcType=VARCHAR} + , #{creditSubject1,jdbcType=VARCHAR}, #{debitAccount2,jdbcType=VARCHAR} + , #{creditSubject2,jdbcType=VARCHAR},#{category,jdbcType=VARCHAR}) + + + update account_mapping + + + TYPE = #{type,jdbcType=VARCHAR}, + + + DEBIT_ACCOUNT1 = #{debitAccount1,jdbcType=VARCHAR}, + + + CREDIT_SUBJECT1 = #{creditSubject1,jdbcType=VARCHAR}, + + + DEBIT_ACCOUNT2 = #{debitAccount2,jdbcType=VARCHAR}, + + + CREDIT_SUBJECT2 = #{creditSubject2,jdbcType=VARCHAR}, + + + CATEGORY = #{category,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/AccountObjectMapper.xml b/src/main/resources/mapper/AccountObjectMapper.xml new file mode 100644 index 0000000..81a7daf --- /dev/null +++ b/src/main/resources/mapper/AccountObjectMapper.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + ID,CATEGORY,ACCOUNT, + DESCRIPTION,LEVEL,REMARK + + + + + + + delete + from account_object + where ID = #{id,jdbcType=INTEGER} + + + insert into account_object + ( ID, CATEGORY, ACCOUNT + , DESCRIPTION, LEVEL, REMARK) + values ( #{id,jdbcType=INTEGER}, #{category,jdbcType=VARCHAR}, #{account,jdbcType=VARCHAR} + , #{description,jdbcType=VARCHAR}, #{level,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}) + + + update account_object + + + CATEGORY = #{category,jdbcType=VARCHAR}, + + + ACCOUNT = #{account,jdbcType=VARCHAR}, + + + DESCRIPTION = #{description,jdbcType=VARCHAR}, + + + LEVEL = #{level,jdbcType=VARCHAR}, + + + REMARK = #{remark,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/AccountPeriodMapper.xml b/src/main/resources/mapper/AccountPeriodMapper.xml new file mode 100644 index 0000000..c59c927 --- /dev/null +++ b/src/main/resources/mapper/AccountPeriodMapper.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + ID,STATUS,PERIOD + + + + + + + + delete from account_period + where ID = #{id,jdbcType=INTEGER} + + + insert into account_period + ( ID,STATUS,PERIOD + ) + values (#{id,jdbcType=INTEGER},#{status,jdbcType=VARCHAR},#{period,jdbcType=VARCHAR} + ) + + + + insert into account_period + + ID, + STATUS, + PERIOD, + + + #{id,jdbcType=INTEGER}, + #{status,jdbcType=VARCHAR}, + #{period,jdbcType=VARCHAR}, + + + + + update account_period + + + STATUS = #{status,jdbcType=VARCHAR}, + + + PERIOD = #{period,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + + update account_period + set + STATUS = #{status,jdbcType=VARCHAR}, + PERIOD = #{period,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/AppMenuMapper.xml b/src/main/resources/mapper/AppMenuMapper.xml new file mode 100644 index 0000000..7c40ef9 --- /dev/null +++ b/src/main/resources/mapper/AppMenuMapper.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + ID,PAGE_PATH,ICON_PATH, + SELECTED_ICON_PATH,TEXT,EN_TEXT, + ACTIVE + + + + + + diff --git a/src/main/resources/mapper/AttendOrgMapper.xml b/src/main/resources/mapper/AttendOrgMapper.xml new file mode 100644 index 0000000..48825a5 --- /dev/null +++ b/src/main/resources/mapper/AttendOrgMapper.xml @@ -0,0 +1,245 @@ + + + + + + + + + + + + + + + + + + + + + + ID, PID, ORG_CODE, ORG_NAME, IS_DEL, EXT01, EXT02, EXT03, EXT04, EXT05, CREATE_BY, + CREATE_DATE, UPDATE_BY, UPDATE_DATE, REMARK + + + + delete from attend_org + where ID = #{id,jdbcType=INTEGER} + + + insert into attend_org (PID, ORG_CODE, ORG_NAME, + IS_DEL, EXT01, EXT02, + EXT03, EXT04, EXT05, + CREATE_BY, CREATE_DATE, UPDATE_BY, + UPDATE_DATE, REMARK) + values (#{pid,jdbcType=INTEGER}, #{orgCode,jdbcType=VARCHAR}, #{orgName,jdbcType=VARCHAR}, + #{isDel,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, + #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}, + #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, + #{updateDate,jdbcType=TIMESTAMP}, #{remark,jdbcType=VARCHAR}) + + + insert into attend_org + + + PID, + + + ORG_CODE, + + + ORG_NAME, + + + IS_DEL, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + CREATE_BY, + + + CREATE_DATE, + + + UPDATE_BY, + + + UPDATE_DATE, + + + REMARK, + + + + + #{pid,jdbcType=INTEGER}, + + + #{orgCode,jdbcType=VARCHAR}, + + + #{orgName,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + #{remark,jdbcType=VARCHAR}, + + + + + update attend_org + + + PID = #{pid,jdbcType=INTEGER}, + + + ORG_CODE = #{orgCode,jdbcType=VARCHAR}, + + + ORG_NAME = #{orgName,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + + + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + + + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + + + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + + + REMARK = #{remark,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update attend_org + set PID = #{pid,jdbcType=INTEGER}, + ORG_CODE = #{orgCode,jdbcType=VARCHAR}, + ORG_NAME = #{orgName,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR}, + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + REMARK = #{remark,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + + + diff --git a/src/main/resources/mapper/BandAreaConfigMapper.xml b/src/main/resources/mapper/BandAreaConfigMapper.xml new file mode 100644 index 0000000..876c35a --- /dev/null +++ b/src/main/resources/mapper/BandAreaConfigMapper.xml @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + ID, BAND, AREA, HOTEL, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + + delete from band_area_config + where ID = #{id,jdbcType=INTEGER} + + + + insert into band_area_config (BAND, AREA, HOTEL, + EXT01, EXT02, EXT03, + EXT04, EXT05) + values (#{band,jdbcType=VARCHAR}, #{area,jdbcType=VARCHAR}, #{hotel,jdbcType=VARCHAR}, + #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, + #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}) + + + + insert into band_area_config + + + BAND, + + + AREA, + + + HOTEL, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{band,jdbcType=VARCHAR}, + + + #{area,jdbcType=VARCHAR}, + + + #{hotel,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + + update band_area_config + + + BAND = #{band,jdbcType=VARCHAR}, + + + AREA = #{area,jdbcType=VARCHAR}, + + + HOTEL = #{hotel,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + + update band_area_config + set BAND = #{band,jdbcType=VARCHAR}, + AREA = #{area,jdbcType=VARCHAR}, + HOTEL = #{hotel,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/BandConfigMapper.xml b/src/main/resources/mapper/BandConfigMapper.xml new file mode 100644 index 0000000..da0e35d --- /dev/null +++ b/src/main/resources/mapper/BandConfigMapper.xml @@ -0,0 +1,280 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, BAND, AREA, ITEM, RATE, EXT01, EXT02, EXT03, EXT04, EXT05, EXT06, EXT07, EXT08, EXT09, + EXT10 + + + + + delete + from band_config + where ID = #{id,jdbcType=INTEGER} + + + + insert into band_config (BAND, AREA, ITEM, RATE, EXT01, + EXT02, EXT03, EXT04, + EXT05, EXT06, EXT07, + EXT08, EXT09, EXT10) + values (#{bandValue,jdbcType=VARCHAR}, #{area,jdbcType=VARCHAR}, #{item,jdbcType=VARCHAR}, + #{RATE,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}, #{ext06,jdbcType=VARCHAR}, #{ext07,jdbcType=VARCHAR}, + #{ext08,jdbcType=VARCHAR}, #{ext09,jdbcType=VARCHAR}, #{ext10,jdbcType=VARCHAR}) + + + + insert into band_config + + + BAND, + + + AREA, + + + ITEM, + + + RATE, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + EXT06, + + + EXT07, + + + EXT08, + + + EXT09, + + + EXT10, + + + + + #{bandValue,jdbcType=VARCHAR}, + + + #{area,jdbcType=VARCHAR}, + + + #{item,jdbcType=VARCHAR}, + + + #{rate,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{ext06,jdbcType=VARCHAR}, + + + #{ext07,jdbcType=VARCHAR}, + + + #{ext08,jdbcType=VARCHAR}, + + + #{ext09,jdbcType=VARCHAR}, + + + #{ext10,jdbcType=VARCHAR}, + + + + + + update band_config + + + BAND = #{bandValue,jdbcType=VARCHAR}, + + + AREA = #{area,jdbcType=VARCHAR}, + + + ITEM = #{item,jdbcType=VARCHAR}, + + + RATE = #{rate,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + EXT06 = #{ext06,jdbcType=VARCHAR}, + + + EXT07 = #{ext07,jdbcType=VARCHAR}, + + + EXT08 = #{ext08,jdbcType=VARCHAR}, + + + EXT09 = #{ext09,jdbcType=VARCHAR}, + + + EXT10 = #{ext10,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + + update band_config + set BAND = #{bandValue,jdbcType=VARCHAR}, + AREA = #{area,jdbcType=VARCHAR}, + ITEM = #{item,jdbcType=VARCHAR}, + RATE = #{rate,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR}, + EXT06 = #{ext06,jdbcType=VARCHAR}, + EXT07 = #{ext07,jdbcType=VARCHAR}, + EXT08 = #{ext08,jdbcType=VARCHAR}, + EXT09 = #{ext09,jdbcType=VARCHAR}, + EXT10 = #{ext10,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + + + + + diff --git a/src/main/resources/mapper/CorpInvoiceReceiveHeaderMapper.xml b/src/main/resources/mapper/CorpInvoiceReceiveHeaderMapper.xml new file mode 100644 index 0000000..f8144eb --- /dev/null +++ b/src/main/resources/mapper/CorpInvoiceReceiveHeaderMapper.xml @@ -0,0 +1,305 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID,DATE_OF_RECEIPT,BUYER, + INVOICE_TYPE,SELLER,INVOICE_CODE, + INVOICE_NUM,INVOICE_DATE,AMOUNT_MONEY, + TAX_AMOUNT,TOTAL_AMOUNT,USERNAME, + TYPE,ODD_NUM,VALID_STATUS, + REMARKS,STATUS,TICKET_CODE,VERIFIED_CODE,BUYER_CODE,SELLER_CODE,INVOICE_REMARK,IMG_URL,SEND_STATUS + + + + + + + + delete from corp_invoice_receive_header + where ID = #{id,jdbcType=INTEGER} + + + insert into corp_invoice_receive_header + ( ID,DATE_OF_RECEIPT,BUYER + ,INVOICE_TYPE,SELLER,INVOICE_CODE + ,INVOICE_NUM,INVOICE_DATE,AMOUNT_MONEY + ,TAX_AMOUNT,TOTAL_AMOUNT,USERNAME + ,TYPE,ODD_NUM,VALID_STATUS + ,REMARKS,STATUS,TICKET_CODE,VERIFIED_CODE,BUYER_CODE,SELLER_CODE,INVOICE_REMARK,IMG_URL,SEND_STATUS) + values (#{id,jdbcType=INTEGER},#{dateOfReceipt,jdbcType=DATE},#{buyer,jdbcType=VARCHAR} + ,#{invoiceType,jdbcType=VARCHAR},#{seller,jdbcType=VARCHAR},#{invoiceCode,jdbcType=VARCHAR} + ,#{invoiceNum,jdbcType=VARCHAR},#{invoiceDate,jdbcType=VARCHAR},#{amountMoney,jdbcType=VARCHAR} + ,#{taxAmount,jdbcType=VARCHAR},#{totalAmount,jdbcType=VARCHAR},#{username,jdbcType=VARCHAR} + ,#{type,jdbcType=INTEGER},#{oddNum,jdbcType=VARCHAR},#{validStatus,jdbcType=VARCHAR} + ,#{remarks,jdbcType=VARCHAR},#{status,jdbcType=VARCHAR} + ,#{ticketCode,jdbcType=VARCHAR},#{verifiedCode,jdbcType=VARCHAR},#{buyerCode,jdbcType=VARCHAR} + ,#{sellerCode,jdbcType=VARCHAR},#{invoiceRemark,jdbcType=VARCHAR} + ,#{imgUrl,jdbcType=VARCHAR},#{sendStatus,jdbcType=VARCHAR}) + + + insert into corp_invoice_receive_header + + ID, + DATE_OF_RECEIPT, + BUYER, + INVOICE_TYPE, + SELLER, + INVOICE_CODE, + INVOICE_NUM, + INVOICE_DATE, + AMOUNT_MONEY, + TAX_AMOUNT, + TOTAL_AMOUNT, + USERNAME, + TYPE, + ODD_NUM, + VALID_STATUS, + REMARKS, + STATUS, + TICKET_CODE, + VERIFIED_CODE, + BUYER_CODE, + SELLER_CODE, + INVOICE_REMARK, + IMG_URL, + SEND_STATUS, + + + #{id,jdbcType=INTEGER}, + #{dateOfReceipt,jdbcType=DATE}, + #{buyer,jdbcType=VARCHAR}, + #{invoiceType,jdbcType=VARCHAR}, + #{seller,jdbcType=VARCHAR}, + #{invoiceCode,jdbcType=VARCHAR}, + #{invoiceNum,jdbcType=VARCHAR}, + #{invoiceDate,jdbcType=VARCHAR}, + #{amountMoney,jdbcType=VARCHAR}, + #{taxAmount,jdbcType=VARCHAR}, + #{totalAmount,jdbcType=VARCHAR}, + #{username,jdbcType=VARCHAR}, + #{type,jdbcType=INTEGER}, + #{oddNum,jdbcType=VARCHAR}, + #{validStatus,jdbcType=VARCHAR}, + #{remarks,jdbcType=VARCHAR}, + #{status,jdbcType=VARCHAR}, + #{ticketCode,jdbcType=VARCHAR}, + #{verifiedCode,jdbcType=VARCHAR}, + #{buyerCode,jdbcType=VARCHAR}, + #{sellerCode,jdbcType=VARCHAR}, + #{invoiceRemark,jdbcType=VARCHAR}, + #{imgUrl,jdbcType=VARCHAR}, + #{sendStatus,jdbcType=VARCHAR}, + + + + update corp_invoice_receive_header + + + DATE_OF_RECEIPT = #{dateOfReceipt,jdbcType=DATE}, + + + BUYER = #{buyer,jdbcType=VARCHAR}, + + + INVOICE_TYPE = #{invoiceType,jdbcType=VARCHAR}, + + + SELLER = #{seller,jdbcType=VARCHAR}, + + + INVOICE_CODE = #{invoiceCode,jdbcType=VARCHAR}, + + + INVOICE_NUM = #{invoiceNum,jdbcType=VARCHAR}, + + + INVOICE_DATE = #{invoiceDate,jdbcType=VARCHAR}, + + + AMOUNT_MONEY = #{amountMoney,jdbcType=VARCHAR}, + + + TAX_AMOUNT = #{taxAmount,jdbcType=VARCHAR}, + + + TOTAL_AMOUNT = #{totalAmount,jdbcType=VARCHAR}, + + + USERNAME = #{username,jdbcType=VARCHAR}, + + + TYPE = #{type,jdbcType=INTEGER}, + + + ODD_NUM = #{oddNum,jdbcType=VARCHAR}, + + + VALID_STATUS = #{validStatus,jdbcType=VARCHAR}, + + + REMARKS = #{remarks,jdbcType=VARCHAR}, + + + STATUS = #{status,jdbcType=VARCHAR}, + + + TICKET_CODE = #{ticketCode,jdbcType=VARCHAR}, + + + VERIFIED_CODE = #{verifiedCode,jdbcType=VARCHAR}, + + + BUYER_CODE = #{buyerCode,jdbcType=VARCHAR}, + + + SELLER_CODE = #{sellerCode,jdbcType=VARCHAR}, + + + INVOICE_REMARK = #{invoiceRemark,jdbcType=VARCHAR}, + + + IMG_URL = #{imgUrl,jdbcType=VARCHAR}, + + + SEND_STATUS = #{sendStatus,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update corp_invoice_receive_header + set + DATE_OF_RECEIPT = #{dateOfReceipt,jdbcType=DATE}, + BUYER = #{buyer,jdbcType=VARCHAR}, + INVOICE_TYPE = #{invoiceType,jdbcType=VARCHAR}, + SELLER = #{seller,jdbcType=VARCHAR}, + INVOICE_CODE = #{invoiceCode,jdbcType=VARCHAR}, + INVOICE_NUM = #{invoiceNum,jdbcType=VARCHAR}, + INVOICE_DATE = #{invoiceDate,jdbcType=VARCHAR}, + AMOUNT_MONEY = #{amountMoney,jdbcType=VARCHAR}, + TAX_AMOUNT = #{taxAmount,jdbcType=VARCHAR}, + TOTAL_AMOUNT = #{totalAmount,jdbcType=VARCHAR}, + USERNAME = #{username,jdbcType=VARCHAR}, + TYPE = #{type,jdbcType=INTEGER}, + ODD_NUM = #{oddNum,jdbcType=VARCHAR}, + VALID_STATUS = #{validStatus,jdbcType=VARCHAR}, + REMARKS = #{remarks,jdbcType=VARCHAR}, + STATUS = #{status,jdbcType=VARCHAR}, + TICKET_CODE = #{ticketCode,jdbcType=VARCHAR}, + VERIFIED_CODE = #{verifiedCode,jdbcType=VARCHAR}, + BUYER_CODE = #{buyerCode,jdbcType=VARCHAR}, + SELLER_CODE = #{sellerCode,jdbcType=VARCHAR}, + INVOICE_REMARK = #{invoiceRemark,jdbcType=VARCHAR}, + IMG_URL = #{imgUrl,jdbcType=VARCHAR}, + SEND_STATUS = #{sendStatus,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/CorpInvoiceReceiveLineMapper.xml b/src/main/resources/mapper/CorpInvoiceReceiveLineMapper.xml new file mode 100644 index 0000000..82efc51 --- /dev/null +++ b/src/main/resources/mapper/CorpInvoiceReceiveLineMapper.xml @@ -0,0 +1,202 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID,PID,NAME, + UNIT,QUANTITY,PRICE, + TOTAL,EXTRA_FIELDS,SPECIFICATION, + TAX_RATE,TAX,DEDUCTION_AMOUNT, + DEDUCTION_TAX_RATE,DEDUCTION_TAX,IS_DEL, + DIFFERENCE,ORIGIN_UNIT,ORIGIN_QUANTITY, + ORIGIN_PRICE + + + + + + + + delete from corp_invoice_receive_line + where ID = #{id,jdbcType=VARCHAR} + + + insert into corp_invoice_receive_line + ( ID,PID,NAME + ,UNIT,QUANTITY,PRICE + ,TOTAL,EXTRA_FIELDS,SPECIFICATION + ,TAX_RATE,TAX,DEDUCTION_AMOUNT + ,DEDUCTION_TAX_RATE,DEDUCTION_TAX,IS_DEL + ,DIFFERENCE,ORIGIN_UNIT,ORIGIN_QUANTITY + ,ORIGIN_PRICE) + values (#{id,jdbcType=VARCHAR},#{pid,jdbcType=VARCHAR},#{name,jdbcType=VARCHAR} + ,#{unit,jdbcType=VARCHAR},#{quantity,jdbcType=VARCHAR},#{price,jdbcType=VARCHAR} + ,#{total,jdbcType=VARCHAR},#{extraFields,jdbcType=VARCHAR},#{specification,jdbcType=VARCHAR} + ,#{taxRate,jdbcType=VARCHAR},#{tax,jdbcType=VARCHAR},#{deductionAmount,jdbcType=VARCHAR} + ,#{deductionTaxRate,jdbcType=VARCHAR},#{deductionTax,jdbcType=VARCHAR},#{isDel,jdbcType=TINYINT} + ,#{difference,jdbcType=VARCHAR},#{originUnit,jdbcType=VARCHAR},#{originQuantity,jdbcType=VARCHAR} + ,#{originPrice,jdbcType=VARCHAR}) + + + insert into corp_invoice_receive_line + + ID, + PID, + NAME, + UNIT, + QUANTITY, + PRICE, + TOTAL, + EXTRA_FIELDS, + SPECIFICATION, + TAX_RATE, + TAX, + DEDUCTION_AMOUNT, + DEDUCTION_TAX_RATE, + DEDUCTION_TAX, + IS_DEL, + DIFFERENCE, + ORIGIN_UNIT, + ORIGIN_QUANTITY, + ORIGIN_PRICE, + + + #{id,jdbcType=VARCHAR}, + #{pid,jdbcType=VARCHAR}, + #{name,jdbcType=VARCHAR}, + #{unit,jdbcType=VARCHAR}, + #{quantity,jdbcType=VARCHAR}, + #{price,jdbcType=VARCHAR}, + #{total,jdbcType=VARCHAR}, + #{extraFields,jdbcType=VARCHAR}, + #{specification,jdbcType=VARCHAR}, + #{taxRate,jdbcType=VARCHAR}, + #{tax,jdbcType=VARCHAR}, + #{deductionAmount,jdbcType=VARCHAR}, + #{deductionTaxRate,jdbcType=VARCHAR}, + #{deductionTax,jdbcType=VARCHAR}, + #{isDel,jdbcType=TINYINT}, + #{difference,jdbcType=VARCHAR}, + #{originUnit,jdbcType=VARCHAR}, + #{originQuantity,jdbcType=VARCHAR}, + #{originPrice,jdbcType=VARCHAR}, + + + + update corp_invoice_receive_line + + + PID = #{pid,jdbcType=VARCHAR}, + + + NAME = #{name,jdbcType=VARCHAR}, + + + UNIT = #{unit,jdbcType=VARCHAR}, + + + QUANTITY = #{quantity,jdbcType=VARCHAR}, + + + PRICE = #{price,jdbcType=VARCHAR}, + + + TOTAL = #{total,jdbcType=VARCHAR}, + + + EXTRA_FIELDS = #{extraFields,jdbcType=VARCHAR}, + + + SPECIFICATION = #{specification,jdbcType=VARCHAR}, + + + TAX_RATE = #{taxRate,jdbcType=VARCHAR}, + + + TAX = #{tax,jdbcType=VARCHAR}, + + + DEDUCTION_AMOUNT = #{deductionAmount,jdbcType=VARCHAR}, + + + DEDUCTION_TAX_RATE = #{deductionTaxRate,jdbcType=VARCHAR}, + + + DEDUCTION_TAX = #{deductionTax,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=TINYINT}, + + + DIFFERENCE = #{difference,jdbcType=VARCHAR}, + + + ORIGIN_UNIT = #{originUnit,jdbcType=VARCHAR}, + + + ORIGIN_QUANTITY = #{originQuantity,jdbcType=VARCHAR}, + + + ORIGIN_PRICE = #{originPrice,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=VARCHAR} + + + update corp_invoice_receive_line + set + PID = #{pid,jdbcType=VARCHAR}, + NAME = #{name,jdbcType=VARCHAR}, + UNIT = #{unit,jdbcType=VARCHAR}, + QUANTITY = #{quantity,jdbcType=VARCHAR}, + PRICE = #{price,jdbcType=VARCHAR}, + TOTAL = #{total,jdbcType=VARCHAR}, + EXTRA_FIELDS = #{extraFields,jdbcType=VARCHAR}, + SPECIFICATION = #{specification,jdbcType=VARCHAR}, + TAX_RATE = #{taxRate,jdbcType=VARCHAR}, + TAX = #{tax,jdbcType=VARCHAR}, + DEDUCTION_AMOUNT = #{deductionAmount,jdbcType=VARCHAR}, + DEDUCTION_TAX_RATE = #{deductionTaxRate,jdbcType=VARCHAR}, + DEDUCTION_TAX = #{deductionTax,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=TINYINT}, + DIFFERENCE = #{difference,jdbcType=VARCHAR}, + ORIGIN_UNIT = #{originUnit,jdbcType=VARCHAR}, + ORIGIN_QUANTITY = #{originQuantity,jdbcType=VARCHAR}, + ORIGIN_PRICE = #{originPrice,jdbcType=VARCHAR} + where ID = #{id,jdbcType=VARCHAR} + + diff --git a/src/main/resources/mapper/CorpPaymentHeaderMapper.xml b/src/main/resources/mapper/CorpPaymentHeaderMapper.xml new file mode 100644 index 0000000..a484a76 --- /dev/null +++ b/src/main/resources/mapper/CorpPaymentHeaderMapper.xml @@ -0,0 +1,314 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, BUSINESS_COMPANY, PAY_NUM, `NAME`, `TYPE`, CURRENCY, AMOUNT, SUBMIT_NAME, SUBMIT_DATE, + `STATUS`, CHECKER, COST_CENTER, DOCUMENT,VENDOR, VENDORCODE, REQUESTID, EXT01,EXT02,EXT03,EXT04,EXT05 + + + + + delete from corp_payment_header + where ID = #{id,jdbcType=INTEGER} + + + insert into corp_payment_header (BUSINESS_COMPANY, PAY_NUM, `NAME`, + `TYPE`, CURRENCY, AMOUNT, + SUBMIT_NAME, SUBMIT_DATE, `STATUS`, + CHECKER, COST_CENTER, DOCUMENT, VENDOR, VENDORCODE, REQUESTID + ) + values (#{businessCompany,jdbcType=VARCHAR}, #{payNum,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{currency,jdbcType=VARCHAR}, #{amount,jdbcType=BIGINT}, + #{submitName,jdbcType=VARCHAR}, #{submitDate,jdbcType=DATE}, #{status,jdbcType=VARCHAR}, + #{checker,jdbcType=VARCHAR}, #{costCenter,jdbcType=VARCHAR}, #{document,jdbcType=VARCHAR}, + #{vendor,jdbcType=VARCHAR}, #{vendorCode,jdbcType=VARCHAR}, #{requestId,jdbcType=VARCHAR} + ) + + + insert into corp_payment_header + + + BUSINESS_COMPANY, + + + PAY_NUM, + + + `NAME`, + + + `TYPE`, + + + CURRENCY, + + + AMOUNT, + + + SUBMIT_NAME, + + + SUBMIT_DATE, + + + `STATUS`, + + + CHECKER, + + + COST_CENTER, + + + DOCUMENT, + + + VENDOR, + + + VENDORCODE, + + + REQUESTID, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{businessCompany,jdbcType=VARCHAR}, + + + #{payNum,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{currency,jdbcType=VARCHAR}, + + + #{amount,jdbcType=BIGINT}, + + + #{submitName,jdbcType=VARCHAR}, + + + #{submitDate,jdbcType=DATE}, + + + #{status,jdbcType=VARCHAR}, + + + #{checker,jdbcType=VARCHAR}, + + + #{costCenter,jdbcType=VARCHAR}, + + + #{document,jdbcType=VARCHAR}, + + + #{vendor,jdbcType=VARCHAR}, + + + #{vendorCode,jdbcType=VARCHAR}, + + + #{requestId,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update corp_payment_header + + + BUSINESS_COMPANY = #{businessCompany,jdbcType=VARCHAR}, + + + PAY_NUM = #{payNum,jdbcType=VARCHAR}, + + + `NAME` = #{name,jdbcType=VARCHAR}, + + + `TYPE` = #{type,jdbcType=VARCHAR}, + + + CURRENCY = #{currency,jdbcType=VARCHAR}, + + + AMOUNT = #{amount,jdbcType=BIGINT}, + + + SUBMIT_NAME = #{submitName,jdbcType=VARCHAR}, + + + SUBMIT_DATE = #{submitDate,jdbcType=DATE}, + + + `STATUS` = #{status,jdbcType=VARCHAR}, + + + CHECKER = #{checker,jdbcType=VARCHAR}, + + + COST_CENTER = #{costCenter,jdbcType=VARCHAR}, + + + VENDOR = #{vendor,jdbcType=VARCHAR}, + + + VENDORCODE = #{vendorCode,jdbcType=VARCHAR}, + + + REQUESTID = #{requestId,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update corp_payment_header + set BUSINESS_COMPANY = #{businessCompany,jdbcType=VARCHAR}, + PAY_NUM = #{payNum,jdbcType=VARCHAR}, + `NAME` = #{name,jdbcType=VARCHAR}, + `TYPE` = #{type,jdbcType=VARCHAR}, + CURRENCY = #{currency,jdbcType=VARCHAR}, + AMOUNT = #{amount,jdbcType=BIGINT}, + SUBMIT_NAME = #{submitName,jdbcType=VARCHAR}, + SUBMIT_DATE = #{submitDate,jdbcType=DATE}, + `STATUS` = #{status,jdbcType=VARCHAR}, + CHECKER = #{checker,jdbcType=VARCHAR}, + COST_CENTER = #{costCenter,jdbcType=VARCHAR}, + DOCUMENT = #{document,jdbcType=VARCHAR}, + VENDOR = #{vendor,jdbcType=VARCHAR}, + VENDORCODE = #{vendorCode,jdbcType=VARCHAR}, + REQUESTID = #{requestId,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + diff --git a/src/main/resources/mapper/CorpPaymentLineMapper.xml b/src/main/resources/mapper/CorpPaymentLineMapper.xml new file mode 100644 index 0000000..51e3562 --- /dev/null +++ b/src/main/resources/mapper/CorpPaymentLineMapper.xml @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + ID,PID,EXPENSE_TYPE, + INVOICE_CODE,INVOICE_NUM,INVOICE_DATE, + TAX,TAX_AMOUNT,CURRENCY, + AMOUNT,RECEIVED,EXT01,EXT02,EXT03,EXT04,EXT05 + + + + + + + delete + from corp_payment_line + where ID = #{id,jdbcType=INTEGER} + + + insert into corp_payment_line + ( ID, PID, EXPENSE_TYPE + , INVOICE_CODE, INVOICE_NUM, INVOICE_DATE + , TAX, TAX_AMOUNT, CURRENCY + , AMOUNT, RECEIVED) + values ( #{id,jdbcType=INTEGER}, #{pId,jdbcType=VARCHAR}, #{expenseType,jdbcType=VARCHAR} + , #{invoiceCode,jdbcType=VARCHAR}, #{invoiceNum,jdbcType=VARCHAR}, #{invoiceDate,jdbcType=VARCHAR} + , #{tax,jdbcType=VARCHAR}, #{taxAmount,jdbcType=VARCHAR}, #{currency,jdbcType=VARCHAR} + , #{amount,jdbcType=VARCHAR}, #{received,jdbcType=VARCHAR}) + + + insert into corp_payment_line + + ID, + PID, + EXPENSE_TYPE, + INVOICE_CODE, + INVOICE_NUM, + INVOICE_DATE, + TAX, + TAX_AMOUNT, + CURRENCY, + AMOUNT, + RECEIVED, + + + #{id,jdbcType=INTEGER}, + #{pId,jdbcType=VARCHAR}, + #{expenseType,jdbcType=VARCHAR}, + #{invoiceCode,jdbcType=VARCHAR}, + #{invoiceNum,jdbcType=VARCHAR}, + #{invoiceDate,jdbcType=VARCHAR}, + #{tax,jdbcType=VARCHAR}, + #{taxAmount,jdbcType=VARCHAR}, + #{currency,jdbcType=VARCHAR}, + #{amount,jdbcType=VARCHAR}, + #{received,jdbcType=VARCHAR}, + + + + insert into corp_payment_line + ( PID, EXPENSE_TYPE + , INVOICE_CODE, INVOICE_NUM, INVOICE_DATE + , TAX, TAX_AMOUNT, CURRENCY + , AMOUNT, RECEIVED,EXT01,EXT02,EXT03,EXT04,EXT05) + values + + ( #{record.pId,jdbcType=VARCHAR}, #{record.expenseType,jdbcType=VARCHAR} + , #{record.invoiceCode,jdbcType=VARCHAR}, #{record.invoiceNum,jdbcType=VARCHAR}, #{record.invoiceDate,jdbcType=VARCHAR} + , #{record.tax,jdbcType=VARCHAR}, #{record.taxAmount,jdbcType=VARCHAR}, #{record.currency,jdbcType=VARCHAR} + , #{record.amount,jdbcType=VARCHAR}, #{record.received,jdbcType=VARCHAR}, #{record.ext01,jdbcType=VARCHAR} + , #{record.ext02,jdbcType=VARCHAR}, #{record.ext03,jdbcType=VARCHAR} + , #{record.ext04,jdbcType=VARCHAR}, #{record.ext05,jdbcType=VARCHAR}) + + + + update corp_payment_line + + + PID = #{pId,jdbcType=VARCHAR}, + + + EXPENSE_TYPE = #{expenseType,jdbcType=VARCHAR}, + + + INVOICE_CODE = #{invoiceCode,jdbcType=VARCHAR}, + + + INVOICE_NUM = #{invoiceNum,jdbcType=VARCHAR}, + + + INVOICE_DATE = #{invoiceDate,jdbcType=VARCHAR}, + + + TAX = #{tax,jdbcType=VARCHAR}, + + + TAX_AMOUNT = #{taxAmount,jdbcType=VARCHAR}, + + + CURRENCY = #{currency,jdbcType=VARCHAR}, + + + AMOUNT = #{amount,jdbcType=VARCHAR}, + + + RECEIVED = #{received,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update corp_payment_line + set RECEIVED = '1' + where INVOICE_NUM = #{num} + and INVOICE_CODE = #{code} + + + update corp_payment_line + set PID = #{lineId,jdbcType=VARCHAR}, + EXPENSE_TYPE = #{expenseType,jdbcType=VARCHAR}, + INVOICE_CODE = #{invoiceCode,jdbcType=VARCHAR}, + INVOICE_NUM = #{invoiceNum,jdbcType=VARCHAR}, + INVOICE_DATE = #{invoiceDate,jdbcType=VARCHAR}, + TAX = #{tax,jdbcType=VARCHAR}, + TAX_AMOUNT = #{taxAmount,jdbcType=VARCHAR}, + CURRENCY = #{currency,jdbcType=VARCHAR}, + AMOUNT = #{amount,jdbcType=VARCHAR}, + RECEIVED = #{received,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + diff --git a/src/main/resources/mapper/CorporateInvoiceMapper.xml b/src/main/resources/mapper/CorporateInvoiceMapper.xml index 3f13b30..0675c49 100644 --- a/src/main/resources/mapper/CorporateInvoiceMapper.xml +++ b/src/main/resources/mapper/CorporateInvoiceMapper.xml @@ -114,6 +114,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -859,6 +960,141 @@ + + + + + + + select + + from data_obj_mapping + where 1=1 + and available = 1 + and is_del = 0 + and json_locate = #{locate} + and kind = #{kind} + + + diff --git a/src/main/resources/mapper/CorporateInvoiceScannerFilesMapper.xml b/src/main/resources/mapper/CorporateInvoiceScannerFilesMapper.xml new file mode 100644 index 0000000..09aafd3 --- /dev/null +++ b/src/main/resources/mapper/CorporateInvoiceScannerFilesMapper.xml @@ -0,0 +1,198 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + ,scanner_id + ,invoice_number + ,split_file_path + ,pdf_path + ,ocr_result + ,ocr_status + ,verify_status + ,ocr_interface + ,ocr_cost + ,create_date + ,update_date + ,ext01 + ,ext02 + ,ext03 + , ext04 + ,ext05 + ,ext06 + ,ext07 + ,ext08 + ,ext09 + ,ext10 + + + + update corporate_invoice_scanner_files + + + scanner_id = #{scannerId}, + + + invoice_number = #{invoiceNumber}, + + + split_file_path = #{splitFilePath}, + + + pdf_path = #{pdfPath}, + + + ocr_result = #{ocrResult}, + + + ocr_status = #{ocrStatus}, + + + verify_status = #{verifyStatus}, + + + ocr_interface = #{ocrInterface}, + + + ocr_cost = #{ocrCost}, + + + create_date = #{createDate}, + + + update_date = #{updateDate}, + + + ext01 = #{ext01}, + + + ext02 = #{ext02}, + + + ext03 = #{ext03}, + + + ext04 = #{ext04}, + + + ext05 = #{ext05}, + + + ext06 = #{ext06}, + + + ext07 = #{ext07}, + + + ext08 = #{ext08}, + + + ext09 = #{ext09}, + + + ext10 = #{ext10}, + + + where id = #{id} + + + + + + + + + insert into corporate_invoice_scanner_files + ( id + ,scanner_id + ,invoice_number + ,split_file_path + ,pdf_path + ,ocr_result + ,ocr_status + ,verify_status + ,ocr_interface + ,ocr_cost + ,create_date + ,update_date + ,ext01 + ,ext02 + ,ext03 + , ext04 + ,ext05 + ,ext06 + ,ext07 + ,ext08 + ,ext09 + ,ext10) + values ( #{id,jdbcType=BIGINT} + , #{scannerId,jdbcType=BIGINT} + , #{invoiceNumber,jdbcType=VARCHAR} + , #{splitFilePath,jdbcType=VARCHAR} + , #{pdfPath,jdbcType=VARCHAR} + , #{ocrResult,jdbcType=VARCHAR} + , #{ocrStatus,jdbcType=INTEGER} + , #{verifyStatus,jdbcType=INTEGER} + , #{ocrInterface,jdbcType=VARCHAR} + , #{ocrCost,jdbcType=INTEGER} + , #{createDate,jdbcType=TIMESTAMP} + , #{updateDate,jdbcType=TIMESTAMP} + , #{ext01,jdbcType=VARCHAR} + , #{ext02,jdbcType=VARCHAR} + , #{ext03,jdbcType=VARCHAR} + , #{ext04,jdbcType=VARCHAR} + , #{ext05,jdbcType=VARCHAR} + , #{ext06,jdbcType=VARCHAR} + , #{ext07,jdbcType=VARCHAR} + , #{ext08,jdbcType=VARCHAR} + , #{ext09,jdbcType=VARCHAR} + , #{ext10,jdbcType=VARCHAR}) + + diff --git a/src/main/resources/mapper/CurrencyMapper.xml b/src/main/resources/mapper/CurrencyMapper.xml new file mode 100644 index 0000000..fcc007b --- /dev/null +++ b/src/main/resources/mapper/CurrencyMapper.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + ID, NAME, IS_DEL, CODE + + + + + + + + + delete + from currency + where ID = #{id} + + + + + + + insert into currency (ID, NAME, IS_DEL, CODE) + values (#{id}, #{name}, #{isDel}, #{code}) + + + + + insert into currency + + + ID, + + + NAME, + + + IS_DEL, + + + CODE, + + + + + #{id}, + + + #{name}, + + + #{isDel}, + + + #{code}, + + + + + + update currency + + + NAME = #{name}, + + + IS_DEL = #{isDel}, + + + CODE = #{code}, + + + where ID = #{id} + + + + + update currency + set NAME = #{name}, + IS_DEL = #{isDel}, + CODE = #{code} + where ID = #{id} + + + + + + + ${sql} + + + + + + diff --git a/src/main/resources/mapper/CustomerMapper.xml b/src/main/resources/mapper/CustomerMapper.xml new file mode 100644 index 0000000..4423778 --- /dev/null +++ b/src/main/resources/mapper/CustomerMapper.xml @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into customer(CUSTOMER, IS_DEL, CREATE_TIME, ORG_UNIT_WORD, SEND_TYPE, MULTI_INV, MANUAL_FIELD_CONFIG, + COR_MAX_VALID, SMART_ATTACHMENT, FORCE_VALID, UNVALID_SEND, COMPANY_WORD, + EXPENSE_TYPE_ACTIVE) + values (#{customer}, #{isDel}, #{createTime}, #{orgUnitWord}, #{sendType}, #{multiInv}, #{manualFieldConfig}, + #{corMaxValid,jdbcType=TINYINT}, #{smartAttachment,jdbcType=BOOLEAN}, + #{forceValid,jdbcType=TINYINT}, #{unValidSend,jdbcType=BOOLEAN}, #{companyWord,jdbcType=VARCHAR}, + #{expenseTypeActive,jdbcType=BOOLEAN}) + + + + + update customer + + + CUSTOMER = #{customer}, + + + IS_DEL = #{isDel}, + + + CREATE_TIME = #{createTime}, + + + ORG_UNIT_WORD = #{orgUnitWord}, + + + SEND_TYPE = #{sendType}, + + + MULTI_INV = #{multiInv}, + + + MANUAL_FIELD_CONFIG = #{manualFieldConfig}, + + + COR_MAX_VALID = #{corMaxValid,jdbcType=TINYINT}, + + + SMART_ATTACHMENT = #{smartAttachment,jdbcType=BOOLEAN}, + + + FORCE_VALID = #{forceValid,jdbcType=TINYINT}, + + + UNVALID_SEND = #{unValidSend,jdbcType=BOOLEAN}, + + + COMPANY_WORD = #{companyWord,jdbcType=VARCHAR}, + + + EXPENSE_TYPE_ACTIVE = #{expenseTypeActive,jdbcType=BOOLEAN}, + + + where ID = #{id} + + + + + delete + from customer + where ID = #{id} + + diff --git a/src/main/resources/mapper/DeductionCompanyMapper.xml b/src/main/resources/mapper/DeductionCompanyMapper.xml new file mode 100644 index 0000000..7939122 --- /dev/null +++ b/src/main/resources/mapper/DeductionCompanyMapper.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + id,name,code + + + + delete + from deduction_company + where id = #{id,jdbcType=INTEGER} + + + insert into deduction_company + (id, name, code) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}) + + + update deduction_company + + + name = #{name,jdbcType=VARCHAR}, + + + code = #{code,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/DeductionConfigMapper.xml b/src/main/resources/mapper/DeductionConfigMapper.xml new file mode 100644 index 0000000..4e917fe --- /dev/null +++ b/src/main/resources/mapper/DeductionConfigMapper.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + ID,INVOICE_TYPE,EXPENSE_TYPES + + + diff --git a/src/main/resources/mapper/ErrorReportMapper.xml b/src/main/resources/mapper/ErrorReportMapper.xml new file mode 100644 index 0000000..9a681af --- /dev/null +++ b/src/main/resources/mapper/ErrorReportMapper.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + ID,REPORT_ID,STATUS, + CREATE_TIME + + + + + delete + from error_report + where ID = #{id,jdbcType=BIGINT} + + + insert into error_report + ( ID, REPORT_ID, STATUS + , CREATE_TIME) + values ( #{id,jdbcType=BIGINT}, #{reportId,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR} + , #{createTime,jdbcType=TIMESTAMP}) + + + update error_report + + + REPORT_ID = #{reportId,jdbcType=VARCHAR}, + + + STATUS = #{status,jdbcType=VARCHAR}, + + + CREATE_TIME = #{createTime,jdbcType=TIMESTAMP}, + + + where ID = #{id,jdbcType=BIGINT} + + + + delete + from error_report + where REPORT_ID = #{reportId} + + diff --git a/src/main/resources/mapper/ExpCombReportMapper.xml b/src/main/resources/mapper/ExpCombReportMapper.xml new file mode 100644 index 0000000..61c7a0c --- /dev/null +++ b/src/main/resources/mapper/ExpCombReportMapper.xml @@ -0,0 +1,176 @@ + + + + + + + + + + + + + + + + + COMB_REPORT_ID, COMB_REPORT_NAME, COMB_START, COMB_END, POLICY, USER_ID, IS_SEND, + CONCUR_ID, COMB_TIME, REMARK + + + + delete from exp_comb_report + where COMB_REPORT_ID = #{combReportId,jdbcType=BIGINT} + + + insert into exp_comb_report (COMB_REPORT_NAME, COMB_START, COMB_END, + POLICY, USER_ID, IS_SEND, + CONCUR_ID, COMB_TIME, REMARK + ) + values (#{combReportName,jdbcType=VARCHAR}, #{combStart,jdbcType=VARCHAR}, #{combEnd,jdbcType=VARCHAR}, + #{policy,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER}, #{isSend,jdbcType=INTEGER}, + #{concurId,jdbcType=VARCHAR}, #{combTime,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR} + ) + + + insert into exp_comb_report + + + COMB_REPORT_NAME, + + + COMB_START, + + + COMB_END, + + + POLICY, + + + USER_ID, + + + IS_SEND, + + + CONCUR_ID, + + + COMB_TIME, + + + REMARK, + + + + + #{combReportName,jdbcType=VARCHAR}, + + + #{combStart,jdbcType=VARCHAR}, + + + #{combEnd,jdbcType=VARCHAR}, + + + #{policy,jdbcType=VARCHAR}, + + + #{userId,jdbcType=INTEGER}, + + + #{isSend,jdbcType=INTEGER}, + + + #{concurId,jdbcType=VARCHAR}, + + + #{combTime,jdbcType=VARCHAR}, + + + #{remark,jdbcType=VARCHAR}, + + + + + update exp_comb_report + + + COMB_REPORT_NAME = #{combReportName,jdbcType=VARCHAR}, + + + COMB_START = #{combStart,jdbcType=VARCHAR}, + + + COMB_END = #{combEnd,jdbcType=VARCHAR}, + + + POLICY = #{policy,jdbcType=VARCHAR}, + + + USER_ID = #{userId,jdbcType=INTEGER}, + + + IS_SEND = #{isSend,jdbcType=INTEGER}, + + + CONCUR_ID = #{concurId,jdbcType=VARCHAR}, + + + COMB_TIME = #{combTime,jdbcType=VARCHAR}, + + + REMARK = #{remark,jdbcType=VARCHAR}, + + + where COMB_REPORT_ID = #{combReportId,jdbcType=BIGINT} + + + update exp_comb_report + set COMB_REPORT_NAME = #{combReportName,jdbcType=VARCHAR}, + COMB_START = #{combStart,jdbcType=VARCHAR}, + COMB_END = #{combEnd,jdbcType=VARCHAR}, + POLICY = #{policy,jdbcType=VARCHAR}, + USER_ID = #{userId,jdbcType=INTEGER}, + IS_SEND = #{isSend,jdbcType=INTEGER}, + CONCUR_ID = #{concurId,jdbcType=VARCHAR}, + COMB_TIME = #{combTime,jdbcType=VARCHAR}, + REMARK = #{remark,jdbcType=VARCHAR} + where COMB_REPORT_ID = #{combReportId,jdbcType=BIGINT} + + + + insert into exp_comb_report (COMB_REPORT_NAME, COMB_START, COMB_END, + POLICY, USER_ID, IS_SEND, + COMB_TIME, REMARK + ) + values + + (#{record.combReportName,jdbcType=VARCHAR}, #{record.combStart,jdbcType=VARCHAR} + ,#{record.combEnd,jdbcType=VARCHAR}, #{record.policy,jdbcType=VARCHAR} + ,#{record.userId,jdbcType=INTEGER}, #{record.isSend,jdbcType=INTEGER} + ,#{record.combTime,jdbcType=VARCHAR},#{record.remark,jdbcType=VARCHAR}) + + + + + diff --git a/src/main/resources/mapper/ExpCombReportSubMapper.xml b/src/main/resources/mapper/ExpCombReportSubMapper.xml new file mode 100644 index 0000000..4019236 --- /dev/null +++ b/src/main/resources/mapper/ExpCombReportSubMapper.xml @@ -0,0 +1,72 @@ + + + + + + + + + + ID, COMB_REPORT_ID, EXPENSE_REPROTS_ID + + + + delete from exp_comb_report_sub + where ID = #{id,jdbcType=BIGINT} + + + insert into exp_comb_report_sub (COMB_REPORT_ID, EXPENSE_REPROTS_ID) + values (#{combReportId,jdbcType=INTEGER}, #{expenseReprotsId,jdbcType=INTEGER}) + + + insert into exp_comb_report_sub + + + COMB_REPORT_ID, + + + EXPENSE_REPROTS_ID, + + + + + #{combReportId,jdbcType=INTEGER}, + + + #{expenseReprotsId,jdbcType=INTEGER}, + + + + + update exp_comb_report_sub + + + COMB_REPORT_ID = #{combReportId,jdbcType=INTEGER}, + + + EXPENSE_REPROTS_ID = #{expenseReprotsId,jdbcType=INTEGER}, + + + where ID = #{id,jdbcType=BIGINT} + + + update exp_comb_report_sub + set COMB_REPORT_ID = #{combReportId,jdbcType=INTEGER}, + EXPENSE_REPROTS_ID = #{expenseReprotsId,jdbcType=INTEGER} + where ID = #{id,jdbcType=BIGINT} + + + + insert into exp_comb_report_sub (COMB_REPORT_ID, EXPENSE_REPROTS_ID) + values + + (#{record.combReportId,jdbcType=INTEGER}, #{record.expenseReprotsId,jdbcType=INTEGER}) + + + + diff --git a/src/main/resources/mapper/FileMapper.xml b/src/main/resources/mapper/FileMapper.xml new file mode 100644 index 0000000..9171f25 --- /dev/null +++ b/src/main/resources/mapper/FileMapper.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + ID, `PATH`, URI, `TYPE`, PID, `DESCRIPTION`,UPLOAD_USER,UPLOAD_TIME + + + + + + + + delete + from file + where ID = #{id,jdbcType=INTEGER} + + + insert into file (`PATH`, URI, `TYPE`, + PID, DESCRIPTION, UPLOAD_USER, UPLOAD_TIME) + values (#{path,jdbcType=VARCHAR}, #{uri,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, + #{pid,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{uploadUser,jdbcType=INTEGER}, + #{uploadTime,jdbcType=TIMESTAMP}) + + + update file + + + `PATH` = #{path,jdbcType=VARCHAR}, + + + URI = #{uri,jdbcType=VARCHAR}, + + + `TYPE` = #{type,jdbcType=VARCHAR}, + + + PID = #{pid,jdbcType=VARCHAR}, + + + `DESCRIPTION` = #{description,jdbcType=VARCHAR}, + + + `UPLOAD_USER` = #{uploadUser,jdbcType=INTEGER}, + + + UPLOAD_TIME = #{uploadTime,jdbcType=TIMESTAMP}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/FilesConfigMapper.xml b/src/main/resources/mapper/FilesConfigMapper.xml new file mode 100644 index 0000000..b8be6c7 --- /dev/null +++ b/src/main/resources/mapper/FilesConfigMapper.xml @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + ID,TYPE,TO_TYPE, + CUSTOM1,CUSTOM2,CUSTOM3, + CUSTOM4, EXT01, EXT02, EXT03, EXT04, EXT05, EXT06, EXT07, EXT08, EXT09, EXT10 + + + + + delete + from files_config + where ID = #{id,jdbcType=INTEGER} + + + insert into files_config + ( ID, TYPE, TO_TYPE + , CUSTOM1, CUSTOM2, CUSTOM3 + , CUSTOM4) + values ( #{id,jdbcType=INTEGER}, #{type,jdbcType=VARCHAR}, #{toType,jdbcType=INTEGER} + , #{custom1,jdbcType=VARCHAR}, #{custom2,jdbcType=VARCHAR}, #{custom3,jdbcType=VARCHAR} + , #{custom4,jdbcType=VARCHAR}) + + + update files_config + + + TYPE = #{type,jdbcType=VARCHAR}, + + + TO_TYPE = #{toType,jdbcType=INTEGER}, + + + CUSTOM1 = #{custom1,jdbcType=VARCHAR}, + + + CUSTOM2 = #{custom2,jdbcType=VARCHAR}, + + + CUSTOM3 = #{custom3,jdbcType=VARCHAR}, + + + CUSTOM4 = #{custom4,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update files_config + set TYPE = #{type,jdbcType=VARCHAR}, + TO_TYPE = #{toType,jdbcType=INTEGER}, + CUSTOM1 = #{custom1,jdbcType=VARCHAR}, + CUSTOM2 = #{custom2,jdbcType=VARCHAR}, + CUSTOM3 = #{custom3,jdbcType=VARCHAR}, + CUSTOM4 = #{custom4,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/mapper/FilesMapper.xml b/src/main/resources/mapper/FilesMapper.xml new file mode 100644 index 0000000..0e4aecf --- /dev/null +++ b/src/main/resources/mapper/FilesMapper.xml @@ -0,0 +1,411 @@ + + + + + + + + + + + + + + + + + + + + + + + + ID, + FILE_NAME, + INVOICE_ID, + FILE_PATH,MQ_ID,TYPE,AUTO_INSERT,EFILES_ID, + STATUS,EXT01,EXT02,EXT03,EXT04,EXT05 + + + + + + + + + delete + from files + where ID = #{id} + + + delete f,fo,im + from files f + left join files_ocr fo on fo.FILES_ID = f.ID + left join invoice_item_mileage im on im.FILES_ID = f.ID + where FILE_NAME = #{fileName} + + + delete + from files + where FILE_NAME like concat(#{fileName,jdbcType=VARCHAR}, '%') + limit 1 + + + insert into files (ID, FILE_NAME, INVOICE_ID, + FILE_PATH, MQ_ID,TYPE,AUTO_INSERT,EFILES_ID, + STATUS,EXT01,EXT02,EXT03,EXT04,EXT05) + values (#{id}, #{fileName}, #{invoiceId}, + #{filePath}, #{mqId}, #{type}, #{autoInsert}, #{efilesId}, + #{status}, #{ext01}, #{ext02}, #{ext03}, #{ext04}, #{ext05}) + + + insert into files + + + #{id}, + + + #{fileName}, + + + #{invoiceId}, + + + #{filePath}, + + + #{mqId}, + + + #{type}, + + + #{autoInsert}, + + + #{efilesId}, + + + #{status}, + + #{ext01}, + #{ext02}, + #{ext03}, + #{ext04}, + #{ext05}, + + + + ID, + + + FILE_NAME, + + + INVOICE_ID, + + + FILE_PATH, + + + MQ_ID, + + + TYPE, + + + AUTO_INSERT, + + + EFILES_ID, + + + STATUS, + + EXT01, + EXT02, + EXT03, + EXT04, + EXT05, + + + + update files + + + FILE_NAME = #{fileName}, + + + INVOICE_ID = #{invoiceId}, + + + FILE_PATH = #{filePath}, + + + MQ_ID = #{mqId,jdbcType=VARCHAR}, + + + TYPE = #{type,jdbcType=VARCHAR}, + + + AUTO_INSERT = #{autoInsert,jdbcType=VARCHAR}, + + + EFILES_ID = #{efilesId}, + + + STATUS = #{status}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id} + + + update files + set FILE_NAME = #{fileName}, + INVOICE_ID = #{invoiceId}, + FILE_PATH = #{filePath}, + MQ_ID = #{mqId,jdbcType=VARCHAR}, + TYPE = #{type,jdbcType=VARCHAR}, + AUTO_INSERT = #{autoInsert,jdbcType=VARCHAR}, + EFILES_ID = #{efilesId,jdbcType=BIGINT}, + STATUS = #{status,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id} + + + + + + + + + + + + + update files set EXT03 = 'Y' where FILE_NAME = #{fileName} + + + + + + update files set EXT03 = 'Y' where EFILES_ID = #{efilesId} and INVOICE_ID = #{invoiceId} + + + + + + + + + + + + + + update files + set STATUS = '1' + where STATUS = '0' and INVOICE_ID = #{invoiceId} and (type = '图片' or type = '电子附件') + + + + + + + + + + update files + set EXT03 = '' + where EXT03 = 'Y' and INVOICE_ID = #{invoiceId} + + + + + + + diff --git a/src/main/resources/mapper/FilesOcrMapper.xml b/src/main/resources/mapper/FilesOcrMapper.xml new file mode 100644 index 0000000..ac434f9 --- /dev/null +++ b/src/main/resources/mapper/FilesOcrMapper.xml @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + ID,TYPE,INV_DATE, + AMOUNT,VERIFIED_DATA,INVOICE_ID, + FILES_ID, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + + + + + + + delete + from files_ocr + where ID = #{id,jdbcType=BIGINT} + + + insert into files_ocr + ( ID, TYPE, INV_DATE + , AMOUNT, VERIFIED_DATA, INVOICE_ID + , FILES_ID, EXT01, EXT02, EXT03, EXT04, EXT05) + values ( #{id,jdbcType=BIGINT}, #{type,jdbcType=VARCHAR}, #{invDate,jdbcType=VARCHAR} + , #{amount,jdbcType=VARCHAR}, #{verifiedData,jdbcType=VARCHAR}, #{invoiceId,jdbcType=VARCHAR} + , #{filesId,jdbcType=INTEGER}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}) + + + update files_ocr + + + TYPE = #{type,jdbcType=VARCHAR}, + + + INV_DATE = #{invDate,jdbcType=VARCHAR}, + + + AMOUNT = #{amount,jdbcType=VARCHAR}, + + + VERIFIED_DATA = #{verifiedData,jdbcType=VARCHAR}, + + + INVOICE_ID = #{invoiceId,jdbcType=VARCHAR}, + + + FILES_ID = #{filesId,jdbcType=INTEGER}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + + delete + from files_ocr + where FILES_ID = #{filesId} + + + + + diff --git a/src/main/resources/mapper/HelpMapper.xml b/src/main/resources/mapper/HelpMapper.xml new file mode 100644 index 0000000..306e563 --- /dev/null +++ b/src/main/resources/mapper/HelpMapper.xml @@ -0,0 +1,171 @@ + + + + + + + + + + + + + + + + + + ID, TITLE, REASON_ONE, SOLUTION_ONE, REASON_TWO, SOLUTION_TWO, REASON_THREE, SOLUTION_THREE, + REASON_FOUR, SOLUTION_FOUR, IS_DEL + + + + delete + from help + where ID = #{id,jdbcType=INTEGER} + + + insert into help (ID, TITLE, REASON_ONE, + SOLUTION_ONE, REASON_TWO, SOLUTION_TWO, + REASON_THREE, SOLUTION_THREE, REASON_FOUR, + SOLUTION_FOUR, IS_DEL) + values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{reasonOne,jdbcType=VARCHAR}, + #{solutionOne,jdbcType=VARCHAR}, #{reasonTwo,jdbcType=VARCHAR}, #{solutionTwo,jdbcType=VARCHAR}, + #{reasonThree,jdbcType=VARCHAR}, #{solutionThree,jdbcType=VARCHAR}, #{reasonFour,jdbcType=VARCHAR}, + #{solutionFour,jdbcType=VARCHAR}, #{isDel,jdbcType=VARCHAR}) + + + insert into help + + + ID, + + + TITLE, + + + REASON_ONE, + + + SOLUTION_ONE, + + + REASON_TWO, + + + SOLUTION_TWO, + + + REASON_THREE, + + + SOLUTION_THREE, + + + REASON_FOUR, + + + SOLUTION_FOUR, + + + IS_DEL, + + + + + #{id,jdbcType=INTEGER}, + + + #{title,jdbcType=VARCHAR}, + + + #{reasonOne,jdbcType=VARCHAR}, + + + #{solutionOne,jdbcType=VARCHAR}, + + + #{reasonTwo,jdbcType=VARCHAR}, + + + #{solutionTwo,jdbcType=VARCHAR}, + + + #{reasonThree,jdbcType=VARCHAR}, + + + #{solutionThree,jdbcType=VARCHAR}, + + + #{reasonFour,jdbcType=VARCHAR}, + + + #{solutionFour,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + + + update help + + + TITLE = #{title,jdbcType=VARCHAR}, + + + REASON_ONE = #{reasonOne,jdbcType=VARCHAR}, + + + SOLUTION_ONE = #{solutionOne,jdbcType=VARCHAR}, + + + REASON_TWO = #{reasonTwo,jdbcType=VARCHAR}, + + + SOLUTION_TWO = #{solutionTwo,jdbcType=VARCHAR}, + + + REASON_THREE = #{reasonThree,jdbcType=VARCHAR}, + + + SOLUTION_THREE = #{solutionThree,jdbcType=VARCHAR}, + + + REASON_FOUR = #{reasonFour,jdbcType=VARCHAR}, + + + SOLUTION_FOUR = #{solutionFour,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update help + set TITLE = #{title,jdbcType=VARCHAR}, + REASON_ONE = #{reasonOne,jdbcType=VARCHAR}, + SOLUTION_ONE = #{solutionOne,jdbcType=VARCHAR}, + REASON_TWO = #{reasonTwo,jdbcType=VARCHAR}, + SOLUTION_TWO = #{solutionTwo,jdbcType=VARCHAR}, + REASON_THREE = #{reasonThree,jdbcType=VARCHAR}, + SOLUTION_THREE = #{solutionThree,jdbcType=VARCHAR}, + REASON_FOUR = #{reasonFour,jdbcType=VARCHAR}, + SOLUTION_FOUR = #{solutionFour,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + diff --git a/src/main/resources/mapper/InternationalizationMapper.xml b/src/main/resources/mapper/InternationalizationMapper.xml new file mode 100644 index 0000000..9f754df --- /dev/null +++ b/src/main/resources/mapper/InternationalizationMapper.xml @@ -0,0 +1,101 @@ + + + + + + + + + + + + ID, COMMON, CH, EN, IS_DEL + + + + delete + from internationalization + where ID = #{id,jdbcType=INTEGER} + + + insert into internationalization (ID, COMMON, CH, + EN, IS_DEL) + values (#{id,jdbcType=INTEGER}, #{common,jdbcType=VARCHAR}, #{ch,jdbcType=VARCHAR}, + #{en,jdbcType=VARCHAR}, #{isDel,jdbcType=VARCHAR}) + + + insert into internationalization + + + ID, + + + COMMON, + + + CH, + + + EN, + + + IS_DEL, + + + + + #{id,jdbcType=INTEGER}, + + + #{common,jdbcType=VARCHAR}, + + + #{ch,jdbcType=VARCHAR}, + + + #{en,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + + + update internationalization + + + COMMON = #{common,jdbcType=VARCHAR}, + + + CH = #{ch,jdbcType=VARCHAR}, + + + EN = #{en,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update internationalization + set COMMON = #{common,jdbcType=VARCHAR}, + CH = #{ch,jdbcType=VARCHAR}, + EN = #{en,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + diff --git a/src/main/resources/mapper/JsadapterMapper.xml b/src/main/resources/mapper/JsadapterMapper.xml new file mode 100644 index 0000000..ba49431 --- /dev/null +++ b/src/main/resources/mapper/JsadapterMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + ID, JS_FUNCTION, `DESC` + + + + + delete + from js_adapter + where ID = #{id} + + + insert into js_adapter ( JS_FUNCTION, `DESC`) values ( #{jsFunction}, #{desc}) + + + update js_adapter + + + JS_FUNCTION = #{jsFunction}, + + + `DESC` = #{desc}, + + + where ID = #{id} + + + + + + + diff --git a/src/main/resources/mapper/MaterialMapper.xml b/src/main/resources/mapper/MaterialMapper.xml new file mode 100644 index 0000000..2e62530 --- /dev/null +++ b/src/main/resources/mapper/MaterialMapper.xml @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + ID, CODE, MATERIAL, DESCRIPTION, `TYPE`, `STATUS`, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + delete from material + where ID = #{id,jdbcType=BIGINT} + + + insert into material (CODE, MATERIAL, DESCRIPTION, + `TYPE`, `STATUS`, EXT01, + EXT02, EXT03, EXT04, + EXT05) + values (#{code,jdbcType=VARCHAR}, #{material,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}) + + + insert into material + + + CODE, + + + MATERIAL, + + + DESCRIPTION, + + + `TYPE`, + + + `STATUS`, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{code,jdbcType=VARCHAR}, + + + #{material,jdbcType=VARCHAR}, + + + #{description,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{status,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update material + + + CODE = #{code,jdbcType=VARCHAR}, + + + MATERIAL = #{material,jdbcType=VARCHAR}, + + + DESCRIPTION = #{description,jdbcType=VARCHAR}, + + + `TYPE` = #{type,jdbcType=VARCHAR}, + + + `STATUS` = #{status,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + update material + set CODE = #{code,jdbcType=VARCHAR}, + MATERIAL = #{material,jdbcType=VARCHAR}, + DESCRIPTION = #{description,jdbcType=VARCHAR}, + `TYPE` = #{type,jdbcType=VARCHAR}, + `STATUS` = #{status,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=BIGINT} + + + + + + + diff --git a/src/main/resources/mapper/PaymentTypeMapper.xml b/src/main/resources/mapper/PaymentTypeMapper.xml new file mode 100644 index 0000000..16e2454 --- /dev/null +++ b/src/main/resources/mapper/PaymentTypeMapper.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + ID, CODE, `NAME`, REMARK, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + delete from payment_type + where ID = #{id,jdbcType=BIGINT} + + + insert into payment_type (CODE, `NAME`, REMARK, + EXT01, EXT02, EXT03, + EXT04, EXT05) + values (#{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}, + #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, + #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}) + + + insert into payment_type + + + CODE, + + + `NAME`, + + + REMARK, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{code,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{remark,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update payment_type + + + CODE = #{code,jdbcType=VARCHAR}, + + + `NAME` = #{name,jdbcType=VARCHAR}, + + + REMARK = #{remark,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + update payment_type + set CODE = #{code,jdbcType=VARCHAR}, + `NAME` = #{name,jdbcType=VARCHAR}, + REMARK = #{remark,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=BIGINT} + + + + + diff --git a/src/main/resources/mapper/PostBoxMapper.xml b/src/main/resources/mapper/PostBoxMapper.xml new file mode 100644 index 0000000..50bab26 --- /dev/null +++ b/src/main/resources/mapper/PostBoxMapper.xml @@ -0,0 +1,834 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID + , SUBJECT, `FROM`, TICKET_TYPE, BUYER, INVOICE_MONEY, INVOICE_NUM, IDENTIFY_RESULT, + INVOICE_DATE, RECEIVE_DATE, FILE_PATH, USER_ID, `REPEAT`, SUBMIT, DEL, `TYPE`, ORIGINAL_PATH + , CREATE_TIME, + INVOICE_TYPE, CONSUME_TYPE, CURRENCY, CITY, SUPPLIER, INVOICE_CODE, GET_ON_TIME, + DEBUS_TIME, DESCR, IMG_PATH, CLIENT, CHECK_CODE, TAX, DATA_JSON, PRE_TAX, TAX_RATE, NEED_VALID, + VALID_STATUS, VALID_COUNT, VALID_DAY_COUNT, LOGIN_ID, EXT01, EXT02, EXT03, EXT04, + EXT05,OTHER_FIELDS,TRADE_DATE,INVOICE_STATUS, RECEIPT_ID, IS_SEND, EXT06, EXT07, EXT08, EXT09, + EXT10 + + + + + + + + + + + + + + + update post_box + set DEL = 1 + where ID = #{id,jdbcType=INTEGER} + + + insert into post_box + + + SUBJECT, + + + `FROM`, + + + TICKET_TYPE, + + + BUYER, + + + INVOICE_MONEY, + + + INVOICE_NUM, + + + IDENTIFY_RESULT, + + + INVOICE_DATE, + + + RECEIVE_DATE, + + + FILE_PATH, + + + USER_ID, + + + `REPEAT`, + + + SUBMIT, + + + DEL, + + + `TYPE`, + + + ORIGINAL_PATH, + + + CREATE_TIME, + + + INVOICE_TYPE, + + + CONSUME_TYPE, + + + CURRENCY, + + + CITY, + + + SUPPLIER, + + + INVOICE_CODE, + + + GET_ON_TIME, + + + DEBUS_TIME, + + + DESCR, + + + IMG_PATH, + + + CLIENT, + + + CHECK_CODE, + + + TAX, + + + DATA_JSON, + + + PRE_TAX, + + + TAX_RATE, + + + NEED_VALID, + + + VALID_STATUS, + + + VALID_COUNT, + + + VALID_DAY_COUNT, + + + LOGIN_ID, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + OTHER_FIELDS, + + + TRADE_DATE, + + + INVOICE_STATUS, + + + RECEIPT_ID, + + + IS_SEND, + + + EXT06, + + + EXT07, + + + EXT08, + + + EXT09, + + + EXT10, + + + + + #{subject,jdbcType=VARCHAR}, + + + #{from,jdbcType=VARCHAR}, + + + #{ticketType,jdbcType=VARCHAR}, + + + #{buyer,jdbcType=VARCHAR}, + + + #{invoiceMoney,jdbcType=VARCHAR}, + + + #{invoiceNum,jdbcType=VARCHAR}, + + + #{identifyResult,jdbcType=VARCHAR}, + + + #{invoiceDate,jdbcType=VARCHAR}, + + + #{receiveDate,jdbcType=VARCHAR}, + + + #{filePath,jdbcType=VARCHAR}, + + + #{userId,jdbcType=INTEGER}, + + + #{repeat,jdbcType=BOOLEAN}, + + + #{submit,jdbcType=BOOLEAN}, + + + #{del,jdbcType=BOOLEAN}, + + + #{type,jdbcType=INTEGER}, + + + #{originalPath,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{invoiceType,jdbcType=VARCHAR}, + + + #{consumeType,jdbcType=VARCHAR}, + + + #{currency,jdbcType=VARCHAR}, + + + #{city,jdbcType=VARCHAR}, + + + #{supplier,jdbcType=VARCHAR}, + + + #{invoiceCode,jdbcType=VARCHAR}, + + + #{getOnTime,jdbcType=VARCHAR}, + + + #{debusTime,jdbcType=VARCHAR}, + + + #{descr,jdbcType=VARCHAR}, + + + #{imgPath,jdbcType=VARCHAR}, + + + #{client,jdbcType=INTEGER}, + + + #{checkCode,jdbcType=VARCHAR}, + + + #{tax,jdbcType=VARCHAR}, + + + #{dataJson,jdbcType=LONGVARCHAR}, + + + #{preTax,jdbcType=VARCHAR}, + + + #{taxRate,jdbcType=VARCHAR}, + + + #{needValid,jdbcType=BIT}, + + + #{validStatus,jdbcType=BIT}, + + + #{validCount,jdbcType=TINYINT}, + + + #{validDayCount,jdbcType=TINYINT}, + + + #{loginId,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{otherFields,jdbcType=VARCHAR}, + + + #{tradeDate,jdbcType=VARCHAR}, + + + #{invoiceStatus,jdbcType=VARCHAR}, + + + #{receiptId,jdbcType=VARCHAR}, + + + #{isSend,jdbcType=VARCHAR}, + + + #{ext06,jdbcType=VARCHAR}, + + + #{ext07,jdbcType=VARCHAR}, + + + #{ext08,jdbcType=VARCHAR}, + + + #{ext09,jdbcType=VARCHAR}, + + + #{ext10,jdbcType=VARCHAR}, + + + + + update post_box + + + SUBJECT = #{subject,jdbcType=VARCHAR}, + + + `FROM` = #{from,jdbcType=VARCHAR}, + + + TICKET_TYPE = #{ticketType,jdbcType=VARCHAR}, + + + BUYER = #{buyer,jdbcType=VARCHAR}, + + + INVOICE_MONEY = #{invoiceMoney,jdbcType=VARCHAR}, + + + INVOICE_NUM = #{invoiceNum,jdbcType=VARCHAR}, + + + IDENTIFY_RESULT = #{identifyResult,jdbcType=VARCHAR}, + + + INVOICE_DATE = #{invoiceDate,jdbcType=VARCHAR}, + + + RECEIVE_DATE = #{receiveDate,jdbcType=VARCHAR}, + + + FILE_PATH = #{filePath,jdbcType=VARCHAR}, + + + USER_ID = #{userId,jdbcType=INTEGER}, + + + `REPEAT` = #{repeat,jdbcType=BOOLEAN}, + + + SUBMIT = #{submit,jdbcType=BOOLEAN}, + + + DEL = #{del,jdbcType=BOOLEAN}, + + + `TYPE` = #{type,jdbcType=INTEGER}, + + + ORIGINAL_PATH = #{originalPath,jdbcType=VARCHAR}, + + + INVOICE_TYPE = #{invoiceType,jdbcType=VARCHAR}, + + + CONSUME_TYPE = #{consumeType,jdbcType=VARCHAR}, + + + CURRENCY = #{currency,jdbcType=VARCHAR}, + + + CITY = #{city,jdbcType=VARCHAR}, + + + SUPPLIER = #{supplier,jdbcType=VARCHAR}, + + + INVOICE_CODE = #{invoiceCode,jdbcType=VARCHAR}, + + + GET_ON_TIME = #{getOnTime,jdbcType=VARCHAR}, + + + DEBUS_TIME = #{debusTime,jdbcType=VARCHAR}, + + + DESCR = #{descr,jdbcType=VARCHAR}, + + + IMG_PATH = #{imgPath,jdbcType=VARCHAR}, + + + CLIENT = #{client,jdbcType=INTEGER}, + + + CHECK_CODE = #{checkCode,jdbcType=VARCHAR}, + + + TAX = #{tax,jdbcType=VARCHAR}, + + + DATA_JSON = #{dataJson,jdbcType=LONGVARCHAR}, + + + PRE_TAX = #{preTax,jdbcType=VARCHAR}, + + + TAX_RATE = #{taxRate,jdbcType=VARCHAR}, + + + NEED_VALID = #{needValid,jdbcType=BIT}, + + + VALID_STATUS = #{validStatus,jdbcType=BIT}, + + + VALID_COUNT = #{validCount,jdbcType=TINYINT}, + + + VALID_DAY_COUNT = #{validDayCount,jdbcType=TINYINT}, + + + LOGIN_ID = #{loginId,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + OTHER_FIELDS = #{otherFields,jdbcType=VARCHAR}, + + + TRADE_DATE = #{tradeDate,jdbcType=VARCHAR}, + + + INVOICE_STATUS = #{invoiceStatus,jdbcType=VARCHAR}, + + + RECEIPT_ID = #{receiptId,jdbcType=VARCHAR}, + + + IS_SEND = #{isSend,jdbcType=VARCHAR}, + + + EXT06 = #{ext06,jdbcType=VARCHAR}, + + + EXT07 = #{ext07,jdbcType=VARCHAR}, + + + EXT08 = #{ext08,jdbcType=VARCHAR}, + + + EXT09 = #{ext09,jdbcType=VARCHAR}, + + + EXT10 = #{ext10,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + + + + update + post_box + set VALID_DAY_COUNT = 0 + where VALID_STATUS = 0 + and DEL = '0' + and VALID_DAY_COUNT != 0; + update post_box set EXT02 = '',DESCR = '' where EXT02 like '%该张发票超出当天查验次数%' and VALID_STATUS = 0 and DEL = '0'; + update post_box set EXT02 = '',DESCR = '' + where EXT02 like '%查无此票%' and VALID_STATUS = 0 and DEL = '0' + and find_in_set('电子', INVOICE_TYPE) + and TO_DAYS(NOW()) - TO_DAYS(INVOICE_DATE) <= 1; + + + + update post_box set RECEIPT_ID = #{receiptId} where ID = #{id} + + + + update post_box set IS_SEND = #{isSend} where ID = #{id} + + + + update post_box set IS_SEND = #{isSend}, RECEIPT_ID = #{receiptId} where ID = #{id} + + + + + + update post_box a,t_10_report_line b + set a.EXT06 = b.report_entry_id,a.EXT07 = b.report_id + where a.RECEIPT_ID = b.attributer7 + and a.DEL = '0' and a.IS_SEND = '2' + and (a.EXT06 is null or a.EXT06 = '') and (a.EXT07 is null or a.EXT07 = '') + and SUBSTRING(a.CREATE_TIME,1,10) >= #{updateStr} + + + + + + update post_box + set EXT04 = '1' + where ID = #{id} + + + + + diff --git a/src/main/resources/mapper/PreferencesMapper.xml b/src/main/resources/mapper/PreferencesMapper.xml new file mode 100644 index 0000000..6db4997 --- /dev/null +++ b/src/main/resources/mapper/PreferencesMapper.xml @@ -0,0 +1,128 @@ + + + + + + + + + + + ID, INVOICE_TYPE, CONSUMPTION_TYPE, EXPENSE_TYPES + + + + + + + delete + from preferences + where ID = #{id,jdbcType=INTEGER} + + + insert into preferences (INVOICE_TYPE, CONSUMPTION_TYPE, EXPENSE_TYPES) + values (#{invoiceType,jdbcType=INTEGER}, #{consumptionType,jdbcType=VARCHAR}, #{expenseTypes,jdbcType=VARCHAR}) + + + update preferences + + + INVOICE_TYPE = #{invoiceType,jdbcType=INTEGER}, + + + CONSUMPTION_TYPE = #{consumptionType,jdbcType=VARCHAR}, + + + EXPENSE_TYPES = #{expenseTypes,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update preferences + set INVOICE_TYPE = #{invoiceType,jdbcType=INTEGER}, + CONSUMPTION_TYPE = #{consumptionType,jdbcType=VARCHAR}, + EXPENSE_TYPES = #{expenseTypes,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + diff --git a/src/main/resources/mapper/RuleConfigMapper.xml b/src/main/resources/mapper/RuleConfigMapper.xml new file mode 100644 index 0000000..054fa11 --- /dev/null +++ b/src/main/resources/mapper/RuleConfigMapper.xml @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, `RULE`, TICKET_TYPE, `LEVEL`, PARAMS, CLIENT_ID, TYPE + + + + + + + + + delete + from rule_config + where ID = #{id,jdbcType=INTEGER} + + + insert into rule_config (`RULE`, TICKET_TYPE, `LEVEL`, + PARAMS, CLIENT_ID, TYPE) + values (#{rule,jdbcType=INTEGER}, #{ticketType,jdbcType=INTEGER}, #{level,jdbcType=SMALLINT}, + #{params,jdbcType=VARCHAR}, #{clientId,jdbcType=INTEGER}, #{type,jdbcType=INTEGER}) + + + update rule_config + + + `RULE` = #{rule,jdbcType=INTEGER}, + + + TICKET_TYPE = #{ticketType,jdbcType=INTEGER}, + + + `LEVEL` = #{level,jdbcType=SMALLINT}, + + + PARAMS = #{params,jdbcType=VARCHAR}, + + + CLIENT_ID = #{clientId,jdbcType=INTEGER}, + + + TYPE = #{type,jdbcType=INTEGER} + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/RuleMapper.xml b/src/main/resources/mapper/RuleMapper.xml new file mode 100644 index 0000000..1f1f94c --- /dev/null +++ b/src/main/resources/mapper/RuleMapper.xml @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + ID, `NAME`, MESSAGE_EN, MESSAGE_CN, CLIENT_ID, `TYPE`, REMARK, SORT, EXT01, EXT02, + EXT03, EXT04, EXT05 + + + + + delete + from rule + where ID = #{id,jdbcType=INTEGER} + + + insert into rule (`NAME`, MESSAGE_EN, MESSAGE_CN, + CLIENT_ID, `TYPE`, REMARK, + SORT, EXT01, EXT02, + EXT03, EXT04, EXT05) + values (#{name,jdbcType=VARCHAR}, #{messageEn,jdbcType=VARCHAR}, #{messageCn,jdbcType=VARCHAR}, + #{clientId,jdbcType=INTEGER}, #{type,jdbcType=SMALLINT}, #{remark,jdbcType=VARCHAR}, + #{sort,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, + #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}) + + + insert into rule + + + `NAME`, + + + MESSAGE_EN, + + + MESSAGE_CN, + + + CLIENT_ID, + + + `TYPE`, + + + REMARK, + + + SORT, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{name,jdbcType=VARCHAR}, + + + #{messageEn,jdbcType=VARCHAR}, + + + #{messageCn,jdbcType=VARCHAR}, + + + #{clientId,jdbcType=INTEGER}, + + + #{type,jdbcType=SMALLINT}, + + + #{remark,jdbcType=VARCHAR}, + + + #{sort,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update rule + + + `NAME` = #{name,jdbcType=VARCHAR}, + + + MESSAGE_EN = #{messageEn,jdbcType=VARCHAR}, + + + MESSAGE_CN = #{messageCn,jdbcType=VARCHAR}, + + + CLIENT_ID = #{clientId,jdbcType=INTEGER}, + + + `TYPE` = #{type,jdbcType=SMALLINT}, + + + REMARK = #{remark,jdbcType=VARCHAR}, + + + SORT = #{sort,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update rule + set `NAME` = #{name,jdbcType=VARCHAR}, + MESSAGE_EN = #{messageEn,jdbcType=VARCHAR}, + MESSAGE_CN = #{messageCn,jdbcType=VARCHAR}, + CLIENT_ID = #{clientId,jdbcType=INTEGER}, + `TYPE` = #{type,jdbcType=SMALLINT}, + REMARK = #{remark,jdbcType=VARCHAR}, + SORT = #{sort,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + + diff --git a/src/main/resources/mapper/RuleTypeMapper.xml b/src/main/resources/mapper/RuleTypeMapper.xml new file mode 100644 index 0000000..d415e68 --- /dev/null +++ b/src/main/resources/mapper/RuleTypeMapper.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + ID, CODE, `NAME`, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + delete from rule_type + where ID = #{id,jdbcType=BIGINT} + + + insert into rule_type (CODE, `NAME`, EXT01, + EXT02, EXT03, EXT04, + EXT05) + values (#{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}) + + + insert into rule_type + + + CODE, + + + `NAME`, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{code,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update rule_type + + + CODE = #{code,jdbcType=VARCHAR}, + + + `NAME` = #{name,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + update rule_type + set CODE = #{code,jdbcType=VARCHAR}, + `NAME` = #{name,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=BIGINT} + + + + + + + diff --git a/src/main/resources/mapper/ScannerCenterFilesMapper.xml b/src/main/resources/mapper/ScannerCenterFilesMapper.xml new file mode 100644 index 0000000..81b1280 --- /dev/null +++ b/src/main/resources/mapper/ScannerCenterFilesMapper.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + id, + upload_file_path, + is_finished, + page_size, + current_page, + create_date, + update_date, + report_id, + ext01, + ext02, + ext03, + ext04, + ext05, + current_deal_file + + + insert into scanner_center_files + ( + upload_file_path, + is_finished, + page_size, + current_page, + create_date, + update_date, + report_id, + ext01, + ext02, + ext03, + ext04, + ext05, + current_deal_file) + values + ( + #{uploadFilePath}, + #{isFinished}, + #{pageSize}, + #{currentPage}, + #{createDate}, + #{updateDate}, + #{reportId}, + #{ext01}, + #{ext02}, + #{ext03}, + #{ext04}, + #{ext05}, + #{currentDealFile} + ) + + + + update + scanner_center_files + set upload_file_path = #{uploadFilePath}, + is_finished = #{isFinished}, + page_size = #{pageSize}, + current_page = #{currentPage}, + create_date = #{createDate,jdbcType=TIMESTAMP}, + report_id = #{reportId}, + ext01 = #{ext01}, + ext02 = #{ext02}, + ext03 = #{ext03}, + ext04 = #{ext04}, + ext05 = #{ext05}, + current_deal_file = #{currentDealFile} + where id = #{id} + + + update scanner_center_files + set is_finished = "1" + where report_id = #{reportId} + + + + diff --git a/src/main/resources/mapper/ScannerLogsMapper.xml b/src/main/resources/mapper/ScannerLogsMapper.xml new file mode 100644 index 0000000..70c6a6e --- /dev/null +++ b/src/main/resources/mapper/ScannerLogsMapper.xml @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID,COMPANY_ID,COST_TYPE, + FILE_NAME,INVOICE_UP_NUM,ERROR_NUM, + SEND_TIME, HASH_KEY, MACHINE_CODE,INVOICE_ID, + EXT01,EXT02,EXT03,EXT04,EXT05,EXT06,EXT07,EXT08,EXT09,EXT10 + + + + + + + + + + + + + + + delete + from scanner_logs + where ID = #{id,jdbcType=BIGINT} + + + insert into scanner_logs + ( ID, COMPANY_ID, COST_TYPE + , FILE_NAME, INVOICE_UP_NUM, ERROR_NUM + , SEND_TIME, HASH_KEY, MACHINE_CODE,INVOICE_ID, + EXT01,EXT02,EXT03,EXT04,EXT05,EXT06,EXT07,EXT08,EXT09,EXT10) + values ( #{id,jdbcType=BIGINT}, #{companyId,jdbcType=VARCHAR}, #{costType,jdbcType=VARCHAR} + , #{fileName,jdbcType=VARCHAR}, #{invoiceUpNum,jdbcType=INTEGER}, #{errorNum,jdbcType=INTEGER} + , #{sendTime,jdbcType=TIMESTAMP}, #{hashKey,jdbcType=VARCHAR}, #{machineCode,jdbcType=VARCHAR}, #{invoiceId,jdbcType=VARCHAR}, + #{ext01,jdbcType=VARCHAR},#{ext02,jdbcType=VARCHAR},#{ext03,jdbcType=VARCHAR},#{ext04,jdbcType=VARCHAR},#{ext05,jdbcType=VARCHAR}, + #{ext06,jdbcType=VARCHAR},#{ext07,jdbcType=VARCHAR},#{ext08,jdbcType=VARCHAR},#{ext09,jdbcType=VARCHAR},#{ext10,jdbcType=VARCHAR}) + + + update scanner_logs + + + COMPANY_ID = #{companyId,jdbcType=VARCHAR}, + + + COST_TYPE = #{costType,jdbcType=VARCHAR}, + + + FILE_NAME = #{fileName,jdbcType=VARCHAR}, + + + INVOICE_UP_NUM = #{invoiceUpNum,jdbcType=INTEGER}, + + + ERROR_NUM = #{errorNum,jdbcType=INTEGER}, + + + SEND_TIME = #{sendTime,jdbcType=TIMESTAMP}, + + + HASH_KEY = #{hashKey,jdbcType=VARCHAR}, + + + MACHINE_CODE = #{machineCode,jdbcType=VARCHAR}, + + + INVOICE_ID = #{invoiceId,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + EXT06 = #{ext06,jdbcType=VARCHAR}, + + + EXT07 = #{ext07,jdbcType=VARCHAR}, + + + EXT08 = #{ext08,jdbcType=VARCHAR}, + + + EXT09 = #{ext09,jdbcType=VARCHAR}, + + + EXT10 = #{ext10,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + diff --git a/src/main/resources/mapper/SupplierBlacklistMapper.xml b/src/main/resources/mapper/SupplierBlacklistMapper.xml new file mode 100644 index 0000000..171a668 --- /dev/null +++ b/src/main/resources/mapper/SupplierBlacklistMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + ID, `NAME`, CODE, TAX_ID, CLIENT + + + + + + + delete from supplier_blacklist + where ID = #{id,jdbcType=INTEGER} + + + + insert into supplier_blacklist (`NAME`, CODE, TAX_ID, + CLIENT) + values (#{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{taxId,jdbcType=VARCHAR}, + #{client,jdbcType=INTEGER}) + + + + update supplier_blacklist + + + `NAME` = #{name,jdbcType=VARCHAR}, + + + CODE = #{code,jdbcType=VARCHAR}, + + + TAX_ID = #{taxId,jdbcType=VARCHAR}, + + + CLIENT = #{client,jdbcType=INTEGER}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/SupplierDiffAllowMapper.xml b/src/main/resources/mapper/SupplierDiffAllowMapper.xml new file mode 100644 index 0000000..8f3684f --- /dev/null +++ b/src/main/resources/mapper/SupplierDiffAllowMapper.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + id,org_id,cor_type_id, + diff_allow + + + + + delete + from supplier_diff_allow + where id = #{id,jdbcType=INTEGER} + + + insert into supplier_diff_allow + ( id, org_id, cor_type_id + , diff_allow) + values ( #{id,jdbcType=INTEGER}, #{orgId,jdbcType=INTEGER}, #{corTypeId,jdbcType=INTEGER} + , #{diffAllow,jdbcType=BOOLEAN}) + + + update supplier_diff_allow + + + org_id = #{orgId,jdbcType=INTEGER}, + + + cor_type_id = #{corTypeId,jdbcType=INTEGER}, + + + diff_allow = #{diffAllow,jdbcType=BOOLEAN}, + + + where id = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/SupplierMapper.xml b/src/main/resources/mapper/SupplierMapper.xml index ac5b075..b940866 100644 --- a/src/main/resources/mapper/SupplierMapper.xml +++ b/src/main/resources/mapper/SupplierMapper.xml @@ -71,6 +71,7 @@ and CODE = #{code} + limit 1 + select + + from supplier_order_header + where BILL_ID = #{billId,jdbcType=VARCHAR} + + + delete from supplier_order_header + where BILL_ID = #{billId,jdbcType=VARCHAR} + + + insert into supplier_order_header (BILL_ID, BILL_NUMBER, BILL_NAME, BILL_NAME_REMARK, + INVOICE_TYPE, BUSINESS_TYPE, COMPANY_CODE, + COMPANY_NAME, ORG_CODE, ORG_NAME, + CURRENCY, PAY_AMOUNT, PAY_DATE, + APPLY_MAN, GS_NUM, OA_NUM, + SUPPLIER_CODE, SUPPLIER_NAME, BRANCH_BANK, + ACCOUNT_INFO, PAY_TYPE, NON_PURCHASE, + PURCHASE, CONTRACT, BRAND, + STAKEHOLDER, ALIPAY, ACTIVITY_START_TIME, + ACTIVITY_END_TIME, FREEZE_START_TIME, FREEZE_END_TIME, + IS_DIGITAL_MARKET, IS_INNER_PAY, IS_ABROAD_PAY, + APPROVAL_COMMENT, SUBMIT_DATE, IS_COLLECT, + IS_MATCH, `STATUS`, IS_DEL, + `OWNER`, CREATE_BY, CREATE_DATE, + UPDATE_BY, UPDATE_DATE, EXT01, + EXT02, EXT03, EXT04, + EXT05, EXT06, EXT07, + EXT08, EXT09, EXT10, + RECEIVED, INTERNAL, HAV_CONTRACT, HAV_INVOICE, + KOL_NAME, KOL_FULL_NAME, `UID`, + SUPPLIER_TYPE, IS_WHITE_LIST, WHITE_COMPANY, + OTHER_COMPANY + ) + values (#{billId,jdbcType=VARCHAR}, #{billNumber,jdbcType=VARCHAR}, #{billName,jdbcType=VARCHAR}, #{billNameRemark,jdbcType=VARCHAR}, + #{invoiceType,jdbcType=VARCHAR}, #{businessType,jdbcType=VARCHAR}, #{companyCode,jdbcType=VARCHAR}, + #{companyName,jdbcType=VARCHAR}, #{orgCode,jdbcType=VARCHAR}, #{orgName,jdbcType=VARCHAR}, + #{currency,jdbcType=VARCHAR}, #{payAmount,jdbcType=DECIMAL}, #{payDate,jdbcType=VARCHAR}, + #{applyMan,jdbcType=VARCHAR}, #{gsNum,jdbcType=VARCHAR}, #{oaNum,jdbcType=VARCHAR}, + #{supplierCode,jdbcType=VARCHAR}, #{supplierName,jdbcType=VARCHAR}, #{branchBank,jdbcType=VARCHAR}, + #{accountInfo,jdbcType=VARCHAR}, #{payType,jdbcType=VARCHAR}, #{nonPurchase,jdbcType=VARCHAR}, + #{purchase,jdbcType=VARCHAR}, #{contract,jdbcType=VARCHAR}, #{brand,jdbcType=VARCHAR}, + #{stakeholder,jdbcType=VARCHAR}, #{alipay,jdbcType=VARCHAR}, #{activityStartTime,jdbcType=VARCHAR}, + #{activityEndTime,jdbcType=VARCHAR}, #{freezeStartTime,jdbcType=VARCHAR}, #{freezeEndTime,jdbcType=VARCHAR}, + #{isDigitalMarket,jdbcType=VARCHAR}, #{isInnerPay,jdbcType=VARCHAR}, #{isAbroadPay,jdbcType=VARCHAR}, + #{approvalComment,jdbcType=VARCHAR}, #{submitDate,jdbcType=VARCHAR}, #{isCollect,jdbcType=VARCHAR}, + #{isMatch,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR}, #{isDel,jdbcType=VARCHAR}, + #{owner,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, + #{updateBy,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}, #{ext06,jdbcType=VARCHAR}, #{ext07,jdbcType=VARCHAR}, + #{ext08,jdbcType=VARCHAR}, #{ext09,jdbcType=VARCHAR}, #{ext10,jdbcType=VARCHAR}, + #{received,jdbcType=VARCHAR}, #{internal,jdbcType=VARCHAR}, #{havContract,jdbcType=VARCHAR}, #{havInvoice,jdbcType=VARCHAR}, + #{kolName,jdbcType=VARCHAR}, #{kolFullName,jdbcType=VARCHAR}, #{uid,jdbcType=VARCHAR}, + #{supplierType,jdbcType=VARCHAR}, #{isWhiteList,jdbcType=VARCHAR}, #{whiteCompany,jdbcType=VARCHAR}, + #{otherCompany,jdbcType=VARCHAR} + ) + + + insert into supplier_order_header + + + BILL_ID, + + + BILL_NUMBER, + + + BILL_NAME, + + + BILL_NAME_REMARK, + + + INVOICE_TYPE, + + + BUSINESS_TYPE, + + + COMPANY_CODE, + + + COMPANY_NAME, + + + ORG_CODE, + + + ORG_NAME, + + + CURRENCY, + + + PAY_AMOUNT, + + + PAY_DATE, + + + APPLY_MAN, + + + GS_NUM, + + + OA_NUM, + + + SUPPLIER_CODE, + + + SUPPLIER_NAME, + + + BRANCH_BANK, + + + ACCOUNT_INFO, + + + PAY_TYPE, + + + NON_PURCHASE, + + + PURCHASE, + + + CONTRACT, + + + BRAND, + + + STAKEHOLDER, + + + ALIPAY, + + + ACTIVITY_START_TIME, + + + ACTIVITY_END_TIME, + + + FREEZE_START_TIME, + + + FREEZE_END_TIME, + + + IS_DIGITAL_MARKET, + + + IS_INNER_PAY, + + + IS_ABROAD_PAY, + + + APPROVAL_COMMENT, + + + SUBMIT_DATE, + + + IS_COLLECT, + + + IS_MATCH, + + + `STATUS`, + + + IS_DEL, + + + `OWNER`, + + + CREATE_BY, + + + CREATE_DATE, + + + UPDATE_BY, + + + UPDATE_DATE, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + EXT06, + + + EXT07, + + + EXT08, + + + EXT09, + + + EXT10, + + + RECEIVED, + + + INTERNAL, + + + HAV_CONTRACT, + + + HAV_INVOICE, + + + KOL_NAME, + + + KOL_FULL_NAME, + + + `UID`, + + + SUPPLIER_TYPE, + + + IS_WHITE_LIST, + + + WHITE_COMPANY, + + + OTHER_COMPANY, + + + + + #{billId,jdbcType=VARCHAR}, + + + #{billNumber,jdbcType=VARCHAR}, + + + #{billName,jdbcType=VARCHAR}, + + + #{billNameRemark,jdbcType=VARCHAR}, + + + #{invoiceType,jdbcType=VARCHAR}, + + + #{businessType,jdbcType=VARCHAR}, + + + #{companyCode,jdbcType=VARCHAR}, + + + #{companyName,jdbcType=VARCHAR}, + + + #{orgCode,jdbcType=VARCHAR}, + + + #{orgName,jdbcType=VARCHAR}, + + + #{currency,jdbcType=VARCHAR}, + + + #{payAmount,jdbcType=DECIMAL}, + + + #{payDate,jdbcType=VARCHAR}, + + + #{applyMan,jdbcType=VARCHAR}, + + + #{gsNum,jdbcType=VARCHAR}, + + + #{oaNum,jdbcType=VARCHAR}, + + + #{supplierCode,jdbcType=VARCHAR}, + + + #{supplierName,jdbcType=VARCHAR}, + + + #{branchBank,jdbcType=VARCHAR}, + + + #{accountInfo,jdbcType=VARCHAR}, + + + #{payType,jdbcType=VARCHAR}, + + + #{nonPurchase,jdbcType=VARCHAR}, + + + #{purchase,jdbcType=VARCHAR}, + + + #{contract,jdbcType=VARCHAR}, + + + #{brand,jdbcType=VARCHAR}, + + + #{stakeholder,jdbcType=VARCHAR}, + + + #{alipay,jdbcType=VARCHAR}, + + + #{activityStartTime,jdbcType=VARCHAR}, + + + #{activityEndTime,jdbcType=VARCHAR}, + + + #{freezeStartTime,jdbcType=VARCHAR}, + + + #{freezeEndTime,jdbcType=VARCHAR}, + + + #{isDigitalMarket,jdbcType=VARCHAR}, + + + #{isInnerPay,jdbcType=VARCHAR}, + + + #{isAbroadPay,jdbcType=VARCHAR}, + + + #{approvalComment,jdbcType=VARCHAR}, + + + #{submitDate,jdbcType=VARCHAR}, + + + #{isCollect,jdbcType=VARCHAR}, + + + #{isMatch,jdbcType=VARCHAR}, + + + #{status,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + #{owner,jdbcType=VARCHAR}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{ext06,jdbcType=VARCHAR}, + + + #{ext07,jdbcType=VARCHAR}, + + + #{ext08,jdbcType=VARCHAR}, + + + #{ext09,jdbcType=VARCHAR}, + + + #{ext10,jdbcType=VARCHAR}, + + + #{received,jdbcType=VARCHAR}, + + + #{internal,jdbcType=VARCHAR}, + + + #{havContract,jdbcType=VARCHAR}, + + + #{havInvoice,jdbcType=VARCHAR}, + + + #{kolName,jdbcType=VARCHAR}, + + + #{kolFullName,jdbcType=VARCHAR}, + + + #{uid,jdbcType=VARCHAR}, + + + #{supplierType,jdbcType=VARCHAR}, + + + #{isWhiteList,jdbcType=VARCHAR}, + + + #{whiteCompany,jdbcType=VARCHAR}, + + + #{otherCompany,jdbcType=VARCHAR}, + + + + + update supplier_order_header + + + BILL_NUMBER = #{billNumber,jdbcType=VARCHAR}, + + + BILL_NAME = #{billName,jdbcType=VARCHAR}, + + + BILL_NAME_REMARK = #{billNameRemark,jdbcType=VARCHAR}, + + + INVOICE_TYPE = #{invoiceType,jdbcType=VARCHAR}, + + + BUSINESS_TYPE = #{businessType,jdbcType=VARCHAR}, + + + COMPANY_CODE = #{companyCode,jdbcType=VARCHAR}, + + + COMPANY_NAME = #{companyName,jdbcType=VARCHAR}, + + + ORG_CODE = #{orgCode,jdbcType=VARCHAR}, + + + ORG_NAME = #{orgName,jdbcType=VARCHAR}, + + + CURRENCY = #{currency,jdbcType=VARCHAR}, + + + PAY_AMOUNT = #{payAmount,jdbcType=DECIMAL}, + + + PAY_DATE = #{payDate,jdbcType=VARCHAR}, + + + APPLY_MAN = #{applyMan,jdbcType=VARCHAR}, + + + GS_NUM = #{gsNum,jdbcType=VARCHAR}, + + + OA_NUM = #{oaNum,jdbcType=VARCHAR}, + + + SUPPLIER_CODE = #{supplierCode,jdbcType=VARCHAR}, + + + SUPPLIER_NAME = #{supplierName,jdbcType=VARCHAR}, + + + BRANCH_BANK = #{branchBank,jdbcType=VARCHAR}, + + + ACCOUNT_INFO = #{accountInfo,jdbcType=VARCHAR}, + + + PAY_TYPE = #{payType,jdbcType=VARCHAR}, + + + NON_PURCHASE = #{nonPurchase,jdbcType=VARCHAR}, + + + PURCHASE = #{purchase,jdbcType=VARCHAR}, + + + CONTRACT = #{contract,jdbcType=VARCHAR}, + + + BRAND = #{brand,jdbcType=VARCHAR}, + + + STAKEHOLDER = #{stakeholder,jdbcType=VARCHAR}, + + + ALIPAY = #{alipay,jdbcType=VARCHAR}, + + + ACTIVITY_START_TIME = #{activityStartTime,jdbcType=VARCHAR}, + + + ACTIVITY_END_TIME = #{activityEndTime,jdbcType=VARCHAR}, + + + FREEZE_START_TIME = #{freezeStartTime,jdbcType=VARCHAR}, + + + FREEZE_END_TIME = #{freezeEndTime,jdbcType=VARCHAR}, + + + IS_DIGITAL_MARKET = #{isDigitalMarket,jdbcType=VARCHAR}, + + + IS_INNER_PAY = #{isInnerPay,jdbcType=VARCHAR}, + + + IS_ABROAD_PAY = #{isAbroadPay,jdbcType=VARCHAR}, + + + APPROVAL_COMMENT = #{approvalComment,jdbcType=VARCHAR}, + + + SUBMIT_DATE = #{submitDate,jdbcType=VARCHAR}, + + + IS_COLLECT = #{isCollect,jdbcType=VARCHAR}, + + + IS_MATCH = #{isMatch,jdbcType=VARCHAR}, + + + `STATUS` = #{status,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + `OWNER` = #{owner,jdbcType=VARCHAR}, + + + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + + + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + + + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + + + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + EXT06 = #{ext06,jdbcType=VARCHAR}, + + + EXT07 = #{ext07,jdbcType=VARCHAR}, + + + EXT08 = #{ext08,jdbcType=VARCHAR}, + + + EXT09 = #{ext09,jdbcType=VARCHAR}, + + + EXT10 = #{ext10,jdbcType=VARCHAR}, + + + RECEIVED = #{received,jdbcType=VARCHAR}, + + + INTERNAL = #{internal,jdbcType=VARCHAR}, + + + HAV_CONTRACT = #{havContract,jdbcType=VARCHAR}, + + + HAV_INVOICE = #{havInvoice,jdbcType=VARCHAR}, + + + KOL_NAME = #{kolName,jdbcType=VARCHAR}, + + + KOL_FULL_NAME = #{kolFullName,jdbcType=VARCHAR}, + + + `UID` = #{uid,jdbcType=VARCHAR}, + + + SUPPLIER_TYPE = #{supplierType,jdbcType=VARCHAR}, + + + IS_WHITE_LIST = #{isWhiteList,jdbcType=VARCHAR}, + + + WHITE_COMPANY = #{whiteCompany,jdbcType=VARCHAR}, + + + OTHER_COMPANY = #{otherCompany,jdbcType=VARCHAR}, + + + where BILL_ID = #{billId,jdbcType=VARCHAR} + + + update supplier_order_header + set BILL_NUMBER = #{billNumber,jdbcType=VARCHAR}, + BILL_NAME = #{billName,jdbcType=VARCHAR}, + BILL_NAME_REMARK = #{billNameRemark,jdbcType=VARCHAR}, + INVOICE_TYPE = #{invoiceType,jdbcType=VARCHAR}, + BUSINESS_TYPE = #{businessType,jdbcType=VARCHAR}, + COMPANY_CODE = #{companyCode,jdbcType=VARCHAR}, + COMPANY_NAME = #{companyName,jdbcType=VARCHAR}, + ORG_CODE = #{orgCode,jdbcType=VARCHAR}, + ORG_NAME = #{orgName,jdbcType=VARCHAR}, + CURRENCY = #{currency,jdbcType=VARCHAR}, + PAY_AMOUNT = #{payAmount,jdbcType=DECIMAL}, + PAY_DATE = #{payDate,jdbcType=VARCHAR}, + APPLY_MAN = #{applyMan,jdbcType=VARCHAR}, + GS_NUM = #{gsNum,jdbcType=VARCHAR}, + OA_NUM = #{oaNum,jdbcType=VARCHAR}, + SUPPLIER_CODE = #{supplierCode,jdbcType=VARCHAR}, + SUPPLIER_NAME = #{supplierName,jdbcType=VARCHAR}, + BRANCH_BANK = #{branchBank,jdbcType=VARCHAR}, + ACCOUNT_INFO = #{accountInfo,jdbcType=VARCHAR}, + PAY_TYPE = #{payType,jdbcType=VARCHAR}, + NON_PURCHASE = #{nonPurchase,jdbcType=VARCHAR}, + PURCHASE = #{purchase,jdbcType=VARCHAR}, + CONTRACT = #{contract,jdbcType=VARCHAR}, + BRAND = #{brand,jdbcType=VARCHAR}, + STAKEHOLDER = #{stakeholder,jdbcType=VARCHAR}, + ALIPAY = #{alipay,jdbcType=VARCHAR}, + ACTIVITY_START_TIME = #{activityStartTime,jdbcType=VARCHAR}, + ACTIVITY_END_TIME = #{activityEndTime,jdbcType=VARCHAR}, + FREEZE_START_TIME = #{freezeStartTime,jdbcType=VARCHAR}, + FREEZE_END_TIME = #{freezeEndTime,jdbcType=VARCHAR}, + IS_DIGITAL_MARKET = #{isDigitalMarket,jdbcType=VARCHAR}, + IS_INNER_PAY = #{isInnerPay,jdbcType=VARCHAR}, + IS_ABROAD_PAY = #{isAbroadPay,jdbcType=VARCHAR}, + APPROVAL_COMMENT = #{approvalComment,jdbcType=VARCHAR}, + SUBMIT_DATE = #{submitDate,jdbcType=VARCHAR}, + IS_COLLECT = #{isCollect,jdbcType=VARCHAR}, + IS_MATCH = #{isMatch,jdbcType=VARCHAR}, + `STATUS` = #{status,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=VARCHAR}, + `OWNER` = #{owner,jdbcType=VARCHAR}, + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR}, + EXT06 = #{ext06,jdbcType=VARCHAR}, + EXT07 = #{ext07,jdbcType=VARCHAR}, + EXT08 = #{ext08,jdbcType=VARCHAR}, + EXT09 = #{ext09,jdbcType=VARCHAR}, + EXT10 = #{ext10,jdbcType=VARCHAR}, + RECEIVED = #{received,jdbcType=VARCHAR}, + INTERNAL = #{internal,jdbcType=VARCHAR}, + HAV_CONTRACT = #{havContract,jdbcType=VARCHAR}, + HAV_INVOICE = #{havInvoice,jdbcType=VARCHAR}, + KOL_NAME = #{kolName,jdbcType=VARCHAR}, + KOL_FULL_NAME = #{kolFullName,jdbcType=VARCHAR}, + `UID` = #{uid,jdbcType=VARCHAR}, + SUPPLIER_TYPE = #{supplierType,jdbcType=VARCHAR}, + IS_WHITE_LIST = #{isWhiteList,jdbcType=VARCHAR}, + WHITE_COMPANY = #{whiteCompany,jdbcType=VARCHAR}, + OTHER_COMPANY = #{otherCompany,jdbcType=VARCHAR} + where BILL_ID = #{billId,jdbcType=VARCHAR} + + + + + + + + + + + + + + update supplier_order_header + + + STATUS = #{status}, + + + APPROVAL_COMMENT = #{approvalComment}, + + + OWNER = #{owner}, + + + EXT04 = #{ext04}, + + + where BILL_NUMBER = #{billNumber} + + + + update supplier_order_header + set EXT02 = #{ext02} + where BILL_NUMBER = #{billNumber} + + + diff --git a/src/main/resources/mapper/SupplierOrderItemMatchingMapper.xml b/src/main/resources/mapper/SupplierOrderItemMatchingMapper.xml index ec8eb4e..51d6fef 100644 --- a/src/main/resources/mapper/SupplierOrderItemMatchingMapper.xml +++ b/src/main/resources/mapper/SupplierOrderItemMatchingMapper.xml @@ -178,6 +178,11 @@ matching_id,CREATE_BY, CREATE_DATE, EXT01, EXT02, EXT03, EXT04, EXT05 from supplier_order_item_matching where ITEM_ID = #{itemId,jdbcType=VARCHAR} + delete diff --git a/src/main/resources/mapper/SupplierOrderMapper.xml b/src/main/resources/mapper/SupplierOrderMapper.xml index 4295e35..f83479b 100644 --- a/src/main/resources/mapper/SupplierOrderMapper.xml +++ b/src/main/resources/mapper/SupplierOrderMapper.xml @@ -97,6 +97,14 @@ #{searchOrg,jdbcType=INTEGER})) + + select id,receive_no receiveNo,supplier_code supplierCode + ,order_no orderNo ,goods_num goodsNum + ,item_no itemNo,create_date createDate + ,`status` ,ext01 ,ext02 ,ext03,ext04,ext05 + from supplier_order_refund + + + and supplier_code = #{supplierCode} + + + and order_no = #{orderNo} + + + and item_no = #{itemNo} + + + and status = #{status} + + + + order by create_date desc + + limit #{startNo,jdbcType=INTEGER}, #{length,jdbcType=INTEGER} + + delete from supplier_order_refund @@ -143,9 +177,9 @@ SELECT a.ID, a.RECEIVE_NO, a.RECEIVE_TIME, a.SUPPLIER_CODE, a.ORDER_NO, a.LINE_NUM, a.GOODS, a.UOM, a.GOODS_NUM, a.RECEIVED_NUM, a.CURRENCY, a.UNIT_PRICE, a.AMOUNT, a.COMPANY_NAME, a.`SOURCE`, a.`STATUS`, a.COMPANY_CODE,a.COSTCENTER,a.ORG_CODE,a.ITEM_NO,a.TAX_RATE,a.`OWNER`,a.`DESCRIPTION`,a.CREATION_TIME,a.UPDATE_TIME,a.ORDER_DATE, a.EXT01,a.EXT02,a.EXT03,a.EXT04,a.EXT05,a.SUPPLIER_NAME, - a.RECEIVED_NUM-(select sum(QUANTITY) from supplier_order_item_matching where order_id = a.id) matchNum, - a.AMOUNT-(select sum(total) from supplier_order_item_matching where order_id = a.id) matchAmount, - sum(refund.goods_num) refund_num + a.RECEIVED_NUM-ifnull((select sum(QUANTITY) from supplier_order_item_matching where order_id = a.id),0) matchNum, + a.AMOUNT-ifnull((select sum(total) from supplier_order_item_matching where order_id = a.id),0) matchAmount, + ifnull(sum(refund.goods_num),0) refund_num FROM supplier_order a LEFT JOIN sys_org o ON o.code= a.ORG_CODE left join supplier_order_refund refund diff --git a/src/main/resources/mapper/SupplierOwnerTransferMapper.xml b/src/main/resources/mapper/SupplierOwnerTransferMapper.xml new file mode 100644 index 0000000..57c75e3 --- /dev/null +++ b/src/main/resources/mapper/SupplierOwnerTransferMapper.xml @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + ID, LAST_ID, BILL_ID, `OWNER`, CREATOR, `CURRENT`, TARGET, `STATUS`, IS_DEL, CREATE_BY, + CREATE_DATE, UPDATE_BY, UPDATE_DATE, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + delete from supplier_owner_transfer + where ID = #{id,jdbcType=BIGINT} + + + insert into supplier_owner_transfer (LAST_ID, BILL_ID, `OWNER`, + CREATOR, `CURRENT`, TARGET, + `STATUS`, IS_DEL, CREATE_BY, + CREATE_DATE, UPDATE_BY, UPDATE_DATE, + EXT01, EXT02, EXT03, + EXT04, EXT05) + values (#{lastId,jdbcType=BIGINT}, #{billId,jdbcType=VARCHAR}, #{owner,jdbcType=VARCHAR}, + #{creator,jdbcType=VARCHAR}, #{current,jdbcType=VARCHAR}, #{target,jdbcType=VARCHAR}, + #{status,jdbcType=VARCHAR}, #{isDel,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, + #{createDate,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, + #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, + #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}) + + + insert into supplier_owner_transfer + + + LAST_ID, + + + BILL_ID, + + + `OWNER`, + + + CREATOR, + + + `CURRENT`, + + + TARGET, + + + `STATUS`, + + + IS_DEL, + + + CREATE_BY, + + + CREATE_DATE, + + + UPDATE_BY, + + + UPDATE_DATE, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{lastId,jdbcType=BIGINT}, + + + #{billId,jdbcType=VARCHAR}, + + + #{owner,jdbcType=VARCHAR}, + + + #{creator,jdbcType=VARCHAR}, + + + #{current,jdbcType=VARCHAR}, + + + #{target,jdbcType=VARCHAR}, + + + #{status,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update supplier_owner_transfer + + + LAST_ID = #{lastId,jdbcType=BIGINT}, + + + BILL_ID = #{billId,jdbcType=VARCHAR}, + + + `OWNER` = #{owner,jdbcType=VARCHAR}, + + + CREATOR = #{creator,jdbcType=VARCHAR}, + + + `CURRENT` = #{current,jdbcType=VARCHAR}, + + + TARGET = #{target,jdbcType=VARCHAR}, + + + `STATUS` = #{status,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + + + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + + + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + + + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + update supplier_owner_transfer + set LAST_ID = #{lastId,jdbcType=BIGINT}, + BILL_ID = #{billId,jdbcType=VARCHAR}, + `OWNER` = #{owner,jdbcType=VARCHAR}, + CREATOR = #{creator,jdbcType=VARCHAR}, + `CURRENT` = #{current,jdbcType=VARCHAR}, + TARGET = #{target,jdbcType=VARCHAR}, + `STATUS` = #{status,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=VARCHAR}, + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=BIGINT} + + + + + diff --git a/src/main/resources/mapper/SupplierPoLineMapper.xml b/src/main/resources/mapper/SupplierPoLineMapper.xml new file mode 100644 index 0000000..9a79f17 --- /dev/null +++ b/src/main/resources/mapper/SupplierPoLineMapper.xml @@ -0,0 +1,360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, PO, contract, supplier_code, material_no, material_desc, line_no, pay_date, quantity, + unit, unit_price, tax, discount, net_line_amount, EXT01, EXT02, EXT03, EXT04, EXT05, + CREATE_BY, CREATE_DATE, UPDATE_BY, UPDATE_DATE, IS_DEL + + + + delete from supplier_po_line + where ID = #{id,jdbcType=INTEGER} + + + insert into supplier_po_line (PO, contract, supplier_code, + material_no, material_desc, line_no, + pay_date, quantity, unit, + unit_price, tax, discount, + net_line_amount, EXT01, EXT02, + EXT03, EXT04, EXT05, + CREATE_BY, CREATE_DATE, UPDATE_BY, + UPDATE_DATE, IS_DEL) + values (#{po,jdbcType=VARCHAR}, #{contract,jdbcType=VARCHAR}, #{supplierCode,jdbcType=VARCHAR}, + #{materialNo,jdbcType=VARCHAR}, #{materialDesc,jdbcType=VARCHAR}, #{lineNo,jdbcType=VARCHAR}, + #{payDate,jdbcType=VARCHAR}, #{quantity,jdbcType=VARCHAR}, #{unit,jdbcType=VARCHAR}, + #{unitPrice,jdbcType=VARCHAR}, #{tax,jdbcType=VARCHAR}, #{discount,jdbcType=VARCHAR}, + #{netLineAmount,jdbcType=VARCHAR}, #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, + #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}, + #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, + #{updateDate,jdbcType=TIMESTAMP}, #{isDel,jdbcType=VARCHAR}) + + + insert into supplier_po_line + + + PO, + + + contract, + + + supplier_code, + + + material_no, + + + material_desc, + + + line_no, + + + pay_date, + + + quantity, + + + unit, + + + unit_price, + + + tax, + + + discount, + + + net_line_amount, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + CREATE_BY, + + + CREATE_DATE, + + + UPDATE_BY, + + + UPDATE_DATE, + + + IS_DEL, + + + + + #{po,jdbcType=VARCHAR}, + + + #{contract,jdbcType=VARCHAR}, + + + #{supplierCode,jdbcType=VARCHAR}, + + + #{materialNo,jdbcType=VARCHAR}, + + + #{materialDesc,jdbcType=VARCHAR}, + + + #{lineNo,jdbcType=VARCHAR}, + + + #{payDate,jdbcType=VARCHAR}, + + + #{quantity,jdbcType=VARCHAR}, + + + #{unit,jdbcType=VARCHAR}, + + + #{unitPrice,jdbcType=VARCHAR}, + + + #{tax,jdbcType=VARCHAR}, + + + #{discount,jdbcType=VARCHAR}, + + + #{netLineAmount,jdbcType=VARCHAR}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + #{isDel,jdbcType=VARCHAR}, + + + + + update supplier_po_line + + + PO = #{po,jdbcType=VARCHAR}, + + + contract = #{contract,jdbcType=VARCHAR}, + + + supplier_code = #{supplierCode,jdbcType=VARCHAR}, + + + material_no = #{materialNo,jdbcType=VARCHAR}, + + + material_desc = #{materialDesc,jdbcType=VARCHAR}, + + + line_no = #{lineNo,jdbcType=VARCHAR}, + + + pay_date = #{payDate,jdbcType=VARCHAR}, + + + quantity = #{quantity,jdbcType=VARCHAR}, + + + unit = #{unit,jdbcType=VARCHAR}, + + + unit_price = #{unitPrice,jdbcType=VARCHAR}, + + + tax = #{tax,jdbcType=VARCHAR}, + + + discount = #{discount,jdbcType=VARCHAR}, + + + net_line_amount = #{netLineAmount,jdbcType=VARCHAR}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + + + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + + + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + + + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update supplier_po_line + set PO = #{po,jdbcType=VARCHAR}, + contract = #{contract,jdbcType=VARCHAR}, + supplier_code = #{supplierCode,jdbcType=VARCHAR}, + material_no = #{materialNo,jdbcType=VARCHAR}, + material_desc = #{materialDesc,jdbcType=VARCHAR}, + line_no = #{lineNo,jdbcType=VARCHAR}, + pay_date = #{payDate,jdbcType=VARCHAR}, + quantity = #{quantity,jdbcType=VARCHAR}, + unit = #{unit,jdbcType=VARCHAR}, + unit_price = #{unitPrice,jdbcType=VARCHAR}, + tax = #{tax,jdbcType=VARCHAR}, + discount = #{discount,jdbcType=VARCHAR}, + net_line_amount = #{netLineAmount,jdbcType=VARCHAR}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR}, + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + IS_DEL = #{isDel,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + + + update supplier_po_line + set IS_DEL = '1' + where PO = #{po} + + + + + + + + update supplier_po_line + set IS_DEL = '1' + where ID = #{id} + + + + + + + diff --git a/src/main/resources/mapper/SupplierPoMapper.xml b/src/main/resources/mapper/SupplierPoMapper.xml new file mode 100644 index 0000000..a6e3608 --- /dev/null +++ b/src/main/resources/mapper/SupplierPoMapper.xml @@ -0,0 +1,423 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, po, version_no, order_date, contract_no, company_code, supplier_code, supplier_name, + net_amount, currency, cost_center, requesters_name, po_type, `process`, contacts, + mail_address, `path`, uri, is_del, ext01, ext02, ext03, ext04, ext05, create_by, + create_date, update_by, update_date + + + + delete from supplier_po + where ID = #{id,jdbcType=INTEGER} + + + insert into supplier_po (po, version_no, order_date, + contract_no, company_code, supplier_code, + supplier_name, net_amount, currency, + cost_center, requesters_name, po_type, + `process`, contacts, mail_address, + `path`, uri, is_del, ext01, + ext02, ext03, ext04, + ext05, create_by, create_date, + update_by, update_date) + values (#{po,jdbcType=VARCHAR}, #{versionNo,jdbcType=VARCHAR}, #{orderDate,jdbcType=VARCHAR}, + #{contractNo,jdbcType=VARCHAR}, #{companyCode,jdbcType=VARCHAR}, #{supplierCode,jdbcType=VARCHAR}, + #{supplierName,jdbcType=VARCHAR}, #{netAmount,jdbcType=VARCHAR}, #{currency,jdbcType=VARCHAR}, + #{costCenter,jdbcType=VARCHAR}, #{requestersName,jdbcType=VARCHAR}, #{poType,jdbcType=VARCHAR}, + #{process,jdbcType=VARCHAR}, #{contacts,jdbcType=VARCHAR}, #{mailAddress,jdbcType=VARCHAR}, + #{path,jdbcType=VARCHAR}, #{uri,jdbcType=VARCHAR}, #{isDel,jdbcType=BIT}, #{ext01,jdbcType=VARCHAR}, + #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, #{ext04,jdbcType=VARCHAR}, + #{ext05,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, + #{updateBy,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}) + + + insert into supplier_po + + + po, + + + version_no, + + + order_date, + + + contract_no, + + + company_code, + + + supplier_code, + + + supplier_name, + + + net_amount, + + + currency, + + + cost_center, + + + requesters_name, + + + po_type, + + + `process`, + + + contacts, + + + mail_address, + + + `path`, + + + uri, + + + is_del, + + + ext01, + + + ext02, + + + ext03, + + + ext04, + + + ext05, + + + create_by, + + + create_date, + + + update_by, + + + update_date, + + + + + #{po,jdbcType=VARCHAR}, + + + #{versionNo,jdbcType=VARCHAR}, + + + #{orderDate,jdbcType=VARCHAR}, + + + #{contractNo,jdbcType=VARCHAR}, + + + #{companyCode,jdbcType=VARCHAR}, + + + #{supplierCode,jdbcType=VARCHAR}, + + + #{supplierName,jdbcType=VARCHAR}, + + + #{netAmount,jdbcType=VARCHAR}, + + + #{currency,jdbcType=VARCHAR}, + + + #{costCenter,jdbcType=VARCHAR}, + + + #{requestersName,jdbcType=VARCHAR}, + + + #{poType,jdbcType=VARCHAR}, + + + #{process,jdbcType=VARCHAR}, + + + #{contacts,jdbcType=VARCHAR}, + + + #{mailAddress,jdbcType=VARCHAR}, + + + #{path,jdbcType=VARCHAR}, + + + #{uri,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=BIT}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + + + update supplier_po + + + po = #{po,jdbcType=VARCHAR}, + + + version_no = #{versionNo,jdbcType=VARCHAR}, + + + order_date = #{orderDate,jdbcType=VARCHAR}, + + + contract_no = #{contractNo,jdbcType=VARCHAR}, + + + company_code = #{companyCode,jdbcType=VARCHAR}, + + + supplier_code = #{supplierCode,jdbcType=VARCHAR}, + + + supplier_name = #{supplierName,jdbcType=VARCHAR}, + + + net_amount = #{netAmount,jdbcType=VARCHAR}, + + + currency = #{currency,jdbcType=VARCHAR}, + + + cost_center = #{costCenter,jdbcType=VARCHAR}, + + + requesters_name = #{requestersName,jdbcType=VARCHAR}, + + + po_type = #{poType,jdbcType=VARCHAR}, + + + `process` = #{process,jdbcType=VARCHAR}, + + + contacts = #{contacts,jdbcType=VARCHAR}, + + + mail_address = #{mailAddress,jdbcType=VARCHAR}, + + + `path` = #{path,jdbcType=VARCHAR}, + + + uri = #{uri,jdbcType=VARCHAR}, + + + is_del = #{isDel,jdbcType=BIT}, + + + ext01 = #{ext01,jdbcType=VARCHAR}, + + + ext02 = #{ext02,jdbcType=VARCHAR}, + + + ext03 = #{ext03,jdbcType=VARCHAR}, + + + ext04 = #{ext04,jdbcType=VARCHAR}, + + + ext05 = #{ext05,jdbcType=VARCHAR}, + + + create_by = #{createBy,jdbcType=VARCHAR}, + + + create_date = #{createDate,jdbcType=TIMESTAMP}, + + + update_by = #{updateBy,jdbcType=VARCHAR}, + + + update_date = #{updateDate,jdbcType=TIMESTAMP}, + + + where ID = #{id,jdbcType=INTEGER} + + + update supplier_po + set po = #{po,jdbcType=VARCHAR}, + version_no = #{versionNo,jdbcType=VARCHAR}, + order_date = #{orderDate,jdbcType=VARCHAR}, + contract_no = #{contractNo,jdbcType=VARCHAR}, + company_code = #{companyCode,jdbcType=VARCHAR}, + supplier_code = #{supplierCode,jdbcType=VARCHAR}, + supplier_name = #{supplierName,jdbcType=VARCHAR}, + net_amount = #{netAmount,jdbcType=VARCHAR}, + currency = #{currency,jdbcType=VARCHAR}, + cost_center = #{costCenter,jdbcType=VARCHAR}, + requesters_name = #{requestersName,jdbcType=VARCHAR}, + po_type = #{poType,jdbcType=VARCHAR}, + `process` = #{process,jdbcType=VARCHAR}, + contacts = #{contacts,jdbcType=VARCHAR}, + mail_address = #{mailAddress,jdbcType=VARCHAR}, + `path` = #{path,jdbcType=VARCHAR}, + uri = #{uri,jdbcType=VARCHAR}, + is_del = #{isDel,jdbcType=BIT}, + ext01 = #{ext01,jdbcType=VARCHAR}, + ext02 = #{ext02,jdbcType=VARCHAR}, + ext03 = #{ext03,jdbcType=VARCHAR}, + ext04 = #{ext04,jdbcType=VARCHAR}, + ext05 = #{ext05,jdbcType=VARCHAR}, + create_by = #{createBy,jdbcType=VARCHAR}, + create_date = #{createDate,jdbcType=TIMESTAMP}, + update_by = #{updateBy,jdbcType=VARCHAR}, + update_date = #{updateDate,jdbcType=TIMESTAMP} + where ID = #{id,jdbcType=INTEGER} + + + + + + + + + + + update supplier_po + set IS_DEL = '1' + where po = #{po} + + + + update supplier_po a,( select po,sum(net_line_amount) amount + from supplier_po_line + where po in (SELECT po FROM `supplier_po_line` where EXT01 = #{ext01}) + and is_del = '0' + group by po) b + set a.net_amount = b.amount + where a.po = b.po + + + diff --git a/src/main/resources/mapper/SupplierSiteMapper.xml b/src/main/resources/mapper/SupplierSiteMapper.xml new file mode 100644 index 0000000..a0d9ebe --- /dev/null +++ b/src/main/resources/mapper/SupplierSiteMapper.xml @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + ID, CODE, SITE_CODE, ORG_ID, EMAIL, `SOURCE`, SYNC_TIME, `ENABLE`, V_ENABLE_NAME, + V_SYNC_DATE + + + + + delete + from supplier_site + where ID = #{id,jdbcType=INTEGER} + + + delete + from supplier_site + where `CODE` = #{code,jdbcType=VARCHAR} + + + insert into supplier_site + + + CODE, + + + SITE_CODE, + + + ORG_ID, + + + EMAIL, + + + `SOURCE`, + + + SYNC_TIME, + + + `ENABLE`, + + + + + #{code,jdbcType=VARCHAR}, + + + #{siteCode,jdbcType=VARCHAR}, + + + #{orgId,jdbcType=INTEGER}, + + + #{email,jdbcType=VARCHAR}, + + + #{source,jdbcType=VARCHAR}, + + + #{syncTime,jdbcType=TIMESTAMP}, + + + #{enable,jdbcType=BOOLEAN}, + + + + + update supplier_site + + + CODE = #{code,jdbcType=VARCHAR}, + + + SITE_CODE = #{siteCode,jdbcType=VARCHAR}, + + + ORG_ID = #{orgId,jdbcType=INTEGER}, + + + EMAIL = #{email,jdbcType=VARCHAR}, + + + `SOURCE` = #{source,jdbcType=VARCHAR}, + + + SYNC_TIME = #{syncTime,jdbcType=TIMESTAMP}, + + + `ENABLE` = #{enable,jdbcType=BOOLEAN}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/SysNotificationMapper.xml b/src/main/resources/mapper/SysNotificationMapper.xml new file mode 100644 index 0000000..98e240f --- /dev/null +++ b/src/main/resources/mapper/SysNotificationMapper.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + ID,TITLE,CONTENT, + LEVEL,UPDATE_TIME,SORT, + IS_DEL + + + + + + delete + from sys_notification + where ID = #{id,jdbcType=INTEGER} + + + insert into sys_notification + ( ID, TITLE, CONTENT + , LEVEL, UPDATE_TIME, SORT + , IS_DEL) + values ( #{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR} + , #{level,jdbcType=TINYINT}, #{updateTime,jdbcType=TIMESTAMP}, #{sort,jdbcType=INTEGER} + , #{isDel,jdbcType=BOOLEAN}) + + + update sys_notification + + + TITLE = #{title,jdbcType=VARCHAR}, + + + CONTENT = #{content,jdbcType=VARCHAR}, + + + LEVEL = #{level,jdbcType=TINYINT}, + + + UPDATE_TIME = #{updateTime,jdbcType=TIMESTAMP}, + + + SORT = #{sort,jdbcType=INTEGER}, + + + IS_DEL = #{isDel,jdbcType=BOOLEAN}, + + + where ID = #{id,jdbcType=INTEGER} + + + + + + + diff --git a/src/main/resources/mapper/SysOaDeptMapper.xml b/src/main/resources/mapper/SysOaDeptMapper.xml new file mode 100644 index 0000000..9a3b6ef --- /dev/null +++ b/src/main/resources/mapper/SysOaDeptMapper.xml @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + + ID, CODE, DEPARTMAENT_ID, SUB_COMPANY_ID, SUB_DEPARTMAENT_ID, IS_DEL, CREATE_BY, + CREATE_DATE, UPDATE_BY, UPDATE_DATE, EXT01, EXT02, EXT03, EXT04, EXT05 + + + + delete from sys_oa_dept + where ID = #{id,jdbcType=BIGINT} + + + insert into sys_oa_dept (CODE, DEPARTMAENT_ID, SUB_COMPANY_ID, + SUB_DEPARTMAENT_ID, IS_DEL, CREATE_BY, + CREATE_DATE, UPDATE_BY, UPDATE_DATE, + EXT01, EXT02, EXT03, + EXT04, EXT05) + values (#{code,jdbcType=VARCHAR}, #{departmaentId,jdbcType=VARCHAR}, #{subCompanyId,jdbcType=VARCHAR}, + #{subDepartmaentId,jdbcType=VARCHAR}, #{isDel,jdbcType=BIT}, #{createBy,jdbcType=VARCHAR}, + #{createDate,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, + #{ext01,jdbcType=VARCHAR}, #{ext02,jdbcType=VARCHAR}, #{ext03,jdbcType=VARCHAR}, + #{ext04,jdbcType=VARCHAR}, #{ext05,jdbcType=VARCHAR}) + + + insert into sys_oa_dept + + + CODE, + + + DEPARTMAENT_ID, + + + SUB_COMPANY_ID, + + + SUB_DEPARTMAENT_ID, + + + IS_DEL, + + + CREATE_BY, + + + CREATE_DATE, + + + UPDATE_BY, + + + UPDATE_DATE, + + + EXT01, + + + EXT02, + + + EXT03, + + + EXT04, + + + EXT05, + + + + + #{code,jdbcType=VARCHAR}, + + + #{departmaentId,jdbcType=VARCHAR}, + + + #{subCompanyId,jdbcType=VARCHAR}, + + + #{subDepartmaentId,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=BIT}, + + + #{createBy,jdbcType=VARCHAR}, + + + #{createDate,jdbcType=TIMESTAMP}, + + + #{updateBy,jdbcType=VARCHAR}, + + + #{updateDate,jdbcType=TIMESTAMP}, + + + #{ext01,jdbcType=VARCHAR}, + + + #{ext02,jdbcType=VARCHAR}, + + + #{ext03,jdbcType=VARCHAR}, + + + #{ext04,jdbcType=VARCHAR}, + + + #{ext05,jdbcType=VARCHAR}, + + + + + update sys_oa_dept + + + CODE = #{code,jdbcType=VARCHAR}, + + + DEPARTMAENT_ID = #{departmaentId,jdbcType=VARCHAR}, + + + SUB_COMPANY_ID = #{subCompanyId,jdbcType=VARCHAR}, + + + SUB_DEPARTMAENT_ID = #{subDepartmaentId,jdbcType=VARCHAR}, + + + IS_DEL = #{isDel,jdbcType=BIT}, + + + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + + + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + + + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + + + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + + + EXT01 = #{ext01,jdbcType=VARCHAR}, + + + EXT02 = #{ext02,jdbcType=VARCHAR}, + + + EXT03 = #{ext03,jdbcType=VARCHAR}, + + + EXT04 = #{ext04,jdbcType=VARCHAR}, + + + EXT05 = #{ext05,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=BIGINT} + + + update sys_oa_dept + set CODE = #{code,jdbcType=VARCHAR}, + DEPARTMAENT_ID = #{departmaentId,jdbcType=VARCHAR}, + SUB_COMPANY_ID = #{subCompanyId,jdbcType=VARCHAR}, + SUB_DEPARTMAENT_ID = #{subDepartmaentId,jdbcType=VARCHAR}, + IS_DEL = #{isDel,jdbcType=BIT}, + CREATE_BY = #{createBy,jdbcType=VARCHAR}, + CREATE_DATE = #{createDate,jdbcType=TIMESTAMP}, + UPDATE_BY = #{updateBy,jdbcType=VARCHAR}, + UPDATE_DATE = #{updateDate,jdbcType=TIMESTAMP}, + EXT01 = #{ext01,jdbcType=VARCHAR}, + EXT02 = #{ext02,jdbcType=VARCHAR}, + EXT03 = #{ext03,jdbcType=VARCHAR}, + EXT04 = #{ext04,jdbcType=VARCHAR}, + EXT05 = #{ext05,jdbcType=VARCHAR} + where ID = #{id,jdbcType=BIGINT} + + + + + + + diff --git a/src/main/resources/mapper/SysUserMapper.xml b/src/main/resources/mapper/SysUserMapper.xml index 77fc2d3..9fe245f 100644 --- a/src/main/resources/mapper/SysUserMapper.xml +++ b/src/main/resources/mapper/SysUserMapper.xml @@ -276,7 +276,6 @@ - INSERT INTO corporate_invoice_csv_logs (invoice_id,invoice_number,fh_barcode) VALUES (#{invoiceId},#{number},#{fh_barcode}) diff --git a/src/main/resources/mapper/TaxMappingMapper.xml b/src/main/resources/mapper/TaxMappingMapper.xml new file mode 100644 index 0000000..e2a8025 --- /dev/null +++ b/src/main/resources/mapper/TaxMappingMapper.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + ID, TAX_RATE, CODE, CLIENT + + + + + + + delete from tax_mapping + where ID = #{id,jdbcType=INTEGER} + + + + insert into tax_mapping (TAX_RATE, CODE, CLIENT + ) + values (#{taxRate,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{client,jdbcType=INTEGER} + ) + + + + update tax_mapping + + + TAX_RATE = #{taxRate,jdbcType=VARCHAR}, + + + CODE = #{code,jdbcType=VARCHAR}, + + + CLIENT = #{client,jdbcType=INTEGER}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/TicketTypeMapper.xml b/src/main/resources/mapper/TicketTypeMapper.xml new file mode 100644 index 0000000..4a84601 --- /dev/null +++ b/src/main/resources/mapper/TicketTypeMapper.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + ID, `VALUE`, PID, IS_DEL, `LANGUAGE`, CODE, INVCTYPE, IS_ERCPT, TAX_RATE, ext01,ext02,ext03,ext04,ext05 + + + + + + + + delete + from ticket_type + where ID = #{id,jdbcType=INTEGER} + + + insert into ticket_type (`VALUE`, PID, IS_DEL, + `LANGUAGE`, CODE, INVCTYPE, IS_ERCPT) + values (#{value,jdbcType=VARCHAR}, #{pid,jdbcType=INTEGER}, #{isDel,jdbcType=VARCHAR}, + #{language,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{invctype,jdbcType=VARCHAR}, + #{isErcpt,jdbcType=BOOLEAN}) + + + update ticket_type + + + `VALUE` = #{value,jdbcType=VARCHAR}, + + + PID = #{pid,jdbcType=INTEGER}, + + + IS_DEL = #{isDel,jdbcType=VARCHAR}, + + + `LANGUAGE` = #{language,jdbcType=VARCHAR}, + + + CODE = #{code,jdbcType=VARCHAR}, + + + INVCTYPE = #{invctype,jdbcType=VARCHAR}, + + + IS_ERCPT = #{isErcpt,jdbcType=BOOLEAN}, + + + where ID = #{id,jdbcType=INTEGER} + + + + + diff --git a/src/main/resources/mapper/TicketTypeMappingMapper.xml b/src/main/resources/mapper/TicketTypeMappingMapper.xml new file mode 100644 index 0000000..88569f1 --- /dev/null +++ b/src/main/resources/mapper/TicketTypeMappingMapper.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + ID,TICKET_CODE,TITLE, + TICKET_CODE_MAPPING,ACTIVE + + + + + + delete + from ticket_type_mapping + where ID = #{id,jdbcType=INTEGER} + + + insert into ticket_type_mapping + ( ID, TICKET_CODE, TITLE + , TICKET_CODE_MAPPING, ACTIVE) + values ( #{id,jdbcType=INTEGER}, #{ticketCode,jdbcType=VARCHAR}, #{title,jdbcType=VARCHAR} + , #{ticketCodeMapping,jdbcType=VARCHAR}, #{active,jdbcType=BOOLEAN}) + + + update ticket_type_mapping + + + TICKET_CODE = #{ticketCode,jdbcType=VARCHAR}, + + + TITLE = #{title,jdbcType=VARCHAR}, + + + TICKET_CODE_MAPPING = #{ticketCodeMapping,jdbcType=VARCHAR}, + + + ACTIVE = #{active,jdbcType=BOOLEAN}, + + + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/UserConfigListMapper.xml b/src/main/resources/mapper/UserConfigListMapper.xml new file mode 100644 index 0000000..37188a8 --- /dev/null +++ b/src/main/resources/mapper/UserConfigListMapper.xml @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + ID, USER_ID, PARAMS1, PARAMS2, PARAMS3, PARAMS4, PARAMS5, `TYPE` + + + + + + delete + from user_config_list + where ID = #{id,jdbcType=INTEGER} + + + delete + from user_config_list + where TYPE = #{type,jdbcType=VARCHAR} + and USER_ID = #{userId,jdbcType=INTEGER} + + + insert into user_config_list (USER_ID, PARAMS1, PARAMS2, + PARAMS3, PARAMS4, PARAMS5, + `TYPE`) + values (#{userId,jdbcType=INTEGER}, #{params1,jdbcType=VARCHAR}, #{params2,jdbcType=VARCHAR}, + #{params3,jdbcType=VARCHAR}, #{params4,jdbcType=VARCHAR}, #{params5,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}) + + + insert into user_config_list + + + USER_ID, + + + PARAMS1, + + + PARAMS2, + + + PARAMS3, + + + PARAMS4, + + + PARAMS5, + + + `TYPE`, + + + + + #{userId,jdbcType=INTEGER}, + + + #{params1,jdbcType=VARCHAR}, + + + #{params2,jdbcType=VARCHAR}, + + + #{params3,jdbcType=VARCHAR}, + + + #{params4,jdbcType=VARCHAR}, + + + #{params5,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + + + update user_config_list + + + USER_ID = #{userId,jdbcType=INTEGER}, + + + PARAMS1 = #{params1,jdbcType=VARCHAR}, + + + PARAMS2 = #{params2,jdbcType=VARCHAR}, + + + PARAMS3 = #{params3,jdbcType=VARCHAR}, + + + PARAMS4 = #{params4,jdbcType=VARCHAR}, + + + PARAMS5 = #{params5,jdbcType=VARCHAR}, + + + `TYPE` = #{type,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + + + update user_config_list + set USER_ID = #{userId,jdbcType=INTEGER}, + PARAMS1 = #{params1,jdbcType=VARCHAR}, + PARAMS2 = #{params2,jdbcType=VARCHAR}, + PARAMS3 = #{params3,jdbcType=VARCHAR}, + PARAMS4 = #{params4,jdbcType=VARCHAR}, + PARAMS5 = #{params5,jdbcType=VARCHAR}, + `TYPE` = #{type,jdbcType=VARCHAR} + where ID = #{id,jdbcType=INTEGER} + + diff --git a/src/main/resources/mapper/UserGuideMapper.xml b/src/main/resources/mapper/UserGuideMapper.xml new file mode 100644 index 0000000..f47a736 --- /dev/null +++ b/src/main/resources/mapper/UserGuideMapper.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + ID,TITLE,CONTENT,TITLE_EN,CONTENT_EN, + UPDATE_TIME,SORT,IS_DEL + + + + + + delete + from user_guide + where ID = #{id,jdbcType=INTEGER} + + + insert into user_guide + ( ID, TITLE, CONTENT + , UPDATE_TIME, SORT, IS_DEL, TITLE_EN, CONTENT_EN) + values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR} + , #{updateTime,jdbcType=TIMESTAMP}, #{sort,jdbcType=INTEGER}, #{isDel,jdbcType=BOOLEAN}, + #{titleEn,jdbcType=VARCHAR}, #{contentEn,jdbcType=VARCHAR}) + + + update user_guide + + + TITLE = #{title,jdbcType=VARCHAR}, + + + CONTENT = #{content,jdbcType=VARCHAR}, + + + UPDATE_TIME = #{updateTime,jdbcType=TIMESTAMP}, + + + SORT = #{sort,jdbcType=INTEGER}, + + + IS_DEL = #{isDel,jdbcType=BOOLEAN}, + + + CONTENT_EN = #{contentEn,jdbcType=VARCHAR}, + + + TITLE_EN = #{titleEn,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=INTEGER} + +