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..ded25e4 --- /dev/null +++ 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 new file mode 100644 index 0000000..2a0f902 --- /dev/null +++ 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) + "%' "); + } + + } +} 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..0fbe25c --- /dev/null +++ b/so/src/private/nccloud/api/impl/so/m30/APISaleOrderMaitainImpl.java @@ -0,0 +1,733 @@ +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; +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.jdbc.framework.processor.MapProcessor; +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.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; +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.SaleOrderNPriceMnyCal; +import nccloud.api.impl.so.m30.fill.SaleOrderSaveFillValue; +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.*; + +/** + * @Description: 销售订单维护实现类 + * @author: yanghff + * @date: 2019-10-23 下午4:57:49 + * @Copyright: + */ +public class APISaleOrderMaitainImpl 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, 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 + || 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); + // 有值不覆盖 + // 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) { + 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; + } + + /** + * @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 + 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_vid,pk_dept from org_dept_v where code = '[code]' "; + sql = sql.replace("[code]", cdeptvid); + 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", "") + ""); + } + } + } + // 业务员 + 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("pk_psndoc")); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-staffObj:" + staffObj); + if (staffObj != null) { + String id = BFPubTools.getString_TrimAsNull(staffObj); + if (!id.isEmpty()) { + orderHVO.setCemployeeid(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("pk_customer")); + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-invCustObj:" + invCustObj); + if (invCustObj != null) { + String id = BFPubTools.getString_TrimAsNull(invCustObj); + if (!id.isEmpty()) { + orderHVO.setCinvoicecustid(id); + } + } + } + } catch (Exception e) { + NCCForUAPLogger.debug("APISaleOrderMaitainImpl-setOtherId-exp:" + e.getMessage()); + throw new RuntimeException(e); + } + } + } + + 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 { + 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()); + } + + 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 new file mode 100644 index 0000000..9aacd84 --- /dev/null +++ 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/api/so/saleinvoice/operator/saveCommitAction.java b/so/src/public/nccloud/api/so/saleinvoice/operator/saveCommitAction.java new file mode 100644 index 0000000..22687b0 --- /dev/null +++ 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 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..d1adc92 --- /dev/null +++ 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")); + /* */ + } + /* */ + } + + +}