C# 金蝶WEB API

**PS.
金蝶的DLL大家只能自己找资源了~博客不能发发这些;
至于代码上我写了很多注释,主要是方便接手的人看,嫌注释累赘的自行删减吧,或者cs编辑区右键→【大纲显示】→【折叠到定义】即可~
这里批量查询函数ExecuteBillQuery返回结果我包装成【字典】,各位可以按需修改为其他形式的对象结果集
在这里插入图片描述

引用参考

在这里插入图片描述

using JD_FXSynTool.Entity;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web.Script.Serialization;

工具类

    /// /// 金蝶接口/// 数据字典(详见辅助资料列表)/// public static class JD_Helper{/// /// Json.net 序列化工具/// private readonly static JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };/// /// 查询数上限/// public const int QueryLimitSum = 2000;/// /// 客户业务对象表单Id/// public const string BD_Customer = "BD_Customer";/// /// 销售出库单对象表单Id/// public const string SAL_OUTSTOCK = "SAL_OUTSTOCK";/// /// 销售单对象表单Id/// public const string SAL_SaleOrder = "SAL_SaleOrder";/// /// 物料对象表单Id/// public const string BD_MATERIAL = "BD_MATERIAL";/// /// 销售报价单对象表单Id/// public const string SAL_QUOTATION = "SAL_QUOTATION";/// /// 账套id/// private readonly static string JD_accountBookId = SettingHelper.GetString("JD_accountBookId");/// /// 是否处于暂停状态/// public static bool isPause = false;/// /// 系统【辅助属性】分类信息/// public static ConcurrentDictionary<string, string> assistantDatas = new ConcurrentDictionary<string, string>();/// /// 系统【客户分组】分类信息/// public static ConcurrentDictionary<string, string> FGroups = new ConcurrentDictionary<string, string>();/// /// 系统【辅助属性】信息/// public static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> assistantDataDetails = new ConcurrentDictionary<string, ConcurrentDictionary<string, string>>();/// /// 金蝶客户端对象/// public static readonly K3CloudApiClient client = new K3CloudApiClient(SettingHelper.GetString("JD_CloudUrl"));/// /// 金蝶获取对象属性键值对对象范围/// public static readonly List<string> jd_ObjectDataApiNames = new List<string>{"BD_RecCondition",// 收款条件};/// /// 登录校验/// 正常用例返回:/// {///  "Message": null,///  "MessageCode": "CheckPasswordPolicy",///  "LoginResultType": 1,                                     // 登录成功Success = 1///  "Context": {///    "UserLocale": "zh-CN",///    "LogLocale": "",///    "DBid": ".......",///    "DatabaseType": 3,///    "SessionId": ".......",///    "UseLanguages": [///      {///        "LocaleId": 2052,///        "LocaleName": "中文(简体/中国)",///        "Alias": "CN"///      }///    ],///    "UserId": 447411,///    "UserName": "XXX",///    "CustomName": "XXX有限公司",///    "DisplayVersion": "...",///    "DataCenterName": "888",///    "UserToken": "...",///    "CurrentOrganizationInfo": {///      "ID": ..,///      "AcctOrgType": "1",///      "Name": "......",///      "FunctionIds": [///        101,///        102,///        103,///        104,///        107,///        108,///        109,///        110,///        111,///        112,///        113///      ]///     },///    "IsCH_ZH_AutoTrans": false,///    "ClientType": 1,///    "WeiboAuthInfo": {///      "WeiboUrl": null,///      "NetWorkID": null,///      "CompanyNetworkID": null,///      "Account": " @",///      "AppKey": "......",///      "AppSecret": "......",///      "TokenKey": " ",///      "TokenSecret": " ",///      "Verify": null,///      "CallbackUrl": null,///      "UserId": " ",///      "Charset": {///        "BodyName": "utf-8",///        "EncodingName": "Unicode (UTF-8)",///        "HeaderName": "utf-8",///        "WebName": "utf-8",///        "WindowsCodePage": 1200,///        "IsBrowserDisplay": true,///        "IsBrowserSave": true,///        "IsMailNewsDisplay": true,///        "IsMailNewsSave": true,///        "IsSingleByte": false,///        "EncoderFallback": {///          "DefaultString": "?",///          "MaxCharCount": 1///        },///        "DecoderFallback": {///          "DefaultString": "?",///          "MaxCharCount": 1///        },///        "IsReadOnly": true,///        "CodePage": 65001///      }///    }///  },///  "KDSVCSessionId": null,///  "FormId": null,///  "RedirectFormParam": null,///  "FormInputObject": null,///  "ErrorStackTrace": null,///  "Lcid": 0,///  "AccessToken": null,///  "KdAccessResult": null,///  "IsSuccessByAPI": true///}/// /// 帐套Id/// 用户名称/// 用户密码/// 语言标识,默认简体中文/// public static JObject ValidateLogin(string username, string password, int lcid = 2052){if (string.IsNullOrWhiteSpace(username))throw new ArgumentException("【用户名称】不允许为空...", nameof(username));else if (string.IsNullOrWhiteSpace(password))throw new ArgumentException("【用户密码】不允许为空...", nameof(password));string apiInterfaceName = "批量保存对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);return JsonConvert.DeserializeObject<JObject>(client.ValidateLogin(JD_accountBookId, username, password, lcid));}#region 客户对象操作/// /// 查看客户/// 正常用例返回:/// {///  "Result": {///    "ResponseStatus": null,///    "Result": {///      "Id": 392916,///      "msterID": 392916,///      "DocumentStatus": "C",///      "ForbidStatus": "A",///      "MultiLanguageText": [///        {///          "PkId": ...,///          "LocaleId": ....,///          "Name": ".....有限公司",///          "Description": " ",///          "ShortName": " "///        }///      ],///      "Name": [///        {///          "Key": 2052,///          "Value": ".....有限公司"///        }///      ],///      "Number": "07.....",///      "Description": [///        {///          "Key": 2052,///          "Value": " "///        }///      ],///      "CreateOrgId_Id": 1,///      "CreateOrgId": {///        "Id": 1,///        "MultiLanguageText": [///          {///            "PkId": 1,///            "LocaleId": 2052,///            "Name": ".....股份公司"///          },///          {///            "PkId": 100001,///            "LocaleId": 1033,///            "Name": " "///          },///          {///            "PkId": 100002,///            "LocaleId": 3076,///            "Name": " "///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": ".....股份公司"///          },///          {///            "Key": 1033,///            "Value": " "///          },///          {///            "Key": 3076,///            "Value": " "///          }///        ],///        "Number": "100"///      },///      "UseOrgId_Id": 1,///      "UseOrgId": {///        "Id": 1,///        "MultiLanguageText": [///          {///            "PkId": 1,///            "LocaleId": 2052,///            "Name": ".....股份公司"///          },///          {///            "PkId": 100001,///            "LocaleId": 1033,///            "Name": " "///          },///          {///            "PkId": 100002,///            "LocaleId": 3076,///            "Name": " "///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "....股份公司"///          },///          {///            "Key": 1033,///            "Value": " "///          },///          {///            "Key": 3076,///            "Value": " "///          }///        ],///        "Number": "100"///      },///      "CreatorId_Id": 126076,///      "CreatorId": {///        "Id": 126076,///        "Name": "实施顾问",///        "UserAccount": "99999"///      },///      "ModifierId_Id": 292562,///      "ModifierId": {///        "Id": 292562,///        "Name": "......",///        "UserAccount": " "///      },///      "CreateDate": "2018-04-10T13:13:15.703",///      "FModifyDate": "2018-08-03T14:57:52.307",///      "ShortName": [///        {///          "Key": 2052,///          "Value": " "///        }///      ],///      "COUNTRY_Id": "46a524cf-5797-4e46-bd0a-7203fc426d9c",///      "COUNTRY": {///        "Id": "46a524cf-5797-4e46-bd0a-7203fc426d9c",///        "FNumber": "CHN",///        "MultiLanguageText": [///          {///            "PkId": "1001",///            "LocaleId": 2052,///            "FDataValue": "中国"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "中国"///          }///        ]///      },///      "PROVINCIAL_Id": " ",///      "PROVINCIAL": null,///      "FZIP": " ",///      "TEL": "0769-82636346",///      "FTAXREGISTERCODE": " ",///      "FAX": "0769-82636349",///      "FGROUPCUSTID_Id": 0,///      "FGROUPCUSTID": null,///      "FSUPPLIERID_Id": 0,///      "FSUPPLIERID": null,///      "TRADINGCURRID_Id": 1,///      "TRADINGCURRID": {///        "Id": 1,///        "msterID": 1,///        "MultiLanguageText": [///          {///            "PkId": 2,///            "LocaleId": 2052,///            "Name": "人民币"///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "人民币"///          }///        ],///        "Number": "PRE001",///        "Sysmbol": "¥",///        "PriceDigits": 6,///        "AmountDigits": 2,///        "IsShowCSymbol": true,///        "FormatOrder": "1",///        "RoundType": "1"///      },///      "SALDEPTID_Id": 402587,///      "SALDEPTID": {///        "Id": 402587,///        "msterID": 402587,///        "MultiLanguageText": [///          {///            "PkId": 101264,///            "LocaleId": 2052,///            "Name": "营销二部"///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "营销二部"///          }///        ],///        "Number": "014.002"///      },///      "SALGROUPID_Id": 0,///      "SALGROUPID": null,///      "SELLER_Id": 402629,///      "SELLER": {///        "Id": 402629,///        "msterID": 402629,///        "MultiLanguageText": [///          {///            "PkId": 100471,///            "LocaleId": 2052,///            "Name": "....."///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "......."///          }///        ],///        "Number": "EMP0055",///        "DeptId_Id": 402587,///        "DeptId": {///          "Id": 402587,///          "msterID": 402587,///          "Number": "014.002",///          "MultiLanguageText": [///            {///              "PkId": 101264,///              "LocaleId": 2052,///              "Name": "营销二部"///            }///          ],///          "Name": [///            {///              "Key": 2052,///              "Value": "营销二部"///            }///          ]///        },///        "STAFFID": "402618",///        "BD_SALESMANENTRY": []///      },///      "TRANSLEADTIME": 0,///      "PRICELISTID_Id": 0,///      "PRICELISTID": null,///      "DISCOUNTLISTID_Id": 0,///      "DISCOUNTLISTID": null,///      "SETTLETYPEID_Id": 0,///      "SETTLETYPEID": null,///      "RECEIVECURRID_Id": 0,///      "RECEIVECURRID": null,///      "RECCONDITIONID_Id": 353452,///      "RECCONDITIONID": {///        "Id": 353452,///        "MultiLanguageText": [///          {///            "PkId": 100014,///            "LocaleId": 2052,///            "Name": "赊销105天"///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "赊销105天"///          }///        ],///        "Number": "012"///      },///      "FISCREDITCHECK": false,///      "APPROVERID_Id": 324385,///      "APPROVERID": {///        "Id": 324385,///        "Name": "......",///        "UserAccount": " "///      },///      "APPROVEDATE": "2018-08-03T14:44:03.853",///      "FORBIDDERID_Id": 0,///      "FORBIDDERID": null,///      "FORBIDDATE": null,///      "TaxType_Id": "9e855eb97bec43e7b50c3e0e0bf51210",///      "TaxType": {///        "Id": "9e855eb97bec43e7b50c3e0e0bf51210",///        "FNumber": "SFL02_SYS",///        "MultiLanguageText": [///          {///            "PkId": "7841e26e9e5a4fe6a83e7cdbe0c24175",///            "LocaleId": 2052,///            "FDataValue": "一般纳税人"///          },///          {///            "PkId": "2942b840514242b299738f8b9bbe2095",///            "LocaleId": 3076,///            "FDataValue": "一般納稅人"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "一般纳税人"///          },///          {///            "Key": 3076,///            "Value": "一般納稅人"///          }///        ]///      },///      "CustTypeId_Id": "673cb7c55ea24626ae639ff2ec5adf0e",///      "CustTypeId": {///        "Id": "673cb7c55ea24626ae639ff2ec5adf0e",///        "FNumber": "KHLB001_SYS",///        "MultiLanguageText": [///          {///            "PkId": "8b45c5f776054f59a89f1f71854a9d88",///            "LocaleId": 2052,///            "FDataValue": "普通销售客户"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "普通销售客户"///          }///        ]///      },///      "ADDRESS": "..........",///      "WEBSITE": " ",///      "FGroup_Id": 392892,///      "FGroup": {///        "Id": 392892,///        "Number": "07",///        "MultiLanguageText": [///          {///            "PkId": 100044,///            "LocaleId": 2052,///            "Name": "磁业"///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "磁业"///          }///        ]///      },///      "CompanyScale_Id": " ",///      "CompanyScale": null,///      "CompanyType_Id": " ",///      "CompanyType": null,///      "CompanyNature_Id": " ",///      "CompanyNature": null,///      "CorrespondOrgId_Id": 0,///      "CorrespondOrgId": null,///      "Priority": 1,///      "InvoiceType": "1",///      "TaxRate_Id": 233,///      "TaxRate": {///        "Id": 233,///        "msterID": 233,///        "MultiLanguageText": [///          {///            "PkId": 10019,///            "LocaleId": 2052,///            "Name": "16%增值税"///          }///        ],///        "Name": [///          {///            "Key": 2052,///            "Value": "16%增值税"///          }///        ],///        "Number": "SL01_SYS"///      },///      "IsDefPayer": false,///      "CPAdminCode": " ",///      "IsGroup": false,///      "IsTrade": true,///      "TPEnName": " ",///      "TPCorporater": " ",///      "CusBelonngDepId_Id": 0,///      "CusBelonngDepId": null,///      "Code": " ",///      "TheGroup": " ",///      "CUSTTYPE_Id": "...",///      "CUSTTYPE": {///        "Id": "..",///        "FNumber": "CustType_09",///        "MultiLanguageText": [///          {///            "PkId": "....",///            "LocaleId": 2052,///            "FDataValue": "直接客户"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "直接客户"///          }///        ]///      },///      "CustProperty_Id": " ",///      "CustProperty": null,///      "F_JDS_DateDeclareLately": null,///      "Fspecialcust_Id": " ",///      "Fspecialcust": null,///      "F_JDS_QSXSBase_Id": 0,///      "F_JDS_QSXSBase": null,///      "F_JDS_ZHYDate": null,///      "F_JDS_FSELLER1_Id": 0,///      "F_JDS_FSELLER1": null,///      "F_JDS_FXDJ_Id": "...",///      "F_JDS_FXDJ": {///        "Id": "..",///        "FNumber": "FXDJ02",///        "MultiLanguageText": [///          {///            "PkId": "..",///            "LocaleId": 2052,///            "FDataValue": "B"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "B"///          }///        ]///      },///      "F_JDS_QSFXDJ_Id": "...",///      "F_JDS_QSFXDJ": {///        "Id": "...",///        "FNumber": "FXDJ02",///        "MultiLanguageText": [///          {///            "PkId": "...",///            "LocaleId": 2052,///            "FDataValue": "B"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "B"///          }///        ]///      },///      "F_JDS_PMFXDJ_Id": "...",///      "F_JDS_PMFXDJ": {///        "Id": "..",///        "FNumber": "...",///        "MultiLanguageText": [///          {///            "PkId": "...",///            "LocaleId": 2052,///            "FDataValue": "A"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "A"///          }///        ]///      },///      "F_JDS_CYFXDJ_Id": "...",///      "F_JDS_CYFXDJ": {///        "Id": "...",///        "FNumber": "FXDJ02",///        "MultiLanguageText": [///          {///            "PkId": "...",///            "LocaleId": 2052,///            "FDataValue": "B"///          }///        ],///        "FDataValue": [///          {///            "Key": 2052,///            "Value": "B"///          }///        ]///      },///      "BD_CUSTLOCATION": [],///      "BD_CUSTBANK": [///        {///          "Id": 0,///          "BANKCODE": null,///          "CURRENCYID_Id": 0,///          "CURRENCYID": null,///          "ACCOUNTNAME": null,///          "ISDEFAULT": false,///          "COUNTRY_Id": "",///          "COUNTRY": null,///          "MultiLanguageText": [],///          "OPENBANKNAME": [],///          "BankTypeRec_Id": 0,///          "BankTypeRec": null,///          "OpenAddressRec": null,///          "CNAPS": null,///          "TPName": null,///          "TPPhone": null///        }///      ],///      "BD_CUSTCONTACT": [],///      "BD_CUSTORDERORG": [///        {///          "Id": 0,///          "OrderOrgId_Id": 0,///          "OrderOrgId": null,///          "ISDEFAULT": true///        }///      ],///      "BD_CUSTOMEREXT": [///        {///          "Id": 110145,///          "EnableSL": false,///          "FreezeStatus": "A",///          "FreezeLimit": " ",///          "FreezeOperator_Id": 0,///          "FreezeOperator": null,///          "FreezeDate": null,///          "PROVINCE_Id": " ",///          "PROVINCE": null,///          "CITY_Id": " ",///          "CITY": null,///          "DefaultConsiLoc_Id": 0,///          "DefaultConsiLoc": null,///          "DefaultSettleLoc_Id": 0,///          "DefaultSettleLoc": null,///          "DefaultPayerLoc_Id": 0,///          "DefaultPayerLoc": null,///          "DefaultContact_Id": 0,///          "DefaultContact": null///        }///      ],///      "TP_FBD_CusCredit": [///        {///          "Id": 0,///          "Seq": 1,///          "TPTradePropertyId_Id": 0,///          "TPTradePropertyId": null,///          "TPCreditRank_Id": 0,///          "TPCreditRank": null,///          "TPCurrencyId_Id": 7,///          "TPCurrencyId": {///            "Id": 7,///            "msterID": 7,///            "MultiLanguageText": [///              {///                "PkId": 20,///                "LocaleId": 2052,///                "Name": "美元"///              }///            ],///            "Name": [///              {///                "Key": 2052,///                "Value": "美元"///              }///            ],///            "Number": "PRE007",///            "Sysmbol": "$",///            "PriceDigits": 6,///            "AmountDigits": 2,///            "IsShowCSymbol": true,///            "FormatOrder": "1",///            "RoundType": "1"///          },///          "TPCreditAmt": 0.0,///          "CreAmt": 0.0,///          "TPIsUsed": true,///          "TPStartDate": "2020-03-24T00:00:00",///          "TPStopDate": null,///          "TPUseStyle": "1",///          "TPActDate": 0,///          "TPCreditContent": null///        }///      ]///    }///  }///}/// /// 单据编号/// 表的主键Id/// 创建者组织,字符串类型/// public static JObject CustomerView(string Number, string Id, string CreateOrgId = null){return View(BD_Customer, Number, Id, CreateOrgId);}/// /// 保存(新增&修改)客户信息/// /// /// public static JObject CustomerSave(SaveJson saveCustomer){if (saveCustomer == null || saveCustomer.Model == null || !(saveCustomer.Model is SaveCustomerModel saveCustomerModel))throw new ArgumentException("【saveCustomer.Model】必须为非空SaveCustomerModel类型...", nameof(saveCustomer));else if (string.IsNullOrWhiteSpace(saveCustomerModel.FName))throw new ArgumentException("【saveCustomer.Model.FName】内容不允许为空...", nameof(saveCustomer));FCreateOrgId FCreateOrgId = saveCustomerModel.FCreateOrgId;if (FCreateOrgId == null || string.IsNullOrWhiteSpace(FCreateOrgId.FNumber))throw new ArgumentException("【saveCustomer.Model.FCreateOrgId】内容不允许为空...", nameof(saveCustomer));return Save(saveCustomer, BD_Customer);}/// /// 批量保存(新增&修改)客户信息/// /// /// public static JObject CustomerBatchSave(BatchSaveJson savesCustomer){if (savesCustomer == null || savesCustomer.Model == null || !savesCustomer.Model.Any())throw new ArgumentException("【savesCustomer.Model】及其内容不允许为空...", nameof(savesCustomer));savesCustomer.Model.ForEach((model) =>{if (!(model is SaveCustomerModel saveCustomerModel))throw new ArgumentException("【savesCustomer.Model】元素必须为SaveCustomerModel类型...", nameof(savesCustomer));else if (string.IsNullOrWhiteSpace(saveCustomerModel.FName))throw new ArgumentException("【saveCustomer.Model[?].FName】内容不允许为空...", nameof(savesCustomer));FCreateOrgId FCreateOrgId = saveCustomerModel.FCreateOrgId;if (FCreateOrgId == null || string.IsNullOrWhiteSpace(FCreateOrgId.FNumber))throw new ArgumentException("【saveCustomer.Model[?].FCreateOrgId】内容不允许为空...", nameof(savesCustomer));});return BatchSave(savesCustomer, BD_Customer);}/// /// 删除客户信息/// /// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// public static JObject CustomerDelete(string[] Numbers, string Ids, string CreateOrgId = null){return Delete(BD_Customer, Numbers, Ids, CreateOrgId);}#endregion#region 获取辅助属性/// /// 根据辅助属性分类FNumber/// /// 金蝶中辅助属性分类的中文名称/// public static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> GetAssistantDataDetails(string[] assistantDataNames){if (assistantDataNames == null || assistantDataNames.Length == 0)return null;string filterString = "FNAME IN (";foreach (string assistantDataName in assistantDataNames)filterString += assistantDataName + ",";filterString.TrimEnd(',');filterString += " )";List<Dictionary<string, string>> assistantDatas = ExecuteBillQuery("BOS_ASSISTANTDATA", "FNumber,FNAME", filterString);if (assistantDatas == null || assistantDatas.Count == 0)return null;filterString = "FID.FNumber IN (";foreach (Dictionary<string, string> assistantData in assistantDatas)filterString += assistantData["FNumber"] + ",";filterString.TrimEnd(',');filterString += " )";List<Dictionary<string, string>> assistantDataDetails = ExecuteBillQuery("BOS_ASSISTANTDATA_DETAIL", "FDataValue,FNumber,FID.FNumber", filterString);ConcurrentDictionary<string, ConcurrentDictionary<string, string>> result = new ConcurrentDictionary<string, ConcurrentDictionary<string, string>>();foreach (Dictionary<string, string> assistantDataDetail in assistantDataDetails){if (assistantDataDetail["FID.FNumber"] != null){if (result.ContainsKey(assistantDataDetail["FID.FNumber"]))result[assistantDataDetail["FID.FNumber"]].AddOrUpdate(GetValue(assistantDataDetail["FDataValue"]), assistantDataDetail["FNumber"], (key, val) => { return assistantDataDetail["FNumber"]; });else// 首次添加{ConcurrentDictionary<string, string> assistantData = new ConcurrentDictionary<string, string>();assistantData.TryAdd(GetValue(assistantDataDetail["FDataValue"]), assistantDataDetail["FNumber"]);result.TryAdd(assistantDataDetail["FID.FNumber"], assistantData);}}}return result;}/// /// 获取所有辅助属性/// /// 金蝶中辅助属性分类的中文名称/// public static void GetAllAssistantDataDetails(){assistantDatas.Clear();// 刷新辅助属性分类列表assistantDataDetails.Clear();// 刷新辅助属性明细键值对List<Dictionary<string, string>> assistantDataList = ExecuteBillQuery("BOS_ASSISTANTDATA", "FNUMBER,FNAME");foreach (Dictionary<string, string> assistantData in assistantDataList)assistantDatas.TryAdd(assistantData["FNUMBER"], assistantData["FNAME"]);List<Dictionary<string, string>> assistantDataDetailsList = ExecuteBillQuery("BOS_ASSISTANTDATA_DETAIL","FDataValue," +// 明细中文名称"FNumber," +// 明细编码"FID.FNumber,FID," +// 主选项标识"");assistantDataDetails.TryAdd("", new ConcurrentDictionary<string, string>());foreach (Dictionary<string, string> assistantDataDetail in assistantDataDetailsList){if (string.IsNullOrWhiteSpace(assistantDataDetail["FID.FNumber"]))assistantDataDetails[""].TryAdd(assistantDataDetail["FDataValue"], assistantDataDetail["FNumber"]);// 有些键值对没有FNumber,FIDelse if (assistantDataDetails.ContainsKey(assistantDataDetail["FID.FNumber"]))assistantDataDetails[assistantDataDetail["FID.FNumber"]].AddOrUpdate(assistantDataDetail["FDataValue"], assistantDataDetail["FNumber"], (key, val) => { return assistantDataDetail["FNumber"]; });else// 首次添加{ConcurrentDictionary<string, string> assistantData = new ConcurrentDictionary<string, string>();assistantData.TryAdd(assistantDataDetail["FDataValue"], assistantDataDetail["FNumber"]);assistantDataDetails.TryAdd(assistantDataDetail["FID.FNumber"], assistantData);LogHelper.logger.Debug("已获取金蝶辅助属性【" + assistantDatas[assistantDataDetail["FID.FNumber"]] + ":" + assistantDataDetail["FID.FNumber"] + "】");}}#region 对象属性foreach (string jd_apiName in jd_ObjectDataApiNames){List<Dictionary<string, string>> dataList = ExecuteBillQuery(jd_apiName, "FName,FNumber");ConcurrentDictionary<string, string> datas = new ConcurrentDictionary<string, string>();foreach (Dictionary<string, string> data in dataList)datas.TryAdd(data["FName"], data["FNumber"]);assistantDataDetails.TryAdd("BD_RecCondition", datas);LogHelper.logger.Debug("已获取金蝶对象属性【" + jd_apiName + "】");}#endregion}/// /// 获取所有客户分组/// public static void GetFGroups(){FGroups.Clear();FGroups.TryAdd("国内", "01");FGroups.TryAdd("出口", "02");FGroups.TryAdd("内部", "03");FGroups.TryAdd("外部", "04");FGroups.TryAdd("高明", "05");FGroups.TryAdd("特陶", "06");FGroups.TryAdd("磁业", "07");FGroups.TryAdd("其他", "09");FGroups.TryAdd("展厅客户", "10");FGroups.TryAdd("测试组", "99");}/// /// 获取所有客户分组/// public static string GetFGroupFNumber(string fname){return FGroups[fname];}/// /// 获取金蝶辅助属性值/// /// public static string GetAssistantDataDetailValue(string assistantDataDetailName, string assistantDataName = null){if (string.IsNullOrEmpty(assistantDataDetailName)) return null;if (assistantDataName == null || !assistantDataDetails.ContainsKey(assistantDataName)) // 对于唯一的属性名称可以不传属性分类FNumer{Dictionary<string, string> results = new Dictionary<string, string>();foreach (KeyValuePair<string, ConcurrentDictionary<string, string>> assistantDataDetail in assistantDataDetails)if (assistantDataDetail.Value.ContainsKey(assistantDataDetailName))results.Add(assistantDataDetail.Key, assistantDataDetail.Value[assistantDataDetailName]);if (results.Count == 1)return results.Values.First();else{string selectNames = "";foreach (KeyValuePair<string, string> result in results)selectNames += result + "/";string errorMsg = "属性名称【" + assistantDataDetailName + "】在金蝶辅助属性中有同名值不存在或不唯一,请添加下列属性分类名称之一作为补充参数【" + selectNames + "】";LogHelper.logger.Error(errorMsg);LogHelper.SendMsg(errorMsg);return null;}}else if (assistantDataDetails[assistantDataName].ContainsKey(assistantDataDetailName))return assistantDataDetails[assistantDataName][assistantDataDetailName];else{string options = "";foreach (KeyValuePair<string, string> keyValuePair in assistantDataDetails[assistantDataName]){options += keyValuePair.Key + " ";}string errorMsg = "金蝶辅助属性【" + assistantDataName + "】编码表【" + options + "】中不含【" + assistantDataDetailName + "】";LogHelper.logger.Error(errorMsg);LogHelper.SendMsg(errorMsg);return null;}}#endregion#region 基础对象操作/// /// 删除对象信息/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false", // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		}///	}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject Delete(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "删除" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.Delete(formid, JavaScriptSerializer.Serialize(jsonObj)));}/// /// 保存对象信息/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false", // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		},///		"Id": "",///		"NeedReturnData": [{}]///	}///}/// /// 业务对象表单Id/// /// public static JObject Save(SaveJson saveJson, string formid){string apiInterfaceName = "保存" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);return JsonConvert.DeserializeObject<JObject>(client.Save(formid, JavaScriptSerializer.Serialize(saveJson)));}/// /// 批量保存对象信息/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false", // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		},///		"NeedReturnData": [{}]///	}///}/// /// 业务对象表单Id/// /// public static JObject BatchSave(BatchSaveJson savesJson, string formid){string apiInterfaceName = "批量保存" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);return JsonConvert.DeserializeObject<JObject>(client.BatchSave(formid, JavaScriptSerializer.Serialize(savesJson)));}/// /// 查看对象信息/// {///     "Result":///         {///             "ResponseStatus":"",///             "Result":"{}"///         }/// }/// /// 业务对象表单Id/// 单据编号/// 表的主键Id/// 创建者组织,字符串类型/// public static JObject View(string formid, string Number, string Id, string CreateOrgId = null){string apiInterfaceName = "查看" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);if (string.IsNullOrWhiteSpace(formid))throw new ArgumentException("【业务对象表单Id】不允许为空...", nameof(formid));else if (string.IsNullOrWhiteSpace(Number) && string.IsNullOrWhiteSpace(Id))throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Number));object jsonObj = new { CreateOrgId, Number, Id };return JsonConvert.DeserializeObject<JObject>(client.View(formid, JavaScriptSerializer.Serialize(jsonObj)));}/// /// 提交对象信息/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false",  // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		}///	}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject Submit(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "提交" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.Submit(formid, JavaScriptSerializer.Serialize(jsonObj)));}/// /// 审核对象信息/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false", // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		}///	}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject Audit(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "审核" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.Audit(formid, JavaScriptSerializer.Serialize(jsonObj)));}/// /// 反审核对象信息(返回【未审核】)/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false", // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		}///	}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject UnAudit(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "反审核" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.UnAudit(formid, JavaScriptSerializer.Serialize(jsonObj)));}/// /// 禁用对象信息/// {///"Result": {///	"ResponseStatus": {///		"ErrorCode": "",///		"IsSuccess": "false", // 是否成功///		"Errors": [{///			"FieldName": "",///			"Message": "",///			"DIndex": 0///           }],///		"SuccessEntitys": [{///			"Id": "",///			"Number": "",///			"DIndex": 0///           }],///		"SuccessMessages": [{///			"FieldName": "",///			"Message": "",///			"DIndex": 0///		}]///	}///}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject Forbid(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "禁用" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.ExcuteOperation(formid, "Forbid", JavaScriptSerializer.Serialize(jsonObj)));}/// /// 反禁用(启用)对象信息/// {///"Result": {///	"ResponseStatus": {///		"ErrorCode": "",///		"IsSuccess": "false", // 是否成功///		"Errors": [{///			"FieldName": "",///			"Message": "",///			"DIndex": 0///           }],///		"SuccessEntitys": [{///			"Id": "",///			"Number": "",///			"DIndex": 0///           }],///		"SuccessMessages": [{///			"FieldName": "",///			"Message": "",///			"DIndex": 0///		}]///	}///}///}/// /// 业务对象表单Id/// 单据编号集合,数组类型,格式["billNo1","billNo1",...]/// 表的主键Id,字符串类型,格式"Id1,Id2,..."/// 创建者组织,字符串类型/// private static JObject Enable(string formid, string[] Numbers, string Ids, string CreateOrgId = null){string apiInterfaceName = "启用/反禁用" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] idArray = Ids.Split(',');if ((!idArray.Any() || idArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))&& (!Numbers.Any() || Numbers.Any((number) => { return string.IsNullOrWhiteSpace(number); }))){throw new ArgumentException("【表的主键Id】或【单据编号】其中之一不允许为空...", nameof(Numbers));}object jsonObj = new { CreateOrgId, Numbers, Ids };return JsonConvert.DeserializeObject<JObject>(client.ExcuteOperation(formid, "Enable", JavaScriptSerializer.Serialize(jsonObj)));}/// /// 查询单据信息(列表查询)/// [{///	"fieldKey1": "fieldValue1",///	"fieldKey2": "fieldValue2",///	...///}, {///	"fieldKey21": "fieldValue21",///	"fieldKey22": "fieldValue22",///	...///}, ...]/// /// 业务对象表单Id/// 字段keys,字符串类型用逗号分隔,比如"key1,key2..."/// 最大行数,不能超过2000/// 开始行/// 总行数/// 过滤/// 排序字段/// public static List<List<object>> ExecuteBillQuery2(string FormId, string FieldKeys, int Limit, int StartRow = 0, int TopRowCount = 0, string FilterString = null, string OrderString = null){string apiInterfaceName = "查询" + FormId + "单据信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] keyArray = FieldKeys.Trim().TrimEnd(',').Split(',');if (!keyArray.Any() || keyArray.Any((key) => { return string.IsNullOrWhiteSpace(key); }))throw new ArgumentException("【字段keys】不允许为空...", nameof(FieldKeys));else if (TopRowCount < 0)throw new ArgumentException("【总行数】不允许小于0...", nameof(TopRowCount));else if (StartRow < 0)throw new ArgumentException("【开始行】不允许小于0...", nameof(StartRow));else if (Limit < 0 || Limit > QueryLimitSum)throw new ArgumentException("【最大行数】不允许小于0或大于"+ QueryLimitSum + "...", nameof(Limit));object jsonObj = new { FormId, FieldKeys, FilterString, OrderString, TopRowCount, StartRow, Limit };return client.ExecuteBillQuery(JavaScriptSerializer.Serialize(jsonObj));}/// /// 查询单据信息(列表查询)/// [{///	"fieldKey1": "fieldValue1",///	"fieldKey2": "fieldValue2",///	...///}, {///	"fieldKey21": "fieldValue21",///	"fieldKey22": "fieldValue22",///	...///}, ...]/// /// 业务对象表单Id/// 字段keys,字符串类型用逗号分隔,比如"key1,key2..."/// 过滤/// 排序字段/// public static List<List<object>> ExecuteBillQuery0(string FormId, string FieldKeys, string FilterString = null, string OrderString = null){List<List<object>> newList;List<List<object>> resultList = new List<List<object>>();int startRow = 0;do{newList = ExecuteBillQuery2(FormId, FieldKeys, QueryLimitSum, startRow, 0, FilterString, OrderString);resultList.AddRange(newList);startRow += QueryLimitSum;} while (newList.Count == QueryLimitSum);return resultList;}/// /// 查询单据信息(列表查询)/// [{///	"fieldKey1": "fieldValue1",///	"fieldKey2": "fieldValue2",///	...///}, {///	"fieldKey21": "fieldValue21",///	"fieldKey22": "fieldValue22",///	...///}, ...]/// /// 业务对象表单Id/// 字段keys,字符串类型用逗号分隔,比如"key1,key2..."/// 过滤/// 排序字段/// public static List<Dictionary<string, string>> ExecuteBillQuery(string FormId, string FieldKeys, string FilterString = null, string OrderString = null){List<List<object>> newList;// 单轮检索结果List<List<object>> resultList = new List<List<object>>();// 总结果int startRow = 0;do{newList = ExecuteBillQuery2(FormId, FieldKeys, QueryLimitSum, startRow, 0, FilterString, OrderString);resultList.AddRange(newList);startRow += QueryLimitSum;} while (newList.Count == QueryLimitSum);List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();string[] fieldKeys = FieldKeys.Replace(" ","").TrimEnd(',').Split(',');foreach (List<object> objs in resultList){Dictionary<string, string> fieldName_obj = new Dictionary<string, string>();for (int i = 0; i < fieldKeys.Length; i++)fieldName_obj.Add(fieldKeys[i], GetValue(objs[i]));results.Add(fieldName_obj);}return results;}/// /// 分配对象信息/// N个组织同用一份对象,实际生成N个对象,其中一个对象修改时修改内容会同步到其他分配对象/// {///	"Result": {///		"ResponseStatus": {///			"ErrorCode": "",///			"IsSuccess": "false",  // 是否成功///			"Errors": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///            }],///			"SuccessEntitys": [{///				"Id": "",///				"Number": "",///				"DIndex": 0///            }],///			"SuccessMessages": [{///				"FieldName": "",///				"Message": "",///				"DIndex": 0///			}]///		}///	}///}/// /// 业务对象表单Id/// 目标组织Id集合,格式["billNo1","billNo1",...]/// 被分配的单据主键集合,格式"Id1,Id2,..."/// 分配后是否自动提交与审核/// private static JObject Allocate(string formid, string TOrgIds, string PkIds, string IsAutoSubmitAndAudit = "false"){string apiInterfaceName = "分配" + formid + "对象信息";LogHelper.logger.Info("开始调用金蝶【" + apiInterfaceName + "】接口...");WaitForPause(apiInterfaceName);string[] PkIdArray = PkIds.Split(',');if (!PkIdArray.Any() || PkIdArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))throw new ArgumentException("【被分配的单据主键集合】及其内容不允许为空...", nameof(PkIds));string[] TOrgIdArray = TOrgIds.Split(',');if (!TOrgIdArray.Any() || TOrgIdArray.Any((id) => { return string.IsNullOrWhiteSpace(id); }))throw new ArgumentException("【目标组织Id集合】及其内容不允许为空...", nameof(TOrgIds));IsAutoSubmitAndAudit = IsAutoSubmitAndAudit.Equals("true", StringComparison.OrdinalIgnoreCase) ? "true" : "false";object jsonObj = new { IsAutoSubmitAndAudit, TOrgIds, PkIds };return JsonConvert.DeserializeObject<JObject>(client.Allocate(formid, JavaScriptSerializer.Serialize(jsonObj)));}#endregion/// /// 获取属性值的字符串形式/// /// 对象值/// public static string GetValue(object obj){if (obj == null)return null;return StringHelper.RemoveDoubleQuotes(obj.ToString());}/// /// 暂停等待/// public static void WaitForPause(string apiInterfaceName){bool hasPause = isPause;if (isPause)LogHelper.logger.Info("已暂停访问【" + apiInterfaceName + "】接口...");while (isPause)Thread.Sleep(500);if (hasPause)LogHelper.logger.Info("即将继续访问【" + apiInterfaceName + "】接口...");}}

特化对象BatchSaveJson

这个对象不是纯手打的,是我在https://www.bejson.com/convert/json2csharp/结合API文档生成的,由于涉及业务所以这里就不公开内容了;


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部