123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689 |
- using EyeSoft.Extensions;
- using OASystem.Domain.Dtos.QiYeWeChat;
- using OASystem.Domain.ViewModels.QiYeWeChat;
- using System.Diagnostics;
- using System.Text.Json;
- namespace OASystem.API.OAMethodLib.QiYeWeChatAPI
- {
- /// <summary>
- /// 聚合Api 服务
- /// </summary>
- public class QiYeWeChatApiService : IQiYeWeChatApiService
- {
- private readonly HttpClient _httpClient;
- //private readonly string CorpId = "wwe978bef5495a0728"; //企业Id
- //private readonly string PersonnelAssistant_AgentId = "3010011"; //人事助手Id
- //private readonly string PunchCard_AgentId = "3010185"; //打卡Id
- //private readonly string Email_AgentId = "1000004"; //E-Mail Id
- //private readonly string Approve_AgentId = "3010040"; //审批 Id
- //private readonly string GroupStatus_AgentId = "1000008"; //OA通知 Id
- private readonly string PersonnelAssistant_Corpsecret = "ig--IJd6TxWDMJ1wT4e-RDRcRX12v5GjB359DNATwJ4"; //人事助手凭证密钥
- private readonly string PunchCard_Corpsecret = "Xhrl37GOqlAjsu0VzUSJECaJdjzkDXQLbvrzRsZQb8M"; //打卡凭证密钥
- private readonly string Email_Corpsecret = "NA1zbJM15GmgjPYwDOqz59dIo1Wnug-MbU107MeUemc"; //E-Mail 凭证密钥
- private readonly string AddressBook_Corpsecret = "Y1tnjh7j-BvbqAytAoXZPUbmDR6dqLTL6mXtc6PZ7fo"; //通讯录同步 凭证密钥
- private readonly string Approve_Corpsecret = "k_Jo69Jw9Hqg_in-Rypbs30PNbxOYa1t4e-dxYuT-kw"; //审批 凭证密钥
- private readonly string GroupStatus_Corpsecret = "7J_ST3jTPzbZpFwl7ttToTVufjEx6O2wuApvKHxt2Ak"; //OA通知Secret
- private readonly DateTime _1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
- private readonly JobPostRepository _jobPostRep;
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="clientFactory"></param>
- /// <param name="jobPostRep"></param>
- public QiYeWeChatApiService(IHttpClientFactory clientFactory, JobPostRepository jobPostRep)
- {
- _httpClient = clientFactory.CreateClient("PublicQiYeWeChatApi"); ;
- _jobPostRep = jobPostRep;
- }
- /// <summary>
- /// 获取access_token
- /// </summary>
- /// <param name="applicationType">
- /// 1:人事助手
- /// 2:打卡
- /// 3:邮件
- /// 4:通讯录同步
- /// 5:审批
- /// 6:团组状态通知
- /// </param>
- /// <returns></returns>
- private async Task<Access_TokenView> GetTokenAsync(int applicationType)
- {
- Access_TokenView tokenResult = new Access_TokenView();
- Access_Token_Request access_Token = new Access_Token_Request();
- string cacheName = string.Empty;
- if (applicationType == 1)
- {
- access_Token.corpsecret = PersonnelAssistant_Corpsecret; //人事助手
- cacheName = "PersonnelAssistant_Access_Token";
- }
- else if (applicationType == 2)
- {
- access_Token.corpsecret = PunchCard_Corpsecret; //打卡
- cacheName = "PunchCard_Access_Token";
- }
- else if (applicationType == 3)
- {
- access_Token.corpsecret = Email_Corpsecret; //E-Mail
- cacheName = "Enail_Access_Token";
- }
- else if (applicationType == 4) //通讯录同步
- {
- access_Token.corpsecret = AddressBook_Corpsecret;
- cacheName = "AddressBook_Access_Token";
- }
- else if (applicationType == 5) //审批
- {
- access_Token.corpsecret = Approve_Corpsecret;
- cacheName = "Approve_Access_Token";
- }
- else if (applicationType == 6) //团组状态通知
- {
- access_Token.corpsecret = GroupStatus_Corpsecret;
- cacheName = "GroupStatus_Access_Token";
- }
- else
- {
- tokenResult.errmsg = "未识别应用类型Id!";
- return tokenResult;
- }
- string access_token = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<string>(cacheName);//string 取
- if (string.IsNullOrEmpty(access_token))
- {
- string access_token_url = string.Format(@"/cgi-bin/gettoken?corpid={0}&corpsecret={1}", access_Token.corpid, access_Token.corpsecret);
- var access_tokenReq = await _httpClient.GetAsync(access_token_url);
- if (access_tokenReq.IsSuccessStatusCode)
- {
- var stringResponse = await access_tokenReq.Content.ReadAsStringAsync();
- tokenResult = System.Text.Json.JsonSerializer.Deserialize<Access_TokenView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (tokenResult.errcode == 0)
- {
- TimeSpan ts = DateTime.Now.AddMinutes(118) - DateTime.Now; //设置redis 过期时间 118分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>(cacheName, tokenResult.access_token, ts);//string 存
- }
- }
- else
- {
- tokenResult.errmsg = "企业微信Token未获取到!";
- }
- }
- else
- {
- tokenResult.errcode = 0;
- tokenResult.access_token = access_token;
- }
- return tokenResult;
- }
- #region 添加员工
- /// <summary>
- /// 获取成员ID列表
- /// </summary>
- /// <returns></returns>
- public async Task<UserIdListView> GetUserIdListAsync()
- {
- UserIdListView userIdListView = new UserIdListView();
- Access_TokenView access_Token = await GetTokenAsync(4);
- if (access_Token.errcode != 0)
- {
- userIdListView.errcode = access_Token.errcode;
- userIdListView.errmsg = access_Token.errmsg;
- return userIdListView;
- }
- string url = string.Format("/cgi-bin/user/list_id?access_token={0}&debug=1", access_Token.access_token);
- var jsonData = new
- {
- access_token = access_Token.access_token, //调用接口凭证
- };
- var json = System.Text.Json.JsonSerializer.Serialize(jsonData);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- userIdListView = System.Text.Json.JsonSerializer.Deserialize<UserIdListView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return userIdListView;
- }
- /// <summary>
- /// 获取成员信息
- /// </summary>
- /// <returns></returns>
- public async Task<QYWX_UserInfosView> GetUserInfosAsync()
- {
- QYWX_UserInfosView infoViews = new QYWX_UserInfosView();
- //获取员工useridList
- UserIdListView useridView = await GetUserIdListAsync();
- if (useridView.errcode != 0)
- {
- infoViews.errcode = useridView.errcode;
- infoViews.errmsg = useridView.errmsg;
- return infoViews;
- }
- Access_TokenView access_Token = await GetTokenAsync(4);
- if (access_Token.errcode != 0)
- {
- infoViews.errcode = access_Token.errcode;
- infoViews.errmsg = access_Token.errmsg;
- return infoViews;
- }
- List<QYWX_UserInfo> items = new List<QYWX_UserInfo>();
- string urlTitle = string.Format("/cgi-bin/user/get?access_token={0}", access_Token.access_token);
- foreach (var item in useridView.dept_user)
- {
- if (!string.IsNullOrEmpty(item.userid))
- {
- QYWX_UserInfoView _UserInfoView = new QYWX_UserInfoView();
- string url = string.Format("{0}&userid={1}", urlTitle, item.userid);
- var create_Req = await _httpClient.GetAsync(url);
- if (create_Req.IsSuccessStatusCode)
- {
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- _UserInfoView = System.Text.Json.JsonSerializer.Deserialize<QYWX_UserInfoView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (_UserInfoView.errcode == 0)
- {
- items.Add(new QYWX_UserInfo()
- {
- userid = _UserInfoView.QYWX_User.userid,
- name = _UserInfoView.QYWX_User.name,
- mobile = _UserInfoView.QYWX_User.mobile,
- position = _UserInfoView.QYWX_User.position,
- email = _UserInfoView.QYWX_User.email,
- biz_mail = _UserInfoView.QYWX_User.biz_mail,
- });
- }
- }
- }
- }
- infoViews.errcode = 0;
- infoViews.errmsg = "操作成功!";
- infoViews.QYWX_Users = items;
- return infoViews;
- }
- /// <summary>
- /// 获取部门列表
- /// </summary>
- /// <param name="access_token"></param>
- /// <returns></returns>
- private async Task<DepartmentListView> GetDepartmentAsync(string access_token)
- {
- DepartmentListView result = new DepartmentListView();
- string dep_url = string.Format("/cgi-bin/department/list?access_token={0}&debug=1", access_token);
- var depReq = await _httpClient.GetAsync(dep_url);
- if (depReq.IsSuccessStatusCode)
- {
- var stringResponse = await depReq.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<DepartmentListView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- else
- {
- result.errcode = -1;
- result.errmsg = "企业微信部门列表未获取到!";
- }
- return result;
- }
- /// <summary>
- /// 创建员工
- /// </summary>
- /// <param name="create_Request"></param>
- /// <returns></returns>
- public async Task<ResponseBase> CreateAsync(Create_Request create_Request)
- {
- ResponseBase responseBase = new ResponseBase();
- #region 职位
- string depName = string.Empty,
- jobName = string.Empty;
- List<Sys_JobPostI> jobs = await _jobPostRep.QueryJobPost(string.Empty);
- Sys_JobPostI jobPost = jobs.Where(it => it.IsDel == 0 && it.Id == Convert.ToInt32(create_Request.position)).FirstOrDefault();
- if (jobPost != null)
- {
- depName = jobPost.DepName;
- jobName = jobPost.JobName;
- }
- create_Request.position = jobName;
- if (string.IsNullOrEmpty(create_Request.biz_mail))
- {
- create_Request.biz_mail = string.Format("{0}@pan-american-intl.com", create_Request.userid);
- }
- #endregion
- Access_TokenView access_Token = new Access_TokenView();
- access_Token = await GetTokenAsync(4);
- if (access_Token.errcode == 0)
- {
- create_Request.access_token = access_Token.access_token;
- #region 处理部门
- Access_TokenView dep_Access_Token = await GetTokenAsync(1);
- if (dep_Access_Token.errcode != 0)
- {
- responseBase.errcode = dep_Access_Token.errcode;
- responseBase.errmsg = dep_Access_Token.errmsg;
- }
- DepartmentListView depData = await GetDepartmentAsync(dep_Access_Token.access_token);
- if (depData.errcode == 0)
- {
- var depData1 = depData.department.Where(x => x.name == depName).FirstOrDefault();
- if (depData1 != null)
- {
- create_Request.department = new List<long> { depData1.id };
- }
- else
- {
- responseBase.errcode = -1;
- responseBase.errmsg = "未在企业微信上找到OA内设置的部门";
- return responseBase;
- }
- }
- else
- {
- responseBase.errcode = depData.errcode;
- responseBase.errmsg = depData.errmsg;
- return responseBase;
- }
- #endregion
- create_Request.access_token = access_Token.access_token;
- string create_url = string.Format("/cgi-bin/user/create?access_token={0}", create_Request.access_token);
- var json = System.Text.Json.JsonSerializer.Serialize(create_Request);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(create_url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- responseBase = System.Text.Json.JsonSerializer.Deserialize<ResponseBase>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- else
- {
- responseBase.errcode = access_Token.errcode;
- responseBase.errmsg = access_Token.errmsg;
- }
- return responseBase;
- }
- #endregion
- #region 打卡
- /// <summary>
- /// 获取企业所有打卡规则
- /// </summary>
- /// <returns></returns>
- public async Task<CorpCheckInRuleView> GetCheckIn_CorpCheckInOptionAsync()
- {
- CorpCheckInRuleView corpCheckInRuleView = new CorpCheckInRuleView();
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- corpCheckInRuleView.errcode = access_Token.errcode;
- corpCheckInRuleView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return corpCheckInRuleView;
- }
- string url = string.Format("/cgi-bin/checkin/getcorpcheckinoption?access_token={0}", access_Token.access_token);
- var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- corpCheckInRuleView = System.Text.Json.JsonSerializer.Deserialize<CorpCheckInRuleView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return corpCheckInRuleView;
- }
- /// <summary>
- /// 获取月打卡记录数据
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInView> GetCheckin_MonthDataAsync1(DateTime startDt, DateTime endDt)
- {
- CheckInView checkInView = new CheckInView();
- //获取员工Id
- UserIdListView userIdListView = await GetUserIdListAsync();
- if (userIdListView.errcode != 0)
- {
- checkInView.errcode = userIdListView.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
- return checkInView;
- }
- if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
- {
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
- return checkInView;
- }
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInView.errcode = access_Token.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
- checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid!).ToList();
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return checkInView;
- }
- /// <summary>
- /// 获取月打卡记录数据
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInView> GetCheckin_MonthDataAsync(DateTime startDt, DateTime endDt)
- {
- CheckInView checkInView = new CheckInView();
- //获取员工Id
- UserIdListView userIdListView = await GetUserIdListAsync();
- if (userIdListView.errcode != 0)
- {
- checkInView.errcode = userIdListView.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
- return checkInView;
- }
- if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
- {
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
- return checkInView;
- }
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInView.errcode = access_Token.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInView;
- }
- #region 处理超31天的月报表数据
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
- checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid ?? "").ToList();
- uint starttimeOne, endtimeOne, starttimeTwo, endtimeTwo;
- int days = (int)(endDt - startDt).TotalDays;
- if (days > 32)
- {
- starttimeOne = (uint)((startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- endtimeOne = (uint)((startDt.AddDays(31).ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- starttimeTwo = (uint)((startDt.AddDays(32).ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- endtimeTwo = (uint)((endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- checkInReq.starttime = starttimeOne;
- checkInReq.endtime = endtimeOne;
- CheckInView checkInViewOne = new CheckInView();
- var jsonOne = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var contentOne = new StringContent(jsonOne, Encoding.UTF8, "application/json");
- var create_ReqOne = await _httpClient.PostAsync(url, contentOne);
- var stringResponseOne = await create_ReqOne.Content.ReadAsStringAsync();
- checkInViewOne = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponseOne,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInViewOne.errcode != 0)
- {
- return checkInViewOne;
- }
- checkInReq.starttime = starttimeTwo;
- checkInReq.endtime = endtimeTwo;
- CheckInView checkInViewTwo = new CheckInView();
- var jsonTwo = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var contentTwo = new StringContent(jsonTwo, Encoding.UTF8, "application/json");
- var create_ReqTwo = await _httpClient.PostAsync(url, contentTwo);
- var stringResponseTwo = await create_ReqTwo.Content.ReadAsStringAsync();
- checkInViewTwo = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponseTwo,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInViewTwo.errcode != 0)
- {
- return checkInViewTwo;
- }
- #region 整合月报表数据
- foreach (var item_one in checkInViewOne.datas)
- {
- foreach (var item_two in checkInViewTwo.datas)
- {
- if (item_one.base_info.acctid.Equals(item_two.base_info.acctid))
- {
- #region summary_info 汇总信息整合
- item_one.summary_info.work_days += item_two.summary_info.work_days; //应打卡天数
- item_one.summary_info.regular_days += item_two.summary_info.regular_days; //正常天数
- item_one.summary_info.except_days += item_two.summary_info.except_days; //异常天数
- item_one.summary_info.regular_work_sec += item_two.summary_info.regular_work_sec; //实际工作时长,为统计周期每日实际工作时长之和
- item_one.summary_info.standard_work_sec += item_two.summary_info.standard_work_sec; //标准工作时长,为统计周期每日标准工作时长之和
- #endregion
- #region exception_infos 异常状态统计信息 整合
- item_one.exception_infos.AddRange(item_two.exception_infos);
- #endregion
- #region sp_items 假勤统计信息整合
- item_one.sp_items.AddRange(item_two.sp_items);
- #endregion
- #region overwork_info 加班情况 整合
- item_one.overwork_info.workday_over_sec += item_two.overwork_info.workday_over_sec; //工作日加班时长
- item_one.overwork_info.holidays_over_sec += item_two.overwork_info.holidays_over_sec; //节假日加班时长
- item_one.overwork_info.restdays_over_sec += item_two.overwork_info.restdays_over_sec; //休息日加班时长
- #endregion
- break;
- }
- }
- }
- #endregion
- checkInView = checkInViewOne;
- }
- else
- {
- checkInReq.starttime = (uint)((startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- checkInReq.endtime = (uint)((endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- #endregion
- return checkInView;
- }
- /// <summary>
- /// 获取月打卡数据(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInView> GetCheckin_MonthDataRedisAsync(DateTime startDt, DateTime endDt)
- {
- CheckInView checkInView = new CheckInView();
- string checkInDatastring = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<string>("Checkin_MonthData");//List<T> 取
- if (!string.IsNullOrEmpty(checkInDatastring))
- {
- checkInView = JsonConvert.DeserializeObject<CheckInView>(checkInDatastring);
- return checkInView;
- }
- //获取员工Id
- UserIdListView userIdListView = await GetUserIdListAsync();
- if (userIdListView.errcode != 0)
- {
- checkInView.errcode = userIdListView.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
- return checkInView;
- }
- if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
- {
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
- return checkInView;
- }
- //获取月打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInView.errcode = access_Token.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
- checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid!).ToList();
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInView.errcode == 0)
- {
- TimeSpan ts = DateTime.Now.AddMinutes(60) - DateTime.Now; //设置redis 过期时间 60分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>("Checkin_MonthData", JsonConvert.SerializeObject(checkInView), ts);//List<T> 存
- }
- return checkInView;
- }
- public async Task<object> QueryAssessmentByUser(DateTime startDt, DateTime endDt, List<string> qiyeUidList)
- {
- AssessmentByUserListView assessmentByUserListView = new AssessmentByUserListView();
- List<AssessmentByUserView> AssessmentByUserView = new List<AssessmentByUserView>();
- assessmentByUserListView.Data = AssessmentByUserView;
- assessmentByUserListView.errcode = 0;
- assessmentByUserListView.errmsg = "成功";
- CheckInView? checkInView = new CheckInView();
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- assessmentByUserListView.errcode = access_Token.errcode;
- assessmentByUserListView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return assessmentByUserListView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
- checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- checkInReq.useridlist = qiyeUidList;
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInView == null)
- {
- assessmentByUserListView.errcode = -1;
- assessmentByUserListView.errmsg = "checkInView Deserialize Error";
- return assessmentByUserListView;
- }
- if (checkInView.errcode != 0)
- {
- assessmentByUserListView.errcode = checkInView.errcode;
- assessmentByUserListView.errmsg = checkInView.errmsg;
- return assessmentByUserListView;
- }
- var errorUserList = new List<string>();
- //遍历用户数据
- foreach (var item in checkInView.datas)
- {
- //有异常状态的情况下获取具体异常信息
- if (item.summary_info.except_days > 0)
- {
- errorUserList.Add(item.base_info.acctid);
- }
- assessmentByUserListView.Data.Add(new Domain.ViewModels.QiYeWeChat.AssessmentByUserView
- {
- Accid = item.base_info.acctid,
- Except_days = item.summary_info.except_days,
- Name = item.base_info.name,
- Regular_days = item.summary_info.regular_days,
- Exception_info_List = new List<Exception_info>(),
- Work_days = item.summary_info.work_days
- });
- }
- if (errorUserList.Count > 0) {
- var dayInfo = await GetCheckinDataAsync(errorUserList, 3, startDt, endDt);
- if (dayInfo.errcode != 0)
- {
- assessmentByUserListView.errcode = dayInfo.errcode;
- assessmentByUserListView.errmsg = dayInfo.errmsg;
- assessmentByUserListView.Data = new List<AssessmentByUserView>();
- return assessmentByUserListView;
- }
- var dic = new Dictionary<ErrorType, List<string>>()
- {
- { ErrorType.迟到 , new List<string>{ "时间异常" } },
- { ErrorType.缺卡 , new List<string>{ "未打卡" } },
- };
- foreach (var item in dayInfo.checkindata)
- {
- foreach (var user in assessmentByUserListView.Data)
- {
- if (user.Accid == item.userid)
- {
- //遍历异常信息
- if (!item.exception_type.IsNullOrWhiteSpace())
- {
- var linqFind = dic.First(x => x.Value.Contains(item.exception_type));
- var errinfo = new Exception_info
- {
- Date = item.checkin_time_dt,
- Type = linqFind.Key,
- Info = item.exception_type
- };
- user.Exception_info_List.Add(errinfo);
- }
- }
- }
- }
- }
- return assessmentByUserListView;
- }
- /// <summary>
- /// 获取打卡记录数据
- /// </summary>
- /// <param name="useridlist">需要获取打卡记录的用户列表</param>
- /// <param name="opencheckindatatype">打卡类型。1:上下班打卡;2:外出打卡;3:全部打卡</param>
- /// <param name="startDt">获取打卡记录的开始时间。Unix时间戳</param>
- /// <param name="endDt">获取打卡记录的结束时间。Unix时间戳</param>
- /// <returns></returns>
- public async Task<CheckInDataView> GetCheckinDataAsync(List<string> useridlist, int opencheckindatatype, DateTime startDt, DateTime endDt)
- {
- CheckInDataView checkInDataView = new CheckInDataView();
- //参数处理
- if (useridlist.Count <= 0)
- {
- checkInDataView.errmsg = "请填写企业微信用户id,可为多个!";
- return checkInDataView;
- }
- if (useridlist.Count > 100)
- {
- checkInDataView.errmsg = "用户列表不超过100个。若用户超过100个,请分批获取!";
- return checkInDataView;
- }
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInDataView.errcode = access_Token.errcode;
- checkInDataView.errmsg = string.Format("【企业微信】【获取打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInDataView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckindata?access_token={0}", access_Token.access_token);
- DateTime centerDt = startDt.AddDays(30);
- long startTs = (long)(startDt - _1970).TotalSeconds;
- long centerTs = (long)(centerDt - _1970).TotalSeconds;
- long endTs = (long)(endDt - _1970).TotalSeconds;
- CheckInData_Request checkInData_Req = new CheckInData_Request()
- {
- access_token = access_Token.access_token,
- opencheckindatatype = opencheckindatatype,
- useridlist = useridlist,
- starttime = startTs,
- endtime = centerTs
- };
- var json = System.Text.Json.JsonSerializer.Serialize(checkInData_Req);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInDataView = System.Text.Json.JsonSerializer.Deserialize<CheckInDataView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (centerDt < endDt)
- {
- checkInData_Req.starttime = centerTs;
- checkInData_Req.endtime = endTs;
- var json1 = System.Text.Json.JsonSerializer.Serialize(checkInData_Req);
- var content1 = new StringContent(json1, Encoding.UTF8, "application/json");
- var create_Req1 = await _httpClient.PostAsync(url, content1);
- var stringResponse1 = await create_Req1.Content.ReadAsStringAsync();
- CheckInDataView checkInDataView1 = System.Text.Json.JsonSerializer.Deserialize<CheckInDataView>(stringResponse1,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInDataView1.errcode != 0)
- {
- return checkInDataView1;
- }
- checkInDataView.checkindata.AddRange(checkInDataView1.checkindata);
- return checkInDataView;
- }
- return checkInDataView;
- }
- /// <summary>
- /// 获取打卡日报数据
- /// </summary>
- /// <param name="useridlist"></param>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInDayDataView> GetCheckInDayDataAsync1(List<string> useridlist, DateTime startDt, DateTime endDt)
- {
- CheckInDayDataView checkInDayDataView = new CheckInDayDataView();
- //参数处理
- if (useridlist.Count <= 0)
- {
- checkInDayDataView.errmsg = "请填写企业微信用户id,可为多个!";
- return checkInDayDataView;
- }
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInDayDataView.errcode = access_Token.errcode;
- checkInDayDataView.errmsg = string.Format("【企业微信】【获取打卡日报数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInDayDataView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_daydata?access_token={0}&debug=1", access_Token.access_token);
- long startTs = (startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- long endTs = (endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- var checkInData_Req = new
- {
- access_token = access_Token.access_token,
- useridlist = useridlist,
- starttime = startTs,
- endtime = endTs
- };
- var json = System.Text.Json.JsonSerializer.Serialize(checkInData_Req);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInDayDataView = System.Text.Json.JsonSerializer.Deserialize<CheckInDayDataView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return checkInDayDataView;
- }
- /// <summary>
- /// 获取打卡日报数据
- /// </summary>
- /// <param name="useridlist"></param>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInDayDataView> GetCheckInDayDataAsync(List<string> useridlist, DateTime startDt, DateTime endDt)
- {
- CheckInDayDataView checkInDayDataView = new CheckInDayDataView();
- //参数处理
- if (useridlist.Count <= 0)
- {
- checkInDayDataView.errmsg = "请填写企业微信用户id,可为多个!";
- return checkInDayDataView;
- }
- //获取打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInDayDataView.errcode = access_Token.errcode;
- checkInDayDataView.errmsg = string.Format("【企业微信】【获取打卡日报数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInDayDataView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_daydata?access_token={0}&debug=1", access_Token.access_token);
- int days = (int)(endDt - startDt).TotalDays;
- if (days > 31)
- {
- long startTs_One = (startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- long endTs_One = (startDt.AddDays(31).ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- long startTs_Two = (startDt.AddDays(31).ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- long endTs_Two = (endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- var checkInData_ReqOne = new
- {
- access_token = access_Token.access_token,
- useridlist = useridlist,
- starttime = startTs_One,
- endtime = endTs_One
- };
- var jsonOne = System.Text.Json.JsonSerializer.Serialize(checkInData_ReqOne);
- var contentOne = new StringContent(jsonOne, Encoding.UTF8, "application/json");
- var create_ReqOne = await _httpClient.PostAsync(url, contentOne);
- var stringResponseOne = await create_ReqOne.Content.ReadAsStringAsync();
- CheckInDayDataView checkInDayDataViewOne = System.Text.Json.JsonSerializer.Deserialize<CheckInDayDataView>(stringResponseOne,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInDayDataViewOne.errcode != 0)
- {
- return checkInDayDataViewOne;
- }
- var checkInData_ReqTwo = new
- {
- access_token = access_Token.access_token,
- useridlist = useridlist,
- starttime = startTs_Two,
- endtime = endTs_Two
- };
- var jsonTwo = System.Text.Json.JsonSerializer.Serialize(checkInData_ReqTwo);
- var contentTwo = new StringContent(jsonTwo, Encoding.UTF8, "application/json");
- var create_ReqTwo = await _httpClient.PostAsync(url, contentTwo);
- var stringResponseTwo = await create_ReqTwo.Content.ReadAsStringAsync();
- CheckInDayDataView checkInDayDataViewTwo = System.Text.Json.JsonSerializer.Deserialize<CheckInDayDataView>(stringResponseTwo,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInDayDataViewTwo.errcode != 0)
- {
- return checkInDayDataViewTwo;
- }
- checkInDayDataViewOne.datas.AddRange(checkInDayDataViewTwo.datas);
- return checkInDayDataViewOne;
- }
- else
- {
- long startTs = (startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- long endTs = (endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- var checkInData_Req = new
- {
- access_token = access_Token.access_token,
- useridlist = useridlist,
- starttime = startTs,
- endtime = endTs
- };
- var json = System.Text.Json.JsonSerializer.Serialize(checkInData_Req);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInDayDataView = System.Text.Json.JsonSerializer.Deserialize<CheckInDayDataView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- return checkInDayDataView;
- }
- #endregion
- #region 审批
- /// <summary>
- /// 获取审批数据(旧)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<ApprovalDataView> GetApprovalDataAsync(DateTime startDt, DateTime endDt)
- {
- ApprovalDataView approvalDataView = new ApprovalDataView();
- //获取审批数据 token
- Access_TokenView access_Token = await GetTokenAsync(5);
- if (access_Token.errcode != 0)
- {
- approvalDataView.errcode = access_Token.errcode;
- approvalDataView.errmsg = string.Format("【企业微信】【获取审批数据】【Token】【Msg】{0}", access_Token.errmsg);
- return approvalDataView;
- }
- string url = string.Format("/cgi-bin/corp/getapprovaldata?access_token={0}", access_Token.access_token);
- ApprovalData_Request approvalDataReq = new ApprovalData_Request();
- approvalDataReq.access_token = access_Token.access_token;
- approvalDataReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- approvalDataReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- var json = System.Text.Json.JsonSerializer.Serialize(approvalDataReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- approvalDataView = System.Text.Json.JsonSerializer.Deserialize<ApprovalDataView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- List<Sp_Info> sp_datas = new List<Sp_Info>();
- sp_datas.AddRange(approvalDataView.data);
- int index = 0;
- //多次访问审批接口
- if (approvalDataView.total >= 100)
- {
- approvalDataView.total -= 100;
- int forTotal = approvalDataView.total % 100 == 0 ? approvalDataView.total / 100 : approvalDataView.total / 100 + 1;
- long? next_spnum = approvalDataView.next_spnum;
- approvalDataReq.next_spnum = next_spnum;
- for (int i = 0; i < forTotal; i++)
- {
- index++;
- var for_json = System.Text.Json.JsonSerializer.Serialize(approvalDataReq);
- var for_content = new StringContent(for_json, Encoding.UTF8, "application/json");
- var for_create_Req = await _httpClient.PostAsync(url, for_content);
- var for_stringResponse = await for_create_Req.Content.ReadAsStringAsync();
- ApprovalDataView for_approvalDataView = System.Text.Json.JsonSerializer.Deserialize<ApprovalDataView>(for_stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- approvalDataReq.next_spnum = for_approvalDataView.next_spnum; //重新定义游标
- sp_datas.AddRange(for_approvalDataView.data); //追加数据
- }
- approvalDataView.total += 100;
- }
- approvalDataView.data = sp_datas;
- return approvalDataView;
- }
- /// <summary>
- /// 获取审批数据(旧)(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<List<Sp_Info>> GetApprovalDatasAsync(DateTime startDt, DateTime endDt)
- {
- List<Sp_Info> sp_Infos = new List<Sp_Info>();
- //获取所有打卡补卡,审批 数据 前后范围增加10天
- DateTime sp_startDt = startDt.AddDays(-10);
- DateTime sp_centerDt = sp_startDt.AddDays(30);
- DateTime sp_endDt = endDt.AddDays(10);
- ApprovalDataView approvalData_1 = await GetApprovalDataAsync(sp_startDt, sp_centerDt); //时间段内所有 审批数据
- ApprovalDataView approvalData_2 = await GetApprovalDataAsync(sp_centerDt, sp_endDt); //时间段内所有 审批数据
- if (approvalData_1.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_startDt + " - " + sp_centerDt + " 内审批 Msg:" + approvalData_1.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_1.data);
- if (approvalData_2.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_centerDt + " - " + sp_endDt + " 内审批 Msg:" + approvalData_2.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_2.data);
- sp_Infos = sp_Infos.Where(it => it.sp_status == 2).ToList(); //存储已审核的数据
- return sp_Infos;
- }
- /// <summary>
- /// 获取审批数据(旧)(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<List<Sp_Info>> GetApprovalDatasRedisAsync(DateTime startDt, DateTime endDt)
- {
- List<Sp_Info> sp_Infos = new List<Sp_Info>();
- //获取所有打卡补卡,审批 数据 前后范围增加10天
- DateTime sp_startDt = startDt.AddDays(-10);
- DateTime sp_centerDt = sp_startDt.AddDays(30);
- DateTime sp_endDt = endDt.AddDays(10);
- string redisName = "ApprovalData" + sp_startDt.ToString("yyyyMMdd") + "-" + sp_endDt.ToString("yyyyMMdd");
- string sp_InfosString = string.Empty;
- //sp_InfosString = await RedisRepository.RedisFactory
- // .CreateRedisRepository()
- // .StringGetAsync<string>(redisName);//string 取
- if (string.IsNullOrEmpty(sp_InfosString))
- {
- ApprovalDataView approvalData_1 = await GetApprovalDataAsync(sp_startDt, sp_centerDt); //时间段内所有 审批数据
- ApprovalDataView approvalData_2 = await GetApprovalDataAsync(sp_centerDt, sp_endDt); //时间段内所有 审批数据
- if (approvalData_1.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_startDt + " - " + sp_centerDt + " 内审批 Msg:" + approvalData_1.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_1.data);
- if (approvalData_2.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_centerDt + " - " + sp_endDt + " 内审批 Msg:" + approvalData_2.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_2.data);
- sp_Infos = sp_Infos.Where(it => it.sp_status == 2).ToList(); //存储已审核的数据
- TimeSpan ts = DateTime.Now.AddMinutes(60) - DateTime.Now; //设置redis 过期时间 60分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>(redisName, JsonConvert.SerializeObject(sp_Infos), ts);//string 存
- }
- else
- {
- sp_Infos = JsonConvert.DeserializeObject<List<Sp_Info>>(sp_InfosString);
- }
- return sp_Infos;
- }
- /// <summary>
- /// 批量获取审批单号
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <param name="creator">
- /// 申请人
- /// </param>
- /// <param name="sp_status">
- /// sp_status-审批单状态(1-审批中;2-已通过;3-已驳回;4-已撤销;6-通过后撤销;7-已删除;10-已支付)
- /// </param>
- /// <param name="record_type">
- /// record_type == 0 ALL 有值 请填写对应值
- /// record_type - 审批单类型属性,1-请假;2-打卡补卡;3-出差;4-外出;5-加班; 6- 调班;7-会议室预定;8-退款审批;9-红包报销审批
- /// </param>
- /// <returns></returns>
- private async Task<ApprovalInfoView> GetApprovalInfoAsync(DateTime startDt, DateTime endDt, string creator, int sp_status, int record_type)
- {
- Stopwatch sw = new Stopwatch();
- sw.Start();
- ApprovalInfoView approvalInfoView = new ApprovalInfoView();
- //获取所有打卡补卡,审批 数据 向前增加30天 向后范围增加15天
- DateTime sp_startDt = startDt.AddDays(-30);
- DateTime sp_endDt = endDt.AddDays(15);
- //获取审批数据 token
- Access_TokenView access_Token = await GetTokenAsync(5);
- if (access_Token.errcode != 0)
- {
- approvalInfoView.errcode = access_Token.errcode;
- approvalInfoView.errmsg = string.Format("【企业微信】【批量获取审批单号】【Token】【Msg】{0}", access_Token.errmsg);
- return approvalInfoView;
- }
- string url = string.Format("/cgi-bin/oa/getapprovalinfo?access_token={0}", access_Token.access_token);
- List<Dic> filters = new List<Dic> {
- new Dic() { key = "creator", value = creator }, //筛选条件 申请人
- new Dic() { key = "sp_status", value = sp_status.ToString() }, //筛选条件 审核状态 2 已同意
- };
- if (record_type != 0)
- {
- filters.Add(new Dic() { key = "record_type", value = record_type.ToString() }); //筛选条件 审批单类型 请假 1
- }
- int days = (sp_endDt - sp_startDt).Days;
- decimal runCount = days % 30;
- int runCount1 = 0;
- if (runCount == 0) runCount1 = (int)(days % 30.00M);
- else runCount1 = (int)Math.Ceiling(days / 30.00M);
- List<string> sp_no_lists = new List<string>();
- for (int i = 0; i < runCount1; i++)
- {
- DateTime for_sp_startDt = sp_startDt;
- DateTime for_sp_endDt = sp_startDt.AddDays(30);
- sp_startDt = sp_startDt.AddDays(30);
- if (for_sp_endDt >= sp_endDt)
- {
- for_sp_endDt = sp_endDt;
- }
- ApprovalInfo_Request approvalInfoReq = new ApprovalInfo_Request()
- {
- access_token = access_Token.access_token,
- starttime = (uint)ConvertToTimeSpan(for_sp_startDt),
- endtime = (uint)ConvertToTimeSpan(for_sp_endDt),
- filters = filters.ToList(),
- };
- var json = System.Text.Json.JsonSerializer.Serialize(approvalInfoReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- ApprovalInfoView approvalInfoView1 = System.Text.Json.JsonSerializer.Deserialize<ApprovalInfoView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- #region 分页调用 new_next_cursor != null
- string new_cursor = approvalInfoView1.new_next_cursor;
- while (!string.IsNullOrEmpty(new_cursor))
- {
- approvalInfoReq.new_cursor = new_cursor;
- var json1 = System.Text.Json.JsonSerializer.Serialize(approvalInfoReq);
- var content1 = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req1 = await _httpClient.PostAsync(url, content1);
- var stringResponse1 = await create_Req1.Content.ReadAsStringAsync();
- ApprovalInfoView approvalInfoView11 = System.Text.Json.JsonSerializer.Deserialize<ApprovalInfoView>(stringResponse1,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (approvalInfoView11.errcode != 0)
- {
- return approvalInfoView1;
- }
- new_cursor = approvalInfoView11.new_next_cursor;
- if (approvalInfoView11.sp_no_list.Count > 0 || approvalInfoView11.sp_no_list != null)
- {
- sp_no_lists.AddRange(approvalInfoView1.sp_no_list);
- }
- }
- #endregion
- if (approvalInfoView1.errcode != 0)
- {
- return approvalInfoView1;
- }
- if (approvalInfoView1.sp_no_list.Count > 0 || approvalInfoView1.sp_no_list != null)
- {
- sp_no_lists.AddRange(approvalInfoView1.sp_no_list);
- }
- }
- approvalInfoView.errcode = 0;
- if (sp_no_lists.Count > 0)
- {
- sp_no_lists = sp_no_lists.Distinct().ToList();
- }
- approvalInfoView.sp_no_list = sp_no_lists;
- sw.Stop();
- approvalInfoView.errmsg = approvalInfoView.errmsg + " 耗时:" + sw.Elapsed.TotalMilliseconds + "ms";
- return approvalInfoView;
- }
- /// <summary>
- /// 获取审批申请详情
- /// </summary>
- /// <param name="sp_no"></param>
- /// <returns></returns>
- public async Task<ApprovalDetailView> GetApprovalDetailAsync(string sp_no)
- {
- ApprovalDetailView ApprovalDetailView = new ApprovalDetailView();
- if (string.IsNullOrEmpty(sp_no))
- {
- return ApprovalDetailView;
- }
- //获取审批数据 token
- Access_TokenView access_Token = await GetTokenAsync(5);
- if (access_Token.errcode != 0)
- {
- ApprovalDetailView.errcode = access_Token.errcode;
- ApprovalDetailView.errmsg = string.Format("【企业微信】【审批申请详情】【Token】【Msg】{0}", access_Token.errmsg);
- return ApprovalDetailView;
- }
- string url = string.Format("/cgi-bin/oa/getapprovaldetail?access_token={0}", access_Token.access_token);
- ApprovalDetail_Request approvalDetail_Req = new ApprovalDetail_Request()
- {
- access_token = access_Token.access_token,
- sp_no = sp_no,
- };
- var json = System.Text.Json.JsonSerializer.Serialize(approvalDetail_Req);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- ApprovalDetailView = System.Text.Json.JsonSerializer.Deserialize<ApprovalDetailView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return ApprovalDetailView;
- }
- /// <summary>
- /// 批量获取审批详情
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <param name="creator">
- /// 申请人
- /// </param>
- /// <param name="sp_status">
- /// sp_status-审批单状态(1-审批中;2-已通过;3-已驳回;4-已撤销;6-通过后撤销;7-已删除;10-已支付)
- /// </param>
- /// <param name="record_type">
- /// record_type - 审批单类型属性,1-请假;2-打卡补卡;3-出差;4-外出;5-加班; 6- 调班;7-会议室预定;8-退款审批;9-红包报销审批
- /// </param>
- /// <returns></returns>
- public async Task<List<Sp_Detail>> GetApprovalDetailsAsync(DateTime startDt, DateTime endDt, string creator, int sp_status, int record_type)
- {
- Stopwatch sw = new Stopwatch();
- sw.Start();
- List<Sp_Detail> details = new List<Sp_Detail>();
- if (string.IsNullOrEmpty(creator))
- {
- return details;
- }
- ApprovalInfoView approvalInfoView = new ApprovalInfoView();
- approvalInfoView = await GetApprovalInfoAsync(startDt, endDt, creator, sp_status, record_type);
- if (approvalInfoView.errcode != 0)
- {
- return details;
- }
- //循环查询详情
- foreach (var item in approvalInfoView.sp_no_list)
- {
- ApprovalDetailView approvalDetailView = new ApprovalDetailView();
- approvalDetailView = await GetApprovalDetailAsync(item);
- if (approvalDetailView.errcode != 0)
- {
- Log.Error("【GetApprovalDetailsAsync】 record_type:" + record_type + " ErrorMsg:" + approvalDetailView.errmsg);
- break;
- }
- details.Add(approvalDetailView.info);
- }
- sw.Stop();
- double hs = sw.Elapsed.TotalMilliseconds;
- return details;
- }
- /// <summary>
- /// 获取审批模板详情
- /// </summary>
- /// <param name="template_id">模板Id</param>
- /// <returns></returns>
- public async Task<TemplateDetailView> GetTemplateDetailAsync(string template_id)
- {
- TemplateDetailView templateDetailView = new TemplateDetailView();
- if (string.IsNullOrEmpty(template_id))
- {
- templateDetailView.errmsg = "template_id为空!";
- return templateDetailView;
- }
- //获取审批数据 token
- Access_TokenView access_Token = await GetTokenAsync(5);
- if (access_Token.errcode != 0)
- {
- templateDetailView.errcode = access_Token.errcode;
- templateDetailView.errmsg = string.Format("【企业微信】【审批申请详情】【Token】【Msg】{0}", access_Token.errmsg);
- return templateDetailView;
- }
- string url = string.Format("/cgi-bin/oa/gettemplatedetail?access_token={0}", access_Token.access_token);
- var approvalDetail_Req = new
- {
- access_token = access_Token.access_token,
- template_id = template_id,
- };
- var json = System.Text.Json.JsonSerializer.Serialize(approvalDetail_Req);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- templateDetailView = System.Text.Json.JsonSerializer.Deserialize<TemplateDetailView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return templateDetailView;
- }
- #endregion
- #region hook机器人
- /// <summary>
- /// 发送团组信息给财务群
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public async Task<ResponseBase> RobotSendMsg_GroupInfo(string msg)
- {
- string key = "b4fe152f-a97a-48b1-830f-ab447f6d2f5f";
- string url = string.Format("/cgi-bin/webhook/send?key={0}", key);
- RobotSendMsg_GroupInfo_Content contentStr = new RobotSendMsg_GroupInfo_Content() { content = msg };
- RobotSendMsg_GroupInfo_Param reqJson = new RobotSendMsg_GroupInfo_Param()
- {
- msgtype = "markdown",
- markdown = contentStr
- };
- var json = System.Text.Json.JsonSerializer.Serialize(reqJson);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- ResponseBase sendMsgView = System.Text.Json.JsonSerializer.Deserialize<ResponseBase>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return sendMsgView;
- }
- #endregion
- #region 团组状态通知
- /// <summary>
- /// 获取部门成员
- /// </summary>
- /// <param name="departmentId"></param>
- /// <returns></returns>
- public async Task<GroupStatus_UserSimplelistView> GroupStatus_GetUserList(int departmentId = 8402038)
- {
- GroupStatus_UserSimplelistView result = new GroupStatus_UserSimplelistView();
- Access_TokenView access_Token = await GetTokenAsync(6);
- if (access_Token.errcode != 0)
- {
- result.errcode = access_Token.errcode;
- result.errmsg = string.Format("【企业微信】【团组状态通知】【Token】【Msg】{0}", access_Token.errmsg);
- return result;
- }
- string url = string.Format("/cgi-bin/user/simplelist?access_token={0}&department_id={1}", access_Token.access_token, departmentId);
- var simplelist_Req = await _httpClient.GetAsync(url);
- if (simplelist_Req.IsSuccessStatusCode)
- {
- var stringResponse = await simplelist_Req.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<GroupStatus_UserSimplelistView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- else
- {
- result.errcode = -1;
- result.errmsg = "企业微信部门列表未获取到!";
- }
- return result;
- }
- /// <summary>
- /// 创建群聊
- /// </summary>
- /// <param name="chatName"></param>
- /// <param name="owner"></param>
- /// <param name="userList"></param>
- /// <param name="chatId"></param>
- /// <returns></returns>
- public async Task<GroupStatus_CreateChatView> GroupStatus_CreateChat(string chatName, string owner, List<string> userList, string chatId)
- {
- GroupStatus_CreateChatView result = new GroupStatus_CreateChatView();
- Access_TokenView access_Token = await GetTokenAsync(6);
- if (access_Token.errcode != 0)
- {
- result.errcode = access_Token.errcode;
- result.errmsg = string.Format("【企业微信】【团组状态通知】【Token】【Msg】{0}", access_Token.errmsg);
- return result;
- }
- GroupStatus_CreateChat reqJson = new GroupStatus_CreateChat()
- {
- chatid = chatId,
- name = chatName,
- owner = owner,
- userlist = userList
- };
- string url = string.Format("/cgi-bin/appchat/create?access_token={0}&debug=1", access_Token.access_token);
- var json = System.Text.Json.JsonSerializer.Serialize(reqJson);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<GroupStatus_CreateChatView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return result;
- }
- /// <summary>
- /// 向群聊发送信息
- /// </summary>
- /// <param name="chatId"></param>
- /// <param name="msgContent"></param>
- /// <param name="msgType"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public async Task<ResponseBase> GroupStatus_SendChatMsg_Markdown(string chatId, string msgContent, string msgType = "markdown")
- {
- ResponseBase result = new ResponseBase();
- Access_TokenView access_Token = await GetTokenAsync(6);
- if (access_Token.errcode != 0)
- {
- result.errcode = access_Token.errcode;
- result.errmsg = string.Format("【企业微信】【团组状态通知】【Token】【Msg】{0}", access_Token.errmsg);
- return result;
- }
- RobotSendMsg_GroupInfo_Content markdown = new RobotSendMsg_GroupInfo_Content() { content = msgContent };
- GroupStatus_AppChatSend_Markdown reqJson = new GroupStatus_AppChatSend_Markdown()
- {
- chatid = chatId,
- msgtype = msgType,
- markdown = markdown
- };
- string url = string.Format("/cgi-bin/appchat/send?access_token={0}", access_Token.access_token);
- var json = System.Text.Json.JsonSerializer.Serialize(reqJson);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<ResponseBase>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return result;
- }
- /// <summary>
- /// 向用户发送Markdown信息
- /// </summary>
- /// <param name="toUser"></param>
- /// <param name="msgContent"></param>
- /// <param name="msgType"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public async Task<GroupStatus_SendMessageView> GroupStatus_SendMessage_ToUser_Markdown(List<string> toUser, string msgContent, string msgType = "markdown")
- {
- GroupStatus_SendMessageView result = new GroupStatus_SendMessageView();
- Access_TokenView access_Token = await GetTokenAsync(6);
- if (access_Token.errcode != 0)
- {
- result.errcode = access_Token.errcode;
- result.errmsg = string.Format("【企业微信】【团组状态通知】【Token】【Msg】{0}", access_Token.errmsg);
- return result;
- }
- RobotSendMsg_GroupInfo_Content markdown = new RobotSendMsg_GroupInfo_Content() { content = msgContent };
- string userIds = "";
- toUser.ForEach(s => userIds += s + "|");
- userIds = userIds.TrimEnd('|');
- GroupStatus_AppSend_Markdown reqJson = new GroupStatus_AppSend_Markdown()
- {
- markdown = markdown,
- touser = userIds
- };
- string url = string.Format("/cgi-bin/message/send?access_token={0}&debug=1", access_Token.access_token);
- var json = System.Text.Json.JsonSerializer.Serialize(reqJson);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<GroupStatus_SendMessageView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return result;
- }
- #endregion
- public long ConvertToTimeSpan(DateTime dt)
- {
- return (dt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
- }
-
- }
- }
|