GroupListService.cs 42 KB

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