GroupListService.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. privateList.Add(item);
  403. //if (string.IsNullOrWhiteSpace(school))
  404. //{
  405. // privateList.Add(item);
  406. //}
  407. //else
  408. //{
  409. // if (!string.IsNullOrWhiteSpace(item.school))
  410. // {
  411. // if (item.school.Equals(school))
  412. // {
  413. // privateList.Add(item);
  414. // }
  415. // }
  416. // else
  417. // {
  418. // privateList.Add(item);
  419. // }
  420. //}
  421. }
  422. if (privateList.IsNotEmpty())
  423. {
  424. groups.Add("Teacher", privateList);
  425. }
  426. }
  427. if (groups.Count != 0)
  428. {
  429. if (groupLists.IsNotEmpty())
  430. {
  431. groupLists .AddRange(groups.SelectMany(x => x.Value).ToList());
  432. }
  433. else {
  434. groupLists = groups.SelectMany(x => x.Value).ToList();
  435. }
  436. }
  437. }
  438. return groupLists;
  439. }
  440. 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)
  441. {
  442. List<RMember> members = new List<RMember>();
  443. List<RGroupList> groupLists = new List<RGroupList>();
  444. if (classes != null) {
  445. classes.RemoveAll(x => x == null);
  446. }
  447. if (classes==null || classes.Count<=0) {
  448. return (members, groupLists);
  449. }
  450. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  451. {
  452. //默认的教研组
  453. members = new List<RMember>();
  454. 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}") }))
  455. {
  456. RMember member = new RMember
  457. {
  458. id = item.id,
  459. name = item.name,
  460. picture = item.picture,
  461. type = 1,
  462. };
  463. members.Add(member);
  464. }
  465. RGroupList groupList = new RGroupList
  466. {
  467. id = "TeacherAll",
  468. name = "TeacherAll",
  469. code = $"GroupList-{school}",
  470. school = school,
  471. scope = "school",
  472. type = "TeacherAll",
  473. members = members
  474. };
  475. groupLists = new List<RGroupList> { groupList };
  476. }
  477. else
  478. {
  479. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  480. List<Student> students = new List<Student>();
  481. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  482. if (!string.IsNullOrEmpty(school))
  483. {
  484. List<RGroupList> schoolList = new List<RGroupList>();
  485. string queryText = $"select value(c) from c where c.id in ({sql})";
  486. //await _dingDing.SendBotMsg($"{queryText}",GroupNames.成都开发測試群組);
  487. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  488. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  489. {
  490. schoolList.Add(item);
  491. }
  492. if (schoolList.IsNotEmpty())
  493. {
  494. groups.Add("School", schoolList);
  495. }
  496. //取差集,减少二次搜寻
  497. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  498. if (classes.IsNotEmpty())
  499. {
  500. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  501. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  502. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  503. {
  504. students.Add(item);
  505. }
  506. //取差集,减少二次搜寻
  507. classes = classes.Except(students.Select(y => y.classId)).ToList();
  508. }
  509. if (classes.IsNotEmpty()) {
  510. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  511. //搜寻没有关联学生的行政班
  512. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  513. .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})",
  514. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  515. {
  516. ///行政班(学生搜寻classId动态返回)class
  517. List<RMember> smembers = new List<RMember>();
  518. RGroupList group = new RGroupList
  519. {
  520. id = item.id,
  521. code = $"GroupList-{school}",
  522. name = item.name,
  523. periodId = item.periodId,
  524. scope = "school",
  525. school = school,
  526. type = "class",
  527. year = item.year,
  528. members = smembers,
  529. scount = smembers.Count,
  530. pk= "GroupList",
  531. leader=item.leader,
  532. no=item.no,
  533. };
  534. groupLists.Add(group);
  535. }
  536. //取差集,减少二次搜寻
  537. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  538. }
  539. }
  540. if (classes.IsNotEmpty())
  541. {
  542. List<RGroupList> privateList = new List<RGroupList>();
  543. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  544. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  545. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  546. {
  547. privateList.Add(item);
  548. //if (string.IsNullOrWhiteSpace(school))
  549. //{
  550. // privateList.Add(item);
  551. //}
  552. //else
  553. //{
  554. // if (!string.IsNullOrWhiteSpace(item.school))
  555. // {
  556. // if (item.school.Equals(school))
  557. // {
  558. // privateList.Add(item);
  559. // }
  560. // }
  561. // else
  562. // {
  563. // privateList.Add(item);
  564. // }
  565. //}
  566. }
  567. if (privateList.IsNotEmpty())
  568. {
  569. groups.Add("Teacher", privateList);
  570. }
  571. }
  572. foreach (var item in groups)
  573. {
  574. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  575. foreach (var group in list)
  576. {
  577. (List<RGroupList> rgroups, List<RMember> rmembers) =await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key,_dingDing,school);
  578. members.AddRange(rmembers);
  579. }
  580. }
  581. groupLists .AddRange(groups.SelectMany(x => x.Value).ToList());
  582. if (students.IsNotEmpty())
  583. {
  584. List<string> sqlList = students.Select(x => x.classId).ToList();
  585. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  586. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  587. 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})",
  588. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  589. {
  590. ///行政班(学生搜寻classId动态返回)class
  591. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  592. .Select(y => new RMember
  593. {
  594. id = y.id,
  595. code = school,
  596. name = y.name,
  597. type = 2,
  598. picture = y.picture,
  599. no = y.no,
  600. classId=y.classId,
  601. //groupId=y.groupId,
  602. groupName=y.groupName ,
  603. irs=y.irs,
  604. }).ToList();
  605. members.AddRange(smembers);
  606. RGroupList group = new RGroupList
  607. {
  608. id = item.id,
  609. code = $"GroupList-{school}",
  610. name = item.name,
  611. periodId = item.periodId,
  612. scope = "school",
  613. school = school,
  614. type = "class",
  615. year = item.year,
  616. members = smembers,
  617. scount = smembers.Count,
  618. no=item.no,
  619. leader=item.leader,
  620. pk= "GroupList"
  621. };
  622. groupLists.Add(group);
  623. }
  624. //去重。
  625. 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();
  626. }
  627. }
  628. if (groupids.IsNotEmpty()) {
  629. List<RMember> rmembers = new List<RMember>();
  630. groupLists.ForEach(y => {
  631. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  632. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  633. if ( grpids.Contains("default"))
  634. {
  635. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  636. if (gpmember.IsNotEmpty())
  637. {
  638. gpmember.AddRange(gpmemberdft);
  639. }
  640. else {
  641. gpmember = gpmemberdft;
  642. }
  643. }
  644. y.members = gpmember;
  645. });
  646. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  647. 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();
  648. 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();
  649. if (tmdids.IsNotEmpty()) {
  650. rmembers.AddRange(tmdids);
  651. }
  652. if (students.IsNotEmpty())
  653. {
  654. rmembers.AddRange(students);
  655. }
  656. return (rmembers, groupLists);
  657. }
  658. else {
  659. return (members, groupLists);
  660. }
  661. }
  662. public static async Task< List<RGroupList> > GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService,CosmosClient client,string type, List<string> scopes, string school, DingDing _dingDing)
  663. {
  664. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  665. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  666. if (scopes.Contains("school"))
  667. {
  668. if (!string.IsNullOrEmpty(school))
  669. {
  670. List<RGroupList> groupLists= new List<RGroupList>();
  671. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  672. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  673. {
  674. groupLists.Add(item);
  675. }
  676. groups.Add("School", groupLists);
  677. }
  678. }
  679. else if (scopes.Contains("private")) {
  680. List<RGroupList> groupLists = new List<RGroupList>();
  681. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  682. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  683. {
  684. groupLists.Add(item);
  685. //if (string.IsNullOrWhiteSpace(school))
  686. //{
  687. // groupLists.Add(item);
  688. //}
  689. //else
  690. //{
  691. // if (!string.IsNullOrWhiteSpace(item.school))
  692. // {
  693. // if (item.school.Equals(school))
  694. // {
  695. // groupLists.Add(item);
  696. // }
  697. // }
  698. // else {
  699. // groupLists.Add(item);
  700. // }
  701. //}
  702. }
  703. groups.Add("Teacher", groupLists);
  704. }
  705. foreach (var item in groups)
  706. {
  707. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  708. foreach (var group in list)
  709. {
  710. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing,school);
  711. }
  712. }
  713. var lists= groups.SelectMany(x => x.Value).ToList() ;
  714. return lists;
  715. }
  716. 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)
  717. {
  718. try {
  719. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  720. var members = groups.SelectMany(y => y.members).ToList();
  721. //去重
  722. 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();
  723. 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();
  724. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  725. List<Student> studentsData = new List<Student>();
  726. if (stu != null)
  727. {
  728. foreach (var item in stu)
  729. {
  730. var ids = item.list.Select(x => x.id).ToList();
  731. if (ids.IsNotEmpty())
  732. {
  733. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId FROM c ");
  734. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  735. stuSql.Append($"where c.id in ({insql})");
  736. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  737. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  738. {
  739. student.schoolId = item.key;
  740. studentsData.Add(student);
  741. }
  742. }
  743. }
  744. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  745. groups.ForEach(x =>
  746. {
  747. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  748. if (item > 0)
  749. {
  750. changes.Add(x);
  751. }
  752. });
  753. }
  754. List<TmdUser> tmdsData = new List<TmdUser>();
  755. if (tmdids.IsNotEmpty())
  756. {
  757. string memberTbname = "";
  758. if ($"{type}".Equals("activity"))
  759. {
  760. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  761. var schoolTeachers = mbers.GroupBy(y=>y.code).Select(m=>new {key= m.Key,list = m.ToList() });
  762. foreach (var schoolTeacher in schoolTeachers) {
  763. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  764. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  765. tmdidSql.Append($" where c.id in ({insql})");
  766. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  767. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  768. {
  769. tmdsData.Add(tmd);
  770. }
  771. }
  772. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  773. groups.ForEach(x =>
  774. {
  775. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  776. if (item > 0)
  777. {
  778. changes.Add(x);
  779. }
  780. });
  781. }
  782. else {
  783. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  784. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  785. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  786. {
  787. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  788. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  789. tmdidSql.Append($" where c.id in ({insql})");
  790. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  791. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  792. {
  793. tmdsData.Add(tmd);
  794. }
  795. }
  796. else
  797. {
  798. {
  799. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  800. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  801. tmdidSql.Append($" where c.id in ({insql})");
  802. memberTbname = "Teacher";
  803. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  804. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  805. {
  806. tmdsData.Add(tmd);
  807. }
  808. }
  809. {
  810. //取差集,减少二次搜寻
  811. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  812. if (tmdidexp.IsNotEmpty())
  813. {
  814. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  815. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  816. tmdidSql.Append($" where c.id in ({insql})");
  817. memberTbname = "Student";
  818. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  819. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  820. {
  821. tmdsData.Add(tmd);
  822. }
  823. }
  824. }
  825. }
  826. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  827. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  828. groups.ForEach(x =>
  829. {
  830. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  831. if (item > 0)
  832. {
  833. changes.Add(x);
  834. }
  835. });
  836. }
  837. }
  838. ///获取真实的名称
  839. var content = new StringContent(tmdids.Select(x=>x.id).ToJsonString(), Encoding.UTF8, "application/json");
  840. string json = await _coreAPIHttpService.GetUserInfos(content);
  841. if (!string.IsNullOrWhiteSpace(json)) {
  842. try
  843. {
  844. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  845. if (tmdInfos.IsNotEmpty())
  846. {
  847. tmdsData.ForEach(y =>
  848. {
  849. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  850. if (tmd != null)
  851. {
  852. y.name = tmd?.name;
  853. y.picture = tmd?.picture;
  854. }
  855. else {
  856. groups.ForEach(x =>
  857. {
  858. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  859. if (item > 0)
  860. {
  861. changes.Add(x);
  862. }
  863. });
  864. }
  865. });
  866. }
  867. }
  868. catch (Exception ex)
  869. {
  870. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
  871. }
  872. }
  873. tmdids.ForEach(x =>
  874. {
  875. var user = tmdsData.Find(y => y.id.Equals(x.id));
  876. x.name = user?.name;
  877. x.picture = user?.picture;
  878. });
  879. students.ForEach(x =>
  880. {
  881. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  882. x.name = student?.name;
  883. x.picture = student?.picture;
  884. x.classId = student?.classId;
  885. });
  886. var mbs = tmdids;
  887. mbs.AddRange(students);
  888. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  889. {
  890. foreach (var change in changes)
  891. {
  892. change.tcount = change.members.Where(x => x.type == 1).Count();
  893. change.scount = change.members.Where(x => x.type == 2).Count();
  894. GroupList group= change.ToJsonString().ToObject<GroupList>();
  895. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  896. }
  897. }
  898. groups.ForEach(x => x.members.ForEach(y=> {
  899. if (y.type == 1) {
  900. var tmd =tmdids.Find(t => t.id.Equals(y.id));
  901. y.name = tmd?.name;
  902. y.picture = tmd?.picture;
  903. }
  904. if (y.type == 2)
  905. {
  906. var student = students.Find(t => t.id.Equals(y.id)&& t.code.Equals(y.code));
  907. y.name = student?.name;
  908. y.picture = student?.picture;
  909. y.classId = student?.classId;
  910. }
  911. }));
  912. HashSet<string > schoolCodes= groups.SelectMany(x=>x.members).Where(y=>!string.IsNullOrEmpty(y.code)).Select(z=>z.code).ToHashSet();
  913. if (schoolCodes != null && schoolCodes.Count > 0) {
  914. List<School> schools= new List<School>();
  915. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",",schoolCodes.Select(x=>$"'{x}'"))})";
  916. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") })) {
  917. schools.Add(item);
  918. }
  919. if (schools.IsNotEmpty()) {
  920. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  921. var school= schools.Find(j => j.id.Equals(z.code));
  922. z.schoolName = school?.name;
  923. });
  924. }
  925. }
  926. return (groups, mbs);
  927. } catch (Exception ex) {
  928. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location},GetGroupListMemberInfo()\n{ex.Message}{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  929. }
  930. return (null, null);
  931. }
  932. }
  933. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  934. {
  935. public bool Equals((string id, string code) x, (string id, string code) y)
  936. {
  937. return x.id.Equals(y.id) && x.code.Equals(y.code);
  938. }
  939. public int GetHashCode((string id, string code) obj)
  940. {
  941. if (obj.id != null && obj.code != null)
  942. {
  943. return 1;
  944. }
  945. else
  946. {
  947. return 0;
  948. }
  949. }
  950. }
  951. }