Files
lserp_cs_6.0/其他程序/Lskj.GetDingTalkAttendance/Lskj.GetDingTalkAttendance/FrmMain.cs
T
cyf ab56a9bcf7 基线 SVN r240
SVN-Revision: r240
2025-02-06 06:46:06 +00:00

412 lines
20 KiB
C#

using Lskj.Control;
using Lskj.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Lskj.GetDingTalkAttendance
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
this.Load += OnFrmMainLoad;
}
/// <summary>
/// 获取数据的timer
/// </summary>
public System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
/// <summary>
/// 界面上下文
/// </summary>
public SynchronizationContext SyncContext;
private void OnFrmMainLoad(object sender, EventArgs e)
{
string appKey = IniHelper.Read("AppKey");
if (!string.IsNullOrEmpty(appKey))
{
txt_AppKey.Text = appKey;
}
string appSecret = IniHelper.Read("AppSecret");
if (!string.IsNullOrEmpty(appSecret))
{
txt_AppSecret.Text = appSecret;
}
string dbServer = IniHelper.Read("DBServer");
if (!string.IsNullOrEmpty(dbServer))
{
txt_DBServer.Text = dbServer;
}
string dbName = IniHelper.Read("DBName");
if (!string.IsNullOrEmpty(dbName))
{
txt_DBName.Text = dbName;
}
string dbUser = IniHelper.Read("DBUser");
if (!string.IsNullOrEmpty(dbUser))
{
txt_DBUser.Text = dbUser;
}
string password = IniHelper.Read("Password");
if (!string.IsNullOrEmpty(password))
{
txt_Password.Text = password;
}
string timePoint = IniHelper.Read("TimePoint");
if (!string.IsNullOrEmpty(timePoint))
{
txt_TimePoint.Text = timePoint;
}
txt_AppKey.TextChanged += OnTextChanged;
txt_AppSecret.TextChanged += OnTextChanged;
txt_DBName.TextChanged += OnTextChanged;
txt_DBServer.TextChanged += OnTextChanged;
txt_DBUser.TextChanged += OnTextChanged;
txt_Password.TextChanged += OnTextChanged;
txt_TimePoint.TextChanged += OnTextChanged;
startBtn.Click += OnStartBtnClick;
SyncContext = SynchronizationContext.Current;
}
/// <summary>
/// 文本值改变时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTextChanged(object sender, EventArgs e)
{
if (sender == txt_AppKey)
{
IniHelper.Write("AppKey", txt_AppKey.Text);
}
if (sender == txt_AppSecret)
{
IniHelper.Write("AppSecret", txt_AppSecret.Text);
}
if (sender == txt_DBServer)
{
IniHelper.Write("DBServer", txt_DBServer.Text);
}
if (sender == txt_DBName)
{
IniHelper.Write("DBName", txt_DBName.Text);
}
if (sender == txt_DBUser)
{
IniHelper.Write("DBUser", txt_DBUser.Text);
}
if (sender == txt_Password)
{
IniHelper.Write("Password", txt_Password.Text);
}
if (sender == txt_TimePoint)
{
IniHelper.Write("TimePoint", txt_TimePoint.Text);
}
}
/// <summary>
/// 开始同步按钮点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnStartBtnClick(object sender, EventArgs e)
{
DBConfig.Instance.ServerName = txt_DBServer.Text;
DBConfig.Instance.DataBase = txt_DBName.Text;
if (DBConfig.Instance.CreateConnection())
{
CreateAttendanceTable();
timer.Interval = 200;
timer.Tick += OnTimerTick;
timer.Enabled = true;
}
else
{
MessageUtil.Show("服务器连接失败");
}
}
/// <summary>
/// timer事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTimerTick(object sender, EventArgs e)
{
timer.Enabled = false;
try
{
string[] timePoints = txt_TimePoint.Text.Split(',');
foreach (string timePoint in timePoints)
{
if (DateTime.TryParse(timePoint, out DateTime dateTime))
{
if (DateTime.Now.TimeOfDay > dateTime.TimeOfDay)
{
string checkDateFrom = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");
string checkDateTo = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
string appkey = this.txt_AppKey.Text;
string appsecret = this.txt_AppSecret.Text;
HttpTools.setting("application/x-www-form-urlencoded", "", "");
if (GetAccessToken(appkey, appsecret, out string accessToken))
{
List<string> deptsList = new List<string>();
GetDepartmentsList(accessToken, "1", deptsList);
List<string> usersList = new List<string>();
foreach (string deptid in deptsList)
{
GetUsersList(accessToken, deptid, usersList);
}
foreach (string userid in usersList)
{
GetAttendance(accessToken, userid, checkDateFrom, checkDateTo);
}
}
}
}
}
}
catch (Exception ex)
{
SyncContext.Post(AddMsg, $"TimerTick:获取考勤信息失败,{ex.Message}。");
}
timer.Enabled = true;
}
/// <summary>
/// 更新界面信息
/// </summary>
/// <param name="state"></param>
private void AddMsg(object state)
{
string msg = state + "";
txt_Msg.AppendText($"{msg}\r\n");
}
/// <summary>
/// 创建表
/// </summary>
private void CreateAttendanceTable()
{
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.AppendLine("if not exists(select top 1 * from sysObjects where Id = OBJECT_ID(N'P_DingTalkAttendanceTab') and xtype = 'U')");
sqlBuilder.AppendLine("begin");
sqlBuilder.AppendLine("CREATE TABLE P_DingTalkAttendanceTab (id INT IDENTITY(1,1) PRIMARY KEY, gmtModified VARCHAR(200), baseCheckTime VARCHAR(200), groupId VARCHAR(200), timeResult VARCHAR(200), deviceId VARCHAR(200), approveId VARCHAR(200), userAccuracy VARCHAR(200), classId VARCHAR(200), workDate VARCHAR(200), bizId VARCHAR(200), planId VARCHAR(200), checkType VARCHAR(200), planCheckTime VARCHAR(200), corpId VARCHAR(200), locationResult VARCHAR(200), userLongitude VARCHAR(200), isLegal VARCHAR(200), procInstId VARCHAR(200), gmtCreate VARCHAR(200), userId VARCHAR(200), outsideRemark VARCHAR(200), userAddress VARCHAR(200), userLatitude VARCHAR(200), sourceType VARCHAR(200), userCheckTime VARCHAR(200), locationMethod VARCHAR(200));");
sqlBuilder.AppendLine("end");
SqlHelper.ExecuteNonQuery(sqlBuilder.ToString());
}
/// <summary>
/// 获取token
/// </summary>
/// <param name="appkey"></param>
/// <param name="appsecret"></param>
/// <param name="access_token"></param>
/// <returns></returns>
private bool GetAccessToken(string appkey, string appsecret, out string access_token)
{
bool success = true;
access_token = "";
try
{
string postUrl = $"https://oapi.dingtalk.com/gettoken";
Dictionary<string, string> pmsDic = new Dictionary<string, string>();
pmsDic.Add("appkey", appkey);
pmsDic.Add("appsecret", appsecret);
HttpWebResponse webResponse = HttpTools.Get(postUrl, "", pmsDic, null, HttpTools.Method.GET, out CookieCollection cookieCollection, out string result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject returnJObject = (JObject)JsonConvert.DeserializeObject(result);
if (returnJObject.ContainsKey("errcode") && (returnJObject["errcode"] + "").Equals("0"))
{
access_token = returnJObject["access_token"] + "";
}
}
}
catch (Exception ex)
{
SyncContext.Post(AddMsg, $"GetAccessToken:accesstoken获取失败,{ex.Message}。");
success = false;
}
return success;
}
/// <summary>
/// 获部门信息
/// </summary>
/// <param name="access_token"></param>
/// <param name="dept_id"></param>
/// <param name="deptsList"></param>
/// <returns></returns>
private bool GetDepartmentsList(string access_token, string dept_id, List<string> deptsList)
{
if (deptsList == null)
{
deptsList = new List<string>();
}
bool success = true;
try
{
string postUrl = $"https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token={access_token}";
JObject pmsJObject = new JObject();
pmsJObject.Add("dept_id", dept_id);
pmsJObject.Add("language", "zh_CN");
string pmsBody = JsonConvert.SerializeObject(pmsJObject);
HttpWebResponse webResponse = HttpTools.Post(postUrl, pmsBody, null, HttpTools.Method.POST, out CookieCollection cookieCollection, out string result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject returnJObject = (JObject)JsonConvert.DeserializeObject(result);
if (returnJObject.ContainsKey("errcode") && (returnJObject["errcode"] + "").Equals("0"))
{
JArray departmentJArray = (JArray)returnJObject["result"];
foreach (JObject item in departmentJArray)
{
string deptid = item["dept_id"] + "";
deptsList.Add(deptid);
GetDepartmentsList(access_token, deptid, deptsList);
}
}
}
}
catch (Exception ex)
{
SyncContext.Post(AddMsg, $"GetDepartmentsList:部门{dept_id}信息获取失败,{ex.Message}。");
success = false;
}
return success;
}
/// <summary>
/// 获取部门员工列表
/// </summary>
/// <param name="accessToken"></param>
/// <param name="userId"></param>
/// <param name="checkDateFrom"></param>
/// <param name="checkDateTo"></param>
/// <returns></returns>
private bool GetUsersList(string access_token, string dept_id, List<string> usersList)
{
if (usersList == null)
{
usersList = new List<string>();
}
bool success = true;
try
{
if (!string.IsNullOrEmpty(access_token))
{
string postUrl = $"https://oapi.dingtalk.com/topapi/user/listid?access_token={access_token}";
JObject pmsJObject = new JObject();
pmsJObject.Add("dept_id", dept_id);
string pmsBody = JsonConvert.SerializeObject(pmsJObject);
HttpWebResponse webResponse = HttpTools.Post(postUrl, pmsBody, null, HttpTools.Method.POST, out CookieCollection cookieCollection, out string result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject returnJObject = (JObject)JsonConvert.DeserializeObject(result);
if (returnJObject.ContainsKey("errcode") && (returnJObject["errcode"] + "").Equals("0"))
{
JArray usersJArray = (JArray)returnJObject["result"]["userid_list"];
foreach (JValue item in usersJArray)
{
string userid = item.Value + "";
usersList.Add(userid);
}
}
}
}
else
{
success = false;
}
}
catch (Exception ex)
{
SyncContext.Post(AddMsg, $"GetUsersList:部门{dept_id}员工列表信息获取失败,{ex.Message}。");
success = false;
}
return success;
}
/// <summary>
/// 获取打卡记录
/// </summary>
/// <param name="accessToken"></param>
/// <param name="userId"></param>
/// <param name="checkDateFrom"></param>
/// <param name="checkDateTo"></param>
/// <returns></returns>
private bool GetAttendance(string access_token, string user, string checkDateFrom, string checkDateTo)
{
bool success = true;
try
{
if (!string.IsNullOrEmpty(access_token))
{
string postUrl = $"https://oapi.dingtalk.com/attendance/listRecord?access_token={access_token}";
JObject pmsJObject = new JObject();
JArray userIdArray = new JArray();
userIdArray.Add(user);
pmsJObject.Add("userIds", userIdArray);
pmsJObject.Add("checkDateFrom", checkDateFrom);
pmsJObject.Add("checkDateTo", checkDateTo);
pmsJObject.Add("isI18n", "false");
string pmsBody = JsonConvert.SerializeObject(pmsJObject);
HttpWebResponse webResponse = HttpTools.Post(postUrl, pmsBody, null, HttpTools.Method.POST, out CookieCollection cookieCollection, out string result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject returnJObject = (JObject)JsonConvert.DeserializeObject(result);
if (returnJObject.ContainsKey("errcode") && (returnJObject["errcode"] + "").Equals("0"))
{
JArray resultJArray = (JArray)returnJObject["recordresult"];
foreach (JObject item in resultJArray)
{
string gmtModified = item.ContainsKey("gmtModified") ? item["gmtModified"] + "" : "";
string baseCheckTime = item.ContainsKey("baseCheckTime") ? item["baseCheckTime"] + "" : "";
string groupId = item.ContainsKey("groupId") ? item["groupId"] + "" : "";
string timeResult = item.ContainsKey("timeResult") ? item["timeResult"] + "" : "";
string deviceId = item.ContainsKey("deviceId") ? item["deviceId"] + "" : "";
string approveId = item.ContainsKey("approveId") ? item["approveId"] + "" : "";
string userAccuracy = item.ContainsKey("userAccuracy") ? item["userAccuracy"] + "" : "";
string classId = item.ContainsKey("classId") ? item["classId"] + "" : "";
string workDate = item.ContainsKey("workDate") ? item["workDate"] + "" : "";
string bizId = item.ContainsKey("bizId") ? item["bizId"] + "" : "";
string planId = item.ContainsKey("planId") ? item["planId"] + "" : "";
string id = item.ContainsKey("id") ? item["id"] + "" : "";
string checkType = item.ContainsKey("checkType") ? item["checkType"] + "" : "";
string planCheckTime = item.ContainsKey("planCheckTime") ? item["planCheckTime"] + "" : "";
string corpId = item.ContainsKey("corpId") ? item["corpId"] + "" : "";
string locationResult = item.ContainsKey("locationResult") ? item["locationResult"] + "" : "";
string userLongitude = item.ContainsKey("userLongitude") ? item["userLongitude"] + "" : "";
string isLegal = item.ContainsKey("isLegal") ? item["isLegal"] + "" : "";
string procInstId = item.ContainsKey("procInstId") ? item["procInstId"] + "" : "";
string gmtCreate = item.ContainsKey("gmtCreate") ? item["gmtCreate"] + "" : "";
string userId = item.ContainsKey("userId") ? item["userId"] + "" : "";
string outsideRemark = item.ContainsKey("outsideRemark") ? item["outsideRemark"] + "" : "";
string userAddress = item.ContainsKey("userAddress") ? item["userAddress"] + "" : "";
string userLatitude = item.ContainsKey("userLatitude") ? item["userLatitude"] + "" : "";
string sourceType = item.ContainsKey("sourceType") ? item["sourceType"] + "" : "";
string userCheckTime = item.ContainsKey("userCheckTime") ? item["userCheckTime"] + "" : "";
string locationMethod = item.ContainsKey("locationMethod") ? item["locationMethod"] + "" : "";
string insertSql = $"insert into P_DingTalkAttendanceTab (gmtModified, baseCheckTime, groupId, timeResult, deviceId, approveId, userAccuracy, classId, workDate, bizId, planId, id, checkType, planCheckTime, corpId, locationResult, userLongitude, isLegal, procInstId, gmtCreate, userId, outsideRemark, userAddress, userLatitude, sourceType, userCheckTime, locationMethod) values ('{gmtModified}', '{baseCheckTime}', '{groupId}', '{timeResult}', '{deviceId}', '{approveId}', '{userAccuracy}', '{classId}', '{workDate}', '{bizId}', '{planId}', '{id}', '{checkType}', '{planCheckTime}', '{corpId}', '{locationResult}', '{userLongitude}', '{isLegal}', '{procInstId}', '{gmtCreate}', '{userId}', '{outsideRemark}', '{userAddress}', '{userLatitude}', '{sourceType}', '{userCheckTime}', '{locationMethod}');";
SqlHelper.ExecuteNonQuery(insertSql);
}
}
}
}
else
{
success = false;
}
}
catch (Exception ex)
{
SyncContext.Post(AddMsg, $"GetAttendance:人员{user}签到信息获取失败,{ex.Message}。");
success = false;
}
return success;
}
}
}