You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/Areas/MvcShipping/Helper/DingTalkHelper.cs

841 lines
25 KiB
C#

2 years ago
using AlibabaCloud.SDK.Dingtalkh5package_1_0.Models;
using AlibabaCloud.SDK.Dingtalkvillage_1_0.Models;
using DSWeb.Areas.CommMng.DAL;
2 years ago
using DSWeb.Areas.Dispatch.Helper;
2 years ago
using DSWeb.Areas.MvcShipping.DB;
using DSWeb.Areas.MvcShipping.Job;
using DSWeb.Areas.MvcShipping.Models.MsOpSeaeBaoXian;
using DSWeb.Common.DB;
using HcUtility.Comm;
using java.rmi.server;
using java.util;
2 years ago
using log4net;
using Microsoft.Office.Interop.Excel;
2 years ago
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.Contracts;
using System.IO;
2 years ago
using System.Linq;
using System.Runtime.Caching;
using System.Runtime.Serialization.Json;
using System.Text;
2 years ago
using System.Web;
2 years ago
using Tea;
using static DSWeb.Areas.CommMng.Controllers.WorkFlowController;
using static DSWeb.Areas.MvcShipping.Helper.DingTalk_SendAuditWork;
2 years ago
namespace DSWeb.Areas.MvcShipping.Helper
{
public static class DingTalkHelper
{
public static readonly string DingTalkAccessTokenStoreKey = "DingTalkToken";
private static ILog logger = LogManager.GetLogger("DingTalkHelper");
/// <summary>
/// 发送工作通知
/// https://open-dev.dingtalk.com/apiExplorer#/?devType=org&api=dingtalk.oapi.message.corpconversation.asyncsend_v2
/// </summary>
/// <param name="uid"></param>
/// <param name="msg"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
2 years ago
public static bool SendMessage(string uid, string msg)
{
DingTalkContext dingTalkContext = new DingTalkContext();
var pAgentid = dingTalkContext.ParamSets.FirstOrDefault(p => p.PARAMNAME == "DingTalkAgentid");
if (pAgentid == null || string.IsNullOrWhiteSpace(pAgentid.PARAMVALUE))
{
throw new Exception("钉钉Agentid参数配置错误");
}
var user = dingTalkContext.Users.FirstOrDefault(u => u.GID == uid);
if (user != null && !string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
var token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
var json = new
{
agent_id = pAgentid.PARAMVALUE,
userid_list = user.DingTalkAccount,
msg = new
{
msgtype = "text",
text = new
{
content = msg
}
}
};
string resp = WebRequestHelper.DoPost($"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={token}", JsonConvert.SerializeObject(json));
logger.Debug(resp);
var jsonObj = JsonConvert.DeserializeAnonymousType(resp, new
{
errcode = 0,
errmsg = "",
task_id = ""
});
if (jsonObj.errcode == 0)
{
return true;
}
}
return false;
}
2 years ago
/// <summary>
/// 读取实例当前值 data内容是json文本
/// </summary>
/// <param name="instanceId"></param>
/// <returns></returns>
public static DBResult DingTalk_Instanceinfo(string instanceId) {
//https://open.dingtalk.com/document/isvapp-server/queries-a-process-instance-based-on-its-id
var result = new DBResult();
DingTalk_Instanceinfo dh = new DingTalk_Instanceinfo();
dh.MakeSendMessage(instanceId);//i0P82FAHT_G9TWJmavxGdg03131673000830
result = dh.DoSend();
return result;
}
//public static DBResult DingTalk_ReadWMSINInstance(string instanceId)
//{
// var result = new DBResult();
// var instanceiddic = BasicDataRefDAL.GetLogicInfo(wmsno, "钉钉审批");
// if (instanceiddic == null || !instanceiddic.ContainsKey("instanceId"))
// {
// return result.SetErrorInfo(wmsno + "没有进行钉钉审批");
// }
// else
// {
// }
// var _r = DingTalk_Instanceinfo(instanceId);
// if (!_r.Success)
// {
// return _r;
// }
// 如果成功 用数据对象解析结果 并做相应处理
//}
public static DBResult Send_WMSIN(string uid, string wmsno)
{
var result = new DBResult();
DingTalk_SendAuditWork dh = new DingTalk_SendAuditWork(uid);
if (dh.cansend(wmsno))
{
result= dh.MakeSendMessage(wmsno);
if (!result.Success) {
return result;
}
result = dh.DoSend();
}
else {
result.SetErrorInfo("该业务已发送");
}
return result;
}
}
public class DingTalkSendHelper {
public DingTalkSendHelper() { }
public string url { get; set; }
public string uid { get; set; }
public object SendObject { get; set; }
public SysParamSet pAgentid { get; set; }
public DB.User user { get; set; } = null;
public object jsonObj { get; set; }
public Dictionary<string, string> dicObj { get; set; } = new Dictionary<string, string>();
public string json { get; set; }
public string token { get; set; }
public Dictionary<string, string> HeaderDic { get; set; }
private static ILog logger = LogManager.GetLogger("DingTalkHelper");
public DingTalkContext dingTalkContext { get; set; } = new DingTalkContext();
DBResult result { get; set; } = new DBResult();
public DBResult getUser()
{
user = dingTalkContext.Users.FirstOrDefault(u => u.GID == uid);
if (user == null || string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
result.SetErrorInfo("用户没有维护钉钉userid");
return result;
}
result.OK();
return result;
}
public DBResult GetAgentid() {
result = new DBResult();
pAgentid = dingTalkContext.ParamSets.FirstOrDefault(p => p.PARAMNAME == "DingTalkAgentid");
if (pAgentid == null || string.IsNullOrWhiteSpace(pAgentid.PARAMVALUE))
{
result.SetErrorInfo("钉钉Agentid参数配置错误");
return result;
}
result.OK();
return result;
}
public DBResult DoSend() {
var result = new DBResult();
string resp = WebRequestHelper.DoPost(url, JsonConvert.SerializeObject(jsonObj));
logger.Debug(resp);
result.setMessage(true,"发送成功", jsonObj);
return result;
}
public DBResult DoSend_Header()
{
var result = new DBResult();
string resp = "";
if (jsonObj != null)
{
resp=WebRequestHelper.DoPost_Header(url, HeaderDic, jsonObj);
}
else {
resp=WebRequestHelper.DoPost_Header(url, HeaderDic);
}
logger.Debug(resp);
result.setMessage(true, "发送成功", resp);
return result;
}
public DBResult DoGet_Header_Param()
{
var result = new DBResult();
string resp = WebRequestHelper.DoGet_Header_Param(url, HeaderDic, dicObj);
//logger.Debug(resp);
result.setMessage(true, "发送成功", resp);
return result;
}
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
}
public class DingTalk_SendWorkMessage : DingTalkSendHelper {
public DingTalk_SendWorkMessage(string uid) {
this.uid = uid;
}
public DBResult MakeSendMessage(string msg) {
var result = new DBResult();
result = GetAgentid();
if (!result.Success) return result;
result = getUser();
if (!result.Success) return result;
jsonObj = new
{
agent_id = pAgentid.PARAMVALUE,
userid_list = user.DingTalkAccount,
msg = new
{
msgtype = "text",
text = new
{
content = msg
}
}
};
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={token}";
result.OK();
return result;
}
}
public class DingTalk_SendAuditWork : DingTalkSendHelper
{
public string BSNO { get; set; }
public DingTalk_SendAuditWork(string uid)
{
this.uid = uid;
getUser();
}
public class DingTalkFormField {
public string name { get; set; }
public string value { get; set; }
public DingTalkFormField(string name, string value)
{
this.name = name;
this.value = value;
}
}
public class DingTalkForm_approvers
{
public string actionType { get; set; }
public List<string> userIds { get; set; }
public DingTalkForm_approvers(string actionType, List<string> userIds)
{
this.actionType = actionType;
this.userIds = userIds;
}
}
public class DingTalk_OAAuditBody {
public long deptId { get; set; }
public List<DingTalkForm_approvers> approvers { get; set; } = new List<DingTalkForm_approvers>();
public long microappAgentId { get; set; }
public string originatorUserId { get; set; }
public string processCode { get; set; }
public List<DingTalkFormField> formComponentValues { get; set; } = new List<DingTalkFormField>();
}
public bool cansend(string GID) {
//看是否已发过
var logiclog = BasicDataRefDAL.GetLogicInfo(GID, "钉钉审批");
if (logiclog.Count > 0)
{
return false;
}
return true;
}
public DBResult MakeSendMessage(string wmsno)
{
var result = new DBResult();
wmsno = wmsno.Replace("'", "");
try
{
if (string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
return result.SetErrorInfo("请配置用户的钉钉id");
}
BSNO = wmsno;
DingTalk_OAAuditBody body = new DingTalk_OAAuditBody();
var dp = DingTalkProcess.GetDingTalkProcess("诚锐入货通知");
body.deptId = dp.deptid;//
//获取用户的钉钉id
var dtc = new DingTalkContext();
body.approvers.Add(new DingTalkForm_approvers("OR", new List<string> { user.DingTalkAccount }));
body.microappAgentId = dp.agentid;//
body.originatorUserId = user.DingTalkAccount;
body.processCode = dp.processCode;
var cdc = new CommonDataContext();
var wms = cdc.wms.First(p => p.WMSNO == wmsno);
var wmsinList = cdc.wms_in.Where(x => x.ASSOCIATEDNO == wms.GID).ToList();
var list = new List<List<DingTalkFormField>>();
var list = new List<List<DingTalkFormField>>();
var idlist = wmsinList.Select(s => s.CHEDUIID).ToList();
var list = cdc.info_client.Where(x => idlist.Contains(x.GID)).ToList();
foreach (var item in wmsinList)
{
var newrk = new List<DingTalkFormField>
{
new DingTalkFormField("提单号", item.BLNO),
new DingTalkFormField("箱号", item.CNTRNO),
new DingTalkFormField("品名", item.GOODSNAME),
new DingTalkFormField("重量", item.GOODSRKSL.ToString()),
new DingTalkFormField("件数", item.GOODSPACK.ToString()),
new DingTalkFormField("尺码", item.CHIMA1.ToString()),
new DingTalkFormField("库位", item.CHIMA1.ToString())
};
list.Add(newrk);
if (list != null && list.Exists(x => x.GID == item.CHEDUIID))
{
var = list.First(x => x.GID == item.CHEDUIID);
var newcl = new List<DingTalkFormField>{
new DingTalkFormField("车队", .SHORTNAME),
new DingTalkFormField("车牌号", item.TRUCKNO)
};
list.Add(newcl);
}
}
var = new DingTalkFormField("入库信息", JsonConvert.SerializeObject(list));
var = new DingTalkFormField("车队信息", JsonConvert.SerializeObject(list));
body.formComponentValues = new List<DingTalkFormField>
{
//new DingTalkFormField("提单号", "123123")
//增加字段内容
new DingTalkFormField("客户名称", wms.CUSTOMERNAME),
new DingTalkFormField("入库日期", ((DateTime)wms.WMSDATE).ToString("yyyy-MM-dd")),
,
};
jsonObj = body;
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://api.dingtalk.com/v1.0/workflow/processInstances";
HeaderDic = new Dictionary<string, string>
{
{ "x-acs-dingtalk-access-token", token }
};
result.OK();
return result;
}
catch (Exception e) {
return result.SetErrorInfo(e.Message );
}
}
public class DingTalk_SendAuditResult {
public string instanceId { get; set; }
}
public DBResult DoSend() {
var result = base.DoSend_Header();
if (result.Success) {
try
{
var jo = new DingTalk_SendAuditResult();
jo = (DingTalk_SendAuditResult)JsonToObject(result.Data.ToString(), jo);
var dic = new Dictionary<string, string>();
dic.Add("instanceId", jo.instanceId);
BasicDataRefDAL.SaveLogicInfo(BSNO, "钉钉审批", dic);
}catch(Exception ex)
{
}
}
return result;
2 years ago
}
2 years ago
}
public class DingTalk_Instanceinfo : DingTalkSendHelper {
public string instanceId { get; set; }
public DingTalk_Instanceinfo()
{
//this.uid = uid;
}
public DBResult MakeSendMessage(string instanceId )
{
this.instanceId = instanceId;
var result = new DBResult();
jsonObj = null;
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://api.dingtalk.com/v1.0/workflow/processInstances" ;
dicObj= new Dictionary<string, string> {
{"processInstanceId",instanceId }
};
HeaderDic = new Dictionary<string, string>
{
{ "x-acs-dingtalk-access-token", token }
};
result.OK();
return result;
}
public DBResult DoSend()
{
var result = base.DoGet_Header_Param();
if (result.Success)
{
try
{
BasicDataRefDAL.SaveLog(result.Data.ToString(), uid, "读取业务信息","返回");
//jo = (DingTalk_Instanceinfo)JsonToObject(result.Data.ToString(), jo);
}
catch (Exception ex)
{
}
}
return result;
}
}
#region 处理钉钉回调返回值
public class DingTalkCallbackDealHelper
{
public string processInstanceId { get; set; }
public string processCode { get; set; }
public string type { get; set; }
public DingTalkCallbackDealHelper() { }
public DingTalkCallbackDealHelper(string instanceId) {
processInstanceId = instanceId;
}
public DingTalkCallbackDealHelper(CallBackInfo callbackinfo)
{
processInstanceId = callbackinfo.processInstanceId;
processCode = callbackinfo.processCode;
type = callbackinfo.type;
}
}
public class OperationRecords
{
/// <summary>
///
/// </summary>
public string date { get; set; }
/// <summary>
///
/// </summary>
public string result { get; set; }
/// <summary>
///
/// </summary>
public string type { get; set; }
/// <summary>
///
/// </summary>
public string userId { get; set; }
}
public class FormComponentValues
{
/// <summary>
///
/// </summary>
public string componentType { get; set; }
/// <summary>
/// 客户名称
/// </summary>
public string name { get; set; }
/// <summary>
///
/// </summary>
public string bizAlias { get; set; }
/// <summary>
///
/// </summary>
public string id { get; set; }
/// <summary>
/// 众盈
/// </summary>
public string value { get; set; }
public GetRowValues() {
//用value值文本来解析成 行信息
var result = new ();
if (value.Contains("\\\"rowValue\\\""))
{
try
{
var _value = value.Replace("\\", "");
var hxx = JsonConvert.DeserializeObject<>(_value);
result = hxx;
}
catch (Exception ex)
{ }
}
return result;
}
}
public class Tasks
{
/// <summary>
///
/// </summary>
public string result { get; set; }
/// <summary>
///
/// </summary>
public string activityId { get; set; }
/// <summary>
///
/// </summary>
public string pcUrl { get; set; }
/// <summary>
///
/// </summary>
public string createTime { get; set; }
/// <summary>
///
/// </summary>
public string mobileUrl { get; set; }
/// <summary>
///
/// </summary>
public string userId { get; set; }
/// <summary>
///
/// </summary>
public int taskId { get; set; }
/// <summary>
///
/// </summary>
public string status { get; set; }
}
public class Result
{
/// <summary>
///
/// </summary>
public List<string> attachedProcessInstanceIds { get; set; }
/// <summary>
///
/// </summary>
public string businessId { get; set; }
/// <summary>
/// 邓羽提交的入库统计
/// </summary>
public string title { get; set; }
/// <summary>
///
/// </summary>
public string originatorDeptId { get; set; }
/// <summary>
///
/// </summary>
public List<OperationRecords> operationRecords { get; set; }
/// <summary>
///
/// </summary>
public List<FormComponentValues> formComponentValues { get; set; }
/// <summary>
///
/// </summary>
public string result { get; set; }
/// <summary>
///
/// </summary>
public string bizAction { get; set; }
/// <summary>
///
/// </summary>
public string createTime { get; set; }
/// <summary>
///
/// </summary>
public string originatorUserId { get; set; }
/// <summary>
///
/// </summary>
public List<Tasks> tasks { get; set; }
/// <summary>
/// 青岛诚锐众盈货运代理有限公司
/// </summary>
public string originatorDeptName { get; set; }
/// <summary>
///
/// </summary>
public string status { get; set; }
}
public class DingTalkInstanceinfo
{
/// <summary>
///
/// </summary>
public Result result { get; set; }
/// <summary>
///
/// </summary>
public bool success { get; set; }
}
public class
{
public List<rowValue> rowValue { get; set; }
public string rowNumber { get; set; }
public string getValue(string fieldname) {
var result = "";
if (rowValue.Exists(x => x.label == fieldname)) {
result = rowValue.First(x => x.label == fieldname).value;
}
return result;
}
}
public class rowValue
{
public string bizAlias { get; set; }
public string label { get; set; }
public string value { get; set; }
public string key { get; set; }
}
#endregion
#region 钉钉业务类
public class DingTalkProcess {
public string processname { get; set; }
public string processCode { get; set; }
public string token { get; set; }
public string aes_key { get; set; }
public string appkey { get; set; }
public long agentid { get; set; }
public long deptid { get; set; }
//public string callbackstr { get; set; }
public DingTalkCallbackDealHelper callbackinfo { get; set; }
public void SaveCallBack(CallBackInfo _callbackinfo) {
callbackinfo = new DingTalkCallbackDealHelper(_callbackinfo);
}
public DingTalkProcess() { }
public DingTalkProcess(string processname) { this.processname = processname; }
/// <summary>
/// 这些数值来自于钉钉中某个组织的某个应用。一个应用可以监听多个实际业务的返回值
/// </summary>
/// <param name="processname"></param>
/// <returns></returns>
public static DingTalkProcess GetDingTalkProcess(string processname) {
var result = new DingTalkProcess();
if (processname == "测试入货通知") {
result = new DingTalkProcess_(processname);
return result;
}
if (processname == "诚锐入货通知")
{
result = new DingTalkProcess_(processname);
return result;
}
return result;
}
public virtual DBResult DoDeal() { return new DBResult(); }
}
public class DingTalkProcess_ : DingTalkProcess
{
public DingTalkProcess_(string processname)
{
this.processname = processname;
processCode = "PROC-0DC40EA2-E9D2-4917-A597-AD77EC055C49";
token = "zbGFOwrH6zCvq3VE3izLmWRTNUC1YcX";
aes_key = "sb6GkCKsUwNQo3RKbX1MzHKea1ZsE221n3xQ9hwJBMK";
appkey = "dingsaofiohmsrcbxyef";
agentid = 2298782307;
agentid = 809181118;
}
public override DBResult DoDeal() {
var result = new DBResult();
//根据processinstancid 读取审批实例信息
var Str = DingTalkHelper.DingTalk_Instanceinfo(callbackinfo.processInstanceId);
//解析返回结果
return result;
}
}
public class DingTalkProcess_ : DingTalkProcess
{
public DingTalkProcess_(string processname) {
this.processname = processname;
processCode = "PROC-0888A19C-0562-42AC-A9C6-24E4C4398410";
token = "CWhvNvfyuNf9D8halMs5PyHV70CrFx3E";
aes_key = "O5u6L8YnUaucnC8FyFNMeMeGE5uoYSAGFGdg3rOHftt";
appkey = "dingkt5caipnn4fbuqsf";
agentid = 2365401074;
deptid = 432400353;
}
public override DBResult DoDeal()
{
return new DBResult();
}
}
#endregion
2 years ago
}