与第三方系统对接,生成Cloud出入库单据

案例:

Cloud的采购订单同步到第三方系统,第三方系统入库后同步生成Cloud采购入库单。

解决方案:调用采购订单的下推API,先生成保存状态的采购入库单(采购入库单中的仓库是必填项,可以在采购订单中默认一个仓库通过单据转换关系携带,或者通过单据转换插件默认一个仓库),然后根据第三方的系统传过来的数据,调用这个采购入库单的保存API(JSON中的FID和FEntryID需要给定值,这个定值就是这个采购入库单的FID和FEntryID),将数量等信息按照第三方系统传过来的数据进行修改。

示例代码,仅供参考。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Contracts;
using Kingdee.BOS;
using Kingdee.BOS.Core;
using System.IO;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.Core.Msg;
using Kingdee.BOS.Util;
using System.Dynamic;
using Kingdee.BOS.Orm.Drivers;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.DataEntity;
using Newtonsoft.Json;

namespace K3CloudPlugIn
{
    public class GetInstockDataInfo : IScheduleService
    {
        K3CloudApiClient client = new K3CloudApiClient(Common.url);
        /// <summary>
        /// 实际运行的Run 方法
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="schedule"></param>
        public void Run(Context ctx, Schedule schedule)
        {
            //获取入库单中间表数据,并生成相应的采购入库单,委外入库单,生产入库单
            K3JSTService.XZGTCBS InstockService = new K3JSTService.XZGTCBS();
            string FDate = DateTime.Now.ToShortDateString();
            //调用WebService,将数据插入中间表
            //FDate = "2019-12-11";
            InstockService.GetCaiGouRuKuInfo(FDate);
            string ReturnInfo = "";
            string JsonInfo = "";
            string BillSql = "";
            string EntrySql = "";
            string result = "";
            int TotalRows = 0;
            string io_id = "";//聚水潭入库单ID
            string po_id = "";//聚水潭入库单关联的采购单ID
            DataSet ds_BillSql = new DataSet();
            DataSet ds_EntrySql = new DataSet();
            string OrderSql = "";
            DataSet ds_OrderSql = new DataSet();
            string FBillNo = "";
            string FBillID = "";
            JObject jsonRoot;
            JArray Numbers;
            JObject CustomParams;
            var loginResult = "";
            var resultType = 0;
            string autrjson;
            JObject joAudit;
            JObject joAuditIsSucess;
            JArray Fields;
            string AlterSql = "";
            DataSet ds_AlterSql = new DataSet();
            JObject basedata;
            string SaveResult = "";
            string FOrgId = "";
            BillSql = @"/*dialect*/select distinct a.* from MyOrderHouse a left join MyOrderHouseEntry b on a.io_id = b.io_id ";
            BillSql = BillSql + "left join T_BD_MATERIAL c on c.F_RFGW_TEXT = b.sku_id where ISNULL(c.FMATERIALID,0) > 0 and ISNULL(a.WinBillID,0) = 0 ";
            ds_BillSql = Kingdee.BOS.ServiceHelper.DBServiceHelper.ExecuteDataSet(ctx, BillSql);
            TotalRows = ds_BillSql.Tables[0].Rows.Count;
            if (TotalRows > 0)
            {
                for (int i = 0; i < TotalRows; i++)
                {
                    io_id = ds_BillSql.Tables[0].Rows[i]["io_id"].ToString();
                    po_id = ds_BillSql.Tables[0].Rows[i]["po_id"].ToString();

                    #region 第一种情况:该入库单对应的采购订单是由Cloud的采购订单同步过去的
                    //第一种情况:该入库单对应的采购订单是由Cloud的采购订单同步过去的
                    OrderSql = @"/*dialect*/select * from t_PUR_POOrder where FJSTORDERNO = '" + po_id + "'";
                    ds_OrderSql = Kingdee.BOS.ServiceHelper.DBServiceHelper.ExecuteDataSet(ctx,OrderSql);
                    if (ds_OrderSql.Tables[0].Rows.Count > 0)
                    {
                        FOrgId = ds_OrderSql.Tables[0].Rows[0]["FPURCHASEORGID"].ToString();
                        //获取入库单的物料编码和数量,以及对应采购订单的分录内码
                        EntrySql = @"/*dialect*/select distinct e.FENTRYID as 'EntryID',b.qty as 'Qty',c.FNUMBER as 'MatNO' from MyOrderHouse a left join MyOrderHouseEntry b on a.io_id = b.io_id ";
                        EntrySql = EntrySql + "left join T_BD_MATERIAL c on b.sku_id = c.F_RFGW_TEXT left join t_PUR_POOrder d on a.po_id = d.FJSTORDERNO ";
                        EntrySql = EntrySql + "left join t_PUR_POOrderEntry e on d.FID = e.FID and c.FMATERIALID = e.FMATERIALID ";
                        EntrySql = EntrySql + "where a.io_id = '" + io_id + "' and ISNULL(e.FENTRYID,0) > 0 and ISNULL(c.FMATERIALID,0) > 0 and c.FUSEORGID = '" + FOrgId + "'";
                        ds_EntrySql = Kingdee.BOS.ServiceHelper.DBServiceHelper.ExecuteDataSet(ctx,EntrySql);
                        if (ds_EntrySql.Tables[0].Rows.Count > 0)
                        {
                            Common.STKEntryIds = new string[ds_EntrySql.Tables[0].Rows.Count];
                            Common.STKMats = new string[ds_EntrySql.Tables[0].Rows.Count];
                            Common.STKMatIds = new int[ds_EntrySql.Tables[0].Rows.Count];
                            Common.STKqty = new decimal[ds_EntrySql.Tables[0].Rows.Count];
                            Common.STKprice = new decimal[ds_EntrySql.Tables[0].Rows.Count];
                            for (int j = 0; j < ds_EntrySql.Tables[0].Rows.Count; j++)
                            {
                                Common.STKMats[j] = ds_EntrySql.Tables[0].Rows[j]["MatNO"].ToString();
                                Common.STKEntryIds[j] = ds_EntrySql.Tables[0].Rows[j]["EntryID"].ToString();
                                Common.STKqty[j] = Convert.ToDecimal(ds_EntrySql.Tables[0].Rows[j]["Qty"].ToString());
                            }
                        }
                        //调用采购订单的下推API
                        // 开始构建Web API参数对象
                        // using Newtonsoft.Json.Linq;  // (需引用Newtonsoft.Json.dll)
                        jsonRoot = new JObject();
                        jsonRoot.Add("Ids", "");//单据内码集合,字符串类型,格式:"Id1,Id2,..."(使用内码时必录)
                        Numbers = new JArray();
                        jsonRoot.Add("Numbers", Numbers);//单据编码集合,数组类型,格式:[No1,No2,...](使用编码时必录)
                        jsonRoot.Add("EntryIds", string.Join(",", Common.STKEntryIds));//分录内码集合,逗号分隔(分录下推时必录),注(按分录下推时,单据内码和编码不需要填,否则按整单下推)
                        jsonRoot.Add("RuleId", "44789b6e-ef2e-44a3-bcb9-dd38b8f13eae");//转换规则内码,字符串类型(未启用默认转换规则时,则必录)
                        jsonRoot.Add("TargetBillTypeId", "");//目标单据类型内码,字符串类型(非必录)
                        jsonRoot.Add("TargetOrgId", 0);//目标组织内码,整型(非必录)
                        jsonRoot.Add("TargetFormId", "STK_InStock");//目标单据FormId,字符串类型,(启用默认转换规则时,则必录)
                        jsonRoot.Add("IsEnableDefaultRule", "true"); //是否启用默认转换规则,布尔类型,默认false(非必录)
                        jsonRoot.Add("IsDraftWhenSaveFail", "false");
                        CustomParams = new JObject();//自定义参数,字典类型,格式:"{key1:value1,key2:value2,...}"(非必录) ,注(传到转换插件的操作选项中,平台不会解析里面的值)
                        jsonRoot.Add("CustomParams", CustomParams);
                        JsonInfo = jsonRoot.ToString();
                        loginResult = client.ValidateLogin(Common.dbid, Common.username,Common.password, 2052);
                        resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                        //登录结果类型等于1,代表登录成功
                        if (resultType == 1)
                        {
                            ReturnInfo = client.Push("PUR_PurchaseOrder", JsonInfo);
                            try
                            {
                                JObject jo = (JObject)JsonConvert.DeserializeObject(ReturnInfo);
                                JObject JoResult = (JObject)JsonConvert.DeserializeObject(jo["Result"]["ResponseStatus"].ToString());
                                JArray array = (JArray)JsonConvert.DeserializeObject(JoResult["SuccessEntitys"].ToString());
                                FBillNo = array[0]["Number"].ToString();
                                FBillID = array[0]["Id"].ToString();

                                if (FBillNo != "")
                                {
                                    //调用采购入库单的保存API,修改实收数量和仓库
                                    jsonRoot = new JObject();
                                    jsonRoot.Add("Creator", "");
                                    Fields = new JArray();
                                    Fields.Add("FInStockEntry");
                                    Fields.Add("FRealQty");

                                    jsonRoot.Add("NeedUpDateFields", Fields);
                                    jsonRoot.Add("NeedReturnFields", new JArray());
                                    jsonRoot.Add("IsDeleteEntry", "false");
                                    jsonRoot.Add("SubSystemId", "");
                                    jsonRoot.Add("IsVerifyBaseDataField", "false");
                                    jsonRoot.Add("IsEntryBatchFill", "True");
                                    jsonRoot.Add("ValidateFlag", "True");
                                    jsonRoot.Add("NumberSearch", "True");
                                    jsonRoot.Add("InterationFlags", "STK_InvCheckResult");
                                    // Model: 单据详细数据参数
                                    JObject model = new JObject();
                                    jsonRoot.Add("Model", model);
                                    // 单据主键:必须填写,系统据此判断是新增还是修改单据;新增单据,填0
                                    model.Add("FID", FBillID.ToString());

                                    JArray entryRows = new JArray();
                                    // 把单据体行集合,添加到model中,以单据体Key为标识
                                    string entityKey = "FInStockEntry";
                                    model.Add(entityKey, entryRows);

                                    AlterSql = @"/*dialect*/select b.FSEQ,b.FENTRYID,c.FNUMBER,b.FREALQTY from t_STK_InStock a left join T_STK_INSTOCKENTRY b on a.fid = b.fid ";
                                    AlterSql = AlterSql + "left join T_BD_MATERIAL c on b.FMATERIALID = c.FMATERIALID where a.fbillno = '" + FBillNo + "'";
                                    ds_AlterSql = Kingdee.BOS.ServiceHelper.DBServiceHelper.ExecuteDataSet(ctx, AlterSql);
                                    for (int j = 0; j < ds_AlterSql.Tables[0].Rows.Count; j++)
                                    {
                                        for (int k = 0; k < Common.STKEntryIds.Length; k++)
                                        {
                                            //if (ds_AlterSql.Tables[0].Rows[j]["FSEQ"].ToString().Equals(Common.Seqs[k].ToString()) && ds_AlterSql.Tables[0].Rows[j]["FMATERIALID"].ToString().Equals(Common.TarMatIds[k].ToString()))
                                            if (ds_AlterSql.Tables[0].Rows[j]["FNUMBER"].ToString().Equals(Common.STKMats[k].ToString()))
                                            {
                                                // 添加新行,把新行加入到单据体行集合
                                                JObject entryRow = new JObject();
                                                entryRows.Add(entryRow);
                                                // 给新行,设置关键字段值
                                                // 单据体主键:必须填写,系统据此判断是新增还是修改行
                                                entryRow.Add("FEntryID", ds_AlterSql.Tables[0].Rows[j]["FENTRYID"].ToString());
                                                entryRow.Add("FRealQty", Convert.ToDecimal(Common.STKqty[k].ToString()));
                                            }
                                        }
                                    }
                                    SaveResult = Save("STK_InStock", jsonRoot.ToString());
                                    try
                                    {
                                        JObject josave = (JObject)JsonConvert.DeserializeObject(SaveResult);
                                        string number = josave["Result"]["Number"].ToString();
                                        string id = josave["Result"]["Id"].ToString();
                                        if (number != "")
                                        {
                                            autrjson = "{"CreateOrgId":0,"Numbers":["" + FBillNo + ""],"InterationFlags":"STK_InvCheckResult"}";
                                            result = Audit("STK_InStock", autrjson);
                                            joAudit = (JObject)JsonConvert.DeserializeObject(result);
                                            joAuditIsSucess = (JObject)JsonConvert.DeserializeObject(joAudit["Result"]["ResponseStatus"].ToString());
                                            string IsSucess = joAuditIsSucess["IsSuccess"].ToString();
                                            if (IsSucess.Equals("True"))
                                            {
                                                Kingdee.BOS.ServiceHelper.DBServiceHelper.Execute(ctx, @"/*dialect*/update MyOrderHouse set WinBillID = '" + FBillID + "',WinBillNO = '" + FBillNo + "' where io_id = '" + io_id + "'");
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {                                       
                                        throw;
                                    }                                   
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    #endregion
                }
            }

        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public bool Login()
        {
            string dbid = Common.dbid;
            string username = Common.username;
            string password = Common.password;
            var loginResult = client.Login(
                               dbid,
                               username,
                               password,
                               2052);
            return loginResult;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="formid"></param>
        /// <param name="jsonstr"></param>
        /// <returns></returns>
        public string Save(string formid, string jsonstr)
        {
            string result = "登录失败,请检查与站点地址、数据中心Id,用户名及密码!";
            //string result = "";
            if (Login())
            {
                result = client.Execute<string>(
                                               "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save",
                                               new object[] { formid, jsonstr });
            }
            return result;
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="formid"></param>
        /// <param name="jsonstr"></param>
        /// <returns></returns>
        public string Audit(string formid, string jsonstr)
        {
            string result = "登录失败,请检查与站点地址、数据中心Id,用户名及密码!";
            result = client.Execute<string>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit", new object[] { formid, jsonstr });
            result = client.Execute<string>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit", new object[] { formid, jsonstr });
            return result;
        }
    }
}

原文地址:https://www.cnblogs.com/zfangfang/p/12079738.html