GroupListService.cs 49 KB

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