GroupListService.cs 40 KB

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