公司自动开始用钉钉后,企业的相关信息化软件开始使用钉钉上的应用程序。与销售公司相关的就是CRM系统。
CRM系统中客户是私人的,如果想多个人同时负责,需要添加客户负责人。由于公司的特殊性质,客户特别多,经常会有人要求增加客户负责人。每天都有几个小时在做这样的工作。钉钉消息、添加负责人,太繁琐了。
学以致用,开发个工具自动化处理任务。
闲话少说,开干。
设计思路
- 确认CRM是否有自动添加客户负责人的接口
- 确认钉钉的审批接口是否可以使用
- 确认接口数据都能拿到后,后台写个服务即可。
CRM系统分配用户
1、采集客户信息
分配客户负责人是通过客户的dataid来处理的,首先需要采集客户信息。幸好以前有定时服务采集客户信息。跳过
2、分配客户负责人接口
客户负责人分配才是这次的自动化处理的关键,通过查看CRM的API接口。可以实现,按照下面的代码执行即可。
public static void ReqDistributionCustomer(string datatids,string distributionUserIds, string userid, string corpid, string token, Action<string> SuccessCallback = null, Action<string> FailCallback = null)
{
string url = "http://127.0.0.1/pro/v1/api/customer/distribution";
StringBuilder data = new StringBuilder(); data.Append($@"{{""corpid"":""{corpid}"",""dataIdList"":[{datatids}],""distributionUserIds"":[""{distributionUserIds}""],""subBusinessType"":101,""userId"":""{userid}""}}");
string sign = Common.sha256($"{data.ToString()}{token}").ToLower();
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/json";
req.Headers.Add("sign", sign);
req.ServicePoint.ConnectionLimit = int.MaxValue;
req.ServicePoint.Expect100Continue = false;
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] buffer = Encoding.UTF8.GetBytes(data.ToString());
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
}
req.BeginGetResponse(new AsyncCallback(RspDistributionCustomer), new object[] { req, datatids, userid, corpid, token, distributionUserIds, SuccessCallback, FailCallback });
}
private static void RspDistributionCustomer(IAsyncResult result)
{
object[] parms = result.AsyncState as object[];
string datatids = parms[1].ToString();
string userid = parms[2].ToString();
string corpid = parms[3].ToString();
string token = parms[4].ToString();
string distributionUserIds = parms[5].ToString();
HttpWebRequest req = parms[0] as HttpWebRequest;
Action<string> SuccessCallback = parms[6] as Action<string>;
Action<string> FailCallback = parms[7] as Action<string>;
using (HttpWebResponse rsp = req.EndGetResponse(result) as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string msg = "";
msg = reader.ReadToEnd();
var jsondata = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(msg);
if (!(bool)(jsondata.success))
{
if (FailCallback != null)
FailCallback(datatids);
}
else {
if (SuccessCallback != null)
SuccessCallback(datatids);
}
}
}
}
获取钉钉的审批信息
- 在钉钉上创建新审批,根据要求设置表单格式,支持多个客户同时添加相同的负责人。
- 为了防止随意添加客户负责人 增加了字段任意当前客户负责人,可以在系统中进行校验。 或者是 定期对所有客户的负责人进行校验,如果没有任何跟进、销售机会、合同信息可以主动删除该客户负责人。
- 关于附件,其实最好的办法是把客户放到附件里面,但是看了一下开放平台,后台开发文档,没有办法获取审批中的附件信息。【难过】,只好允许用户直接录入多个客户了
获取钉钉的审批记录
钉钉要求每次获取只能获取20条记录,如果想获取更多只能翻页获取。
其实关于钉钉的开放平台,讲解的还是很详细的,根据要求传参数即可。钉钉现在都是Java开发了,.NET还得自己写。
对于多年的.NET程序员大叔来说,这都不是事,轻松搞定.
public static void ReqDingProcess(string token, DateTime dt, Action<string> SuccessCallback, Action<string> FailCallback,int cursor=0)
{
string url = $"https://oapi.dingtalk.com/topapi/processinstance/listids?access_token={token}";
StringBuilder data = new StringBuilder();
data.Append($@"{{""process_code"":""{FzrProcessCode}"",""start_time"":{Common.ConvertDateTimeLong(dt)},""size"":20,""cursor"":{cursor}}}");
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36";
req.Accept = "application/json, text/plain, */*";
req.KeepAlive = true;
req.ContentType = "application/json;charset=UTF-8";
req.Headers.Add("X-Requested-With", "XMLHttpRequest");
req.ServicePoint.ConnectionLimit = int.MaxValue;
req.ServicePoint.Expect100Continue = false;
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] buffer = Encoding.UTF8.GetBytes(data.ToString());
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
}
req.BeginGetResponse(new AsyncCallback(RspDingProcess), new object[] { req, token, dt, SuccessCallback, FailCallback });
}
public static void RspDingProcess(IAsyncResult result)
{
object[] parms = result.AsyncState as object[];
string token = parms[1].ToString();
DateTime dt = DateTime.Parse(parms[2].ToString());
HttpWebRequest req = parms[0] as HttpWebRequest;
Action<string> SuccessCallback = parms[3] as Action<string>;
Action<string> FailCallback = parms[4] as Action<string>;
using (HttpWebResponse rsp = req.EndGetResponse(result) as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string msg = "";
msg = reader.ReadToEnd();
var jsondata = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(msg);
if (jsondata.result.next_cursor != null) {
int nextcursor =int.Parse( jsondata.result.next_cursor.ToString());
ReqDingProcess(token, dt, SuccessCallback, FailCallback, nextcursor);
}
var rows = jsondata.result.list;
foreach (var row in rows)
{
queueFzrProcess.Enqueue(row.ToString());
}
}
}
}
public static void ReqDingProcessInfo(string token,string procid, Action<string> SuccessCallback, Action<string> FailCallback)
{
string url = $"https://oapi.dingtalk.com/topapi/processinstance/get?access_token={token}";
StringBuilder data = new StringBuilder();
data.Append($@"{{""process_instance_id"":""{procid}""}}");
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36";
req.Accept = "application/json, text/plain, */*";
req.KeepAlive = true;
req.ContentType = "application/json;charset=UTF-8";
req.Headers.Add("X-Requested-With", "XMLHttpRequest");
req.ServicePoint.ConnectionLimit = int.MaxValue;
req.ServicePoint.Expect100Continue = false;
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] buffer = Encoding.UTF8.GetBytes(data.ToString());
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
}
req.BeginGetResponse(new AsyncCallback(RspDingProcessInfo), new object[] { req, token, procid, SuccessCallback, FailCallback });
}
public static void RspDingProcessInfo(IAsyncResult result)
{
object[] parms = result.AsyncState as object[];
string token = parms[1].ToString();
string procid = parms[2].ToString();
HttpWebRequest req = parms[0] as HttpWebRequest;
Action<string> SuccessCallback = parms[3] as Action<string>;
Action<string> FailCallback = parms[4] as Action<string>;
using (HttpWebResponse rsp = req.EndGetResponse(result) as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string msg = "";
msg = reader.ReadToEnd();
var jsondata = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(msg);
string businessid = jsondata.process_instance.business_id.ToString();
string customers = "";
string fzrNew = "";
StringBuilder sbFzrSource = new StringBuilder();
var fields = jsondata.process_instance.form_component_values;
foreach (var field in fields) {
switch (field.name.ToString()) {
case "客户名称": {
customers = field.value.ToString().Trim();
break;
}
case "需添加的负责人": {
string userstr= field.ext_value.ToString();
var jsonuser= Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(userstr);
foreach (var u in jsonuser)
{
fzrNew = u.emplId.ToString().Trim();
}
break;
}
case "选择任意当前客户负责人": {
string userstr = field.ext_value.ToString();
var jsonuser = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(userstr);
foreach (var u in jsonuser) {
sbFzrSource.Append($",{u.emplId.ToString().Trim()}");
}
break;
}
}
}
if (sbFzrSource.Length > 0)
sbFzrSource.Remove(0, 1);
string[] lstcustomer = customers.Split(new string[] { "\n", ",", ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string str in lstcustomer)
{
ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();
dic.AddOrUpdate("businessid", businessid, (k, v) => businessid);
dic.AddOrUpdate("customer", str, (k, v) => str);
dic.AddOrUpdate("fzr", fzrNew, (k, v) => fzrNew);
dic.AddOrUpdate("fzrSource", sbFzrSource.ToString(), (k, v) => sbFzrSource.ToString());
dic.AddOrUpdate("procid", procid,(k,v)=>procid);
queueProcs.Enqueue(dic);
}
}
}
}
定时任务
5分钟抓取一次审批。
根据抓到的最新的审批记录,查询每个审批记录的详情,获取相关的客户信息、负责人信息。
审批通过后把结果写入数据库,已经抓取过的数据,不再进行处理
问题:由于钉钉和CRM系统的接口处理有一定的时间差异,一般来说钉钉的系统比较快,由于CRM系统没有处理完,钉钉已经把业务处理完了,所以判断数据库那可能会出现重复。处理过的审批最好放到缓存中才完美。
#region 获取负责人流程信息
Task.Factory.StartNew(() =>
{
DateTime dt = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
//5分钟一次
while (true)
{
if (string.IsNullOrWhiteSpace(Business.DingAccessToken))
{
Thread.Sleep(1000);
continue;
}
Business.ReqDingProcess(Business.DingAccessToken, dt,
new Action<string>(str => { }),
new Action<string>(str => { })
);
dt = DateTime.Now;
Thread.Sleep(1000 * 60 * 5);
}
});
//获取流程信息
Task.Factory.StartNew(() =>
{
string logpath = $"{AppDomain.CurrentDomain.BaseDirectory}/logs/DingProcess";
if (!Directory.Exists(logpath))
Directory.CreateDirectory(logpath);
while (true)
{
if (string.IsNullOrWhiteSpace(Business.DingAccessToken))
{
Thread.Sleep(1000);
continue;
}
if (Business.queueFzrProcess.IsEmpty)
{
Thread.Sleep(1000);
continue;
}
Business.queueFzrProcess.TryDequeue(out string procid);
if (string.IsNullOrWhiteSpace(procid))
continue;
//如果该条目已经处理 则不再处理
var procids= DbAccess.Query($"select 1 from DingProc_CustomerFZR where procid='{procid}'");
if (procids.Any())
continue;
Business.ReqDingProcessInfo(Business.DingAccessToken, procid,
new Action<string>(str => { }),
new Action<string>(str => { })
);
Thread.Sleep(100);
}
});
//根据客户名称查询客户ID 并记录客户信息到数据库
Task.Factory.StartNew(() => {
Dictionary<string, ConcurrentDictionary<string, string>> dicTemp = new Dictionary<string, ConcurrentDictionary<string, string>>();
while (true)
{
if (Business.XbbModel == null)
{
Thread.Sleep(1000);
continue;
}
if (Business.queueProcs.IsEmpty) {
Thread.Sleep(1000);
continue;
}
Business.queueProcs.TryDequeue(out ConcurrentDictionary<string, string> dic);
if (dic == null) {
Thread.Sleep(1000);
continue;
}
//查询数据库中客户是否存在
var custid= DbAccess.Query($"select dataId from Customer{DateTime.Now.ToString("yyyyMMdd")} where text_1='{dic["customer"]}'");
if (!custid.Any())
{
dic.AddOrUpdate("result", "客户名称不存在",(k,v)=>v);
Business.queueProcsResult.Enqueue(dic);
//客户名称不存在,保存到数据库等待处理结果
Thread.Sleep(1000);
continue;
}
string dataid = (custid.FirstOrDefault()).dataId.ToString();
if (dicTemp.ContainsKey(dataid)) {
Business.queueProcs.Enqueue(dic);
Thread.Sleep(10000);
continue;
}
dicTemp.Add(dataid, dic);
Business.ReqDistributionCustomer(dataid, dic["fzr"], Business.XbbModel.UserID, Business.XbbModel.CorpId, Business.XbbModel.token,
new Action<string>(success => {
dicTemp[success].AddOrUpdate("result", "成功", (k, v) => v);
Business.queueProcsResult.Enqueue(dicTemp[success]);
dicTemp.Remove(success);
}),
new Action<string>(fail => {
dicTemp[fail].AddOrUpdate("result", "失败", (k, v) => v);
Business.queueProcsResult.Enqueue(dicTemp[fail]);
dicTemp.Remove(fail);
})
);
}
});
Task.Factory.StartNew(() =>
{
List<Dictionary<string, string>> lstdic = new List<Dictionary<string, string>>();
while (true) {
if (Business.queueProcsResult.IsEmpty) {
Thread.Sleep(1000);
continue;
}
while (!Business.queueProcsResult.IsEmpty) {
if (lstdic.Count > 50)
break;
Business.queueProcsResult.TryDequeue(out ConcurrentDictionary<string, string> dic);
if (dic == null)
continue;
Dictionary<string, string> dicTemp = new Dictionary<string, string>();
foreach (var kv in dic)
dicTemp.Add(kv.Key, kv.Value);
lstdic.Add(dicTemp);
}
DbAccess.AddTran(lstdic, "DingProc_CustomerFZR", null);
}
});
#endregion
欢迎大家点评
学以致用,解放劳动力,把更多时光用在更美好的生活里。
来源:oschina
链接:https://my.oschina.net/u/4382640/blog/4279525