package com.malk.fenggefushi.service.Impl; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.malk.fenggefushi.entity.Order; import com.malk.fenggefushi.service.HeiHuOrderService; import com.malk.fenggefushi.test.test; import com.malk.server.aliwork.YDConf; import com.malk.server.aliwork.YDParam; import com.malk.server.aliwork.YDSearch; import com.malk.server.common.McR; import com.malk.server.dingtalk.DDConf; import com.malk.service.aliwork.YDClient; import com.malk.service.aliwork.YDService; import com.malk.utils.UtilHttp; import com.malk.utils.UtilMap; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.checkerframework.checker.fenum.qual.SwingBoxOrientation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; @Slf4j @Service public class HeiHuOrderServiceImpl implements HeiHuOrderService { @Autowired private YDClient ydClient; @Autowired private YDConf ydConf; @Autowired private YDService ydService; @Autowired private DDConf ddConf; /*登录获取黑湖登录token*/ @Override public McR HeiHuAccessToken() throws JacksonException { HashMap body = new HashMap(); body.put("type",1);//type=1,登录方式为工厂代号+账号+密码 body.put("code","648910");//工厂代号 body.put("username","FGJK");//账号 body.put("password","b715db070346a8a59e0eba5da27f8e4938536bb7867e09592326fde2");//密码加密 HashMap header = new HashMap(); header.put("X-CLIENT","lite-web");//固定 header.put("Content-Type","application/json"); String s = UtilHttp.doPost("https://liteweb.blacklake.cn/api/user/v1/users/_login", header, null, body); String data = new ObjectMapper().readTree(s).get("data").asText(); return McR.success(data); } /*抓取黑湖工单发起宜搭审批流程*/ @Override public McR StartYidaAproval(String OrderNo,String fromUuid) throws JacksonException { HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); HashMap body = new HashMap(); body.put("orderNo",OrderNo);//订单编码 /*TODO:对json进行处理*/ String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body); JSONObject jsonObject = JSONObject.parseObject(jsonString); JSONArray dataArray = jsonObject.getJSONArray("data"); //基础信息字段 String orderNo = ""; String customerName = "";Long orderTime = null;Long arrivalPlanTime = null;String contractNo = ""; String operatorName = "";double orderDiscount = 0;String customerCode = ""; // 提取自定义字段 String productPhoto = "";//产品照片:182852 String sampleType = "";//样品类型:69230 String processType = "";//工艺类型:47768 String productType = "";//产品类型:47770 String orderType = "";//订单类型:47771 String department = "";//部门:47777 String season = "";//季节:47778 String expectedOrderQty = "";//预计下单量:59314 double estimatedUnitPrice = 0;//辅料预估单价:161769 String purchaseOrderNumber = "";//对应预采购单号:113495 String qualityConfirmation = "";//品质确认:113119 String materialCycle = "";//物料周期:113086 //产品详情字段 String productCode = "";String productName = "";String productSpec = "";int productStockQty;int qty; String productUnitName = "";double unitPrice;double amount;double discount;double taxInclusiveAmount; double taxRate;String productArrivalPlanTime = "";String productOriginType = ""; //其他信息 String contactName = "";String contactNumbers = "";String contactAddress = ""; for (int i = 0; i < dataArray.size(); i++) { JSONObject data = dataArray.getJSONObject(i); // 提取订单基本信息 orderNo = data.getString("orderNo");//订单编号:orderNo customerName = data.getString("customerName");//客户:customerName orderTime = data.getLong("orderTime");//下单日期:orderTime arrivalPlanTime = data.getLong("arrivalPlanTime");//计划交货日期:arrivalPlanTime contractNo = data.getString("contractNo");//合同号:contractNo operatorName = data.getString("operatorName");//业务员:operatorName orderDiscount = data.getDoubleValue("orderDiscount")*100;//整单折扣:orderDiscount customerCode = data.getString("customerCode");//客户名称:customerCode //提取其他信息 contactName = data.getString("contactName");//联系人 contactNumbers = data.getString("contactNumbers");//联系电话 contactAddress = data.getString("contactAddress");//联系地址 JSONArray customFields = data.getJSONArray("customFieldValues"); if (customFields != null) { for (int j = 0; j < customFields.size(); j++) { JSONObject field = customFields.getJSONObject(j); long fieldId = field.getLongValue("fieldId"); String value = field.getString("value"); switch ((int)fieldId) { case 70931: productPhoto = value; break; case 69230: sampleType = value; break; case 47768: processType = value; break; case 47770: productType = value; break; case 47771: orderType = value; break; case 47777: department = value; break; case 47778: season = value; break; case 59314: expectedOrderQty = value;break; case 161769: estimatedUnitPrice = Double.parseDouble(value);break; case 113495:purchaseOrderNumber = value;break; case 113119:qualityConfirmation = value;break; case 113086:materialCycle = value;break; } } } } /*判断订单类型来封装数据*/ HashMap formdata = new HashMap(); /*主表*/ formdata.put("textField_mfqgmwcw",orderNo); formdata.put("textField_mfqgmwcx",customerName); formdata.put("dateField_mfqgmwcy",orderTime); formdata.put("dateField_mfqgmwcz",arrivalPlanTime); formdata.put("textField_mfqgmwd5",contractNo); formdata.put("textField_mgc0kc5u",operatorName); formdata.put("numberField_mfqgmwd7",orderDiscount); formdata.put("selectField_mg5y3rcr",orderType); formdata.put("textField_mfqgmwdn",processType); formdata.put("textField_mfqgmwdo",productType); formdata.put("textField_mg5y3rda",department); formdata.put("textField_mfqgmwdx",season); formdata.put("textField_mfqi6ui8",contactName); formdata.put("textField_mfqi6ui9",contactNumbers); formdata.put("textField_mfqi6uia",contactAddress); List> imageAttachments = new ArrayList<>(); //处理多照片 if(productPhoto != null && productPhoto.contains(",")){ String[] photoUrls = productPhoto.split(","); for (String url : photoUrls){ String trimmedUrl = url.trim(); if(!trimmedUrl.isEmpty()){ Map imageInfo = new HashMap<>(); imageInfo.put("name",productType); imageInfo.put("downloadUrl",trimmedUrl); imageInfo.put("previewUrl",trimmedUrl); imageInfo.put("url",trimmedUrl); imageInfo.put("ext","png"); imageAttachments.add(imageInfo); } } }else { HashMap imageInfo = new HashMap(); imageInfo.put("name",productType); imageInfo.put("downloadUrl",productPhoto); imageInfo.put("previewUrl",productPhoto); imageInfo.put("url",productPhoto); imageInfo.put("ext","png"); imageAttachments.add(imageInfo); } formdata.put("imageField_mfqgmwde",imageAttachments); if(orderType.equals("样品订单")){ formdata.put("textField_mfqgmwdh",customerCode); formdata.put("textField_mg5y3rdd",sampleType); formdata.put("textField_mgc1xl62",expectedOrderQty); }else if(orderType.equals("贸易公司订单")){ formdata.put("numberField_mg5y3rcx",estimatedUnitPrice); formdata.put("textField_mg5y3rcy",purchaseOrderNumber); formdata.put("textField_mg5y3rcz",qualityConfirmation); formdata.put("textField_mg5y3rd0",materialCycle); formdata.put("textField_mfqgmwdh",customerCode); }else{ formdata.put("textField_mfqgmwdh",customerCode); } /*子表*/ JSONArray products = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList"); List> tableData = new ArrayList(); if (products != null) { for (int i = 0; i < products.size(); i++) { JSONObject detail = products.getJSONObject(i); HashMap row = new HashMap(); // String color = ""; JSONArray array1 = detail.getJSONArray("customFieldValues"); color = array1.stream() .map(obj -> (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 82259) .map(item -> item.getString("value")) .findFirst() .orElse(null); ArrayList colorList = new ArrayList(); colorList.add(color); String color_AAA = getProductColor(colorList); row.put("textField_mk0jz9i1",color_AAA);//中文颜色 row.put("textField_mfqgmwe1",detail.getString("productCode"));//产品编号 row.put("textField_mfqgmwe2",detail.getString("productName"));//产品名称 row.put("textField_mfqgmwe3",detail.getString("productSpec"));//产品规格 row.put("textField_mfqgmwe4","0".equals(detail.getString("productOriginType")) ? "自制" : "其它");//产品属性 row.put("numberField_mfqgmwe5",detail.getIntValue("productStockQty"));//库存数量 row.put("numberField_mfqgmwe6",detail.getIntValue("qty"));//数量 row.put("textField_mfqgmwe7",detail.getString("productUnitName"));//单位 row.put("numberField_mfqgmwe8",detail.getDoubleValue("unitPrice"));//单价 row.put("numberField_mfqgmwe9",detail.getDoubleValue("amount"));//报价金额 row.put("numberField_mfqgmwea",detail.getDoubleValue("discount")*100);//折扣 row.put("numberField_mfqgmweb",detail.getDoubleValue("taxInclusiveAmount"));//折扣 row.put("numberField_mfqgmwec",detail.getDoubleValue("taxRate"));//税率 row.put("dateField_mfqgmwed",detail.getLong("arrivalPlanTime"));//产品交货日期 tableData.add(row); } } formdata.put("tableField_mfqgmwe0",tableData); System.out.println(formdata); /*发起流程*/ String userid = getDDToken(operatorName); String dd = ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid(fromUuid) .userId(userid) .formDataJson(JSON.toJSONString(formdata)) .build(), YDConf.FORM_OPERATION.start).toString(); log.info("----------【销售订单】已发起----------"); return McR.success(dd); } @Override public String getDDToken(String Name) { HashMap body = new HashMap(); body.put("appKey","dingie28nalt6tcnzizl"); body.put("appSecret","Ss7na86M_BWPEXhKffiQDA-8jXvuBhBklfD8C-ot7xGwiDKfFMIf9y00mXYutfCB"); String s = UtilHttp.doPost("https://api.dingtalk.com/v1.0/oauth2/accessToken", null, null, body); String accessToken = JSONObject.parseObject(s).getString("accessToken"); HashMap header = new HashMap(); header.put("x-acs-dingtalk-access-token",accessToken); HashMap bodyy = new HashMap(); bodyy.put("queryWord", Name); bodyy.put("offset",0); bodyy.put("size",10); String s1 = UtilHttp.doPost("https://api.dingtalk.com/v1.0/contact/users/search", header, null, bodyy); List list = JSONObject.parseObject(s1).getJSONArray("list").toJavaList(String.class); String userId = ""; if(list!= null && !list.isEmpty()){ userId = list.get(0); } return userId; } @SneakyThrows @Override public McR startYidaProcurementAproval(String OrderNo,String FormUuType) throws JsonProcessingException { HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); HashMap body = new HashMap(); body.put("orderCode",OrderNo);//订单编号 String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单 JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data"); //基础信息字段 String orderCode = "";String shortName = "";Long purchaseTime = null;Long planArrivalTime = null;String purchaserName = ""; String gysnumber = ""; double orderDiscount = 0; //自定义信息 String department = "";//部门:186341 String add = "";//地址:32869 String SalesOrderNumber = "";//销售订单号:59332 String PaymentStatus = "";//付款情况:55674 String PortOfShipment = "";//出运地:42003 String ShippingStatus = "";//出运状态:42002 //产品详情字段 String productCode = "";String productName = "";String productSpec = "";int purchaseNum; String unitName = "";double purchasePrice;double purchaseAmount;double discount;double taxInclusiveAmount; double taxRate;Long productArrivalPlanTime = null; //其他信息 String contactName = "";String contactNumber = "";String contactAddress = ""; for (int i=0;i> tableData = new ArrayList(); if(products != null){ for (int i = 0; i < products.size(); i++) { JSONObject detail = products.getJSONObject(i); HashMap row = new HashMap(); row.put("textField_mfqia332",detail.getString("productCode"));//产品编码 row.put("textField_mfqia333",detail.getString("productName"));//产品名称 row.put("textField_mfqia334",detail.getString("productSpec"));//产品规格 row.put("numberField_mfqia335",detail.getInteger("purchaseNum"));//采购数量 row.put("textField_mfqia336",detail.getString("unitName"));//单位 row.put("numberField_mfqia337",detail.getDouble("purchasePrice"));//单价 row.put("numberField_mg4gqvdm",detail.getDouble("purchaseAmount"));//报价金额 row.put("numberField_mg4gqvdn",detail.getDouble("discount"));//折扣 row.put("numberField_mg4gqvdo",detail.getDouble("taxInclusiveAmount"));//含税金额 row.put("numberField_mg4gqvdp",detail.getDouble("taxRate"));//税率 row.put("dateField_mg4gqvdq",detail.getLong("productArrivalTime"));//产品到货日期 tableData.add(row); } } /*todo:新版栏目:客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别、生产工厂、采购单价、采购金额、利润率、美金汇率、辅料预估成本*/ String customerName = "",styleNumber = "",productDescription = "",color = "",currency = ""; Double number,unitPrice,salesAmount; Double rate = 1.00;Double saletotalAmount = 0.00;Double procuretotalAmount = 0.00;Double saletotalnum =0.00; Double estimatedtotalAmount = 0.00;Double estimatedPrice = 0.00; Double USDrate = 0.00;Double flygcb = 0.00; ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(jsonString); JsonNode dataNode = rootNode.get("data"); String orderNumber = "";//销售订单编号 if(dataNode != null && dataNode.isArray()){ for(JsonNode item : dataNode){ JsonNode orderNoNode = item.get("orderCode"); JsonNode saleOrders = item.get("relationSaleOrders"); if(saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0){ orderNumber = saleOrders.get(0).asText(); } } } HashMap body_A = new HashMap(); body_A.put("orderNo",orderNumber); String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo:查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别 JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据 for(int i=0;i> tabledata = new ArrayList(); if(products_A != null){ for (int i=0;i (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 82259) .map(item -> item.getString("value")) .findFirst() .orElse(null); ArrayList colorList = new ArrayList(); colorList.add(color); String color_AAA = getProductColor(colorList); row.put("textField_mhsj6gtr",color_AAA);//todo:颜色 number = detail.getDoubleValue("qty");//数量 row.put("numberField_mhsj6gts",number);//todo:数量 saletotalnum = saletotalnum + number; unitPrice = detail.getDoubleValue("unitPrice");//销售单价 row.put("numberField_mhsj6gtt",unitPrice);//todo:销售单价 salesAmount = number * unitPrice;//销售金额 row.put("numberField_mhsj6gtu",salesAmount);//todo:销售金额 String customFieldValues = detail.getString("customFieldValues"); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonarray = mapper.readTree(customFieldValues); for (JsonNode node : jsonarray){ if(node.get("fieldId").asInt() == 47919){ currency = node.get("value").asText(); }else if (node.get("fieldId").asInt() == 165251){ rate = node.get("value").asDouble(); USDrate = rate; }else if (node.get("fieldId").asInt() == 161783) { flygcb = node.get("value").asDouble(); } } row.put("textField_mhtxft3p",currency);//todo:币别 row.put("numberField_ml85btkc",USDrate);//todo:美金汇率 row.put("numberField_ml85btkd",flygcb);//todo:辅料预估成本 //下面是采购订单的明细数据 row.put("textField_mhsj6gtv",shortName);//todo:生产工厂 for(int j=0;j> customFiled = new ArrayList(); HashMap field = new HashMap(); field.put("name","销售订单钉钉审批状态"); field.put("value",Approvalresult);//审批状态 customFiled.add(field); body.put("saleOrderCustomFieldsValue",customFiled);//订单状态明细 String dd = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/update", header, null, body); log.info("---------【回传销售订单状态完成】----------"); return McR.success(dd); } @SneakyThrows @Override public McR SyncPurchaseOrderStatus(String formInstanceId,String Approvalresult) throws JsonProcessingException { HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); Map formdata = ydClient.queryData(YDParam.builder().formInstId(formInstanceId) .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData(); String jsonString = formdata.get("tableField_ml7ch2pj").toString(); JSONArray tableField_ml7ch2pj = JSON.parseArray(jsonString); for (int i=0;i> customFiled = new ArrayList(); HashMap field = new HashMap(); field.put("name","采购订单钉钉审批状态"); field.put("value",Approvalresult);//审批状态 customFiled.add(field); body1.put("purchaseOrderCustomFieldsValue",customFiled); UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1); log.info("---------【回传,{},采购订单状态完成】-----------",data.getString("orderCode")); } } return McR.success(); } @Override @SneakyThrows public McR salesAproval(Map body) throws JacksonException { StartYidaAproval(body.get("order").toString(),"FORM-472F0C1BD8DF41FA965A0B4525779B67S421");//todo:发起销售订单流程档案 HashMap formdata = new HashMap(); formdata.put("textField_mgq90lwf",body.get("order").toString()); Instant now = Instant.now(); long timestampMillis = now.toEpochMilli(); formdata.put("dateField_mgq90lwg",timestampMillis); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-1693380A673E498C827CD0A4C2D8214CIK90") .userId("3320511511-1158713155") .formDataJson(JSON.toJSONString(formdata)) .build(), YDConf.FORM_OPERATION.create).toString();//todo:销售合同档案 log.info("[销售订单流程发起,销售汇总表已同步]"); return McR.success(); } @Override @SneakyThrows public McR Procurement(Map body_new) throws JacksonException { //1、每次创建的时候才去查询宜搭采购订单底表 log.info("【开始查询宜搭采购订单汇总】"); String formUuid = "FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91"; YDParam ydParam = YDParam.builder().formUuid(formUuid).build(); ydParam.setPageSize(1); long totalCount = ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getTotalCount(); List dataList = new ArrayList<>(); ydParam.setCurrentPage(1); ydParam.setPageSize(100); int totalPages = (int) Math.ceil((double) totalCount / ydParam.getPageSize()); for (int page = 1; page <= totalPages; page++) { ydParam.setCurrentPage(page); dataList.addAll((List) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData()); } int i =0; String jsonStr = ""; ArrayList procureList = new ArrayList();//采购订单汇总-订单号 for (Map li : dataList) { i++; jsonStr = li.get("formData").toString(); String orderNumber = new ObjectMapper().readTree(jsonStr).get("textField_mgq932hi").asText(); procureList.add(orderNumber); } //2、其次就是在查询下黑湖工单,时间为当前时间 HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); HashMap body = new HashMap(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime todayMidnight = LocalDate.now().atStartOfDay(); String formattedToday = todayMidnight.format(formatter); body.put("createdAtGte",formattedToday);//创建时间大于等于 /*TODO:对json进行处理*/ String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//TODO:查询采购订单 List orderNoList = new ArrayList<>();//存在这个orderList里面 ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(jsonString); JsonNode dataNode = rootNode.get("data"); String orderNumber = "";//销售订单编号 List orderNumberList = new ArrayList<>();//todo:存在关联多个销售订单 String purchaseOrderNo = "";//采购订单编号 String orderType = "";//销售订单类型 if (dataNode != null && dataNode.isArray()) { for (JsonNode item : dataNode) { JsonNode orderNoNode = item.get("orderCode"); if (orderNoNode != null) { purchaseOrderNo = orderNoNode.asText(); } JsonNode saleOrders = item.get("relationSaleOrders"); if (saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0) { for (int j = 0; j < saleOrders.size(); j++) { orderNumberList.add(saleOrders.get(j).asText()); } orderNumber = saleOrders.get(0).asText(); } //每次查询下是否为“样品订单”推过来的采购订单 HashMap body2 = new HashMap(); body2.put("orderNo",orderNumber); String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body2);//TODO: 查询销售订单 ObjectMapper objectMapper2 = new ObjectMapper(); JsonNode dataNode2 = objectMapper2.readTree(jsonString2).get("data"); if(dataNode2 != null && dataNode2.isArray()){ for (JsonNode item2 : dataNode2){ JsonNode customFieldValues = item2.get("customFieldValues"); if (customFieldValues != null && customFieldValues.isArray()) { for (JsonNode field : customFieldValues) { JsonNode fieldIdNode = field.get("fieldId"); // 查找fieldId为47771的字段:订单类型 if (fieldIdNode != null && fieldIdNode.asInt() == 47771) { JsonNode valueNode = field.get("value"); if (valueNode != null) { orderType = valueNode.asText(); break; } } } } } } if (orderNoNode != null && !orderType.equals("样品订单") ) { orderNoList.add(orderNoNode.asText()); } } } //3、两者比较[procureList\orderList],差别的一个发起审批流程,排除订单类型为“样品订单”外 Set orderNoSet = new HashSet<>(orderNoList); Set procureSet = new HashSet<>(procureList); List onlyInSalesList = new ArrayList<>(); for (String item : procureList) { if (!orderNoSet.contains(item)) { onlyInSalesList.add(item); } } List onlyInOrderNoList = new ArrayList<>(); for (String item : orderNoList) { if (!procureSet.contains(item)) { onlyInOrderNoList.add(item); } } System.out.println("要发起的采购订单: " + onlyInOrderNoList);//这里的orderNoList中的元素可能为[],为空的话就不发起流程 //4、非样品订单发起宜搭审批流程 if(orderType.equals("样品订单")){ HashMap formdata2 = new HashMap(); formdata2.put("textField_mgq932hi",purchaseOrderNo); formdata2.put("textField_mhyh7ues",orderNumber); Instant now = Instant.now(); long timestampMillis = now.toEpochMilli(); formdata2.put("dateField_mgq932hj",timestampMillis); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91") .userId("3320511511-1158713155") .formDataJson(JSON.toJSONString(formdata2)) .build(),YDConf.FORM_OPERATION.create).toString(); log.info("[样品订单流程不发起,采购汇总表已同步]"); } for (int j=0;j< onlyInOrderNoList.size();j++){ String orderNo = onlyInOrderNoList.get(j); startYidaProcurementAproval(orderNo,"FORM-5BD5B7F6C8B249A5ADD6E1C82DEAA2C086FY"); //5、发起流程写入采购订单汇总表 HashMap formdata = new HashMap(); formdata.put("textField_mgq932hi",orderNo); formdata.put("textField_mhyh7ues",orderNumber); Instant now = Instant.now(); long timestampMillis = now.toEpochMilli(); formdata.put("dateField_mgq932hj",timestampMillis); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91") .userId("3320511511-1158713155") .formDataJson(JSON.toJSONString(formdata)) .build(), YDConf.FORM_OPERATION.create).toString(); log.info("[采购订单流程发起,采购汇总表已同步]"); } //6、样品订单也要写入采购订单汇总表内 if(orderType.equals("样品订单")){ HashMap formdata2 = new HashMap(); formdata2.put("textField_mgq932hi",purchaseOrderNo); formdata2.put("textField_mhyh7ues",orderNumber); Instant now = Instant.now(); long timestampMillis = now.toEpochMilli(); formdata2.put("dateField_mgq932hj",timestampMillis); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91") .userId("3320511511-1158713155") .formDataJson(JSON.toJSONString(formdata2)) .build(),YDConf.FORM_OPERATION.create).toString(); log.info("[样品订单流程不发起,采购汇总表已同步]"); } return McR.success(); } // 定义核心字段KEY数组 private static final List CORE_KEY_LIST=Arrays.asList("numberField_mfqgmwe6","numberField_mfqgmwe8","textField_mk0jz9i1");//数量 单价 中文颜色 private static final String MATCH_KEY = "textField_mhsj6gtp"; @Override public McR salesUpdate(Map body_new) throws JacksonException { /*todo:1、修改销售明细的颜色、数量、单价(已实现) 2、修改计划交货日期(进行中)*/ // 查询销售订单明细 HashMap head = new HashMap(); head.put("X-AUTH",HeiHuAccessToken().getData().toString()); head.put("Content-Type","application/json"); HashMap bodyy = new HashMap(); bodyy.put("orderNo",body_new.get("order").toString()); String saleDetails = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", head, null, bodyy); JSONArray datas = JSONObject.parseObject(saleDetails).getJSONArray("data"); JSONArray prods = JSONObject.parseObject(saleDetails).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList"); List> tabledata = new ArrayList(); String customerCode = "";String orderNo = ""; String arrivalPlanTime_New = ""; for (int b=0;b< datas.size();b++){ JSONObject object = datas.getJSONObject(b); customerCode = object.getString("customerCode");//客户 orderNo = object.getString("orderNo");//订单号 arrivalPlanTime_New = object.getString("arrivalPlanTime");//计划交货日期 } for (int a=0;a< prods.size();a++){ JSONObject detail = prods.getJSONObject(a); HashMap row = new HashMap(); String productCode = detail.getString("productCode");//款号 String productName = detail.getString("productName");//产品描述 Double qty = detail.getDouble("qty");//数量 Double unitPrice = detail.getDouble("unitPrice");//单价 double saleamount = detail.getDouble("qty") * detail.getDouble("unitPrice");//销售金额 String color = ""; JSONArray array1 = detail.getJSONArray("customFieldValues"); color = array1.stream() .map(obj -> (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 82259) .map(item -> item.getString("value")) .findFirst() .orElse(null); String currency = ""; currency = array1.stream() .map(obj -> (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 47919) .map(item -> item.getString("value")) .findFirst() .orElse(null); //币别 ArrayList colorList = new ArrayList(); colorList.add(color); String color_AAA = getProductColor(colorList);//颜色 row.put("textField_mhsj6gtn",customerCode); row.put("textField_mhsj6gto",orderNo); row.put("textField_mhsj6gtp",productCode); row.put("textField_mhsj6gtq",productName); row.put("textField_mk4rrk35",color_AAA);// row.put("numberField_mk4rrk3b",qty);// row.put("numberField_mk4rrk3d",unitPrice);// row.put("numberField_mk4rrk3e",saleamount);// row.put("textField_mhtxft3p",currency); tabledata.add(row); } // 销售订单明细转换为宜搭表单字段的 formData HashMap fromdata = new HashMap(); fromdata.put("tableField_mhsj6gtm",tabledata); log.info("[修改后的销售明细值],{}",tabledata); // 查询修改前的宜搭数据 formData List> tabledata_yida = new ArrayList(); List list = (List) ydClient.queryData(YDParam.builder() .formUuid("FORM-472F0C1BD8DF41FA965A0B4525779B67S421") .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch( "textField_mfqgmwcw", orderNo, "订单编号", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ)))) .build() ,YDConf.FORM_QUERY.retrieve_list).getData(); String formInstanceId = (String) list.get(0).get("formInstanceId"); Map data = (Map) ydClient.queryData(YDParam.builder().formInstId(formInstanceId) .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData(); String arrivalPlanTime_Old = data.get("dateField_mfqgmwcz").toString(); List> table = (List>) data.get("tableField_mfqgmwe0"); for (Map row : table) { HashMap row_yida = new HashMap(); row_yida.put("textField_mhsj6gtn",data.get("textField_mfqgmwcx")); row_yida.put("textField_mhsj6gto",data.get("textField_mfqgmwcw")); row_yida.put("textField_mhsj6gtp",row.get("textField_mfqgmwe1")); row_yida.put("textField_mhsj6gtq",row.get("textField_mfqgmwe2")); row_yida.put("textField_mk4rrk35",row.get("textField_mk0jz9i1")); row_yida.put("numberField_mk4rrk3b",row.get("numberField_mfqgmwe6")); row_yida.put("numberField_mk4rrk3d",row.get("numberField_mfqgmwe8")); row_yida.put("numberField_mk4rrk3e",row.get("numberField_mfqgmweb")); row_yida.put("textField_mhtxft3p",row.get("textField_mk0xio3b")); tabledata_yida.add(row_yida); } HashMap fromdata_yida = new HashMap(); fromdata_yida.put("tableField_mhsj6gtm",tabledata_yida); log.info("[修改前的销售明细值],{}",tabledata_yida); // 对比获取变更的KEY列表 AI List> result = compareAndGetChanges(tabledata_yida, tabledata); log.info("[变更的值],{}",result); // 包含 发起宜搭审批 StartYidaAproval(orderNo,"FORM-9A44F1DA0F5B4D319A6D06692767564CFHDS"); //查找销售订单变更审批的实例id List lis = (List) ydClient.queryData(YDParam.builder() .formUuid("FORM-9A44F1DA0F5B4D319A6D06692767564CFHDS") .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch( "textField_mfqgmwcw", orderNo, "订单编号", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ)))) .build() ,YDConf.FORM_QUERY.retrieve_list).getData(); String instanceId = (String) lis.get(0).get("formInstanceId"); log.info("[销售订单审批变更的实例id],{}",instanceId); //把变更的数据整理去走operateData方法 Map>> grouped = result.stream() .collect(Collectors.groupingBy(m -> (String) m.get("billNo"))); List> ret = new ArrayList<>(); for (List> group : grouped.values()) { Map merged = new LinkedHashMap<>(); // 保持插入顺序(可选) for (Map item : group) { String field = (String) item.get("field"); Object oldValue = item.get("oldValue"); merged.put(field, oldValue); } ret.add(merged); } System.out.println("即将插入的数据" + ret); Map formdata = new HashMap(); if(!arrivalPlanTime_New.equals(arrivalPlanTime_Old)){ formdata.put("textareaField_mjghnmvv",AAAA(arrivalPlanTime_Old)); } formdata.put("tableField_mk4rrk3k",ret); ydClient.operateData(YDParam.builder() .formInstanceId(instanceId) .updateFormDataJson(JSONObject.toJSONString(formdata)) .build(),YDConf.FORM_OPERATION.update); return McR.success(); } /** * 对比新旧列表,返回所有变更项(Java 8 兼容) * * 返回格式:List> * 每个 Map 包含: * - "billNo": 单号(textField_mhsj6gtp 的值) * - "field": 变更的字段名 * - "oldValue": 旧值 * - "newValue": 新值 */ public static List> compareAndGetChanges( List> oldList, List> newList) { Map> oldIndex = toIndex(oldList); Map> newIndex = toIndex(newList); List> changes = new ArrayList<>(); for (String billNo : oldIndex.keySet()) { Map oldRow = oldIndex.get(billNo); Map newRow = newIndex.get(billNo); if (newRow == null) { continue; } for (Map.Entry entry : oldRow.entrySet()) { String field = entry.getKey(); Object oldValue = entry.getValue(); Object newValue = newRow.get(field); if (!Objects.equals(oldValue, newValue)) { Map change = new HashMap<>(); change.put("billNo", billNo); change.put("field", field); change.put("oldValue", oldValue); change.put("newValue", newValue); changes.add(change); } } } return changes; } // 构建以 textField_mhsj6gtp 为 key 的索引 private static Map> toIndex(List> list) { Map> index = new HashMap<>(); for (Map row : list) { if (row.containsKey(MATCH_KEY)) { String key = String.valueOf(row.get(MATCH_KEY)); // 避免重复 key 覆盖(保留第一个) if (!index.containsKey(key)) { index.put(key, row); } } } return index; } /*返回备注信息*/ public static String AAAA(String ccc){ String aa = ""; String dd = Instant.ofEpochMilli(Long.parseLong(ccc)) .atZone(ZoneId.of("Asia/Shanghai")) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); aa = "{\"dateField_mfqgmwcz\":\"

" + dd +"

\"}"; return aa; } @Override public String getProductColor(List list) throws JacksonException { HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); HashMap body = new HashMap(); body.put("type","PRODUCT"); body.put("ids",list); String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/customField/associatedBusinessObject/entity/queryList", header, null, body); JSONObject jsonObject = JSONObject.parseObject(doPost); JSONArray dataArray = jsonObject.getJSONArray("data"); System.out.println(dataArray); /* String productName = ""; for (int i = 0; i < dataArray.size(); i++) { JSONObject data = dataArray.getJSONObject(i); productName = data.getString("productName"); }*/ String colorValue = ""; if (dataArray != null && dataArray.size() > 0) { JSONObject data = dataArray.getJSONObject(0); JSONObject customFieldValues = data.getJSONObject("customFieldValues"); if (customFieldValues != null) { // 直接获取指定字段的值 colorValue = customFieldValues.getString("product1741831360685211"); } } return colorValue; } @Override public McR purchaseSchedule() throws JacksonException { HashMap header = new HashMap(); header.put("X-AUTH", HeiHuAccessToken().getData().toString()); header.put("Content-Type", "application/json"); String targetValue = "合同确认,提交审批"; // String targetValue1 = "合同修改,修改审批"; Map> purchaserOrderCodes = new HashMap<>(); int pageNum = 1; int pageSize = 100; boolean hasMoreData = true; while (hasMoreData) { HashMap body = new HashMap(); Map page = new HashMap<>(); page.put("pageNum", pageNum); page.put("pageSize", pageSize); List status = Arrays.asList(1); body.put("page", page); body.put("status", status); String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//查询采购订单 ObjectMapper mapper = new ObjectMapper(); Map response = mapper.readValue(doPost, Map.class); if (!"01000000".equals(response.get("code"))) { System.out.println("请求失败: " + response.get("msg")); break; } List> dataList = (List>) response.get("data"); if (dataList != null) { for (Map item : dataList) { String purchaserName = (String) item.get("purchaserName"); if (purchaserName == null) purchaserName = "未知"; boolean hasTargetStatus = false; List> customFieldValues = (List>) item.get("customFieldValues"); if (customFieldValues != null) { for (Map field : customFieldValues) { // if (targetValue.equals(field.get("value") ) || targetValue1.equals(field.get("value"))) { if (targetValue.equals(field.get("value"))) { hasTargetStatus = true; break; } } } if (hasTargetStatus) { String orderCode = (String) item.get("orderCode"); if (orderCode != null) { purchaserOrderCodes.computeIfAbsent(purchaserName, k -> new ArrayList<>()).add(orderCode); } } } hasMoreData = dataList.size() >= pageSize; } else { hasMoreData = false; } pageNum++; try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } // 输出所有采购员的待审批订单 System.out.println("========== 所有采购员的待审批订单统计 =========="); if (purchaserOrderCodes.isEmpty()) { System.out.println("没有找到钉钉审批状态为'" + targetValue + "'的订单"); } else { int totalPurchasers = purchaserOrderCodes.size(); int totalOrders = purchaserOrderCodes.values().stream().mapToInt(List::size).sum(); System.out.println("共找到 " + totalOrders + " 个待审批订单"); System.out.println("涉及 " + totalPurchasers + " 位采购员"); System.out.println(); // 输出每个采购员的情况 for (Map.Entry> entry : purchaserOrderCodes.entrySet()) { String purchaserName = entry.getKey(); List orderCodes = entry.getValue(); int orderCount = orderCodes.size(); System.out.println("采购员: " + purchaserName); System.out.println("待审批订单数量: " + orderCount); if (orderCount > 1) { System.out.println("⚠️ 注意:该采购员有 " + orderCount + " 个待审批订单"); } System.out.println("订单编号: " + String.join(", ", orderCodes)); System.out.println(); } // 按订单数量排序输出 System.out.println("========== 按待审批订单数量排序 =========="); purchaserOrderCodes.entrySet().stream() .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size())) .forEach(entry -> { String purchaserName = entry.getKey(); List orderCodes = entry.getValue(); System.out.println(purchaserName + " (" + orderCodes.size() + "个): " + String.join(", ", orderCodes)); // ========== 修改点1:声明两个列表分别存储不同毛利率的订单数据 ========== // 针对同一个采购员,遍历下面的订单编号 System.out.println("开始处理采购员 " + purchaserName + " 的 " + orderCodes.size() + " 个待审批订单"); // 高毛利率表单数据 (mlv >= 0.15) HashMap formdataHigh = new HashMap(); List> tabledataHigh = new ArrayList(); // 低毛利率表单数据 (mlv < 0.15) HashMap formdataLow = new HashMap(); List> tabledataLow = new ArrayList(); // ========== 修改点2:为每个订单创建临时存储列表 ========== // 用于暂存每个订单的明细数据,等计算出毛利率后再决定添加到哪个列表 Map>> tempOrderDataMap = new HashMap<>(); // 用于存储每个订单的汇总数据,用于计算毛利率 Map> orderSummaryForMlv = new HashMap<>(); for (String orderCode : orderCodes) { System.out.println("正在处理订单: " + orderCode); // ========== 修改点3:为当前订单创建临时数据存储 ========== List> currentOrderRows = new ArrayList<>(); double orderTotalSalesAmount = 0.0; double orderTotalPurchaseAmount = 0.0; double orderTotalFlygcb = 0.0; //todo:查询订单的销售订单 | 客户 销售订单号 款式 产品描述 颜色 | 数量 销售单价 销售金额 | 币别 美金汇率 辅料预估成本 销售总金额 String customerName = "",orderNumber ="",styleNumber ="",productDescription = "",color = ""; Double number,unitPrice,salesAmount; String currency = ""; Double USDrate = 0.00; Double flygcb = 0.00; Double saletotalAmount = 0.00; Double estimatedPrice = 0.00;//辅料预估单价 HashMap body = new HashMap(); body.put("orderCode",orderCode);//订单编号 String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body); //todo:查询采购订单 生产工厂(供应商) String shortName = ""; JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data"); for (int i=0;i 0){ orderNumber = saleOrders.get(0).asText();//销售订单号 } } } HashMap body_A = new HashMap(); body_A.put("orderNo",orderNumber); String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo:查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别 JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据 for(int i=0;i (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 82259) .map(item -> item.getString("value")) .findFirst() .orElse(null); ArrayList colorList = new ArrayList(); colorList.add(color); String color_AAA = null; try { color_AAA = getProductColor(colorList); } catch (JacksonException e) { throw new RuntimeException(e); } row.put("textField_ml7c3yhs", color_AAA);//todo:颜色 number = detail.getDoubleValue("qty");//数量 row.put("numberField_ml7c3yht", number);//todo:数量 unitPrice = detail.getDoubleValue("unitPrice");//销售单价 row.put("numberField_ml7c3yhu", unitPrice);//todo:销售单价 salesAmount = number * unitPrice;//销售金额 row.put("numberField_ml7c3yhv", salesAmount);//todo:销售金额 String customFieldValues = detail.getString("customFieldValues"); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonarray = null; try { jsonarray = mapper.readTree(customFieldValues); } catch (JsonProcessingException e) { throw new RuntimeException(e); } for (JsonNode node : jsonarray) { if (node.get("fieldId").asInt() == 47919) { currency = node.get("value").asText(); } else if (node.get("fieldId").asInt() == 165251) { USDrate = node.get("value").asDouble(); } else if (node.get("fieldId").asInt() == 161783) { flygcb = node.get("value").asDouble(); } } row.put("textField_ml7c3yhw", currency);//todo:币别 row.put("numberField_ml86221y", USDrate);//todo:美金汇率 row.put("numberField_ml86221z", flygcb);//todo:辅料预估成本 if(currency.equals("USD")){ saletotalAmount = salesAmount * USDrate; }else { saletotalAmount = salesAmount; } row.put("numberField_ml862220",saletotalAmount); //下面是采购订单的明细数据 row.put("textField_ml7c3yhx",shortName);//todo:生产工厂 for(int j=0;j并暂存 ========== Map rowMap = new HashMap<>(); for (Object key : row.keySet()) { Object value = row.get(key); rowMap.put(key.toString(), value != null ? value.toString() : ""); } currentOrderRows.add(rowMap); // ========== 修改点5:累加当前订单的汇总数据用于计算毛利率 ========== orderTotalSalesAmount += saletotalAmount; orderTotalPurchaseAmount += (Double)row.get("numberField_ml7c3yi0"); orderTotalFlygcb += flygcb; } } // ========== 修改点6:计算当前订单的毛利率 ========== double mlv = 0.0; if (orderTotalSalesAmount > 0) { mlv = (orderTotalSalesAmount - orderTotalPurchaseAmount - orderTotalFlygcb) / orderTotalSalesAmount; } System.out.println("订单 " + orderCode + " 毛利率: " + String.format("%.2f%%", mlv * 100)); // ========== 修改点7:根据毛利率决定添加到哪个列表 ========== if (mlv >= 0.15) { // 高毛利率订单 tabledataHigh.addAll(currentOrderRows); System.out.println("订单 " + orderCode + " 归类到高毛利率审批(>=15%)"); } else { // 低毛利率订单 tabledataLow.addAll(currentOrderRows); System.out.println("订单 " + orderCode + " 归类到低毛利率审批(<15%)"); } } // ========== 修改点8:分别处理高低毛利率的审批 ========== // 处理高毛利率的审批 (mlv >= 0.15) if (!tabledataHigh.isEmpty()) { System.out.println("\n========== 开始处理高毛利率审批(>=15%),共 " + tabledataHigh.size() + " 条明细 =========="); //组装数据塞到采购明细表 formdataHigh.put("tableField_ml6g7k5d", tabledataHigh); //组装数据塞到采购审批单号明细 List> orderSummaryListHigh = calculateOrderSummary(tabledataHigh); formdataHigh.put("tableField_ml7ch2pj", orderSummaryListHigh); //数值统计毛利率 int szHigh = 0; for (Map map : orderSummaryListHigh) { Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo"); log.info((String) numberFieldMm2t71jo); szHigh += Integer.parseInt((String) numberFieldMm2t71jo); } formdataHigh.put("numberField_mm2t71jp", szHigh); /*发起流程 - 高毛利率审批*/ String userId = getDDToken(purchaserName); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") // 高毛利率使用原表单 .userId(userId) .formDataJson(JSON.toJSONString(formdataHigh)) .build(), YDConf.FORM_OPERATION.start).toString(); /*修改采购订单为审批中*/ for (Map map : orderSummaryListHigh) { String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk"); callback(textFieldMl7ch2pk); } System.out.println("高毛利率审批流程发起完成"); } // 处理低毛利率的审批 (mlv < 0.15) if (!tabledataLow.isEmpty()) { System.out.println("\n========== 开始处理低毛利率审批(<15%),共 " + tabledataLow.size() + " 条明细 =========="); //组装数据塞到采购明细表 formdataLow.put("tableField_ml6g7k5d", tabledataLow); //组装数据塞到采购审批单号明细 List> orderSummaryListLow = calculateOrderSummary(tabledataLow); formdataLow.put("tableField_ml7ch2pj", orderSummaryListLow); //数值统计毛利率 int szLow = 0; for (Map map : orderSummaryListLow) { Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo"); log.info((String) numberFieldMm2t71jo); szLow += Integer.parseInt((String) numberFieldMm2t71jo); } formdataLow.put("numberField_mm2t71jp", szLow); /*发起流程 - 低毛利率审批*/ String userId = getDDToken(purchaserName); // ========== 修改点9:如果低毛利率需要不同表单,可以在这里修改formUuid ========== ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") // 如果需要不同流程,替换这里的UUID .userId(userId) .formDataJson(JSON.toJSONString(formdataLow)) .build(), YDConf.FORM_OPERATION.start).toString(); /*修改采购订单为审批中*/ for (Map map : orderSummaryListLow) { String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk"); callback(textFieldMl7ch2pk); } System.out.println("低毛利率审批流程发起完成"); } }); } return null; } @Override public McR purchaseUpdateSchedule() throws JacksonException { HashMap header = new HashMap(); header.put("X-AUTH", HeiHuAccessToken().getData().toString()); header.put("Content-Type", "application/json"); String targetValue = "合同修改,修改审批"; Map> purchaserOrderCodes = new HashMap<>(); int pageNum = 1; int pageSize = 100; boolean hasMoreData = true; boolean isUpdate = false; while (hasMoreData) { HashMap body = new HashMap(); Map page = new HashMap<>(); page.put("pageNum", pageNum); page.put("pageSize", pageSize); List status = Arrays.asList(1); body.put("page", page); body.put("status", status); String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//查询采购订单 ObjectMapper mapper = new ObjectMapper(); Map response = mapper.readValue(doPost, Map.class); if (!"01000000".equals(response.get("code"))) { System.out.println("请求失败: " + response.get("msg")); break; } List> dataList = (List>) response.get("data"); if (dataList != null) { for (Map item : dataList) { String purchaserName = (String) item.get("purchaserName"); if (purchaserName == null) purchaserName = "未知"; boolean hasTargetStatus = false; List> customFieldValues = (List>) item.get("customFieldValues"); if (customFieldValues != null) { for (Map field : customFieldValues) { if (targetValue.equals(field.get("value"))) { hasTargetStatus = true; break; } } } if (hasTargetStatus) { String orderCode = (String) item.get("orderCode"); if (orderCode != null) { purchaserOrderCodes.computeIfAbsent(purchaserName, k -> new ArrayList<>()).add(orderCode); } } } hasMoreData = dataList.size() >= pageSize; } else { hasMoreData = false; } pageNum++; try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } // 输出所有采购员的待审批订单 System.out.println("========== 所有采购员的待审批订单统计 =========="); if (purchaserOrderCodes.isEmpty()) { System.out.println("没有找到钉钉审批状态为'" + targetValue + "'的订单"); } else { int totalPurchasers = purchaserOrderCodes.size(); int totalOrders = purchaserOrderCodes.values().stream().mapToInt(List::size).sum(); System.out.println("共找到 " + totalOrders + " 个待审批订单"); System.out.println("涉及 " + totalPurchasers + " 位采购员"); System.out.println(); // 输出每个采购员的情况 for (Map.Entry> entry : purchaserOrderCodes.entrySet()) { String purchaserName = entry.getKey(); List orderCodes = entry.getValue(); int orderCount = orderCodes.size(); System.out.println("采购员: " + purchaserName); System.out.println("待审批订单数量: " + orderCount); if (orderCount > 1) { System.out.println("⚠️ 注意:该采购员有 " + orderCount + " 个待审批订单"); } System.out.println("订单编号: " + String.join(", ", orderCodes)); System.out.println(); } // 按订单数量排序输出 System.out.println("========== 按待审批订单数量排序 =========="); purchaserOrderCodes.entrySet().stream() .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size())) .forEach(entry -> { String purchaserName = entry.getKey(); List orderCodes = entry.getValue(); System.out.println(purchaserName + " (" + orderCodes.size() + "个): " + String.join(", ", orderCodes)); // ========== 修改点1:声明两个列表分别存储不同毛利率的订单数据 ========== // 针对同一个采购员,遍历下面的订单编号 System.out.println("开始处理采购员 " + purchaserName + " 的 " + orderCodes.size() + " 个待审批订单"); // 高毛利率表单数据 (mlv >= 0.15) HashMap formdataHigh = new HashMap(); List> tabledataHigh = new ArrayList(); // 低毛利率表单数据 (mlv < 0.15) HashMap formdataLow = new HashMap(); List> tabledataLow = new ArrayList(); // ========== 修改点2:为每个订单创建临时存储列表 ========== // 用于暂存每个订单的明细数据,等计算出毛利率后再决定添加到哪个列表 Map>> tempOrderDataMap = new HashMap<>(); // 用于存储每个订单的汇总数据,用于计算毛利率 Map> orderSummaryForMlv = new HashMap<>(); List oldHighIds = new ArrayList<>(); List oldLowIds = new ArrayList<>(); for (String orderCode : orderCodes) { System.out.println("正在处理订单: " + orderCode); // ========== 修改点3:为当前订单创建临时数据存储 ========== List> currentOrderRows = new ArrayList<>(); double orderTotalSalesAmount = 0.0; double orderTotalPurchaseAmount = 0.0; double orderTotalFlygcb = 0.0; //todo:查询订单的销售订单 | 客户 销售订单号 款式 产品描述 颜色 | 数量 销售单价 销售金额 | 币别 美金汇率 辅料预估成本 销售总金额 String customerName = "",orderNumber ="",styleNumber ="",productDescription = "",color = ""; Double number,unitPrice,salesAmount; String currency = ""; Double USDrate = 0.00; Double flygcb = 0.00; Double saletotalAmount = 0.00; Double estimatedPrice = 0.00;//辅料预估单价 HashMap body = new HashMap(); body.put("orderCode",orderCode);//订单编号 String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body); //todo:查询采购订单 生产工厂(供应商) String shortName = ""; JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data"); for (int i=0;i 0){ orderNumber = saleOrders.get(0).asText();//销售订单号 } } } HashMap body_A = new HashMap(); body_A.put("orderNo",orderNumber); String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo:查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别 JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据 for(int i=0;i (JSONObject) obj) .filter(item -> item.getIntValue("fieldId") == 82259) .map(item -> item.getString("value")) .findFirst() .orElse(null); ArrayList colorList = new ArrayList(); colorList.add(color); String color_AAA = null; try { color_AAA = getProductColor(colorList); } catch (JacksonException e) { throw new RuntimeException(e); } row.put("textField_ml7c3yhs", color_AAA);//todo:颜色 number = detail.getDoubleValue("qty");//数量 row.put("numberField_ml7c3yht", number);//todo:数量 unitPrice = detail.getDoubleValue("unitPrice");//销售单价 row.put("numberField_ml7c3yhu", unitPrice);//todo:销售单价 salesAmount = number * unitPrice;//销售金额 row.put("numberField_ml7c3yhv", salesAmount);//todo:销售金额 String customFieldValues = detail.getString("customFieldValues"); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonarray = null; try { jsonarray = mapper.readTree(customFieldValues); } catch (JsonProcessingException e) { throw new RuntimeException(e); } for (JsonNode node : jsonarray) { if (node.get("fieldId").asInt() == 47919) { currency = node.get("value").asText(); } else if (node.get("fieldId").asInt() == 165251) { USDrate = node.get("value").asDouble(); } else if (node.get("fieldId").asInt() == 161783) { flygcb = node.get("value").asDouble(); } } row.put("textField_ml7c3yhw", currency);//todo:币别 row.put("numberField_ml86221y", USDrate);//todo:美金汇率 row.put("numberField_ml86221z", flygcb);//todo:辅料预估成本 if(currency.equals("USD")){ saletotalAmount = salesAmount * USDrate; }else { saletotalAmount = salesAmount; } row.put("numberField_ml862220",saletotalAmount); //下面是采购订单的明细数据 row.put("textField_ml7c3yhx",shortName);//todo:生产工厂 for(int j=0;j并暂存 ========== Map rowMap = new HashMap<>(); for (Object key : row.keySet()) { Object value = row.get(key); rowMap.put(key.toString(), value != null ? value.toString() : ""); } currentOrderRows.add(rowMap); // ========== 修改点5:累加当前订单的汇总数据用于计算毛利率 ========== orderTotalSalesAmount += saletotalAmount; orderTotalPurchaseAmount += (Double)row.get("numberField_ml7c3yi0"); orderTotalFlygcb += flygcb; } } // ========== 修改点6:计算当前订单的毛利率 ========== double mlv = 0.0; if (orderTotalSalesAmount > 0) { mlv = (orderTotalSalesAmount - orderTotalPurchaseAmount - orderTotalFlygcb) / orderTotalSalesAmount; } System.out.println("订单 " + orderCode + " 毛利率: " + String.format("%.2f%%", mlv * 100)); // ========== 修改点7:根据毛利率决定添加到哪个列表 ========== if (mlv >= 0.15) { // 高毛利率订单 tabledataHigh.addAll(currentOrderRows); oldHighIds.add(orderCode); System.out.println("订单 " + orderCode + " 归类到高毛利率审批(>=15%)"); } else { // 低毛利率订单 tabledataLow.addAll(currentOrderRows); oldLowIds.add(orderCode); System.out.println("订单 " + orderCode + " 归类到低毛利率审批(<15%)"); } } // ========== 修改点8:分别处理高低毛利率的审批 ========== // 处理高毛利率的审批 (mlv >= 0.15) if (!tabledataHigh.isEmpty()) { System.out.println("\n========== 开始处理高毛利率审批(>=15%),共 " + tabledataHigh.size() + " 条明细 =========="); List> oldList = new ArrayList<>(); oldHighIds.forEach(h->{ List dataList = ydService.queryFormData_all(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY") .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h))) .build()); if (ObjectUtil.isNotNull(dataList) && dataList.size()>0){ List sonList = ydService.queryDetails(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formInstanceId(UtilMap.getString(dataList.get(0),"textField_mmx9gycu")) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") .tableFieldId("tableField_ml6g7k5d") .build()); if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){ sonList.forEach(s->{ Map map = new HashMap<>(); TABLEFIELD_ENUM.forEach((k,v)->{ map.put(v,UtilMap.getString(s,k)); }); oldList.add(map); }); } } }); //组装数据塞到采购明细表 formdataHigh.put("tableField_ml6g7k5d", tabledataHigh); formdataHigh.put("tableField_mmx6gata", oldList); //组装数据塞到采购审批单号明细 List> orderSummaryListHigh = calculateOrderSummary(tabledataHigh); formdataHigh.put("tableField_ml7ch2pj", orderSummaryListHigh); //数值统计毛利率 int szHigh = 0; for (Map map : orderSummaryListHigh) { Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo"); log.info((String) numberFieldMm2t71jo); szHigh += Integer.parseInt((String) numberFieldMm2t71jo); } formdataHigh.put("numberField_mm2t71jp", szHigh); /*发起流程 - 高毛利率审批*/ String userId = getDDToken(purchaserName); ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") // 高毛利率使用原表单 .userId(userId) .formDataJson(JSON.toJSONString(formdataHigh)) .build(), YDConf.FORM_OPERATION.start).toString(); /*修改采购订单为审批中*/ for (Map map : orderSummaryListHigh) { String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk"); callback(textFieldMl7ch2pk); } System.out.println("高毛利率审批流程发起完成"); } // 处理低毛利率的审批 (mlv < 0.15) if (!tabledataLow.isEmpty()) { System.out.println("\n========== 开始处理低毛利率审批(<15%),共 " + tabledataLow.size() + " 条明细 =========="); List> oldList = new ArrayList<>(); oldLowIds.forEach(h->{ List dataList = ydService.queryFormData_all(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY") .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h))) .build()); if (ObjectUtil.isNotNull(dataList) && dataList.size()>0){ List sonList = ydService.queryDetails(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formInstanceId(UtilMap.getString(dataList.get(0),"textField_mmx9gycu")) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") .tableFieldId("tableField_ml6g7k5d") .build()); if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){ sonList.forEach(s->{ Map map = new HashMap<>(); TABLEFIELD_ENUM.forEach((k,v)->{ map.put(v,UtilMap.getString(s,k)); }); oldList.add(map); }); } } }); //组装数据塞到采购明细表 formdataHigh.put("tableField_mmx6gata", oldList); //组装数据塞到采购明细表 formdataLow.put("tableField_ml6g7k5d", tabledataLow); //组装数据塞到采购审批单号明细 List> orderSummaryListLow = calculateOrderSummary(tabledataLow); formdataLow.put("tableField_ml7ch2pj", orderSummaryListLow); //数值统计毛利率 int szLow = 0; for (Map map : orderSummaryListLow) { Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo"); log.info((String) numberFieldMm2t71jo); szLow += Integer.parseInt((String) numberFieldMm2t71jo); } formdataLow.put("numberField_mm2t71jp", szLow); /*发起流程 - 低毛利率审批*/ String userId = getDDToken(purchaserName); // ========== 修改点9:如果低毛利率需要不同表单,可以在这里修改formUuid ========== ydClient.operateData(YDParam.builder() .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken()) .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2") // 如果需要不同流程,替换这里的UUID .userId(userId) .formDataJson(JSON.toJSONString(formdataLow)) .build(), YDConf.FORM_OPERATION.start).toString(); /*修改采购订单为审批中*/ for (Map map : orderSummaryListLow) { String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk"); callback(textFieldMl7ch2pk); } System.out.println("低毛利率审批流程发起完成"); } }); } return null; } private static final Map TABLEFIELD_ENUM =new HashMap<>(); static { TABLEFIELD_ENUM.put("textField_mm2t71jm","textField_mmx6gast"); TABLEFIELD_ENUM.put("textField_ml6g7k5e","textField_mmx6gasu"); TABLEFIELD_ENUM.put("textField_ml6g7k5f","textField_mmx6gasv"); TABLEFIELD_ENUM.put("textField_ml7c3yhq","textField_mmx6gasw"); TABLEFIELD_ENUM.put("textField_ml7c3yhr","textField_mmx6gasx"); TABLEFIELD_ENUM.put("textField_ml7c3yhs","textField_mmx6gasy"); TABLEFIELD_ENUM.put("numberField_ml7c3yht","numberField_mmx6gasz"); TABLEFIELD_ENUM.put("numberField_ml7c3yhu","numberField_mmx6gat0"); TABLEFIELD_ENUM.put("numberField_ml7c3yhv","numberField_mmx6gat1"); TABLEFIELD_ENUM.put("textField_ml7c3yhw","textField_mmx6gat2"); TABLEFIELD_ENUM.put("numberField_ml86221y","numberField_mmx6gat3"); TABLEFIELD_ENUM.put("numberField_ml86221z","numberField_mmx6gat4"); TABLEFIELD_ENUM.put("numberField_ml862220","numberField_mmx6gat5"); TABLEFIELD_ENUM.put("textField_ml7c3yhx","textField_mmx6gat6"); TABLEFIELD_ENUM.put("numberField_ml7c3yhy","numberField_mmx6gat7"); TABLEFIELD_ENUM.put("numberField_ml7c3yhz","numberField_mmx6gat8"); TABLEFIELD_ENUM.put("numberField_ml7c3yi0","numberField_mmx6gat9"); } /** * 根据orderCode对tabledata进行分类求和 * @param tableData 原始明细数据 * @return 按orderCode汇总后的数据列表(只包含求和结果) */ private List> calculateOrderSummary(List> tableData) { // 使用Map暂存每个orderCode的汇总数据 Map> summaryMap = new LinkedHashMap<>(); for (Map row : tableData) { String orderCode = row.get("textField_mm2t71jm"); // 采购订单号 if (orderCode == null || orderCode.isEmpty()) { continue; } // 获取或创建该订单的汇总Map Map orderSum = summaryMap.computeIfAbsent(orderCode, k -> { Map newMap = new HashMap<>(); newMap.put("salesAmount", 0.0); // 销售金额总和 newMap.put("purchaseAmount", 0.0); // 采购金额总和 newMap.put("flygcb", 0.0); // 辅料预估成本总和 return newMap; }); // 累加各项金额 String salesAmountStr = UtilMap.getString(row,"numberField_ml862220"); String purchaseAmountStr = UtilMap.getString(row,"numberField_ml7c3yi0"); String flygcbStr = UtilMap.getString(row,"numberField_ml86221z"); try { if (salesAmountStr != null && !salesAmountStr.isEmpty()) { orderSum.put("salesAmount", orderSum.get("salesAmount") + Double.parseDouble(salesAmountStr)); } if (purchaseAmountStr != null && !purchaseAmountStr.isEmpty()) { orderSum.put("purchaseAmount", orderSum.get("purchaseAmount") + Double.parseDouble(purchaseAmountStr)); } if (flygcbStr != null && !flygcbStr.isEmpty()) { orderSum.put("flygcb", orderSum.get("flygcb") + Double.parseDouble(flygcbStr)); } } catch (NumberFormatException e) { System.err.println("数字格式错误: " + e.getMessage()); } } // 转换为最终的List> List> result = new ArrayList<>(); for (Map.Entry> entry : summaryMap.entrySet()) { String orderCode = entry.getKey(); Map sums = entry.getValue(); double salesAmount = sums.get("salesAmount"); double purchaseAmount = sums.get("purchaseAmount"); double flygcb = sums.get("flygcb"); // 构建结果行 Map summaryRow = new LinkedHashMap<>(); summaryRow.put("textField_ml7ch2pk", orderCode);//orderCode:采购审批单单号 summaryRow.put("numberField_ml862225", formatNumber(salesAmount));//salesAmount:销售总金额 summaryRow.put("numberField_ml862226", formatNumber(purchaseAmount));//purchaseAmount:采购订单总金额 summaryRow.put("numberField_ml862228", formatNumber(flygcb));//flygcb:辅料预估总成本 summaryRow.put("numberField_ml86222d",formatNumber((salesAmount - purchaseAmount - flygcb) / salesAmount));//毛利率 Double mlv = (salesAmount - purchaseAmount - flygcb) / salesAmount; if(mlv >= 0.15){ summaryRow.put("numberField_mm2t71jo", String.valueOf(1)); }else { summaryRow.put("numberField_mm2t71jo", String.valueOf(0)); } result.add(summaryRow); } return result; } /** * 格式化数字,去除多余的.0 */ private String formatNumber(double number) { if (Math.abs(number - Math.round(number)) < 0.000001) { return String.valueOf((long) number); } else { return String.format("%.2f", number); } } /*采购订单发起更新状态*/ @SneakyThrows public McR callback(String orderNum){ HashMap header = new HashMap(); header.put("X-AUTH",HeiHuAccessToken().getData().toString()); header.put("Content-Type","application/json"); HashMap body = new HashMap(); body.put("orderCode",orderNum);//订单编号 String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单 JSONArray dataArray = JSONObject.parseObject(jsonString2).getJSONArray("data"); for (int k=0;k> customFiled = new ArrayList(); HashMap field = new HashMap(); field.put("name","采购订单钉钉审批状态"); field.put("value","审批中");//审批状态 customFiled.add(field); body1.put("purchaseOrderCustomFieldsValue",customFiled); UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1); } return McR.success(); } /*获取宜搭采购订单汇总*/ @SneakyThrows McR getPurchaseList(){ log.info("开始查询宜搭采购订单汇总表"); String formUuid = "FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91"; YDParam ydParam = YDParam.builder().formUuid(formUuid).build(); ydParam.setPageSize(1); long totalCount = ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getTotalCount(); List datalist = new ArrayList<>(); ydParam.setCurrentPage(1); ydParam.setPageSize(100); int totalPages = (int)Math.ceil((double) totalCount / ydParam.getPageSize()); for (int page = 1;page <= totalPages;page++){ ydParam.setCurrentPage(page); datalist.addAll((List) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData()); } int i =0; String jsonStr = ""; Map orderMap = new HashMap<>();//格式:采购订单/关联销售订单 for(Map li : datalist){ i++; // log.info("{}/{}",i,datalist.size()); jsonStr = li.get("formData").toString(); String orderNum = new ObjectMapper().readTree(jsonStr).get("textField_mgq932hi").asText(); String relatedOrderNum = new ObjectMapper().readTree(jsonStr).get("textField_mhyh7ues").asText(); orderMap.put(orderNum, relatedOrderNum); } return McR.success(orderMap); } }