GroupListService.cs 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  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. if (tmdids!=null && jointmdid!=null)
  464. {
  465. change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  466. }
  467. if (oldtmdids!= null &&leavetmdid != null) {
  468. change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  469. }
  470. }
  471. else
  472. {
  473. if (tmdids!=null && jointmdid!=null)
  474. {
  475. change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
  476. }
  477. if (oldtmdids!= null &&leavetmdid != null)
  478. {
  479. change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
  480. }
  481. }
  482. var stuids = list.members.FindAll(x => x.type == 2);
  483. var oldstuids = oldList.members.FindAll(x => x.type == 2);
  484. var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  485. var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  486. change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  487. change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
  488. }
  489. else
  490. {
  491. //离开的
  492. if (oldList != null)
  493. {
  494. var tmdids = oldList.members.FindAll(x => x.type == 1);
  495. if (tmdids.IsNotEmpty())
  496. {
  497. if (list.type.Equals("research") || list.type.Equals("yxtrain"))
  498. {
  499. change.tchleave.AddRange(tmdids);
  500. }
  501. else
  502. {
  503. change.tmdleave.AddRange(tmdids);
  504. }
  505. }
  506. var stuids = oldList.members.FindAll(x => x.type == 2);
  507. if (stuids.IsNotEmpty())
  508. {
  509. change.stuleave.AddRange(stuids);
  510. }
  511. }
  512. }
  513. }
  514. if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
  515. || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
  516. {
  517. var messageChange = new ServiceBusMessage(change.ToJsonString());
  518. messageChange.ApplicationProperties.Add("name", "GroupChange");
  519. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  520. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  521. }
  522. }
  523. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
  524. return list;
  525. }
  526. public static async Task<GroupList> CheckListNo(GroupList list, AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option)
  527. {
  528. try
  529. {
  530. var client = _azureCosmos.GetCosmosClient();
  531. if (string.IsNullOrEmpty(list.no))
  532. {
  533. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  534. for (int i = 0; i < 10; i++)
  535. {
  536. List<string> noStus = new List<string>();
  537. var queryNo = $"SELECT c.no FROM c where c.no ='{list.no}'";
  538. if (list.scope.Equals("school"))
  539. {
  540. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
  541. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{list.code}") }))
  542. {
  543. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  544. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  545. {
  546. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  547. while (accounts.MoveNext())
  548. {
  549. JsonElement account = accounts.Current;
  550. noStus.Add(account.GetProperty("no").GetString());
  551. }
  552. }
  553. }
  554. }
  555. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
  556. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("GroupList") }))
  557. {
  558. using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
  559. if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  560. {
  561. var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
  562. while (accounts.MoveNext())
  563. {
  564. JsonElement account = accounts.Current;
  565. noStus.Add(account.GetProperty("no").GetString());
  566. }
  567. }
  568. }
  569. if (noStus.Count == 0)
  570. {
  571. break;
  572. }
  573. else
  574. {
  575. if (i == 9)
  576. {
  577. string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
  578. await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
  579. throw new Exception(msg);
  580. }
  581. else
  582. {
  583. list.no = $"{Utils.CreatSaltString(6, "123456789")}";
  584. }
  585. }
  586. }
  587. }
  588. }
  589. catch (Exception ex)
  590. {
  591. }
  592. return list;
  593. }
  594. /// <summary>
  595. ///根据任意名单id获取名单摘要信息。
  596. /// </summary>
  597. /// <param name="client"></param>
  598. /// <param name="_dingDing"></param>
  599. /// <param name="classes"></param>
  600. /// <param name="school"></param>
  601. /// <param name="SummarySql"></param>
  602. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  603. /// <returns></returns>
  604. public static async Task<List<GroupListDto>> GetGroupListByListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school,
  605. 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)
  606. {
  607. List<GroupListDto> groupLists = null;
  608. try
  609. {
  610. classes.RemoveAll(x => x == null);
  611. if (!classes.IsNotEmpty())
  612. {
  613. return null;
  614. }
  615. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  616. {
  617. //默认的教研组
  618. GroupListDto groupList = new GroupListDto
  619. {
  620. id = "TeacherAll",
  621. name = "TeacherAll",
  622. code = $"GroupList-{school}",
  623. school = school,
  624. scope = "school",
  625. type = "yxtrain",
  626. };
  627. groupLists = new List<GroupListDto> { groupList };
  628. }
  629. else
  630. {
  631. Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
  632. //List<Student> students = new List<Student>();
  633. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  634. if (!string.IsNullOrEmpty(school))
  635. {
  636. List<GroupListDto> schoolList = new List<GroupListDto>();
  637. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  638. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  639. {
  640. schoolList.Add(item);
  641. }
  642. if (schoolList.IsNotEmpty())
  643. {
  644. groups.Add("School", schoolList);
  645. }
  646. //取差集,减少二次搜寻
  647. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  648. if (classes.IsNotEmpty())
  649. {
  650. if (!groupLists.IsNotEmpty())
  651. {
  652. groupLists = new List<GroupListDto>();
  653. }
  654. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  655. //搜寻没有关联学生的行政班
  656. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText:
  657. $"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})",
  658. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  659. {
  660. ///行政班(学生搜寻classId动态返回)class
  661. GroupListDto group = new GroupListDto
  662. {
  663. id = item.id,
  664. code = $"GroupList-{school}",
  665. name = item.name,
  666. periodId = item.periodId,
  667. scope = "school",
  668. school = school,
  669. type = "class",
  670. year = item.year,
  671. expire = item.expire,
  672. leader = item.leader,
  673. no = item.no,
  674. pk = "GroupList",
  675. graduate = item.graduate,
  676. grades= new HashSet<int> { item.year }
  677. };
  678. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  679. if (graduate >= 0)
  680. {
  681. if (group.graduate == graduate)
  682. {
  683. groupLists.Add(group);
  684. }
  685. }
  686. //全部。
  687. else
  688. {
  689. groupLists.Add(group);
  690. }
  691. // groupLists.Add(group);
  692. }
  693. //取差集,减少二次搜寻
  694. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  695. }
  696. }
  697. if (classes.IsNotEmpty())
  698. {
  699. List<GroupListDto> privateList = new List<GroupListDto>();
  700. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  701. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
  702. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  703. {
  704. privateList.Add(item);
  705. //if (string.IsNullOrWhiteSpace(school))
  706. //{
  707. // privateList.Add(item);
  708. //}
  709. //else
  710. //{
  711. // if (!string.IsNullOrWhiteSpace(item.school))
  712. // {
  713. // if (item.school.Equals(school))
  714. // {
  715. // privateList.Add(item);
  716. // }
  717. // }
  718. // else
  719. // {
  720. // privateList.Add(item);
  721. // }
  722. //}
  723. }
  724. if (privateList.IsNotEmpty())
  725. {
  726. groups.Add("Teacher", privateList);
  727. }
  728. }
  729. if (groups.Count != 0)
  730. {
  731. if (groupLists.IsNotEmpty())
  732. {
  733. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  734. }
  735. else
  736. {
  737. groupLists = groups.SelectMany(x => x.Value).ToList();
  738. }
  739. }
  740. }
  741. } catch (Exception ex ) {
  742. await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  743. }
  744. return groupLists;
  745. }
  746. /// <summary>
  747. /// 根据任意名单id获取成员信息。rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  748. /// </summary>
  749. /// <param name="_coreAPIHttpService"></param>
  750. /// <param name="client"></param>
  751. /// <param name="_dingDing"></param>
  752. /// <param name="classes"></param>
  753. /// <param name="school"></param>
  754. /// <param name="groupids"></param>
  755. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  756. /// <returns></returns>
  757. public static async Task<(List<RMember>rmembers, List<RGroupList> groups)> GetMemberByListids(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing,
  758. List<string> classes, string school, List<(string, List<string>)> groupids = null, int graduate = -1)
  759. {
  760. List<RMember> members = new List<RMember>();
  761. List<RGroupList> groupLists = new List<RGroupList>();
  762. if (classes != null)
  763. {
  764. classes.RemoveAll(x => x == null);
  765. }
  766. if (classes == null || classes.Count <= 0)
  767. {
  768. return (members, groupLists);
  769. }
  770. string periodId = string.Empty;
  771. if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  772. {
  773. //默认的教研组
  774. members = new List<RMember>();
  775. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  776. GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ",
  777. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  778. {
  779. RMember member = new RMember
  780. {
  781. id = item.id,
  782. name = item.name,
  783. picture = item.picture,
  784. type = 1,
  785. // nickname=item.name,
  786. };
  787. members.Add(member);
  788. }
  789. RGroupList groupList = new RGroupList
  790. {
  791. id = "TeacherAll",
  792. name = "TeacherAll",
  793. code = $"GroupList-{school}",
  794. school = school,
  795. scope = "school",
  796. type = "TeacherAll",
  797. members = members
  798. };
  799. groupLists = new List<RGroupList> { groupList };
  800. }
  801. else
  802. {
  803. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  804. List<Student> students = new List<Student>();
  805. string sql = string.Join(",", classes.Select(x => $"'{x}'"));
  806. if (!string.IsNullOrEmpty(school))
  807. {
  808. List<RGroupList> schoolList = new List<RGroupList>();
  809. string queryText = $"select value(c) from c where c.id in ({sql})";
  810. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
  811. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  812. {
  813. schoolList.Add(item);
  814. }
  815. if (schoolList.IsNotEmpty())
  816. {
  817. groups.Add("School", schoolList);
  818. }
  819. //取差集,减少二次搜寻
  820. classes = classes.Except(schoolList.Select(y => y.id)).ToList();
  821. if (classes.IsNotEmpty())
  822. {
  823. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  824. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
  825. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  826. {
  827. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  828. if (graduate >= 0)
  829. {
  830. if (item.graduate == graduate)
  831. {
  832. students.Add(item);
  833. }
  834. }
  835. //全部。
  836. else
  837. {
  838. students.Add(item);
  839. }
  840. // students.Add(item);
  841. }
  842. //取差集,减少二次搜寻
  843. classes = classes.Except(students.Select(y => y.classId)).ToList();
  844. }
  845. if (classes.IsNotEmpty())
  846. {
  847. string insql = string.Join(",", classes.Select(x => $"'{x}'"));
  848. //搜寻没有关联学生的行政班
  849. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
  850. .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})",
  851. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  852. {
  853. ///行政班(学生搜寻classId动态返回)class
  854. List<RMember> smembers = new List<RMember>();
  855. RGroupList group = new RGroupList
  856. {
  857. id = item.id,
  858. code = $"GroupList-{school}",
  859. name = item.name,
  860. periodId = item.periodId,
  861. scope = "school",
  862. school = school,
  863. type = "class",
  864. year = item.year,
  865. expire = item.expire,
  866. members = smembers,
  867. scount = smembers.Count,
  868. pk = "GroupList",
  869. leader = item.leader,
  870. no = item.no,
  871. graduate = item.graduate,
  872. grades= new HashSet<int>() { item.year }
  873. };
  874. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  875. if (graduate >= 0)
  876. {
  877. if (group.graduate == graduate)
  878. {
  879. groupLists.Add(group);
  880. }
  881. }
  882. //全部。
  883. else
  884. {
  885. groupLists.Add(group);
  886. }
  887. //groupLists.Add(group);
  888. }
  889. //取差集,减少二次搜寻
  890. classes = classes.Except(groupLists.Select(y => y.id)).ToList();
  891. }
  892. }
  893. if (classes.IsNotEmpty())
  894. {
  895. List<RGroupList> privateList = new List<RGroupList>();
  896. sql = string.Join(",", classes.Select(x => $"'{x}'"));
  897. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
  898. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  899. {
  900. privateList.Add(item);
  901. //if (string.IsNullOrWhiteSpace(school))
  902. //{
  903. // privateList.Add(item);
  904. //}
  905. //else
  906. //{
  907. // if (!string.IsNullOrWhiteSpace(item.school))
  908. // {
  909. // if (item.school.Equals(school))
  910. // {
  911. // privateList.Add(item);
  912. // }
  913. // }
  914. // else
  915. // {
  916. // privateList.Add(item);
  917. // }
  918. //}
  919. }
  920. if (privateList.IsNotEmpty())
  921. {
  922. groups.Add("Teacher", privateList);
  923. }
  924. }
  925. foreach (var item in groups)
  926. {
  927. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  928. foreach (var group in list)
  929. {
  930. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  931. members.AddRange(rmembers);
  932. }
  933. }
  934. groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
  935. if (students.IsNotEmpty())
  936. {
  937. List<string> sqlList = students.Select(x => x.classId).ToList();
  938. string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
  939. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  940. 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})",
  941. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
  942. {
  943. ///行政班(学生搜寻classId动态返回)class
  944. List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
  945. .Select(y => new RMember
  946. {
  947. id = y.id,
  948. code = school,
  949. name = y.name,
  950. //nickname = y.name,
  951. type = 2,
  952. picture = y.picture,
  953. no = y.no,
  954. classId = y.classId,
  955. groupId = y.groupId,
  956. groupName = y.groupName,
  957. irs = y.irs,
  958. year= y.year,
  959. graduate = y.graduate,
  960. gender= y.gender,
  961. periodId=y.periodId,
  962. }).ToList();
  963. members.AddRange(smembers);
  964. RGroupList group = new RGroupList
  965. {
  966. id = item.id,
  967. code = $"GroupList-{school}",
  968. name = item.name,
  969. periodId = item.periodId,
  970. scope = "school",
  971. school = school,
  972. type = "class",
  973. expire= item.expire,
  974. year = item.year,
  975. members = smembers,
  976. scount = smembers.Count,
  977. no = item.no,
  978. leader = item.leader,
  979. pk = "GroupList",
  980. graduate = item.graduate,
  981. grades= new HashSet<int> { item.year}
  982. };
  983. //graduate传入的状态>=0 表示指定状态查询,且传入的状态与数据库的状态一致。
  984. if (graduate >= 0)
  985. {
  986. if (group.graduate == graduate)
  987. {
  988. groupLists.Add(group);
  989. }
  990. }
  991. //全部。
  992. else
  993. {
  994. groupLists.Add(group);
  995. }
  996. // groupLists.Add(group);
  997. }
  998. //去重。
  999. 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();
  1000. }
  1001. }
  1002. if (groupids.IsNotEmpty())
  1003. {
  1004. List<RMember> rmembers = new List<RMember>();
  1005. groupLists.ForEach(y => {
  1006. (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
  1007. var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
  1008. if (grpids.Contains("default"))
  1009. {
  1010. var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
  1011. if (gpmember.IsNotEmpty())
  1012. {
  1013. gpmember.AddRange(gpmemberdft);
  1014. }
  1015. else
  1016. {
  1017. gpmember = gpmemberdft;
  1018. }
  1019. }
  1020. y.members = gpmember;
  1021. });
  1022. var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
  1023. 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();
  1024. 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();
  1025. if (tmdids.IsNotEmpty())
  1026. {
  1027. rmembers.AddRange(tmdids);
  1028. }
  1029. if (students.IsNotEmpty())
  1030. {
  1031. rmembers.AddRange(students);
  1032. }
  1033. groupLists.ForEach(x => {
  1034. if (string.IsNullOrWhiteSpace(x.periodId)) {
  1035. var meb = x.members.Where(z => !string.IsNullOrWhiteSpace(z.periodId)).FirstOrDefault();
  1036. if (meb!= null)
  1037. {
  1038. x.periodId=meb?.periodId;
  1039. }
  1040. }
  1041. });
  1042. return (rmembers, groupLists);
  1043. }
  1044. else
  1045. {
  1046. groupLists.ForEach(x => {
  1047. if (string.IsNullOrWhiteSpace(x.periodId))
  1048. {
  1049. var meb = x.members.Where(z => !string.IsNullOrWhiteSpace(z.periodId)).FirstOrDefault();
  1050. if (meb!= null)
  1051. {
  1052. x.periodId=meb?.periodId;
  1053. }
  1054. }
  1055. });
  1056. return (members, groupLists);
  1057. }
  1058. }
  1059. /// <summary>
  1060. /// 根据名单类型获取名单及成员信息。
  1061. /// </summary>
  1062. /// <param name="_coreAPIHttpService"></param>
  1063. /// <param name="client"></param>
  1064. /// <param name="type"></param>
  1065. /// <param name="scopes"></param>
  1066. /// <param name="school"></param>
  1067. /// <param name="_dingDing"></param>
  1068. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1069. /// <returns></returns>
  1070. public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing, int graduate = -1)
  1071. {
  1072. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  1073. Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
  1074. if (scopes.Contains("school"))
  1075. {
  1076. if (!string.IsNullOrEmpty(school))
  1077. {
  1078. List<RGroupList> groupLists = new List<RGroupList>();
  1079. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1080. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  1081. {
  1082. groupLists.Add(item);
  1083. }
  1084. groups.Add("School", groupLists);
  1085. }
  1086. }
  1087. else if (scopes.Contains("private"))
  1088. {
  1089. List<RGroupList> groupLists = new List<RGroupList>();
  1090. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1091. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  1092. {
  1093. groupLists.Add(item);
  1094. //if (string.IsNullOrWhiteSpace(school))
  1095. //{
  1096. // groupLists.Add(item);
  1097. //}
  1098. //else
  1099. //{
  1100. // if (!string.IsNullOrWhiteSpace(item.school))
  1101. // {
  1102. // if (item.school.Equals(school))
  1103. // {
  1104. // groupLists.Add(item);
  1105. // }
  1106. // }
  1107. // else {
  1108. // groupLists.Add(item);
  1109. // }
  1110. //}
  1111. }
  1112. groups.Add("Teacher", groupLists);
  1113. }
  1114. foreach (var item in groups)
  1115. {
  1116. var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
  1117. foreach (var group in list)
  1118. {
  1119. (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school,graduate);
  1120. }
  1121. }
  1122. var lists = groups.SelectMany(x => x.Value).ToList();
  1123. return lists;
  1124. }
  1125. /// <summary>
  1126. /// 根据名单类型,名单分组信息获取成员信息, rmembers是去重的信息,groups是名单及人员信息,同一个人可能在不同的名单内。
  1127. /// </summary>
  1128. /// <param name="_coreAPIHttpService"></param>
  1129. /// <param name="client"></param>
  1130. /// <param name="type"></param>
  1131. /// <param name="groups"></param>
  1132. /// <param name="groupTbname"></param>
  1133. /// <param name="_dingDing"></param>
  1134. /// <param name="school"></param>
  1135. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1136. /// <returns></returns>
  1137. public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client,
  1138. string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school, int graduate = -1)
  1139. {
  1140. try
  1141. {
  1142. HashSet<RGroupList> changes = new HashSet<RGroupList>();
  1143. var members = groups.SelectMany(y => y.members).ToList();
  1144. //去重
  1145. 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();
  1146. 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();
  1147. var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
  1148. List<Student> studentsData = new List<Student>();
  1149. string periodId = "";
  1150. if (stu != null)
  1151. {
  1152. foreach (var item in stu)
  1153. {
  1154. var ids = item.list.Select(x => x.id).ToList();
  1155. if (ids.IsNotEmpty())
  1156. {
  1157. 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 ");
  1158. string insql = string.Join(",", ids.Select(x => $"'{x}'"));
  1159. stuSql.Append($"where c.id in ({insql})");
  1160. await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
  1161. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
  1162. {
  1163. periodId=student.periodId;
  1164. student.schoolId = item.key;
  1165. studentsData.Add(student);
  1166. }
  1167. }
  1168. }
  1169. var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
  1170. groups.ForEach(x =>
  1171. {
  1172. int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1173. if (item > 0)
  1174. {
  1175. changes.Add(x);
  1176. }
  1177. });
  1178. }
  1179. List<TmdUser> tmdsData = new List<TmdUser>();
  1180. if (tmdids.IsNotEmpty())
  1181. {
  1182. string memberTbname = "";
  1183. if ($"{type}".Equals("activity"))
  1184. {
  1185. var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
  1186. var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
  1187. foreach (var schoolTeacher in schoolTeachers)
  1188. {
  1189. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1190. string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
  1191. tmdidSql.Append($" where c.id in ({insql})");
  1192. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1193. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
  1194. {
  1195. tmdsData.Add(tmd);
  1196. }
  1197. }
  1198. var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
  1199. groups.ForEach(x =>
  1200. {
  1201. int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
  1202. if (item > 0)
  1203. {
  1204. changes.Add(x);
  1205. }
  1206. });
  1207. }
  1208. else
  1209. {
  1210. //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
  1211. //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
  1212. if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
  1213. {
  1214. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1215. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1216. tmdidSql.Append($" where c.id in ({insql})");
  1217. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1218. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1219. {
  1220. tmdsData.Add(tmd);
  1221. }
  1222. }
  1223. else
  1224. {
  1225. {
  1226. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1227. string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
  1228. tmdidSql.Append($" where c.id in ({insql})");
  1229. memberTbname = "Teacher";
  1230. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1231. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1232. {
  1233. tmdsData.Add(tmd);
  1234. }
  1235. }
  1236. {
  1237. //取差集,减少二次搜寻
  1238. var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1239. if (tmdidexp.IsNotEmpty())
  1240. {
  1241. StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
  1242. string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
  1243. tmdidSql.Append($" where c.id in ({insql})");
  1244. memberTbname = "Student";
  1245. await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
  1246. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  1247. {
  1248. tmdsData.Add(tmd);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
  1254. var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
  1255. groups.ForEach(x =>
  1256. {
  1257. int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
  1258. if (item > 0)
  1259. {
  1260. changes.Add(x);
  1261. }
  1262. });
  1263. }
  1264. }
  1265. if (tmdids.IsNotEmpty() && _coreAPIHttpService.check) {
  1266. ///获取真实的名称 ,大于50则不处理
  1267. if (tmdids.Count < 60)
  1268. {
  1269. var content = new StringContent(tmdids.Select(x => x.id).ToHashSet().ToJsonString(), Encoding.UTF8, "application/json");
  1270. string json = null;
  1271. try
  1272. {
  1273. json = await _coreAPIHttpService.GetUserInfos(content);
  1274. if (!string.IsNullOrWhiteSpace(json))
  1275. {
  1276. List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
  1277. if (tmdInfos.IsNotEmpty())
  1278. {
  1279. tmdsData.ForEach(y =>
  1280. {
  1281. var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
  1282. if (tmd != null)
  1283. {
  1284. y.name = tmd?.name;
  1285. y.picture = tmd?.picture;
  1286. }
  1287. else
  1288. {
  1289. groups.ForEach(x =>
  1290. {
  1291. int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
  1292. if (item > 0)
  1293. {
  1294. changes.Add(x);
  1295. }
  1296. });
  1297. }
  1298. });
  1299. }
  1300. }
  1301. }
  1302. catch (Exception ex)
  1303. {
  1304. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n {ex.Message}\n{ex.StackTrace}{tmdids.Select(x => x.id).ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1305. }
  1306. }
  1307. }
  1308. tmdids.ForEach(x =>
  1309. {
  1310. var user = tmdsData.Find(y => y.id.Equals(x.id));
  1311. x.name = user?.name;
  1312. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? user?.name : x.nickname;
  1313. x.picture = user?.picture;
  1314. });
  1315. students.ForEach(x =>
  1316. {
  1317. var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
  1318. if (student != null)
  1319. {
  1320. x.name = student?.name;
  1321. // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? student?.name:x.nickname;
  1322. x.picture = student?.picture;
  1323. x.classId = student?.classId;
  1324. x.graduate = student.graduate;
  1325. x.year = student.year;
  1326. x.gender= student.gender;
  1327. x.periodId = student.periodId;
  1328. }
  1329. });
  1330. var mbs = tmdids;
  1331. mbs.AddRange(students);
  1332. if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
  1333. {
  1334. foreach (var change in changes)
  1335. {
  1336. change.tcount = change.members.Where(x => x.type == 1).Count();
  1337. change.scount = change.members.Where(x => x.type == 2).Count();
  1338. GroupList group = change.ToJsonString().ToObject<GroupList>();
  1339. await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
  1340. }
  1341. }
  1342. groups.ForEach(x =>
  1343. {
  1344. x.members.ForEach(y =>
  1345. {
  1346. if (y.type == 1)
  1347. {
  1348. var tmd = tmdids.Find(t => t.id.Equals(y.id));
  1349. y.name = tmd?.name;
  1350. //y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? tmd?.nickname : y.nickname;
  1351. y.picture = tmd?.picture;
  1352. }
  1353. if (y.type == 2)
  1354. {
  1355. var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
  1356. if (student != null)
  1357. {
  1358. y.name = student?.name;
  1359. // y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? student?.nickname : y.nickname;
  1360. y.picture = student?.picture;
  1361. y.classId = student?.classId;
  1362. y.graduate = student.graduate;
  1363. y.gender = student.gender;
  1364. y.year = student.year;
  1365. x.periodId = student.periodId;
  1366. x.grades.Add(student.year);
  1367. }
  1368. }
  1369. });
  1370. if (!x.type.Equals("class")) {
  1371. 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);
  1372. if (yearc.Any())
  1373. {
  1374. //有一半的人是同一个班的,则以
  1375. if (yearc.First().count * 1.0 / x.members.Count > 0.51)
  1376. {
  1377. x.year = yearc.First().key;
  1378. }
  1379. }
  1380. }
  1381. if (!x.scope.Equals("private")) {
  1382. x.periodId=periodId;
  1383. }
  1384. });
  1385. HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
  1386. if (schoolCodes != null && schoolCodes.Count > 0)
  1387. {
  1388. List<School> schools = new List<School>();
  1389. string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
  1390. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1391. {
  1392. schools.Add(item);
  1393. }
  1394. if (schools.IsNotEmpty())
  1395. {
  1396. groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
  1397. var school = schools.Find(j => j.id.Equals(z.code));
  1398. z.schoolName = school?.name;
  1399. });
  1400. }
  1401. }
  1402. if (graduate >= 0)
  1403. {
  1404. groups= groups.FindAll(x => x.graduate == graduate);
  1405. if (groups != null) {
  1406. groups.ForEach(x =>
  1407. {
  1408. x.members.RemoveAll(y => y.graduate != graduate);
  1409. });
  1410. }
  1411. mbs.RemoveAll(z => z.graduate != graduate);
  1412. return (groups, mbs);
  1413. }
  1414. //直接返回
  1415. else {
  1416. return (groups, mbs);
  1417. }
  1418. }
  1419. catch (Exception ex)
  1420. {
  1421. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location},GetGroupListMemberInfo()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1422. }
  1423. return (null, null);
  1424. }
  1425. /// <summary>
  1426. /// 处理活动结束的
  1427. /// </summary>
  1428. /// <param name="_coreAPIHttpService"></param>
  1429. /// <param name="cosmosClient">数据库</param>
  1430. /// <param name="_dingDing">钉钉消息</param>
  1431. /// <param name="school">学校编码</param>
  1432. /// <param name="classes">行政班</param>
  1433. /// <param name="stuLists">学生</param>
  1434. /// <param name="tchLists">教师</param>
  1435. /// <param name="_groupLists">分组</param>
  1436. /// <param name="graduate">毕业类型0在校,1毕业 , -1查全部。</param>
  1437. /// <returns></returns>
  1438. 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)
  1439. {
  1440. List<FMember> fMembers = new();
  1441. if (classes != null && classes.Count > 0)
  1442. {
  1443. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, classes, school);
  1444. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 1, }));
  1445. }
  1446. if (stuLists != null && stuLists.Count > 0)
  1447. {
  1448. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, stuLists, school);
  1449. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1450. }
  1451. /* if (tchLists != null && tchLists.Count > 0)
  1452. {
  1453. (List<RMember> staffList, List<RGroupList> classInfos) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school);
  1454. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1455. }*/
  1456. if (tchLists != null && tchLists.Count > 0)
  1457. {
  1458. (List<RMember> staffList, List<RGroupList> groupLists1) = await GetMemberByListids(_coreAPIHttpService, cosmosClient, _dingDing, tchLists, school, _groupLists);
  1459. staffList.ForEach(x => fMembers.Add(new FMember() { id = x.id, code = school, type = 2 }));
  1460. }
  1461. return fMembers;
  1462. }
  1463. }
  1464. public class CompareIdCode : IEqualityComparer<(string id, string code)>
  1465. {
  1466. public bool Equals((string id, string code) x, (string id, string code) y)
  1467. {
  1468. return x.id.Equals(y.id) && x.code.Equals(y.code);
  1469. }
  1470. public int GetHashCode((string id, string code) obj)
  1471. {
  1472. if (obj.id != null && obj.code != null)
  1473. {
  1474. return 1;
  1475. }
  1476. else
  1477. {
  1478. return 0;
  1479. }
  1480. }
  1481. }
  1482. }