GroupListService.cs 74 KB

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