GroupListService.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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<RMember>, List<RGroupList> groups)> GetStutmdidListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school)
  272. {
  273. List<RMember> members = new List<RMember>();
  274. List<RGroupList> groupLists = null;
  275. if (classes.Count == 1 && classes.First().Equals("default") && !string.IsNullOrEmpty(school))
  276. {
  277. //默认的教研组
  278. members = new List<RMember>();
  279. 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}") }))
  280. {
  281. RMember member = new RMember
  282. {
  283. id = item.id,
  284. name = item.name,
  285. picture = item.picture,
  286. type = 1,
  287. };
  288. members.Add(member);
  289. }
  290. RGroupList groupList = new RGroupList
  291. {
  292. id = "default",
  293. name = "default",
  294. code = $"GroupList-{school}",
  295. school = school,
  296. scope = "school",
  297. type = "research",
  298. members = members
  299. };
  300. groupLists = new List<RGroupList> { groupList };
  301. }
  302. else
  303. {
  304. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  305. List<Student> students = new List<Student>();
  306. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  307. if (!string.IsNullOrEmpty(school))
  308. {
  309. List<RGroupList> schoolList = new List<RGroupList>();
  310. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  311. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  312. {
  313. schoolList.Add(item);
  314. }
  315. if (schoolList.IsNotEmpty())
  316. {
  317. groups.Add("School", schoolList);
  318. }
  319. //取差集,减少二次搜寻
  320. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  321. if (classes.IsNotEmpty())
  322. {
  323. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  324. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  325. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  326. {
  327. students.Add(item);
  328. }
  329. //取差集,减少二次搜寻
  330. classes = classes.Except(students.Select(y => y.classId)).ToList();
  331. }
  332. }
  333. if (classes.IsNotEmpty())
  334. {
  335. List<RGroupList> privateList = new List<RGroupList>();
  336. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  337. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  338. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  339. {
  340. privateList.Add(item);
  341. }
  342. if (privateList.IsNotEmpty())
  343. {
  344. groups.Add("Teacher", privateList);
  345. }
  346. }
  347. foreach (var item in groups)
  348. {
  349. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  350. foreach (var group in list)
  351. {
  352. (List<RGroupList> rgroups, List<RMember> rmembers) =await GetGroupListMemberInfo(client, group.key, group.list, item.Key,_dingDing);
  353. members.AddRange(rmembers);
  354. }
  355. }
  356. groupLists = groups.SelectMany(x => x.Value).ToList();
  357. if (students.IsNotEmpty())
  358. {
  359. List<string> sqlList = students.Select(x => x.classId).ToList();
  360. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  361. 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})",
  362. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  363. {
  364. ///行政班(学生搜寻classId动态返回)class
  365. List<RMember> smembers = 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();
  366. RGroupList group = new RGroupList
  367. {
  368. id = item.id,
  369. code = $"GroupList-{school}",
  370. name = item.name,
  371. periodId = item.periodId,
  372. scope = "school",
  373. school = school,
  374. type = "class",
  375. year = item.year,
  376. members = smembers,
  377. scount = smembers.Count
  378. };
  379. groupLists.Add(group);
  380. }
  381. }
  382. }
  383. return (members,groupLists);
  384. }
  385. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CosmosClient client, string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing)
  386. {
  387. try {
  388. var members = groups.SelectMany(y => y.members).ToList();
  389. //去重
  390. 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();
  391. 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();
  392. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  393. List<Student> studentsData = new List<Student>();
  394. if (stu != null)
  395. {
  396. foreach (var item in stu)
  397. {
  398. var ids = item.list.Select(x => x.id).ToList();
  399. if (ids.IsNotEmpty())
  400. {
  401. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.classId FROM c ");
  402. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  403. stuSql.Append($"where c.id in ({insql})");
  404. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  405. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  406. {
  407. student.schoolId = item.key;
  408. studentsData.Add(student);
  409. }
  410. }
  411. }
  412. }
  413. List<TmdUser> tmdsData = new List<TmdUser>();
  414. if (tmdids.IsNotEmpty())
  415. {
  416. string memberTbname = "";
  417. //可能会出现在两种表中
  418. if ($"{type}".Equals("teach") || $"{type}".Equals("research") || $"{type}".Equals("group")
  419. || $"{type}".Equals("friend") || $"{type}".Equals("manage") || $"{type}".Equals("subject"))
  420. {
  421. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  422. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  423. tmdidSql.Append($" where c.id in ({insql})");
  424. memberTbname = "Teacher";
  425. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  426. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  427. {
  428. tmdsData.Add(tmd);
  429. }
  430. }
  431. if ($"{type}".Equals("teach") || $"{type}".Equals("friend") || $"{type}".Equals("group"))
  432. {
  433. //取差集,减少二次搜寻
  434. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  435. if (tmdidexp.IsNotEmpty())
  436. {
  437. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  438. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  439. tmdidSql.Append($" where c.id in ({insql})");
  440. memberTbname = "Student";
  441. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  442. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  443. {
  444. tmdsData.Add(tmd);
  445. }
  446. }
  447. }
  448. //去重
  449. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  450. }
  451. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  452. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  453. groups.ForEach(x =>
  454. {
  455. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  456. if (item > 0)
  457. {
  458. changes.Add(x);
  459. }
  460. });
  461. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  462. groups.ForEach(x =>
  463. {
  464. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  465. if (item > 0)
  466. {
  467. changes.Add(x);
  468. }
  469. });
  470. tmdids.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.schoolId.Equals(x.code));
  479. x.name = student?.name;
  480. x.picture = student?.picture;
  481. x.no = student?.no;
  482. x.classId = student?.classId;
  483. });
  484. var mbs = tmdids;
  485. mbs.AddRange(students);
  486. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  487. {
  488. foreach (var change in changes)
  489. {
  490. change.tcount = change.members.Where(x => x.type == 1).Count();
  491. change.scount = change.members.Where(x => x.type == 2).Count();
  492. GroupList group= change.ToJsonString().ToObject<GroupList>();
  493. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  494. }
  495. }
  496. groups.ForEach(x => x.members.ForEach(y=> {
  497. if (y.type == 1) {
  498. var tmd =tmdids.Find(t => t.id.Equals(y.id));
  499. y.name = tmd?.name;
  500. y.picture = tmd?.picture;
  501. }
  502. if (y.type == 2)
  503. {
  504. var student = students.Find(t => t.id.Equals(y.id)&& t.code.Equals(y.code));
  505. y.name = student?.name;
  506. y.picture = student?.picture;
  507. y.no = student?.no;
  508. y.classId = student?.classId;
  509. }
  510. }));
  511. return (groups, mbs);
  512. } catch (Exception ex) {
  513. await _dingDing.SendBotMsg($"OS,GetGroupListMemberInfo()\n{ex.Message}{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  514. }
  515. return (null, null);
  516. }
  517. public static async Task FixActivity(CosmosClient client, DingDing _dingDing, GroupChange groupChange, string type)
  518. {
  519. try
  520. {
  521. 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}' " +
  522. $" and (( array_contains(c.classes,'{groupChange.listid}')) or ( array_contains(c.stuLists,'{groupChange.listid}'))or ( array_contains(c.tchLists,'{groupChange.listid}')))";
  523. //$"and A1 in('{groupChange.listid}') ";
  524. List<MQActivity> datas = new List<MQActivity>();
  525. if (groupChange.scope.Equals("school", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(groupChange.school))
  526. {
  527. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
  528. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{groupChange.school}") }))
  529. {
  530. datas.Add(item);
  531. }
  532. ///还要处理该学校每个老师发布的班级的
  533. List<SchoolTeacher> teachers = new List<SchoolTeacher>();
  534. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>(queryText: $"SELECT c.id, c.name FROM c",
  535. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{groupChange.school}") }))
  536. {
  537. teachers.Add(item);
  538. }
  539. foreach (var techer in teachers)
  540. {
  541. 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 " +
  542. $" where c.school='{groupChange.school}' and c.pk='{type}'" +
  543. $" and (( array_contains(c.classes,'{groupChange.listid}')) or ( array_contains(c.stuLists,'{groupChange.listid}')))";
  544. // $" and A1 in('{groupChange.listid}') ";
  545. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: queryTech,
  546. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{techer.id}") }))
  547. {
  548. datas.Add(item);
  549. }
  550. }
  551. }
  552. if (groupChange.scope.Equals("private", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(groupChange.creatorId))
  553. {
  554. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
  555. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{groupChange.creatorId}") }))
  556. {
  557. datas.Add(item);
  558. }
  559. }
  560. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  561. foreach (MQActivity activity in datas)
  562. {
  563. //已经完结的不再允许加入,还未开始的。
  564. if (activity.progress.Equals("finish") || activity.progress.Equals("pending"))
  565. {
  566. continue;
  567. }
  568. List<string> classes = ExamService.getClasses(activity.classes, activity.stuLists);
  569. //stujoin新加入名单的
  570. foreach (Member member in groupChange.stujoin)
  571. {
  572. var stucourse = new StuActivity
  573. {
  574. id = activity.id,
  575. scode = activity.code,
  576. name = activity.name,
  577. code = $"Activity-{member.code.Replace("Base-", "")}-{member.id}",
  578. scope = activity.scope,
  579. school = activity.school,
  580. creatorId = activity.creatorId,
  581. pk = "Activity",
  582. type = type,
  583. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  584. startTime = activity.startTime,
  585. endTime = activity.endTime,
  586. blob = activity.blob,
  587. owner = activity.owner,
  588. createTime = nowtime,
  589. taskStatus = -1,
  590. classIds = classes
  591. };
  592. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  593. }
  594. //tmdjoin新加入的
  595. foreach (Member member in groupChange.tmdjoin)
  596. {
  597. var stucourse = new StuActivity
  598. {
  599. id = activity.id,
  600. scode = activity.code,
  601. name = activity.name,
  602. code = $"Activity-{member.id}",
  603. scope = activity.scope,
  604. school = activity.school,
  605. creatorId = activity.creatorId,
  606. pk = "Activity",
  607. type = type,
  608. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  609. startTime = activity.startTime,
  610. endTime = activity.endTime,
  611. blob = activity.blob,
  612. owner = activity.owner,
  613. createTime = nowtime,
  614. taskStatus = -1,
  615. classIds = classes
  616. };
  617. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  618. }
  619. //tchjoin新加入的
  620. foreach (Member member in groupChange.tchjoin)
  621. {
  622. var stucourse = new StuActivity
  623. {
  624. id = activity.id,
  625. scode = activity.code,
  626. name = activity.name,
  627. code = $"Activity-{member.id}",
  628. scope = activity.scope,
  629. school = activity.school,
  630. creatorId = activity.creatorId,
  631. pk = "Activity",
  632. type = type,
  633. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  634. startTime = activity.startTime,
  635. endTime = activity.endTime,
  636. blob = activity.blob,
  637. owner = activity.owner,
  638. createTime = nowtime,
  639. taskStatus = -1,
  640. classIds = classes
  641. };
  642. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  643. }
  644. foreach (Member member in groupChange.stuleave)
  645. {
  646. try
  647. {
  648. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.code.Replace("Base-", "")}-{member.id}"));
  649. }
  650. catch (CosmosException)
  651. {
  652. continue;
  653. // 继续执行 删除失败
  654. }
  655. }
  656. foreach (Member member in groupChange.tmdleave)
  657. {
  658. try
  659. {
  660. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.id}"));
  661. }
  662. catch (CosmosException)
  663. {
  664. continue;
  665. // 继续执行 删除失败
  666. }
  667. }
  668. foreach (Member member in groupChange.tchleave)
  669. {
  670. try
  671. {
  672. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{member.id}"));
  673. }
  674. catch (CosmosException)
  675. {
  676. continue;
  677. // 继续执行 删除失败
  678. }
  679. }
  680. }
  681. }
  682. catch (Exception ex)
  683. {
  684. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n{ex.Message}{ex.StackTrace}{groupChange.ToJsonString()}{type}", GroupNames.醍摩豆服務運維群組);
  685. }
  686. }
  687. public static async Task FixStuCourse(CosmosClient client, DingDing _dingDing, GroupChange groupChange)
  688. {
  689. //1.查找学校或教师的课程是否包含该名单的课程。
  690. 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}'";
  691. List<Course> courses = new List<Course>();
  692. if (groupChange.scope.Equals("school") && !string.IsNullOrEmpty(groupChange.school))
  693. {
  694. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: query,
  695. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{groupChange.school}") }))
  696. {
  697. courses.Add(item);
  698. }
  699. }
  700. if (groupChange.scope.Equals("private") && !string.IsNullOrEmpty(groupChange.creatorId))
  701. {
  702. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Course>(queryText: query,
  703. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{groupChange.creatorId}") }))
  704. {
  705. courses.Add(item);
  706. }
  707. }
  708. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  709. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 需要处理的课程\n{courses.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  710. //2.获取课程的id 并尝试添加或移除对应的学生课程记录StuCourse。
  711. foreach (var course in courses)
  712. {
  713. //学生新加入名单的
  714. foreach (Member member in groupChange.stujoin)
  715. {
  716. var stucourse = new StuCourse
  717. {
  718. id = course.id,
  719. scode = course.code,
  720. name = course.name,
  721. code = $"StuCourse-{member.code.Replace("Base-", "")}-{member.id}",
  722. scope = course.scope,
  723. school = course.school,
  724. creatorId = course.creatorId,
  725. pk = "StuCourse",
  726. stulist = new List<string> { groupChange.listid },
  727. createTime = nowtime
  728. };
  729. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  730. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  731. }
  732. //tmd新加入的
  733. foreach (Member member in groupChange.tmdjoin)
  734. {
  735. var stucourse = new StuCourse
  736. {
  737. id = course.id,
  738. scode = course.code,
  739. name = course.name,
  740. code = $"StuCourse-{member.id}",
  741. scope = course.scope,
  742. school = course.school,
  743. creatorId = course.creatorId,
  744. pk = "StuCourse",
  745. stulist = new List<string> { groupChange.listid },
  746. createTime = nowtime
  747. };
  748. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  749. await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  750. }
  751. //移除名单的。 在点击相关的课程,再去二次校验是否存在,不存在则再去删除。
  752. foreach (var delStu in groupChange.stuleave)
  753. {
  754. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delStu.code.Replace("Base-", "")}-{delStu.id}"));
  755. }
  756. foreach (var delTmd in groupChange.tmdleave)
  757. {
  758. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delTmd}"));
  759. }
  760. }
  761. }
  762. }
  763. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  764. {
  765. public bool Equals((string id, string code) x, (string id, string code) y)
  766. {
  767. return x.id.Equals(y.id) && x.code.Equals(y.code);
  768. }
  769. public int GetHashCode((string id, string code) obj)
  770. {
  771. if (obj.id != null && obj.code != null)
  772. {
  773. return 1;
  774. }
  775. else
  776. {
  777. return 0;
  778. }
  779. }
  780. }
  781. }