12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148 |
- using Azure.Cosmos;
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using HTEXLib.COMM.Helpers;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using TEAMModelOS.Models;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.SDK.Models.Service;
- using System.Text.RegularExpressions;
- using TEAMModelOS.SDK.Models;
- using System.Net.Http;
- namespace TEAMModelOS.SDK
- {
- public class GroupListService
- {
- /// <summary>
- /// 查询名单成员所在的名单列表,
- /// </summary>
- /// <param name="_coreAPIHttpService"></param>
- /// <param name="client"></param>
- /// <param name="_dingDing"></param>
- /// <param name="memberId">成员id </param>
- /// <param name="memberType">成员类型</param>
- /// <param name="school">成员所在的学校 ,可为空</param>
- /// <param name="groupTypes">过滤名单的类型集合,不传则是全部</param>
- /// <returns></returns>
- public static async Task<List<GroupListGrp>> GetMemberInGroupList(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing, string memberId, int memberType, string school,List<string> groupTypes) {
- List<GroupListGrp> groupLists = new List<GroupListGrp>();
- if (groupTypes.IsEmpty() || groupTypes.Contains("class")) {
- if (!string.IsNullOrWhiteSpace(school) && memberType == 2)
- {
- Student student = null;
- try
- {
- student = await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemAsync<Student>(memberId, new PartitionKey($"Base-{school}"));
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- return null;
- }
- if (!string.IsNullOrWhiteSpace(student.classId))
- {
- try
- {
- Class clazz = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(student.classId, new PartitionKey($"Class-{school}"));
- GroupListGrp groupList = new GroupListGrp
- {
- id = clazz.id,
- code = $"GroupList-{clazz.school}",
- name = clazz.name,
- periodId = clazz.periodId,
- pk = "GroupList",
- year = clazz.year,
- school = clazz.school,
- scope = "school",
- type = "class",
- no = clazz.no,
- leader = clazz.teacher?.id,
- };
- groupLists.Add(groupList);
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- }
- }
- }
- }
- 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 ";
- if (groupTypes.IsEmpty() || groupTypes.Contains("teach")) {
- //教学班
- StringBuilder teachsql = new StringBuilder();
- if (!string.IsNullOrWhiteSpace(school) && memberType == 2) {
- teachsql.Append($"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 ");
- }
- if (memberType == 1)
- {
- teachsql.Append($"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='teach' and m.id='{memberId}' and m.type=1 ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- //个人名单
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("research")))
- {
- //教研组
- StringBuilder teachsql = new StringBuilder();
- teachsql.Append($"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='research' and m.id='{memberId}' and m.type=1 ");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (!string.IsNullOrWhiteSpace(school) && (groupTypes.IsEmpty() || groupTypes.Contains("yxtrain")))
- {
- //研修名单
- StringBuilder teachsql = new StringBuilder();
- teachsql.Append($"SELECT distinct {SummarySql} FROM c join m in c.members where c.type='yxtrain' and m.id='{memberId}' and m.type=1 ");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- return groupLists;
- }
- /// <summary>
- ///-1状态异常,0加入成功, 1加入学生或醍摩豆ID为空,2重复加入 ,3不允许跨校加入名单, 4表示个人名单未开放加入
- /// </summary>
- /// <param name="client"></param>
- /// <param name="_stuListNo"></param>
- /// <param name="userid"></param>
- /// <param name="type"></param>
- /// <param name="school"></param>
- /// <returns></returns>
- public static async Task<(int status, GroupList stuList)> CodeJoinList(CosmosClient client, string _stuListNo, string userid, int type, string school)
- {
- var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
- (int status, GroupList stuList) data = (-1, null);
- if (!string.IsNullOrEmpty(school))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
- {
- data = JoinList(item, userid, type, school);
- break;
- }
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- if (item.joinLock == 0) {
- //状态=4 表示未开放加入。
- return (4, item);
- }
- data = JoinList(item, userid, type, school);
- break;
- }
- return data;
- }
- public static (int status, GroupList stuList) JoinList(GroupList stuList, string userid, int type, string school)
- {
- int status = -1;
- if (!string.IsNullOrWhiteSpace(stuList.school) && !string.IsNullOrWhiteSpace(school))
- {
- if (!stuList.school.Equals(school))
- {
- status = 3;//不允许跨校加入名单
- return (status, stuList);
- }
- }
- string irs = string.Empty;
- List<string> irsOrder = stuList.members.Select(x => x.irs)?.Where(y => !string.IsNullOrEmpty(y) && Regex.IsMatch(y, @"^\d*$")).OrderBy(x => int.Parse(x)).ToList();
- if (!irsOrder.Contains("0"))
- {
- irsOrder.Insert(0, "0");
- }
- if (irsOrder != null)
- {
- if (!irsOrder.Contains("0"))
- {
- irsOrder.Insert(0, "0");
- }
- }
- else { irsOrder = new List<string>() { "0" }; }
- for (int i = 0; i < irsOrder.Count; i++)
- {
- irs = $"{int.Parse(irsOrder[i]) + 1}";
- int index = i + 1;
- if (index <= irsOrder.Count - 1)
- {
- if (!irs.Equals(irsOrder[index]))
- {
- break;
- }
- }
- }
- if (string.IsNullOrEmpty($"{userid}"))
- {
- //加入学生或醍摩豆ID为空
- status = 1;
- }
- else
- {
- if (type == 1)
- {
- var student = stuList.members.Find(x => x.type == 1 && x.id.Equals(userid));
- if (student != null)
- {
- //重复加入
- status = 2;
- }
- else
- {
- //加入成功
- status = 0;
- stuList.members.Add(new Member { id = userid, type = type, irs = irs, no = irs });
- }
- }
- else if (type == 2)
- {
- var student = stuList.members.Find(x => x.type == 2 && x.id.Equals(userid) && x.code.Equals(school));
- if (student != null)
- {
- //重复加入
- status = 2;
- }
- else
- {
- status = 0;
- stuList.members.Add(new Member { id = userid, code = school, type = type, irs = irs, no = irs });
- }
- }
- }
- return (status, stuList);
- }
- public static async Task<GroupList> UpsertList(GroupList list, AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus)
- {
- bool isnew = false;
- var client = _azureCosmos.GetCosmosClient();
- if (string.IsNullOrEmpty(list.id))
- {
- list.id = Guid.NewGuid().ToString();
- isnew = true;
- }
- string tbname = list.scope.Equals("private") ? "Teacher" : "School";
- var tmembers = list.members.Where(x => x.type == 1);
- var smembers = list.members.Where(x => x.type == 2);
- list.scount = smembers.Count();
- list.tcount = tmembers.Count();
- //if (smembers.Count() > 0 && smembers.Select(x => x.code).ToHashSet().Count()>=2) {
- // //处理移除多个学校的名单,只保留一个学校的。
- // if (string.IsNullOrWhiteSpace(list.school))
- // {
- // HashSet<string> codes = smembers.Select(x => x.code).ToHashSet();
- // list.school = codes.First();
- // codes.Remove(codes.First());
- // list.members.RemoveAll(x => codes.Contains(x.code));
- // }
- // else {
- // list.members.RemoveAll(x => !x.code.Equals(list.school));
- // }
- //}
- if (string.IsNullOrWhiteSpace(list.school) && smembers.Count() >= 1)
- {
- list.school = smembers.First().code;
- }
- if (!string.IsNullOrWhiteSpace(list.school) && smembers.Count() == 0 && list.scope.Equals("private"))
- {
- list.school = null;
- }
- //学生名单,教研组会触发活动中间表刷新
- if (list.type.Equals("teach") || list.type.Equals("research") || list.type.Equals("yxtrain") || list.type.Equals("activity"))
- {
- GroupChange change = new GroupChange()
- {
- type = list.type,
- listid = list.id,
- scope = list.scope,
- originCode = list.school,
- school = list.school,
- creatorId = list.creatorId
- };
- GroupList oldList = null;
- if (!isnew)
- {
- try
- {
- oldList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>(list.id, new PartitionKey(list.code));
- }
- catch (CosmosException)
- {
- oldList = null;
- }
- }
- if (list.members.IsNotEmpty() && (oldList == null || !oldList.members.IsNotEmpty()))
- {
- //加入的
- var tmdids = list.members.FindAll(x => x.type == 1);
- if (tmdids.IsNotEmpty())
- {
- if (list.type.Equals("research") || list.type.Equals("yxtrain"))
- {
- change.tchjoin.AddRange(tmdids);
- }
- else
- {
- change.tmdjoin.AddRange(tmdids);
- }
- }
- var stuids = list.members.FindAll(x => x.type == 2);
- if (stuids.IsNotEmpty())
- {
- change.stujoin.AddRange(stuids);
- }
- }
- else
- {
- if (list.members.IsNotEmpty())
- {
- var tmdids = list.members.FindAll(x => x.type == 1);
- var oldtmdids = oldList.members.FindAll(x => x.type == 1);
- //取各自的差集
- //新=》旧差集,表示新增
- var jointmdid = tmdids.Select(x => x.id).Except(oldtmdids.Select(y => y.id)).ToList();
- //旧=》新差集,表示离开
- var leavetmdid = oldtmdids.Select(x => x.id).Except(tmdids.Select(y => y.id)).ToList();
- if (list.type.Equals("research") || list.type.Equals("yxtrain"))
- {
- change.tchjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
- change.tchleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
- }
- else
- {
- change.tmdjoin.AddRange(tmdids.Where(x => jointmdid.Exists(y => y.Equals(x.id))));
- change.tmdleave.AddRange(oldtmdids.Where(x => leavetmdid.Exists(y => y.Equals(x.id))));
- }
- var stuids = list.members.FindAll(x => x.type == 2);
- var oldstuids = oldList.members.FindAll(x => x.type == 2);
- var joinstudent = stuids.Select(x => (x.id, x.code)).Except(oldstuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
- var leavestudent = oldstuids.Select(x => (x.id, x.code)).Except(stuids.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
- change.stujoin.AddRange(stuids.Where(x => joinstudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
- change.stuleave.AddRange(oldstuids.Where(x => leavestudent.Exists(y => y.id.Equals(x.id) && y.code.Equals(x.code))));
- }
- else
- {
- //离开的
- if (oldList != null)
- {
- var tmdids = oldList.members.FindAll(x => x.type == 1);
- if (tmdids.IsNotEmpty())
- {
- if (list.type.Equals("research") || list.type.Equals("yxtrain"))
- {
- change.tchleave.AddRange(tmdids);
- }
- else
- {
- change.tmdleave.AddRange(tmdids);
- }
- }
- var stuids = oldList.members.FindAll(x => x.type == 2);
- if (stuids.IsNotEmpty())
- {
- change.stuleave.AddRange(stuids);
- }
- }
- }
- }
- if (change.tmdjoin.Count != 0 || change.tmdleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0
- || change.tchjoin.Count != 0 || change.tchleave.Count != 0)
- {
- var messageChange = new ServiceBusMessage(change.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "GroupChange");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(list, new PartitionKey(list.code));
- return list;
- }
- public static async Task<GroupList> CheckListNo(GroupList list, AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- if (string.IsNullOrEmpty(list.no))
- {
- list.no = $"{Utils.CreatSaltString(6, "123456789")}";
- for (int i = 0; i < 10; i++)
- {
- List<string> noStus = new List<string>();
- var queryNo = $"SELECT c.no FROM c where c.no ='{list.no}'";
- if (list.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{list.code}") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- noStus.Add(account.GetProperty("no").GetString());
- }
- }
- }
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("GroupList") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- noStus.Add(account.GetProperty("no").GetString());
- }
- }
- }
- if (noStus.Count == 0)
- {
- break;
- }
- else
- {
- if (i == 9)
- {
- string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
- await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
- throw new Exception(msg);
- }
- else
- {
- list.no = $"{Utils.CreatSaltString(6, "123456789")}";
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- }
- return list;
- }
- public static async Task<List<GroupListDto>> GetGroupListListids(CosmosClient client, DingDing _dingDing, List<string> classes, string school,
- 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 ")
- {
- classes.RemoveAll(x => x == null);
- if (!classes.IsNotEmpty()) {
- return null;
- }
- List<GroupListDto> groupLists = null;
- if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
- {
- //默认的教研组
- GroupListDto groupList = new GroupListDto
- {
- id = "TeacherAll",
- name = "TeacherAll",
- code = $"GroupList-{school}",
- school = school,
- scope = "school",
- type = "yxtrain",
- };
- groupLists = new List<GroupListDto> { groupList };
- }
- else
- {
- Dictionary<string, List<GroupListDto>> groups = new Dictionary<string, List<GroupListDto>>();
- //List<Student> students = new List<Student>();
- string sql = string.Join(",", classes.Select(x => $"'{x}'"));
- if (!string.IsNullOrEmpty(school))
- {
- List<GroupListDto> schoolList = new List<GroupListDto>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
- {
- schoolList.Add(item);
- }
- if (schoolList.IsNotEmpty())
- {
- groups.Add("School", schoolList);
- }
- //取差集,减少二次搜寻
- classes = classes.Except(schoolList.Select(y => y.id)).ToList();
- if (classes.IsNotEmpty())
- {
- if (!groupLists.IsNotEmpty())
- {
- groupLists = new List<GroupListDto>();
- }
- string insql = string.Join(",", classes.Select(x => $"'{x}'"));
- //搜寻没有关联学生的行政班
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupListDto>(queryText: $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader from c where c.id in ({insql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
- {
- ///行政班(学生搜寻classId动态返回)class
- GroupListDto group = new GroupListDto
- {
- id = item.id,
- code = $"GroupList-{school}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = school,
- type = "class",
- year = item.year,
- leader = item.leader,
- no = item.no,
- pk = "GroupList",
- };
- groupLists.Add(group);
- }
- //取差集,减少二次搜寻
- classes = classes.Except(groupLists.Select(y => y.id)).ToList();
- }
- }
- if (classes.IsNotEmpty())
- {
- List<GroupListDto> privateList = new List<GroupListDto>();
- sql = string.Join(",", classes.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupListDto>(queryText: $"select {SummarySql} from c where c.id in ({sql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- privateList.Add(item);
- //if (string.IsNullOrWhiteSpace(school))
- //{
- // privateList.Add(item);
- //}
- //else
- //{
- // if (!string.IsNullOrWhiteSpace(item.school))
- // {
- // if (item.school.Equals(school))
- // {
- // privateList.Add(item);
- // }
- // }
- // else
- // {
- // privateList.Add(item);
- // }
- //}
- }
- if (privateList.IsNotEmpty())
- {
- groups.Add("Teacher", privateList);
- }
- }
- if (groups.Count != 0)
- {
- if (groupLists.IsNotEmpty())
- {
- groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
- }
- else
- {
- groupLists = groups.SelectMany(x => x.Value).ToList();
- }
- }
- }
- return groupLists;
- }
- public static async Task<(List<RMember>, List<RGroupList> groups)> GetStutmdidListids(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, DingDing _dingDing, List<string> classes, string school, List<(string, List<string>)> groupids = null)
- {
- List<RMember> members = new List<RMember>();
- List<RGroupList> groupLists = new List<RGroupList>();
- if (classes != null)
- {
- classes.RemoveAll(x => x == null);
- }
- if (classes == null || classes.Count <= 0)
- {
- return (members, groupLists);
- }
- if (classes.Count == 1 && classes.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
- {
- //默认的教研组
- members = new List<RMember>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdInfo>(queryText: $"SELECT c.id,c.name,c.picture FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- RMember member = new RMember
- {
- id = item.id,
- name = item.name,
- picture = item.picture,
- type = 1,
- // nickname=item.name,
- };
- members.Add(member);
- }
- RGroupList groupList = new RGroupList
- {
- id = "TeacherAll",
- name = "TeacherAll",
- code = $"GroupList-{school}",
- school = school,
- scope = "school",
- type = "TeacherAll",
- members = members
- };
- groupLists = new List<RGroupList> { groupList };
- }
- else
- {
- Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
- List<Student> students = new List<Student>();
- string sql = string.Join(",", classes.Select(x => $"'{x}'"));
- if (!string.IsNullOrEmpty(school))
- {
- List<RGroupList> schoolList = new List<RGroupList>();
- string queryText = $"select value(c) from c where c.id in ({sql})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: queryText,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
- {
- schoolList.Add(item);
- }
- if (schoolList.IsNotEmpty())
- {
- groups.Add("School", schoolList);
- }
- //取差集,减少二次搜寻
- classes = classes.Except(schoolList.Select(y => y.id)).ToList();
- if (classes.IsNotEmpty())
- {
- sql = string.Join(",", classes.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
- {
- students.Add(item);
- }
- //取差集,减少二次搜寻
- classes = classes.Except(students.Select(y => y.classId)).ToList();
- }
- if (classes.IsNotEmpty())
- {
- string insql = string.Join(",", classes.Select(x => $"'{x}'"));
- //搜寻没有关联学生的行政班
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School")
- .GetItemQueryIterator<RGroupList>(queryText: $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader from c where c.id in ({insql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
- {
- ///行政班(学生搜寻classId动态返回)class
- List<RMember> smembers = new List<RMember>();
- RGroupList group = new RGroupList
- {
- id = item.id,
- code = $"GroupList-{school}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = school,
- type = "class",
- year = item.year,
- members = smembers,
- scount = smembers.Count,
- pk = "GroupList",
- leader = item.leader,
- no = item.no,
- };
- groupLists.Add(group);
- }
- //取差集,减少二次搜寻
- classes = classes.Except(groupLists.Select(y => y.id)).ToList();
- }
- }
- if (classes.IsNotEmpty())
- {
- List<RGroupList> privateList = new List<RGroupList>();
- sql = string.Join(",", classes.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: $"select value(c) from c where c.id in ({sql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- privateList.Add(item);
- //if (string.IsNullOrWhiteSpace(school))
- //{
- // privateList.Add(item);
- //}
- //else
- //{
- // if (!string.IsNullOrWhiteSpace(item.school))
- // {
- // if (item.school.Equals(school))
- // {
- // privateList.Add(item);
- // }
- // }
- // else
- // {
- // privateList.Add(item);
- // }
- //}
- }
- if (privateList.IsNotEmpty())
- {
- groups.Add("Teacher", privateList);
- }
- }
- foreach (var item in groups)
- {
- var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
- foreach (var group in list)
- {
- (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school);
- members.AddRange(rmembers);
- }
- }
- groupLists.AddRange(groups.SelectMany(x => x.Value).ToList());
- if (students.IsNotEmpty())
- {
- List<string> sqlList = students.Select(x => x.classId).ToList();
- string insql = string.Join(",", sqlList.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<RGroupList>(queryText: $"select c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.teacher.id as leader from c where c.id in ({insql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
- {
- ///行政班(学生搜寻classId动态返回)class
- List<RMember> smembers = students.Where(x => x.classId.Equals(item.id))
- .Select(y => new RMember
- {
- id = y.id,
- code = school,
- name = y.name,
- //nickname = y.name,
- type = 2,
- picture = y.picture,
- no = y.no,
- classId = y.classId,
- //groupId=y.groupId,
- groupName = y.groupName,
- irs = y.irs,
-
- }).ToList();
- members.AddRange(smembers);
- RGroupList group = new RGroupList
- {
- id = item.id,
- code = $"GroupList-{school}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = school,
- type = "class",
- year = item.year,
- members = smembers,
- scount = smembers.Count,
- no = item.no,
- leader = item.leader,
- pk = "GroupList"
- };
- groupLists.Add(group);
- }
- //去重。
- 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();
- }
- }
- if (groupids.IsNotEmpty())
- {
- List<RMember> rmembers = new List<RMember>();
- groupLists.ForEach(y => {
- (string id, List<string> grpids) = groupids.Find(x => x.Item1.Equals(y.id));
- var gpmember = y.members.FindAll(x => !string.IsNullOrEmpty(x.groupName) && grpids.Contains(x.groupName));
- if (grpids.Contains("default"))
- {
- var gpmemberdft = y.members.FindAll(x => string.IsNullOrWhiteSpace(x.groupName));
- if (gpmember.IsNotEmpty())
- {
- gpmember.AddRange(gpmemberdft);
- }
- else
- {
- gpmember = gpmemberdft;
- }
- }
- y.members = gpmember;
- });
- var gpgpmembers = groupLists.SelectMany(x => x.members).ToList();
- 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();
- 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();
- if (tmdids.IsNotEmpty())
- {
- rmembers.AddRange(tmdids);
- }
- if (students.IsNotEmpty())
- {
- rmembers.AddRange(students);
- }
- return (rmembers, groupLists);
- }
- else
- {
- return (members, groupLists);
- }
- }
- public static async Task<List<RGroupList>> GetGroupListMemberByType(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<string> scopes, string school, DingDing _dingDing)
- {
- StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
- Dictionary<string, List<RGroupList>> groups = new Dictionary<string, List<RGroupList>>();
- if (scopes.Contains("school"))
- {
- if (!string.IsNullOrEmpty(school))
- {
- List<RGroupList> groupLists = new List<RGroupList>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
- {
- groupLists.Add(item);
- }
- groups.Add("School", groupLists);
- }
- }
- else if (scopes.Contains("private"))
- {
- List<RGroupList> groupLists = new List<RGroupList>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- groupLists.Add(item);
- //if (string.IsNullOrWhiteSpace(school))
- //{
- // groupLists.Add(item);
- //}
- //else
- //{
- // if (!string.IsNullOrWhiteSpace(item.school))
- // {
- // if (item.school.Equals(school))
- // {
- // groupLists.Add(item);
- // }
- // }
- // else {
- // groupLists.Add(item);
- // }
- //}
- }
- groups.Add("Teacher", groupLists);
- }
- foreach (var item in groups)
- {
- var list = item.Value.GroupBy(x => x.type).Select(y => new { key = y.Key, list = y.ToList() });
- foreach (var group in list)
- {
- (List<RGroupList> rgroups, List<RMember> rmembers) = await GetGroupListMemberInfo(_coreAPIHttpService, client, group.key, group.list, item.Key, _dingDing, school);
- }
- }
- var lists = groups.SelectMany(x => x.Value).ToList();
- return lists;
- }
- public static async Task<(List<RGroupList> groups, List<RMember> members)> GetGroupListMemberInfo(CoreAPIHttpService _coreAPIHttpService, CosmosClient client, string type, List<RGroupList> groups, string groupTbname, DingDing _dingDing, string school)
- {
- try
- {
- HashSet<RGroupList> changes = new HashSet<RGroupList>();
- var members = groups.SelectMany(y => y.members).ToList();
- //去重
- 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();
- 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();
- var stu = students.GroupBy(x => x.code).Select(y => new { key = y.Key, list = y.ToList() });
- List<Student> studentsData = new List<Student>();
- if (stu != null)
- {
- foreach (var item in stu)
- {
- var ids = item.list.Select(x => x.id).ToList();
- if (ids.IsNotEmpty())
- {
- StringBuilder stuSql = new StringBuilder($"SELECT distinct c.name,c.id,c.code,c.picture,c.no,c.irs,c.classId FROM c ");
- string insql = string.Join(",", ids.Select(x => $"'{x}'"));
- stuSql.Append($"where c.id in ({insql})");
- await foreach (var student in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: stuSql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{item.key}") }))
- {
- student.schoolId = item.key;
- studentsData.Add(student);
- }
- }
- }
- var unexist_student = students.Select(x => (x.id, x.code)).Except(studentsData.Select(y => (y.id, y.schoolId)), new CompareIdCode()).ToList();
- groups.ForEach(x =>
- {
- int item = x.members.RemoveAll(y => y.type == 2 && unexist_student.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
- if (item > 0)
- {
- changes.Add(x);
- }
- });
- }
- List<TmdUser> tmdsData = new List<TmdUser>();
- if (tmdids.IsNotEmpty())
- {
- string memberTbname = "";
- if ($"{type}".Equals("activity"))
- {
- var mbers = groups.SelectMany(x => x.members).Where(z => !string.IsNullOrEmpty(z.code));
- var schoolTeachers = mbers.GroupBy(y => y.code).Select(m => new { key = m.Key, list = m.ToList() });
- foreach (var schoolTeacher in schoolTeachers)
- {
- StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
- string insql = string.Join(",", schoolTeacher.list.Select(x => $"'{x.id}'"));
- tmdidSql.Append($" where c.id in ({insql})");
- await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolTeacher.key}") }))
- {
- tmdsData.Add(tmd);
- }
- }
- var unexist_teachers = mbers.Select(x => (x.id, x.code)).Except(tmdsData.Select(y => (y.id, y.code)), new CompareIdCode()).ToList();
- groups.ForEach(x =>
- {
- int item = x.members.RemoveAll(y => y.type == 2 && unexist_teachers.Exists(x => x.id.Equals(y.id) && x.Item2.Equals(y.code)));
- if (item > 0)
- {
- changes.Add(x);
- }
- });
- }
- else
- {
- //处理研修名单,如果是学校老师的,则需要检查SchoolTeacher
- //处理 学校教研组,学校管理人员,学校任课教师,学校研修名单。
- if (!string.IsNullOrEmpty(school) && ($"{type}".Equals("yxtrain") || $"{type}".Equals("research") || $"{type}".Equals("manage") || $"{type}".Equals("subject")))
- {
- StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
- string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
- tmdidSql.Append($" where c.id in ({insql})");
- await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- tmdsData.Add(tmd);
- }
- }
- else
- {
- {
- StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
- string insql = string.Join(",", tmdids.Select(x => $"'{x.id}'"));
- tmdidSql.Append($" where c.id in ({insql})");
- memberTbname = "Teacher";
- await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- tmdsData.Add(tmd);
- }
- }
- {
- //取差集,减少二次搜寻
- var tmdidexp = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
- if (tmdidexp.IsNotEmpty())
- {
- StringBuilder tmdidSql = new StringBuilder($"SELECT distinct c.name,c.id,c.picture FROM c ");
- string insql = string.Join(",", tmdidexp.Select(x => $"'{x}'"));
- tmdidSql.Append($" where c.id in ({insql})");
- memberTbname = "Student";
- await foreach (var tmd in client.GetContainer(Constant.TEAMModelOS, memberTbname).GetItemQueryIterator<TmdUser>(queryText: tmdidSql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- tmdsData.Add(tmd);
- }
- }
- }
- }
- tmdsData = tmdsData.Where((x, i) => tmdsData.FindIndex(n => n.id.Equals(x.id)) == i).ToList();
- var unexist_tmdid = tmdids.Select(x => x.id).Except(tmdsData.Select(y => y.id)).ToList();
- groups.ForEach(x =>
- {
- int item = x.members.RemoveAll(y => unexist_tmdid.Contains(y.id) && y.type == 1);
- if (item > 0)
- {
- changes.Add(x);
- }
- });
- }
- }
- if (tmdids.IsNotEmpty() && _coreAPIHttpService.check) {
- ///获取真实的名称
- var content = new StringContent(tmdids.Select(x => x.id).ToHashSet().ToJsonString(), Encoding.UTF8, "application/json");
- string json = null;
- try
- {
- json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- List<TmdInfo> tmdInfos = json.ToObject<List<TmdInfo>>();
- if (tmdInfos.IsNotEmpty())
- {
- tmdsData.ForEach(y =>
- {
- var tmd = tmdInfos.Find(x => x.id.Equals(y.id));
- if (tmd != null)
- {
- y.name = tmd?.name;
- y.picture = tmd?.picture;
- }
- else
- {
- groups.ForEach(x =>
- {
- int item = x.members.RemoveAll(z => z.id.Equals(y.id) && z.type == 1);
- if (item > 0)
- {
- changes.Add(x);
- }
- });
- }
- });
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.Message}\n{ex.StackTrace}{tmdids.Select(x => x.id).ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
-
- tmdids.ForEach(x =>
- {
- var user = tmdsData.Find(y => y.id.Equals(x.id));
- x.name = user?.name;
- // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? user?.name : x.nickname;
- x.picture = user?.picture;
- });
- students.ForEach(x =>
- {
- var student = studentsData.Find(y => y.id.Equals(x.id) && y.schoolId.Equals(x.code));
- x.name = student?.name;
- // x.nickname = string.IsNullOrWhiteSpace(x.nickname) ? student?.name:x.nickname;
- x.picture = student?.picture;
- x.classId = student?.classId;
- });
- var mbs = tmdids;
- mbs.AddRange(students);
- if (changes.Count > 0 && !string.IsNullOrEmpty(groupTbname))
- {
- foreach (var change in changes)
- {
- change.tcount = change.members.Where(x => x.type == 1).Count();
- change.scount = change.members.Where(x => x.type == 2).Count();
- GroupList group = change.ToJsonString().ToObject<GroupList>();
- await client.GetContainer(Constant.TEAMModelOS, groupTbname).ReplaceItemAsync(group, group.id, new PartitionKey(group.code));
- }
- }
- groups.ForEach(x => x.members.ForEach(y => {
- if (y.type == 1)
- {
- var tmd = tmdids.Find(t => t.id.Equals(y.id));
- y.name = tmd?.name;
- //y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? tmd?.nickname : y.nickname;
- y.picture = tmd?.picture;
- }
- if (y.type == 2)
- {
- var student = students.Find(t => t.id.Equals(y.id) && t.code.Equals(y.code));
- y.name = student?.name;
- // y.nickname = string.IsNullOrWhiteSpace(y.nickname) ? student?.nickname : y.nickname;
- y.picture = student?.picture;
- y.classId = student?.classId;
- }
- }));
- HashSet<string> schoolCodes = groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).Select(z => z.code).ToHashSet();
- if (schoolCodes != null && schoolCodes.Count > 0)
- {
- List<School> schools = new List<School>();
- string insql = $"select c.name,c.id from c where c.id in ({string.Join(",", schoolCodes.Select(x => $"'{x}'"))})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: insql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(item);
- }
- if (schools.IsNotEmpty())
- {
- groups.SelectMany(x => x.members).Where(y => !string.IsNullOrEmpty(y.code)).ToList().ForEach(z => {
- var school = schools.Find(j => j.id.Equals(z.code));
- z.schoolName = school?.name;
- });
- }
- }
- return (groups, mbs);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location},GetGroupListMemberInfo()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- return (null, null);
- }
- }
- public class CompareIdCode : IEqualityComparer<(string id, string code)>
- {
- public bool Equals((string id, string code) x, (string id, string code) y)
- {
- return x.id.Equals(y.id) && x.code.Equals(y.code);
- }
- public int GetHashCode((string id, string code) obj)
- {
- if (obj.id != null && obj.code != null)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- }
- }
|