GroupListService.cs 41 KB

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