From 54270dd8d4bbcda6f7a777a369b12720cc9a0cf3 Mon Sep 17 00:00:00 2001 From: hefengkai <958118178@qq.com> Date: Tue, 4 Mar 2025 17:53:42 +0800 Subject: [PATCH 1/5] first commit --- .../BusiregForSyncSaleorderAndToBIP.java | 0 .../resource/GatheringbillRestResource.java | 0 .../nccloud/openapi/ArriveResourcesTest.java | 20 + .../nccloud/openapi/BaseOpenApiTest.java | 406 ++++++++++++++++++ .../supplierprice/rule/SupPriceQryRule.java | 0 .../nc/vo/pp/report/util/PurpRptUtils.java | 0 .../impl/so/m30/APISaleOrderMaitainImpl.java | 403 +++++++++++++++++ .../api/so/m30/IAPISaleOrderMaitain.java | 0 .../operator/saveCommitAction.java | 0 .../openapi/so/m30/SaleOrderResource.java | 0 10 files changed, 829 insertions(+) create mode 100644 arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java create mode 100644 arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java create mode 100644 arap/src/public/nccloud/openapi/ArriveResourcesTest.java create mode 100644 arap/src/public/nccloud/openapi/BaseOpenApiTest.java create mode 100644 purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java create mode 100644 purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java create mode 100644 so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java create mode 100644 so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java create mode 100644 so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java create mode 100644 so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java diff --git a/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java b/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java new file mode 100644 index 0000000..e69de29 diff --git a/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java b/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java new file mode 100644 index 0000000..e69de29 diff --git a/arap/src/public/nccloud/openapi/ArriveResourcesTest.java b/arap/src/public/nccloud/openapi/ArriveResourcesTest.java new file mode 100644 index 0000000..ea131cf --- /dev/null +++ b/arap/src/public/nccloud/openapi/ArriveResourcesTest.java @@ -0,0 +1,20 @@ +package nccloud.openapi; + + +public class ArriveResourcesTest extends nccloud.openapi.BaseOpenApiTest { + public void save() { + String url = "/nccloud/api/pu/arrive/saveFromOrder"; + + try { + String result = requestOpenApiByJSON(url, "resources/Arrive.json"); + System.out.println(result); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) { + ArriveResourcesTest test = new ArriveResourcesTest(); + test.save(); + } +} diff --git a/arap/src/public/nccloud/openapi/BaseOpenApiTest.java b/arap/src/public/nccloud/openapi/BaseOpenApiTest.java new file mode 100644 index 0000000..28cc9ce --- /dev/null +++ b/arap/src/public/nccloud/openapi/BaseOpenApiTest.java @@ -0,0 +1,406 @@ +package nccloud.openapi; + + +import com.alibaba.fastjson.JSONObject; +import nc.ws.opm.pub.utils.security.SecurityUtil; +import nccloud.openapi.BaseOpenApiTest.HttpClientWapper.Response; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.commons.httpclient.util.EncodingUtil; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.io.ClassPathResource; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import java.io.*; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.security.spec.X509EncodedKeySpec; +import java.util.*; +import java.util.Map.Entry; + +/** + * @description: 审批流程接口测试 + * @author:guoxqc@yonyou.com + * @date:2020年10月23日 + */ +public class BaseOpenApiTest { + // public static final String BASE_URL_DEV="http://192.168.82.5:9999"; + public static final String BASE_URL_DEV = "http://127.0.0.1:8088"; +// public static final String BASE_URL_DEV = "http://192.168.82.104:7788"; +// public static final String BASE_URL_DEV="http://192.168.82.1:9081"; +// public static final String BASE_URL_DEV="http://172.23.17.146:8001"; + /** + * APP ID + */ + public static final String CLIENT_ID; + /** + * APP Secret + */ + public static final String CLIENT_SECRET; + /** + * 公钥 + */ + public static final String PUBLIC_KEY; + /** + * 账套编码 + */ + public static final String BIZ_CENTER; + /** + * 用户编码 + */ + public static final String USER_CODE; + + static { + ResourceBundle config = ResourceBundle.getBundle("nccloud.openapi.config"); + CLIENT_ID = config.getString("client_id"); + CLIENT_SECRET = config.getString("client_secret"); + PUBLIC_KEY = config.getString("pub_key"); + BIZ_CENTER = config.getString("biz_center"); + USER_CODE = config.getString("user_code"); + } + + public HttpClientWapper client = new HttpClientWapper(); + + /** + * @param url + * @param param + * @return + * @throws Exception + */ + public String requestOpenApi(String url, Map param) throws Exception { + return requestOpenApi(url, new JSONObject(param)); + } + + /** + * @param url + * @param param + * @return + * @throws Exception + */ + public String requestOpenApi(String url, JSONObject param) throws Exception { + return requestOpenApi(url, param.toJSONString()); + } + + /** + * @param url + * @param fileName + * @return + * @throws Exception + */ + public String requestOpenApiByJSON(String url, String fileName) throws Exception { + ClassPathResource classPathResorce = new ClassPathResource(fileName, this.getClass()); + StringBuffer data = new StringBuffer(); + try { + InputStream in = classPathResorce.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); + String line = reader.readLine(); + while (StringUtils.isNotEmpty(line)) { + data.append(line); + line = reader.readLine(); + } + } catch (IOException e1) { + e1.printStackTrace(); + } + return requestOpenApi(url, data.toString()); + } + + public String requestOpenApi(String url, String param) throws Exception { + String accessToken = this.getAccessTokenByClient(); + System.out.println(param.replace(" ", "")); + String sign = digest(CLIENT_ID + PUBLIC_KEY); + List
headers = new ArrayList
(); + headers.add(new Header("Content-Type", "application/json;charset=UTF-8")); + headers.add(new Header("signature", sign)); + headers.add(new Header("ucg_flag", "y")); + headers.add(new Header("access_token", accessToken)); + headers.add(new Header("client_id", CLIENT_ID)); + Response response; + try { + response = client.post(BASE_URL_DEV + url, headers.toArray(new Header[headers.size()]), null, param); +// System.out.println(response.getData()); + return response.getData(); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + return e.getMessage(); + } + } + + /** + * @param seed 种子,用于生成公钥 + * @param src 明文 + * @return + * @throws Exception + * @description RSA加密 + */ + public String pubEncrypt(String seed, String src) throws Exception { + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = genPublicKey(PUBLIC_KEY); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(1, key); + byte[] data = src.getBytes(); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + int i = 0; + while (inputLen - offSet > 0) { + byte[] cache; + ; + if (inputLen - offSet > 117) { + cache = cipher.doFinal(data, offSet, 117); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * 117; + } + target = new BASE64Encoder().encodeBuffer(out.toByteArray()); + } catch (Exception e) { + throw new Exception("加密失败" + e.getMessage()); + } finally { + if (out != null) { + out.close(); + } + } + return target; + } + + /** + * @param str + * @return + * @description 信息摘要 + */ + public static String digest(String str) { + String encodestr = ""; + try { + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); + encodestr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return encodestr; + } + + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i = 0; i < bytes.length; i++) { + temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + + /** + * @param PUBLIC_KEY + * @return + * @throws Exception + * @description 根据种子生成密钥对 + */ + public static Key genPublicKey(String seed) throws Exception { + Key key = null; + try { + byte[] keyBytes = new BASE64Decoder().decodeBuffer(seed); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); + key = keyFactory.generatePublic(x509KeySpec); + } catch (Exception e) { + throw new Exception("无效的密钥 " + e.getMessage()); + } + return key; + } + + /** + * Http请求包装类 + * + * @author guoxiangqiao + * @date 2019年12月11日 + */ + public class HttpClientWapper { + public static final int HTTP_STATUS_SUCCESS = 200; + + /** + * post请求 + * + * @param url + * @param headers + * @param requestBody + * @return + * @throws Exception + */ + public Response post(String url, Header[] headers, NameValuePair[] requestBody, String requestEntityStr) throws Exception { + HttpClient client = new HttpClient(); + PostMethod postMethod = new PostMethod(url); + if (headers != null) { + for (Header header : headers) { + postMethod.setRequestHeader(header); + } + } + if (requestBody != null) { + postMethod.setRequestBody(requestBody); + } + if (StringUtils.isNotEmpty(requestEntityStr)) { + StringRequestEntity requestEntity = new StringRequestEntity(requestEntityStr, null, "utf-8"); + postMethod.setRequestEntity(requestEntity); + } + int httpStatus = client.executeMethod(postMethod); + String result = this.getResponseBodyAsString(postMethod); + return new Response(httpStatus, result); + } + + public String getResponseBodyAsString(PostMethod postMethod) throws IOException { + byte[] rawdata = null; + rawdata = postMethod.getResponseBody(); + return rawdata != null ? EncodingUtil.getString(rawdata, "utf-8") : null; + } + + /** + * @param params + * @return + * @description Map转URL参数 + * @author guoxqc@yonyou.com + * @date 2020年10月22日 + */ + public String getURLParam(Map params) { + StringBuffer paramStr = new StringBuffer(); + if (!params.isEmpty()) { + for (Entry kv : params.entrySet()) { + paramStr.append(kv.getKey()); + paramStr.append("="); + paramStr.append(kv.getValue()); + paramStr.append("&"); + } + paramStr.deleteCharAt(paramStr.length() - 1); + } + return paramStr.toString(); + } + + /** + * get请求 + * + * @param url + * @param headers + * @param params + * @return + * @throws Exception + */ + public Response get(String url, Header[] headers, NameValuePair[] params) throws Exception { + HttpClient client = new HttpClient(); + GetMethod getMethod = new GetMethod(url); + if (params != null) { + getMethod.setQueryString(params); + } + if (headers != null) { + for (Header header : headers) { + getMethod.setRequestHeader(header); + } + } + int httpStatus = client.executeMethod(getMethod); + String result = getMethod.getResponseBodyAsString(); + return new Response(httpStatus, result); + } + + /** + * 获取url查询参数 + * + * @param params + * @return + */ + public String getQueryString(NameValuePair[] params) { + GetMethod getMethod = new GetMethod(); + getMethod.setQueryString(params); + return getMethod.getQueryString(); + } + + class Response { + private int httpStatus; + private String data; + + public int getHttpStatus() { + return httpStatus; + } + + public void setHttpStatus(int httpStatus) { + this.httpStatus = httpStatus; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Response(int httpStatus, String data) { + super(); + this.httpStatus = httpStatus; + this.data = data; + } + + public Response() { + super(); + } + } + } + + public static String getSHA256(String str, String key) throws Exception { + byte[] salt = new byte[16]; + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(key.getBytes()); + random.nextBytes(salt); + String salt_value = new BASE64Encoder().encodeBuffer(salt); + return digest(str + salt_value.replaceAll("\r|\n", "")); + } + + /** + * @return + * @throws Exception + * @description 获取AccessToken + */ + @SuppressWarnings("static-access") + public String getAccessTokenByClient() throws Exception { + String url = BASE_URL_DEV + "/nccloud/opm/accesstoken"; + List
headers = new ArrayList
(); + headers.add(new Header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")); + // 获取信息摘要 + String signature = getSHA256(CLIENT_ID + CLIENT_SECRET + PUBLIC_KEY, PUBLIC_KEY); + // 使用PUBLIC_KEY生成公钥,对CLIENT_SECRET加密 + SecurityUtil securityUtil = new SecurityUtil(); + String CLIENT_SECRETEn = URLEncoder.encode(securityUtil.pubEncrypt(PUBLIC_KEY, CLIENT_SECRET), "utf-8"); + Map params = new HashMap(); + params.put("client_id", CLIENT_ID); + params.put("userCode", USER_CODE); + params.put("grant_type", "client_credentials"); + params.put("biz_center", BIZ_CENTER); + params.put("signature", signature); + params.put("client_secret", CLIENT_SECRETEn); + try { + Response response = client.post(url, headers.toArray(new Header[headers.size()]), null, client.getURLParam(params)); + System.out.println(response.getData()); + JSONObject result = JSONObject.parseObject(response.getData()); + boolean success = result.getBoolean("success"); + if (success) { + return result.getJSONObject("data").getString("access_token"); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java b/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java new file mode 100644 index 0000000..e69de29 diff --git a/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java b/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java new file mode 100644 index 0000000..e69de29 diff --git a/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java b/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java new file mode 100644 index 0000000..09c1b65 --- /dev/null +++ b/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java @@ -0,0 +1,403 @@ +package nccloud.api.impl.so.m30; + +import nc.bd.itf.tools.BFPubTools; +import nc.bs.dao.BaseDAO; +import nc.bs.framework.common.NCLocator; +import nc.itf.fi.pub.Currency; +import nc.itf.scmpub.reference.uap.pf.PfServiceScmUtil; +import nc.itf.so.m30.self.ISaleOrderMaintain; +import nc.itf.so.m30.self.ISaleOrderScriptMaintain; +import nc.itf.uap.pf.IPFBusiAction; +import nc.jdbc.framework.processor.ColumnProcessor; +import nc.pubitf.so.m30.api.ISaleOrderQueryAPI; +import nc.vo.ml.NCLangRes4VoTransl; +import nc.vo.pub.BusinessException; +import nc.vo.pub.VOStatus; +import nc.vo.pub.lang.UFBoolean; +import nc.vo.pub.lang.UFDate; +import nc.vo.pub.lang.UFDouble; +import nc.vo.pubapp.pattern.exception.ExceptionUtils; +import nc.vo.pubapp.pflow.PfUserObject; +import nc.vo.scmpub.check.billvalidate.BillVOsCheckRule; +import nc.vo.scmpub.res.billtype.SOBillType; +import nc.vo.scmpub.util.StringUtil; +import nc.vo.so.m30.entity.SaleOrderBVO; +import nc.vo.so.m30.entity.SaleOrderHVO; +import nc.vo.so.m30.entity.SaleOrderVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryBVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryHVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryVO; +import nc.vo.so.pub.SOConstant; +import nc.vo.so.pub.keyvalue.IKeyValue; +import nc.vo.so.pub.keyvalue.VOKeyValue; +import nc.vo.so.pub.util.AggVOUtil; +import nc.vo.so.pub.util.SOCurrencyUtil; +import nccloud.api.impl.so.m30.check.SaleOrderValidator; +import nccloud.api.impl.so.m30.fill.SaleOrderSaveFillValue; +import nccloud.api.impl.so.m30.fill.SetUpdateData; +import nccloud.api.so.m30.IAPISaleOrderMaitain; +import nccloud.baseapp.core.log.NCCForUAPLogger; +import nccloud.dto.scmpub.pflow.SCMCloudPFlowContext; +import nccloud.pubitf.scmpub.commit.service.IBatchRunScriptService; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * @Description: 销售订单维护实现类 + * @author: yanghff + * @date: 2019-10-23 下午4:57:49 + * @Copyright: + */ +public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { + + @Override + public SaleOrderVO[] save(SaleOrderVO[] vos) throws BusinessException { + + SaleOrderVO[] fillvos = vos; + // 检查非空项 + for (SaleOrderVO vo : vos) { + SaleOrderHVO hvo = vo.getParentVO(); + String corigcurrencyid = hvo.getCorigcurrencyid(); + UFDate dbilldate = hvo.getDbilldate(); + SaleOrderBVO[] bvos = vo.getChildrenVO(); + String sql = " select bd_currtype.pk_currtype from bd_currtype where (code='" + hvo.getCorigcurrencyid() + "' or pk_currtype='" + hvo.getCorigcurrencyid() + "') and dr=0 "; + Object o = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + if (o != null) { + hvo.setCorigcurrencyid(BFPubTools.getString_TrimAsNull(o)); + } else { + throw new BusinessException("表头币种不能为空或币种不存在"); + } + sql = " select bd_currtype.pk_currtype from bd_currtype where (code='" + bvos[0].getCcurrencyid() + "' or pk_currtype='" + bvos[0].getCcurrencyid() + "') and dr=0 "; + Object o1 = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + if (o1 == null) { + throw new BusinessException("表体币种不能为空或币种不存在"); + } + String csettleorgid = bvos[0].getCsettleorgid(); + String ccurrencyorgid = o1.toString(); + UFDouble exchangerate = SOCurrencyUtil.getInCurrencyRateByOrg(csettleorgid, BFPubTools.getString_TrimAsNull(o), ccurrencyorgid, dbilldate); + for (SaleOrderBVO bvo : bvos) { + bvo.setCcurrencyid(BFPubTools.getString_TrimAsNull(o1)); + if (!BFPubTools.getString_TrimAsNull(o).equals(ccurrencyorgid)) { + bvo.setNexchangerate(exchangerate); + } else { + bvo.setNexchangerate(UFDouble.ONE_DBL); + } + + } + +// bvo.setNexchangerate(rateReturnObject.getRate()); +// bvo.setCratetype(rateReturnObject.getPk_ratetype()); +// bvo.setFratecategory( rateReturnObject.getRate_category()); +// bvo.setDratedate( rateReturnObject.getDate()); + + } + + + BillVOsCheckRule checker = new BillVOsCheckRule(new SaleOrderValidator()); + checker.check(vos); + // 填充默认值 + new SaleOrderSaveFillValue().setDefValue(vos); + // 有值不覆盖 + for (SaleOrderVO ordervo : vos) { + calculatorPrice(ordervo); + } + + SaleOrderVO[] combinBillVOs = + (SaleOrderVO[]) AggVOUtil.combinBillVO(fillvos, vos); + // 保存 + SaleOrderVO[] retvos = + (SaleOrderVO[]) PfServiceScmUtil.processBatch(SOConstant.WRITE, + SOBillType.Order.getCode(), combinBillVOs, null, null); + + SaleOrderVO[] billvos = ((ISaleOrderQueryAPI) NCLocator.getInstance().lookup(ISaleOrderQueryAPI.class)).queryVOByIDs(new String[]{retvos[0].getParentVO().getPrimaryKey()}); + if (billvos != null) { + ((IPFBusiAction) NCLocator.getInstance().lookup(IPFBusiAction.class)).processAction("APPROVE", billvos[0].getParentVO().getVtrantypecode(), null, billvos[0], null, null); + } + return retvos; + } + + public void calculatorPrice(SaleOrderVO ordervo) throws BusinessException { + + + IKeyValue keyValue = new VOKeyValue(ordervo); + + + String ctrantypeid = keyValue.getHeadStringValue(SaleOrderHVO.CTRANTYPEID); + if (StringUtil.isEmptyTrimSpace(ctrantypeid)) { + ExceptionUtils.wrappBusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006013_0", "04006013-0024")/*@res "请先选择交易类型!"*/); + } + // 1.缓存交易类型VO + + SaleOrderBVO[] vbos = ordervo.getChildrenVO(); + UFDouble sumnum = UFDouble.ZERO_DBL; + UFDouble sumnny = UFDouble.ZERO_DBL; + String ybpk = ordervo.getParentVO().getCorigcurrencyid(); + + for (int i = 0; i < vbos.length; i++) { + SaleOrderBVO childrenVO = vbos[i]; + String zbbz = childrenVO.getCcurrencyid(); + + childrenVO.setFtaxtypeflag(1); + //得到税率 + UFDouble ntaxrate = BFPubTools.getUFDouble_NullAsZero(childrenVO.getNtaxrate()); + + // 折本汇率 + UFDouble nexchangerate = childrenVO.getNexchangerate(); + //含税单价 + UFDouble nqtorigtaxprice = childrenVO.getNqtorigtaxprice(); + //无税单价 + UFDouble nqtorigprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); + // 价税合计 + // UFDouble norigtaxmny=nqtorigtaxprice.multiply(childrenVO.getNqtunitnum()); + UFDouble norigtaxmny = nqtorigtaxprice.multiply(childrenVO.getNqtunitnum()).setScale(2, 4); + childrenVO.setNorigtaxmny(norigtaxmny); + //无税金额 + UFDouble norigmny = nqtorigprice.multiply(childrenVO.getNqtunitnum()); + + childrenVO.setNorigmny(Currency.getFormaUfValue(ybpk, norigmny)); + //税额 + childrenVO.setNqtorigprice(nqtorigprice.setScale(4, 4)); + + + //无税本币金额单价 + UFDouble taxspric = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); + + + sumnum = sumnum.add(childrenVO.getNastnum()); + sumnny = sumnny.add(childrenVO.getNorigtaxmny()); + + + nqtorigprice = nqtorigprice.setScale(4, 4); + //nqtorigtaxnetprc--含税净价 + childrenVO.setNqtorigtaxnetprc(nqtorigtaxprice); + //,nqtorignetprice --无税净价 + childrenVO.setNqtorignetprice(nqtorigprice); + String Vqtunitrate = childrenVO.getVqtunitrate(); + UFDouble dVqtunitrate = UFDouble.ONE_DBL; + if (Vqtunitrate != null) { + dVqtunitrate = BFPubTools.getUFDouble_NullAsZero(Vqtunitrate.split("/")[0]); + } + //,norigtaxprice --主含税单价 + + UFDouble wsje = taxspric.multiply(nexchangerate).multiply(childrenVO.getNqtunitnum()); + if (ybpk.equals(zbbz) && BFPubTools.getString_TrimAsNull(childrenVO.getCqtunitid()).equals(BFPubTools.getString_TrimAsNull(childrenVO.getCastunitid()))) { + wsje = taxspric.multiply(nexchangerate).multiply(childrenVO.getNqtunitnum()); + } + + + wsje = Currency.getFormaUfValue(zbbz, wsje); + //本币无税金额 + childrenVO.setNorigtaxprice(nqtorigtaxprice.div(dVqtunitrate).setScale(4, 4)); + //,norigprice --主无税单价 + childrenVO.setNorigprice(nqtorigprice.div(dVqtunitrate).setScale(4, 4)); + //,norigtaxnetprice --主含税净价 + childrenVO.setNorigtaxnetprice(childrenVO.getNorigtaxprice()); + //,norignetprice --主无税净价 + childrenVO.setNorignetprice(childrenVO.getNorigprice()); + // ncaltaxmny --计税金额 + + // ,nqttaxprice --本币含税单价 + childrenVO.setNqttaxprice(nqtorigtaxprice.multiply(nexchangerate)); + //,nqtprice --本币无税单价 + UFDouble bbwsd = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + childrenVO.setNqtprice(bbwsd.setScale(4, 4)); + //, nqttaxnetprice --本币含税净价 + childrenVO.setNqttaxnetprice(nqtorigtaxprice.multiply(nexchangerate)); + //,nqtnetprice --本币无税净价 + UFDouble Nqtnetprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + childrenVO.setNqtnetprice(Nqtnetprice.setScale(4, 4)); + //,ntaxprice --主本币含税单价 , nprice --主本币无税单价 + childrenVO.setNtaxprice(nqtorigtaxprice.div(dVqtunitrate).multiply(nexchangerate).setScale(4, 4)); + UFDouble Nprice = nqtorigtaxprice.div(dVqtunitrate).div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + childrenVO.setNprice(Nprice.setScale(4, 4)); + //,ntaxnetprice --主本币含税净价 + //,nnetprice --主本币无税净价 + childrenVO.setNtaxnetprice(nqtorigtaxprice.div(dVqtunitrate).multiply(nexchangerate).setScale(4, 4)); + UFDouble Nnetprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).div(dVqtunitrate); + childrenVO.setNnetprice(Nnetprice.multiply(nexchangerate).setScale(4, 4)); +// ,nmny --本币无税金额 +// ,ntaxmny --本币价税合计 + childrenVO.setNmny(Currency.getFormaUfValue(zbbz, norigmny.multiply(nexchangerate))); + childrenVO.setNtaxmny(nqtorigtaxprice.multiply(nexchangerate).multiply(childrenVO.getNqtunitnum()).setScale(2, 4)); +// childrenVO.setNtaxmny(nqtorigtaxprice.multiply(nexchangerate).multiply(childrenVO.getNqtunitnum())); + childrenVO.setNcaltaxmny(wsje); + UFDouble ntax = norigtaxmny.multiply(nexchangerate).sub(wsje); + childrenVO.setNtax(ntax.setScale(2, 4)); + } + ordervo.getParentVO().setNtotalnum(sumnum); +// ordervo.getParentVO().setNtotalorigmny(sumnny); + ordervo.getParentVO().setNtotalorigmny(sumnny.setScale(2, 4)); + } + + + @Override + public SaleOrderVO[] update(SaleOrderVO[] vos) throws BusinessException { + + // 获取参数vo的id + Map> ids = this.getIds(vos); + if (ids.keySet() == null || ids.values() == null + || ids.values().size() == 0) { + ExceptionUtils.wrappBusinessException("请传入订单主键和订单行主键"); + } + String[] hids = ids.keySet().toArray(new String[ids.keySet().size()]); + // 查询销售订单 + ISaleOrderMaintain service = + NCLocator.getInstance().lookup(ISaleOrderMaintain.class); + SaleOrderVO[] originVos = service.querySaleorder(hids); + SetUpdateData setData = new SetUpdateData(); + setData.setData(vos, originVos); + setOtherId(vos); + // 有值不覆盖 + SaleOrderVO[] combinBillVOs = + (SaleOrderVO[]) AggVOUtil.combinBillVO(vos, originVos); + // 设置单据状态 + for (SaleOrderVO vo : vos) { + vo.getParentVO().setStatus(VOStatus.UPDATED); + for (SaleOrderBVO bvo : vo.getChildrenVO()) { + bvo.setStatus(VOStatus.UPDATED); + } + } + // 保存 + ISaleOrderScriptMaintain maintainsrv = + NCLocator.getInstance().lookup(ISaleOrderScriptMaintain.class); + SaleOrderVO[] retvos = + maintainsrv.saleOrderUpdate(combinBillVOs, null, originVos); + return retvos; + } + + /** + * @Description: 获取参数vo的id + * @date: 2019-11-1 上午10:31:42 + * @version NCC1909 + */ + private Map> getIds(SaleOrderVO[] vos) { + Map> ids = new HashMap>(); + for (SaleOrderVO vo : vos) { + String hid = vo.getParentVO().getCsaleorderid(); + Set bids = new HashSet(); + for (SaleOrderBVO bvo : vo.getChildrenVO()) { + bids.add(bvo.getCsaleorderbid()); + } + ids.put(hid, bids); + } + return ids; + } + + private void setOtherId(SaleOrderVO[] vos) { + for (SaleOrderVO vo : vos) { + // 部门、业务员、开票客户编码转id + String cdeptvid = vo.getParentVO().getCdeptvid(); + String cemployeeid = vo.getParentVO().getCdeptvid(); + String cinvoicecustid = vo.getParentVO().getCdeptvid(); + try { + String sql = ""; + // 部门 + if (cdeptvid != null && !cdeptvid.isEmpty()) { + sql = " select pk_dept from org_dept where code = '[code]' "; + sql = sql.replace("[code]", cdeptvid); + Object deptObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-deptObj:" + deptObj); + if (deptObj != null) { + String id = BFPubTools.getString_TrimAsNull(deptObj); + if (!id.isEmpty()) { + vo.getParentVO().setCdeptvid(id); + } + } + } + // 业务员 + if (cemployeeid != null && !cemployeeid.isEmpty()) { + sql = " select pk_psndoc from bd_psndoc where code = '[code]' "; + sql = sql.replace("[code]", cemployeeid); + Object staffObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-staffObj:" + staffObj); + if (staffObj != null) { + String id = BFPubTools.getString_TrimAsNull(staffObj); + if (!id.isEmpty()) { + vo.getParentVO().setCdeptvid(id); + } + } + } + // 开票客户 + if (cinvoicecustid != null && !cinvoicecustid.isEmpty()) { + sql = " select pk_customer from bd_customer where code = '[code]' "; + sql = sql.replace("[code]", cinvoicecustid); + Object invCustObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-invCustObj:" + invCustObj); + if (invCustObj != null) { + String id = BFPubTools.getString_TrimAsNull(invCustObj); + if (!id.isEmpty()) { + vo.getParentVO().setCdeptvid(id); + } + } + } + } catch (Exception e) { + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-exp:" + e.getMessage()); + throw new RuntimeException(e); + } + } + } + + + @Override + public SaleOrderVO[] modify(SaleOrderHistoryVO[] vos) throws BusinessException { + for (SaleOrderHistoryVO vo : vos) { + SaleOrderHistoryHVO hvo = vo.getParentVO(); + UFDate dbilldate = hvo.getDbilldate(); + SaleOrderHistoryBVO[] bvos = vo.getChildrenVO(); + String sql = " select bd_currtype.pk_currtype from bd_currtype where (code='" + hvo.getCorigcurrencyid() + "' or pk_currtype='" + hvo.getCorigcurrencyid() + "') and dr=0 "; + Object o = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + if (o != null) { + hvo.setCorigcurrencyid(BFPubTools.getString_TrimAsNull(o)); + } else { + throw new BusinessException("表头币种不能为空或币种不存在"); + } + sql = " select bd_currtype.pk_currtype from bd_currtype where (code='" + bvos[0].getCcurrencyid() + "' or pk_currtype='" + bvos[0].getCcurrencyid() + "') and dr=0 "; + Object o1 = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + if (o1 == null) { + throw new BusinessException("表体币种不能为空或币种不存在"); + } + String csettleorgid = bvos[0].getCsettleorgid(); + String ccurrencyorgid = o1.toString(); + UFDouble exchangerate = SOCurrencyUtil.getInCurrencyRateByOrg(csettleorgid, BFPubTools.getString_TrimAsNull(o), ccurrencyorgid, dbilldate); + for (SaleOrderHistoryBVO bvo : bvos) { + bvo.setCcurrencyid(BFPubTools.getString_TrimAsNull(o1)); + if (!BFPubTools.getString_TrimAsNull(o).equals(ccurrencyorgid)) { + bvo.setNexchangerate(exchangerate); + } else { + bvo.setNexchangerate(UFDouble.ONE_DBL); + } + + } + } + for (SaleOrderVO ordervo : vos) { + calculatorPrice(ordervo); + } + Map eParam = new HashMap(); + eParam.put("nolockandconsist", UFBoolean.TRUE); + + SCMCloudPFlowContext context = new SCMCloudPFlowContext(); + context.setBillType(SOBillType.Order30R.getCode()); + PfUserObject userObject = new PfUserObject(); + userObject.setUserObject(null); + context.seteParam(eParam); + context.setUserObj(new PfUserObject[]{userObject}); + context.setBillVos(vos); + context.setActionName("REVISEWRITE"); + IBatchRunScriptService service2 = (IBatchRunScriptService) NCLocator.getInstance().lookup(IBatchRunScriptService.class); + SaleOrderHistoryVO[] objects = (SaleOrderHistoryVO[]) service2.run(context, SaleOrderHistoryVO.class); + + + return (SaleOrderVO[]) NCLocator.getInstance().lookup(IPFBusiAction.class).processAction("APPROVE", "30R", null, objects[0], null, null); + } + + private void cheageHVo(SaleOrderHistoryVO billvo, SaleOrderVO saleOrderVO) { + SaleOrderHistoryHVO hvo = billvo.getParentVO(); + SaleOrderHVO oldvo = saleOrderVO.getParentVO(); + hvo.setCinvoicecustid(oldvo.getCinvoicecustid()); + hvo.setCemployeeid(oldvo.getCemployeeid()); + } + +} diff --git a/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java b/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java new file mode 100644 index 0000000..e69de29 diff --git a/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java b/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java new file mode 100644 index 0000000..e69de29 diff --git a/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java b/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java new file mode 100644 index 0000000..e69de29 From 7309d459d84a747201d8983ff0b0f7f56c597c3b Mon Sep 17 00:00:00 2001 From: hefengkai <958118178@qq.com> Date: Tue, 4 Mar 2025 18:00:02 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E6=9C=80=E6=96=B0=E4=BB=B7=E6=A0=BC?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../supplierprice/rule/SupPriceQryRule.java | 231 ++++++++++++++++++ .../nc/vo/pp/report/util/PurpRptUtils.java | 178 ++++++++++++++ 2 files changed, 409 insertions(+) diff --git a/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java b/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java index e69de29..ded25e4 100644 --- a/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java +++ b/purp/src/private/nc/impl/pp/supplierprice/rule/SupPriceQryRule.java @@ -0,0 +1,231 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package nc.impl.pp.supplierprice.rule; + +import nc.vo.pp.report.entity.PurpReportTransMap; +import nc.vo.pp.report.util.PurpRptUtils; +import nc.vo.pp.supplierprice.entity.SupPriceRptConst; +import nc.vo.pp.util.StringUtils; +import nc.vo.pub.lang.UFDate; +import nc.vo.pub.query.ConditionVO; +import nc.vo.pubapp.AppContext; +import nc.vo.scmpub.util.ArrayUtil; +import nc.vo.util.CloneUtil; + +import java.util.ArrayList; +import java.util.List; + +public class SupPriceQryRule { + public SupPriceQryRule() { + } + + public String getWhereCtForHis(PurpReportTransMap tranMap, PurpRptUtils rptutils, String htablealias, String btablealias) { + ConditionVO[] convos = this.getInitQryCondVOs(tranMap, rptutils); + if (ArrayUtil.isEmpty(convos)) { + return ""; + } else { + ConditionVO[] copyconvos = (ConditionVO[]) CloneUtil.deepClone(convos); + List list = new ArrayList(); + for (ConditionVO vo : copyconvos) { + if (vo.getFieldCode().equals("pk_supplier")) { + vo.setFieldCode(htablealias + ".cvendorid"); + list.add(vo); + } else if (vo.getFieldCode().equals("tcreatetime")) { + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + + vo.setFieldCode(htablealias + ".creationtime"); + list.add(vo); + } else if (!vo.getFieldCode().equals("fpricesrctype")) { + if (vo.getFieldCode().equals("dvaliddate")) { + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + + vo.setFieldCode(htablealias + ".dbilldate"); + list.add(vo); + } else if (vo.getFieldCode().equals("dinvaliddate")) { + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + } else { + vo.setFieldCode(htablealias + "." + vo.getFieldCode()); + list.add(vo); + } + } + } + + StringBuilder sql = new StringBuilder(""); + sql.append((new ConditionVO()).getSQLStr((ConditionVO[]) list.toArray(new ConditionVO[list.size()]))); + this.addMarWhere(sql, tranMap, rptutils, btablealias); + return sql.toString(); + } + } + + public String getWhereCtForNew(PurpReportTransMap tranMap, PurpRptUtils rptutils, String htablealias, String btablealias) { + ConditionVO[] convos = this.getInitQryCondVOs(tranMap, rptutils); + if (ArrayUtil.isEmpty(convos)) { + return ""; + } else { + ConditionVO[] copyconvos = (ConditionVO[]) CloneUtil.deepClone(convos); + List list = new ArrayList(); + for (ConditionVO vo : copyconvos) { + if (vo.getFieldCode().equals(SupPriceRptConst.DBUSINESSDATE)) { + int month = Integer.valueOf(vo.getValue()); + UFDate curdate = AppContext.getInstance().getBusiDate(); + UFDate befdate = curdate.getDateBefore(month * 30); + vo.setFieldCode(htablealias + ".dbilldate"); + vo.setOperaCode("between"); + vo.setDataType(3); + vo.setValue(befdate.toString() + " ," + curdate.toString() + " "); + } else if (vo.getFieldCode().equals("pk_supplier")) { + vo.setFieldCode(htablealias + ".cvendorid"); + } else if (vo.getFieldCode().equalsIgnoreCase("memo")) { + tranMap.put("memo", vo); + } else { + vo.setFieldCode(htablealias + "." + vo.getFieldCode()); + } + if (!vo.getFieldCode().equalsIgnoreCase("memo")) { + list.add(vo); + } + } + + StringBuilder sql = new StringBuilder(""); + ConditionVO[] array = list.toArray(new ConditionVO[0]); + sql.append((new ConditionVO()).getSQLStr(array)); + this.addMarWhere(sql, tranMap, rptutils, btablealias); + return sql.toString(); + } + } + + public String getWhereOrderForHis(PurpReportTransMap tranMap, PurpRptUtils rptutils, String htablealias, String btablealias) { + List list = new ArrayList(); + ConditionVO[] convos = this.getInitQryCondVOs(tranMap, rptutils); + if (ArrayUtil.isEmpty(convos)) { + return ""; + } else { + ConditionVO[] convosCt = (ConditionVO[]) CloneUtil.deepClone(convos); + + for (ConditionVO vo : convosCt) { + if (!vo.getFieldCode().equals("bsc") && !vo.getFieldCode().equals("fpricesrctype")) { + if (vo.getFieldCode().equals("dinvaliddate")) { + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + } else if (vo.getFieldCode().equals("dvaliddate")) { + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + } else if (vo.getFieldCode().equals("tcreatetime")) { + vo.setFieldCode(htablealias + ".creationtime"); + if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + } + + list.add(vo); + } else { + vo.setFieldCode(htablealias + "." + vo.getFieldCode()); + list.add(vo); + } + } + } + + StringBuilder sql = new StringBuilder(""); + sql.append((new ConditionVO()).getSQLStr((ConditionVO[]) list.toArray(new ConditionVO[list.size()]))); + this.addMarWhere(sql, tranMap, rptutils, btablealias); + return sql.toString(); + } + } + + public String getWhereOrderForNew(PurpReportTransMap tranMap, PurpRptUtils rptutils, String htablealias, String btablealias) { + List list = new ArrayList(); + ConditionVO[] convos = this.getInitQryCondVOs(tranMap, rptutils); + ConditionVO[] convosCt = (ConditionVO[]) CloneUtil.deepClone(convos); + + for (ConditionVO vo : convosCt) { + if (vo.getFieldCode().equals(SupPriceRptConst.DBUSINESSDATE)) { + int month = Integer.valueOf(vo.getValue()); + UFDate curdate = AppContext.getInstance().getBusiDate(); + UFDate befdate = curdate.getDateBefore(month * 30); + vo.setFieldCode(htablealias + ".dbilldate"); + vo.setOperaCode("between"); + vo.setDataType(3); + vo.setValue(befdate.toString() + " ," + curdate.toString() + " "); + list.add(vo); + } else if (vo.getFieldCode().equalsIgnoreCase("memo")) { + tranMap.put("memo", vo); + } else if (!vo.getFieldCode().equals("bsc")) { + vo.setFieldCode(htablealias + "." + vo.getFieldCode()); + list.add(vo); + } + } + + StringBuilder sql = new StringBuilder(""); + sql.append((new ConditionVO()).getSQLStr((ConditionVO[]) list.toArray(new ConditionVO[list.size()]))); + this.addMarWhere(sql, tranMap, rptutils, btablealias); + return sql.toString(); + } + + public String getWhereSupPrice(PurpReportTransMap tranMap, PurpRptUtils rptutils, String tablealias) { + ConditionVO[] convos = this.getInitQryCondVOs(tranMap, rptutils); + if (ArrayUtil.isEmpty(convos)) { + return ""; + } else { + ConditionVO[] copyconvos = (ConditionVO[]) CloneUtil.deepClone(convos); + List list = new ArrayList(); + for (ConditionVO vo : copyconvos) { + if (vo.getFieldCode().equals(SupPriceRptConst.DBUSINESSDATE)) { + int month = Integer.valueOf(vo.getValue()); + UFDate curdate = AppContext.getInstance().getBusiDate(); + UFDate befdate = curdate.getDateBefore(month * 30); + vo.setFieldCode(tablealias + ".dvaliddate"); + vo.setOperaCode("between"); + vo.setDataType(3); + vo.setValue(befdate.toString() + " ," + curdate.toString() + " "); + } else if (vo.getDataType() == 3 && vo.getOperaCode().equalsIgnoreCase("=")) { + UFDate date = new UFDate(vo.getValue()); + vo.setValue(date.toLocalString()); + vo.setFieldCode(tablealias + "." + vo.getFieldCode()); + } else if (vo.getFieldCode().equalsIgnoreCase("memo")) { + tranMap.put("memo", vo); + } else { + vo.setFieldCode(tablealias + "." + vo.getFieldCode()); + } + if (!vo.getFieldCode().equalsIgnoreCase("memo")) { + list.add(vo); + } + } + + StringBuilder sql = new StringBuilder(""); + ConditionVO[] array = list.toArray(new ConditionVO[0]); + sql.append((new ConditionVO()).getSQLStr(array)); + this.addMarWhere(sql, tranMap, rptutils, tablealias); + return sql.toString(); + } + } + + private void addMarWhere(StringBuilder sql, PurpReportTransMap tranMap, PurpRptUtils rptutils, String btablealias) { + String[] marQryKeys = new String[]{SupPriceRptConst.MARBASCLASS, SupPriceRptConst.MATERIALCODE, SupPriceRptConst.MARTERIALNAME}; + String marwhere = rptutils.getWhereForMar(tranMap, btablealias, marQryKeys); + if (!StringUtils.isEmpty(marwhere)) { + sql.append(" and " + marwhere); + } + + } + + private ConditionVO[] getInitQryCondVOs(PurpReportTransMap tranMap, PurpRptUtils rptutils) { + ConditionVO[] generalvos = tranMap.getConditionVOs(SupPriceRptConst.SUPPRICE_GENERALCOND); + ConditionVO[] logicalvos = tranMap.getConditionVOs(SupPriceRptConst.SUPPRICE_LOGICALCOND); + return rptutils.combineCondVOs(generalvos, logicalvos); + } +} diff --git a/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java b/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java index e69de29..2a0f902 100644 --- a/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java +++ b/purp/src/public/nc/vo/pp/report/util/PurpRptUtils.java @@ -0,0 +1,178 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package nc.vo.pp.report.util; + +import nc.bs.ic.icreport.pub.RPMetaDataUtil; +import nc.bs.pubapp.report.ReportPermissionUtils; +import nc.pub.smart.context.SmartContext; +import nc.pub.smart.data.DataSet; +import nc.pub.smart.metadata.MetaData; +import nc.vo.ml.MultiLangUtil; +import nc.vo.ml.NCLangRes4VoTransl; +import nc.vo.pp.report.entity.PurpReportTransMap; +import nc.vo.pub.ISuperVO; +import nc.vo.pub.query.ConditionVO; +import nc.vo.pubapp.pattern.model.entity.view.AbstractDataView; +import nc.vo.pubapp.pattern.model.meta.entity.view.IDataViewMeta; +import nc.vo.scmbd.pub.SCMESAPI; +import nc.vo.scmpub.util.ArrayUtil; + +import java.util.HashMap; +import java.util.Map; + +public class PurpRptUtils { + public static final int UFDATEDATATIMETYPE = 8; + public static final int UFDATEDATATYPE = 3; + + public PurpRptUtils() { + } + + public ConditionVO[] combineCondVOs(ConditionVO[] generalvos, ConditionVO[] logicalvos) { + ConditionVO[] endvos = null; + if (!ArrayUtil.isEmpty(generalvos)) { + endvos = generalvos; + } + + if (!ArrayUtil.isEmpty(logicalvos) && ArrayUtil.isEmpty(endvos)) { + endvos = logicalvos; + } else if (!ArrayUtil.isEmpty(logicalvos) && endvos != null && endvos.length > 0) { + System.arraycopy(logicalvos, 0, endvos, endvos.length, logicalvos.length); + } + + return endvos; + } + + public DataSet convertDataSet(IDataViewMeta md, AbstractDataView[] vos) { + String[] fields = md.getAttributeNames(); + MetaData mtd = new MetaData(); + RPMetaDataUtil.addVOMetaFieldByKeys(mtd, md, fields); + if (vos != null && vos.length > 0) { + Object[][] datas = new Object[vos.length][fields.length]; + + for (int i = 0; i < vos.length; ++i) { + if (vos[i] != null) { + for (int k = 0; k < fields.length; ++k) { + datas[i][k] = vos[i].getAttributeValue(fields[k]); + } + } + } + + return new DataSet(mtd, datas); + } else { + DataSet ds = new DataSet(); + ds.setMetaData(mtd); + return ds; + } + } + + public String getChnNo() { + return NCLangRes4VoTransl.getNCLangRes().getStrByID("40050004", "1400500040031"); + } + + public String getChnYes() { + return NCLangRes4VoTransl.getNCLangRes().getStrByID("40050004", "1400500040030"); + } + + public String getPermisionInnerJoin(SmartContext context, Class marclass, String btablealias) { + ReportPermissionUtils utils = new ReportPermissionUtils(context); + Map, String> beanMap = new HashMap(); + beanMap.put(marclass, btablealias); + return utils.getPermissionSQL(beanMap); + } + + public String getWhereForMar(PurpReportTransMap tranMap, String btablealias, String[] marQryKeys) { + String marclassKey = marQryKeys[0]; + String marcodeKey = marQryKeys[1]; + String marnameKey = marQryKeys[2]; + ConditionVO codeVO = this.getMarCondVO(tranMap, marcodeKey); + ConditionVO nameVO = this.getMarCondVO(tranMap, marnameKey); + ConditionVO classVO = this.getMarCondVO(tranMap, marclassKey); + boolean flag = tranMap.get("memo") == null; + if (null == codeVO && null == nameVO && null == classVO && flag) { + return ""; + } else { + StringBuilder wheresql = new StringBuilder(); + wheresql.append(btablealias + ".pk_material in ( select bd_material.pk_material from bd_material bd_material where bd_material.dr=0 "); + if (codeVO != null) { + wheresql.append(" and "); + this.setMarWhere(codeVO, "bd_material.code", wheresql); + } + + if (nameVO != null) { + String langseq = MultiLangUtil.getCurrentLangSeqSuffix(); + wheresql.append(" and "); + this.setMarWhere(nameVO, "bd_material.name" + langseq, wheresql); + } + + if (classVO != null) { + wheresql.append(" and "); + this.setMarWhere(classVO, "bd_material.pk_marbasclass", wheresql); + } + if (!flag) { + ConditionVO memoVo = (ConditionVO) tranMap.get("memo"); + wheresql.append(" and "); + this.setMarWhere(memoVo, "bd_material.memo", wheresql); + } + + wheresql.append(" ) "); + return wheresql.toString(); + } + } + + public ConditionVO updUFDateCondVO(ConditionVO condvo, String qryDlgWhereSql, String dateField) { + if (!qryDlgWhereSql.contains(dateField)) { + return null; + } else { + String[] conds = qryDlgWhereSql.split(dateField); + StringBuilder valueBuilder = new StringBuilder(); + String first = conds[1].split("'")[1]; + if (condvo.getOperaCode().equalsIgnoreCase("between")) { + if (condvo.getValue().toLowerCase().contains("isnull")) { + if (condvo.getValue().toLowerCase().startsWith("isnull")) { + valueBuilder.append(first); + condvo.setOperaCode("<="); + } else { + valueBuilder.append(first); + condvo.setOperaCode(">="); + } + + condvo.setValue(valueBuilder.toString()); + return condvo; + } + + String end = conds[2].split("'")[1]; + valueBuilder.append(first); + valueBuilder.append(","); + valueBuilder.append(end); + } else { + valueBuilder.append(first); + } + + condvo.setValue(valueBuilder.toString()); + return condvo; + } + } + + private ConditionVO getMarCondVO(PurpReportTransMap tranMap, String key) { + ConditionVO[] tempvos = tranMap.getConditionVOs(key); + return ArrayUtil.isEmpty(tempvos) ? null : tempvos[0]; + } + + private void setMarWhere(ConditionVO condvo, String field, StringBuilder wheresql) { + if (condvo.getOperaCode().equals("in")) { + wheresql.append(field + " in " + condvo.getValue()); + } else if (condvo.getOperaCode().equals("=")) { + wheresql.append(field + " = '" + SCMESAPI.sqlEncodeGeneral(condvo.getValue()) + "' "); + } else if (condvo.getOperaCode().equals("left like")) { + String value = condvo.getValue().replaceAll("\\(", "").replaceAll("\\)", ""); + wheresql.append(field + " like '" + SCMESAPI.sqlEncodeGeneral(value) + "%' "); + } else if (condvo.getOperaCode().equals("like")) { + String value = condvo.getValue().replaceAll("\\(", "").replaceAll("\\)", ""); + wheresql.append(field + " like '%" + SCMESAPI.sqlEncodeGeneral(value) + "%' "); + } + + } +} From a46c3275c1605675ea3fc80b84368a19248912da Mon Sep 17 00:00:00 2001 From: mzr <1562242162@qq.com> Date: Tue, 4 Mar 2025 18:03:35 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E6=8E=A5=E6=94=B6BIP=E5=BC=80=E7=A5=A8?= =?UTF-8?q?=E7=94=B3=E8=AF=B7=E7=94=9F=E6=88=90=E9=94=80=E5=94=AE=E5=8F=91?= =?UTF-8?q?=E7=A5=A8-=E6=B1=87=E7=8E=87=E5=8F=8A=E5=B8=81=E7=A7=8D?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../operator/saveCommitAction.java | 422 ++++++++++++++++++ 1 file changed, 422 insertions(+) diff --git a/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java b/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java index e69de29..22687b0 100644 --- a/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java +++ b/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java @@ -0,0 +1,422 @@ +package nccloud.api.so.saleinvoice.operator; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import nc.bs.framework.common.InvocationInfoProxy; +import nc.bs.framework.common.NCLocator; +import nc.bs.framework.core.util.ObjectCreator; +import nc.itf.uap.IUAPQueryBS; +import nc.jdbc.framework.processor.ColumnProcessor; +import nc.jdbc.framework.processor.MapProcessor; +import nc.pubitf.so.m32.api.ISaleinvoiceQueryAPI; +import nc.vo.pub.BusinessException; +import nc.vo.pub.lang.UFDouble; +import nc.vo.pubapp.pattern.model.entity.bill.AbstractBill; +import nc.vo.pubapp.pflow.PfUserObject; +import nc.vo.so.m32.entity.SaleInvoiceHVO; +import nc.vo.so.m32.entity.SaleInvoiceVO; +import nccloud.api.baseapp.exchange.convert.IExchangeForService; +import nccloud.api.baseapp.exchange.convert.OpenApiConvertDataObject; +import nccloud.api.baseapp.exchange.convert.OpenApiConvertDataResult; +import nccloud.api.rest.utils.ResultMessageUtil; +import nccloud.dto.scmpub.script.entity.SCMScriptResultDTO; +import nccloud.dto.scmpub.tax.entity.TaxInvoiceType; +import nccloud.pubitf.riart.pflow.CloudPFlowContext; +import nccloud.pubitf.scmpub.commit.service.IBatchRunScriptService; +import nccloud.pubitf.scmpub.ssc.service.ISSCService; +import nccloud.pubitf.ssctp.sscbd.lientage.ISSClientageMatchService.BusiUnitTypeEnum; +import nccloud.ws.rest.resource.AbstractNCCRestResource; +import org.json.JSONString; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Map; + + +@Path("so/saleinvoice/operator") +public class saveCommitAction extends AbstractNCCRestResource { + + public static String fplxStr = "";// 开票申请发票类型 + + public saveCommitAction() { + + } + + public OpenApiConvertDataResult changeToExchangeData(OpenApiConvertDataObject openApiConvertDataObject) + throws Exception { + return getPFxxEJBService().changeToExchangeData(openApiConvertDataObject); + } + + public static IExchangeForService getPFxxEJBService() { + IExchangeForService exchangeForService = (IExchangeForService) ObjectCreator.newInstance("ufesbexpress", + "nccloud.pubimpl.pfxx.convert.ExchangeForServiceImpl"); + return exchangeForService; + } + + @Override + public String getModule() { + return "so"; + } + + @POST + @Path("/saveCommit") + @Consumes({"application/json"}) + @Produces({"application/json"}) + public JSONString saveCommit(JSONString json) throws Exception { + JSONObject jobject = JSONObject.parseObject(json.toJSONString()); + if (jobject == null) { + return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null")); + } else { + JSONObject bject = jobject.getJSONObject("billhead"); + if (bject == null) { + return ResultMessageUtil.exceptionToJSON(new NullPointerException("billhead:null")); + } else { + + JSONObject ufinterfaceObj = jsonObjectAss(jobject); + String tsType = ufinterfaceObj.getString("tsType"); + if (tsType != null && tsType.equals("1")) { + Exception e = new NullPointerException("销售订单查询关联失败!"); + return ResultMessageUtil.exceptionToJSON(e); + } + JSONObject bjects = ufinterfaceObj.getJSONObject("ufinterface"); + String billtype = bjects.getString("billtype"); + String account = bjects.getString("account"); + String omscode = bjects.getString("orgcode"); + String groupcode = bjects.getString("groupcode"); + + if (billtype != null && account != null && groupcode != null && "32".equals(billtype)) { + OpenApiConvertDataObject openApiconvertData0bject = new OpenApiConvertDataObject(); + openApiconvertData0bject.setAccount(account); + openApiconvertData0bject.setBilltype(billtype); + openApiconvertData0bject.setGroupcode(groupcode); + openApiconvertData0bject.setOpenApiJsonData(ufinterfaceObj); + try { + OpenApiJsonConvertToExChangeXmlService oService = new OpenApiJsonConvertToExChangeXmlService(); + OpenApiConvertDataResult r = oService.changeToExchangeData(openApiconvertData0bject); + JSONObject returnJson = r.getDesc(); + String content = ""; + // 逐层解析 JSON 数据 + JSONObject ufinterface = returnJson.getJSONObject("ufinterface"); + if (ufinterface != null) { + JSONArray sendResultArray = ufinterface.getJSONArray("sendresult"); + if (sendResultArray != null && sendResultArray.size() > 0) { + // 提取 content 字段 + content = sendResultArray.getJSONObject(0).getString("content"); + } + } + if (content == null || content.equals("")) { + return r != null + ? ResultMessageUtil.toJSON(r.getDesc(), "0") + : ResultMessageUtil.exceptionToJSON(new NullPointerException("未知异常")); + } + String[] ids = {content}; + SaleInvoiceVO[] saleInvoiceVO = NCLocator.getInstance().lookup(ISaleinvoiceQueryAPI.class) + .queryVOByIDs(ids); + SaleInvoiceVO saleInvoiceVO22 = saleInvoiceVO[0]; + SaleInvoiceHVO saleInvoiceHVO = saleInvoiceVO22.getParentVO(); + // 销售发票审核开始 + InvocationInfoProxy.getInstance().setUserId(saleInvoiceHVO.getApprover()); + CloudPFlowContext context = new CloudPFlowContext(); + context.setBillType("32"); + context.setBillVos(new SaleInvoiceVO[]{saleInvoiceVO[0]}); + ISSCService sscService = (ISSCService) NCLocator.getInstance().lookup(ISSCService.class); + String[] actionNames = sscService.isStartSSCWorkFlow( + (AbstractBill[]) ((AbstractBill[]) context.getBillVos()), BusiUnitTypeEnum.SO); + context.setActionName("APPROVE"); + context.setTrantype("32-02"); + context.setBatch(false); + context.setBatchUserObj(new PfUserObject[]{new PfUserObject()}); + IBatchRunScriptService service = (IBatchRunScriptService) NCLocator.getInstance() + .lookup(IBatchRunScriptService.class); + SCMScriptResultDTO result = service.runBacth(context, SaleInvoiceVO.class); + // 销售发票审核结束 + TaxInvoiceType typeObj = TaxInvoiceType.SpecialInvoice; + SaleInvoiceToTaxInvServiceImpl saleInvoiceToTaxInvService = new SaleInvoiceToTaxInvServiceImpl(); + saleInvoiceToTaxInvService.issueTaxInvoice(saleInvoiceVO, typeObj); + + return r != null + ? ResultMessageUtil.toJSON(r.getDesc(), "0") + : ResultMessageUtil.exceptionToJSON(new NullPointerException("未知异常")); + } catch (Exception e) { + return ResultMessageUtil.exceptionToJSON(e); + } + } else { + Exception e = new NullPointerException( + "billtype:" + billtype + ",account:" + account + ",groupcode:" + groupcode); + return ResultMessageUtil.exceptionToJSON(e); + } + + } + } + } + + public static JSONObject jsonObjectAss(JSONObject originalJson) throws Exception { + try { + // 构建目标 JSON 格式 + JSONObject resultJson = new JSONObject(); + // 添加 ufinterface 字段 + JSONObject ufinterface = new JSONObject(); + ufinterface.put("billtype", "32"); + ufinterface.put("sender", "BIP_NC"); + ufinterface.put("level", "0"); + ufinterface.put("replace", "Y"); + ufinterface.put("roottag", "bill"); + ufinterface.put("isexchange", "Y"); + ufinterface.put("account", "01"); + ufinterface.put("groupcode", "00"); + // 处理 bill 数组 + JSONArray billArray = new JSONArray(); + JSONObject bill = new JSONObject(); + // billhead 结构 + JSONObject billhead = new JSONObject(); + billhead = originalJson.getJSONObject("billhead");// 传入JSON对象 + billhead.put("pk_org_v", originalJson.getJSONObject("billhead").getString("pk_org"));// 开票组织版本=开票组织 + billhead.put("pk_group", "00");// 集团 + fplxStr = originalJson.getJSONObject("billhead").getString("vdef22"); + billhead.put("vtrantypecode", "32-02");// 发票类型编码 + billhead.put("cbiztypeid", "SO01");// 业务流程 + billhead.put("approver", "BIP");// 审批人 + billhead.put("fstatusflag", 1);// 单据状态 + billhead.put("billmaker", "BIP");// 制单人 + billhead.put("csendcountryid", "CN");// 发货国家 + billhead.put("crececountryid", "CN");// 收货国家 + billhead.put("ctaxcountryid", "CN");// 报税国家 + // 2025-2-8付业要求修改,根据发票类型Q(自定义档案)对照发票类型 + String ctrantypeidStr = "32-02";// 默认普通发票 + if (fplxStr != null && fplxStr.equals("31")) { + ctrantypeidStr = "32-01"; + } else if (fplxStr != null && fplxStr.equals("32")) { + ctrantypeidStr = "32-02"; + } else if (fplxStr != null && fplxStr.equals("36")) { + ctrantypeidStr = "32-Cxx-03"; + } + billhead.put("ctrantypeid", ctrantypeidStr);// 发票类型 + // billhead.put("ctrantypeid", "32-02");//发票类型 + billhead.put("fbuysellflag", "1");// 购销类型 + billhead.put("creator", "BIP");// 创建人 + billhead.put("ccurrencyid", "CNY");// 本位币 + billhead.put("corigcurrencyid", "CNY");// 币种 + billhead.put("nexchangerate", 1);// 折本汇率 + billhead.put("btriatradeflag", 0);// 三角贸易 + JSONObject newItem = new JSONObject(); + JSONObject otherJson = new JSONObject(); + JSONArray csaleinvoicebid = new JSONArray(); + // 遍历原始数据中的 csaleinvoicebid 数组 + for (int i = 0; i < originalJson.getJSONObject("billhead").getJSONArray("csaleinvoicebid").size(); i++) { + JSONObject item = originalJson.getJSONObject("billhead").getJSONArray("csaleinvoicebid") + .getJSONObject(i); + + JSONObject itemDetails = new JSONObject(); + itemDetails = item; + itemDetails.put("carorgid", originalJson.getJSONObject("billhead").getString("pk_org"));// 应收组织 + itemDetails.put("csendstockorgid", + originalJson.getJSONObject("billhead").getString("pk_org"));// 库存组织原始版本 + itemDetails.put("cmaterialid", item.getString("cmaterialvid"));// 物料编码 + Map value2 = getSaleorderVo(item.getString("csrcbid")); + if (value2 == null) { + resultJson = new JSONObject(); + resultJson.put("tsType", "1"); + return resultJson; + } + itemDetails.put("vfirsttype", "30");// 源头单据类型 + itemDetails.put("vfirstcode", value2.get("vbillcode"));// 源头单据号 + itemDetails.put("blargessflag", value2.get("blargessflag"));// 赠品 + itemDetails.put("vfirsttrantype", "30-01");// 源头交易类型 + itemDetails.put("vfirstrowno", value2.get("crowno"));// 源头单据行号 + itemDetails.put("cfirstid", item.getString("csrcid"));// 源头单据主表 + itemDetails.put("cfirstbid", item.getString("csrcbid"));// 源头单据子表 + itemDetails.put("vsrctype", "30");// 来源单据类型 + itemDetails.put("vsrccode", value2.get("vbillcode"));// 来源单据号 + itemDetails.put("vsrctrantype", "30-01");// 来源交易类型 + itemDetails.put("vsrcrowno", value2.get("crowno"));// 来源单据行号 + // 通过 ntaxrate 获取 taxcode + String taxcodeStr = getTaxcode(item.getString("ntaxrate")); + // 将 taxcodeStr 放入 bodyMap + itemDetails.put("ctaxcodeid", taxcodeStr);// 税码 + itemDetails.put("nnum", item.getString("nastnum"));// 主数量 + itemDetails.put("ftaxtypeflag", 1);// 扣税类别 + itemDetails.put("pk_group", "00");// 集团 + itemDetails.put("pk_org", originalJson.getJSONObject("billhead").getString("pk_org"));// 开票组织 + itemDetails.put("cunitid", item.getString("castunitid"));// 主单位 + +// double nastnum = Double.parseDouble(item.getString("nastnum"));//数量 +// double nqtorigtaxprice = Double.parseDouble(item.getString("nqtorigtaxprice"));//含税单价 +// double ntaxrate = Double.parseDouble(item.getString("ntaxrate"));//税率 +// +// double nqtorigprice = +// Math.round(nqtorigtaxprice / (1 + ntaxrate) * 100.0) / 100.0;//不含税单价、无税单价(含税单价/(1+税率)) +// double norigmny = Math.round(nqtorigprice * nastnum * 100.0) / 100.0;//无税金额(不含税单价*数量) +// double norigtaxmny = Math.round(nastnum * nqtorigtaxprice * 100.0) / 100.0;//价税合计、含税金额(数量*含税单价) +// double norigtaxprice = Math.round(nqtorigtaxprice * 100.0) / 100.0;//主含税单价(含税单价) +// double norignetprice = nqtorigprice;//主无税净价(不含税单价) +// double ntax = Math.round(norigtaxmny / (1 + ntaxrate) * ntaxrate * 100.0) / 100.0;//税额(含税金额/(1+税率)*税率) +// double ncaltaxmny = norigmny;//计税金额(无税金额) +// double norigtaxnetprice = norigtaxprice;//主含税净价(主含税单价) + +// BigDecimal nastnum = new BigDecimal(item.getString("nastnum"));//数量 +// BigDecimal nqtorigtaxprice = new BigDecimal(item.getString("nqtorigtaxprice"));//含税单价 +// BigDecimal ntaxrate = new BigDecimal(item.getString("ntaxrate"));//税率 +// +// // 1. 计算不含税单价 +// BigDecimal nqtorigprice = nqtorigtaxprice.divide(BigDecimal.ONE.add(ntaxrate), 4, RoundingMode.HALF_UP); +// // 2. 计算无税金额 = 不含税单价 * 数量 +// BigDecimal norigmny = nqtorigprice.multiply(nastnum).setScale(4, RoundingMode.HALF_UP); +// // 3. 计算税额 = 无税金额 * 税率 +// BigDecimal ntax = norigmny.multiply(ntaxrate).setScale(4, RoundingMode.HALF_UP); +// // 4. 计算含税金额 = 无税金额 + 税额 +// BigDecimal norigtaxmny = norigmny.add(ntax).setScale(4, RoundingMode.HALF_UP); +// // 主含税单价(即含税单价) +// BigDecimal norigtaxprice = nqtorigtaxprice.setScale(4, RoundingMode.HALF_UP); +// // 主无税净价(即不含税单价) +// BigDecimal norignetprice = nqtorigprice; +// // 计税金额 = 无税金额 +// BigDecimal ncaltaxmny = norigmny; +// // 主含税净价 = 含税单价(原始) +// BigDecimal norigtaxnetprice = norigtaxprice; + + // 输入参数:从你的 item 获取各个字段 + BigDecimal nastnum = new BigDecimal(item.getString("nastnum")); // 数量 + nastnum = nastnum.setScale(4, RoundingMode.HALF_UP); + BigDecimal nqtorigtaxprice = new BigDecimal(item.getString("nqtorigtaxprice")); // 含税单价 + nqtorigtaxprice = nqtorigtaxprice.setScale(4, RoundingMode.HALF_UP); + BigDecimal ntaxrate = new BigDecimal(item.getString("ntaxrate")).divide(new BigDecimal("100")); // 税率 + ntaxrate = ntaxrate.setScale(4, RoundingMode.HALF_UP); + + // 含税净价 + BigDecimal norigtaxnetprice = nqtorigtaxprice; + // 1. 计算价税合计(含税金额) + BigDecimal norigtaxmny = nastnum.multiply(norigtaxnetprice).setScale(2, RoundingMode.HALF_UP); + // 2. 计算折扣额 + BigDecimal discountAmount = nastnum.multiply(nqtorigtaxprice).subtract(norigtaxmny) + .setScale(4, RoundingMode.HALF_UP); + // 3. 计算税额(两种方法:应税外加税和应税内含税) + BigDecimal ntax = norigtaxmny.multiply(ntaxrate) + .divide(BigDecimal.ONE.add(ntaxrate), 2, RoundingMode.HALF_UP); // 应税外加税 + BigDecimal taxInclusiveInner = norigtaxmny.multiply(ntaxrate) + .setScale(4, RoundingMode.HALF_UP); // 应税内含税 + // 4. 计算无税金额 + BigDecimal norigmny = norigtaxmny.subtract(ntax).setScale(2, RoundingMode.HALF_UP); + // 4. 计算无税单价(nqtorigprice = 无税金额 / 数量) + BigDecimal nqtorigprice = norigmny.divide(nastnum, 4, RoundingMode.HALF_UP); + // 计税金额 = 无税金额 + BigDecimal ncaltaxmny = norigmny; + // 主含税单价(即含税单价) + BigDecimal norigtaxprice = nqtorigtaxprice.setScale(4, RoundingMode.HALF_UP); + // 主无税净价(即不含税单价) + BigDecimal norignetprice = nqtorigprice; + + // 从销售订单中获取币种 + String corigcurrencyid = getString_TrimAsNull(value2.get("corigcurrencyid")); + otherJson.put("corigcurrencyid", "".equals(corigcurrencyid) ? "CNY" : corigcurrencyid); + // 从销售订单中获取折本汇率 + BigDecimal nexchangerate = getUFDouble_NullAsZero(value2.get("nexchangerate")).toBigDecimal(); + otherJson.put("nexchangerate", nexchangerate); + // 单价和金额*汇率 + nqtorigprice = nqtorigprice.multiply(nexchangerate); + norigmny = norigmny.multiply(nexchangerate); + norigtaxmny = norigtaxmny.multiply(nexchangerate); + norigtaxprice = norigtaxprice.multiply(nexchangerate); + norignetprice = norignetprice.multiply(nexchangerate); + nqtorigtaxprice = nqtorigtaxprice.multiply(nexchangerate); + norigtaxnetprice = norigtaxnetprice.multiply(nexchangerate); + + + itemDetails.put("nqtorigprice", nqtorigprice);// 无税单价 + itemDetails.put("norigprice", nqtorigprice);// 主无税单价 + itemDetails.put("norigmny", norigmny);// 无税金额 + itemDetails.put("nmny", norigmny);// 本币无税金额 + itemDetails.put("norigtaxmny", norigtaxmny);// 价税合计 + itemDetails.put("norigtaxprice", norigtaxprice);// 主含税单价 + itemDetails.put("norignetprice", norignetprice);// 主无税净价 + itemDetails.put("nqtorigtaxprice", nqtorigtaxprice);// 含税单价 + itemDetails.put("ntax", ntax);// 税额 + itemDetails.put("ncaltaxmny", ncaltaxmny);// 计税金额 + itemDetails.put("norigtaxnetprice", norigtaxnetprice);// 主含税净价 + itemDetails.put("nnetprice", norignetprice);// 主本币无税净价 + itemDetails.put("ntaxmny", norigtaxmny);// 本币价税合计 + csaleinvoicebid.add(itemDetails); + + + } + newItem.put("item", csaleinvoicebid); + billhead.put("csaleinvoicebid", newItem); + if (otherJson != null && !otherJson.isEmpty()) { + // 查询销售订单中的币种和汇率 + billhead.put("corigcurrencyid", otherJson.get("corigcurrencyid"));// 币种 + billhead.put("nexchangerate", otherJson.get("nexchangerate"));// 折本汇率 + } + bill.put("billhead", billhead); + bill.put("id", ""); + // 将 bill 数组添加到 ufinterface 中 + billArray.add(bill); + ufinterface.put("bill", billArray); + // 将 ufinterface 添加到最终的 resultJson 中 + resultJson.put("ufinterface", ufinterface); + return resultJson; + } catch (Exception e) { + return (JSONObject) ResultMessageUtil.exceptionToJSON(e); + } + } + + + // 方法:检查必填项并返回转化后的Map + public static String checkRequiredFields(JSONObject data) throws Exception { + String returnStr = ""; + // 2. 检查必填字段 pk_org + String pkOrg = (String) data.getOrDefault("pk_org", ""); + if (pkOrg.isEmpty()) { + return "字段pk_org缺失或为空!"; + } + // 2. 检查必填字段 pk_org + String vbillcode = (String) data.getOrDefault("vbillcode", ""); + if (vbillcode.isEmpty()) { + return "字段vbillcode缺失或为空!"; + } + return returnStr; + } + + private static String getTaxcode(String taxrateStr) throws BusinessException { + IUAPQueryBS queryBS = NCLocator.getInstance().lookup(IUAPQueryBS.class); + String sql = + " select code FROM bd_taxrate tt inner join bd_taxcode tc on tt.pk_taxcode=tc.pk_taxcode where taxrate='" + + taxrateStr + "' AND ROWNUM = 1 "; + String taxcodeStr = (String) queryBS.executeQuery(sql, new ColumnProcessor()); + return taxcodeStr; + } + + private static Map getSaleorderVo(String csourcebillbidStr) throws BusinessException { + IUAPQueryBS queryBS = NCLocator.getInstance().lookup(IUAPQueryBS.class); + String sql = " select s.vbillcode,s.csaleorderid,sb.csaleorderbid,sb.crowno,sb.blargessflag,sb.nexchangerate,s.corigcurrencyid from so_saleorder_b sb\n" + + "inner join so_saleorder s on sb.csaleorderid=s.csaleorderid\n" + + "where sb.csaleorderbid='" + csourcebillbidStr + "' "; + Map value2 = (Map) queryBS.executeQuery(sql, new MapProcessor()); + return value2; + } + + private static String getString_TrimAsNull(Object value) { + if ((value == null) || (value.toString().trim().isEmpty())) { + return ""; + } + return value.toString().trim(); + } + + private static UFDouble getUFDouble_NullAsZero(Object value) { + if ((value == null) || (value.toString().trim().isEmpty()) || (value.toString().trim().equals("~"))) + return UFDouble.ONE_DBL; + if ((value instanceof UFDouble)) + return (UFDouble) value; + if ((value instanceof BigDecimal)) { + return new UFDouble((BigDecimal) value); + } + return new UFDouble(value.toString().trim()); + } + + public IUAPQueryBS getQueryService() { + return NCLocator.getInstance().lookup(IUAPQueryBS.class); + } + +} \ No newline at end of file From 839021a256bd9c6f15674d251f69e34cc8069a2c Mon Sep 17 00:00:00 2001 From: mzr <1562242162@qq.com> Date: Tue, 4 Mar 2025 18:05:47 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E6=8E=A5=E6=94=B6BIP=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E7=94=9F=E6=88=90=E6=94=B6=E6=AC=BE=E5=8D=95=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusiregForSyncSaleorderAndToBIP.java | 261 ++++ .../resource/GatheringbillRestResource.java | 1145 +++++++++++++++++ 2 files changed, 1406 insertions(+) diff --git a/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java b/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java index e69de29..31c099f 100644 --- a/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java +++ b/arap/src/private/nc/bs/arap/busireg/BusiregForSyncSaleorderAndToBIP.java @@ -0,0 +1,261 @@ +package nc.bs.arap.busireg; + +import com.alibaba.fastjson.JSONObject; +import com.google.gson.Gson; +import com.yonyou.cloud.utils.StringUtils; +import nc.bs.businessevent.BdUpdateEvent; +import nc.bs.businessevent.BusinessEvent; +import nc.bs.businessevent.IBusinessEvent; +import nc.bs.businessevent.IBusinessListener; +import nc.bs.dao.BaseDAO; +import nc.bs.trade.business.HYSuperDMO; +import nc.bs.uapbd.util.IgnoreSslUtil; +import nc.jdbc.framework.processor.ColumnProcessor; +import nc.jdbc.framework.processor.MapProcessor; +import nc.vo.arap.basebill.BaseAggVO; +import nc.vo.arap.utils.ArrayUtil; +import nc.vo.pub.AggregatedValueObject; +import nc.vo.pub.BusinessException; +import nc.vo.pub.CircularlyAccessibleValueObject; +import nc.vo.pub.lang.UFDouble; +import nc.vo.so.m30.entity.SaleOrderHVO; +import nccloud.bs.arap.sagas.util.SagasUtils; +import nccloud.commons.lang.ArrayUtils; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +public class BusiregForSyncSaleorderAndToBIP implements IBusinessListener{ + + @Override + public void doAction(IBusinessEvent event) throws BusinessException { + // TODO Auto-generated method stub + BaseAggVO[] bills = getBills(event); + if (ArrayUtils.isEmpty(bills) || SagasUtils.isCompensateStage()) { + return; + } + // 更新 销售订单 + try { + BaseDAO dao = new BaseDAO(); + for(BaseAggVO aggvo : bills) { + CircularlyAccessibleValueObject headvo = aggvo.getParentVO(); + // 本次收款金额 + Object money = headvo.getAttributeValue("money"); + // 收款单主键 + Object pk_busibill = headvo.getAttributeValue("pk_gatherbill"); + // 销售订单主键 + Object csaleorderid = headvo.getAttributeValue("def3"); + // 根据销售订单主键,查询比较字段 + String sql = "select vdef17, vdef15, vdef14, vdef11, vdef9 from so_saleorder where csaleorderid = '" + csaleorderid + "' and dr = 0 "; + HashMap hm = (HashMap)dao.executeQuery(sql, new MapProcessor()); + Object vdef17 = hm.get("vdef17"); + Object vdef15 = hm.get("vdef15"); + Object vdef14 = hm.get("vdef14"); + Object vdef11 = hm.get("vdef11"); + Object vdef9 = hm.get("vdef9"); + // 合同号 + Object ctpk = aggvo.getChildrenVO()[0].getAttributeValue("def6"); + // 查询合同号下 + String sql1 = " select sum(ar_gatheritem.money_cr) sk_effect_money " + + " from ar_gatheritem " + + " left join ar_gatherbill on ar_gatherbill.pk_gatherbill = ar_gatheritem.pk_gatherbill " + + " where ar_gatherbill.dr = 0 and ar_gatheritem.dr = 0 and ar_gatherbill.EFFECTSTATUS = 10 " + + " and ar_gatheritem.def6 = '" + ctpk + "'"; + Object obj = dao.executeQuery(sql1, new ColumnProcessor()); + // 收款单累计金额 + UFDouble sk_effect_money = UFDouble.ZERO_DBL; + if(obj != null) { + sk_effect_money = new UFDouble(obj.toString()); + } + // 表头合同金额 + UFDouble ctmoney = UFDouble.ZERO_DBL; + if(vdef17 != null) { + ctmoney = new UFDouble(vdef17.toString()); + } + // 预收比例 + UFDouble preratio = UFDouble.ZERO_DBL; + if(vdef15 != null) { + preratio = new UFDouble(vdef15.toString()); + } + // 收款大于预收 + if (sk_effect_money.compareTo(UFDouble.ZERO_DBL) > 0 && sk_effect_money.sub(ctmoney.multiply(preratio)).compareTo(UFDouble.ZERO_DBL) >= 0) { + String updateSQL = "update so_saleorder set vdef11 = (select pk_defdoc from bd_defdoc where code = 'fhk01') where csaleorderid = '" + csaleorderid + "'"; + dao.executeUpdate(updateSQL); + } else if (sk_effect_money.compareTo(UFDouble.ZERO_DBL) > 0 && sk_effect_money.sub(ctmoney.multiply(preratio)).compareTo(UFDouble.ZERO_DBL) < 0) { + String updateSQL = "update so_saleorder set vdef11 = (select pk_defdoc from bd_defdoc where code = 'fhk02') where csaleorderid = '" + csaleorderid + "'"; + dao.executeUpdate(updateSQL); + } + JSONObject HTXSDD = new JSONObject(); + HTXSDD.put("id", vdef9); + HYSuperDMO dmo= new HYSuperDMO(); + SaleOrderHVO[] hvo = (SaleOrderHVO[])dmo.queryByWhereClause(SaleOrderHVO.class, "csaleorderid='"+csaleorderid+"'"); + + + // 实际预收款 npreceivemny + UFDouble npreceivemny = hvo[0].getNpreceivemny(); + JSONObject p = new JSONObject(); + HTXSDD.put("actPreRecvAmt", npreceivemny.getDouble()); + // 实际收款金额 nreceivedmny + UFDouble nreceivedmny = hvo[0].getNreceivedmny(); + HTXSDD.put("actRecvAmt", nreceivedmny.getDouble()); + // 是否收到预收款 + Object vdef14Code = dao.executeQuery("select code from bd_defdoc where pk_defdoc = '" + vdef14 + "'", new ColumnProcessor()); + HTXSDD.put("isPreRecv", vdef14Code); + // 是否收到发货款 + Object vdef11Code = dao.executeQuery("select code from bd_defdoc where pk_defdoc = '" + vdef11 + "'", new ColumnProcessor()); + HTXSDD.put("isShipRecdAmt", vdef11Code); + p.put("HTXSDD", HTXSDD); + System.out.println(p.toJSONString()); + // 获取旗舰版的token + Map params = new HashMap<>(); + String appKey = "a3c57e0d871240e9b9bf56b35001a324"; + String appSecret = "a959f7786db8dbb9a2c0493b5855a46bea68ad75"; + String tokenUrl="https://www.tkkfbip.com/iuap-api-auth/open-auth/selfAppAuth/getAccessToken"; + String toBipUrl="https://www.tkkfbip.com/iuap-api-gateway/oxp4h3x6/current_yonbip_default_sys/KKAPI/contractSaleOrder/update?access_token="; + // 除签名外的其他参数 + params.put("appKey", appKey); + String timestamp = String.valueOf(System.currentTimeMillis()); + params.put("timestamp", timestamp); + // 计算签名 + Map treeMap; + if (params instanceof TreeMap) { + treeMap = params; + } else { + treeMap = new TreeMap<>(params); + } + StringBuilder stringBuilder = new StringBuilder(); + for (Map.Entry entry : treeMap.entrySet()) { + stringBuilder.append(entry.getKey()).append(entry.getValue()); + } + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + String base64String = Base64.getEncoder().encodeToString(signData); + String signature = URLEncoder.encode(base64String, "UTF-8"); + params.put("signature", signature); + String responseString = doGet(tokenUrl, params); + Gson gson = new Gson(); + Map result = gson.fromJson(responseString, Map.class); + if (StringUtils.equals("00000", result.get("code").toString())) { + Map tokenInfo = (Map) result.get("data"); + String access_token = (String) tokenInfo.get("access_token"); + doPost(toBipUrl+ access_token, p); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private BaseAggVO[] getBills(IBusinessEvent event) { + Object value = null; + if (event instanceof BusinessEvent) { + value = ((BusinessEvent)event).getObject(); + } else if (event instanceof BdUpdateEvent) { + value = ((BdUpdateEvent)event).getNewObject(); + } + BaseAggVO[] bills = null; + if (null != value) { + if (value.getClass().isArray()) { + Object[] objs = (Object[])value; + bills = (objs instanceof BaseAggVO[]) ? (BaseAggVO[])objs : (BaseAggVO[])ArrayUtil.convertSupers2Subs((AggregatedValueObject[])objs, BaseAggVO.class); + } else { + bills = new BaseAggVO[1]; + bills[0] = (BaseAggVO)value; + } + } + return bills; + } + +private String doGet(String requestUrl, Map paramMap) throws IOException { + + StringBuilder param = new StringBuilder("?"); + if (paramMap != null) { + for (Map.Entry entry : paramMap.entrySet()) { + param.append(entry.getKey()); + param.append("="); + param.append(entry.getValue()); + param.append("&"); + } + param.deleteCharAt(param.length() - 1); + } + String url = requestUrl + param; + URL u = new URL(url); + try { + if("https".equalsIgnoreCase(u.getProtocol())){//判定网址是否信任,不信任则调用忽略信任工具类SslUtil + IgnoreSslUtil.ignoreSsl(); + } + HttpsURLConnection connection = (HttpsURLConnection)u.openConnection(); + connection.setRequestMethod("GET"); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + connection.connect(); + StringBuilder response =new StringBuilder(); + int responsecode = connection.getResponseCode(); + if(responsecode == HttpsURLConnection.HTTP_OK) { + InputStream inputstream =connection.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream)); + String line; + + while((line =reader.readLine()) != null) { + response.append(line); + } + reader.close(); + } + connection.disconnect(); + return response.toString(); + } catch(Exception e) { + e.printStackTrace(); + } + + + + return null; + } + + private String doPost(String requestUrl, JSONObject json) throws IOException { + URL u = new URL(requestUrl); + try { + if("https".equalsIgnoreCase(u.getProtocol())){//判定网址是否信任,不信任则调用忽略信任工具类SslUtil + IgnoreSslUtil.ignoreSsl(); + } + HttpsURLConnection connection = (HttpsURLConnection)u.openConnection(); + // 设置请求方法 + connection.setRequestMethod("POST"); + // 设置请求属性 + connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); + // 发送POST请求必须设置如下两行 + connection.setDoOutput(true); + connection.setDoInput(true); + byte[] outputInBytes = json.toJSONString().getBytes(StandardCharsets.UTF_8); + // 写入数据到请求体 + OutputStream os = connection.getOutputStream(); + os.write(outputInBytes); + // 获取响应码 + int responseCode = connection.getResponseCode(); + System.out.println("Response Code: " + responseCode); + // 读取响应 + String response = ""; + try(BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + br.readLine(); + System.out.println("Response: " + response); + } + // 关闭连接 + connection.disconnect(); + return response; + } catch(Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java b/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java index e69de29..ae08f10 100644 --- a/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java +++ b/arap/src/public/nc/api/arap/resource/GatheringbillRestResource.java @@ -0,0 +1,1145 @@ +/* */ +package nc.api.arap.resource; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.google.gson.Gson; +import nc.bd.itf.tools.BFPubTools; +import nc.bs.dao.BaseDAO; +import nc.bs.dao.DAOException; +import nc.bs.framework.common.InvocationInfoProxy; +import nc.bs.framework.common.NCLocator; +import nc.bs.sec.esapi.NCESAPI; +import nc.bs.trade.business.HYPubBO; +import nc.bs.trade.business.HYSuperDMO; +import nc.itf.arap.pub.IArapBillService; +import nc.jdbc.framework.processor.ColumnProcessor; +import nc.jdbc.framework.processor.MapProcessor; +import nc.vo.arap.basebill.BaseAggVO; +import nc.vo.arap.gathering.AggGatheringBillVO; +import nc.vo.arap.gathering.GatheringBillItemVO; +import nc.vo.arap.gathering.GatheringBillVO; +import nc.vo.bd.defdoc.DefdocVO; +import nc.vo.ml.NCLangRes4VoTransl; +import nc.vo.pub.BusinessException; +import nc.vo.pub.CircularlyAccessibleValueObject; +import nc.vo.pub.lang.UFBoolean; +import nc.vo.pub.lang.UFDouble; +import nc.vo.pubapp.pattern.pub.MathTool; +import nc.vo.so.m30.entity.SaleOrderBVO; +import nc.vo.so.m30.entity.SaleOrderHVO; +import nccloud.api.rest.utils.NCCRestUtils; +import nccloud.api.rest.utils.ResultMessageUtil; +import nccloud.commons.lang.StringUtils; +import nccloud.pubitf.arap.openapi.IARAPOpenAPIService; +import nccloud.pubitf.arap.openapi.IGatheringbillOpenService; +import org.json.JSONString; +import uap.ws.rest.util.UAPRSConstance; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import java.util.zip.GZIPInputStream; +/* */ +/* */ +/* */ +/* */ +/* */ + + +/* */ +/* */ +/* */ +/* */ +/* */ +/* */ +/* */ +/* */ +@Path("arap/gatheringbill") +/* */ public class GatheringbillRestResource + /* */ extends ArapBaseRestResource + /* */ { + + + HYSuperDMO dmo = null; + + public HYSuperDMO getSuperDMO() { + + if (dmo == null) { + dmo = new HYSuperDMO(); + } + + return dmo; + } + + + @POST + @Path("/insert") + @Consumes(UAPRSConstance.MEDIATYPE_JSON) + @Produces(UAPRSConstance.MEDIATYPE_JSON) + public JSONString insertPaybill(JSONString str) { + NCCRestUtils.initInvocationInfo(); + String json = str.toJSONString(); + Map billMap = super.fromJson(json, Map.class); + GatheringBillVO headvo = (GatheringBillVO) super.fromJsonToVO(billMap, GatheringBillVO.class); + + @SuppressWarnings("unchecked") + List> itemMaps = (List>) billMap.get("items"); + List itemvos = new ArrayList(); + if (itemMaps != null && itemMaps.size() > 0) { + for (Map item : itemMaps) { + GatheringBillItemVO itemvo = (GatheringBillItemVO) super.fromJsonToVO(item, GatheringBillItemVO.class); + itemvos.add(itemvo); + } + } + AggGatheringBillVO bill = new AggGatheringBillVO(); + bill.setParentVO(headvo); + bill.setChildrenVO(itemvos.toArray(new GatheringBillItemVO[0])); + + try { + Map returnMap = NCLocator.getInstance().lookup(IGatheringbillOpenService.class).saveBill(bill); + return ResultMessageUtil.toJSON(returnMap); + } catch (BusinessException e) { + return ResultMessageUtil.exceptionToJSON(e); + } + } + + /** + * 该收款单保存为BIP专业保存方法。请谨慎修改; + * + * @param str + * @return + */ + + + /* */ + @POST + /* */ + @Path("/bipinsert") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString bipInsertPaybill(JSONString str) { + InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677"); + /* 48 */ + NCCRestUtils.initInvocationInfo(); + /* 49 */ + String json = str.toJSONString(); + /* 50 */ + Map billMap = (Map) fromJson(json, Map.class); + billMap.put("recaccount", billMap.get("ar_recaccount")); + /* 51 */ + GatheringBillVO headvo = (GatheringBillVO) ArapBaseRestResource.fromJsonToVO(billMap, GatheringBillVO.class); + + headvo.setDef28(headvo.getBilldate().toStdString());// 交易日期 + + // 汇率为空时,默认为1 + if (headvo.getRate() == null) { + headvo.setRate(UFDouble.ONE_DBL); + } + /* */ + // 结算方式名称 + Object balatypeName = ""; + // 金额 + UFDouble money = new UFDouble(0); + // 组织本币金额 + UFDouble local_money = new UFDouble(0); + // 税率 + UFDouble ntaxrate = new UFDouble(0); + // 税码 + String ctaxcode = ""; + + BaseDAO dao = new BaseDAO(); + + // 销售订单号 + String csaleorderid = ""; + + try { + HYPubBO hybo = new HYPubBO(); + headvo.setIsinit(new UFBoolean(false)); + // 默认 收款类型 默认合同收款单 + Object pk_billtypecode = hybo.findColValue("bd_billtype", "PK_BILLTYPECODE", "billtypename = '合同收款单' "); + headvo.setPk_tradetype(pk_billtypecode.toString()); + // 业务流程 默认【收款结算】 + Object pk_busitype = hybo.findColValue("bd_busitype", "busicode", "businame = '收款结算' "); + headvo.setPk_busitype(pk_busitype.toString()); + // 往来对象0-客户 2-部门 3-业务员 默认客户 + headvo.setObjtype(0); + // 销售订单号 + csaleorderid = headvo.getDef3(); + // 客户 + Object customerid = hybo.findColValue("so_saleorder", "ccustomerid", "csaleorderid = '" + csaleorderid + "' "); + Object customerCode = hybo.findColValue("bd_customer", "code", "pk_customer = '" + customerid + "' "); + headvo.setCustomer(customerCode.toString()); + + Object tr = dao.executeQuery("select ntaxrate from so_saleorder_b where csaleorderid = '" + csaleorderid + "'", new ColumnProcessor()); + if (tr != null) { + ntaxrate = new UFDouble(tr.toString()); + } + + // 税码 + Object ctaxcodeid = hybo.findColValue("so_saleorder_b", "ctaxcodeid", "csaleorderid = '" + csaleorderid + "' "); + Object tc = hybo.findColValue("bd_taxcode", "code", "pk_taxcode = '" + ctaxcodeid + "' "); + ctaxcode = BFPubTools.getString_TrimAsNull(tc); + + // 业务员 + Object cemployeeid = hybo.findColValue("so_saleorder", "cemployeeid", "csaleorderid = '" + csaleorderid + "' "); + if (cemployeeid != null) {// 能够获取到值,但是该值可能在销售订单生成的时候,没有翻译,依然存的是人员编码,如果存的是人员编码,则说明该人员在erp系统中不存在 + Object cemployeeCode = hybo.findColValue("bd_psndoc", "code", "pk_psndoc = '" + cemployeeid + "' "); + if (cemployeeCode != null) { + headvo.setPk_psndoc(cemployeeCode.toString()); + // 部门 + Object deptCode = hybo.findColValue("org_orgs", "code", + " pk_org in( select pk_dept from bd_psnjob where pk_psndoc = '" + cemployeeid + "')"); + if (deptCode != null) { + headvo.setPk_deptid(deptCode.toString()); + } + + } + + } + + + // pk_currtype 币种编码 默认人民币 + if (headvo.getPk_currtype() == null || headvo.getPk_currtype().isEmpty()) { + headvo.setPk_currtype("CNY"); + } + + // accessorynum 附件张数 默认2 + headvo.setAccessorynum(2); + // 制单人 默认BIP + headvo.setBillmaker("BIP"); + // 结算方式名称 + String balatypeCode = headvo.getPk_balatype(); + if (!StringUtils.isEmpty(balatypeCode)) { + Object pk_balatype = hybo.findColValue("bd_balatype", "pk_balatype", " code = '" + balatypeCode + "' "); +// headvo.setPk_balatype(pk_balatype.toString()); + if (pk_balatype != null) { + balatypeName = hybo.findColValue("bd_balatype", "name", " code = '" + balatypeCode + "' "); + } + + } + + // 银行收款账号 + // 原币金额 + // 单据状态 + headvo.setBillstatus(-1); + // 单据来源系统编码 + headvo.setSrc_syscode(17); + // 合同金额 + // 结算组织 + headvo.setSett_org(headvo.getPk_org()); + } catch (Exception e) { + return ResultMessageUtil.exceptionToJSON(e); + } + + /* */ + /* 54 */ + List> itemMaps = (List) billMap.get("items"); + /* 55 */ + List itemvos = new ArrayList(); + /* 56 */ + if (itemMaps != null && itemMaps.size() > 0) { + /* 57 */ + for (Map item : itemMaps) { + /* 58 */ + GatheringBillItemVO itemvo = (GatheringBillItemVO) ArapBaseRestResource.fromJsonToVO(item, GatheringBillItemVO.class); + + try { + HYPubBO hybo = new HYPubBO(); + itemvo.setRecaccount(headvo.getRecaccount()); + // pk_balatype 结算方式 表头带出 + itemvo.setPk_balatype(headvo.getPk_balatype()); + // 票据类型 checktype 结算方式:银行承兑汇票-电子、银行承兑汇票-纸质=银行承兑汇票;商业承兑汇票-电子、商业承兑汇票-纸质=商业承兑汇票 + String checktypeName = ""; + +// if("银行承兑汇票-电子".equals(balatypeName) || "银行承兑汇票-纸质".equals(balatypeName)) { +// checktypeName = "银行承兑汇票"; +// } +// if("商业承兑汇票-电子".equals(balatypeName) || "商业承兑汇票-纸质".equals(balatypeName)) { +// checktypeName = "商业承兑汇票"; +// } + + if ("银行承兑汇票-电子".equals(balatypeName)) { + checktypeName = "电子银行承兑汇票"; + } else if ("商业承兑汇票-电子".equals(balatypeName)) { + checktypeName = "电子商业承兑汇票"; + } else if ("商业承兑汇票-纸质".equals(balatypeName)) { + checktypeName = "商业承兑汇票"; + } else if ("银行承兑汇票-纸质".equals(balatypeName)) { + checktypeName = "银行承兑汇票"; + } + + if (checktypeName != "") { + Object checktypeCode = hybo.findColValue("bd_notetype", "code", " name = '" + checktypeName + "' "); + itemvo.setChecktype(checktypeCode.toString()); + } + +// Object checktypeCode = hybo.findColValue("bd_notetype", "code", " name = '" + checktypeName + "' "); +// itemvo.setChecktype(checktypeCode.toString()); + // objtype 往来对象0-客户 2-部门 3-业务员 表头带出 + itemvo.setObjtype(headvo.getObjtype()); + // supplier 客户编码 表头带出 + itemvo.setCustomer(headvo.getCustomer()); + // pk_dept 部门编码 表头带出 + itemvo.setPk_deptid(headvo.getPk_deptid()); + // pk_psndoc 业务员编码 表头带出 + itemvo.setPk_psndoc(headvo.getPk_psndoc()); + // pk_currtype 币种编码 表头带出 + itemvo.setPk_currtype(headvo.getPk_currtype()); + // prepay 收款性质 默认应收款 0 + itemvo.setPrepay(0); + // + UFDouble money_cr = itemvo.getMoney_cr(); + UFDouble local_tax_cr = money_cr.multiply(ntaxrate).div(100); + itemvo.setLocal_tax_cr(local_tax_cr); + // + UFDouble notax_cr = money_cr.sub(local_tax_cr); + itemvo.setNotax_cr(notax_cr); + itemvo.setRate(headvo.getRate()); + // 组织本币汇率 + if (itemvo.getRate() == null) { + itemvo.setRate(UFDouble.ZERO_DBL); + } + // + itemvo.setTaxcodeid(ctaxcode); + // + itemvo.setTaxrate(ntaxrate); + + // 收支项目 + itemvo.setPk_subjcode("201"); +// itemvo.setSubjcode("201"); + money = money.add(itemvo.getMoney_cr()); + UFDouble local_money_cr = itemvo.getMoney_cr().multiply(itemvo.getRate()).setScale(2, 4); + itemvo.setLocal_money_cr(local_money_cr); + local_money.add(local_money_cr); + + Object def2 = itemvo.getDef2(); + if (def2 != null) + itemvo.setDef2(hybo.findColValue("bd_defdoc", "pk_defdoc", " code = '" + def2 + "' ") + ""); + Object def3 = itemvo.getDef3(); + if (def3 != null) + itemvo.setDef3(hybo.findColValue("bd_defdoc", "pk_defdoc", " code = '" + def3 + "' ") + ""); + Object def6 = itemvo.getDef6(); + if (def6 != null) + itemvo.setDef6(hybo.findColValue("bd_defdoc", "pk_defdoc", " code = '" + def6 + "' ") + ""); + Object def36 = itemvo.getDef36(); + if (def36 != null) + itemvo.setDef36(hybo.findColValue("bd_defdoc", "pk_defdoc", " code = '" + def36 + "' ") + ""); + + + HYSuperDMO dmo = new HYSuperDMO(); + SaleOrderHVO[] hvo = (SaleOrderHVO[]) dmo.queryByWhereClause(SaleOrderHVO.class, "vbillcode='" + def2 + "'"); + SaleOrderBVO[] bvos = (SaleOrderBVO[]) dmo.queryByWhereClause(SaleOrderBVO.class, "csaleorderid='" + hvo[0].getPrimaryKey() + "'"); + if (bvos != null) { + itemvo.setSrc_billid(bvos[0].getCsaleorderid()); + itemvo.setSrc_itemid(bvos[0].getCsaleorderbid()); + itemvo.setSrc_billtype("30"); + itemvo.setSrc_tradetype(hvo[0].getVtrantypecode()); + itemvo.setTop_billid(bvos[0].getCsaleorderid()); + itemvo.setTop_itemid(bvos[0].getCsaleorderbid()); + itemvo.setTop_billtype("30"); + } + + + } catch (Exception e) { + return ResultMessageUtil.exceptionToJSON(e); + } + + + /* 59 */ + itemvos.add(itemvo); + /* */ + } + /* */ + } + + headvo.setMoney(money); + headvo.setGloballocal(money); + // headvo.setRate(new UFDouble(1)); + headvo.setLocal_money(local_money); + + /* 62 */ + AggGatheringBillVO bill = new AggGatheringBillVO(); + /* 63 */ + bill.setParentVO(headvo); + /* 64 */ + bill.setChildrenVO((CircularlyAccessibleValueObject[]) itemvos.toArray(new GatheringBillItemVO[0])); + /* */ + /* */ + try { + /* 67 */ + Map returnMap = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).saveBill(bill); + + JSONString resultJson = ResultMessageUtil.toJSON(returnMap); + // 保存后动作 + + + JSONObject js_result = JSON.parseObject(resultJson.toJSONString()); + + if (js_result.containsKey("success")) { + if (js_result.getString("success").equals("true")) { + if (js_result.containsKey("data")) { + JSONObject js_data = js_result.getJSONObject("data"); + String pk_gatherid = js_data.getString("pk_bill"); + String pk_org = js_data.getString("pk_org"); + + GatheringBillItemVO[] billItemVOs = (GatheringBillItemVO[]) bill.getChildrenVO(); + + for (GatheringBillItemVO gatheringBillItemVO : billItemVOs) { + afterChangeMny(gatheringBillItemVO.getSrc_billid(), pk_org, billItemVOs[0].getDef6(), pk_gatherid); + } + + + } + } + } + +// afterChangeMny(); + + +///* 68 */ return ResultMessageUtil.toJSON(returnMap); + return resultJson; + /* 69 */ + } catch (BusinessException e) { + /* 70 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + + + // 实际收款金额 01无约定预付款 02有约定已收到预付款 03有约定未收到款 + + /** + * @param csaleorderid 销售订单id + * @param pk_org 组织 + * @param ctid 合同id + * @param pk_gatherid 收款单id + */ + private void afterChangeMny(String csaleorderid, String pk_org, String ctid, String pk_gatherid) { + + + try { + + // 合同id + if (StringUtils.isEmpty(ctid)) { + return; + } + + // 获取销售订单表头 + SaleOrderHVO hvo = (SaleOrderHVO) getSuperDMO().queryByPrimaryKey(SaleOrderHVO.class, csaleorderid); + if (hvo == null) { + return; + } + + String vdef9 = hvo.getVdef9();// BIP 合同销售订单id + if (StringUtils.isEmpty(vdef9)) {// 为空,不是从bip 生成的 + return; + } + // 合同金额vdef17 + UFDouble ctmny = new UFDouble(hvo.getVdef17() == null ? "0" : hvo.getVdef17()); + // 预收比例vdef15 + UFDouble yfrate = new UFDouble(hvo.getVdef15() == null ? "0" : hvo.getVdef15()); + UFDouble temp_yf_mny = ctmny.multiply(yfrate); + + // 发货比例vdef16 + UFDouble fhrate = new UFDouble(hvo.getVdef16() == null ? "0" : hvo.getVdef16()); + UFDouble temp_fh_mny = ctmny.multiply(fhrate); + + // vdef14 预付款标识 + String vdef14 = "01";// 01无约定预付款 + + // vdef11 发货款标识 + String vdef11 = "fhk03";// fhk03无约定发货款 + + UFDouble total_mny = UFDouble.ZERO_DBL;// 当前组织下本合同所有收款单金额累计 + + String sum_sql = "select sum(money_cr) as money_cr from ar_gatheritem where def6 not in ('~') and dr=0 and def6='" + ctid + "'"; + Map map = (Map) new BaseDAO().executeQuery(sum_sql, new MapProcessor()); + if (map != null) { + total_mny = new UFDouble(String.valueOf(map.get("money_cr"))); + } + + + if ((MathTool.compareTo(yfrate, UFDouble.ZERO_DBL) == 0)) { + + } else { + if (MathTool.compareTo(total_mny, temp_yf_mny) >= 0) {// 累计收款金额≥合同金额*预收比例 + vdef14 = "02"; // 02有约定已收到预付款 + } else { + vdef14 = "03";// 03 有约定未收到款 + } + + } + + if ((MathTool.compareTo(fhrate, UFDouble.ZERO_DBL) == 0)) { + + } else { + if (MathTool.compareTo(total_mny, temp_fh_mny) >= 0) {// 累计收款金额≥合同金额*发货比例 + vdef11 = "fhk01";// fhk01有约定已收到发货款 + } else { + vdef11 = "fhk02";// fhk02有约定未收到发货款 + } + + + } + + DefdocVO[] defdocVOs = (DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='xsdd' ) and code='" + vdef14 + "' and dr=0 "); + if (defdocVOs != null && defdocVOs.length > 0) { + hvo.setVdef14(defdocVOs[0].getPrimaryKey()); + } + + defdocVOs = (DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='FHK' ) and code='" + vdef11 + "' and dr=0 "); + if (defdocVOs != null && defdocVOs.length > 0) { + hvo.setVdef11(defdocVOs[0].getPrimaryKey()); + } + + +// getSuperDMO().update(hvo); + pushBipCtOrderUpdate(hvo, vdef14, vdef11); + + } catch (DAOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * BIP 合同销售订单更新 + * + * @param hvo + * @param vdef14 预付款标识 + * @param vdef11 发货款标识 + */ + private void pushBipCtOrderUpdate(SaleOrderHVO hvo, String vdef14, String vdef11) { + + String baseUrl = ""; + + Map bipParamMap = checkBipParam(); + if (bipParamMap.isEmpty()) { + return; + } + + baseUrl = bipParamMap.get("baseUrl"); + String contractSaleOrderUrl = bipParamMap.get("contractSaleOrder");// 开票申请单回传 + if (StringUtils.isEmpty(contractSaleOrderUrl)) { + return; + } + Gson gson = new Gson(); + try { + String accessToken = getAccessToken(baseUrl, bipParamMap); + if (accessToken != "") { + Map tokenParam = new HashMap<>(); + tokenParam.put("access_token", accessToken); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + String custUpdateUrl = baseUrl + contractSaleOrderUrl; + JSONObject js_apct_detail = new JSONObject(); + JSONObject js_apct = new JSONObject(); + js_apct.put("id", hvo.getVdef9()); + js_apct.put("isShipRecdAmt", vdef11); + js_apct.put("isPreRecv", vdef14); + js_apct.put("actRecvAmt", hvo.getNreceivedmny().floatValue()); + js_apct.put("actPreRecvAmt", hvo.getNpreceivemny().floatValue()); + js_apct_detail.put("HTXSDD", js_apct); + String resultString = doSendHttp(custUpdateUrl, "POST", tokenParam, "", headers, js_apct_detail.toJSONString()); + Map updateMap = gson.fromJson(resultString, Map.class); + if (StringUtils.equals("200", updateMap.get("code").toString())) {// 保存更新成功后需要更新日志表 + getSuperDMO().update(hvo); + } else { +// getSuperDMO().update(hvo); + } + + } + } catch (InvalidKeyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (DAOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + + /** + * 检查bip参数是否完整 + * + * @return + */ + private Map checkBipParam() { + + Map map = new HashMap(); + + String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='BIP-sq' and dr=0 ) and dr=0"; + + try { + DefdocVO[] defdocVOs = (DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, strWhere); + if (defdocVOs != null && defdocVOs.length > 0) { + for (DefdocVO defdocVO : defdocVOs) { + + map.put(defdocVO.getCode().trim(), defdocVO.getName()); + + } + } + } catch (DAOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return map; + + } + + + private static String doGet(String path, Map params) throws IOException { + HttpURLConnection conn = null; + InputStream is = null; + BufferedReader br = null; + StringBuilder result = new StringBuilder(); + try { + if (params != null) { + String paramStr = ""; + for (String key : params.keySet()) { + if (!paramStr.isEmpty()) { + paramStr += '&'; + } + paramStr += key + '=' + params.get(key); + } + + if (path.indexOf('?') > 0) { + path += '&' + paramStr; + } else { + path += '?' + paramStr; + } + } + // 创建远程url连接对象 + URL url = new URL(path); + if ("https".equalsIgnoreCase(url.getProtocol())) {// 判定网址是否信任,不信任则调用忽略信任工具类SslUtil + IgnoreSslUtil.ignoreSsl(); + } + // 通过远程url连接对象打开一个连接,强转成HTTPURLConnection类 + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + // 设置连接超时时间和读取超时时间 + conn.setConnectTimeout(120000); + conn.setReadTimeout(120000); + conn.setRequestProperty("Accept", "application/json"); + // 发送请求 + conn.connect(); + // 通过conn取得输入流,并使用Reader读取 + if (200 == conn.getResponseCode()) { + is = conn.getInputStream(); + br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + String line; + while ((line = br.readLine()) != null) { + result.append(line); + System.out.println(line); + } + } else { + System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } +// finally { +// try { +// if (br != null) { +// br.close(); +// } +// if (is != null) { +// is.close(); +// } +// } catch (IOException ioe) { +// ioe.printStackTrace(); +// } +// conn.disconnect(); +// } + return result.toString(); + } + + + private String getAccessToken(String baseUrl, Map bipParamMap) throws NoSuchAlgorithmException, InvalidKeyException, IOException { + String tokenUrl = baseUrl + "/iuap-api-auth/open-auth/selfAppAuth/getAccessToken"; +// String appKey = "f10c4bf17b1d4e1fb08eb82bf8540eab"; + String appKey = bipParamMap.get("appKey"); + +// String appSecret = "71dc2a58ca378c1a1143231a62e73e75a60e9236"; + String appSecret = bipParamMap.get("appSecret"); + String accessToken = ""; + Map params = new HashMap<>(); + + + params.put("appKey", appKey); + String timestamp = String.valueOf(System.currentTimeMillis()); + params.put("timestamp", timestamp); + // 计算签名 + Map treeMap; + if (params instanceof TreeMap) { + treeMap = params; + } else { + treeMap = new TreeMap<>(params); + } + StringBuilder stringBuilder = new StringBuilder(); + for (Map.Entry entry : treeMap.entrySet()) { + stringBuilder.append(entry.getKey()).append(entry.getValue()); + } + Mac mac = Mac.getInstance("HmacSHA256"); + + mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + String base64String = Base64.getEncoder().encodeToString(signData); + String signature = URLEncoder.encode(base64String, "UTF-8"); + params.put("signature", signature); + + String responseString = doGet(tokenUrl, params); + + Gson gson = new Gson(); + Map result = gson.fromJson(responseString, Map.class); + if (StringUtils.equals("00000", result.get("code").toString())) { + Map tokenInfo = (Map) result.get("data"); + accessToken = (String) tokenInfo.get("access_token"); + + } + + + return accessToken; + } + + + public static String doSendHttp(String baseUrl, String method, Map paramMap, String mediaType, Map headers, String json) { + HttpURLConnection urlConnection = null; + InputStream in = null; + OutputStream out = null; + BufferedReader bufferedReader = null; + String result = null; + try { + StringBuffer sb = new StringBuffer(); + sb.append(baseUrl); + if (paramMap != null) { + sb.append("?"); + for (Map.Entry entry : paramMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key + "=" + value).append("&"); + baseUrl = sb.toString().substring(0, sb.toString().length() - 1); + } + } +// log.error("uRL:" + baseUrl); +// // 打印请求URL和方法 +// log.error("Request URL: " + baseUrl); +// log.error("Request Method: " + method); + URL urlobj = new URL(baseUrl); + if ("https".equalsIgnoreCase(urlobj.getProtocol())) {// 判定网址是否信任,不信任则调用忽略信任工具类SslUtil + IgnoreSslUtil.ignoreSsl(); + } + urlConnection = (HttpURLConnection) urlobj.openConnection(); + urlConnection.setConnectTimeout(50000); + urlConnection.setRequestMethod(method); + urlConnection.setDoInput(true); + urlConnection.setUseCaches(false); + // 如果设置了自定义头,则打印它们 + if (headers != null && !headers.isEmpty()) { + for (Map.Entry entry : headers.entrySet()) { + urlConnection.addRequestProperty(entry.getKey(), entry.getValue()); +// log.error("Request Header: " + entry.getKey() + ": " + entry.getValue()); + } + } + if (json != null && json.length() > 0) { +// log.error("Request Body: " + json); + urlConnection.setDoInput(true); + urlConnection.setDoOutput(true); + out = urlConnection.getOutputStream(); + out.write(json.getBytes("utf-8")); + out.flush(); + } + int resCode = urlConnection.getResponseCode(); + String ecod = urlConnection.getContentEncoding(); + if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED + || resCode == HttpURLConnection.HTTP_ACCEPTED) { + if (StringUtils.isNotEmpty(ecod) && ecod.equals("gzip")) { + in = new GZIPInputStream(urlConnection.getInputStream()); + } else { + in = urlConnection.getInputStream(); + } + } else { + in = urlConnection.getErrorStream(); + } + bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8")); + StringBuffer temp = new StringBuffer(); + String line = bufferedReader.readLine(); + while (line != null) { + temp.append(line).append("\r\n"); + line = bufferedReader.readLine(); + } + if (ecod == null || ecod.equals("gzip")) { + ecod = Charset.forName("utf-8").name(); + } + result = new String(temp.toString().getBytes("utf-8"), ecod); + } catch (Exception e) { + JSONObject js = new JSONObject(); + js.put("", -1); + js.put("message", "调用外系统接口失败:" + e.getMessage()); + result = js.toString(); + e.printStackTrace(); + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + urlConnection.disconnect(); + } + return result; + } + + + /* */ + /* */ + @POST + /* */ + @Path("/query") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString queryPayablebill(Map conditionMap) { + /* 79 */ + NCCRestUtils.initInvocationInfo(); + /* */ + try { + /* 81 */ + List> bills = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).queryBill(conditionMap); + /* 82 */ + return ResultMessageUtil.toJSON(bills); + /* 83 */ + } catch (BusinessException e) { + /* 84 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + + /* */ + /* */ + /* */ + /* */ + @POST + /* */ + @Path("/update") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString updatePayablebill(JSONString str) { + /* 95 */ + NCCRestUtils.initInvocationInfo(); + /* 96 */ + String json = str.toJSONString(); + /* 97 */ + Map billMap = (Map) fromJson(json, Map.class); + /* */ + try { + /* 99 */ + Map returnMap = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).updateBill(billMap); + /* 100 */ + return ResultMessageUtil.toJSON(returnMap); + /* 101 */ + } catch (BusinessException e) { + /* 102 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + + /* */ + /* */ + /* */ + @POST + /* */ + @Path("/delete") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString deleteGatheringbill(JSONString str) { + /* 112 */ + NCCRestUtils.initInvocationInfo(); + /* 113 */ + String json = str.toJSONString(); + /* 114 */ + Map billMap = (Map) fromJson(json, Map.class); + /* 115 */ + String[] pk_gatherbills = null; + /* 116 */ + if (StringUtils.isEmpty((CharSequence) billMap.get("pk_gatherbill"))) { + /* */ + /* */ + try { + /* 119 */ + List returnMap = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).getPkBySrc(billMap); + /* 120 */ + if (returnMap != null) { + /* 121 */ + pk_gatherbills = (String[]) returnMap.toArray(new String[returnMap.size()]); + /* */ + } else { + /* 123 */ + return ResultMessageUtil.exceptionToJSON(NCLangRes4VoTransl.getNCLangRes().getStrByID("2006pub_0", "02006pub-0970"), "filed"); + /* */ + } + /* */ + /* 126 */ + } catch (BusinessException e) { + /* 127 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } else { + /* 130 */ + String pk_gatherbill = (String) billMap.get("pk_gatherbill"); + /* 131 */ + String PK_GATHERBILL = NCESAPI.sqlEncode(pk_gatherbill); + /* 132 */ + pk_gatherbills = PK_GATHERBILL.split(","); + /* */ + } + /* */ + try { + /* 135 */ + IArapBillService service = (IArapBillService) NCLocator.getInstance().lookup(IArapBillService.class); + /* 136 */ + BaseAggVO[] bills = service.queryArapBillByPKs(pk_gatherbills, "F2"); + /* 137 */ + ((IARAPOpenAPIService) NCLocator.getInstance().lookup(IARAPOpenAPIService.class)).executeBatchPM("DELETE", bills); + /* 138 */ + Map returnMap = new HashMap(); + /* 139 */ + returnMap.put("successful", "Y"); + /* 140 */ + return ResultMessageUtil.toJSON(returnMap); + /* 141 */ + } catch (BusinessException e) { + /* 142 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + + /* */ + /* */ + /* */ + @POST + /* */ + @Path("/commit") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString CommitGatheringbill(JSONString str) { + /* 152 */ + NCCRestUtils.initInvocationInfo(); + /* 153 */ + String json = str.toJSONString(); + /* 154 */ + Map billMap = (Map) fromJson(json, Map.class); + /* 155 */ + String[] pk_gatherbills = null; + /* 156 */ + if (StringUtils.isEmpty((CharSequence) billMap.get("pk_gatherbill"))) { + /* */ + try { + /* 158 */ + List returnMap = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).getPkBySrc(billMap); + /* */ + /* 160 */ + if (returnMap != null) { + /* 161 */ + pk_gatherbills = (String[]) returnMap.toArray(new String[returnMap.size()]); + /* */ + } else { + /* 163 */ + return ResultMessageUtil.exceptionToJSON(NCLangRes4VoTransl.getNCLangRes().getStrByID("2006pub_0", "02006pub-0970"), "filed"); + /* */ + } + /* */ + /* 166 */ + } catch (BusinessException e) { + /* 167 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } else { + /* 170 */ + String pk_gatherbill = (String) billMap.get("pk_gatherbill"); + /* 171 */ + String PK_GATHERBILL = NCESAPI.sqlEncode(pk_gatherbill); + /* 172 */ + pk_gatherbills = PK_GATHERBILL.split(","); + /* */ + } + /* */ + try { + /* 175 */ + Map returnMap = ((IARAPOpenAPIService) NCLocator.getInstance().lookup(IARAPOpenAPIService.class)).doBatchCommit(pk_gatherbills, "F2", "COMMIT"); + /* 176 */ + if (Integer.parseInt(returnMap.get("failNum").toString()) == 0) { + /* 177 */ + return ResultMessageUtil.toJSON(returnMap.get("message")); + /* */ + } + /* 179 */ + if (Integer.parseInt(returnMap.get("successNum").toString()) == 0) { + /* 180 */ + return ResultMessageUtil.exceptionToJSON((String) returnMap.get("message"), "false"); + /* */ + } + /* 182 */ + return ResultMessageUtil.toJSON(returnMap.get("message")); + /* 183 */ + } catch (BusinessException e) { + /* 184 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + + /* */ + /* */ + /* */ + /* */ + /* */ + @POST + /* */ + @Path("/uncommit") + /* */ + @Consumes({"application/json"}) + /* */ + @Produces({"application/json"}) + /* */ public JSONString UnCommitGatheringbill(JSONString str) { + /* 196 */ + NCCRestUtils.initInvocationInfo(); + /* 197 */ + String json = str.toJSONString(); + /* 198 */ + Map billMap = (Map) fromJson(json, Map.class); + /* 199 */ + String[] pk_gatherbills = null; + /* 200 */ + if (StringUtils.isEmpty((CharSequence) billMap.get("pk_gatherbill"))) { + /* */ + try { + /* 202 */ + List returnMap = ((IGatheringbillOpenService) NCLocator.getInstance().lookup(IGatheringbillOpenService.class)).getPkBySrc(billMap); + /* */ + /* 204 */ + if (returnMap != null) { + /* 205 */ + pk_gatherbills = (String[]) returnMap.toArray(new String[returnMap.size()]); + /* */ + } else { + /* 207 */ + return ResultMessageUtil.exceptionToJSON(NCLangRes4VoTransl.getNCLangRes().getStrByID("2006pub_0", "02006pub-0970"), "filed"); + /* */ + } + /* */ + /* 210 */ + } catch (BusinessException e) { + /* 211 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } else { + /* 214 */ + String pk_gatherbill = (String) billMap.get("pk_gatherbill"); + /* 215 */ + String PK_GATHERBILL = NCESAPI.sqlEncode(pk_gatherbill); + /* 216 */ + pk_gatherbills = PK_GATHERBILL.split(","); + /* */ + } + /* */ + try { + /* 219 */ + Map returnMap = ((IARAPOpenAPIService) NCLocator.getInstance().lookup(IARAPOpenAPIService.class)).doBatchCommit(pk_gatherbills, "F2", "UNCOMMIT"); + /* 220 */ + if (Integer.parseInt(returnMap.get("failNum").toString()) == 0) { + /* 221 */ + return ResultMessageUtil.toJSON(returnMap.get("message")); + /* */ + } + /* 223 */ + if (Integer.parseInt(returnMap.get("successNum").toString()) == 0) { + /* 224 */ + return ResultMessageUtil.exceptionToJSON((String) returnMap.get("message"), "false"); + /* */ + } + /* 226 */ + return ResultMessageUtil.toJSON(returnMap.get("message")); + /* 227 */ + } catch (BusinessException e) { + /* 228 */ + return ResultMessageUtil.exceptionToJSON(e); + /* */ + } + /* */ + } + /* */ +} + + +/* Location: E:\2024\tkncchome\modules\arap\lib\pubarap_openapi.jar!/nc/api/arap/resource/GatheringbillRestResource.class + * Java compiler version: 8 (52.0) + * JD-Core Version: 1.0.7 + */ \ No newline at end of file From 5a11c774179d6bb0ddf4a643460fb4a2ae73fbfe Mon Sep 17 00:00:00 2001 From: mzr <1562242162@qq.com> Date: Tue, 4 Mar 2025 18:06:59 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E9=94=80=E5=94=AE=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E7=94=9F=E5=8D=95=E5=8F=8A=E9=94=80=E5=94=AE=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=BF=AE=E8=AE=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/so/m30/APISaleOrderMaitainImpl.java | 412 ++++++++++-- .../api/so/m30/IAPISaleOrderMaitain.java | 35 + .../openapi/so/m30/SaleOrderResource.java | 629 ++++++++++++++++++ 3 files changed, 1035 insertions(+), 41 deletions(-) diff --git a/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java b/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java index 09c1b65..0fbe25c 100644 --- a/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java +++ b/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java @@ -1,5 +1,6 @@ package nccloud.api.impl.so.m30; +import com.alibaba.fastjson.JSON; import nc.bd.itf.tools.BFPubTools; import nc.bs.dao.BaseDAO; import nc.bs.framework.common.NCLocator; @@ -9,6 +10,7 @@ import nc.itf.so.m30.self.ISaleOrderMaintain; import nc.itf.so.m30.self.ISaleOrderScriptMaintain; import nc.itf.uap.pf.IPFBusiAction; import nc.jdbc.framework.processor.ColumnProcessor; +import nc.jdbc.framework.processor.MapProcessor; import nc.pubitf.so.m30.api.ISaleOrderQueryAPI; import nc.vo.ml.NCLangRes4VoTransl; import nc.vo.pub.BusinessException; @@ -16,9 +18,11 @@ import nc.vo.pub.VOStatus; import nc.vo.pub.lang.UFBoolean; import nc.vo.pub.lang.UFDate; import nc.vo.pub.lang.UFDouble; +import nc.vo.pubapp.AppContext; import nc.vo.pubapp.pattern.exception.ExceptionUtils; import nc.vo.pubapp.pflow.PfUserObject; import nc.vo.scmpub.check.billvalidate.BillVOsCheckRule; +import nc.vo.scmpub.fill.pricemny.INumPriceMnyCalculator; import nc.vo.scmpub.res.billtype.SOBillType; import nc.vo.scmpub.util.StringUtil; import nc.vo.so.m30.entity.SaleOrderBVO; @@ -33,17 +37,14 @@ import nc.vo.so.pub.keyvalue.VOKeyValue; import nc.vo.so.pub.util.AggVOUtil; import nc.vo.so.pub.util.SOCurrencyUtil; import nccloud.api.impl.so.m30.check.SaleOrderValidator; +import nccloud.api.impl.so.m30.fill.SaleOrderNPriceMnyCal; import nccloud.api.impl.so.m30.fill.SaleOrderSaveFillValue; -import nccloud.api.impl.so.m30.fill.SetUpdateData; import nccloud.api.so.m30.IAPISaleOrderMaitain; import nccloud.baseapp.core.log.NCCForUAPLogger; import nccloud.dto.scmpub.pflow.SCMCloudPFlowContext; import nccloud.pubitf.scmpub.commit.service.IBatchRunScriptService; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * @Description: 销售订单维护实现类 @@ -51,7 +52,7 @@ import java.util.Set; * @date: 2019-10-23 下午4:57:49 * @Copyright: */ -public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { +public class APISaleOrderMaitainImpl implements IAPISaleOrderMaitain { @Override public SaleOrderVO[] save(SaleOrderVO[] vos) throws BusinessException { @@ -81,9 +82,9 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { for (SaleOrderBVO bvo : bvos) { bvo.setCcurrencyid(BFPubTools.getString_TrimAsNull(o1)); if (!BFPubTools.getString_TrimAsNull(o).equals(ccurrencyorgid)) { - bvo.setNexchangerate(exchangerate); + // bvo.setNexchangerate(exchangerate); } else { - bvo.setNexchangerate(UFDouble.ONE_DBL); + // bvo.setNexchangerate(UFDouble.ONE_DBL); } } @@ -141,28 +142,28 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { String zbbz = childrenVO.getCcurrencyid(); childrenVO.setFtaxtypeflag(1); - //得到税率 + // 得到税率 UFDouble ntaxrate = BFPubTools.getUFDouble_NullAsZero(childrenVO.getNtaxrate()); // 折本汇率 UFDouble nexchangerate = childrenVO.getNexchangerate(); - //含税单价 + // 含税单价 UFDouble nqtorigtaxprice = childrenVO.getNqtorigtaxprice(); - //无税单价 + // 无税单价 UFDouble nqtorigprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); // 价税合计 // UFDouble norigtaxmny=nqtorigtaxprice.multiply(childrenVO.getNqtunitnum()); UFDouble norigtaxmny = nqtorigtaxprice.multiply(childrenVO.getNqtunitnum()).setScale(2, 4); childrenVO.setNorigtaxmny(norigtaxmny); - //无税金额 + // 无税金额 UFDouble norigmny = nqtorigprice.multiply(childrenVO.getNqtunitnum()); childrenVO.setNorigmny(Currency.getFormaUfValue(ybpk, norigmny)); - //税额 + // 税额 childrenVO.setNqtorigprice(nqtorigprice.setScale(4, 4)); - //无税本币金额单价 + // 无税本币金额单价 UFDouble taxspric = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); @@ -171,7 +172,7 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { nqtorigprice = nqtorigprice.setScale(4, 4); - //nqtorigtaxnetprc--含税净价 + // nqtorigtaxnetprc--含税净价 childrenVO.setNqtorigtaxnetprc(nqtorigtaxprice); //,nqtorignetprice --无税净价 childrenVO.setNqtorignetprice(nqtorigprice); @@ -189,7 +190,7 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { wsje = Currency.getFormaUfValue(zbbz, wsje); - //本币无税金额 + // 本币无税金额 childrenVO.setNorigtaxprice(nqtorigtaxprice.div(dVqtunitrate).setScale(4, 4)); //,norigprice --主无税单价 childrenVO.setNorigprice(nqtorigprice.div(dVqtunitrate).setScale(4, 4)); @@ -234,8 +235,21 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { @Override - public SaleOrderVO[] update(SaleOrderVO[] vos) throws BusinessException { - + public SaleOrderVO[] update(SaleOrderVO[] vos, List> paramList) throws BusinessException { + for (SaleOrderVO vo : vos) { + String countSql = "SELECT count(1) FROM so_saleinvoice_b a" + + " LEFT JOIN so_saleinvoice b ON a.csaleinvoiceid = b.csaleinvoiceid" + + " WHERE b.fopposeflag = 0 AND nvl(b.dr, 0) = 0 and csrcid = '[csrcid]' "; + countSql = countSql.replace("[csrcid]", vo.getParentVO().getCsaleorderid()); + Integer num = (Integer) new BaseDAO().executeQuery(countSql, new ColumnProcessor()); + if (num > 0) { + // fopposeflag 对冲标记 0=正常 1=已被对冲 2=对冲生成 + ExceptionUtils.wrappBusinessException("下游存在未红冲完成的销售发票"); + return null; + } + } + // 编码转id + setOtherId(vos); // 获取参数vo的id Map> ids = this.getIds(vos); if (ids.keySet() == null || ids.values() == null @@ -247,24 +261,57 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { ISaleOrderMaintain service = NCLocator.getInstance().lookup(ISaleOrderMaintain.class); SaleOrderVO[] originVos = service.querySaleorder(hids); - SetUpdateData setData = new SetUpdateData(); - setData.setData(vos, originVos); - setOtherId(vos); + // SetUpdateData setData = new SetUpdateData(); + // setData.setData(vos, originVos); // 有值不覆盖 - SaleOrderVO[] combinBillVOs = - (SaleOrderVO[]) AggVOUtil.combinBillVO(vos, originVos); - // 设置单据状态 + // SaleOrderVO[] combinBillVOs = + // (SaleOrderVO[]) AggVOUtil.combinBillVO(vos, originVos); + // 创建一个新的数组,并进行深拷贝 + SaleOrderVO[] combinBillVOs = new SaleOrderVO[originVos.length]; + for (int i = 0; i < originVos.length; i++) { + combinBillVOs[i] = (SaleOrderVO) originVos[i].clone(); + } + + // 将 vos 中的元素按主键存储在 Map 中 + Map vosMap = new HashMap<>(); for (SaleOrderVO vo : vos) { - vo.getParentVO().setStatus(VOStatus.UPDATED); + vosMap.put(vo.getParentVO().getCsaleorderid(), vo); + } + + // 遍历 combinBillVOs 并更新字段 + for (SaleOrderVO vo : combinBillVOs) { + SaleOrderHVO hvo = vo.getParentVO(); + String primaryKey = hvo.getCsaleorderid(); + SaleOrderVO bipVo = vosMap.get(primaryKey); + // 创建一个Set来存储vos中多的csaleorderbid + Set delBids = findOtherBids(bipVo.getChildrenVO(), vo.getChildrenVO()); + // 设置单据状态 + hvo.setStatus(VOStatus.UPDATED); + // 比较combinBillVOs中的BVO和vos中的BVO for (SaleOrderBVO bvo : vo.getChildrenVO()) { bvo.setStatus(VOStatus.UPDATED); + // 设置删除的物料行的状态 + if (!delBids.isEmpty() && delBids.contains(bvo.getCsaleorderbid())) { + bvo.setStatus(VOStatus.DELETED); + NCCForUAPLogger.debug("findDeletedBids:" + VOStatus.DELETED + ",csaleorderbid = " + bvo.getCsaleorderbid()); + } + } + // 更新 combinBillVO 中的字段为 vos 中的值 + updateFields(vo, bipVo); + // 设置新增的物料行 + if (paramList != null && !paramList.isEmpty()) { + // addBvo(combinBillVOs, paramList); } } + // 联动计算 + INumPriceMnyCalculator cal = new SaleOrderNPriceMnyCal(combinBillVOs); + cal.calculate(); // 保存 ISaleOrderScriptMaintain maintainsrv = NCLocator.getInstance().lookup(ISaleOrderScriptMaintain.class); SaleOrderVO[] retvos = maintainsrv.saleOrderUpdate(combinBillVOs, null, originVos); + ; return retvos; } @@ -289,21 +336,25 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { private void setOtherId(SaleOrderVO[] vos) { for (SaleOrderVO vo : vos) { // 部门、业务员、开票客户编码转id - String cdeptvid = vo.getParentVO().getCdeptvid(); - String cemployeeid = vo.getParentVO().getCdeptvid(); - String cinvoicecustid = vo.getParentVO().getCdeptvid(); + SaleOrderHVO orderHVO = vo.getParentVO(); + String csaleorderid = orderHVO.getCsaleorderid(); + String cdeptvid = orderHVO.getCdeptvid(); + String cemployeeid = orderHVO.getCemployeeid(); + String cinvoicecustid = orderHVO.getCinvoicecustid(); try { String sql = ""; // 部门 if (cdeptvid != null && !cdeptvid.isEmpty()) { - sql = " select pk_dept from org_dept where code = '[code]' "; + sql = " select pk_vid,pk_dept from org_dept_v where code = '[code]' "; sql = sql.replace("[code]", cdeptvid); - Object deptObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); - NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-deptObj:" + deptObj); - if (deptObj != null) { - String id = BFPubTools.getString_TrimAsNull(deptObj); - if (!id.isEmpty()) { - vo.getParentVO().setCdeptvid(id); + Map deptMap = (Map) new BaseDAO().executeQuery(sql, new MapProcessor()); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-deptObj:" + deptMap); + if (deptMap != null && !deptMap.isEmpty()) { + if (!"".equals(deptMap.getOrDefault("pk_dept", "") + "")) { + orderHVO.setCdeptid(deptMap.getOrDefault("pk_dept", "") + ""); + } + if (!"".equals(deptMap.getOrDefault("pk_vid", "") + "")) { + orderHVO.setCdeptvid(deptMap.getOrDefault("pk_vid", "") + ""); } } } @@ -311,12 +362,12 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { if (cemployeeid != null && !cemployeeid.isEmpty()) { sql = " select pk_psndoc from bd_psndoc where code = '[code]' "; sql = sql.replace("[code]", cemployeeid); - Object staffObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + Object staffObj = new BaseDAO().executeQuery(sql, new ColumnProcessor("pk_psndoc")); NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-staffObj:" + staffObj); if (staffObj != null) { String id = BFPubTools.getString_TrimAsNull(staffObj); if (!id.isEmpty()) { - vo.getParentVO().setCdeptvid(id); + orderHVO.setCemployeeid(id); } } } @@ -324,12 +375,12 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { if (cinvoicecustid != null && !cinvoicecustid.isEmpty()) { sql = " select pk_customer from bd_customer where code = '[code]' "; sql = sql.replace("[code]", cinvoicecustid); - Object invCustObj = new BaseDAO().executeQuery(sql, new ColumnProcessor()); + Object invCustObj = new BaseDAO().executeQuery(sql, new ColumnProcessor("pk_customer")); NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-invCustObj:" + invCustObj); if (invCustObj != null) { String id = BFPubTools.getString_TrimAsNull(invCustObj); if (!id.isEmpty()) { - vo.getParentVO().setCdeptvid(id); + orderHVO.setCinvoicecustid(id); } } } @@ -340,6 +391,65 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { } } + private void updateFields(SaleOrderVO target, SaleOrderVO source) { + // 更新 SaleOrderHVO 字段 + SaleOrderHVO targetHVO = target.getParentVO(); + SaleOrderHVO sourceHVO = source.getParentVO(); + // 表头修改修改的字段 + String cdeptvid = sourceHVO.getCdeptvid(); + String cdeptid = sourceHVO.getCdeptid(); + if (cdeptvid != null && !cdeptvid.isEmpty()) { + targetHVO.setCdeptvid(cdeptvid); + targetHVO.setCdeptid(cdeptid); + } + + String cemployeeid = sourceHVO.getCemployeeid(); + if (cemployeeid != null && !cemployeeid.isEmpty()) { + targetHVO.setCemployeeid(cemployeeid); + } + String cinvoicecustid = sourceHVO.getCinvoicecustid(); + if (cinvoicecustid != null && !cinvoicecustid.isEmpty()) { + targetHVO.setCinvoicecustid(cinvoicecustid); + } + + // 更新 SaleOrderBVO 字段 + SaleOrderBVO[] targetBVOs = target.getChildrenVO(); + SaleOrderBVO[] sourceBVOs = source.getChildrenVO(); + + // BVO 的主键是 csaleorderbid + Map sourceBVOsMap = new HashMap<>(); + for (SaleOrderBVO bvo : sourceBVOs) { + sourceBVOsMap.put(bvo.getCsaleorderbid(), bvo); + } + + for (SaleOrderBVO targetBVO : targetBVOs) { + String bvoId = targetBVO.getCsaleorderbid(); + SaleOrderBVO sourceBVO = sourceBVOsMap.get(bvoId); + if (sourceBVO != null) { + int status = targetBVO.getStatus(); + if (VOStatus.UPDATED == status) { + // 数量 + UFDouble nnum = sourceBVO.getNnum(); + targetBVO.setNnum(nnum); + targetBVO.setNastnum(nnum); + // targetBVO.setNqtunitnum(nnum); + // 价税合计 + targetBVO.setNorigtaxmny(sourceBVO.getNorigtaxmny()); + targetBVO.setCmaterialvid(sourceBVO.getCmaterialvid()); + // 折本汇率 + targetBVO.setNexchangerate(sourceBVO.getNexchangerate()); + // 物料编码 + String cmaterialvid = sourceBVO.getCmaterialvid(); + // 物料关联字段赋值 + if (cmaterialvid != null && !cmaterialvid.isEmpty()) { + setMaterl(targetBVO); + } + } + + } + } + } + @Override public SaleOrderVO[] modify(SaleOrderHistoryVO[] vos) throws BusinessException { @@ -365,9 +475,9 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { for (SaleOrderHistoryBVO bvo : bvos) { bvo.setCcurrencyid(BFPubTools.getString_TrimAsNull(o1)); if (!BFPubTools.getString_TrimAsNull(o).equals(ccurrencyorgid)) { - bvo.setNexchangerate(exchangerate); + // bvo.setNexchangerate(exchangerate); } else { - bvo.setNexchangerate(UFDouble.ONE_DBL); + // bvo.setNexchangerate(UFDouble.ONE_DBL); } } @@ -400,4 +510,224 @@ public class APISaleOrderMaitainImpl2 implements IAPISaleOrderMaitain { hvo.setCemployeeid(oldvo.getCemployeeid()); } + private void setMaterl(SaleOrderBVO bVO) { + String cmaterialvid = bVO.getCmaterialvid(); + UFDouble nnum = bVO.getNnum(); + UFDouble ntaxrate = bVO.getNtaxrate(); + try { + String sql = " select a.pk_material,a.pk_source, a.pk_measdoc cunitid,nvl(b.pk_measdoc,a.pk_measdoc) castunitid,nvl(b.measrate,'1/1') measrate " + + "from bd_material a left join bd_materialconvert b on a.pk_material=b.pk_material " + + "where a.code='" + cmaterialvid + "' "; + Map map = (Map) new BaseDAO().executeQuery(sql, new MapProcessor()); + if (map == null) { + throw new BusinessException(cmaterialvid + "物料未查到"); + } + NCCForUAPLogger.debug(String.format( + "setMaterl: cqtunitid = [%S], cunitid = [%S], castunitid = [%S]", + map.get("cqtunitid"), map.get("cunitid"), map.get("castunitid"))); + bVO.setAttributeValue("castunitid", map.get("castunitid")); + bVO.setAttributeValue("vchangerate", map.get("vchangerate")); + + // 重新计算金额 + bVO.setAttributeValue("cqtunitid", map.get("cunitid")); + bVO.setAttributeValue("cunitid", map.get("cunitid")); + + bVO.setAttributeValue("cmaterialid", map.get("pk_material")); + bVO.setAttributeValue("cmaterialvid", map.get("pk_material")); + + UFDouble nqtunitnum = BFPubTools.getUFDouble_NullAsZero(nnum).div(BFPubTools.getUFDouble_NullAsZero(map.get("measrate").toString().split("/")[0])); + bVO.setAttributeValue("nqtunitnum", nqtunitnum); + + sql = "select sl.pk_taxcode from bd_taxrate sl inner join bd_taxcode sm on sl.pk_taxcode=sm.pk_taxcode where sl.taxrate=" + ntaxrate + " and sm.pk_group<>'~' " + + ""; + + String o_pk_project = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor()); + bVO.setAttributeValue("ctaxcodeid", o_pk_project); + } catch (BusinessException e) { + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setMaterl:" + e.getMessage()); + throw new RuntimeException(e); + } + } + + // 新增函数:比较两个vos,返回新增的bids和删除的bids + private Set findOtherBids(SaleOrderBVO[] bipBVOs, SaleOrderBVO[] nccBVOs) { + Set bipBids = new HashSet<>(); + for (SaleOrderBVO bvo : bipBVOs) { + bipBids.add(bvo.getCsaleorderbid()); + } + + Set deletedBids = new HashSet<>(); + for (SaleOrderBVO bvo : nccBVOs) { + if (!bipBids.contains(bvo.getCsaleorderbid())) { + deletedBids.add(bvo.getCsaleorderbid()); + } + } + return deletedBids; + } + + /** + * 修订销售订单的时候新增销售订单物料行的数据 + */ + private void addBvo(SaleOrderVO[] combinBillVOs, List> paramList) { + try { + for (SaleOrderVO vo : combinBillVOs) { + SaleOrderHVO hvo = vo.getParentVO(); + SaleOrderBVO[] bvos = vo.getChildrenVO(); + List bvoList = new ArrayList<>(Arrays.asList(bvos)); + String csaleorderid = hvo.getCsaleorderid(); + String ybpk = hvo.getCorigcurrencyid(); + Map objectMap = Collections.emptyMap(); + for (Map map : paramList) { + objectMap = (Map) map.get(csaleorderid); + } + if (objectMap != null && !objectMap.isEmpty()) { + List bodyArr = (List) objectMap.get("so_saleorder_b"); + for (Object body : bodyArr) { + Map bodydata = (Map) body; + if ("add".equals(bodydata.get("status"))) { + String pkOrgV = hvo.getPk_org_v(); + String pkOrg = hvo.getPk_org(); + String pk_group = AppContext.getInstance().getPkGroup(); + // 新数据的实体 + // SaleOrderBVO newBvo = (SaleOrderBVO) bvos[0].clone(); + SaleOrderBVO newBvo = new SaleOrderBVO(); + newBvo.setStatus(VOStatus.NEW); + newBvo.setAttributeValue("pk_group", pk_group); + newBvo.setAttributeValue("cprojectid", bodydata.get("cprojectid")); + // newBvo.setAttributeValue("ctrafficorgvid", pkOrg); + // newBvo.setAttributeValue("csendstockorgvid", pkOrg); + // newBvo.setAttributeValue("csendstordocid", pkOrg); + // newBvo.setAttributeValue("csendstockorgid", pkOrg); + // newBvo.setAttributeValue("carorgid", pkOrg); + // newBvo.setAttributeValue("carorgvid", pkOrg); + // newBvo.setAttributeValue("csettleorgid", pkOrg); + // newBvo.setAttributeValue("csettleorgvid", pkOrg); + + newBvo.setAttributeValue("ctaxcountryid", "CN"); + newBvo.setAttributeValue("crececountryid", "CN"); + newBvo.setAttributeValue("csendcountryid", "CN"); + + newBvo.setAttributeValue("fbuysellflag", 1); + UFDouble nexchangerateBip = BFPubTools.getUFDouble_NullAsZero(bodydata.get("nexchangerate")); + newBvo.setNexchangerate(nexchangerateBip); + // 设置物料的关联字段的值 + newBvo.setCmaterialvid(bodydata.get("cmaterialvid") + ""); + UFDouble ntaxrate = BFPubTools.getUFDouble_NullAsZero(bodydata.get("ntaxrate")); + UFDouble nnum = BFPubTools.getUFDouble_NullAsZero(bodydata.get("nnum")); + newBvo.setAttributeValue("ntaxrate", ntaxrate); + newBvo.setAttributeValue("nnum", nnum); + newBvo.setVbdef11(bodydata.getOrDefault("vbdef11", "") + ""); + + UFDouble norigtaxprice = BFPubTools.getUFDouble_NullAsZero(bodydata.get("norigtaxprice")); + newBvo.setAttributeValue("norigtaxprice", norigtaxprice); + UFDouble norigprice = BFPubTools.getUFDouble_NullAsZero(bodydata.get("norigprice")); + newBvo.setAttributeValue("norigprice", norigprice); + setMaterl(newBvo); + newBvo.setCsaleorderbid(null); + + newBvo.setCcurrencyid(ybpk); + String zbbz = newBvo.getCcurrencyid(); + + newBvo.setFtaxtypeflag(1); + + // 折本汇率 + UFDouble nexchangerate = newBvo.getNexchangerate(); + // 含税单价 + UFDouble nqtorigtaxprice = BFPubTools.getUFDouble_NullAsZero(bodydata.get("nqtorigtaxprice")); + newBvo.setAttributeValue("nqtorigtaxprice", nqtorigtaxprice); + // 无税单价 + UFDouble nqtorigprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); + // 价税合计 + UFDouble norigtaxmny = nqtorigtaxprice.multiply(newBvo.getNqtunitnum()).setScale(2, 4); + newBvo.setNorigtaxmny(norigtaxmny); + // 无税金额 + UFDouble norigmny = nqtorigprice.multiply(newBvo.getNqtunitnum()); + + newBvo.setNorigmny(Currency.getFormaUfValue(ybpk, norigmny)); + // 税额 + newBvo.setNqtorigprice(nqtorigprice.setScale(4, 4)); + + // 无税本币金额单价 + UFDouble taxspric = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))); + + + nqtorigprice = nqtorigprice.setScale(4, 4); + // nqtorigtaxnetprc--含税净价 + newBvo.setNqtorigtaxnetprc(nqtorigtaxprice); + //,nqtorignetprice --无税净价 + newBvo.setNqtorignetprice(nqtorigprice); + String Vqtunitrate = newBvo.getVqtunitrate(); + UFDouble dVqtunitrate = UFDouble.ONE_DBL; + if (Vqtunitrate != null) { + dVqtunitrate = BFPubTools.getUFDouble_NullAsZero(Vqtunitrate.split("/")[0]); + } + //,norigtaxprice --主含税单价 + + UFDouble wsje = taxspric.multiply(nexchangerate).multiply(newBvo.getNqtunitnum()); + if (ybpk.equals(zbbz) && BFPubTools.getString_TrimAsNull(newBvo.getCqtunitid()).equals(BFPubTools.getString_TrimAsNull(newBvo.getCastunitid()))) { + wsje = taxspric.multiply(nexchangerate).multiply(newBvo.getNqtunitnum()); + } + + + wsje = Currency.getFormaUfValue(zbbz, wsje); + // 本币无税金额 + newBvo.setNorigtaxprice(nqtorigtaxprice.div(dVqtunitrate).setScale(4, 4)); + //,norigprice --主无税单价 + newBvo.setNorigprice(nqtorigprice.div(dVqtunitrate).setScale(4, 4)); + //,norigtaxnetprice --主含税净价 + newBvo.setNorigtaxnetprice(newBvo.getNorigtaxprice()); + //,norignetprice --主无税净价 + newBvo.setNorignetprice(newBvo.getNorigprice()); + // ncaltaxmny --计税金额 + + // ,nqttaxprice --本币含税单价 + newBvo.setNqttaxprice(nqtorigtaxprice.multiply(nexchangerate)); + //,nqtprice --本币无税单价 + UFDouble bbwsd = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + newBvo.setNqtprice(bbwsd.setScale(4, 4)); + //, nqttaxnetprice --本币含税净价 + newBvo.setNqttaxnetprice(nqtorigtaxprice.multiply(nexchangerate)); + //,nqtnetprice --本币无税净价 + UFDouble Nqtnetprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + newBvo.setNqtnetprice(Nqtnetprice.setScale(4, 4)); + //,ntaxprice --主本币含税单价 , nprice --主本币无税单价 + newBvo.setNtaxprice(nqtorigtaxprice.div(dVqtunitrate).multiply(nexchangerate).setScale(4, 4)); + UFDouble Nprice = nqtorigtaxprice.div(dVqtunitrate).div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).multiply(nexchangerate); + newBvo.setNprice(Nprice.setScale(4, 4)); + //,ntaxnetprice --主本币含税净价 + //,nnetprice --主本币无税净价 + newBvo.setNtaxnetprice(nqtorigtaxprice.div(dVqtunitrate).multiply(nexchangerate).setScale(4, 4)); + UFDouble Nnetprice = nqtorigtaxprice.div(UFDouble.ONE_DBL.add(ntaxrate.div(100))).div(dVqtunitrate); + newBvo.setNnetprice(Nnetprice.multiply(nexchangerate).setScale(4, 4)); + // nmny --本币无税金额 + // ntaxmny-- 本币价税合计 + newBvo.setNmny(Currency.getFormaUfValue(zbbz, norigmny.multiply(nexchangerate))); + newBvo.setNtaxmny(nqtorigtaxprice.multiply(nexchangerate).multiply(newBvo.getNqtunitnum()).setScale(2, 4)); + newBvo.setNcaltaxmny(wsje); + UFDouble ntax = norigtaxmny.multiply(nexchangerate).sub(wsje); + newBvo.setNtax(ntax.setScale(2, 4)); + newBvo.setCrowno(bodydata.get("crowno") + ""); + bvoList.add(newBvo); + } + } + } + SaleOrderBVO[] array = bvoList.toArray(new SaleOrderBVO[0]); + vo.setChildrenVO(array); + } + // 填充默认值 + new SaleOrderSaveFillValue().setDefValue(combinBillVOs); + for (SaleOrderVO combinBillVO : combinBillVOs) { + for (SaleOrderBVO saleOrderBVO : combinBillVO.getChildrenVO()) { + // 将实体对象转换为JSON字符串 + String jsonString = JSON.toJSONString(saleOrderBVO); + NCCForUAPLogger.debug("jsonString:" + jsonString); + } + } + + } catch (Exception e) { + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-addBvo:" + e.getMessage()); + throw new RuntimeException(e); + } + } + } diff --git a/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java b/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java index e69de29..9aacd84 100644 --- a/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java +++ b/so/src/public/nccloud/api/so/m30/IAPISaleOrderMaitain.java @@ -0,0 +1,35 @@ +package nccloud.api.so.m30; + +import nc.vo.pub.BusinessException; +import nc.vo.so.m30.entity.SaleOrderVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryVO; + +import java.util.List; +import java.util.Map; + +/** + * @version NCC1909 + * @Description: 销售订单维护接口 + * @author: yanghff + * @date: 2019-11-1 上午9:59:48 + */ +public interface IAPISaleOrderMaitain { + + /** + * @Description: 销售订单新增保存 + * @date: 2019-11-1 上午10:00:22 + * @version NCC1909 + */ + SaleOrderVO[] save(SaleOrderVO[] vos) throws BusinessException; + + /** + * @Description: 销售订单修改保存 + * @date: 2019-11-1 上午10:17:46 + * @version NCC1909 + */ + SaleOrderVO[] update(SaleOrderVO[] vos, List> paramList) throws BusinessException; + + // 变更销售销售订单 + SaleOrderVO[] modify(SaleOrderHistoryVO[] vos) throws BusinessException; + +} diff --git a/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java b/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java index e69de29..d1adc92 100644 --- a/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java +++ b/so/src/public/nccloud/openapi/so/m30/SaleOrderResource.java @@ -0,0 +1,629 @@ +/** + * + */ +package nccloud.openapi.so.m30; + +import nc.bd.itf.tools.BFPubTools; +import nc.bs.dao.BaseDAO; +import nc.bs.framework.common.InvocationInfoProxy; +import nc.bs.framework.common.NCLocator; +import nc.itf.bd.defdoc.IDefdocService; +import nc.itf.pim.project.prv.IProject; +import nc.itf.so.m30.revise.ISaleOrderReviseMaintainApp; +import nc.jdbc.framework.processor.ColumnListProcessor; +import nc.jdbc.framework.processor.ColumnProcessor; +import nc.jdbc.framework.processor.MapProcessor; +import nc.ui.querytemplate.querytree.IQueryScheme; +import nc.vo.bd.defdoc.DefdocVO; +import nc.vo.ml.NCLangRes4VoTransl; +import nc.vo.pim.project.ProjectHeadVO; +import nc.vo.pub.BusinessException; +import nc.vo.pub.VOStatus; +import nc.vo.pub.lang.UFDateTime; +import nc.vo.pubapp.AppContext; +import nc.vo.scmpub.util.CollectionUtils; +import nc.vo.scmpub.util.VOEntityUtil; +import nc.vo.so.m30.entity.SaleOrderBVO; +import nc.vo.so.m30.entity.SaleOrderHVO; +import nc.vo.so.m30.entity.SaleOrderVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryBVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryHVO; +import nc.vo.so.m30.revise.entity.SaleOrderHistoryVO; +import nccloud.api.rest.utils.NCCRestUtils; +import nccloud.api.so.m30.IAPISaleOrderMaitain; +import nccloud.api.so.m30.IAPISaleOrderQuery; +import nccloud.framework.core.exception.ExceptionUtils; +import nccloud.openapi.scmpub.pub.NCCPubRestResource; +import nccloud.openapi.scmpub.pub.TransferMapToVOTool; +import nccloud.openapi.scmpub.util.BillFieldsCodeToPkUtil; +import nccloud.openapi.scmpub.util.CallReturnBuildUtil; +import nccloud.openapi.so.m30.mapping.SaleOrderFieldMapping; +import nccloud.openapi.so.utils.QuerySchemeUtils; +import org.json.JSONString; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @version NCC1909 + * @Description: 销售订单资源访问类 + * @author: yanghff + * @date: 2019-11-1 上午10:02:32 + */ +@Path("so/saleorder") +public class SaleOrderResource extends NCCPubRestResource { + private Integer pageNo = defaultPageIndex; + private Integer pageSize = defaultPageNum; + private static String BODYTABLE = "so_saleorder_b"; + private static String HEADTABLE = "so_saleorder"; + public BaseDAO dao; + + public BaseDAO getDao() { + if (dao == null) { + dao = new BaseDAO(); + } + return dao; + } + + /** + * @Description: 销售订单新增保存 + * @date: 2019-11-1 上午10:03:21 + * @version NCC1909 + */ + @SuppressWarnings("unchecked") + @POST + @Path("save") + @Consumes("application/json") + @Produces("application/json") + public JSONString save(List> paramList) { + InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677"); + try { + for (Map map : paramList) { + if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil + .buildHeadBodyResult()); + } + // 设置集团 + Map headdata = (Map) map.get(HEADTABLE); + headdata.put("pk_org", headdata.get("pk_org_v")); + headdata.put("cdeptid", headdata.get("cdeptvid")); + headdata.put("fstatusflag", 1); + headdata.put("dmakedate", headdata.get("dbilldate")); + headdata.put("dmakedate", headdata.get("dbilldate")); + headdata.put("cinvoicecustid", headdata.get("ccustomerid")); + + String pk_group = AppContext.getInstance().getPkGroup(); + headdata.put("pk_group", pk_group); + List bodyArr = (List) map.get(BODYTABLE); + for (Object body : bodyArr) { + Map bodydata = (Map) body; + bodydata.put("pk_group", pk_group); + bodydata.put("cprojectid", headdata.get("vdef6")); + bodydata.put("ctrafficorgvid", headdata.get("pk_org_v")); + bodydata.put("csendstockorgvid", headdata.get("pk_org_v")); + bodydata.put("csendstordocid", headdata.get("pk_org_v")); + bodydata.put("csendstockorgid", headdata.get("pk_org_v")); + bodydata.put("carorgid", headdata.get("pk_org_v")); + bodydata.put("carorgvid", headdata.get("pk_org_v")); + bodydata.put("csettleorgid", headdata.get("pk_org_v")); + bodydata.put("csettleorgvid", headdata.get("pk_org_v")); + +// bodydata.put("nqtunitnum", bodydata.get("nnum")); + + bodydata.put("ctaxcountryid", "CN"); + bodydata.put("crececountryid", "CN"); + bodydata.put("csendcountryid", "CN"); + + bodydata.put("fbuysellflag", 1); + +// bodydata.put("blargessflag", "N"); + + + // 根据物料编码查询物料信息 + setMaterl(bodydata); + } + } + // 新增自定义档案 + SaleOrderVO[] salevos = OpenAPIParaUtil.changeVO(paramList, HEADTABLE, BODYTABLE); + + genDef(salevos); + + for (Map map : paramList) { + BaseDAO baseDAO = new BaseDAO(); + Map headdata = (Map) map.get(HEADTABLE); + List bodyArr = (List) map.get(BODYTABLE); + for (Object body : bodyArr) { + Map bodydata = (Map) body; + String sql = " select pk_project from bd_project where project_code='" + headdata.get("vdef6") + "' and nvl(dr,0)=0 "; + String o_pk_project = (String) baseDAO.executeQuery(sql, new ColumnProcessor()); + bodydata.put("cprojectid", o_pk_project); + } + } +// BillFieldsCodeToPkUtil.doTranslateVOFields(salevos); + + // 参数形式转换为vo并翻译 + List vosList = + TransferMapToVOTool.transferMapToAggVO(paramList, SaleOrderVO.class, + true); + SaleOrderVO[] vos = vosList.toArray(new SaleOrderVO[vosList.size()]); + // 调用接口保存 + IAPISaleOrderMaitain service = + NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class); + SaleOrderVO[] results = service.save(vos); + // 包装返回信息 + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult( + results, "销售订单保存成功")); + } catch (Exception e) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildFailResult( + null, "销售单保存异常:" + e.getMessage())); + } + } + + private void setMaterl(Map bodydata) throws BusinessException { + String sql = " select a.pk_material,a.pk_source, a.pk_measdoc cunitid,nvl(b.pk_measdoc,a.pk_measdoc) castunitid,nvl(b.measrate,'1/1') measrate from bd_material a left join bd_materialconvert b on a.pk_material=b.pk_material where a.code='" + bodydata.get("cmaterialvid") + "' "; + Map map = (Map) getDao().executeQuery(sql, new MapProcessor()); + if (map == null) { + throw new BusinessException(bodydata.get("cmaterialvid") + "物料未查到"); + } + bodydata.put("castunitid", map.get("castunitid")); + bodydata.put("vchangerate", map.get("measrate")); + // 重新计算金额 + bodydata.put("cqtunitid", map.get("castunitid")); + bodydata.put("cunitid", map.get("cunitid")); + + bodydata.put("cmaterialid", map.get("pk_material")); + bodydata.put("cmaterialvid", map.get("pk_source")); + + bodydata.put("nqtunitnum", BFPubTools.getUFDouble_NullAsZero(bodydata.get("nnum")).div(BFPubTools.getUFDouble_NullAsZero(map.get("measrate").toString().split("/")[0]))); + + sql = "select sl.pk_taxcode from bd_taxrate sl inner join bd_taxcode sm on sl.pk_taxcode=sm.pk_taxcode where sl.taxrate=" + bodydata.get("ntaxrate") + " and sm.pk_group<>'~' " + + ""; + + String o_pk_project = (String) getDao().executeQuery(sql, new ColumnProcessor()); + bodydata.put("ctaxcodeid", o_pk_project); + + + } + + + private void genDef(SaleOrderVO[] salevos) throws BusinessException { + BaseDAO baseDAO = new BaseDAO(); + ArrayList arrhth = new ArrayList(); + ArrayList arrxmh = new ArrayList(); + ArrayList arrxsddh = new ArrayList(); + String pk_org = salevos[0].getParentVO().getPk_org(); + + String sql = " select pk_org,pk_vid from org_orgs where org_orgs.code='" + salevos[0].getParentVO().getPk_org() + "' and nvl(dr,0)=0 and isbusinessunit='Y' "; + + Map map = (Map) baseDAO.executeQuery(sql, new MapProcessor()); + if (map == null) { + throw new BusinessException("采购组织档案未查到"); + } + String o = (String) map.get("pk_org"); + + + String cprocode = salevos[0].getChildrenVO()[0].getCprojectid(); +// String cprocode=salevos[0].getParentVO().getVdef6(); + String cproname = salevos[0].getChildrenVO()[0].getVbdef10(); + if (!BFPubTools.getString_TrimAsNull(cprocode).equals("")) { + sql = " select pk_project from bd_project where project_code='" + cprocode + "' and pk_duty_org='" + o + "' and nvl(dr,0)=0 "; + String o_pk_project = (String) baseDAO.executeQuery(sql, new ColumnProcessor()); + if (o_pk_project == null) { + // 新增项目档案 + createPro(cprocode, cproname, map); + } + } + + + for (int i = 0; i < salevos.length; i++) { + + String vdef6 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef6()); + if (vdef6 != "" && !arrhth.contains(vdef6)) { + + arrhth.add(vdef6); + } + +// if(!arrhth.contains(BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef6()))) { +// arrhth.add(salevos[i].getParentVO().getVdef6()); +// } + + String vdef2 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef2()); + if (vdef2 != "" && !arrxmh.contains(vdef2)) { + arrxmh.add(vdef2); + } +// if(!arrxmh.contains(BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef2()))) { +// arrxmh.add(salevos[i].getParentVO().getVdef2()); +// } + + String vdef13 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef13()); + if (vdef13 != "" && !arrxsddh.contains(vdef13)) { + arrxsddh.add(vdef13); + } + +// if(!arrxsddh.contains(BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef13()))) { +// arrxsddh.add(salevos[i].getParentVO().getVdef13()); +// } + + } +// List newhth=new ArrayList(); + if (arrhth.size() > 0) { + sql = " select code from bd_defdoc where pk_defdoclist in(select pk_defdoclist from bd_defdoclist where code='zdy-001') and pk_org='" + o + "' and "; + sql += BFPubTools.getInSqlWithOutAnd("code", arrhth, 0, arrhth.size()); + ArrayList obj_arrhth = (ArrayList) baseDAO.executeQuery(sql, new ColumnListProcessor()); + if (obj_arrhth != null && obj_arrhth.size() > 0) { + arrhth.removeAll(obj_arrhth); + } + } + + // 组装销售订单数据 + if (arrhth.size() > 0) { + NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrhth, "zdy-001", o.toString())); + } + + +// List newxmh=new ArrayList(); + if (arrxmh.size() > 0) { + sql = " select code from bd_defdoc where pk_defdoclist in(select pk_defdoclist from bd_defdoclist where code='BQxmh') and pk_org='" + o + "' and "; + sql += BFPubTools.getInSqlWithOutAnd("code", arrxmh, 0, arrxmh.size()); + ArrayList obj_arrhth = (ArrayList) baseDAO.executeQuery(sql, new ColumnListProcessor()); + + if (obj_arrhth != null && obj_arrhth.size() > 0) { + + arrxmh.removeAll(obj_arrhth); + } + + } + if (arrxmh.size() > 0) { +// newarrvo.addAll(createDefVO(newxmh,"BQxmh",o.toString())); + NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrxmh, "BQxmh", o.toString())); + } + +// List newxsddh=new ArrayList(); + if (arrxsddh.size() > 0) { + sql = " select code from bd_defdoc where pk_defdoclist in( select pk_defdoclist from bd_defdoclist where code='BIP-ddh') and pk_org='" + o + "' and "; + sql += BFPubTools.getInSqlWithOutAnd("code", arrxsddh, 0, arrxsddh.size()); + ArrayList obj_arrhth = (ArrayList) baseDAO.executeQuery(sql, new ColumnListProcessor()); + if (obj_arrhth != null && obj_arrhth.size() > 0) { + arrxsddh.removeAll(obj_arrhth); + } + } + if (arrxsddh.size() > 0) { +// newarrvo.addAll(createDefVO(newxsddh,"BIP-ddh",o.toString())); + NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrxsddh, "BIP-ddh", o.toString())); + } + // 生成自定义档案 +// if(newarrvo.size()>0) { +// NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o.toString(), newarrvo.toArray(new DefdocVO[newarrvo.size()])); +// } + + } + + private void createPro(String cprocode, String cproname, Map map) throws BusinessException { + String pk_org = (String) map.get("pk_org"); + String pk_org_v = (String) map.get("pk_vid"); + + ProjectHeadVO hvo = new ProjectHeadVO(); + hvo.setProject_code(cprocode); + hvo.setProject_name(cproname); + hvo.setPk_org(pk_org); + hvo.setPk_org_v(pk_org_v); + + hvo.setBill_type("4D10"); + hvo.setCreationtime(new UFDateTime()); + hvo.setCreator(InvocationInfoProxy.getInstance().getUserId()); + hvo.setPk_group(InvocationInfoProxy.getInstance().getGroupId()); + hvo.setDr(0); + hvo.setPk_duty_org(pk_org); + hvo.setTransi_type("4D10-01"); + hvo.setPk_eps("1001A110000000004K64"); + hvo.setPk_duty_dept_v(pk_org_v); + hvo.setEnablestate(2); + NCLocator.getInstance().lookup(IProject.class).insertProject(hvo); + } + + private DefdocVO[] createDefVO(List newhth, String defdoclistcode, String pk_org) throws BusinessException { + String sql = " select pk_defdoclist from bd_defdoclist where code='" + defdoclistcode + "' "; + String o = (String) getDao().executeQuery(sql, new ColumnProcessor()); + + ArrayList arrvo = new ArrayList(); + for (int i = 0; i < newhth.size(); i++) { + DefdocVO vo = new DefdocVO(); + vo.setEnablestate(2); + vo.setPk_defdoclist(o); + vo.setPk_org(pk_org); + vo.setCode(newhth.get(i)); + vo.setName(newhth.get(i)); + vo.setDataoriginflag(0); + vo.setDr(0); + vo.setPk_group(InvocationInfoProxy.getInstance().getGroupId()); + vo.setCreator(InvocationInfoProxy.getInstance().getUserId()); + vo.setCreationtime(new UFDateTime()); + + + arrvo.add(vo); + } + + return arrvo.toArray(new DefdocVO[arrvo.size()]); + + } + + /** + * @Description: 销售订单修改保存 + * @date: 2019-11-1 上午10:03:49 + * @version NCC1909 + */ + @POST + @Path("update") + @Consumes("application/json") + @Produces("application/json") + public JSONString update(Map paramMap) { + InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677"); + try { + if (paramMap == null || !paramMap.containsKey(HEADTABLE) + || !paramMap.containsKey(BODYTABLE)) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil + .buildHeadBodyResult()); + } + List> paramList = + new ArrayList>(); + paramList.add(paramMap); + // 参数形式转换为vo并翻译 + List vosList = + TransferMapToVOTool.transferMapToAggVO(paramList, SaleOrderVO.class, + true); + SaleOrderVO[] vos = vosList.toArray(new SaleOrderVO[vosList.size()]); + List> addMapList = new ArrayList>(); + for (Map objectMap : paramList) { + Map headdata = (Map) objectMap.get(HEADTABLE); + List bodyArr = (List) objectMap.get(BODYTABLE); + for (Object body : bodyArr) { + Map bodydata = (Map) body; + if (!(bodydata.getOrDefault("vbdef11", "") + "").isEmpty()) { + String vbdef11 = bodydata.get("vbdef11") + ""; + String csaleorderid = bodydata.get("csaleorderid") + ""; + String countSql = "SELECT count(1) FROM so_saleorder_b" + + " WHERE nvl(dr,0) = 0 and csaleorderid = '[csaleorderid]' and vbdef11 = '[vbdef11]' "; + countSql = countSql.replace("[csaleorderid]", csaleorderid); + countSql = countSql.replace("[vbdef11]", vbdef11); + Integer num = (Integer) new BaseDAO().executeQuery(countSql, new ColumnProcessor()); + if (num <= 0) { + bodydata.put("status", "add"); + Map map = new HashMap(); + map.put(headdata.get("csaleorderid"), objectMap); + addMapList.add(map); + } + + } + } + } + // 调用接口保存 + IAPISaleOrderMaitain service = + NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class); + SaleOrderVO[] results = service.update(vos, addMapList); + // 包装返回信息 + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult( + results, "销售订单修改成功")); + } catch (Exception e) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildFailResult( + null, "销售订单修改异常:" + e.getMessage())); + } + } + + /** + * @Description: 根据查询方案查询销售订单 + * @date: 2019-11-1 上午10:04:20 + * @version NCC1909 + */ + @POST + @Path("querybyscheme") + @Consumes("application/json") + @Produces("application/json") + public JSONString queryByScheme(Map paramMap) { + SaleOrderVO[] results = null; + try { + // 翻译 + Map fields = + BillFieldsCodeToPkUtil.doTranslateFields(new SaleOrderFieldMapping(), + paramMap); + + // 创建查询方案 + QuerySchemeUtils schemeUtil = + new QuerySchemeUtils(SaleOrderVO.class, fields); + IQueryScheme queryScheme = schemeUtil.creatQueryScheme(); + + // 调用查询接口 + results = + NCLocator.getInstance().lookup(IAPISaleOrderQuery.class) + .queryByScheme(queryScheme); + // 包装返回信息 + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult( + results, "查询销售订单成功")); + } catch (Exception e) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildFailResult( + results, "查询销售订单失败:" + e.getMessage())); + } + } + + + @SuppressWarnings("unchecked") + @POST + @Path("/saleOrderReviseSaveCommit") + @Consumes("application/json") + @Produces("application/json") + public JSONString saleorderRevise(List> paramList) throws Exception { + InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677"); + SaleOrderVO[] results = null; + try { + String id = ""; + + for (Map map : paramList) { + if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil + .buildHeadBodyResult()); + } + // 设置集团 + Map headdata = (Map) map.get(HEADTABLE); + headdata.put("pk_org", headdata.get("pk_org_v")); + + id = BFPubTools.getString_TrimAsNull(headdata.get("csaleorderid")); + if (id.equals("")) { + throw new Exception("csaleorderid" + "主键为空"); + } + String pk_group = AppContext.getInstance().getPkGroup(); + headdata.put("pk_group", pk_group); + List bodyArr = (List) map.get(BODYTABLE); + for (Object body : bodyArr) { + Map bodydata = (Map) body; + bodydata.put("pk_group", pk_group); + bodydata.put("ctaxcountryid", "CN"); + bodydata.put("fbuysellflag", 1); + bodydata.put("blargessflag", "N"); + setMaterl(bodydata); + } + } +// SaleOrderVO[] salevos=OpenAPIParaUtil.changeVO(paramList, HEADTABLE,BODYTABLE); + // 把最新数据传递至历史数据 + // 查询销售订单不存在 + String sql = " select csaleorderid from so_saleorder where csaleorderid='" + id + "' and nvl(dr,0)=0 "; + + String o = (String) getDao().executeQuery(sql, new ColumnProcessor()); + if (o == null) { + throw new Exception("csaleorderid" + "主键为空"); + } + + List vosList = + TransferMapToVOTool.transferMapToAggVO(paramList, SaleOrderVO.class, + true); + SaleOrderVO[] salevos = vosList.toArray(new SaleOrderVO[vosList.size()]); + + ISaleOrderReviseMaintainApp reviseService = (ISaleOrderReviseMaintainApp) NCLocator.getInstance().lookup(ISaleOrderReviseMaintainApp.class); + SaleOrderHistoryVO VOS = reviseService.queryM30ReviseApp(new String[]{id})[0]; + + ArrayList arrbvos = new ArrayList(); + + if (VOS != null) { + SaleOrderBVO[] newbvos = salevos[0].getChildrenVO(); + SaleOrderHistoryBVO[] oldbvos = VOS.getChildrenVO(); + for (int i = 0; i < newbvos.length; i++) { + SaleOrderBVO bvo = newbvos[i]; + // 新增数据 + if (bvo.getPrimaryKey() == null) { + SaleOrderHistoryBVO newvo = (SaleOrderHistoryBVO) oldbvos[0].clone(); + newvo.setCsaleorderbid(""); + newvo.setCrowno(bvo.getCrowno()); + newvo.setStatus(VOStatus.NEW); + // 重新设置数据 + createNewBVo(newvo, bvo); + arrbvos.add(newvo); + continue; + } + for (int j = 0; j < oldbvos.length; j++) { + if (bvo.getCsaleorderbid().equals(oldbvos[j].getCsaleorderbid())) { + // 交换变更数据 + oldbvos[j].setStatus(VOStatus.UPDATED); + createNewBVo(oldbvos[j], bvo); + arrbvos.add(oldbvos[j]); + break; + } + } + } + } + SaleOrderHistoryHVO headvo = VOS.getParentVO(); + headvo.setStatus(1); + headvo.setApprover(null); + headvo.setTaudittime(null); + headvo.setAttributeValue("pseudocolumn", 0); + check30And30RTS(VOS); + + VOS.setChildrenVO((SaleOrderHistoryBVO[]) CollectionUtils.listToArray(arrbvos)); + SaleOrderHistoryVO[] vodis = {VOS}; + VOEntityUtil.clearVOsValue(VOEntityUtil.getBodyVOs(vodis), new String[]{"corderhistorybid"}); + + IAPISaleOrderMaitain service = + NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class); + results = service.modify(vodis); + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult( + results, "销售订单保存成功")); + } catch (Exception e) { + return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildFailResult( + results, "销售订单修订失败:" + e.getMessage())); + } + + } + + private void createNewBVo(SaleOrderHistoryBVO newvo, SaleOrderBVO bvo) throws Exception { + // 重置物料信息 + newvo.setCmaterialid(bvo.getCmaterialid()); + newvo.setCmaterialvid(newvo.getCmaterialvid()); + newvo.setCunitid(bvo.getCunitid()); + newvo.setCastunitid(bvo.getCastunitid()); + newvo.setCqtunitid(bvo.getCqtunitid()); +// newvo.setStatus(VOStatus.NEW); + newvo.setNnum(bvo.getNnum()); + newvo.setNqtunitnum(bvo.getNqtunitnum()); + newvo.setNastnum(bvo.getNqtunitnum()); + newvo.setVchangerate(bvo.getVchangerate()); + newvo.setNtaxrate(bvo.getNtaxrate()); + newvo.setCrowno(bvo.getCrowno()); + newvo.setNqtorigtaxprice(bvo.getNqtorigtaxprice()); + newvo.setCtaxcodeid(bvo.getCtaxcodeid()); + + } + + private void cheageHVo(SaleOrderHistoryVO billvo, SaleOrderVO saleOrderVO) { + SaleOrderHistoryHVO hvo = billvo.getParentVO(); + SaleOrderHVO oldvo = saleOrderVO.getParentVO(); + hvo.setCinvoicecustid(oldvo.getCinvoicecustid()); + hvo.setCemployeeid(oldvo.getCemployeeid()); + } + + private void check30And30RTS(SaleOrderHistoryVO vo) { + /* 109 */ + ISaleOrderReviseMaintainApp service = (ISaleOrderReviseMaintainApp) NCLocator.getInstance().lookup(ISaleOrderReviseMaintainApp.class); + /* */ + try { + /* 111 */ + SaleOrderHistoryVO[] vos = service.queryM30ReviseApp(new String[]{vo.getPrimaryKey()}); + /* 112 */ + Map billMap = new HashMap(); + /* 113 */ + for (SaleOrderHistoryBVO bvo : vos[0].getChildrenVO()) { + /* 114 */ + billMap.put(bvo.getCsaleorderbid(), bvo.getTs()); + /* */ + } + /* 116 */ + for (SaleOrderHistoryBVO bvo : vo.getChildrenVO()) { + /* 117 */ + if (bvo.getStatus() != 2 && bvo.getStatus() != 0) { + /* 118 */ + UFDateTime ts = (UFDateTime) billMap.get(bvo.getCsaleorderbid()); + /* 119 */ + if (!ts.equals(bvo.getTs())) { + /* 120 */ + ExceptionUtils.wrapBusinessException(NCLangRes4VoTransl.getNCLangRes() + /* 121 */.getStrByID("4006013_0", "04006013-0006")); + /* */ + } + /* */ + } + /* */ + /* */ + } + /* 126 */ + } catch (BusinessException e) { + /* 127 */ + ExceptionUtils.wrapBusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006013_0", "04006013-0006")); + /* */ + } + /* */ + } + + +}