GroupListService.cs 41 KB

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