| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789 |
- package com.uas.eis.service.Impl;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.TypeReference;
- import com.uas.eis.config.DonlimConfig;
- import com.uas.eis.core.config.SpObserver;
- import com.uas.eis.core.support.TokenProperties;
- import com.uas.eis.dao.*;
- import com.uas.eis.dto.*;
- import com.uas.eis.service.CommonService;
- import com.uas.eis.service.ERPService;
- import com.uas.eis.service.NuoNuoSDKService;
- import com.uas.eis.utils.*;
- import nuonuo.open.sdk.NNOpenSDK;
- import org.apache.commons.lang.StringUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- /**
- * @author koul
- * @email koul@usoftchina.com
- * @date 2021-12-06 18:27
- */
- @Service
- public class ERPServiceImpl implements ERPService {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- private static Map<String, String> tokenConfig = TokenProperties.getAllProperty();
- @Autowired
- private BaseDao baseDao;
- @Autowired
- private DonlimConfig donlimConfig;
- @Autowired
- private CommonService commonService;
- @Autowired
- private NuoNuoSDKService nuoNuoSDKService;
- @Override
- public Map<String, Object> pushInvoiceOrder(String master, int id) {
- Map<String, Object> map = new HashMap<String, Object>();
- try{
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- String url = donlimConfig.getRoute();
- System.out.println(url);
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- if (donlimConfig.isProd()) {
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- }
- logger.info("pushInvoiceOrder begin: master {} ,id {} ", master, id);
- SpObserver.putSp(master);
- SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code " +
- " left join custinvoicemsg on ci_cucode = cu_code " +
- " where io_id=" + id);
- if (rs_main.next()) {
- //String autoInvoiceFlag= baseDao.isDBSetting("InvoiceOrder", "autoInvoice")?"true":"false";
- //数据组装
- InvoiceOrderDTO invoiceOrderDTO = new InvoiceOrderDTO();
- invoiceOrderDTO.setOrderType(rs_main.getGeneralString("IO_ORDERTYPE"));
- invoiceOrderDTO.setAutoInvoiceFlag(rs_main.getGeneralString("io_autoinvoice"));//自动开票
- invoiceOrderDTO.setRepeatCall("0");
- OrderDTO orderDTO = new OrderDTO();
- orderDTO.setOriginalOrderNo(rs_main.getGeneralString("io_code"));
- orderDTO.setAddDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(rs_main.getDate("io_date")));
- orderDTO.setInvoiceLine(rs_main.getGeneralString("io_invoiceline"));
- orderDTO.setSpecificFactor("0");
- orderDTO.setSaleTaxNum(taxnum);//
- orderDTO.setBuyerName(rs_main.getGeneralString("cu_name"));//客户名称
- orderDTO.setTaxNum(rs_main.getGeneralString("ci_taxnum").trim());//购方税号
- orderDTO.setAccount(rs_main.getGeneralString("ci_account"));
- orderDTO.setAddress(rs_main.getGeneralString("ci_address"));
- orderDTO.setTelephone(rs_main.getGeneralString("ci_telephone"));
- orderDTO.setRemark(rs_main.getGeneralString("io_remark"));
- orderDTO.setPayee(rs_main.getGeneralString("IO_PAYEE"));
- orderDTO.setChecker(rs_main.getGeneralString("IO_CHECKER"));
- orderDTO.setClerk(rs_main.getGeneralString("IO_clerk"));
- orderDTO.setPhone(rs_main.getGeneralString("ci_jf_phone"));
- orderDTO.setEmail(rs_main.getGeneralString("ci_jf_email"));
- //原销售订单编号relateSaleOrderNo
- orderDTO.setRelateSaleOrderNo(rs_main.getGeneralString("io_RelateSaleOrderNo"));
- //原发票号码yfphm
- orderDTO.setYfphm(rs_main.getGeneralString("io_Yfphm"));
- invoiceOrderDTO.setOrderInfo(orderDTO);
- SqlRowList rs_det = baseDao.queryForRowSet("select * from invoiceOrderdet_view where id_ioid=" + id + " order by id_detno");
- List<OrderDetDTO> dets = new ArrayList<>();//商品列表
- while (rs_det.next()) {
- OrderDetDTO orderDetDTO = new OrderDetDTO();
- orderDetDTO.setRowNo(rs_det.getGeneralString("id_id"));//唯一值
- orderDetDTO.setGoodsName(rs_det.getGeneralString("pr_detail"));
- orderDetDTO.setSpec(rs_det.getGeneralString("pr_spec"));
- orderDetDTO.setUnit(rs_det.getGeneralString("pr_unit"));
- orderDetDTO.setNum(rs_det.getGeneralString("id_qty"));
- //orderDetDTO.setPrice(rs_det.getGeneralString("id_price"));//平台算法问题 传单价会有差异,校验可能不通过,所有传金额和数量,不传单价
- orderDetDTO.setTaxRate(rs_det.getGeneralString("taxrate"));//0.13
- orderDetDTO.setTax(rs_det.getGeneralString("TAXTOTAL"));
- /*传含税
- orderDetDTO.setTaxAmount(rs_det.getGeneralString("id_amount"));
- orderDetDTO.setHsbz(rs_det.getGeneralString("hsbz"));*/
- /*传不含税*/
- orderDetDTO.setTaxAmount(rs_det.getGeneralString("NETTOTAL"));
- orderDetDTO.setHsbz("0");
- orderDetDTO.setSpbm(rs_det.getGeneralString("spbm"));
- orderDetDTO.setZke(rs_det.getGeneralString("ZKE"));
- dets.add(orderDetDTO);
- }
- invoiceOrderDTO.setOrderOriginalDetails(dets);
- invoiceOrderDTO.setInvoiceGoodsTransports(new ArrayList<>());
- System.out.println(JSONArray.toJSONString(invoiceOrderDTO));
- logger.info("pushInvoiceOrder master {} , id {} , content {}", master, id,JSONArray.toJSONString(invoiceOrderDTO));
- //调用对接
- NNOpenSDK sdk = NNOpenSDK.getIntance();
- String method = "nuonuo.OpeMplatform.saveOrder"; // API方法名
- String content = sdk.convertToUtf8(JSONArray.toJSONString(invoiceOrderDTO));
- String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
- System.out.println("appKey:"+appKey);
- System.out.println("appSecret:"+appSecret);
- System.out.println("token:"+token);
- System.out.println("taxnum:"+taxnum);
- System.out.println("content:"+content);
- String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
- logger.info("pushInvoiceOrder resultString {}, token {}", result, token);
- Map<Object, Object> res = JSONUtil.toMap(result);
- System.out.println(result);
- Object status = res.get("status");
- Object message = res.get("message");
- if (status != null && "0000".equals(status.toString())) {//调用成功
- baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id=" + id);
- commonService.logSRecord("开票订单对接", id);
- } else if (status != null && "9999".equals(status.toString()) && message != null && message.toString().contains("已存在原始订单")) {
- baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id=" + id);
- commonService.logFRecord("开票订单对接", "(" + status + ")" + message, id);
- } else {
- baseDao.execute("update invoiceOrder set io_dockstatus='对接失败' where io_id=" + id);
- commonService.logFRecord("开票订单对接", "(" + status + ")" + message, id);
- }
- logger.info("pushInvoiceOrder master {} ,id {} status {} message {}", master, id, status, message);
- map.put("success", true);
- map.put("status", status);
- map.put("message", message);
- return map;
- } else {//数据无效
- logger.info("pushInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
- map.put("success", false);
- map.put("message", "对接源信息无效");
- return map;
- }
- }catch (Exception e){
- e.printStackTrace();
- commonService.logFRecord("开票订单对接", e.getMessage(), id);
- }
- return map;
- }
- @Override
- public Map<String, Object> invoiceOrderSubmitKp(String master, int id) {
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- String url = donlimConfig.getRoute();
- System.out.println(url);
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- if (donlimConfig.isProd()) {
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- }
- SpObserver.putSp(master);
- SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
- if (rs_main.next()) {
- NNOpenSDK sdk = NNOpenSDK.getIntance();
- String method = "nuonuo.OpeMplatform.submitKp"; // API方法名
- String code = rs_main.getGeneralString("io_code");
- Map<String, String> reqParam = new HashMap<>();
- reqParam.put("orderNo", code);
- String content = JSONArray.toJSONString(reqParam);
- String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
- String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
- System.out.println(result);
- } else {//数据无效
- logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
- }
- return null;
- }
- @Override
- public Map<String, Object> findOrderState(String master, int id) {
- Map<String, Object> map = new HashMap<String, Object>();
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- if (obs == null) {
- return null;//对接信息为配置
- }
- String url = donlimConfig.getRoute();
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- if (donlimConfig.isProd()) {
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- }
- SpObserver.putSp(master);
- SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
- if (rs_main.next()) {
- String code = rs_main.getGeneralString("io_code");
- NNOpenSDK sdk = NNOpenSDK.getIntance();
- String method = "nuonuo.OpeMplatform.findOrderState"; // API方法名
- Map<String, String> reqParam = new HashMap<>();
- reqParam.put("originalOrderNo", code);
- reqParam.put("saleTaxNum", taxnum);
- String content = JSONArray.toJSONString(reqParam);
- String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
- String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
- System.out.println(result);
- FindOrderStateResp resp = JSON.parseObject(result, new TypeReference<FindOrderStateResp>() {
- });
- System.out.println(resp.getCode());
- System.out.println(resp.getMessage());
- if ("该订单不存在".equals(resp.getMessage())) {
- baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '-1' where io_id = '" + id + "'");
- } else {
- baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '" + resp.getData().getInvoiceStatus() + "'"
- + ",io_errorMsg='" + StringUtil.nvl(resp.getData().getErrorMsg(), "") + "'"
- + " where io_id = '" + id + "'");
- }
- map.put("success", true);
- map.put("result", result);
- return map;
- } else {//数据无效
- logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
- }
- return null;
- }
- @Override
- public Map<String, Object> cancelInvoiceOrder(String master, int id) {
- Map<String, Object> map = new HashMap<String, Object>();
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- if (obs == null) {
- return null;//对接信息为配置
- }
- String url = donlimConfig.getRoute();
- System.out.println(url);
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- if (donlimConfig.isProd()) {
- System.out.println("prod");
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- } else {
- System.out.println("dev");
- }
- SpObserver.putSp(master);
- SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
- if (rs_main.next()) {
- String code = rs_main.getGeneralString("io_code");
- Map<String, String> reqParam = new HashMap<>();
- reqParam.put("originalOrderNo", code);
- reqParam.put("saleTaxNum", taxnum);
- String content = JSONArray.toJSONString(reqParam);
- NNOpenSDK sdk = NNOpenSDK.getIntance();
- String method = "nuonuo.OpeMplatform.deleteOrder"; // API方法名
- String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
- String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
- Map<Object, Object> res = JSONUtil.toMap(result);
- System.out.println(result);
- Object status = res.get("status");
- Object message = res.get("message");
- if (status != null && "0000".equals(status.toString())) {//调用成功
- baseDao.execute("update invoiceOrder set io_dockstatus='' where io_id=" + id);
- baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'SUCCEED',''," + id + ") ");
- map.put("success", true);
- map.put("message", message);
- } else {
- //baseDao.execute("update invoiceOrder set io_dockstatus='取消失败' where io_id=" + id);
- baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'FAILED','(" + status + ")" + message + "'," + id + ") ");
- map.put("success", false);
- map.put("message", "(" + status + ")" + message);
- }
- logger.info("cancelInvoiceOrder master {} ,id {} status {} message {}", master, id, status, message);
- return map;
- } else {//数据无效
- logger.info("cancelInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
- }
- return null;
- }
- @Override
- public Map<String, Object> getElecInvoicesById(String master, Integer id) {
- Map<String, Object> map = new HashMap<String, Object>();
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- if (obs == null) {
- return null;//对接信息为配置
- }
- // System.out.println(url);
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- logger.info("ElecI-getElecInvoicesById:master {} isProd {}", SpObserver.getSp(), donlimConfig.isProd());
- if (donlimConfig.isProd()) {
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- }
- Map<String, Object> m = new HashMap<>();
- m.put("appKey", appKey);
- m.put("appSecret", appSecret);
- m.put("token", token);
- m.put("taxnum", taxnum);
- SpObserver.putSp(master);
- SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code,io_ordertype from " + master + ".invoiceOrder left join " + master + ".customer on io_cucode=cu_code " +
- " where io_id = " + id);
- while (ioList.next()) {
- m.put("io_id", ioList.getGeneralInt("io_id"));
- m.put("io_code", ioList.getGeneralString("io_code"));
- m.put("io_ordertype", ioList.getGeneralInt("io_ordertype"));
- map = getElecInvoices(m);
- }
- return map;
- }
- @Override
- public Map<String, Object> getElecInvoices(Map<String, Object> m) {
- if (Integer.valueOf(m.get("io_ordertype").toString()).equals(2)) {
- return getRedReturnElecInvoices(m);
- }
- String taxnum = m.get("taxnum").toString();
- int ioid = Integer.valueOf(m.get("io_id").toString());
- String ioCode = m.get("io_code").toString();
- Map<String, Object> res = new HashMap<String, Object>();
- String errCode = "-999";
- String errMsg = "";
- try {
- //调用对接
- FindOrderRelationInvoiceReq foriReq = new FindOrderRelationInvoiceReq();
- foriReq.setOriginalOrderNo(ioCode);//订单编号
- foriReq.setSaleTaxNum(taxnum);//销方税号
- foriReq.setNeedInvoiceSourceDetail("1");//是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS。先默认不需要明细
- FindOrderRelationInvoiceResp resp = nuoNuoSDKService.findOrderRelationInvoice(foriReq, m);
- errCode = resp.getStatus();
- errMsg = resp.getMessage();
- logger.info("ElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
- if ("0000".equals(errCode)) {//调用成功
- //记录发票明细
- baseDao.execute(getElecInvoicesSqls(ioid, resp.getData()));
- //红字
- commonService.logSRecord("订单关联发票对接", ioid);
- } else if (!"8958".equals(errCode)) {// {"status":"8958","message":"该订单对应的开票单不存在","data":null} 没有开票单的不记录对接失败日志
- if (errMsg.length() > 3980) {
- errMsg = errMsg.substring(0, 3980);
- }
- baseDao.execute("update invoiceOrder set io_errorMsg='订单关联发票查询失败: " + errMsg + "' where io_id=" + ioid);
- commonService.logFRecord("订单关联发票对接", "(" + errCode + ")" + errMsg, ioid);
- }
- } catch (Exception e) {
- e.printStackTrace();
- errMsg = "发票获取异常";
- if (StringUtil.hasText(e.getMessage())) {
- errMsg = e.getMessage();
- } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
- errMsg = e.getCause().getMessage();
- }
- logger.info("ElecI-DownLoad-master: {} ,id {} message {}", SpObserver.getSp(), ioid, errMsg);
- commonService.logFRecord("订单关联发票对接", errMsg.replaceAll("'", "''"), ioid);
- }
- //获取红字发票PDF地址
- List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice " +
- "where ei_ioid = " + ioid + " and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in (' ','01','04')", String.class);
- if (!CollectionUtil.isEmpty(serialNosAll)) {
- queryRedPdfUrl(serialNosAll, m);
- }
- if (StringUtil.hasText(errMsg) && !"调用成功".equals(errMsg)) {
- res.put("success", false);
- res.put("errCode", errCode);
- res.put("errMsg", errMsg);
- } else {
- res.put("success", true);
- }
- return res;
- }
- private List<String> getElecInvoicesSqls(int ioid, List<FindOrderRelationInvoiceDTO> data) {
- List<String> sqls = new ArrayList<String>();
- boolean syncToBillOut = baseDao.isDBSetting("BillOut", "syncToBillOut");
- for (int i = 0; i < data.size(); i++) {
- FindOrderRelationInvoiceDTO friDto = data.get(i);
- sqls.addAll(friDto.toMergeSql(ioid, (i + 1)));
- }
- sqls.add(" update invoiceOrder set io_refno = (" +
- " select (min(ei_refno)||(case when max(ei_refno) <> min(ei_refno) then '-'||max(ei_refno) else '' end)) " +
- " from ELECINVOICE " +
- " where ei_ioid = io_id and EI_INVOICETYPE = 1 " +
- " and ( nvl(ei_rushredstate,0) <> 1 or (nvl(ei_rushredstate,0) = 1 and exists (Select 1 from invoiceOrder redio where redio.io_ordertype=2 and redio.io_yfphm = ei_refno)) ) " +
- " ) " +
- " where io_id = " + ioid);
- //更新开票记录
- if (syncToBillOut) {
- sqls.add("update BillOut set bi_refno = (select max(io_refno) from invoiceOrder where io_id = " + ioid + " and io_biid = bi_id) where bi_id in (select io_biid from invoiceOrder where io_id = " + ioid + " and io_refno is not null)");
- }
- // System.out.println("sqls:");
- // System.out.println(sqls.toString());
- return sqls;
- }
- @Override
- public Map<String, Object> rushRed(String master, int id) {
- Map<String, Object> map = new HashMap<String, Object>();
- Object[] obs = baseDao.getFieldsDataByCondition("DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
- String url = donlimConfig.getRoute();
- String appKey = donlimConfig.getAppKey();
- String appSecret = donlimConfig.getAppSecret();
- String token = donlimConfig.getToken();
- String taxnum = donlimConfig.getTaxnum();
- if (donlimConfig.isProd()) {
- appKey = obs[0].toString();
- appSecret = obs[1].toString();
- token = obs[2].toString();// 访问令牌
- taxnum = obs[3].toString();// 授权企业税号
- }
- Map<String, Object> m = new HashMap<>();
- m.put("appKey", appKey);
- m.put("appSecret", appSecret);
- m.put("token", token);
- m.put("taxnum", taxnum);
- logger.info("rushRed begin: master {} ,id {} ", master, id);
- SpObserver.putSp(master);
- StringBuffer errmsg = new StringBuffer();
- StringBuffer remindmsg = new StringBuffer();
- SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code left join elecinvoice on io_id=ei_ioid where io_id=" + id + " and nvl(ei_redapplyid,' ')=' ' and nvl(EI_INVOICESTATE,0)=1 and nvl(EI_INVOICETYPE,0)=1 ");
- if (rs_main.hasNext()) {
- int scount = 0;
- while (rs_main.next()) {
- RedInvoiceReq redInvoiceReq = new RedInvoiceReq();
- redInvoiceReq.setBlueInvoiceLine(rs_main.getGeneralString("io_invoiceline"));//蓝票发票种类
- redInvoiceReq.setApplySource("0");//申请方(录入方)身份: 0 销方 1 购方
- redInvoiceReq.setSellerTaxNo(taxnum);//销方税号
- redInvoiceReq.setBuyerName(rs_main.getGeneralString("cu_name"));//购方名称
- redInvoiceReq.setBuyerTaxNo(rs_main.getGeneralString("ei_taxno"));
- redInvoiceReq.setRedReason(rs_main.getGeneralString("io_redreason"));
- //redInvoiceReq.setAutoInvoice("1");//测试是否能自动红冲目前参数无效
- redInvoiceReq.setBlueElecInvoiceNumber(rs_main.getGeneralString("ei_allelectronicinvoicenumber"));
- NNOpenSDK sdk = NNOpenSDK.getIntance();
- String content = sdk.convertToUtf8(JSONArray.toJSONString(redInvoiceReq));
- String method = "nuonuo.OpeMplatform.saveInvoiceRedConfirm"; // API方法名
- String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
- String resp = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
- Map<Object, Object> res = JSONUtil.toMap(resp);
- Object code = res.get("code");
- Object describe = res.get("describe");
- Object result = res.get("result");
- logger.info("rushRed master {} ,id {} code {} describe {} applycode {}", master, id, code, describe, result);
- if (code != null && "E0000".equals(code.toString())) {//调用成功
- baseDao.execute("update elecinvoice set ei_redapplyid='" + result.toString() + "' where ei_id=" + rs_main.getGeneralInt("ei_id"));
- scount++;
- commonService.logSRecord("红字确认单申请(" + rs_main.getGeneralString("ei_refno") + ")", id);
- } else {
- //E9755 describe 该发票存在进行中的红字确认单,暂时不能冲红
- commonService.logFRecord("红字确认单申请(" + rs_main.getGeneralInt("ei_id") + ")", "(" + code + ")" + describe, id);
- errmsg.append("(" + code + ")" + describe).append("</br>");
- }
- }
- //没有自动开红票 但是可以拿状态
- if (scount > 0) {
- m.put("io_id", id);
- m.put("ei_id", 0);
- //获取红字确认状态等信息,若自动开票成功,则同时获取红票信息
- Map<String, Object> mm = queryInvoiceRedConfirm(m);
- if ("false".equals(mm.get("success")) && StringUtil.hasText(mm.get("errMsg"))) {
- remindmsg.append(mm.get("errMsg"));
- }
- }
- } else {//数据无效
- logger.info("rushRed err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
- errmsg.append("对接源信息无效");
- return map;
- }
- if (errmsg.length() > 0) {
- map.put("success", false);
- if (remindmsg.length() > 0) {
- errmsg.append(remindmsg.toString());
- }
- map.put("message", errmsg.toString());
- } else {
- map.put("success", true);
- if (remindmsg.length() > 0) {
- map.put("message", remindmsg.toString());
- }
- }
- return map;
- }
- /*
- 条件:蓝票、有确认单号、待确认或者无需确认的情况下 持续获取红票相关信息
- 按照红冲确认单查询对应状态
- 可以查到信息: 确认单状态、开票状态、冲红原因、
- 若已开票,则自动获取红票 发票号:
- 冲红原因: 1销货退回 2开票有误 3服务中止 4销售折让
- */
- @Override
- public Map<String, Object> queryInvoiceRedConfirm(Map<String, Object> m) {
- int ioid = Integer.valueOf(m.get("io_id").toString());
- int eiid = Integer.valueOf(m.get("ei_id").toString());
- Map<String, Object> res = new HashMap<String, Object>();
- StringBuffer errmsg = new StringBuffer();
- SqlRowList bluePiao = baseDao.queryForRowSet("select ei_id,ei_redapplyid,ei_billStatus,ei_billNo,ei_billUuid,ei_taxExcludedAmount,ei_taxAmount,ei_redReason,io_ordertype " +
- "from elecinvoice left join invoiceOrder on ei_ioid = io_id " +
- "where ei_ioid = '" + ioid + "' " + (eiid > 0 ? "and ei_id = " + eiid : "")
- + " and EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and nvl(ei_billStatus,' ') in (' ','01','02','03','15') " +
- "order by ei_Detno");
- if (bluePiao.hasNext()) {
- boolean isRushRedBill = false;
- while (bluePiao.next()) {
- String redApplyId = bluePiao.getGeneralString("ei_redapplyid");
- eiid = bluePiao.getGeneralInt("ei_id");
- m.put("ei_id", eiid);
- QueryInvoiceRedConfirmReq qircReq = new QueryInvoiceRedConfirmReq();
- qircReq.setIdentity("0");
- qircReq.setBillId(redApplyId);
- String rCode = "-999";
- String describe = "";
- String logCode = "发票红字确认状态查询";
- try {
- QueryInvoiceRedConfirmResp qircResp = nuoNuoSDKService.queryInvoiceRedConfirm(qircReq, m);
- rCode = qircResp.getCode();
- describe = qircResp.getDescribe();
- logger.info("ElecI-queryInvoiceRedConfirmByCode:master {} ,redApplyid {} rCode {} describe {} total {}", SpObserver.getSp(), redApplyId, rCode, describe, qircResp.getResult().getTotal());
- if ("E0000".equals(rCode)) {//调用成功 记录发票明细 1135624457459470336
- List<String> sqls = new ArrayList<>();
- List<QueryInvoiceRedConfirmDTO> qircList = qircResp.getResult().getList();
- for (int i = 0; i < qircList.size(); i++) {
- QueryInvoiceRedConfirmDTO qircfDTO = qircList.get(i);
- //先获取红票状态 不一致才更新
- sqls.add("update elecinvoice set " +
- "ei_billStatus='" + qircfDTO.getBillStatus() + "' " +
- ",ei_billNo='" + StringUtil.nvl(qircfDTO.getBillNo(), "") + "' " + //990000008655037292
- ",ei_billUuid='" + StringUtil.nvl(qircfDTO.getBillUuid(), "") + "' " +
- ",ei_redsid='" + StringUtil.nvl(qircfDTO.getInvoiceSerialNum(), "") + "' " +
- ",ei_redorderno='" + StringUtil.nvl(qircfDTO.getOrderNo(), "") + "' " +
- ",ei_taxExcludedAmount='" + StringUtil.nvl(qircfDTO.getTaxExcludedAmount(), "0") + "' " +
- ",ei_taxAmount='" + StringUtil.nvl(qircfDTO.getTaxAmount(), "0") + "' " +
- ",ei_redReason='" + StringUtil.nvl(qircfDTO.getRedReason(), "") + "' " +
- ",ei_openStatus='" + StringUtil.nvl(qircfDTO.getOpenStatus(), "0") + "' " +
- " where ei_id = " + eiid);
- //针对自动开票场景:若开票,则记录红票数据,调用查询接口批量更新
- if ("1".equals(qircfDTO.getOpenStatus())) { //已开具红字发票标记: 1:已开具 0:未开具 //orderNo 20230731182154174492
- isRushRedBill = true;
- // serialNos 流水号 -- EI_SID -- invoiceSerialNum ; orderNos 开票单号 --- EI_ORDERNO -- ORDERNO
- }
- }
- baseDao.execute(sqls);
- describe = "";
- } else {
- if (describe.length() > 3980) {
- describe = describe.substring(0, 3980);
- }
- errmsg.append(describe).append("</br>");
- baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='" + logCode + ": " + describe + "' where ei_id = " + eiid + " ");
- commonService.logFRecord(logCode, describe, eiid);
- }
- } catch (Exception e) {
- e.printStackTrace();
- describe = "未知异常";
- if (StringUtil.hasText(e.getMessage())) {
- describe = e.getMessage();
- } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
- describe = e.getCause().getMessage();
- }
- commonService.logFRecord(logCode, "发票红冲状态查询:" + describe.replaceAll("'", "''"), eiid);
- }
- if (StringUtil.hasText(describe)) {
- errmsg.append(describe);
- }
- }
- if (isRushRedBill) {
- Map<String, Object> elM = new HashMap<>();
- elM.put("appKey", m.get("appKey"));
- elM.put("appSecret", m.get("appSecret"));
- elM.put("token", m.get("token"));
- elM.put("taxnum", m.get("taxnum"));
- elM.put("io_id", ioid);
- elM.put("io_code", m.get("io_code"));
- elM.put("io_ordertype", bluePiao.getGeneralInt("io_ordertype"));
- Map<String, Object> r = getElecInvoices(elM);
- if (StringUtil.hasText(r.get("errMsg"))) {
- baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='" + r.get("errCode") + ": " + r.get("errMsg") + "' where EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and ei_ioid = " + ioid);
- }
- }
- }
- if (errmsg.length() > 0) {
- res.put("success", false);
- res.put("errMsg", errmsg.toString());
- } else {
- res.put("success", true);
- }
- return res;
- }
- //根据红票流水号 获取红票号及其他信息
- public Map<String, Object> queryRedPdfUrl(List<String> serialNosAll, Map<String, Object> m) {
- Map<String, Object> res = new HashMap<>();
- String describe = "";
- try {
- logger.info("ElecI-queryRedPdfUrl:master {} ,serialNosAll {}", SpObserver.getSp(), serialNosAll.toString());
- List<String> rSql = new ArrayList<String>();
- if (serialNosAll.size() > 0) {
- Stream.iterate(0, n -> n + 1)
- .limit((int) Math.ceil((double) serialNosAll.size() / 50)).forEach(page -> {
- List<String> serialNos = serialNosAll.stream().skip(page * 50).limit(50).collect(Collectors.toList());
- QueryInvoiceResultReq qirReq = new QueryInvoiceResultReq();
- qirReq.setIsOfferInvoiceDetail("0");
- qirReq.setSerialNos(serialNos);
- QueryInvoiceResultResp qirResp = nuoNuoSDKService.queryInvoiceResult(qirReq, m);
- List<QueryInvoiceResultDTO> list = qirResp.getResult();
- if (!CollectionUtil.isEmpty(list)) {
- for (int i = 0; i < list.size(); i++) {
- String sql = list.get(i).updatePdfUrlSql();
- if (!"".equals(sql)) {
- rSql.add(sql);
- }
- }
- }
- });
- }
- // System.out.println("rSql:" + rSql.toString());
- baseDao.execute(rSql);
- } catch (Exception e) {
- e.printStackTrace();
- describe = "未知异常";
- if (StringUtil.hasText(e.getMessage())) {
- describe = e.getMessage();
- } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
- describe = e.getCause().getMessage();
- }
- commonService.logFRecord("查询红票详情", describe.replaceAll("'", "''"), 0);
- }
- return res;
- }
- //退货单 订单开票 根据来源蓝票获取红票信息:写入退货的发票明细、更新来源蓝票对应红票信息、及退货开票记录中
- @Override
- public Map<String, Object> getRedReturnElecInvoices(Map<String, Object> m) {
- String taxnum = m.get("taxnum").toString();
- int ioid = Integer.valueOf(m.get("io_id").toString());
- String ioCode = m.get("io_code").toString();
- Map<String, Object> res = new HashMap<String, Object>();
- String errCode = "-999";
- String errMsg = "";
- SqlRowList ioReturn = baseDao.queryForRowSet("select io_id,io_code,io_relatesaleorderno,io_yfphm,io_biid,io_bicode from invoiceOrder " +
- " where IO_INVOICESTATUS = 2 and io_ordertype = 2 and io_id = " + ioid);
- if (!ioReturn.next()) {
- errMsg = "退货订单:" + ioCode + "(" + ioid + ")不存在";
- logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errMsg);
- commonService.logFRecord("退货订单关联发票对接", errMsg, ioid);
- }
- String relatesaleorderno = ioReturn.getGeneralString("io_relatesaleorderno");//关联蓝票订单号
- String oldInvoiceNumber = ioReturn.getGeneralString("io_yfphm");//原蓝票发票号码
- Integer biid = ioReturn.getGeneralInt("io_biid");
- String bicode = ioReturn.getGeneralString("io_bicode");
- SqlRowList ioBlue = baseDao.queryForRowSet("select ei_id,ei_ioid from ElecInvoice " +
- "where EI_IOCODE ='" + relatesaleorderno + "' and EI_ALLELECTRONICINVOICENUMBER ='" + oldInvoiceNumber + "'");
- if (!ioBlue.next()) {
- errMsg = "原订单:" + relatesaleorderno + "不存在";
- logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errMsg);
- commonService.logFRecord("退货订单关联发票对接", errMsg, ioid);
- }
- Integer eiBlue = ioBlue.getGeneralInt("ei_id");
- try {
- Map<String, Object> mBlue = new HashMap<>();
- mBlue.put("taxnum", taxnum);
- mBlue.put("appKey", m.get("appKey"));
- mBlue.put("appSecret", m.get("appSecret"));
- mBlue.put("token", m.get("token"));
- FindOrderRelationInvoiceReq foriReqBlue = new FindOrderRelationInvoiceReq();
- foriReqBlue.setOriginalOrderNo(relatesaleorderno);//订单编号
- foriReqBlue.setSaleTaxNum(taxnum);//销方税号
- foriReqBlue.setNeedInvoiceSourceDetail("1");//是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS。先默认不需要明细
- FindOrderRelationInvoiceResp resp = nuoNuoSDKService.findOrderRelationInvoice(foriReqBlue, mBlue);
- errCode = resp.getStatus();
- errMsg = resp.getMessage();
- logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
- errCode = resp.getStatus();
- errMsg = resp.getMessage();
- logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
- if ("0000".equals(errCode)) {//调用成功
- List<String> sqls = new ArrayList<>();
- List<FindOrderRelationInvoiceDTO> data = resp.getData();
- for (int i = 0; i < data.size(); i++) {
- FindOrderRelationInvoiceDTO friDto = data.get(i);
- if (friDto.getAllElectronicInvoiceNumber().equals(oldInvoiceNumber)) {
- List<RelateRedInvoiceDTO> relateRedInvoiceList = friDto.getRelateRedInvoiceList();
- for (int j = 0; j < relateRedInvoiceList.size(); j++) {
- RelateRedInvoiceDTO relateRedInvoiceDTO = relateRedInvoiceList.get(j);
- if (StringUtil.hasText(relateRedInvoiceDTO.getAllElectronicInvoiceNumber())) {
- sqls.add("delete ElecInvoice where ei_ioid = " + ioid);
- sqls.add("insert into ElecInvoice (EI_ID, EI_DETNO, EI_IOID, EI_IOCODE, EI_BIID, EI_BICODE " +
- " , EI_SID, EI_ORDERNO, EI_CREATETIME, EI_INVOICETYPE, EI_INVOICELINE, EI_SPECIFICFACTOR, EI_INVOICESTATE, EI_EXCEPTIONMESSAGE, EI_INVOICECODE, EI_INVOICENUMBER, EI_ALLELECTRONICINVOICENUMBER, EI_OLDINVOICECODE, EI_OLDINVOICENUMBER, EI_OLDALLELECTRONICINVOICENU" +
- " , EI_INVOICETIME, EI_INVALIDTIME" +
- " , EI_PDFURL, EI_PDFATTACH, EI_OFDURL, EI_IMAGEURL, EI_CALCEXCLUDINGTAXAMOUNT, EI_CALCTAXAMOUNT, EI_CALEORDERAMOUNT, EI_SELLERTAXNO, EI_SELLERNAME, EI_TAXNO, EI_BUYERNAME, EI_REMARK, EI_CLERKER, EI_PAYEE, EI_CHECKER, EI_BFIELD1, EI_BFIELD2, EI_BFIELD3, EI_INDATE, EI_UPDATEDATE, EI_REFNO" +
- " ,EI_BILLSTATUS,ei_rushredstate,ei_redsid,ei_relativerefno,ei_taxamount,ei_taxexcludedamount) " +
- "SELECT ElecInvoice_Seq.nextval,1," + ioid + ",'" + ioCode + "'," + biid + ",'" + bicode + "' " +
- " , EI_SID, EI_ORDERNO, EI_CREATETIME, EI_INVOICETYPE, EI_INVOICELINE, EI_SPECIFICFACTOR, EI_INVOICESTATE, EI_EXCEPTIONMESSAGE, EI_INVOICECODE, EI_INVOICENUMBER, EI_ALLELECTRONICINVOICENUMBER, EI_OLDINVOICECODE, EI_OLDINVOICENUMBER, EI_OLDALLELECTRONICINVOICENU" +
- " , (to_date('1970-01-0100:00:00','yyyy-mm-dd hh24:mi:ss') + "+relateRedInvoiceDTO.getInvoiceTime()+"/1000/24/60/60) EI_INVOICETIME, EI_INVALIDTIME" +
- " , EI_PDFURL, EI_PDFATTACH, EI_OFDURL, EI_IMAGEURL, EI_CALCEXCLUDINGTAXAMOUNT, EI_CALCTAXAMOUNT, EI_CALEORDERAMOUNT, EI_SELLERTAXNO, EI_SELLERNAME, EI_TAXNO, EI_BUYERNAME, EI_REMARK, EI_CLERKER, EI_PAYEE, EI_CHECKER, EI_BFIELD1, EI_BFIELD2, EI_BFIELD3, EI_INDATE, EI_UPDATEDATE, EI_REFNO" +
- " ,'01' EI_BILLSTATUS,"+friDto.getRushRedState()+" ei_rushredstate,'"+relateRedInvoiceDTO.getSid()+"' ei_redsid,'"+relateRedInvoiceDTO.getAllElectronicInvoiceNumber()+"' ei_relativerefno,"+relateRedInvoiceDTO.getTaxAmount()+" ei_taxamount,"+relateRedInvoiceDTO.getExcludingTaxAmount()+" ei_taxexcludedamount " +
- "FROM ElecInvoice b WHERE EI_ID = " + eiBlue);
- sqls.add("update ElecInvoice set EI_BILLSTATUS='01'" +
- ",ei_rushredstate=" + friDto.getRushRedState() + "" +
- ",ei_redsid='" + relateRedInvoiceDTO.getSid() + "' " +
- ",ei_relativerefno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' " +
- ",ei_taxamount=" + relateRedInvoiceDTO.getTaxAmount() +
- ",ei_taxexcludedamount=" + relateRedInvoiceDTO.getExcludingTaxAmount() +
- ",ei_redpdfurl=null,ei_redpdfattach=null " +
- " where EI_ID = '" + eiBlue + "'");
- sqls.add("update InvoiceOrder set io_refno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' where io_id=" + ioid);
- sqls.add("update billout set bi_refno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' where bi_code='" + bicode + "'");
- }
- }
- }
- }
- //记录发票明细
- // System.out.println(sqls.toString());
- baseDao.execute(sqls);
- //红字
- commonService.logSRecord("退货订单关联发票对接", ioid);
- } else {// {"status":"8958","message":"该订单对应的开票单不存在","data":null} 没有开票单的不记录对接失败日志
- if (errMsg.length() > 3850) {
- errMsg = errMsg.substring(0, 3850);
- }
- baseDao.execute("update invoiceOrder set io_errorMsg='订单关联发票查询失败: " + errMsg + "' where io_id=" + ioid);
- commonService.logFRecord("退货订单关联发票对接", "蓝发票信息获取:(" + errCode + ")" + errMsg, ioid);
- }
- } catch (Exception e) {
- e.printStackTrace();
- errMsg = "发票获取异常";
- if (StringUtil.hasText(e.getMessage())) {
- errMsg = e.getMessage();
- } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
- errMsg = e.getCause().getMessage();
- }
- logger.info("RedReturnElecI-DownLoad-master: {} ,id {} message {}", SpObserver.getSp(), ioid, errMsg);
- commonService.logFRecord("退货订单关联发票对接", errMsg.replaceAll("'", "''"), ioid);
- }
- //获取红字发票PDF地址
- List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice " +
- "where ei_id = " + eiBlue + " and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in (' ','01','04')", String.class);
- if (!CollectionUtil.isEmpty(serialNosAll)) {
- queryRedPdfUrl(serialNosAll, m);
- }
- if (StringUtil.hasText(errMsg) && !"调用成功".equals(errMsg)) {
- res.put("success", false);
- res.put("errCode", errCode);
- res.put("errMsg", errMsg);
- } else {
- res.put("success", true);
- }
- return res;
- }
- }
|