GroupListService.cs 77 KB

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