GroupListService.cs 44 KB

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