GroupListService.cs 48 KB

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