GroupListService.cs 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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. using System.Text.RegularExpressions;
  17. using TEAMModelOS.SDK.Models;
  18. using System.Net.Http;
  19. using DocumentFormat.OpenXml.Wordprocessing;
  20. using static TEAMModelOS.SDK.GroupListService;
  21. namespace TEAMModelOS.SDK
  22. {
  23. public class GroupListService
  24. {
  25. public static async Task DeleteGrouplistEvent(string id , string code,string tbname ,CosmosClient client, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
  26. {
  27. GroupChange change = new GroupChange();
  28. GroupList groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(id.ToString(), new PartitionKey(code));
  29. var tleave = groupList.members.FindAll(x => x.type == 1);
  30. if (tleave.IsNotEmpty())
  31. {
  32. if (groupList.type.Equals("research") || groupList.type.Equals("yxtrain"))
  33. {
  34. change.tchleave.AddRange(tleave);
  35. }
  36. else
  37. {
  38. change.tmdleave.AddRange(tleave);
  39. }
  40. }
  41. var sleave = groupList.members.FindAll(x => x.type == 2);
  42. if (sleave.IsNotEmpty())
  43. {
  44. change.stuleave.AddRange(sleave);
  45. }
  46. change.listid = groupList.id;
  47. change.scope = groupList.scope;
  48. change.originCode = $"{code}";
  49. change.school = groupList.school;
  50. change.creatorId = groupList.creatorId;
  51. change.type = groupList.type;
  52. change.status = "delete";
  53. if (change.tmdleave.IsNotEmpty() || change.tchleave.IsNotEmpty() || change.stuleave.IsNotEmpty())
  54. {
  55. var messageChange = new ServiceBusMessage(change.ToJsonString());
  56. messageChange.ApplicationProperties.Add("name", "GroupChange");
  57. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  58. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  59. }
  60. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(id.ToString(), new PartitionKey(code));
  61. }
  62. /// <summary>
  63. /// 查询名单成员所在的名单列表,
  64. /// </summary>
  65. /// <param name="_coreAPIHttpService"></param>
  66. /// <param name="client"></param>
  67. /// <param name="_dingDing"></param>
  68. /// <param name="memberId">成员id </param>
  69. /// <param name="memberType">成员类型</param>
  70. /// <param name="school">成员所在的学校 ,可为空</param>
  71. /// <param name="groupTypes">过滤名单的类型集合,不传则是全部</param>
  72. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  73. /// <returns></returns>
  74. public static async Task<List<GroupListGrp>> GetMemberInGroupList(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing, string memberId, int memberType, string school,List<string> groupTypes,int graduate =-1) {
  75. List<GroupListGrp> groupLists = new List<GroupListGrp>();
  76. if (groupTypes.IsEmpty() || groupTypes.Contains("class")) {
  77. if (!string.IsNullOrWhiteSpace(school) && memberType == 2)
  78. {
  79. Student student = null;
  80. try
  81. {
  82. student = await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemAsync<Student>(memberId, new PartitionKey($"Base-{school}"));
  83. }
  84. catch (CosmosException ex) when (ex.Status == 404)
  85. {
  86. return null;
  87. }
  88. if (!string.IsNullOrWhiteSpace(student.classId))
  89. {
  90. try
  91. {
  92. Class clazz = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(student.classId, new PartitionKey($"Class-{school}"));
  93. GroupListGrp groupList = new GroupListGrp
  94. {
  95. id = clazz.id,
  96. code = $"GroupList-{clazz.school}",
  97. name = clazz.name,
  98. periodId = clazz.periodId,
  99. pk = "GroupList",
  100. expire=0,
  101. year = clazz.year,
  102. school = clazz.school,
  103. scope = "school",
  104. type = "class",
  105. no = clazz.no,
  106. leader = clazz.teacher?.id,
  107. graduate=clazz.graduate,
  108. grades= new HashSet<int>() { clazz.year}
  109. };
  110. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  111. if (graduate >= 0 )
  112. {
  113. if (groupList.graduate == graduate) {
  114. groupLists.Add(groupList);
  115. }
  116. }
  117. //全部。
  118. else if(graduate == -1)
  119. {
  120. groupLists.Add(groupList);
  121. }
  122. }
  123. catch (CosmosException ex) when (ex.Status == 404)
  124. {
  125. }
  126. }
  127. }
  128. }
  129. string SummarySql = " 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.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire,c.qrcodeExpire ,c.qrcodeDays ,c.grades ";
  130. if (groupTypes.IsEmpty() || groupTypes.Contains("teach")) {
  131. //教学班
  132. string teachsql="";
  133. if (!string.IsNullOrWhiteSpace(school) && memberType == 2) {
  134. teachsql= $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='teach' and m.id='{memberId}' and m.code='{school}' and m.type=2 ";
  135. }
  136. if (memberType == 1)
  137. {
  138. teachsql=$"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='teach' and m.id='{memberId}' and m.type=1 ";
  139. }
  140. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  141. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  142. {
  143. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  144. groupLists.Add(new GroupListGrp(item, groupName));
  145. }
  146. //个人名单
  147. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  148. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  149. {
  150. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  151. groupLists.Add(new GroupListGrp(item, groupName));
  152. }
  153. }
  154. if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("research")))
  155. {
  156. //教研组
  157. string teachsql = $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='research' and m.id='{memberId}' and m.type=1 ";
  158. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  159. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  160. {
  161. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  162. groupLists.Add(new GroupListGrp(item, groupName));
  163. }
  164. }
  165. if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("yxtrain")))
  166. {
  167. //研修名单
  168. string teachsql = $"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='yxtrain' and m.id='{memberId}' and m.type=1 ";
  169. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  170. GetItemQueryIterator<GroupList>(queryText: teachsql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  171. {
  172. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  173. groupLists.Add(new GroupListGrp(item, groupName));
  174. }
  175. }
  176. return groupLists;
  177. }
  178. /// <summary>
  179. ///-1状态异常,0加入成功, 1加入学生或醍摩豆ID为空,2重复加入 ,3不允许跨校加入名单, 4表示个人名单未开放加入,状态=5 ,人数已满。状态=6 ,需要审核通过再加入。状态7 二维码设置已经过期
  180. /// </summary>
  181. /// <param name="client"></param>
  182. /// <param name="_stuListNo"></param>
  183. /// <param name="userid"></param>
  184. /// <param name="type"></param>
  185. /// <param name="school"></param>
  186. /// <returns></returns>
  187. public static async Task<(int status, GroupList stuList,Member member)> CodeJoinList(CosmosClient client,AzureRedisFactory _azureRedis, string _stuListNo, string userid, int type, string school,int year,string name ,string picture,string lang,string courseId= null)
  188. {
  189. var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
  190. (int status, GroupList stuList,Member member) data = (-1, null,null);
  191. if (!string.IsNullOrEmpty(school))
  192. {
  193. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryNo,
  194. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  195. {
  196. data = JoinList(item, userid, type, school,year);
  197. break;
  198. }
  199. }
  200. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
  201. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  202. {
  203. if (item.joinLock == 0) {
  204. //状态=4 表示未开放加入。
  205. return (4, item, null) ;
  206. }
  207. if (item.review ==1)
  208. {
  209. //状态=6 ,人数已满,需要审核通过再加入。
  210. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  211. if (now>item.qrcodeExpire)
  212. {
  213. //二维码设置已经过期,只有需要审核的时候才检查二维码过期问题,目的是为了未正式加入人员的缓存
  214. return (7, item, null);
  215. }
  216. else
  217. {
  218. GroupWaitingList waitingList = new GroupWaitingList
  219. {
  220. stuListNo=_stuListNo,
  221. userid=userid,
  222. type=type,
  223. school= school,
  224. year = year,
  225. groupId = item.id,
  226. groupScope=item.scope,
  227. name = name,
  228. picture = picture,
  229. lang = lang,
  230. qrcodeExpire=item.qrcodeExpire,
  231. groupName= item.name,
  232. applyTime=now
  233. };
  234. string sql = "select value c from c join b in c.schedules where b.groupId='60f92012-72cf-4d5c-a66a-552678303fad'";
  235. string key = $"GroupList:GroupWaitingList:{item.scope}:{item.id}";
  236. string filed = !string.IsNullOrWhiteSpace(school) ? $"{school}_{userid}" : userid;
  237. await _azureRedis.GetRedisClient(8).HashSetAsync(key, filed, waitingList.ToJsonString());
  238. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(item.qrcodeExpire).UtcDateTime);
  239. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{userid}" :$"GroupList:StudentWaitinglist:{userid}" ;
  240. string sutFiled = $"{item.scope}:{item.id}";
  241. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, waitingList.ToJsonString());
  242. //三十天都不登录,则不需要查看申请清单,30*24=720
  243. await _azureRedis.GetRedisClient(8).KeyExpireAsync(stuKey, new TimeSpan(720 , 0, 0));
  244. return (6, item, null);
  245. }
  246. }
  247. if (item.members!=null &&item.limitCount>0 && item.members.Count>=item.limitCount) {
  248. //状态=5 ,人数已满
  249. return (5, item, null);
  250. }
  251. data = JoinList(item, userid, type, school,year);
  252. //TODO 需要考虑已经通过别的途径加入名单,但是缓存数据仍记录数据的问题。 还要考虑手动加入过的。或者在获取名未加入名单成员的临时缓存数据的时候过滤已经加入的。
  253. break;
  254. }
  255. return data;
  256. }
  257. /// <summary>
  258. /// 加入名单等候列表
  259. /// </summary>
  260. public class GroupWaitingList
  261. {
  262. /// <summary>
  263. ///
  264. /// </summary>
  265. public string stuListNo { get; set; }
  266. public string userid { get; set; }
  267. //学生类型,1醍摩豆id,2 校内账号
  268. public int type { get; set; }
  269. public string school { get; set; }
  270. public int year { get; set; }
  271. public string groupId { get; set; }
  272. public string groupScope { get; set; }
  273. public string name { get; set; }
  274. public string picture { get; set; }
  275. public string lang { get; set; }
  276. public long qrcodeExpire { get; set; }
  277. public string groupName { get; set; }
  278. public long applyTime{ get; set; }
  279. /// <summary>
  280. /// 申请状态,-1 申请中,0 通过,1 拒绝,2 已过期。
  281. /// </summary>
  282. public int status { get; set; } = -1;
  283. public List<IdName> courses { get; set; }= new List<IdName>();
  284. }
  285. public static (int status, GroupList stuList, Member member) JoinList(GroupList stuList, string userid, int type, string school,int year)
  286. {
  287. int status = -1;
  288. if (!string.IsNullOrWhiteSpace(stuList.school) && !string.IsNullOrWhiteSpace(school))
  289. {
  290. if (!stuList.school.Equals(school))
  291. {
  292. status = 3;//不允许跨校加入名单
  293. return (status, stuList,null);
  294. }
  295. }
  296. string irs = string.Empty;
  297. List<string> irsOrder = stuList.members.Select(x => x.irs)?.Where(y => !string.IsNullOrEmpty(y) && Regex.IsMatch(y, @"^\d*$")).OrderBy(x => int.Parse(x)).ToList();
  298. if (!irsOrder.Contains("0"))
  299. {
  300. irsOrder.Insert(0, "0");
  301. }
  302. if (irsOrder != null)
  303. {
  304. if (!irsOrder.Contains("0"))
  305. {
  306. irsOrder.Insert(0, "0");
  307. }
  308. }
  309. else { irsOrder = new List<string>() { "0" }; }
  310. for (int i = 0; i < irsOrder.Count; i++)
  311. {
  312. irs = $"{int.Parse(irsOrder[i]) + 1}";
  313. int index = i + 1;
  314. if (index <= irsOrder.Count - 1)
  315. {
  316. if (!irs.Equals(irsOrder[index]))
  317. {
  318. break;
  319. }
  320. }
  321. }
  322. Member member = null;
  323. if (string.IsNullOrEmpty($"{userid}"))
  324. {
  325. //加入学生或醍摩豆ID为空
  326. status = 1;
  327. }
  328. else
  329. {
  330. if (type == 1)
  331. {
  332. member = stuList.members.Find(x => x.type == 1 && x.id.Equals(userid));
  333. if (member != null)
  334. {
  335. //重复加入
  336. status = 2;
  337. }
  338. else
  339. {
  340. //加入成功
  341. status = 0;
  342. member = new Member { id = userid, type = type, irs = irs, no = irs,year=year };
  343. stuList.members.Add(member);
  344. }
  345. }
  346. else if (type == 2)
  347. {
  348. member = stuList.members.Find(x => x.type == 2 && x.id.Equals(userid) && x.code.Equals(school));
  349. if (member != null)
  350. {
  351. //重复加入
  352. status = 2;
  353. }
  354. else
  355. {
  356. status = 0;
  357. member = new Member { id = userid, code = school, type = type, irs = irs, no = irs, year = year };
  358. stuList.members.Add(member);
  359. }
  360. }
  361. }
  362. return (status, stuList, member);
  363. }
  364. public static async Task<GroupList> UpsertList(GroupList list, AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
  365. {
  366. bool isnew = false;
  367. var client = _azureCosmos.GetCosmosClient();
  368. if (string.IsNullOrEmpty(list.id))
  369. {
  370. list.id = Guid.NewGuid().ToString();
  371. isnew = true;
  372. }
  373. string tbname = list.scope.Equals("private") ? "Teacher" : "School";
  374. var tmembers = list.members.Where(x => x.type == 1);
  375. var smembers = list.members.Where(x => x.type == 2);
  376. //处理年级
  377. HashSet<int> grades = new HashSet<int>();
  378. if (smembers.Any()) {
  379. grades = smembers.Where(z => z.year > 2000).Select(z=>z.year).ToHashSet();
  380. }
  381. list.grades = grades;
  382. list.scount = smembers.Count();
  383. list.tcount = tmembers.Count();
  384. //if (smembers.Count() > 0 && smembers.Select(x => x.code).ToHashSet().Count()>=2) {
  385. // //处理移除多个学校的名单,只保留一个学校的。
  386. // if (string.IsNullOrWhiteSpace(list.school))
  387. // {
  388. // HashSet<string> codes = smembers.Select(x => x.code).ToHashSet();
  389. // list.school = codes.First();
  390. // codes.Remove(codes.First());
  391. // list.members.RemoveAll(x => codes.Contains(x.code));
  392. // }
  393. // else {
  394. // list.members.RemoveAll(x => !x.code.Equals(list.school));
  395. // }
  396. //}
  397. if (string.IsNullOrWhiteSpace(list.school) && smembers.Count() >= 1)
  398. {
  399. list.school = smembers.First().code;
  400. }
  401. if (!string.IsNullOrWhiteSpace(list.school) && smembers.Count() == 0 && list.scope.Equals("private"))
  402. {
  403. list.school = null;
  404. }
  405. //学生名单,教研组会触发活动中间表刷新
  406. if (list.type.Equals("teach") || list.type.Equals("research") || list.type.Equals("yxtrain") || list.type.Equals("activity"))
  407. {
  408. GroupChange change = new GroupChange()
  409. {
  410. type = list.type,
  411. listid = list.id,
  412. scope = list.scope,
  413. originCode = list.school,
  414. school = list.school,
  415. creatorId = list.creatorId
  416. };
  417. GroupList oldList = null;
  418. if (!isnew)
  419. {
  420. try
  421. {
  422. oldList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(list.id, new PartitionKey(list.code));
  423. }
  424. catch (CosmosException)
  425. {
  426. oldList = null;
  427. }
  428. }
  429. if (list.members.IsNotEmpty() && (oldList == null || !oldList.members.IsNotEmpty()))
  430. {
  431. //加入的
  432. var tmdids = list.members.FindAll(x => x.type == 1);
  433. if (tmdids.IsNotEmpty())
  434. {
  435. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  436. {
  437. change.tchjoin.AddRange(tmdids);
  438. }
  439. else
  440. {
  441. change.tmdjoin.AddRange(tmdids);
  442. }
  443. }
  444. var stuids = list.members.FindAll(x => x.type == 2);
  445. if (stuids.IsNotEmpty())
  446. {
  447. change.stujoin.AddRange(stuids);
  448. }
  449. }
  450. else
  451. {
  452. if (list.members.IsNotEmpty())
  453. {
  454. var tmdids = list.members.FindAll(x => x.type == 1);
  455. var oldtmdids = oldList.members.FindAll(x => x.type == 1);
  456. //取各自的差集
  457. //新=》旧差集,表示新增
  458. var jointmdid = tmdids.Select(x => x.id).Except(oldtmdids.Select(y => y.id)).ToList();
  459. //旧=》新差集,表示离开
  460. var leavetmdid = oldtmdids.Select(x => x.id).Except(tmdids.Select(y => y.id)).ToList();
  461. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  462. {
  463. change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  464. change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  465. }
  466. else
  467. {
  468. change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  469. change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  470. }
  471. var stuids = list.members.FindAll(x => x.type == 2);
  472. var oldstuids = oldList.members.FindAll(x => x.type == 2);
  473. var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  474. var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  475. change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  476. change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  477. }
  478. else
  479. {
  480. //离开的
  481. if (oldList != null)
  482. {
  483. var tmdids = oldList.members.FindAll(x => x.type == 1);
  484. if (tmdids.IsNotEmpty())
  485. {
  486. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  487. {
  488. change.tchleave.AddRange(tmdids);
  489. }
  490. else
  491. {
  492. change.tmdleave.AddRange(tmdids);
  493. }
  494. }
  495. var stuids = oldList.members.FindAll(x => x.type == 2);
  496. if (stuids.IsNotEmpty())
  497. {
  498. change.stuleave.AddRange(stuids);
  499. }
  500. }
  501. }
  502. }
  503. if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
  504. || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
  505. {
  506. var messageChange = new ServiceBusMessage(change.ToJsonString());
  507. messageChange.ApplicationProperties.Add("name", "GroupChange");
  508. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  509. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  510. }
  511. }
  512. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
  513. return list;
  514. }
  515. public static async Task<GroupList> CheckListNo(GroupList list, AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option)
  516. {
  517. try
  518. {
  519. var client = _azureCosmos.GetCosmosClient();
  520. if (string.IsNullOrEmpty(list.no))
  521. {
  522. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  523. for (int i = 0; i < 10; i++)
  524. {
  525. List<string> noStus = new List<string>();
  526. var queryNo = $"SELECT c.no FROM c where c.no ='{list.no}'";
  527. if (list.scope.Equals("school"))
  528. {
  529. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
  530. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{list.code}") }))
  531. {
  532. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  533. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  534. {
  535. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  536. while (accounts.MoveNext())
  537. {
  538. JsonElement account = accounts.Current;
  539. noStus.Add(account.GetProperty("no").GetString());
  540. }
  541. }
  542. }
  543. }
  544. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
  545. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("GroupList") }))
  546. {
  547. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  548. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  549. {
  550. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  551. while (accounts.MoveNext())
  552. {
  553. JsonElement account = accounts.Current;
  554. noStus.Add(account.GetProperty("no").GetString());
  555. }
  556. }
  557. }
  558. if (noStus.Count == 0)
  559. {
  560. break;
  561. }
  562. else
  563. {
  564. if (i == 9)
  565. {
  566. string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
  567. await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
  568. throw new Exception(msg);
  569. }
  570. else
  571. {
  572. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  573. }
  574. }
  575. }
  576. }
  577. }
  578. catch (Exception ex)
  579. {
  580. }
  581. return list;
  582. }
  583. /// <summary>
  584. ///根据任意名单id获取名单摘要信息。
  585. /// </summary>
  586. /// <param name="client"></param>
  587. /// <param name="_dingDing"></param>
  588. /// <param name="classes"></param>
  589. /// <param name="school"></param>
  590. /// <param name="SummarySql"></param>
  591. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  592. /// <returns></returns>
  593. public static async Task<List<GroupListDto>> GetGroupListByListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school,
  594. string SummarySql = " 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.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire ,c.qrcodeExpire,c.qrcodeDays ,c.grades ", int graduate = -1)
  595. {
  596. List<GroupListDto> groupLists = null;
  597. try
  598. {
  599. classes.RemoveAll(x => x == null);
  600. if (!classes.IsNotEmpty())
  601. {
  602. return null;
  603. }
  604. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  605. {
  606. //默认的教研组
  607. GroupListDto groupList = new GroupListDto
  608. {
  609. id = "TeacherAll",
  610. name = "TeacherAll",
  611. code = $"GroupList-{school}",
  612. school = school,
  613. scope = "school",
  614. type = "yxtrain",
  615. };
  616. groupLists = new List<GroupListDto> { groupList };
  617. }
  618. else
  619. {
  620. Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
  621. //List<Student> students = new List<Student>();
  622. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  623. if (!string.IsNullOrEmpty(school))
  624. {
  625. List<GroupListDto> schoolList = new List<GroupListDto>();
  626. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  627. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  628. {
  629. schoolList.Add(item);
  630. }
  631. if (schoolList.IsNotEmpty())
  632. {
  633. groups.Add("School", schoolList);
  634. }
  635. //取差集,减少二次搜寻
  636. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  637. if (classes.IsNotEmpty())
  638. {
  639. if (!groupLists.IsNotEmpty())
  640. {
  641. groupLists = new List<GroupListDto>();
  642. }
  643. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  644. //搜寻没有关联学生的行政班
  645. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText:
  646. $"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 ,c.graduate from c where c.id in ({insql})",
  647. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  648. {
  649. ///行政班(学生搜寻classId动态返回)class
  650. GroupListDto group = new GroupListDto
  651. {
  652. id = item.id,
  653. code = $"GroupList-{school}",
  654. name = item.name,
  655. periodId = item.periodId,
  656. scope = "school",
  657. school = school,
  658. type = "class",
  659. year = item.year,
  660. expire = item.expire,
  661. leader = item.leader,
  662. no = item.no,
  663. pk = "GroupList",
  664. graduate = item.graduate,
  665. grades= new HashSet<int> { item.year }
  666. };
  667. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  668. if (graduate >= 0)
  669. {
  670. if (group.graduate == graduate)
  671. {
  672. groupLists.Add(group);
  673. }
  674. }
  675. //全部。
  676. else
  677. {
  678. groupLists.Add(group);
  679. }
  680. // groupLists.Add(group);
  681. }
  682. //取差集,减少二次搜寻
  683. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  684. }
  685. }
  686. if (classes.IsNotEmpty())
  687. {
  688. List<GroupListDto> privateList = new List<GroupListDto>();
  689. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  690. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  691. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  692. {
  693. privateList.Add(item);
  694. //if (string.IsNullOrWhiteSpace(school))
  695. //{
  696. // privateList.Add(item);
  697. //}
  698. //else
  699. //{
  700. // if (!string.IsNullOrWhiteSpace(item.school))
  701. // {
  702. // if (item.school.Equals(school))
  703. // {
  704. // privateList.Add(item);
  705. // }
  706. // }
  707. // else
  708. // {
  709. // privateList.Add(item);
  710. // }
  711. //}
  712. }
  713. if (privateList.IsNotEmpty())
  714. {
  715. groups.Add("Teacher", privateList);
  716. }
  717. }
  718. if (groups.Count != 0)
  719. {
  720. if (groupLists.IsNotEmpty())
  721. {
  722. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  723. }
  724. else
  725. {
  726. groupLists = groups.SelectMany(x => x.Value).ToList();
  727. }
  728. }
  729. }
  730. } catch (Exception ex ) {
  731. await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  732. }
  733. return groupLists;
  734. }
  735. /// <summary>
  736. /// 根据任意名单id获取成员信息。rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  737. /// </summary>
  738. /// <param name="_coreAPIHttpService"></param>
  739. /// <param name="client"></param>
  740. /// <param name="_dingDing"></param>
  741. /// <param name="classes"></param>
  742. /// <param name="school"></param>
  743. /// <param name="groupids"></param>
  744. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  745. /// <returns></returns>
  746. public static async Task<(List<RMember>rmembers, List<RGroupList> groups)> GetMemberByListids(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing,
  747. List<string> classes, string school, List<(string, List<string>)> groupids = null, int graduate = -1)
  748. {
  749. List<RMember> members = new List<RMember>();
  750. List<RGroupList> groupLists = new List<RGroupList>();
  751. if (classes != null)
  752. {
  753. classes.RemoveAll(x => x == null);
  754. }
  755. if (classes == null || classes.Count <= 0)
  756. {
  757. return (members, groupLists);
  758. }
  759. string periodId = string.Empty;
  760. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  761. {
  762. //默认的教研组
  763. members = new List<RMember>();
  764. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  765. GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ",
  766. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  767. {
  768. RMember member = new RMember
  769. {
  770. id = item.id,
  771. name = item.name,
  772. picture = item.picture,
  773. type = 1,
  774. // nickname=item.name,
  775. };
  776. members.Add(member);
  777. }
  778. RGroupList groupList = new RGroupList
  779. {
  780. id = "TeacherAll",
  781. name = "TeacherAll",
  782. code = $"GroupList-{school}",
  783. school = school,
  784. scope = "school",
  785. type = "TeacherAll",
  786. members = members
  787. };
  788. groupLists = new List<RGroupList> { groupList };
  789. }
  790. else
  791. {
  792. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  793. List<Student> students = new List<Student>();
  794. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  795. if (!string.IsNullOrEmpty(school))
  796. {
  797. List<RGroupList> schoolList = new List<RGroupList>();
  798. string queryText = $"select value(c) from c where c.id in ({sql})";
  799. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  800. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  801. {
  802. schoolList.Add(item);
  803. }
  804. if (schoolList.IsNotEmpty())
  805. {
  806. groups.Add("School", schoolList);
  807. }
  808. //取差集,减少二次搜寻
  809. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  810. if (classes.IsNotEmpty())
  811. {
  812. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  813. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  814. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  815. {
  816. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  817. if (graduate >= 0)
  818. {
  819. if (item.graduate == graduate)
  820. {
  821. students.Add(item);
  822. }
  823. }
  824. //全部。
  825. else
  826. {
  827. students.Add(item);
  828. }
  829. // students.Add(item);
  830. }
  831. //取差集,减少二次搜寻
  832. classes = classes.Except(students.Select(y => y.classId)).ToList();
  833. }
  834. if (classes.IsNotEmpty())
  835. {
  836. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  837. //搜寻没有关联学生的行政班
  838. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  839. .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 ,c.graduate from c where c.id in ({insql})",
  840. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  841. {
  842. ///行政班(学生搜寻classId动态返回)class
  843. List<RMember> smembers = new List<RMember>();
  844. RGroupList group = new RGroupList
  845. {
  846. id = item.id,
  847. code = $"GroupList-{school}",
  848. name = item.name,
  849. periodId = item.periodId,
  850. scope = "school",
  851. school = school,
  852. type = "class",
  853. year = item.year,
  854. expire = item.expire,
  855. members = smembers,
  856. scount = smembers.Count,
  857. pk = "GroupList",
  858. leader = item.leader,
  859. no = item.no,
  860. graduate = item.graduate,
  861. grades= new HashSet<int>() { item.year }
  862. };
  863. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  864. if (graduate >= 0)
  865. {
  866. if (group.graduate == graduate)
  867. {
  868. groupLists.Add(group);
  869. }
  870. }
  871. //全部。
  872. else
  873. {
  874. groupLists.Add(group);
  875. }
  876. //groupLists.Add(group);
  877. }
  878. //取差集,减少二次搜寻
  879. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  880. }
  881. }
  882. if (classes.IsNotEmpty())
  883. {
  884. List<RGroupList> privateList = new List<RGroupList>();
  885. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  886. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  887. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  888. {
  889. privateList.Add(item);
  890. //if (string.IsNullOrWhiteSpace(school))
  891. //{
  892. // privateList.Add(item);
  893. //}
  894. //else
  895. //{
  896. // if (!string.IsNullOrWhiteSpace(item.school))
  897. // {
  898. // if (item.school.Equals(school))
  899. // {
  900. // privateList.Add(item);
  901. // }
  902. // }
  903. // else
  904. // {
  905. // privateList.Add(item);
  906. // }
  907. //}
  908. }
  909. if (privateList.IsNotEmpty())
  910. {
  911. groups.Add("Teacher", privateList);
  912. }
  913. }
  914. foreach (var item in groups)
  915. {
  916. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  917. foreach (var group in list)
  918. {
  919. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  920. members.AddRange(rmembers);
  921. }
  922. }
  923. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  924. if (students.IsNotEmpty())
  925. {
  926. List<string> sqlList = students.Select(x => x.classId).ToList();
  927. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  928. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  929. 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 ,c.graduate from c where c.id in ({insql})",
  930. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  931. {
  932. ///行政班(学生搜寻classId动态返回)class
  933. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  934. .Select(y => new RMember
  935. {
  936. id = y.id,
  937. code = school,
  938. name = y.name,
  939. //nickname = y.name,
  940. type = 2,
  941. picture = y.picture,
  942. no = y.no,
  943. classId = y.classId,
  944. groupId = y.groupId,
  945. groupName = y.groupName,
  946. irs = y.irs,
  947. year= y.year,
  948. graduate = y.graduate,
  949. gender= y.gender,
  950. periodId=y.periodId,
  951. }).ToList();
  952. members.AddRange(smembers);
  953. RGroupList group = new RGroupList
  954. {
  955. id = item.id,
  956. code = $"GroupList-{school}",
  957. name = item.name,
  958. periodId = item.periodId,
  959. scope = "school",
  960. school = school,
  961. type = "class",
  962. expire= item.expire,
  963. year = item.year,
  964. members = smembers,
  965. scount = smembers.Count,
  966. no = item.no,
  967. leader = item.leader,
  968. pk = "GroupList",
  969. graduate = item.graduate,
  970. grades= new HashSet<int> { item.year}
  971. };
  972. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  973. if (graduate >= 0)
  974. {
  975. if (group.graduate == graduate)
  976. {
  977. groupLists.Add(group);
  978. }
  979. }
  980. //全部。
  981. else
  982. {
  983. groupLists.Add(group);
  984. }
  985. // groupLists.Add(group);
  986. }
  987. //去重。
  988. 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();
  989. }
  990. }
  991. if (groupids.IsNotEmpty())
  992. {
  993. List<RMember> rmembers = new List<RMember>();
  994. groupLists.ForEach(y => {
  995. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  996. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  997. if (grpids.Contains("default"))
  998. {
  999. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  1000. if (gpmember.IsNotEmpty())
  1001. {
  1002. gpmember.AddRange(gpmemberdft);
  1003. }
  1004. else
  1005. {
  1006. gpmember = gpmemberdft;
  1007. }
  1008. }
  1009. y.members = gpmember;
  1010. });
  1011. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  1012. List<RMember> tmdids = gpgpmembers.FindAll(x => x.type == 1).Where((x, i) => gpgpmembers.FindAll(x => x.type == 1).FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1013. List<RMember> students = gpgpmembers.FindAll(x => x.type == 2).Where((x, i) => gpgpmembers.FindAll(x => x.type == 2).FindIndex(n => n.id.Equals(x.id) && n.code.Equals(x.code)) == i).ToList();
  1014. if (tmdids.IsNotEmpty())
  1015. {
  1016. rmembers.AddRange(tmdids);
  1017. }
  1018. if (students.IsNotEmpty())
  1019. {
  1020. rmembers.AddRange(students);
  1021. }
  1022. groupLists.ForEach(x => {
  1023. if (string.IsNullOrWhiteSpace(x.periodId)) {
  1024. var meb = x.members.Where(z => !string.IsNullOrWhiteSpace(z.periodId)).FirstOrDefault();
  1025. if (meb!= null)
  1026. {
  1027. x.periodId=meb?.periodId;
  1028. }
  1029. }
  1030. });
  1031. return (rmembers, groupLists);
  1032. }
  1033. else
  1034. {
  1035. groupLists.ForEach(x => {
  1036. if (string.IsNullOrWhiteSpace(x.periodId))
  1037. {
  1038. var meb = x.members.Where(z => !string.IsNullOrWhiteSpace(z.periodId)).FirstOrDefault();
  1039. if (meb!= null)
  1040. {
  1041. x.periodId=meb?.periodId;
  1042. }
  1043. }
  1044. });
  1045. return (members, groupLists);
  1046. }
  1047. }
  1048. /// <summary>
  1049. /// 根据名单类型获取名单及成员信息。
  1050. /// </summary>
  1051. /// <param name="_coreAPIHttpService"></param>
  1052. /// <param name="client"></param>
  1053. /// <param name="type"></param>
  1054. /// <param name="scopes"></param>
  1055. /// <param name="school"></param>
  1056. /// <param name="_dingDing"></param>
  1057. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1058. /// <returns></returns>
  1059. public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing, int graduate = -1)
  1060. {
  1061. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  1062. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  1063. if (scopes.Contains("school"))
  1064. {
  1065. if (!string.IsNullOrEmpty(school))
  1066. {
  1067. List<RGroupList> groupLists = new List<RGroupList>();
  1068. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1069. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  1070. {
  1071. groupLists.Add(item);
  1072. }
  1073. groups.Add("School", groupLists);
  1074. }
  1075. }
  1076. else if (scopes.Contains("private"))
  1077. {
  1078. List<RGroupList> groupLists = new List<RGroupList>();
  1079. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1080. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  1081. {
  1082. groupLists.Add(item);
  1083. //if (string.IsNullOrWhiteSpace(school))
  1084. //{
  1085. // groupLists.Add(item);
  1086. //}
  1087. //else
  1088. //{
  1089. // if (!string.IsNullOrWhiteSpace(item.school))
  1090. // {
  1091. // if (item.school.Equals(school))
  1092. // {
  1093. // groupLists.Add(item);
  1094. // }
  1095. // }
  1096. // else {
  1097. // groupLists.Add(item);
  1098. // }
  1099. //}
  1100. }
  1101. groups.Add("Teacher", groupLists);
  1102. }
  1103. foreach (var item in groups)
  1104. {
  1105. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  1106. foreach (var group in list)
  1107. {
  1108. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  1109. }
  1110. }
  1111. var lists = groups.SelectMany(x => x.Value).ToList();
  1112. return lists;
  1113. }
  1114. /// <summary>
  1115. /// 根据名单类型,名单分组信息获取成员信息, rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  1116. /// </summary>
  1117. /// <param name="_coreAPIHttpService"></param>
  1118. /// <param name="client"></param>
  1119. /// <param name="type"></param>
  1120. /// <param name="groups"></param>
  1121. /// <param name="groupTbname"></param>
  1122. /// <param name="_dingDing"></param>
  1123. /// <param name="school"></param>
  1124. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1125. /// <returns></returns>
  1126. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client,
  1127. string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school, int graduate = -1)
  1128. {
  1129. try
  1130. {
  1131. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  1132. var members = groups.SelectMany(y => y.members).ToList();
  1133. //去重
  1134. 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();
  1135. 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();
  1136. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  1137. List<Student> studentsData = new List<Student>();
  1138. string periodId = "";
  1139. if (stu != null)
  1140. {
  1141. foreach (var item in stu)
  1142. {
  1143. var ids = item.list.Select(x => x.id).ToList();
  1144. if (ids.IsNotEmpty())
  1145. {
  1146. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId ,c.graduate,c.year ,c.periodId FROM c ");
  1147. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  1148. stuSql.Append($"where c.id in ({insql})");
  1149. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  1150. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  1151. {
  1152. periodId=student.periodId;
  1153. student.schoolId = item.key;
  1154. studentsData.Add(student);
  1155. }
  1156. }
  1157. }
  1158. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  1159. groups.ForEach(x =>
  1160. {
  1161. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1162. if (item > 0)
  1163. {
  1164. changes.Add(x);
  1165. }
  1166. });
  1167. }
  1168. List<TmdUser> tmdsData = new List<TmdUser>();
  1169. if (tmdids.IsNotEmpty())
  1170. {
  1171. string memberTbname = "";
  1172. if ($"{type}".Equals("activity"))
  1173. {
  1174. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  1175. var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
  1176. foreach (var schoolTeacher in schoolTeachers)
  1177. {
  1178. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1179. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  1180. tmdidSql.Append($" where c.id in ({insql})");
  1181. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1182. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  1183. {
  1184. tmdsData.Add(tmd);
  1185. }
  1186. }
  1187. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  1188. groups.ForEach(x =>
  1189. {
  1190. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1191. if (item > 0)
  1192. {
  1193. changes.Add(x);
  1194. }
  1195. });
  1196. }
  1197. else
  1198. {
  1199. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  1200. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  1201. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  1202. {
  1203. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1204. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1205. tmdidSql.Append($" where c.id in ({insql})");
  1206. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1207. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1208. {
  1209. tmdsData.Add(tmd);
  1210. }
  1211. }
  1212. else
  1213. {
  1214. {
  1215. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1216. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1217. tmdidSql.Append($" where c.id in ({insql})");
  1218. memberTbname = "Teacher";
  1219. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1220. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1221. {
  1222. tmdsData.Add(tmd);
  1223. }
  1224. }
  1225. {
  1226. //取差集,减少二次搜寻
  1227. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1228. if (tmdidexp.IsNotEmpty())
  1229. {
  1230. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1231. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  1232. tmdidSql.Append($" where c.id in ({insql})");
  1233. memberTbname = "Student";
  1234. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1235. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1236. {
  1237. tmdsData.Add(tmd);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1243. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1244. groups.ForEach(x =>
  1245. {
  1246. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  1247. if (item > 0)
  1248. {
  1249. changes.Add(x);
  1250. }
  1251. });
  1252. }
  1253. }
  1254. if (tmdids.IsNotEmpty() && _coreAPIHttpService.check) {
  1255. ///获取真实的名称 ,大于50则不处理
  1256. if (tmdids.Count < 60)
  1257. {
  1258. var content = new StringContent(tmdids.Select(x => x.id).ToHashSet().ToJsonString(), Encoding.UTF8, "application/json");
  1259. string json = null;
  1260. try
  1261. {
  1262. json = await _coreAPIHttpService.GetUserInfos(content);
  1263. if (!string.IsNullOrWhiteSpace(json))
  1264. {
  1265. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  1266. if (tmdInfos.IsNotEmpty())
  1267. {
  1268. tmdsData.ForEach(y =>
  1269. {
  1270. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  1271. if (tmd != null)
  1272. {
  1273. y.name = tmd?.name;
  1274. y.picture = tmd?.picture;
  1275. }
  1276. else
  1277. {
  1278. groups.ForEach(x =>
  1279. {
  1280. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  1281. if (item > 0)
  1282. {
  1283. changes.Add(x);
  1284. }
  1285. });
  1286. }
  1287. });
  1288. }
  1289. }
  1290. }
  1291. catch (Exception ex)
  1292. {
  1293. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n {ex.Message}\n{ex.StackTrace}{tmdids.Select(x => x.id).ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1294. }
  1295. }
  1296. }
  1297. tmdids.ForEach(x =>
  1298. {
  1299. var user = tmdsData.Find(y => y.id.Equals(x.id));
  1300. x.name = user?.name;
  1301. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? user?.name : x.nickname;
  1302. x.picture = user?.picture;
  1303. });
  1304. students.ForEach(x =>
  1305. {
  1306. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  1307. if (student != null)
  1308. {
  1309. x.name = student?.name;
  1310. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? student?.name:x.nickname;
  1311. x.picture = student?.picture;
  1312. x.classId = student?.classId;
  1313. x.graduate = student.graduate;
  1314. x.year = student.year;
  1315. x.gender= student.gender;
  1316. x.periodId = student.periodId;
  1317. }
  1318. });
  1319. var mbs = tmdids;
  1320. mbs.AddRange(students);
  1321. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  1322. {
  1323. foreach (var change in changes)
  1324. {
  1325. change.tcount = change.members.Where(x => x.type == 1).Count();
  1326. change.scount = change.members.Where(x => x.type == 2).Count();
  1327. GroupList group = change.ToJsonString().ToObject<GroupList>();
  1328. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  1329. }
  1330. }
  1331. groups.ForEach(x =>
  1332. {
  1333. x.members.ForEach(y =>
  1334. {
  1335. if (y.type == 1)
  1336. {
  1337. var tmd = tmdids.Find(t => t.id.Equals(y.id));
  1338. y.name = tmd?.name;
  1339. //y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? tmd?.nickname : y.nickname;
  1340. y.picture = tmd?.picture;
  1341. }
  1342. if (y.type == 2)
  1343. {
  1344. var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
  1345. if (student != null)
  1346. {
  1347. y.name = student?.name;
  1348. // y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? student?.nickname : y.nickname;
  1349. y.picture = student?.picture;
  1350. y.classId = student?.classId;
  1351. y.graduate = student.graduate;
  1352. y.gender = student.gender;
  1353. y.year = student.year;
  1354. x.periodId = student.periodId;
  1355. x.grades.Add(student.year);
  1356. }
  1357. }
  1358. });
  1359. if (!x.type.Equals("class")) {
  1360. var yearc = x.members.Where(z => z.type == 2).GroupBy(g => g.year).Select(k => new { key = k.Key, count = k.Count() }).OrderByDescending(z => z.count);
  1361. if (yearc.Any())
  1362. {
  1363. //有一半的人是同一个班的,则以
  1364. if (yearc.First().count * 1.0 / x.members.Count > 0.51)
  1365. {
  1366. x.year = yearc.First().key;
  1367. }
  1368. }
  1369. }
  1370. x.periodId=periodId;
  1371. });
  1372. HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
  1373. if (schoolCodes != null && schoolCodes.Count > 0)
  1374. {
  1375. List<School> schools = new List<School>();
  1376. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
  1377. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1378. {
  1379. schools.Add(item);
  1380. }
  1381. if (schools.IsNotEmpty())
  1382. {
  1383. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  1384. var school = schools.Find(j => j.id.Equals(z.code));
  1385. z.schoolName = school?.name;
  1386. });
  1387. }
  1388. }
  1389. if (graduate >= 0)
  1390. {
  1391. groups= groups.FindAll(x => x.graduate == graduate);
  1392. if (groups != null) {
  1393. groups.ForEach(x =>
  1394. {
  1395. x.members.RemoveAll(y => y.graduate != graduate);
  1396. });
  1397. }
  1398. mbs.RemoveAll(z => z.graduate != graduate);
  1399. return (groups, mbs);
  1400. }
  1401. //直接返回
  1402. else {
  1403. return (groups, mbs);
  1404. }
  1405. }
  1406. catch (Exception ex)
  1407. {
  1408. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location},GetGroupListMemberInfo()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1409. }
  1410. return (null, null);
  1411. }
  1412. /// <summary>
  1413. /// 处理活动结束的
  1414. /// </summary>
  1415. /// <param name="_coreAPIHttpService"></param>
  1416. /// <param name="cosmosClient">数据库</param>
  1417. /// <param name="_dingDing">钉钉消息</param>
  1418. /// <param name="school">学校编码</param>
  1419. /// <param name="classes">行政班</param>
  1420. /// <param name="stuLists">学生</param>
  1421. /// <param name="tchLists">教师</param>
  1422. /// <param name="_groupLists">分组</param>
  1423. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1424. /// <returns></returns>
  1425. public static async Task<List<FMember>> GetFinishMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient cosmosClient, DingDing _dingDing, string school, List<string> classes, List<string> stuLists, List<string> tchLists, List<(string, List<string>)> _groupLists = null, int graduate = -1)
  1426. {
  1427. List<FMember> fMembers = new();
  1428. if (classes != null && classes.Count > 0)
  1429. {
  1430. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, classes, school);
  1431. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 1, }));
  1432. }
  1433. if (stuLists != null && stuLists.Count > 0)
  1434. {
  1435. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, stuLists, school);
  1436. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1437. }
  1438. /* if (tchLists != null && tchLists.Count > 0)
  1439. {
  1440. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school);
  1441. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1442. }*/
  1443. if (tchLists != null && tchLists.Count > 0)
  1444. {
  1445. (List<RMember> staffList, List<RGroupList> groupLists1) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school, _groupLists);
  1446. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1447. }
  1448. return fMembers;
  1449. }
  1450. }
  1451. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  1452. {
  1453. public bool Equals((string id, string code) x, (string id, string code) y)
  1454. {
  1455. return x.id.Equals(y.id) && x.code.Equals(y.code);
  1456. }
  1457. public int GetHashCode((string id, string code) obj)
  1458. {
  1459. if (obj.id != null && obj.code != null)
  1460. {
  1461. return 1;
  1462. }
  1463. else
  1464. {
  1465. return 0;
  1466. }
  1467. }
  1468. }
  1469. }