GroupListService.cs 50 KB

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