GroupListService.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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. namespace TEAMModelOS.SDK
  20. {
  21. public class GroupListService
  22. {
  23. public static async Task<(int status, GroupList stuList)> CodeJoinList(CosmosClient client, string _stuListNo, string userid, int type, string school)
  24. {
  25. var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
  26. (int status, GroupList stuList) data = (-1, null);
  27. if (!string.IsNullOrEmpty(school))
  28. {
  29. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryNo,
  30. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  31. {
  32. data = JoinList(item, userid, type, school);
  33. break;
  34. }
  35. }
  36. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
  37. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  38. {
  39. data = JoinList(item, userid, type, school);
  40. break;
  41. }
  42. return data;
  43. }
  44. public static (int status, GroupList stuList) JoinList(GroupList stuList, string userid, int type, string school)
  45. {
  46. int status = -1;
  47. if (!string.IsNullOrWhiteSpace(stuList.school) && !string.IsNullOrWhiteSpace(school))
  48. {
  49. if (!stuList.school.Equals(school))
  50. {
  51. status = 3;//不允许跨校加入名单
  52. return (status, stuList);
  53. }
  54. }
  55. string irs = string.Empty;
  56. List<string> irsOrder = stuList.members.Select(x => x.irs)?.Where(y => !string.IsNullOrEmpty(y) && Regex.IsMatch(y, @"^\d*$")).OrderBy(x => int.Parse(x)).ToList();
  57. if (!irsOrder.Contains("0"))
  58. {
  59. irsOrder.Insert(0, "0");
  60. }
  61. if (irsOrder != null)
  62. {
  63. if (!irsOrder.Contains("0"))
  64. {
  65. irsOrder.Insert(0, "0");
  66. }
  67. }
  68. else { irsOrder = new List<string>() { "0" }; }
  69. for (int i = 0; i < irsOrder.Count; i++)
  70. {
  71. irs = $"{int.Parse(irsOrder[i]) + 1}";
  72. int index = i + 1;
  73. if (index <= irsOrder.Count - 1)
  74. {
  75. if (!irs.Equals(irsOrder[index]))
  76. {
  77. break;
  78. }
  79. }
  80. }
  81. if (string.IsNullOrEmpty($"{userid}"))
  82. {
  83. //加入学生或醍摩豆ID为空
  84. status = 1;
  85. }
  86. else
  87. {
  88. if (type == 1)
  89. {
  90. var student = stuList.members.Find(x => x.type == 1 && x.id.Equals(userid));
  91. if (student != null)
  92. {
  93. //重复加入
  94. status = 2;
  95. }
  96. else
  97. {
  98. //加入成功
  99. status = 0;
  100. stuList.members.Add(new Member { id = userid, type = type, irs = irs, no = irs });
  101. }
  102. }
  103. else if (type == 2)
  104. {
  105. var student = stuList.members.Find(x => x.type == 2 && x.id.Equals(userid) && x.code.Equals(school));
  106. if (student != null)
  107. {
  108. //重复加入
  109. status = 2;
  110. }
  111. else
  112. {
  113. status = 0;
  114. stuList.members.Add(new Member { id = userid, code = school, type = type, irs = irs, no = irs });
  115. }
  116. }
  117. }
  118. return (status, stuList);
  119. }
  120. public static async Task<GroupList> UpsertList(GroupList list, AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
  121. {
  122. bool isnew = false;
  123. var client = _azureCosmos.GetCosmosClient();
  124. if (string.IsNullOrEmpty(list.id))
  125. {
  126. list.id = Guid.NewGuid().ToString();
  127. isnew = true;
  128. }
  129. string tbname = list.scope.Equals("private") ? "Teacher" : "School";
  130. var tmembers = list.members.Where(x => x.type == 1);
  131. var smembers = list.members.Where(x => x.type == 2);
  132. list.scount = smembers.Count();
  133. list.tcount = tmembers.Count();
  134. //if (smembers.Count() > 0 && smembers.Select(x => x.code).ToHashSet().Count()>=2) {
  135. // //处理移除多个学校的名单,只保留一个学校的。
  136. // if (string.IsNullOrWhiteSpace(list.school))
  137. // {
  138. // HashSet<string> codes = smembers.Select(x => x.code).ToHashSet();
  139. // list.school = codes.First();
  140. // codes.Remove(codes.First());
  141. // list.members.RemoveAll(x => codes.Contains(x.code));
  142. // }
  143. // else {
  144. // list.members.RemoveAll(x => !x.code.Equals(list.school));
  145. // }
  146. //}
  147. if (string.IsNullOrWhiteSpace(list.school) && smembers.Count() >= 1)
  148. {
  149. list.school = smembers.First().code;
  150. }
  151. if (!string.IsNullOrWhiteSpace(list.school) && smembers.Count() == 0 && list.scope.Equals("private"))
  152. {
  153. list.school = null;
  154. }
  155. //学生名单,教研组会触发活动中间表刷新
  156. if (list.type.Equals("teach") || list.type.Equals("research") || list.type.Equals("yxtrain") || list.type.Equals("activity"))
  157. {
  158. GroupChange change = new GroupChange()
  159. {
  160. type = list.type,
  161. listid = list.id,
  162. scope = list.scope,
  163. originCode = list.school,
  164. school = list.school,
  165. creatorId = list.creatorId
  166. };
  167. GroupList oldList = null;
  168. if (!isnew)
  169. {
  170. try
  171. {
  172. oldList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(list.id, new PartitionKey(list.code));
  173. }
  174. catch (CosmosException)
  175. {
  176. oldList = null;
  177. }
  178. }
  179. if (list.members.IsNotEmpty() && (oldList == null || !oldList.members.IsNotEmpty()))
  180. {
  181. //加入的
  182. var tmdids = list.members.FindAll(x => x.type == 1);
  183. if (tmdids.IsNotEmpty())
  184. {
  185. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  186. {
  187. change.tchjoin.AddRange(tmdids);
  188. }
  189. else
  190. {
  191. change.tmdjoin.AddRange(tmdids);
  192. }
  193. }
  194. var stuids = list.members.FindAll(x => x.type == 2);
  195. if (stuids.IsNotEmpty())
  196. {
  197. change.stujoin.AddRange(stuids);
  198. }
  199. }
  200. else
  201. {
  202. if (list.members.IsNotEmpty())
  203. {
  204. var tmdids = list.members.FindAll(x => x.type == 1);
  205. var oldtmdids = oldList.members.FindAll(x => x.type == 1);
  206. //取各自的差集
  207. //新=》旧差集,表示新增
  208. var jointmdid = tmdids.Select(x => x.id).Except(oldtmdids.Select(y => y.id)).ToList();
  209. //旧=》新差集,表示离开
  210. var leavetmdid = oldtmdids.Select(x => x.id).Except(tmdids.Select(y => y.id)).ToList();
  211. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  212. {
  213. change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  214. change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  215. }
  216. else
  217. {
  218. change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  219. change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  220. }
  221. var stuids = list.members.FindAll(x => x.type == 2);
  222. var oldstuids = oldList.members.FindAll(x => x.type == 2);
  223. var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  224. var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  225. change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  226. change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  227. }
  228. else
  229. {
  230. //离开的
  231. if (oldList != null)
  232. {
  233. var tmdids = oldList.members.FindAll(x => x.type == 1);
  234. if (tmdids.IsNotEmpty())
  235. {
  236. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  237. {
  238. change.tchleave.AddRange(tmdids);
  239. }
  240. else
  241. {
  242. change.tmdleave.AddRange(tmdids);
  243. }
  244. }
  245. var stuids = oldList.members.FindAll(x => x.type == 2);
  246. if (stuids.IsNotEmpty())
  247. {
  248. change.stuleave.AddRange(stuids);
  249. }
  250. }
  251. }
  252. }
  253. if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
  254. || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
  255. {
  256. var messageChange = new ServiceBusMessage(change.ToJsonString());
  257. messageChange.ApplicationProperties.Add("name", "GroupChange");
  258. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  259. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  260. }
  261. }
  262. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
  263. return list;
  264. }
  265. public static async Task<GroupList> CheckListNo(GroupList list, AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option)
  266. {
  267. try
  268. {
  269. var client = _azureCosmos.GetCosmosClient();
  270. if (string.IsNullOrEmpty(list.no))
  271. {
  272. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  273. for (int i = 0; i < 10; i++)
  274. {
  275. List<string> noStus = new List<string>();
  276. var queryNo = $"SELECT c.no FROM c where c.no ='{list.no}'";
  277. if (list.scope.Equals("school"))
  278. {
  279. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
  280. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{list.code}") }))
  281. {
  282. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  283. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  284. {
  285. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  286. while (accounts.MoveNext())
  287. {
  288. JsonElement account = accounts.Current;
  289. noStus.Add(account.GetProperty("no").GetString());
  290. }
  291. }
  292. }
  293. }
  294. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
  295. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("GroupList") }))
  296. {
  297. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  298. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  299. {
  300. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  301. while (accounts.MoveNext())
  302. {
  303. JsonElement account = accounts.Current;
  304. noStus.Add(account.GetProperty("no").GetString());
  305. }
  306. }
  307. }
  308. if (noStus.Count == 0)
  309. {
  310. break;
  311. }
  312. else
  313. {
  314. if (i == 9)
  315. {
  316. string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
  317. await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
  318. throw new Exception(msg);
  319. }
  320. else
  321. {
  322. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  323. }
  324. }
  325. }
  326. }
  327. }
  328. catch (Exception ex)
  329. {
  330. }
  331. return list;
  332. }
  333. public static async Task<List<GroupListDto>> GetGroupListListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school,
  334. 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 ")
  335. {
  336. List<GroupListDto> groupLists = null;
  337. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  338. {
  339. //默认的教研组
  340. GroupListDto groupList = new GroupListDto
  341. {
  342. id = "TeacherAll",
  343. name = "TeacherAll",
  344. code = $"GroupList-{school}",
  345. school = school,
  346. scope = "school",
  347. type = "yxtrain",
  348. };
  349. groupLists = new List<GroupListDto> { groupList };
  350. }
  351. else
  352. {
  353. Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
  354. //List<Student> students = new List<Student>();
  355. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  356. if (!string.IsNullOrEmpty(school))
  357. {
  358. List<GroupListDto> schoolList = new List<GroupListDto>();
  359. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  360. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  361. {
  362. schoolList.Add(item);
  363. }
  364. if (schoolList.IsNotEmpty())
  365. {
  366. groups.Add("School", schoolList);
  367. }
  368. //取差集,减少二次搜寻
  369. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  370. if (classes.IsNotEmpty())
  371. {
  372. if (!groupLists.IsNotEmpty())
  373. {
  374. groupLists = new List<GroupListDto>();
  375. }
  376. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  377. //搜寻没有关联学生的行政班
  378. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(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 from c where c.id in ({insql})",
  379. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  380. {
  381. ///行政班(学生搜寻classId动态返回)class
  382. GroupListDto group = new GroupListDto
  383. {
  384. id = item.id,
  385. code = $"GroupList-{school}",
  386. name = item.name,
  387. periodId = item.periodId,
  388. scope = "school",
  389. school = school,
  390. type = "class",
  391. year = item.year,
  392. leader = item.leader,
  393. no = item.no,
  394. pk = "GroupList",
  395. };
  396. groupLists.Add(group);
  397. }
  398. //取差集,减少二次搜寻
  399. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  400. }
  401. }
  402. if (classes.IsNotEmpty())
  403. {
  404. List<GroupListDto> privateList = new List<GroupListDto>();
  405. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  406. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  407. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  408. {
  409. privateList.Add(item);
  410. //if (string.IsNullOrWhiteSpace(school))
  411. //{
  412. // privateList.Add(item);
  413. //}
  414. //else
  415. //{
  416. // if (!string.IsNullOrWhiteSpace(item.school))
  417. // {
  418. // if (item.school.Equals(school))
  419. // {
  420. // privateList.Add(item);
  421. // }
  422. // }
  423. // else
  424. // {
  425. // privateList.Add(item);
  426. // }
  427. //}
  428. }
  429. if (privateList.IsNotEmpty())
  430. {
  431. groups.Add("Teacher", privateList);
  432. }
  433. }
  434. if (groups.Count != 0)
  435. {
  436. if (groupLists.IsNotEmpty())
  437. {
  438. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  439. }
  440. else
  441. {
  442. groupLists = groups.SelectMany(x => x.Value).ToList();
  443. }
  444. }
  445. }
  446. return groupLists;
  447. }
  448. public static async Task<(List<RMember>, List<RGroupList> groups)> GetStutmdidListids(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing, List<string> classes, string school, List<(string, List<string>)> groupids = null)
  449. {
  450. List<RMember> members = new List<RMember>();
  451. List<RGroupList> groupLists = new List<RGroupList>();
  452. if (classes != null)
  453. {
  454. classes.RemoveAll(x => x == null);
  455. }
  456. if (classes == null || classes.Count <= 0)
  457. {
  458. return (members, groupLists);
  459. }
  460. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  461. {
  462. //默认的教研组
  463. members = new List<RMember>();
  464. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  465. {
  466. RMember member = new RMember
  467. {
  468. id = item.id,
  469. name = item.name,
  470. picture = item.picture,
  471. type = 1,
  472. };
  473. members.Add(member);
  474. }
  475. RGroupList groupList = new RGroupList
  476. {
  477. id = "TeacherAll",
  478. name = "TeacherAll",
  479. code = $"GroupList-{school}",
  480. school = school,
  481. scope = "school",
  482. type = "TeacherAll",
  483. members = members
  484. };
  485. groupLists = new List<RGroupList> { groupList };
  486. }
  487. else
  488. {
  489. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  490. List<Student> students = new List<Student>();
  491. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  492. if (!string.IsNullOrEmpty(school))
  493. {
  494. List<RGroupList> schoolList = new List<RGroupList>();
  495. string queryText = $"select value(c) from c where c.id in ({sql})";
  496. //await _dingDing.SendBotMsg($"{queryText}",GroupNames.成都开发測試群組);
  497. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  498. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  499. {
  500. schoolList.Add(item);
  501. }
  502. if (schoolList.IsNotEmpty())
  503. {
  504. groups.Add("School", schoolList);
  505. }
  506. //取差集,减少二次搜寻
  507. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  508. if (classes.IsNotEmpty())
  509. {
  510. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  511. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  512. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  513. {
  514. students.Add(item);
  515. }
  516. //取差集,减少二次搜寻
  517. classes = classes.Except(students.Select(y => y.classId)).ToList();
  518. }
  519. if (classes.IsNotEmpty())
  520. {
  521. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  522. //搜寻没有关联学生的行政班
  523. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  524. .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 from c where c.id in ({insql})",
  525. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  526. {
  527. ///行政班(学生搜寻classId动态返回)class
  528. List<RMember> smembers = new List<RMember>();
  529. RGroupList group = new RGroupList
  530. {
  531. id = item.id,
  532. code = $"GroupList-{school}",
  533. name = item.name,
  534. periodId = item.periodId,
  535. scope = "school",
  536. school = school,
  537. type = "class",
  538. year = item.year,
  539. members = smembers,
  540. scount = smembers.Count,
  541. pk = "GroupList",
  542. leader = item.leader,
  543. no = item.no,
  544. };
  545. groupLists.Add(group);
  546. }
  547. //取差集,减少二次搜寻
  548. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  549. }
  550. }
  551. if (classes.IsNotEmpty())
  552. {
  553. List<RGroupList> privateList = new List<RGroupList>();
  554. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  555. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  556. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  557. {
  558. privateList.Add(item);
  559. //if (string.IsNullOrWhiteSpace(school))
  560. //{
  561. // privateList.Add(item);
  562. //}
  563. //else
  564. //{
  565. // if (!string.IsNullOrWhiteSpace(item.school))
  566. // {
  567. // if (item.school.Equals(school))
  568. // {
  569. // privateList.Add(item);
  570. // }
  571. // }
  572. // else
  573. // {
  574. // privateList.Add(item);
  575. // }
  576. //}
  577. }
  578. if (privateList.IsNotEmpty())
  579. {
  580. groups.Add("Teacher", privateList);
  581. }
  582. }
  583. foreach (var item in groups)
  584. {
  585. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  586. foreach (var group in list)
  587. {
  588. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school);
  589. members.AddRange(rmembers);
  590. }
  591. }
  592. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  593. if (students.IsNotEmpty())
  594. {
  595. List<string> sqlList = students.Select(x => x.classId).ToList();
  596. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  597. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  598. 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 from c where c.id in ({insql})",
  599. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  600. {
  601. ///行政班(学生搜寻classId动态返回)class
  602. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  603. .Select(y => new RMember
  604. {
  605. id = y.id,
  606. code = school,
  607. name = y.name,
  608. type = 2,
  609. picture = y.picture,
  610. no = y.no,
  611. classId = y.classId,
  612. //groupId=y.groupId,
  613. groupName = y.groupName,
  614. irs = y.irs,
  615. }).ToList();
  616. members.AddRange(smembers);
  617. RGroupList group = new RGroupList
  618. {
  619. id = item.id,
  620. code = $"GroupList-{school}",
  621. name = item.name,
  622. periodId = item.periodId,
  623. scope = "school",
  624. school = school,
  625. type = "class",
  626. year = item.year,
  627. members = smembers,
  628. scount = smembers.Count,
  629. no = item.no,
  630. leader = item.leader,
  631. pk = "GroupList"
  632. };
  633. groupLists.Add(group);
  634. }
  635. //去重。
  636. 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();
  637. }
  638. }
  639. if (groupids.IsNotEmpty())
  640. {
  641. List<RMember> rmembers = new List<RMember>();
  642. groupLists.ForEach(y => {
  643. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  644. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  645. if (grpids.Contains("default"))
  646. {
  647. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  648. if (gpmember.IsNotEmpty())
  649. {
  650. gpmember.AddRange(gpmemberdft);
  651. }
  652. else
  653. {
  654. gpmember = gpmemberdft;
  655. }
  656. }
  657. y.members = gpmember;
  658. });
  659. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  660. 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();
  661. 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();
  662. if (tmdids.IsNotEmpty())
  663. {
  664. rmembers.AddRange(tmdids);
  665. }
  666. if (students.IsNotEmpty())
  667. {
  668. rmembers.AddRange(students);
  669. }
  670. return (rmembers, groupLists);
  671. }
  672. else
  673. {
  674. return (members, groupLists);
  675. }
  676. }
  677. public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing)
  678. {
  679. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  680. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  681. if (scopes.Contains("school"))
  682. {
  683. if (!string.IsNullOrEmpty(school))
  684. {
  685. List<RGroupList> groupLists = new List<RGroupList>();
  686. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  687. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  688. {
  689. groupLists.Add(item);
  690. }
  691. groups.Add("School", groupLists);
  692. }
  693. }
  694. else if (scopes.Contains("private"))
  695. {
  696. List<RGroupList> groupLists = new List<RGroupList>();
  697. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  698. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  699. {
  700. groupLists.Add(item);
  701. //if (string.IsNullOrWhiteSpace(school))
  702. //{
  703. // groupLists.Add(item);
  704. //}
  705. //else
  706. //{
  707. // if (!string.IsNullOrWhiteSpace(item.school))
  708. // {
  709. // if (item.school.Equals(school))
  710. // {
  711. // groupLists.Add(item);
  712. // }
  713. // }
  714. // else {
  715. // groupLists.Add(item);
  716. // }
  717. //}
  718. }
  719. groups.Add("Teacher", groupLists);
  720. }
  721. foreach (var item in groups)
  722. {
  723. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  724. foreach (var group in list)
  725. {
  726. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school);
  727. }
  728. }
  729. var lists = groups.SelectMany(x => x.Value).ToList();
  730. return lists;
  731. }
  732. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school)
  733. {
  734. try
  735. {
  736. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  737. var members = groups.SelectMany(y => y.members).ToList();
  738. //去重
  739. 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();
  740. 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();
  741. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  742. List<Student> studentsData = new List<Student>();
  743. if (stu != null)
  744. {
  745. foreach (var item in stu)
  746. {
  747. var ids = item.list.Select(x => x.id).ToList();
  748. if (ids.IsNotEmpty())
  749. {
  750. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId FROM c ");
  751. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  752. stuSql.Append($"where c.id in ({insql})");
  753. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  754. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  755. {
  756. student.schoolId = item.key;
  757. studentsData.Add(student);
  758. }
  759. }
  760. }
  761. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  762. groups.ForEach(x =>
  763. {
  764. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  765. if (item > 0)
  766. {
  767. changes.Add(x);
  768. }
  769. });
  770. }
  771. List<TmdUser> tmdsData = new List<TmdUser>();
  772. if (tmdids.IsNotEmpty())
  773. {
  774. string memberTbname = "";
  775. if ($"{type}".Equals("activity"))
  776. {
  777. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  778. var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
  779. foreach (var schoolTeacher in schoolTeachers)
  780. {
  781. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  782. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  783. tmdidSql.Append($" where c.id in ({insql})");
  784. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  785. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  786. {
  787. tmdsData.Add(tmd);
  788. }
  789. }
  790. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  791. groups.ForEach(x =>
  792. {
  793. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  794. if (item > 0)
  795. {
  796. changes.Add(x);
  797. }
  798. });
  799. }
  800. else
  801. {
  802. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  803. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  804. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  805. {
  806. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  807. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  808. tmdidSql.Append($" where c.id in ({insql})");
  809. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  810. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  811. {
  812. tmdsData.Add(tmd);
  813. }
  814. }
  815. else
  816. {
  817. {
  818. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  819. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  820. tmdidSql.Append($" where c.id in ({insql})");
  821. memberTbname = "Teacher";
  822. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  823. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  824. {
  825. tmdsData.Add(tmd);
  826. }
  827. }
  828. {
  829. //取差集,减少二次搜寻
  830. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  831. if (tmdidexp.IsNotEmpty())
  832. {
  833. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  834. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  835. tmdidSql.Append($" where c.id in ({insql})");
  836. memberTbname = "Student";
  837. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  838. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  839. {
  840. tmdsData.Add(tmd);
  841. }
  842. }
  843. }
  844. }
  845. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  846. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  847. groups.ForEach(x =>
  848. {
  849. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  850. if (item > 0)
  851. {
  852. changes.Add(x);
  853. }
  854. });
  855. }
  856. }
  857. ///获取真实的名称
  858. var content = new StringContent(tmdids.Select(x => x.id).ToJsonString(), Encoding.UTF8, "application/json");
  859. string json = await _coreAPIHttpService.GetUserInfos(content);
  860. if (!string.IsNullOrWhiteSpace(json))
  861. {
  862. try
  863. {
  864. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  865. if (tmdInfos.IsNotEmpty())
  866. {
  867. tmdsData.ForEach(y =>
  868. {
  869. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  870. if (tmd != null)
  871. {
  872. y.name = tmd?.name;
  873. y.picture = tmd?.picture;
  874. }
  875. else
  876. {
  877. groups.ForEach(x =>
  878. {
  879. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  880. if (item > 0)
  881. {
  882. changes.Add(x);
  883. }
  884. });
  885. }
  886. });
  887. }
  888. }
  889. catch (Exception ex)
  890. {
  891. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
  892. }
  893. }
  894. tmdids.ForEach(x =>
  895. {
  896. var user = tmdsData.Find(y => y.id.Equals(x.id));
  897. x.name = user?.name;
  898. x.picture = user?.picture;
  899. });
  900. students.ForEach(x =>
  901. {
  902. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  903. x.name = student?.name;
  904. x.picture = student?.picture;
  905. x.classId = student?.classId;
  906. });
  907. var mbs = tmdids;
  908. mbs.AddRange(students);
  909. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  910. {
  911. foreach (var change in changes)
  912. {
  913. change.tcount = change.members.Where(x => x.type == 1).Count();
  914. change.scount = change.members.Where(x => x.type == 2).Count();
  915. GroupList group = change.ToJsonString().ToObject<GroupList>();
  916. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  917. }
  918. }
  919. groups.ForEach(x => x.members.ForEach(y => {
  920. if (y.type == 1)
  921. {
  922. var tmd = tmdids.Find(t => t.id.Equals(y.id));
  923. y.name = tmd?.name;
  924. y.picture = tmd?.picture;
  925. }
  926. if (y.type == 2)
  927. {
  928. var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
  929. y.name = student?.name;
  930. y.picture = student?.picture;
  931. y.classId = student?.classId;
  932. }
  933. }));
  934. HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
  935. if (schoolCodes != null && schoolCodes.Count > 0)
  936. {
  937. List<School> schools = new List<School>();
  938. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
  939. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  940. {
  941. schools.Add(item);
  942. }
  943. if (schools.IsNotEmpty())
  944. {
  945. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  946. var school = schools.Find(j => j.id.Equals(z.code));
  947. z.schoolName = school?.name;
  948. });
  949. }
  950. }
  951. return (groups, mbs);
  952. }
  953. catch (Exception ex)
  954. {
  955. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location},GetGroupListMemberInfo()\n{ex.Message}{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  956. }
  957. return (null, null);
  958. }
  959. }
  960. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  961. {
  962. public bool Equals((string id, string code) x, (string id, string code) y)
  963. {
  964. return x.id.Equals(y.id) && x.code.Equals(y.code);
  965. }
  966. public int GetHashCode((string id, string code) obj)
  967. {
  968. if (obj.id != null && obj.code != null)
  969. {
  970. return 1;
  971. }
  972. else
  973. {
  974. return 0;
  975. }
  976. }
  977. }
  978. }