GroupListService.cs 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  760. {
  761. //默认的教研组
  762. members = new List<RMember>();
  763. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  764. GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ",
  765. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  766. {
  767. RMember member = new RMember
  768. {
  769. id = item.id,
  770. name = item.name,
  771. picture = item.picture,
  772. type = 1,
  773. // nickname=item.name,
  774. };
  775. members.Add(member);
  776. }
  777. RGroupList groupList = new RGroupList
  778. {
  779. id = "TeacherAll",
  780. name = "TeacherAll",
  781. code = $"GroupList-{school}",
  782. school = school,
  783. scope = "school",
  784. type = "TeacherAll",
  785. members = members
  786. };
  787. groupLists = new List<RGroupList> { groupList };
  788. }
  789. else
  790. {
  791. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  792. List<Student> students = new List<Student>();
  793. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  794. if (!string.IsNullOrEmpty(school))
  795. {
  796. List<RGroupList> schoolList = new List<RGroupList>();
  797. string queryText = $"select value(c) from c where c.id in ({sql})";
  798. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  799. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  800. {
  801. schoolList.Add(item);
  802. }
  803. if (schoolList.IsNotEmpty())
  804. {
  805. groups.Add("School", schoolList);
  806. }
  807. //取差集,减少二次搜寻
  808. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  809. if (classes.IsNotEmpty())
  810. {
  811. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  812. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  813. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  814. {
  815. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  816. if (graduate >= 0)
  817. {
  818. if (item.graduate == graduate)
  819. {
  820. students.Add(item);
  821. }
  822. }
  823. //全部。
  824. else
  825. {
  826. students.Add(item);
  827. }
  828. // students.Add(item);
  829. }
  830. //取差集,减少二次搜寻
  831. classes = classes.Except(students.Select(y => y.classId)).ToList();
  832. }
  833. if (classes.IsNotEmpty())
  834. {
  835. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  836. //搜寻没有关联学生的行政班
  837. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  838. .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})",
  839. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  840. {
  841. ///行政班(学生搜寻classId动态返回)class
  842. List<RMember> smembers = new List<RMember>();
  843. RGroupList group = new RGroupList
  844. {
  845. id = item.id,
  846. code = $"GroupList-{school}",
  847. name = item.name,
  848. periodId = item.periodId,
  849. scope = "school",
  850. school = school,
  851. type = "class",
  852. year = item.year,
  853. expire = item.expire,
  854. members = smembers,
  855. scount = smembers.Count,
  856. pk = "GroupList",
  857. leader = item.leader,
  858. no = item.no,
  859. graduate = item.graduate,
  860. grades= new HashSet<int>() { item.year }
  861. };
  862. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  863. if (graduate >= 0)
  864. {
  865. if (group.graduate == graduate)
  866. {
  867. groupLists.Add(group);
  868. }
  869. }
  870. //全部。
  871. else
  872. {
  873. groupLists.Add(group);
  874. }
  875. //groupLists.Add(group);
  876. }
  877. //取差集,减少二次搜寻
  878. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  879. }
  880. }
  881. if (classes.IsNotEmpty())
  882. {
  883. List<RGroupList> privateList = new List<RGroupList>();
  884. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  885. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  886. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  887. {
  888. privateList.Add(item);
  889. //if (string.IsNullOrWhiteSpace(school))
  890. //{
  891. // privateList.Add(item);
  892. //}
  893. //else
  894. //{
  895. // if (!string.IsNullOrWhiteSpace(item.school))
  896. // {
  897. // if (item.school.Equals(school))
  898. // {
  899. // privateList.Add(item);
  900. // }
  901. // }
  902. // else
  903. // {
  904. // privateList.Add(item);
  905. // }
  906. //}
  907. }
  908. if (privateList.IsNotEmpty())
  909. {
  910. groups.Add("Teacher", privateList);
  911. }
  912. }
  913. foreach (var item in groups)
  914. {
  915. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  916. foreach (var group in list)
  917. {
  918. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  919. members.AddRange(rmembers);
  920. }
  921. }
  922. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  923. if (students.IsNotEmpty())
  924. {
  925. List<string> sqlList = students.Select(x => x.classId).ToList();
  926. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  927. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  928. 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})",
  929. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  930. {
  931. ///行政班(学生搜寻classId动态返回)class
  932. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  933. .Select(y => new RMember
  934. {
  935. id = y.id,
  936. code = school,
  937. name = y.name,
  938. //nickname = y.name,
  939. type = 2,
  940. picture = y.picture,
  941. no = y.no,
  942. classId = y.classId,
  943. groupId = y.groupId,
  944. groupName = y.groupName,
  945. irs = y.irs,
  946. year= y.year,
  947. graduate = y.graduate,
  948. gender= y.gender,
  949. }).ToList();
  950. members.AddRange(smembers);
  951. RGroupList group = new RGroupList
  952. {
  953. id = item.id,
  954. code = $"GroupList-{school}",
  955. name = item.name,
  956. periodId = item.periodId,
  957. scope = "school",
  958. school = school,
  959. type = "class",
  960. expire= item.expire,
  961. year = item.year,
  962. members = smembers,
  963. scount = smembers.Count,
  964. no = item.no,
  965. leader = item.leader,
  966. pk = "GroupList",
  967. graduate = item.graduate,
  968. grades= new HashSet<int> { item.year}
  969. };
  970. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  971. if (graduate >= 0)
  972. {
  973. if (group.graduate == graduate)
  974. {
  975. groupLists.Add(group);
  976. }
  977. }
  978. //全部。
  979. else
  980. {
  981. groupLists.Add(group);
  982. }
  983. // groupLists.Add(group);
  984. }
  985. //去重。
  986. 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();
  987. }
  988. }
  989. if (groupids.IsNotEmpty())
  990. {
  991. List<RMember> rmembers = new List<RMember>();
  992. groupLists.ForEach(y => {
  993. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  994. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  995. if (grpids.Contains("default"))
  996. {
  997. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  998. if (gpmember.IsNotEmpty())
  999. {
  1000. gpmember.AddRange(gpmemberdft);
  1001. }
  1002. else
  1003. {
  1004. gpmember = gpmemberdft;
  1005. }
  1006. }
  1007. y.members = gpmember;
  1008. });
  1009. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  1010. 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();
  1011. 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();
  1012. if (tmdids.IsNotEmpty())
  1013. {
  1014. rmembers.AddRange(tmdids);
  1015. }
  1016. if (students.IsNotEmpty())
  1017. {
  1018. rmembers.AddRange(students);
  1019. }
  1020. return (rmembers, groupLists);
  1021. }
  1022. else
  1023. {
  1024. return (members, groupLists);
  1025. }
  1026. }
  1027. /// <summary>
  1028. /// 根据名单类型获取名单及成员信息。
  1029. /// </summary>
  1030. /// <param name="_coreAPIHttpService"></param>
  1031. /// <param name="client"></param>
  1032. /// <param name="type"></param>
  1033. /// <param name="scopes"></param>
  1034. /// <param name="school"></param>
  1035. /// <param name="_dingDing"></param>
  1036. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1037. /// <returns></returns>
  1038. public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing, int graduate = -1)
  1039. {
  1040. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  1041. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  1042. if (scopes.Contains("school"))
  1043. {
  1044. if (!string.IsNullOrEmpty(school))
  1045. {
  1046. List<RGroupList> groupLists = new List<RGroupList>();
  1047. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1048. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  1049. {
  1050. groupLists.Add(item);
  1051. }
  1052. groups.Add("School", groupLists);
  1053. }
  1054. }
  1055. else if (scopes.Contains("private"))
  1056. {
  1057. List<RGroupList> groupLists = new List<RGroupList>();
  1058. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1059. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  1060. {
  1061. groupLists.Add(item);
  1062. //if (string.IsNullOrWhiteSpace(school))
  1063. //{
  1064. // groupLists.Add(item);
  1065. //}
  1066. //else
  1067. //{
  1068. // if (!string.IsNullOrWhiteSpace(item.school))
  1069. // {
  1070. // if (item.school.Equals(school))
  1071. // {
  1072. // groupLists.Add(item);
  1073. // }
  1074. // }
  1075. // else {
  1076. // groupLists.Add(item);
  1077. // }
  1078. //}
  1079. }
  1080. groups.Add("Teacher", groupLists);
  1081. }
  1082. foreach (var item in groups)
  1083. {
  1084. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  1085. foreach (var group in list)
  1086. {
  1087. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  1088. }
  1089. }
  1090. var lists = groups.SelectMany(x => x.Value).ToList();
  1091. return lists;
  1092. }
  1093. /// <summary>
  1094. /// 根据名单类型,名单分组信息获取成员信息, rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  1095. /// </summary>
  1096. /// <param name="_coreAPIHttpService"></param>
  1097. /// <param name="client"></param>
  1098. /// <param name="type"></param>
  1099. /// <param name="groups"></param>
  1100. /// <param name="groupTbname"></param>
  1101. /// <param name="_dingDing"></param>
  1102. /// <param name="school"></param>
  1103. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1104. /// <returns></returns>
  1105. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client,
  1106. string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school, int graduate = -1)
  1107. {
  1108. try
  1109. {
  1110. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  1111. var members = groups.SelectMany(y => y.members).ToList();
  1112. //去重
  1113. 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();
  1114. 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();
  1115. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  1116. List<Student> studentsData = new List<Student>();
  1117. if (stu != null)
  1118. {
  1119. foreach (var item in stu)
  1120. {
  1121. var ids = item.list.Select(x => x.id).ToList();
  1122. if (ids.IsNotEmpty())
  1123. {
  1124. StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId ,c.graduate,c.year FROM c ");
  1125. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  1126. stuSql.Append($"where c.id in ({insql})");
  1127. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  1128. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  1129. {
  1130. student.schoolId = item.key;
  1131. studentsData.Add(student);
  1132. }
  1133. }
  1134. }
  1135. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  1136. groups.ForEach(x =>
  1137. {
  1138. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1139. if (item > 0)
  1140. {
  1141. changes.Add(x);
  1142. }
  1143. });
  1144. }
  1145. List<TmdUser> tmdsData = new List<TmdUser>();
  1146. if (tmdids.IsNotEmpty())
  1147. {
  1148. string memberTbname = "";
  1149. if ($"{type}".Equals("activity"))
  1150. {
  1151. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  1152. var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
  1153. foreach (var schoolTeacher in schoolTeachers)
  1154. {
  1155. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1156. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  1157. tmdidSql.Append($" where c.id in ({insql})");
  1158. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1159. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  1160. {
  1161. tmdsData.Add(tmd);
  1162. }
  1163. }
  1164. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  1165. groups.ForEach(x =>
  1166. {
  1167. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1168. if (item > 0)
  1169. {
  1170. changes.Add(x);
  1171. }
  1172. });
  1173. }
  1174. else
  1175. {
  1176. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  1177. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  1178. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  1179. {
  1180. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1181. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1182. tmdidSql.Append($" where c.id in ({insql})");
  1183. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1184. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1185. {
  1186. tmdsData.Add(tmd);
  1187. }
  1188. }
  1189. else
  1190. {
  1191. {
  1192. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1193. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1194. tmdidSql.Append($" where c.id in ({insql})");
  1195. memberTbname = "Teacher";
  1196. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1197. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1198. {
  1199. tmdsData.Add(tmd);
  1200. }
  1201. }
  1202. {
  1203. //取差集,减少二次搜寻
  1204. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1205. if (tmdidexp.IsNotEmpty())
  1206. {
  1207. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1208. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  1209. tmdidSql.Append($" where c.id in ({insql})");
  1210. memberTbname = "Student";
  1211. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1212. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1213. {
  1214. tmdsData.Add(tmd);
  1215. }
  1216. }
  1217. }
  1218. }
  1219. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1220. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1221. groups.ForEach(x =>
  1222. {
  1223. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  1224. if (item > 0)
  1225. {
  1226. changes.Add(x);
  1227. }
  1228. });
  1229. }
  1230. }
  1231. if (tmdids.IsNotEmpty() && _coreAPIHttpService.check) {
  1232. ///获取真实的名称 ,大于50则不处理
  1233. if (tmdids.Count < 60)
  1234. {
  1235. var content = new StringContent(tmdids.Select(x => x.id).ToHashSet().ToJsonString(), Encoding.UTF8, "application/json");
  1236. string json = null;
  1237. try
  1238. {
  1239. json = await _coreAPIHttpService.GetUserInfos(content);
  1240. if (!string.IsNullOrWhiteSpace(json))
  1241. {
  1242. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  1243. if (tmdInfos.IsNotEmpty())
  1244. {
  1245. tmdsData.ForEach(y =>
  1246. {
  1247. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  1248. if (tmd != null)
  1249. {
  1250. y.name = tmd?.name;
  1251. y.picture = tmd?.picture;
  1252. }
  1253. else
  1254. {
  1255. groups.ForEach(x =>
  1256. {
  1257. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  1258. if (item > 0)
  1259. {
  1260. changes.Add(x);
  1261. }
  1262. });
  1263. }
  1264. });
  1265. }
  1266. }
  1267. }
  1268. catch (Exception ex)
  1269. {
  1270. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n {ex.Message}\n{ex.StackTrace}{tmdids.Select(x => x.id).ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1271. }
  1272. }
  1273. }
  1274. tmdids.ForEach(x =>
  1275. {
  1276. var user = tmdsData.Find(y => y.id.Equals(x.id));
  1277. x.name = user?.name;
  1278. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? user?.name : x.nickname;
  1279. x.picture = user?.picture;
  1280. });
  1281. students.ForEach(x =>
  1282. {
  1283. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  1284. if (student != null)
  1285. {
  1286. x.name = student?.name;
  1287. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? student?.name:x.nickname;
  1288. x.picture = student?.picture;
  1289. x.classId = student?.classId;
  1290. x.graduate = student.graduate;
  1291. x.year = student.year;
  1292. x.gender= student.gender;
  1293. }
  1294. });
  1295. var mbs = tmdids;
  1296. mbs.AddRange(students);
  1297. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  1298. {
  1299. foreach (var change in changes)
  1300. {
  1301. change.tcount = change.members.Where(x => x.type == 1).Count();
  1302. change.scount = change.members.Where(x => x.type == 2).Count();
  1303. GroupList group = change.ToJsonString().ToObject<GroupList>();
  1304. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  1305. }
  1306. }
  1307. groups.ForEach(x =>
  1308. {
  1309. x.members.ForEach(y =>
  1310. {
  1311. if (y.type == 1)
  1312. {
  1313. var tmd = tmdids.Find(t => t.id.Equals(y.id));
  1314. y.name = tmd?.name;
  1315. //y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? tmd?.nickname : y.nickname;
  1316. y.picture = tmd?.picture;
  1317. }
  1318. if (y.type == 2)
  1319. {
  1320. var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
  1321. if (student != null)
  1322. {
  1323. y.name = student?.name;
  1324. // y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? student?.nickname : y.nickname;
  1325. y.picture = student?.picture;
  1326. y.classId = student?.classId;
  1327. y.graduate = student.graduate;
  1328. y.gender = student.gender;
  1329. y.year = student.year;
  1330. y.gender = student.gender;
  1331. x.grades.Add(student.year);
  1332. }
  1333. }
  1334. });
  1335. if (!x.type.Equals("class")) {
  1336. 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);
  1337. if (yearc.Any())
  1338. {
  1339. //有一半的人是同一个班的,则以
  1340. if (yearc.First().count * 1.0 / x.members.Count > 0.51)
  1341. {
  1342. x.year = yearc.First().key;
  1343. }
  1344. }
  1345. }
  1346. });
  1347. HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
  1348. if (schoolCodes != null && schoolCodes.Count > 0)
  1349. {
  1350. List<School> schools = new List<School>();
  1351. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
  1352. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1353. {
  1354. schools.Add(item);
  1355. }
  1356. if (schools.IsNotEmpty())
  1357. {
  1358. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  1359. var school = schools.Find(j => j.id.Equals(z.code));
  1360. z.schoolName = school?.name;
  1361. });
  1362. }
  1363. }
  1364. if (graduate >= 0)
  1365. {
  1366. groups= groups.FindAll(x => x.graduate == graduate);
  1367. if (groups != null) {
  1368. groups.ForEach(x =>
  1369. {
  1370. x.members.RemoveAll(y => y.graduate != graduate);
  1371. });
  1372. }
  1373. mbs.RemoveAll(z => z.graduate != graduate);
  1374. return (groups, mbs);
  1375. }
  1376. //直接返回
  1377. else {
  1378. return (groups, mbs);
  1379. }
  1380. }
  1381. catch (Exception ex)
  1382. {
  1383. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location},GetGroupListMemberInfo()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1384. }
  1385. return (null, null);
  1386. }
  1387. /// <summary>
  1388. /// 处理活动结束的
  1389. /// </summary>
  1390. /// <param name="_coreAPIHttpService"></param>
  1391. /// <param name="cosmosClient">数据库</param>
  1392. /// <param name="_dingDing">钉钉消息</param>
  1393. /// <param name="school">学校编码</param>
  1394. /// <param name="classes">行政班</param>
  1395. /// <param name="stuLists">学生</param>
  1396. /// <param name="tchLists">教师</param>
  1397. /// <param name="_groupLists">分组</param>
  1398. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1399. /// <returns></returns>
  1400. 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)
  1401. {
  1402. List<FMember> fMembers = new();
  1403. if (classes != null && classes.Count > 0)
  1404. {
  1405. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, classes, school);
  1406. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 1, }));
  1407. }
  1408. if (stuLists != null && stuLists.Count > 0)
  1409. {
  1410. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, stuLists, school);
  1411. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1412. }
  1413. /* if (tchLists != null && tchLists.Count > 0)
  1414. {
  1415. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school);
  1416. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1417. }*/
  1418. if (tchLists != null && tchLists.Count > 0)
  1419. {
  1420. (List<RMember> staffList, List<RGroupList> groupLists1) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school, _groupLists);
  1421. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1422. }
  1423. return fMembers;
  1424. }
  1425. }
  1426. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  1427. {
  1428. public bool Equals((string id, string code) x, (string id, string code) y)
  1429. {
  1430. return x.id.Equals(y.id) && x.code.Equals(y.code);
  1431. }
  1432. public int GetHashCode((string id, string code) obj)
  1433. {
  1434. if (obj.id != null && obj.code != null)
  1435. {
  1436. return 1;
  1437. }
  1438. else
  1439. {
  1440. return 0;
  1441. }
  1442. }
  1443. }
  1444. }