GroupListService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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, no = no,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, no = no, 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<RGroupList>> GetStutmdidListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school)
  271. {
  272. List<RGroupList> groupLists = null;
  273. if (classes.Count == 1 && classes.First().Equals("default") && !string.IsNullOrEmpty(school))
  274. {
  275. //默认的教研组
  276. List<RMember> members = new List<RMember>();
  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. RMember member = new RMember
  280. {
  281. id = item.id,
  282. name = item.name,
  283. picture = item.picture,
  284. type = 1,
  285. };
  286. members.Add(member);
  287. }
  288. RGroupList groupList = new RGroupList
  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<RGroupList> { groupList };
  299. }
  300. else
  301. {
  302. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  303. List<Student> students = new List<Student>();
  304. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  305. if (!string.IsNullOrEmpty(school))
  306. {
  307. List<RGroupList> schoolList = new List<RGroupList>();
  308. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(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<RGroupList> privateList = new List<RGroupList>();
  334. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  335. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(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<RMember> members = 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();
  363. RGroupList group = new RGroupList
  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<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CosmosClient client, string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing)
  383. {
  384. try {
  385. var members = groups.SelectMany(y => y.members).ToList();
  386. //去重
  387. List<RMember> 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<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();
  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,c.classId 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<RGroupList> changes = new HashSet<RGroupList>();
  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. x.classId = student?.classId;
  480. });
  481. var mbs = tmids;
  482. mbs.AddRange(students);
  483. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  484. {
  485. foreach (var change in changes)
  486. {
  487. change.tcount = change.members.Where(x => x.type == 1).Count();
  488. change.scount = change.members.Where(x => x.type == 2).Count();
  489. GroupList group= change.ToJsonString().ToObject<GroupList>();
  490. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  491. }
  492. }
  493. return (groups, mbs);
  494. } catch (Exception ex) {
  495. await _dingDing.SendBotMsg($"OS,GetGroupListMemberInfo()\n{ex.Message}{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  496. }
  497. return (null, null);
  498. }
  499. public static async Task FixActivity(CosmosClient client, DingDing _dingDing, GroupChange groupChange, string type)
  500. {
  501. try
  502. {
  503. 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}' " +
  504. $" and (( array_contains(c.classes,'{groupChange.listid}')) or ( array_contains(c.stuLists,'{groupChange.listid}'))or ( array_contains(c.tchLists,'{groupChange.listid}')))";
  505. //$"and A1 in('{groupChange.listid}') ";
  506. List<MQActivity> datas = new List<MQActivity>();
  507. if (groupChange.scope.Equals("school", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(groupChange.school))
  508. {
  509. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
  510. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{groupChange.school}") }))
  511. {
  512. datas.Add(item);
  513. }
  514. ///还要处理该学校每个老师发布的班级的
  515. List<SchoolTeacher> teachers = new List<SchoolTeacher>();
  516. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>(queryText: $"SELECT c.id, c.name FROM c",
  517. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{groupChange.school}") }))
  518. {
  519. teachers.Add(item);
  520. }
  521. foreach (var techer in teachers)
  522. {
  523. 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 " +
  524. $" where c.school='{groupChange.school}' and c.pk='{type}'" +
  525. $" and (( array_contains(c.classes,'{groupChange.listid}')) or ( array_contains(c.stuLists,'{groupChange.listid}')))";
  526. // $" and A1 in('{groupChange.listid}') ";
  527. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: queryTech,
  528. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{techer.id}") }))
  529. {
  530. datas.Add(item);
  531. }
  532. }
  533. }
  534. if (groupChange.scope.Equals("private", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(groupChange.creatorId))
  535. {
  536. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
  537. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{groupChange.creatorId}") }))
  538. {
  539. datas.Add(item);
  540. }
  541. }
  542. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  543. foreach (MQActivity activity in datas)
  544. {
  545. //已经完结的不再允许加入,还未开始的。
  546. if (activity.progress.Equals("finish") || activity.progress.Equals("pending"))
  547. {
  548. continue;
  549. }
  550. List<string> classes = ExamService.getClasses(activity.classes, activity.stuLists);
  551. //stujoin新加入名单的
  552. foreach (Member member in groupChange.stujoin)
  553. {
  554. var stucourse = new StuActivity
  555. {
  556. id = activity.id,
  557. scode = activity.code,
  558. name = activity.name,
  559. code = $"Activity-{member.code.Replace("Base-", "")}-{member.id}",
  560. scope = activity.scope,
  561. school = activity.school,
  562. creatorId = activity.creatorId,
  563. pk = "Activity",
  564. type = type,
  565. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  566. startTime = activity.startTime,
  567. endTime = activity.endTime,
  568. blob = activity.blob,
  569. owner = activity.owner,
  570. createTime = nowtime,
  571. taskStatus = -1,
  572. classIds = classes
  573. };
  574. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  575. }
  576. //tmdjoin新加入的
  577. foreach (Member member in groupChange.tmdjoin)
  578. {
  579. var stucourse = new StuActivity
  580. {
  581. id = activity.id,
  582. scode = activity.code,
  583. name = activity.name,
  584. code = $"Activity-{member.id}",
  585. scope = activity.scope,
  586. school = activity.school,
  587. creatorId = activity.creatorId,
  588. pk = "Activity",
  589. type = type,
  590. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  591. startTime = activity.startTime,
  592. endTime = activity.endTime,
  593. blob = activity.blob,
  594. owner = activity.owner,
  595. createTime = nowtime,
  596. taskStatus = -1,
  597. classIds = classes
  598. };
  599. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  600. }
  601. //tchjoin新加入的
  602. foreach (Member member in groupChange.tchjoin)
  603. {
  604. var stucourse = new StuActivity
  605. {
  606. id = activity.id,
  607. scode = activity.code,
  608. name = activity.name,
  609. code = $"Activity-{member.id}",
  610. scope = activity.scope,
  611. school = activity.school,
  612. creatorId = activity.creatorId,
  613. pk = "Activity",
  614. type = type,
  615. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  616. startTime = activity.startTime,
  617. endTime = activity.endTime,
  618. blob = activity.blob,
  619. owner = activity.owner,
  620. createTime = nowtime,
  621. taskStatus = -1,
  622. classIds = classes
  623. };
  624. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  625. }
  626. foreach (Member member in groupChange.stuleave)
  627. {
  628. try
  629. {
  630. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.code.Replace("Base-", "")}-{member.id}"));
  631. }
  632. catch (CosmosException)
  633. {
  634. continue;
  635. // 继续执行 删除失败
  636. }
  637. }
  638. foreach (Member member in groupChange.tmdleave)
  639. {
  640. try
  641. {
  642. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.id}"));
  643. }
  644. catch (CosmosException)
  645. {
  646. continue;
  647. // 继续执行 删除失败
  648. }
  649. }
  650. foreach (Member member in groupChange.tchleave)
  651. {
  652. try
  653. {
  654. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.id}"));
  655. }
  656. catch (CosmosException)
  657. {
  658. continue;
  659. // 继续执行 删除失败
  660. }
  661. }
  662. }
  663. }
  664. catch (Exception ex)
  665. {
  666. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n{ex.Message}{ex.StackTrace}{groupChange.ToJsonString()}{type}", GroupNames.醍摩豆服務運維群組);
  667. }
  668. }
  669. public static async Task FixStuCourse(CosmosClient client, DingDing _dingDing, GroupChange groupChange)
  670. {
  671. //1.查找学校或教师的课程是否包含该名单的课程。
  672. 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}'";
  673. List<Course> courses = new List<Course>();
  674. if (groupChange.scope.Equals("school") && !string.IsNullOrEmpty(groupChange.school))
  675. {
  676. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: query,
  677. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{groupChange.school}") }))
  678. {
  679. courses.Add(item);
  680. }
  681. }
  682. if (groupChange.scope.Equals("private") && !string.IsNullOrEmpty(groupChange.creatorId))
  683. {
  684. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Course>(queryText: query,
  685. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{groupChange.creatorId}") }))
  686. {
  687. courses.Add(item);
  688. }
  689. }
  690. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  691. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 需要处理的课程\n{courses.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  692. //2.获取课程的id 并尝试添加或移除对应的学生课程记录StuCourse。
  693. foreach (var course in courses)
  694. {
  695. //学生新加入名单的
  696. foreach (Member member in groupChange.stujoin)
  697. {
  698. var stucourse = new StuCourse
  699. {
  700. id = course.id,
  701. scode = course.code,
  702. name = course.name,
  703. code = $"StuCourse-{member.code.Replace("Base-", "")}-{member.id}",
  704. scope = course.scope,
  705. school = course.school,
  706. creatorId = course.creatorId,
  707. pk = "StuCourse",
  708. stulist = new List<string> { groupChange.listid },
  709. createTime = nowtime
  710. };
  711. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  712. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  713. }
  714. //tmd新加入的
  715. foreach (Member member in groupChange.tmdjoin)
  716. {
  717. var stucourse = new StuCourse
  718. {
  719. id = course.id,
  720. scode = course.code,
  721. name = course.name,
  722. code = $"StuCourse-{member.id}",
  723. scope = course.scope,
  724. school = course.school,
  725. creatorId = course.creatorId,
  726. pk = "StuCourse",
  727. stulist = new List<string> { groupChange.listid },
  728. createTime = nowtime
  729. };
  730. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  731. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  732. }
  733. //移除名单的。 在点击相关的课程,再去二次校验是否存在,不存在则再去删除。
  734. foreach (var delStu in groupChange.stuleave)
  735. {
  736. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delStu.code.Replace("Base-", "")}-{delStu.id}"));
  737. }
  738. foreach (var delTmd in groupChange.tmdleave)
  739. {
  740. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delTmd}"));
  741. }
  742. }
  743. }
  744. }
  745. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  746. {
  747. public bool Equals((string id, string code) x, (string id, string code) y)
  748. {
  749. return x.id.Equals(y.id) && x.code.Equals(y.code);
  750. }
  751. public int GetHashCode((string id, string code) obj)
  752. {
  753. if (obj.id != null && obj.code != null)
  754. {
  755. return 1;
  756. }
  757. else
  758. {
  759. return 0;
  760. }
  761. }
  762. }
  763. }