GroupListService.cs 46 KB

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