GroupListService.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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, AzureStorageFactory _azureStorage, 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. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
  123. //学生名单,教研组会触发活动中间表刷新
  124. if (list.type.Equals("teach") || list.type.Equals("research") || list.type.Equals("yxtrain"))
  125. {
  126. GroupChange change = new GroupChange()
  127. {
  128. type = list.type,
  129. listid = list.id,
  130. scope = list.scope,
  131. originCode = list.school,
  132. school = list.school,
  133. creatorId = list.creatorId
  134. };
  135. GroupList oldList = null;
  136. if (!isnew)
  137. {
  138. try
  139. {
  140. oldList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(list.id, new PartitionKey(list.code));
  141. }
  142. catch (CosmosException)
  143. {
  144. oldList = null;
  145. }
  146. }
  147. if (list.members.IsNotEmpty() && (oldList == null || !oldList.members.IsNotEmpty()))
  148. {
  149. //加入的
  150. var tmdids = list.members.FindAll(x => x.type == 1);
  151. if (tmdids.IsNotEmpty())
  152. {
  153. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  154. {
  155. change.tchjoin.AddRange(tmdids);
  156. }
  157. else
  158. {
  159. change.tmdjoin.AddRange(tmdids);
  160. }
  161. }
  162. var stuids = list.members.FindAll(x => x.type == 2);
  163. if (stuids.IsNotEmpty())
  164. {
  165. change.stujoin.AddRange(stuids);
  166. }
  167. }
  168. else
  169. {
  170. if (list.members.IsNotEmpty())
  171. {
  172. var tmdids = list.members.FindAll(x => x.type == 1);
  173. var oldtmdids = oldList.members.FindAll(x => x.type == 1);
  174. //取各自的差集
  175. //新=》旧差集,表示新增
  176. var jointmdid = tmdids.Select(x => x.id).Except(oldtmdids.Select(y => y.id)).ToList();
  177. //旧=》新差集,表示离开
  178. var leavetmdid = oldtmdids.Select(x => x.id).Except(tmdids.Select(y => y.id)).ToList();
  179. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  180. {
  181. change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  182. change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  183. }
  184. else
  185. {
  186. change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  187. change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  188. }
  189. var stuids = list.members.FindAll(x => x.type == 2);
  190. var oldstuids = oldList.members.FindAll(x => x.type == 2);
  191. var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  192. var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  193. change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  194. change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  195. }
  196. else
  197. {
  198. //离开的
  199. if (oldList != null) {
  200. var tmdids = oldList.members.FindAll(x => x.type == 1);
  201. if (tmdids.IsNotEmpty())
  202. {
  203. if (list.type.Equals("research")|| list.type.Equals("yxtrain"))
  204. {
  205. change.tchleave.AddRange(tmdids);
  206. }
  207. else
  208. {
  209. change.tmdleave.AddRange(tmdids);
  210. }
  211. }
  212. var stuids = oldList.members.FindAll(x => x.type == 2);
  213. if (stuids.IsNotEmpty())
  214. {
  215. change.stuleave.AddRange(stuids);
  216. }
  217. }
  218. }
  219. }
  220. if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
  221. || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
  222. {
  223. var messageChange = new ServiceBusMessage(change.ToJsonString());
  224. messageChange.ApplicationProperties.Add("name", "GroupChange");
  225. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  226. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  227. }
  228. }
  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, "0123456789")}";
  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, "0123456789")}";
  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,string SummarySql) {
  300. List<GroupListDto> groupLists = null;
  301. if (classes.Count == 1 && classes.First().Equals("default") && !string.IsNullOrEmpty(school))
  302. {
  303. //默认的教研组
  304. GroupListDto groupList = new GroupListDto
  305. {
  306. id = "default",
  307. name = "default",
  308. code = $"GroupList-{school}",
  309. school = school,
  310. scope = "school",
  311. type = "yxtrain",
  312. };
  313. groupLists = new List<GroupListDto> { groupList };
  314. }
  315. else
  316. {
  317. Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
  318. //List<Student> students = new List<Student>();
  319. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  320. if (!string.IsNullOrEmpty(school))
  321. {
  322. List<GroupListDto> schoolList = new List<GroupListDto>();
  323. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  324. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  325. {
  326. schoolList.Add(item);
  327. }
  328. if (schoolList.IsNotEmpty())
  329. {
  330. groups.Add("School", schoolList);
  331. }
  332. //取差集,减少二次搜寻
  333. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  334. if (classes.IsNotEmpty())
  335. {
  336. if (!groupLists.IsNotEmpty()) {
  337. groupLists = new List<GroupListDto>();
  338. }
  339. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  340. //搜寻没有关联学生的行政班
  341. 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})",
  342. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  343. {
  344. ///行政班(学生搜寻classId动态返回)class
  345. GroupListDto group = new GroupListDto
  346. {
  347. id = item.id,
  348. code = $"GroupList-{school}",
  349. name = item.name,
  350. periodId = item.periodId,
  351. scope = "school",
  352. school = school,
  353. type = "class",
  354. year = item.year,
  355. leader= item.leader,
  356. no= item.no,
  357. pk= "GroupList",
  358. };
  359. groupLists.Add(group);
  360. }
  361. //取差集,减少二次搜寻
  362. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  363. }
  364. }
  365. if (classes.IsNotEmpty())
  366. {
  367. List<GroupListDto> privateList = new List<GroupListDto>();
  368. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  369. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  370. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  371. {
  372. privateList.Add(item);
  373. }
  374. if (privateList.IsNotEmpty())
  375. {
  376. groups.Add("Teacher", privateList);
  377. }
  378. }
  379. if (groups.Count != 0)
  380. {
  381. if (groupLists.IsNotEmpty())
  382. {
  383. groupLists .AddRange(groups.SelectMany(x => x.Value).ToList());
  384. }
  385. else {
  386. groupLists = groups.SelectMany(x => x.Value).ToList();
  387. }
  388. }
  389. }
  390. return groupLists;
  391. }
  392. public static async Task<(List<RMember>, List<RGroupList> groups)> GetStutmdidListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school)
  393. {
  394. List<RMember> members = new List<RMember>();
  395. List<RGroupList> groupLists = new List<RGroupList>();
  396. if (classes.IsEmpty()) {
  397. return (members, groupLists);
  398. }
  399. if (classes.Count == 1 && classes.First().Equals("default") && !string.IsNullOrEmpty(school))
  400. {
  401. //默认的教研组
  402. members = new List<RMember>();
  403. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdInfo>(queryText: $"SELECT value(c) FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  404. {
  405. RMember member = new RMember
  406. {
  407. id = item.id,
  408. name = item.name,
  409. picture = item.picture,
  410. type = 1,
  411. };
  412. members.Add(member);
  413. }
  414. RGroupList groupList = new RGroupList
  415. {
  416. id = "default",
  417. name = "default",
  418. code = $"GroupList-{school}",
  419. school = school,
  420. scope = "school",
  421. type = "yxtrain",
  422. members = members
  423. };
  424. groupLists = new List<RGroupList> { groupList };
  425. }
  426. else
  427. {
  428. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  429. List<Student> students = new List<Student>();
  430. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  431. if (!string.IsNullOrEmpty(school))
  432. {
  433. List<RGroupList> schoolList = new List<RGroupList>();
  434. string queryText = $"select value(c) from c where c.id in ({sql})";
  435. //await _dingDing.SendBotMsg($"{queryText}",GroupNames.成都开发測試群組);
  436. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  437. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  438. {
  439. schoolList.Add(item);
  440. }
  441. if (schoolList.IsNotEmpty())
  442. {
  443. groups.Add("School", schoolList);
  444. }
  445. //取差集,减少二次搜寻
  446. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  447. if (classes.IsNotEmpty())
  448. {
  449. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  450. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  451. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  452. {
  453. students.Add(item);
  454. }
  455. //取差集,减少二次搜寻
  456. classes = classes.Except(students.Select(y => y.classId)).ToList();
  457. }
  458. if (classes.IsNotEmpty()) {
  459. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  460. //搜寻没有关联学生的行政班
  461. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  462. .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})",
  463. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  464. {
  465. ///行政班(学生搜寻classId动态返回)class
  466. List<RMember> smembers = new List<RMember>();
  467. RGroupList group = new RGroupList
  468. {
  469. id = item.id,
  470. code = $"GroupList-{school}",
  471. name = item.name,
  472. periodId = item.periodId,
  473. scope = "school",
  474. school = school,
  475. type = "class",
  476. year = item.year,
  477. members = smembers,
  478. scount = smembers.Count,
  479. pk= "GroupList",
  480. leader=item.leader,
  481. no=item.no,
  482. };
  483. groupLists.Add(group);
  484. }
  485. //取差集,减少二次搜寻
  486. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  487. }
  488. }
  489. if (classes.IsNotEmpty())
  490. {
  491. List<RGroupList> privateList = new List<RGroupList>();
  492. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  493. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  494. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  495. {
  496. privateList.Add(item);
  497. }
  498. if (privateList.IsNotEmpty())
  499. {
  500. groups.Add("Teacher", privateList);
  501. }
  502. }
  503. foreach (var item in groups)
  504. {
  505. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  506. foreach (var group in list)
  507. {
  508. (List<RGroupList> rgroups, List<RMember> rmembers) =await GetGroupListMemberInfo(client, group.key, group.list, item.Key,_dingDing);
  509. members.AddRange(rmembers);
  510. }
  511. }
  512. groupLists .AddRange(groups.SelectMany(x => x.Value).ToList());
  513. if (students.IsNotEmpty())
  514. {
  515. List<string> sqlList = students.Select(x => x.classId).ToList();
  516. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  517. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  518. 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})",
  519. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  520. {
  521. ///行政班(学生搜寻classId动态返回)class
  522. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  523. .Select(y => new RMember
  524. {
  525. id = y.id,
  526. code = school,
  527. name = y.name,
  528. type = 2,
  529. picture = y.picture,
  530. no = y.no,
  531. classId=y.classId,
  532. //groupId=y.groupId,
  533. groupName=y.groupName ,
  534. irs=y.irs,
  535. }).ToList();
  536. members.AddRange(smembers);
  537. RGroupList group = new RGroupList
  538. {
  539. id = item.id,
  540. code = $"GroupList-{school}",
  541. name = item.name,
  542. periodId = item.periodId,
  543. scope = "school",
  544. school = school,
  545. type = "class",
  546. year = item.year,
  547. members = smembers,
  548. scount = smembers.Count,
  549. no=item.no,
  550. leader=item.leader,
  551. pk= "GroupList"
  552. };
  553. groupLists.Add(group);
  554. }
  555. //去重。
  556. 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();
  557. }
  558. }
  559. return (members,groupLists);
  560. }
  561. public static async Task< List<RGroupList> > GetGroupListMemberByType(CosmosClient client,string type, List<string> scopes, string school, DingDing _dingDing)
  562. {
  563. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  564. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  565. if (scopes.Contains("school"))
  566. {
  567. if (!string.IsNullOrEmpty(school))
  568. {
  569. List<RGroupList> groupLists= new List<RGroupList>();
  570. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  571. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  572. {
  573. groupLists.Add(item);
  574. }
  575. groups.Add("School", groupLists);
  576. }
  577. }
  578. else if (scopes.Contains("private")) {
  579. List<RGroupList> groupLists = new List<RGroupList>();
  580. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  581. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  582. {
  583. groupLists.Add(item);
  584. }
  585. groups.Add("Teacher", groupLists);
  586. }
  587. foreach (var item in groups)
  588. {
  589. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  590. foreach (var group in list)
  591. {
  592. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(client, group.key, group.list, item.Key, _dingDing);
  593. }
  594. }
  595. var lists= groups.SelectMany(x => x.Value).ToList() ;
  596. return lists;
  597. }
  598. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CosmosClient client, string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing)
  599. {
  600. try {
  601. var members = groups.SelectMany(y => y.members).ToList();
  602. //去重
  603. 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();
  604. 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();
  605. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  606. List<Student> studentsData = new List<Student>();
  607. if (stu != null)
  608. {
  609. foreach (var item in stu)
  610. {
  611. var ids = item.list.Select(x => x.id).ToList();
  612. if (ids.IsNotEmpty())
  613. {
  614. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId FROM c ");
  615. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  616. stuSql.Append($"where c.id in ({insql})");
  617. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  618. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  619. {
  620. student.schoolId = item.key;
  621. studentsData.Add(student);
  622. }
  623. }
  624. }
  625. }
  626. List<TmdUser> tmdsData = new List<TmdUser>();
  627. if (tmdids.IsNotEmpty())
  628. {
  629. string memberTbname = "";
  630. //可能会出现在两种表中
  631. if ($"{type}".Equals("teach") || $"{type}".Equals("research") || $"{type}".Equals("group")
  632. || $"{type}".Equals("friend") || $"{type}".Equals("manage") || $"{type}".Equals("subject") || $"{type}".Equals("yxtrain"))
  633. {
  634. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  635. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  636. tmdidSql.Append($" where c.id in ({insql})");
  637. memberTbname = "Teacher";
  638. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  639. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  640. {
  641. tmdsData.Add(tmd);
  642. }
  643. }
  644. if ($"{type}".Equals("teach") || $"{type}".Equals("friend") || $"{type}".Equals("group"))
  645. {
  646. //取差集,减少二次搜寻
  647. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  648. if (tmdidexp.IsNotEmpty())
  649. {
  650. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  651. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  652. tmdidSql.Append($" where c.id in ({insql})");
  653. memberTbname = "Student";
  654. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  655. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  656. {
  657. tmdsData.Add(tmd);
  658. }
  659. }
  660. }
  661. //去重
  662. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  663. }
  664. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  665. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  666. groups.ForEach(x =>
  667. {
  668. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  669. if (item > 0)
  670. {
  671. changes.Add(x);
  672. }
  673. });
  674. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  675. groups.ForEach(x =>
  676. {
  677. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  678. if (item > 0)
  679. {
  680. changes.Add(x);
  681. }
  682. });
  683. tmdids.ForEach(x =>
  684. {
  685. var user = tmdsData.Find(y => y.id.Equals(x.id));
  686. x.name = user?.name;
  687. x.picture = user?.picture;
  688. });
  689. students.ForEach(x =>
  690. {
  691. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  692. x.name = student?.name;
  693. x.picture = student?.picture;
  694. x.classId = student?.classId;
  695. });
  696. var mbs = tmdids;
  697. mbs.AddRange(students);
  698. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  699. {
  700. foreach (var change in changes)
  701. {
  702. change.tcount = change.members.Where(x => x.type == 1).Count();
  703. change.scount = change.members.Where(x => x.type == 2).Count();
  704. GroupList group= change.ToJsonString().ToObject<GroupList>();
  705. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  706. }
  707. }
  708. groups.ForEach(x => x.members.ForEach(y=> {
  709. if (y.type == 1) {
  710. var tmd =tmdids.Find(t => t.id.Equals(y.id));
  711. y.name = tmd?.name;
  712. y.picture = tmd?.picture;
  713. }
  714. if (y.type == 2)
  715. {
  716. var student = students.Find(t => t.id.Equals(y.id)&& t.code.Equals(y.code));
  717. y.name = student?.name;
  718. y.picture = student?.picture;
  719. y.classId = student?.classId;
  720. }
  721. }));
  722. return (groups, mbs);
  723. } catch (Exception ex) {
  724. await _dingDing.SendBotMsg($"OS,GetGroupListMemberInfo()\n{ex.Message}{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  725. }
  726. return (null, null);
  727. }
  728. }
  729. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  730. {
  731. public bool Equals((string id, string code) x, (string id, string code) y)
  732. {
  733. return x.id.Equals(y.id) && x.code.Equals(y.code);
  734. }
  735. public int GetHashCode((string id, string code) obj)
  736. {
  737. if (obj.id != null && obj.code != null)
  738. {
  739. return 1;
  740. }
  741. else
  742. {
  743. return 0;
  744. }
  745. }
  746. }
  747. }