GroupListService.cs 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. using Azure.Cosmos;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5. using TEAMModelOS.SDK.DI;
  6. using TEAMModelOS.SDK.Extension;
  7. using TEAMModelOS.SDK.Models.Cosmos.Common;
  8. using HTEXLib.COMM.Helpers;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.Json;
  12. using TEAMModelOS.Models;
  13. using Azure.Messaging.ServiceBus;
  14. using Microsoft.Extensions.Configuration;
  15. using TEAMModelOS.SDK.Models.Service;
  16. using System.Text.RegularExpressions;
  17. using TEAMModelOS.SDK.Models;
  18. using System.Net.Http;
  19. using DocumentFormat.OpenXml.Wordprocessing;
  20. using static TEAMModelOS.SDK.GroupListService;
  21. namespace TEAMModelOS.SDK
  22. {
  23. public class GroupListService
  24. {
  25. public static async Task DeleteGrouplistEvent(string id , string code,string tbname ,CosmosClient client, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
  26. {
  27. GroupChange change = new GroupChange();
  28. GroupList groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(id.ToString(), new PartitionKey(code));
  29. var tleave = groupList.members.FindAll(x => x.type == 1);
  30. if (tleave.IsNotEmpty())
  31. {
  32. if (groupList.type.Equals("research") || groupList.type.Equals("yxtrain"))
  33. {
  34. change.tchleave.AddRange(tleave);
  35. }
  36. else
  37. {
  38. change.tmdleave.AddRange(tleave);
  39. }
  40. }
  41. var sleave = groupList.members.FindAll(x => x.type == 2);
  42. if (sleave.IsNotEmpty())
  43. {
  44. change.stuleave.AddRange(sleave);
  45. }
  46. change.listid = groupList.id;
  47. change.scope = groupList.scope;
  48. change.originCode = $"{code}";
  49. change.school = groupList.school;
  50. change.creatorId = groupList.creatorId;
  51. change.type = groupList.type;
  52. change.status = "delete";
  53. if (change.tmdleave.IsNotEmpty() || change.tchleave.IsNotEmpty() || change.stuleave.IsNotEmpty())
  54. {
  55. var messageChange = new ServiceBusMessage(change.ToJsonString());
  56. messageChange.ApplicationProperties.Add("name", "GroupChange");
  57. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  58. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  59. }
  60. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(id.ToString(), new PartitionKey(code));
  61. }
  62. /// <summary>
  63. /// 查询名单成员所在的名单列表,
  64. /// </summary>
  65. /// <param name="_coreAPIHttpService"></param>
  66. /// <param name="client"></param>
  67. /// <param name="_dingDing"></param>
  68. /// <param name="memberId">成员id </param>
  69. /// <param name="memberType">成员类型</param>
  70. /// <param name="school">成员所在的学校 ,可为空</param>
  71. /// <param name="groupTypes">过滤名单的类型集合,不传则是全部</param>
  72. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  73. /// <returns></returns>
  74. public static async Task<List<GroupListGrp>> GetMemberInGroupList(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing, string memberId, int memberType, string school,List<string> groupTypes,int graduate =-1) {
  75. List<GroupListGrp> groupLists = new List<GroupListGrp>();
  76. if (groupTypes.IsEmpty() || groupTypes.Contains("class")) {
  77. if (!string.IsNullOrWhiteSpace(school) && memberType == 2)
  78. {
  79. Student student = null;
  80. try
  81. {
  82. student = await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemAsync<Student>(memberId, new PartitionKey($"Base-{school}"));
  83. }
  84. catch (CosmosException ex) when (ex.Status == 404)
  85. {
  86. return null;
  87. }
  88. if (!string.IsNullOrWhiteSpace(student.classId))
  89. {
  90. try
  91. {
  92. Class clazz = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(student.classId, new PartitionKey($"Class-{school}"));
  93. GroupListGrp groupList = new GroupListGrp
  94. {
  95. id = clazz.id,
  96. code = $"GroupList-{clazz.school}",
  97. name = clazz.name,
  98. periodId = clazz.periodId,
  99. pk = "GroupList",
  100. expire=0,
  101. year = clazz.year,
  102. school = clazz.school,
  103. scope = "school",
  104. type = "class",
  105. no = clazz.no,
  106. leader = clazz.teacher?.id,
  107. graduate=clazz.graduate,
  108. grades= new HashSet<int>() { clazz.year}
  109. };
  110. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  111. if (graduate >= 0 )
  112. {
  113. if (groupList.graduate == graduate) {
  114. groupLists.Add(groupList);
  115. }
  116. }
  117. //全部。
  118. else if(graduate == -1)
  119. {
  120. groupLists.Add(groupList);
  121. }
  122. }
  123. catch (CosmosException ex) when (ex.Status == 404)
  124. {
  125. }
  126. }
  127. }
  128. }
  129. string SummarySql = " c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire,c.qrcodeExpire ,c.qrcodeDays ,c.grades ";
  130. if (groupTypes.IsEmpty() || groupTypes.Contains("teach")) {
  131. //教学班
  132. string teachsql="";
  133. if (!string.IsNullOrWhiteSpace(school) && memberType == 2) {
  134. teachsql= $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='teach' and m.id='{memberId}' and m.code='{school}' and m.type=2 ";
  135. }
  136. if (memberType == 1)
  137. {
  138. teachsql=$"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='teach' and m.id='{memberId}' and m.type=1 ";
  139. }
  140. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  141. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  142. {
  143. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  144. groupLists.Add(new GroupListGrp(item, groupName));
  145. }
  146. //个人名单
  147. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  148. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  149. {
  150. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  151. groupLists.Add(new GroupListGrp(item, groupName));
  152. }
  153. }
  154. if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("research")))
  155. {
  156. //教研组
  157. string teachsql = $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='research' and m.id='{memberId}' and m.type=1 ";
  158. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  159. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  160. {
  161. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  162. groupLists.Add(new GroupListGrp(item, groupName));
  163. }
  164. }
  165. if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("yxtrain")))
  166. {
  167. //研修名单
  168. string teachsql = $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='yxtrain' and m.id='{memberId}' and m.type=1 ";
  169. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  170. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  171. {
  172. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  173. groupLists.Add(new GroupListGrp(item, groupName));
  174. }
  175. }
  176. return groupLists;
  177. }
  178. /// <summary>
  179. ///-1状态异常,0加入成功, 1加入学生或醍摩豆ID为空,2重复加入 ,3不允许跨校加入名单, 4表示个人名单未开放加入,状态=5 ,人数已满。状态=6 ,需要审核通过再加入。状态7 二维码设置已经过期
  180. /// </summary>
  181. /// <param name="client"></param>
  182. /// <param name="_stuListNo"></param>
  183. /// <param name="userid"></param>
  184. /// <param name="type"></param>
  185. /// <param name="school"></param>
  186. /// <returns></returns>
  187. public static async Task<(int status, GroupList stuList,Member member)> CodeJoinList(CosmosClient client,AzureRedisFactory _azureRedis, string _stuListNo, string userid, int type, string school,int year,string name ,string picture,string lang )
  188. {
  189. var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
  190. (int status, GroupList stuList,Member member) data = (-1, null,null);
  191. if (!string.IsNullOrEmpty(school))
  192. {
  193. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryNo,
  194. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  195. {
  196. data = JoinList(item, userid, type, school,year);
  197. break;
  198. }
  199. }
  200. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
  201. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  202. {
  203. if (item.joinLock == 0) {
  204. //状态=4 表示未开放加入。
  205. return (4, item, null) ;
  206. }
  207. if (item.review ==1)
  208. {
  209. //状态=6 ,人数已满,需要审核通过再加入。
  210. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  211. if (now>item.qrcodeExpire)
  212. {
  213. //二维码设置已经过期,只有需要审核的时候才检查二维码过期问题,目的是为了未正式加入人员的缓存
  214. return (7, item, null);
  215. }
  216. else
  217. {
  218. GroupWaitingList waitingList = new GroupWaitingList
  219. {
  220. stuListNo=_stuListNo,
  221. userid=userid,
  222. type=type,
  223. school= school,
  224. year = year,
  225. groupId = item.id,
  226. name = name,
  227. picture = picture,
  228. lang = lang,
  229. qrcodeExpire=item.qrcodeExpire,
  230. groupName= item.name,
  231. applyTime=now
  232. };
  233. string key = $"GroupList:GroupWaitingList:{item.scope}:{item.id}";
  234. string filed = !string.IsNullOrWhiteSpace(school) ? $"{school}_{userid}" : userid;
  235. await _azureRedis.GetRedisClient(8).HashSetAsync(key, filed, waitingList.ToJsonString());
  236. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(item.qrcodeExpire).UtcDateTime);
  237. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{userid}" :$"GroupList:StudentWaitinglist:{userid}" ;
  238. string sutFiled = $"{item.scope}:{item.id}";
  239. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, waitingList.ToJsonString());
  240. //三十天都不登录,则不需要查看申请清单,30*24=720
  241. await _azureRedis.GetRedisClient(8).KeyExpireAsync(stuKey, new TimeSpan(720 , 0, 0));
  242. return (6, item, null);
  243. }
  244. }
  245. if (item.members!=null &&item.limitCount>0 && item.members.Count>=item.limitCount) {
  246. //状态=5 ,人数已满
  247. return (5, item, null);
  248. }
  249. data = JoinList(item, userid, type, school,year);
  250. //TODO 需要考虑已经通过别的途径加入名单,但是缓存数据仍记录数据的问题。 还要考虑手动加入过的。或者在获取名未加入名单成员的临时缓存数据的时候过滤已经加入的。
  251. break;
  252. }
  253. return data;
  254. }
  255. /// <summary>
  256. /// 加入名单等候列表
  257. /// </summary>
  258. public class GroupWaitingList
  259. {
  260. /// <summary>
  261. ///
  262. /// </summary>
  263. public string stuListNo { get; set; }
  264. public string userid { get; set; }
  265. //学生类型,1醍摩豆id,2 校内账号
  266. public int type { get; set; }
  267. public string school { get; set; }
  268. public int year { get; set; }
  269. public string groupId { get; set; }
  270. public string name { get; set; }
  271. public string picture { get; set; }
  272. public string lang { get; set; }
  273. public long qrcodeExpire { get; set; }
  274. public string groupName { get; set; }
  275. public long applyTime{ get; set; }
  276. /// <summary>
  277. /// 申请状态,-1 申请中,0 通过,1 拒绝。
  278. /// </summary>
  279. public int status { get; set; } = -1;
  280. }
  281. public static (int status, GroupList stuList, Member member) JoinList(GroupList stuList, string userid, int type, string school,int year)
  282. {
  283. int status = -1;
  284. if (!string.IsNullOrWhiteSpace(stuList.school) && !string.IsNullOrWhiteSpace(school))
  285. {
  286. if (!stuList.school.Equals(school))
  287. {
  288. status = 3;//不允许跨校加入名单
  289. return (status, stuList,null);
  290. }
  291. }
  292. string irs = string.Empty;
  293. List<string> irsOrder = stuList.members.Select(x => x.irs)?.Where(y => !string.IsNullOrEmpty(y) && Regex.IsMatch(y, @"^\d*$")).OrderBy(x => int.Parse(x)).ToList();
  294. if (!irsOrder.Contains("0"))
  295. {
  296. irsOrder.Insert(0, "0");
  297. }
  298. if (irsOrder != null)
  299. {
  300. if (!irsOrder.Contains("0"))
  301. {
  302. irsOrder.Insert(0, "0");
  303. }
  304. }
  305. else { irsOrder = new List<string>() { "0" }; }
  306. for (int i = 0; i < irsOrder.Count; i++)
  307. {
  308. irs = $"{int.Parse(irsOrder[i]) + 1}";
  309. int index = i + 1;
  310. if (index <= irsOrder.Count - 1)
  311. {
  312. if (!irs.Equals(irsOrder[index]))
  313. {
  314. break;
  315. }
  316. }
  317. }
  318. Member member = null;
  319. if (string.IsNullOrEmpty($"{userid}"))
  320. {
  321. //加入学生或醍摩豆ID为空
  322. status = 1;
  323. }
  324. else
  325. {
  326. if (type == 1)
  327. {
  328. member = stuList.members.Find(x => x.type == 1 && x.id.Equals(userid));
  329. if (member != null)
  330. {
  331. //重复加入
  332. status = 2;
  333. }
  334. else
  335. {
  336. //加入成功
  337. status = 0;
  338. member = new Member { id = userid, type = type, irs = irs, no = irs,year=year };
  339. stuList.members.Add(member);
  340. }
  341. }
  342. else if (type == 2)
  343. {
  344. member = stuList.members.Find(x => x.type == 2 && x.id.Equals(userid) && x.code.Equals(school));
  345. if (member != null)
  346. {
  347. //重复加入
  348. status = 2;
  349. }
  350. else
  351. {
  352. status = 0;
  353. member = new Member { id = userid, code = school, type = type, irs = irs, no = irs, year = year };
  354. stuList.members.Add(member);
  355. }
  356. }
  357. }
  358. return (status, stuList, member);
  359. }
  360. public static async Task<GroupList> UpsertList(GroupList list, AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
  361. {
  362. bool isnew = false;
  363. var client = _azureCosmos.GetCosmosClient();
  364. if (string.IsNullOrEmpty(list.id))
  365. {
  366. list.id = Guid.NewGuid().ToString();
  367. isnew = true;
  368. }
  369. string tbname = list.scope.Equals("private") ? "Teacher" : "School";
  370. var tmembers = list.members.Where(x => x.type == 1);
  371. var smembers = list.members.Where(x => x.type == 2);
  372. //处理年级
  373. HashSet<int> grades = new HashSet<int>();
  374. if (smembers.Any()) {
  375. grades = smembers.Where(z => z.year > 2000).Select(z=>z.year).ToHashSet();
  376. }
  377. list.grades = grades;
  378. list.scount = smembers.Count();
  379. list.tcount = tmembers.Count();
  380. //if (smembers.Count() > 0 && smembers.Select(x => x.code).ToHashSet().Count()>=2) {
  381. // //处理移除多个学校的名单,只保留一个学校的。
  382. // if (string.IsNullOrWhiteSpace(list.school))
  383. // {
  384. // HashSet<string> codes = smembers.Select(x => x.code).ToHashSet();
  385. // list.school = codes.First();
  386. // codes.Remove(codes.First());
  387. // list.members.RemoveAll(x => codes.Contains(x.code));
  388. // }
  389. // else {
  390. // list.members.RemoveAll(x => !x.code.Equals(list.school));
  391. // }
  392. //}
  393. if (string.IsNullOrWhiteSpace(list.school) && smembers.Count() >= 1)
  394. {
  395. list.school = smembers.First().code;
  396. }
  397. if (!string.IsNullOrWhiteSpace(list.school) && smembers.Count() == 0 && list.scope.Equals("private"))
  398. {
  399. list.school = null;
  400. }
  401. //学生名单,教研组会触发活动中间表刷新
  402. if (list.type.Equals("teach") || list.type.Equals("research") || list.type.Equals("yxtrain") || list.type.Equals("activity"))
  403. {
  404. GroupChange change = new GroupChange()
  405. {
  406. type = list.type,
  407. listid = list.id,
  408. scope = list.scope,
  409. originCode = list.school,
  410. school = list.school,
  411. creatorId = list.creatorId
  412. };
  413. GroupList oldList = null;
  414. if (!isnew)
  415. {
  416. try
  417. {
  418. oldList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(list.id, new PartitionKey(list.code));
  419. }
  420. catch (CosmosException)
  421. {
  422. oldList = null;
  423. }
  424. }
  425. if (list.members.IsNotEmpty() && (oldList == null || !oldList.members.IsNotEmpty()))
  426. {
  427. //加入的
  428. var tmdids = list.members.FindAll(x => x.type == 1);
  429. if (tmdids.IsNotEmpty())
  430. {
  431. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  432. {
  433. change.tchjoin.AddRange(tmdids);
  434. }
  435. else
  436. {
  437. change.tmdjoin.AddRange(tmdids);
  438. }
  439. }
  440. var stuids = list.members.FindAll(x => x.type == 2);
  441. if (stuids.IsNotEmpty())
  442. {
  443. change.stujoin.AddRange(stuids);
  444. }
  445. }
  446. else
  447. {
  448. if (list.members.IsNotEmpty())
  449. {
  450. var tmdids = list.members.FindAll(x => x.type == 1);
  451. var oldtmdids = oldList.members.FindAll(x => x.type == 1);
  452. //取各自的差集
  453. //新=》旧差集,表示新增
  454. var jointmdid = tmdids.Select(x => x.id).Except(oldtmdids.Select(y => y.id)).ToList();
  455. //旧=》新差集,表示离开
  456. var leavetmdid = oldtmdids.Select(x => x.id).Except(tmdids.Select(y => y.id)).ToList();
  457. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  458. {
  459. change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  460. change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  461. }
  462. else
  463. {
  464. change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  465. change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  466. }
  467. var stuids = list.members.FindAll(x => x.type == 2);
  468. var oldstuids = oldList.members.FindAll(x => x.type == 2);
  469. var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  470. var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  471. change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  472. change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  473. }
  474. else
  475. {
  476. //离开的
  477. if (oldList != null)
  478. {
  479. var tmdids = oldList.members.FindAll(x => x.type == 1);
  480. if (tmdids.IsNotEmpty())
  481. {
  482. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  483. {
  484. change.tchleave.AddRange(tmdids);
  485. }
  486. else
  487. {
  488. change.tmdleave.AddRange(tmdids);
  489. }
  490. }
  491. var stuids = oldList.members.FindAll(x => x.type == 2);
  492. if (stuids.IsNotEmpty())
  493. {
  494. change.stuleave.AddRange(stuids);
  495. }
  496. }
  497. }
  498. }
  499. if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
  500. || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
  501. {
  502. var messageChange = new ServiceBusMessage(change.ToJsonString());
  503. messageChange.ApplicationProperties.Add("name", "GroupChange");
  504. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  505. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  506. }
  507. }
  508. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
  509. return list;
  510. }
  511. public static async Task<GroupList> CheckListNo(GroupList list, AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option)
  512. {
  513. try
  514. {
  515. var client = _azureCosmos.GetCosmosClient();
  516. if (string.IsNullOrEmpty(list.no))
  517. {
  518. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  519. for (int i = 0; i < 10; i++)
  520. {
  521. List<string> noStus = new List<string>();
  522. var queryNo = $"SELECT c.no FROM c where c.no ='{list.no}'";
  523. if (list.scope.Equals("school"))
  524. {
  525. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
  526. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{list.code}") }))
  527. {
  528. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  529. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  530. {
  531. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  532. while (accounts.MoveNext())
  533. {
  534. JsonElement account = accounts.Current;
  535. noStus.Add(account.GetProperty("no").GetString());
  536. }
  537. }
  538. }
  539. }
  540. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
  541. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("GroupList") }))
  542. {
  543. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  544. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  545. {
  546. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  547. while (accounts.MoveNext())
  548. {
  549. JsonElement account = accounts.Current;
  550. noStus.Add(account.GetProperty("no").GetString());
  551. }
  552. }
  553. }
  554. if (noStus.Count == 0)
  555. {
  556. break;
  557. }
  558. else
  559. {
  560. if (i == 9)
  561. {
  562. string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
  563. await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
  564. throw new Exception(msg);
  565. }
  566. else
  567. {
  568. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  569. }
  570. }
  571. }
  572. }
  573. }
  574. catch (Exception ex)
  575. {
  576. }
  577. return list;
  578. }
  579. /// <summary>
  580. ///根据任意名单id获取名单摘要信息。
  581. /// </summary>
  582. /// <param name="client"></param>
  583. /// <param name="_dingDing"></param>
  584. /// <param name="classes"></param>
  585. /// <param name="school"></param>
  586. /// <param name="SummarySql"></param>
  587. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  588. /// <returns></returns>
  589. public static async Task<List<GroupListDto>> GetGroupListByListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school,
  590. string SummarySql = " c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire ,c.qrcodeExpire,c.qrcodeDays ,c.grades ", int graduate = -1)
  591. {
  592. List<GroupListDto> groupLists = null;
  593. try
  594. {
  595. classes.RemoveAll(x => x == null);
  596. if (!classes.IsNotEmpty())
  597. {
  598. return null;
  599. }
  600. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  601. {
  602. //默认的教研组
  603. GroupListDto groupList = new GroupListDto
  604. {
  605. id = "TeacherAll",
  606. name = "TeacherAll",
  607. code = $"GroupList-{school}",
  608. school = school,
  609. scope = "school",
  610. type = "yxtrain",
  611. };
  612. groupLists = new List<GroupListDto> { groupList };
  613. }
  614. else
  615. {
  616. Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
  617. //List<Student> students = new List<Student>();
  618. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  619. if (!string.IsNullOrEmpty(school))
  620. {
  621. List<GroupListDto> schoolList = new List<GroupListDto>();
  622. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  623. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  624. {
  625. schoolList.Add(item);
  626. }
  627. if (schoolList.IsNotEmpty())
  628. {
  629. groups.Add("School", schoolList);
  630. }
  631. //取差集,减少二次搜寻
  632. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  633. if (classes.IsNotEmpty())
  634. {
  635. if (!groupLists.IsNotEmpty())
  636. {
  637. groupLists = new List<GroupListDto>();
  638. }
  639. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  640. //搜寻没有关联学生的行政班
  641. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText:
  642. $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader ,c.graduate from c where c.id in ({insql})",
  643. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  644. {
  645. ///行政班(学生搜寻classId动态返回)class
  646. GroupListDto group = new GroupListDto
  647. {
  648. id = item.id,
  649. code = $"GroupList-{school}",
  650. name = item.name,
  651. periodId = item.periodId,
  652. scope = "school",
  653. school = school,
  654. type = "class",
  655. year = item.year,
  656. expire = item.expire,
  657. leader = item.leader,
  658. no = item.no,
  659. pk = "GroupList",
  660. graduate = item.graduate,
  661. grades= new HashSet<int> { item.year }
  662. };
  663. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  664. if (graduate >= 0)
  665. {
  666. if (group.graduate == graduate)
  667. {
  668. groupLists.Add(group);
  669. }
  670. }
  671. //全部。
  672. else
  673. {
  674. groupLists.Add(group);
  675. }
  676. // groupLists.Add(group);
  677. }
  678. //取差集,减少二次搜寻
  679. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  680. }
  681. }
  682. if (classes.IsNotEmpty())
  683. {
  684. List<GroupListDto> privateList = new List<GroupListDto>();
  685. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  686. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  687. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  688. {
  689. privateList.Add(item);
  690. //if (string.IsNullOrWhiteSpace(school))
  691. //{
  692. // privateList.Add(item);
  693. //}
  694. //else
  695. //{
  696. // if (!string.IsNullOrWhiteSpace(item.school))
  697. // {
  698. // if (item.school.Equals(school))
  699. // {
  700. // privateList.Add(item);
  701. // }
  702. // }
  703. // else
  704. // {
  705. // privateList.Add(item);
  706. // }
  707. //}
  708. }
  709. if (privateList.IsNotEmpty())
  710. {
  711. groups.Add("Teacher", privateList);
  712. }
  713. }
  714. if (groups.Count != 0)
  715. {
  716. if (groupLists.IsNotEmpty())
  717. {
  718. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  719. }
  720. else
  721. {
  722. groupLists = groups.SelectMany(x => x.Value).ToList();
  723. }
  724. }
  725. }
  726. } catch (Exception ex ) {
  727. await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  728. }
  729. return groupLists;
  730. }
  731. /// <summary>
  732. /// 根据任意名单id获取成员信息。rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  733. /// </summary>
  734. /// <param name="_coreAPIHttpService"></param>
  735. /// <param name="client"></param>
  736. /// <param name="_dingDing"></param>
  737. /// <param name="classes"></param>
  738. /// <param name="school"></param>
  739. /// <param name="groupids"></param>
  740. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  741. /// <returns></returns>
  742. public static async Task<(List<RMember>rmembers, List<RGroupList> groups)> GetMemberByListids(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing,
  743. List<string> classes, string school, List<(string, List<string>)> groupids = null, int graduate = -1)
  744. {
  745. List<RMember> members = new List<RMember>();
  746. List<RGroupList> groupLists = new List<RGroupList>();
  747. if (classes != null)
  748. {
  749. classes.RemoveAll(x => x == null);
  750. }
  751. if (classes == null || classes.Count <= 0)
  752. {
  753. return (members, groupLists);
  754. }
  755. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  756. {
  757. //默认的教研组
  758. members = new List<RMember>();
  759. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  760. GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ",
  761. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  762. {
  763. RMember member = new RMember
  764. {
  765. id = item.id,
  766. name = item.name,
  767. picture = item.picture,
  768. type = 1,
  769. // nickname=item.name,
  770. };
  771. members.Add(member);
  772. }
  773. RGroupList groupList = new RGroupList
  774. {
  775. id = "TeacherAll",
  776. name = "TeacherAll",
  777. code = $"GroupList-{school}",
  778. school = school,
  779. scope = "school",
  780. type = "TeacherAll",
  781. members = members
  782. };
  783. groupLists = new List<RGroupList> { groupList };
  784. }
  785. else
  786. {
  787. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  788. List<Student> students = new List<Student>();
  789. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  790. if (!string.IsNullOrEmpty(school))
  791. {
  792. List<RGroupList> schoolList = new List<RGroupList>();
  793. string queryText = $"select value(c) from c where c.id in ({sql})";
  794. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  795. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  796. {
  797. schoolList.Add(item);
  798. }
  799. if (schoolList.IsNotEmpty())
  800. {
  801. groups.Add("School", schoolList);
  802. }
  803. //取差集,减少二次搜寻
  804. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  805. if (classes.IsNotEmpty())
  806. {
  807. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  808. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  809. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  810. {
  811. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  812. if (graduate >= 0)
  813. {
  814. if (item.graduate == graduate)
  815. {
  816. students.Add(item);
  817. }
  818. }
  819. //全部。
  820. else
  821. {
  822. students.Add(item);
  823. }
  824. // students.Add(item);
  825. }
  826. //取差集,减少二次搜寻
  827. classes = classes.Except(students.Select(y => y.classId)).ToList();
  828. }
  829. if (classes.IsNotEmpty())
  830. {
  831. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  832. //搜寻没有关联学生的行政班
  833. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  834. .GetItemQueryIterator<RGroupList>(queryText: $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader ,c.graduate from c where c.id in ({insql})",
  835. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  836. {
  837. ///行政班(学生搜寻classId动态返回)class
  838. List<RMember> smembers = new List<RMember>();
  839. RGroupList group = new RGroupList
  840. {
  841. id = item.id,
  842. code = $"GroupList-{school}",
  843. name = item.name,
  844. periodId = item.periodId,
  845. scope = "school",
  846. school = school,
  847. type = "class",
  848. year = item.year,
  849. expire = item.expire,
  850. members = smembers,
  851. scount = smembers.Count,
  852. pk = "GroupList",
  853. leader = item.leader,
  854. no = item.no,
  855. graduate = item.graduate,
  856. grades= new HashSet<int>() { item.year }
  857. };
  858. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  859. if (graduate >= 0)
  860. {
  861. if (group.graduate == graduate)
  862. {
  863. groupLists.Add(group);
  864. }
  865. }
  866. //全部。
  867. else
  868. {
  869. groupLists.Add(group);
  870. }
  871. //groupLists.Add(group);
  872. }
  873. //取差集,减少二次搜寻
  874. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  875. }
  876. }
  877. if (classes.IsNotEmpty())
  878. {
  879. List<RGroupList> privateList = new List<RGroupList>();
  880. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  881. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  882. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  883. {
  884. privateList.Add(item);
  885. //if (string.IsNullOrWhiteSpace(school))
  886. //{
  887. // privateList.Add(item);
  888. //}
  889. //else
  890. //{
  891. // if (!string.IsNullOrWhiteSpace(item.school))
  892. // {
  893. // if (item.school.Equals(school))
  894. // {
  895. // privateList.Add(item);
  896. // }
  897. // }
  898. // else
  899. // {
  900. // privateList.Add(item);
  901. // }
  902. //}
  903. }
  904. if (privateList.IsNotEmpty())
  905. {
  906. groups.Add("Teacher", privateList);
  907. }
  908. }
  909. foreach (var item in groups)
  910. {
  911. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  912. foreach (var group in list)
  913. {
  914. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  915. members.AddRange(rmembers);
  916. }
  917. }
  918. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  919. if (students.IsNotEmpty())
  920. {
  921. List<string> sqlList = students.Select(x => x.classId).ToList();
  922. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  923. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  924. GetItemQueryIterator<RGroupList>(queryText: $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader ,c.graduate from c where c.id in ({insql})",
  925. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  926. {
  927. ///行政班(学生搜寻classId动态返回)class
  928. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  929. .Select(y => new RMember
  930. {
  931. id = y.id,
  932. code = school,
  933. name = y.name,
  934. //nickname = y.name,
  935. type = 2,
  936. picture = y.picture,
  937. no = y.no,
  938. classId = y.classId,
  939. groupId = y.groupId,
  940. groupName = y.groupName,
  941. irs = y.irs,
  942. year= y.year,
  943. graduate = y.graduate,
  944. gender= y.gender,
  945. }).ToList();
  946. members.AddRange(smembers);
  947. RGroupList group = new RGroupList
  948. {
  949. id = item.id,
  950. code = $"GroupList-{school}",
  951. name = item.name,
  952. periodId = item.periodId,
  953. scope = "school",
  954. school = school,
  955. type = "class",
  956. expire= item.expire,
  957. year = item.year,
  958. members = smembers,
  959. scount = smembers.Count,
  960. no = item.no,
  961. leader = item.leader,
  962. pk = "GroupList",
  963. graduate = item.graduate,
  964. grades= new HashSet<int> { item.year}
  965. };
  966. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  967. if (graduate >= 0)
  968. {
  969. if (group.graduate == graduate)
  970. {
  971. groupLists.Add(group);
  972. }
  973. }
  974. //全部。
  975. else
  976. {
  977. groupLists.Add(group);
  978. }
  979. // groupLists.Add(group);
  980. }
  981. //去重。
  982. members = members.FindAll(x => x.type == 2).Where((x, i) => members.FindAll(x => x.type == 2).FindIndex(n => n.id.Equals(x.id) && n.code.Equals(x.code)) == i).ToList();
  983. }
  984. }
  985. if (groupids.IsNotEmpty())
  986. {
  987. List<RMember> rmembers = new List<RMember>();
  988. groupLists.ForEach(y => {
  989. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  990. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  991. if (grpids.Contains("default"))
  992. {
  993. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  994. if (gpmember.IsNotEmpty())
  995. {
  996. gpmember.AddRange(gpmemberdft);
  997. }
  998. else
  999. {
  1000. gpmember = gpmemberdft;
  1001. }
  1002. }
  1003. y.members = gpmember;
  1004. });
  1005. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  1006. List<RMember> tmdids = gpgpmembers.FindAll(x => x.type == 1).Where((x, i) => gpgpmembers.FindAll(x => x.type == 1).FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1007. List<RMember> students = gpgpmembers.FindAll(x => x.type == 2).Where((x, i) => gpgpmembers.FindAll(x => x.type == 2).FindIndex(n => n.id.Equals(x.id) && n.code.Equals(x.code)) == i).ToList();
  1008. if (tmdids.IsNotEmpty())
  1009. {
  1010. rmembers.AddRange(tmdids);
  1011. }
  1012. if (students.IsNotEmpty())
  1013. {
  1014. rmembers.AddRange(students);
  1015. }
  1016. return (rmembers, groupLists);
  1017. }
  1018. else
  1019. {
  1020. return (members, groupLists);
  1021. }
  1022. }
  1023. /// <summary>
  1024. /// 根据名单类型获取名单及成员信息。
  1025. /// </summary>
  1026. /// <param name="_coreAPIHttpService"></param>
  1027. /// <param name="client"></param>
  1028. /// <param name="type"></param>
  1029. /// <param name="scopes"></param>
  1030. /// <param name="school"></param>
  1031. /// <param name="_dingDing"></param>
  1032. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1033. /// <returns></returns>
  1034. public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing, int graduate = -1)
  1035. {
  1036. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  1037. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  1038. if (scopes.Contains("school"))
  1039. {
  1040. if (!string.IsNullOrEmpty(school))
  1041. {
  1042. List<RGroupList> groupLists = new List<RGroupList>();
  1043. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1044. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  1045. {
  1046. groupLists.Add(item);
  1047. }
  1048. groups.Add("School", groupLists);
  1049. }
  1050. }
  1051. else if (scopes.Contains("private"))
  1052. {
  1053. List<RGroupList> groupLists = new List<RGroupList>();
  1054. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1055. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  1056. {
  1057. groupLists.Add(item);
  1058. //if (string.IsNullOrWhiteSpace(school))
  1059. //{
  1060. // groupLists.Add(item);
  1061. //}
  1062. //else
  1063. //{
  1064. // if (!string.IsNullOrWhiteSpace(item.school))
  1065. // {
  1066. // if (item.school.Equals(school))
  1067. // {
  1068. // groupLists.Add(item);
  1069. // }
  1070. // }
  1071. // else {
  1072. // groupLists.Add(item);
  1073. // }
  1074. //}
  1075. }
  1076. groups.Add("Teacher", groupLists);
  1077. }
  1078. foreach (var item in groups)
  1079. {
  1080. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  1081. foreach (var group in list)
  1082. {
  1083. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  1084. }
  1085. }
  1086. var lists = groups.SelectMany(x => x.Value).ToList();
  1087. return lists;
  1088. }
  1089. /// <summary>
  1090. /// 根据名单类型,名单分组信息获取成员信息, rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  1091. /// </summary>
  1092. /// <param name="_coreAPIHttpService"></param>
  1093. /// <param name="client"></param>
  1094. /// <param name="type"></param>
  1095. /// <param name="groups"></param>
  1096. /// <param name="groupTbname"></param>
  1097. /// <param name="_dingDing"></param>
  1098. /// <param name="school"></param>
  1099. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1100. /// <returns></returns>
  1101. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client,
  1102. string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school, int graduate = -1)
  1103. {
  1104. try
  1105. {
  1106. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  1107. var members = groups.SelectMany(y => y.members).ToList();
  1108. //去重
  1109. List<RMember> tmdids = members.FindAll(x => x.type == 1).Where((x, i) => members.FindAll(x => x.type == 1).FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1110. List<RMember> students = members.FindAll(x => x.type == 2).Where((x, i) => members.FindAll(x => x.type == 2).FindIndex(n => n.id.Equals(x.id) && n.code.Equals(x.code)) == i).ToList();
  1111. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  1112. List<Student> studentsData = new List<Student>();
  1113. if (stu != null)
  1114. {
  1115. foreach (var item in stu)
  1116. {
  1117. var ids = item.list.Select(x => x.id).ToList();
  1118. if (ids.IsNotEmpty())
  1119. {
  1120. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId ,c.graduate,c.year FROM c ");
  1121. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  1122. stuSql.Append($"where c.id in ({insql})");
  1123. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  1124. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  1125. {
  1126. student.schoolId = item.key;
  1127. studentsData.Add(student);
  1128. }
  1129. }
  1130. }
  1131. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  1132. groups.ForEach(x =>
  1133. {
  1134. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1135. if (item > 0)
  1136. {
  1137. changes.Add(x);
  1138. }
  1139. });
  1140. }
  1141. List<TmdUser> tmdsData = new List<TmdUser>();
  1142. if (tmdids.IsNotEmpty())
  1143. {
  1144. string memberTbname = "";
  1145. if ($"{type}".Equals("activity"))
  1146. {
  1147. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  1148. var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
  1149. foreach (var schoolTeacher in schoolTeachers)
  1150. {
  1151. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1152. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  1153. tmdidSql.Append($" where c.id in ({insql})");
  1154. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1155. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  1156. {
  1157. tmdsData.Add(tmd);
  1158. }
  1159. }
  1160. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  1161. groups.ForEach(x =>
  1162. {
  1163. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1164. if (item > 0)
  1165. {
  1166. changes.Add(x);
  1167. }
  1168. });
  1169. }
  1170. else
  1171. {
  1172. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  1173. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  1174. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  1175. {
  1176. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1177. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1178. tmdidSql.Append($" where c.id in ({insql})");
  1179. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1180. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1181. {
  1182. tmdsData.Add(tmd);
  1183. }
  1184. }
  1185. else
  1186. {
  1187. {
  1188. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1189. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1190. tmdidSql.Append($" where c.id in ({insql})");
  1191. memberTbname = "Teacher";
  1192. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1193. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1194. {
  1195. tmdsData.Add(tmd);
  1196. }
  1197. }
  1198. {
  1199. //取差集,减少二次搜寻
  1200. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1201. if (tmdidexp.IsNotEmpty())
  1202. {
  1203. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1204. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  1205. tmdidSql.Append($" where c.id in ({insql})");
  1206. memberTbname = "Student";
  1207. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1208. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1209. {
  1210. tmdsData.Add(tmd);
  1211. }
  1212. }
  1213. }
  1214. }
  1215. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1216. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1217. groups.ForEach(x =>
  1218. {
  1219. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  1220. if (item > 0)
  1221. {
  1222. changes.Add(x);
  1223. }
  1224. });
  1225. }
  1226. }
  1227. if (tmdids.IsNotEmpty() && _coreAPIHttpService.check) {
  1228. ///获取真实的名称 ,大于50则不处理
  1229. if (tmdids.Count < 60)
  1230. {
  1231. var content = new StringContent(tmdids.Select(x => x.id).ToHashSet().ToJsonString(), Encoding.UTF8, "application/json");
  1232. string json = null;
  1233. try
  1234. {
  1235. json = await _coreAPIHttpService.GetUserInfos(content);
  1236. if (!string.IsNullOrWhiteSpace(json))
  1237. {
  1238. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  1239. if (tmdInfos.IsNotEmpty())
  1240. {
  1241. tmdsData.ForEach(y =>
  1242. {
  1243. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  1244. if (tmd != null)
  1245. {
  1246. y.name = tmd?.name;
  1247. y.picture = tmd?.picture;
  1248. }
  1249. else
  1250. {
  1251. groups.ForEach(x =>
  1252. {
  1253. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  1254. if (item > 0)
  1255. {
  1256. changes.Add(x);
  1257. }
  1258. });
  1259. }
  1260. });
  1261. }
  1262. }
  1263. }
  1264. catch (Exception ex)
  1265. {
  1266. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n {ex.Message}\n{ex.StackTrace}{tmdids.Select(x => x.id).ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1267. }
  1268. }
  1269. }
  1270. tmdids.ForEach(x =>
  1271. {
  1272. var user = tmdsData.Find(y => y.id.Equals(x.id));
  1273. x.name = user?.name;
  1274. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? user?.name : x.nickname;
  1275. x.picture = user?.picture;
  1276. });
  1277. students.ForEach(x =>
  1278. {
  1279. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  1280. if (student != null)
  1281. {
  1282. x.name = student?.name;
  1283. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? student?.name:x.nickname;
  1284. x.picture = student?.picture;
  1285. x.classId = student?.classId;
  1286. x.graduate = student.graduate;
  1287. x.year = student.year;
  1288. x.gender= student.gender;
  1289. }
  1290. });
  1291. var mbs = tmdids;
  1292. mbs.AddRange(students);
  1293. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  1294. {
  1295. foreach (var change in changes)
  1296. {
  1297. change.tcount = change.members.Where(x => x.type == 1).Count();
  1298. change.scount = change.members.Where(x => x.type == 2).Count();
  1299. GroupList group = change.ToJsonString().ToObject<GroupList>();
  1300. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  1301. }
  1302. }
  1303. groups.ForEach(x =>
  1304. {
  1305. x.members.ForEach(y =>
  1306. {
  1307. if (y.type == 1)
  1308. {
  1309. var tmd = tmdids.Find(t => t.id.Equals(y.id));
  1310. y.name = tmd?.name;
  1311. //y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? tmd?.nickname : y.nickname;
  1312. y.picture = tmd?.picture;
  1313. }
  1314. if (y.type == 2)
  1315. {
  1316. var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
  1317. if (student != null)
  1318. {
  1319. y.name = student?.name;
  1320. // y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? student?.nickname : y.nickname;
  1321. y.picture = student?.picture;
  1322. y.classId = student?.classId;
  1323. y.graduate = student.graduate;
  1324. y.gender = student.gender;
  1325. y.year = student.year;
  1326. y.gender = student.gender;
  1327. x.grades.Add(student.year);
  1328. }
  1329. }
  1330. });
  1331. if (!x.type.Equals("class")) {
  1332. var yearc = x.members.Where(z => z.type == 2).GroupBy(g => g.year).Select(k => new { key = k.Key, count = k.Count() }).OrderByDescending(z => z.count);
  1333. if (yearc.Any())
  1334. {
  1335. //有一半的人是同一个班的,则以
  1336. if (yearc.First().count * 1.0 / x.members.Count > 0.51)
  1337. {
  1338. x.year = yearc.First().key;
  1339. }
  1340. }
  1341. }
  1342. });
  1343. HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
  1344. if (schoolCodes != null && schoolCodes.Count > 0)
  1345. {
  1346. List<School> schools = new List<School>();
  1347. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
  1348. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1349. {
  1350. schools.Add(item);
  1351. }
  1352. if (schools.IsNotEmpty())
  1353. {
  1354. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  1355. var school = schools.Find(j => j.id.Equals(z.code));
  1356. z.schoolName = school?.name;
  1357. });
  1358. }
  1359. }
  1360. if (graduate >= 0)
  1361. {
  1362. groups= groups.FindAll(x => x.graduate == graduate);
  1363. if (groups != null) {
  1364. groups.ForEach(x =>
  1365. {
  1366. x.members.RemoveAll(y => y.graduate != graduate);
  1367. });
  1368. }
  1369. mbs.RemoveAll(z => z.graduate != graduate);
  1370. return (groups, mbs);
  1371. }
  1372. //直接返回
  1373. else {
  1374. return (groups, mbs);
  1375. }
  1376. }
  1377. catch (Exception ex)
  1378. {
  1379. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location},GetGroupListMemberInfo()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1380. }
  1381. return (null, null);
  1382. }
  1383. /// <summary>
  1384. /// 处理活动结束的
  1385. /// </summary>
  1386. /// <param name="_coreAPIHttpService"></param>
  1387. /// <param name="cosmosClient">数据库</param>
  1388. /// <param name="_dingDing">钉钉消息</param>
  1389. /// <param name="school">学校编码</param>
  1390. /// <param name="classes">行政班</param>
  1391. /// <param name="stuLists">学生</param>
  1392. /// <param name="tchLists">教师</param>
  1393. /// <param name="_groupLists">分组</param>
  1394. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1395. /// <returns></returns>
  1396. public static async Task<List<FMember>> GetFinishMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient cosmosClient, DingDing _dingDing, string school, List<string> classes, List<string> stuLists, List<string> tchLists, List<(string, List<string>)> _groupLists = null, int graduate = -1)
  1397. {
  1398. List<FMember> fMembers = new();
  1399. if (classes != null && classes.Count > 0)
  1400. {
  1401. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, classes, school);
  1402. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 1, }));
  1403. }
  1404. if (stuLists != null && stuLists.Count > 0)
  1405. {
  1406. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, stuLists, school);
  1407. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1408. }
  1409. /* if (tchLists != null && tchLists.Count > 0)
  1410. {
  1411. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school);
  1412. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1413. }*/
  1414. if (tchLists != null && tchLists.Count > 0)
  1415. {
  1416. (List<RMember> staffList, List<RGroupList> groupLists1) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school, _groupLists);
  1417. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1418. }
  1419. return fMembers;
  1420. }
  1421. }
  1422. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  1423. {
  1424. public bool Equals((string id, string code) x, (string id, string code) y)
  1425. {
  1426. return x.id.Equals(y.id) && x.code.Equals(y.code);
  1427. }
  1428. public int GetHashCode((string id, string code) obj)
  1429. {
  1430. if (obj.id != null && obj.code != null)
  1431. {
  1432. return 1;
  1433. }
  1434. else
  1435. {
  1436. return 0;
  1437. }
  1438. }
  1439. }
  1440. }